home *** CD-ROM | disk | FTP | other *** search
/ PC World 2005 December (Special) / PCWorld_2005-12_Special_cd.bin / Bezpecnost / lsti / lsti.exe / framework-2.5.exe / h2ph < prev    next >
Text File  |  2005-01-27  |  27KB  |  912 lines

  1. #!/usr/bin/perl
  2.     eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
  3.     if $running_under_some_shell;
  4.  
  5. use strict;
  6.  
  7. use Config;
  8. use File::Path qw(mkpath);
  9. use Getopt::Std;
  10.  
  11. # Make sure read permissions for all are set:
  12. if (defined umask && (umask() & 0444)) {
  13.     umask (umask() & ~0444);
  14. }
  15.  
  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;
  20.  
  21. my $Exit = 0;
  22.  
  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;
  26.  
  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
  34. );
  35.  
  36. my %isatype;
  37. @isatype{@isatype} = (1) x @isatype;
  38. my $inif = 0;
  39. my %Is_converted;
  40. my %bad_file = ();
  41.  
  42. @ARGV = ('-') unless @ARGV;
  43.  
  44. build_preamble_if_necessary();
  45.  
  46. sub reindent($) {
  47.     my($text) = shift;
  48.     $text =~ s/\n/\n    /g;
  49.     $text =~ s/        /\t/g;
  50.     $text;
  51. }
  52.  
  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;
  59.     }
  60.  
  61.     # Recover from header files with unbalanced cpp directives
  62.     $t = '';
  63.     $tab = 0;
  64.  
  65.     # $eval_index goes into ``#line'' directives, to help locate syntax errors:
  66.     $eval_index = 1;
  67.  
  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";
  77.     }
  78.  
  79.     if ($opt_a) { # automagic mode:  locate header file in @inc_dirs
  80.         foreach (@inc_dirs) {
  81.         chdir $_;
  82.         last if -f $file;
  83.         }
  84.     }
  85.  
  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";
  88.     }
  89.  
  90.     print OUT
  91.         "require '_h2ph_pre.ph';\n\n",
  92.         "no warnings 'redefine';\n\n";
  93.  
  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;
  109.             }
  110.             $args =~ s/\b(\w)/\$$1/g;
  111.             $args = "local($args) = \@_;\n$t    ";
  112.             }
  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";
  128.             }
  129.             } else {
  130.                       print OUT "unless(defined(\&$name)) {\n    sub $name $proto\{\n\t${args}eval q($new);\n    }\n}\n";
  131.             }
  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;        #']);
  141.  
  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";
  147.             }
  148.             } else {
  149.                 # Shunt around such directives as `#define FOO FOO':
  150.                 next if " \&$name" eq $new;
  151.  
  152.                       print OUT $t,"unless(defined(\&$name)) {\n    sub $name () {\t",$new,";}\n}\n";
  153.             }
  154.         }
  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");
  179.                     }
  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";
  191.                 }
  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";
  238.         }
  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.         $_ .= $next;
  246.         print OUT "# $next\n" if $opt_D;
  247.         }
  248.         s/#\s*if.*?#\s*endif//g; # drop #ifdefs
  249.         s@/\*.*?\*/@@g;
  250.         s/\s+/ /g;
  251.         next unless /^\s?(typedef\s?)?enum\s?([a-zA-Z_]\w*)?\s?\{(.*)\}\s?([a-zA-Z_]\w*)?\s?;/;
  252.         (my $enum_subs = $3) =~ s/\s//g;
  253.         my @enum_subs = split(/,/, $enum_subs);
  254.         my $enum_val = -1;
  255.         foreach my $enum (@enum_subs) {
  256.         my ($enum_name, $enum_value) = $enum =~ /^([a-zA-Z_]\w*)(=.+)?$/;
  257.         $enum_value =~ s/^=//;
  258.         $enum_val = (length($enum_value) ? $enum_value : $enum_val + 1);
  259.         if ($opt_h) {
  260.             print OUT ($t,
  261.                    "eval(\"\\n#line $eval_index $outfile\\n",
  262.                    "sub $enum_name () \{ $enum_val; \}\") ",
  263.                    "unless defined(\&$enum_name);\n");
  264.             ++ $eval_index;
  265.         } else {
  266.             print OUT ($t,
  267.                    "eval(\"sub $enum_name () \{ $enum_val; \}\") ",
  268.                    "unless defined(\&$enum_name);\n");
  269.         }
  270.         }
  271.     } elsif (/^(?:__extension__\s+)?(?:extern|static)\s+(?:__)?inline(?:__)?\s+/
  272.         and !/;\s*$/ and !/{\s*}\s*$/)
  273.     { # { for vi
  274.         # This is a hack to parse the inline functions in the glibc headers.
  275.         # Warning: massive kludge ahead. We suppose inline functions
  276.         # are mainly constructed like macros.
  277.         while (1) {
  278.         last unless defined ($next = next_line($file));
  279.         chomp $next;
  280.         undef $_, last if $next =~ /__THROW\s*;/
  281.                    or $next =~ /^(__extension__|extern|static)\b/;
  282.         $_ .= " $next";
  283.         print OUT "# $next\n" if $opt_D;
  284.         last if $next =~ /^}|^{.*}\s*$/;
  285.         }
  286.         next if not defined; # because it's only a prototype
  287.         s/\b(__extension__|extern|static|(?:__)?inline(?:__)?)\b//g;
  288.         # violently drop #ifdefs
  289.         s/#\s*if.*?#\s*endif//g
  290.         and print OUT "# some #ifdef were dropped here -- fill in the blanks\n";
  291.         if (s/^(?:\w|\s|\*)*\s(\w+)\s*//) {
  292.         $name = $1;
  293.         } else {
  294.         warn "name not found"; next; # shouldn't occur...
  295.         }
  296.         my @args;
  297.         if (s/^\(([^()]*)\)\s*(\w+\s*)*//) {
  298.         for my $arg (split /,/, $1) {
  299.             if ($arg =~ /(\w+)\s*$/) {
  300.             $curargs{$1} = 1;
  301.             push @args, $1;
  302.             }
  303.         }
  304.         }
  305.         $args = (
  306.         @args
  307.         ? "local(" . (join ',', map "\$$_", @args) . ") = \@_;\n$t    "
  308.         : ""
  309.         );
  310.         my $proto = @args ? '' : '() ';
  311.         $new = '';
  312.         s/\breturn\b//g; # "return" doesn't occur in macros usually...
  313.         expr();
  314.         # try to find and perlify local C variables
  315.         our @local_variables = (); # needs to be a our(): (?{...}) bug workaround
  316.         {
  317.         use re "eval";
  318.         my $typelist = join '|', keys %isatype;
  319.         $new =~ s['
  320.           (?:(?:un)?signed\s+)?
  321.           (?:long\s+)?
  322.           (?:$typelist)\s+
  323.           (\w+)
  324.           (?{ push @local_variables, $1 })
  325.           ']
  326.          [my \$$1]gx;
  327.         $new =~ s['
  328.           (?:(?:un)?signed\s+)?
  329.           (?:long\s+)?
  330.           (?:$typelist)\s+
  331.           ' \s+ &(\w+) \s* ;
  332.           (?{ push @local_variables, $1 })
  333.           ]
  334.          [my \$$1;]gx;
  335.          }
  336.         $new =~ s/&$_\b/\$$_/g for @local_variables;
  337.         $new =~ s/(["\\])/\\$1/g;       #"]);
  338.         # now that's almost like a macro (we hope)
  339.         goto EMIT;
  340.     }
  341.     }
  342.     $Is_converted{$file} = 1;
  343.     if ($opt_e && exists($bad_file{$file})) {
  344.         unlink($Dest_dir . '/' . $outfile);
  345.         $next = '';
  346.     } else {
  347.         print OUT "1;\n";
  348.     queue_includes_from($file) if $opt_a;
  349.     }
  350. }
  351.  
  352. if ($opt_e && (scalar(keys %bad_file) > 0)) {
  353.     warn "Was unable to convert the following files:\n";
  354.     warn "\t" . join("\n\t",sort(keys %bad_file)) . "\n";
  355. }
  356.  
  357. exit $Exit;
  358.  
  359. sub expr {
  360.     my $joined_args;
  361.     if(keys(%curargs)) {
  362.     $joined_args = join('|', keys(%curargs));
  363.     }
  364.     while ($_ ne '') {
  365.     s/^\&\&// && do { $new .= " &&"; next;}; # handle && operator
  366.     s/^\&([\(a-z\)]+)/$1/i;    # hack for things that take the address of
  367.     s/^(\s+)//        && do {$new .= ' '; next;};
  368.     s/^0X([0-9A-F]+)[UL]*//i 
  369.         && do {my $hex = $1;
  370.            $hex =~ s/^0+//;
  371.            if (length $hex > 8 && !$Config{use64bitint}) {
  372.                # Croak if nv_preserves_uv_bits < 64 ?
  373.                $new .=         hex(substr($hex, -8)) +
  374.                    2**32 * hex(substr($hex,  0, -8));
  375.                # The above will produce "errorneus" code
  376.                # if the hex constant was e.g. inside UINT64_C
  377.                # macro, but then again, h2ph is an approximation.
  378.            } else {
  379.                $new .= lc("0x$hex");
  380.            }
  381.            next;};
  382.     s/^(-?\d+\.\d+E[-+]?\d+)[FL]?//i    && do {$new .= $1; next;};
  383.     s/^(\d+)\s*[LU]*//i    && do {$new .= $1; next;};
  384.     s/^("(\\"|[^"])*")//    && do {$new .= $1; next;};
  385.     s/^'((\\"|[^"])*)'//    && do {
  386.         if ($curargs{$1}) {
  387.         $new .= "ord('\$$1')";
  388.         } else {
  389.         $new .= "ord('$1')";
  390.         }
  391.         next;
  392.     };
  393.         # replace "sizeof(foo)" with "{foo}"
  394.         # also, remove * (C dereference operator) to avoid perl syntax
  395.         # problems.  Where the %sizeof array comes from is anyone's
  396.         # guess (c2ph?), but this at least avoids fatal syntax errors.
  397.         # Behavior is undefined if sizeof() delimiters are unbalanced.
  398.         # This code was modified to able to handle constructs like this:
  399.         #   sizeof(*(p)), which appear in the HP-UX 10.01 header files.
  400.         s/^sizeof\s*\(// && do {
  401.             $new .= '$sizeof';
  402.             my $lvl = 1;  # already saw one open paren
  403.             # tack { on the front, and skip it in the loop
  404.             $_ = "{" . "$_";
  405.             my $index = 1;
  406.             # find balanced closing paren
  407.             while ($index <= length($_) && $lvl > 0) {
  408.                 $lvl++ if substr($_, $index, 1) eq "(";
  409.                 $lvl-- if substr($_, $index, 1) eq ")";
  410.                 $index++;
  411.             }
  412.             # tack } on the end, replacing )
  413.             substr($_, $index - 1, 1) = "}";
  414.             # remove pesky * operators within the sizeof argument
  415.             substr($_, 0, $index - 1) =~ s/\*//g;
  416.             next;
  417.         };
  418.     # Eliminate typedefs
  419.     /\(([\w\s]+)[\*\s]*\)\s*[\w\(]/ && do {
  420.         my $doit = 1;
  421.         foreach (split /\s+/, $1) {  # Make sure all the words are types,
  422.             unless($isatype{$_} or $_ eq 'struct' or $_ eq 'union'){
  423.             $doit = 0;
  424.             last;
  425.         }
  426.         }
  427.         if( $doit ){
  428.         s/\([\w\s]+[\*\s]*\)// && next;      # then eliminate them.
  429.         }
  430.     };
  431.     # struct/union member, including arrays:
  432.     s/^([_A-Z]\w*(\[[^\]]+\])?((\.|->)[_A-Z]\w*(\[[^\]]+\])?)+)//i && do {
  433.         my $id = $1;
  434.         $id =~ s/(\.|(->))([^\.\-]*)/->\{$3\}/g;
  435.         $id =~ s/\b([^\$])($joined_args)/$1\$$2/g if length($joined_args);
  436.         while($id =~ /\[\s*([^\$\&\d\]]+)\]/) {
  437.         my($index) = $1;
  438.         $index =~ s/\s//g;
  439.         if(exists($curargs{$index})) {
  440.             $index = "\$$index";
  441.         } else {
  442.             $index = "&$index";
  443.         }
  444.         $id =~ s/\[\s*([^\$\&\d\]]+)\]/[$index]/;
  445.         }
  446.         $new .= " (\$$id)";
  447.     };
  448.     s/^([_a-zA-Z]\w*)//    && do {
  449.         my $id = $1;
  450.         if ($id eq 'struct' || $id eq 'union') {
  451.         s/^\s+(\w+)//;
  452.         $id .= ' ' . $1;
  453.         $isatype{$id} = 1;
  454.         } elsif ($id =~ /^((un)?signed)|(long)|(short)$/) {
  455.         while (s/^\s+(\w+)//) { $id .= ' ' . $1; }
  456.         $isatype{$id} = 1;
  457.         }
  458.         if ($curargs{$id}) {
  459.         $new .= "\$$id";
  460.         $new .= '->' if /^[\[\{]/;
  461.         } elsif ($id eq 'defined') {
  462.         $new .= 'defined';
  463.         } elsif (/^\s*\(/) {
  464.         s/^\s*\((\w),/("$1",/ if $id =~ /^_IO[WR]*$/i;    # cheat
  465.         $new .= " &$id";
  466.         } elsif ($isatype{$id}) {
  467.         if ($new =~ /{\s*$/) {
  468.             $new .= "'$id'";
  469.         } elsif ($new =~ /\(\s*$/ && /^[\s*]*\)/) {
  470.             $new =~ s/\(\s*$//;
  471.             s/^[\s*]*\)//;
  472.         } else {
  473.             $new .= q(').$id.q(');
  474.         }
  475.         } else {
  476.         if ($inif && $new !~ /defined\s*\($/) {
  477.             $new .= '(defined(&' . $id . ') ? &' . $id . ' : 0)';
  478.         } elsif (/^\[/) {
  479.             $new .= " \$$id";
  480.         } else {
  481.             $new .= ' &' . $id;
  482.         }
  483.         }
  484.         next;
  485.     };
  486.     s/^(.)// && do { if ($1 ne '#') { $new .= $1; } next;};
  487.     }
  488. }
  489.  
  490.  
  491. sub next_line
  492. {
  493.     my $file = shift;
  494.     my ($in, $out);
  495.     my $pre_sub_tri_graphs = 1;
  496.  
  497.     READ: while (not eof IN) {
  498.         $in  .= <IN>;
  499.         chomp $in;
  500.         next unless length $in;
  501.  
  502.         while (length $in) {
  503.             if ($pre_sub_tri_graphs) {
  504.                 # Preprocess all tri-graphs 
  505.                 # including things stuck in quoted string constants.
  506.                 $in =~ s/\?\?=/#/g;                         # | ??=|  #|
  507.                 $in =~ s/\?\?\!/|/g;                        # | ??!|  ||
  508.                 $in =~ s/\?\?'/^/g;                         # | ??'|  ^|
  509.                 $in =~ s/\?\?\(/[/g;                        # | ??(|  [|
  510.                 $in =~ s/\?\?\)/]/g;                        # | ??)|  ]|
  511.                 $in =~ s/\?\?\-/~/g;                        # | ??-|  ~|
  512.                 $in =~ s/\?\?\//\\/g;                       # | ??/|  \|
  513.                 $in =~ s/\?\?</{/g;                         # | ??<|  {|
  514.                 $in =~ s/\?\?>/}/g;                         # | ??>|  }|
  515.             }
  516.         if ($in =~ /^\#ifdef __LANGUAGE_PASCAL__/) {
  517.                 # Tru64 disassembler.h evilness: mixed C and Pascal.
  518.         while (<IN>) {
  519.             last if /^\#endif/; 
  520.         }
  521.         next READ;
  522.         }
  523.         if ($in =~ /^extern inline / && # Inlined assembler.
  524.         $^O eq 'linux' && $file =~ m!(?:^|/)asm/[^/]+\.h$!) {
  525.          while (<IN>) {
  526.             last if /^}/; 
  527.         }
  528.         next READ;
  529.         }
  530.             if ($in =~ s/\\$//) {                           # \-newline
  531.                 $out    .= ' ';
  532.                 next READ;
  533.             } elsif ($in =~ s/^([^"'\\\/]+)//) {            # Passthrough
  534.                 $out    .= $1;
  535.             } elsif ($in =~ s/^(\\.)//) {                   # \...
  536.                 $out    .= $1;
  537.             } elsif ($in =~ /^'/) {                         # '...
  538.                 if ($in =~ s/^('(\\.|[^'\\])*')//) {
  539.                     $out    .= $1;
  540.                 } else {
  541.                     next READ;
  542.                 }
  543.             } elsif ($in =~ /^"/) {                         # "...
  544.                 if ($in =~ s/^("(\\.|[^"\\])*")//) {
  545.                     $out    .= $1;
  546.                 } else {
  547.                     next READ;
  548.                 }
  549.             } elsif ($in =~ s/^\/\/.*//) {                  # //...
  550.                 # fall through
  551.             } elsif ($in =~ m/^\/\*/) {                     # /*...
  552.                 # C comment removal adapted from perlfaq6:
  553.                 if ($in =~ s/^\/\*[^*]*\*+([^\/*][^*]*\*+)*\///) {
  554.                     $out    .= ' ';
  555.                 } else {                                    # Incomplete /* */
  556.                     next READ;
  557.                 }
  558.             } elsif ($in =~ s/^(\/)//) {                    # /...
  559.                 $out    .= $1;
  560.             } elsif ($in =~ s/^([^\'\"\\\/]+)//) {
  561.                 $out    .= $1;
  562.             } elsif ($^O eq 'linux' &&
  563.                      $file =~ m!(?:^|/)linux/byteorder/pdp_endian\.h$! &&
  564.                      $in   =~ s!\'T KNOW!!) {
  565.                 $out    =~ s!I DON$!I_DO_NOT_KNOW!;
  566.             } else {
  567.                 if ($opt_e) {
  568.                     warn "Cannot parse $file:\n$in\n";
  569.                     $bad_file{$file} = 1;
  570.                     $in = '';
  571.                     $out = undef;
  572.                     last READ;
  573.                 } else {
  574.         die "Cannot parse:\n$in\n";
  575.                 }
  576.             }
  577.         }
  578.  
  579.         last READ if $out =~ /\S/;
  580.     }
  581.  
  582.     return $out;
  583. }
  584.  
  585.  
  586. # Handle recursive subdirectories without getting a grotesquely big stack.
  587. # Could this be implemented using File::Find?
  588. sub next_file
  589. {
  590.     my $file;
  591.  
  592.     while (@ARGV) {
  593.         $file = shift @ARGV;
  594.  
  595.         if ($file eq '-' or -f $file or -l $file) {
  596.             return $file;
  597.         } elsif (-d $file) {
  598.             if ($opt_r) {
  599.                 expand_glob($file);
  600.             } else {
  601.                 print STDERR "Skipping directory `$file'\n";
  602.             }
  603.         } elsif ($opt_a) {
  604.             return $file;
  605.         } else {
  606.             print STDERR "Skipping `$file':  not a file or directory\n";
  607.         }
  608.     }
  609.  
  610.     return undef;
  611. }
  612.  
  613.  
  614. # Put all the files in $directory into @ARGV for processing.
  615. sub expand_glob
  616. {
  617.     my ($directory)  = @_;
  618.  
  619.     $directory =~ s:/$::;
  620.  
  621.     opendir DIR, $directory;
  622.         foreach (readdir DIR) {
  623.             next if ($_ eq '.' or $_ eq '..');
  624.  
  625.             # expand_glob() is going to be called until $ARGV[0] isn't a
  626.             # directory; so push directories, and unshift everything else.
  627.             if (-d "$directory/$_") { push    @ARGV, "$directory/$_" }
  628.             else                    { unshift @ARGV, "$directory/$_" }
  629.         }
  630.     closedir DIR;
  631. }
  632.  
  633.  
  634. # Given $file, a symbolic link to a directory in the C include directory,
  635. # make an equivalent symbolic link in $Dest_dir, if we can figure out how.
  636. # Otherwise, just duplicate the file or directory.
  637. sub link_if_possible
  638. {
  639.     my ($dirlink)  = @_;
  640.     my $target  = eval 'readlink($dirlink)';
  641.  
  642.     if ($target =~ m:^\.\./: or $target =~ m:^/:) {
  643.         # The target of a parent or absolute link could leave the $Dest_dir
  644.         # hierarchy, so let's put all of the contents of $dirlink (actually,
  645.         # the contents of $target) into @ARGV; as a side effect down the
  646.         # line, $dirlink will get created as an _actual_ directory.
  647.         expand_glob($dirlink);
  648.     } else {
  649.         if (-l "$Dest_dir/$dirlink") {
  650.             unlink "$Dest_dir/$dirlink" or
  651.                 print STDERR "Could not remove link $Dest_dir/$dirlink:  $!\n";
  652.         }
  653.  
  654.         if (eval 'symlink($target, "$Dest_dir/$dirlink")') {
  655.             print "Linking $target -> $Dest_dir/$dirlink\n";
  656.  
  657.             # Make sure that the link _links_ to something:
  658.             if (! -e "$Dest_dir/$target") {
  659.                 mkpath("$Dest_dir/$target", 0755) or
  660.                     print STDERR "Could not create $Dest_dir/$target/\n";
  661.             }
  662.         } else {
  663.             print STDERR "Could not symlink $target -> $Dest_dir/$dirlink:  $!\n";
  664.         }
  665.     }
  666. }
  667.  
  668.  
  669. # Push all #included files in $file onto our stack, except for STDIN
  670. # and files we've already processed.
  671. sub queue_includes_from
  672. {
  673.     my ($file)    = @_;
  674.     my $line;
  675.  
  676.     return if ($file eq "-");
  677.  
  678.     open HEADER, $file or return;
  679.         while (defined($line = <HEADER>)) {
  680.             while (/\\$/) { # Handle continuation lines
  681.                 chop $line;
  682.                 $line .= <HEADER>;
  683.             }
  684.  
  685.             if ($line =~ /^#\s*include\s+<(.*?)>/) {
  686.                 push(@ARGV, $1) unless $Is_converted{$1};
  687.             }
  688.         }
  689.     close HEADER;
  690. }
  691.  
  692.  
  693. # Determine include directories; $Config{usrinc} should be enough for (all
  694. # non-GCC?) C compilers, but gcc uses an additional include directory.
  695. sub inc_dirs
  696. {
  697.     my $from_gcc    = `$Config{cc} -v 2>&1`;
  698.     $from_gcc       =~ s:^Reading specs from (.*?)/specs\b.*:$1/include:s;
  699.  
  700.     length($from_gcc) ? ($from_gcc, $Config{usrinc}) : ($Config{usrinc});
  701. }
  702.  
  703.  
  704. # Create "_h2ph_pre.ph", if it doesn't exist or was built by a different
  705. # version of h2ph.
  706. sub build_preamble_if_necessary
  707. {
  708.     # Increment $VERSION every time this function is modified:
  709.     my $VERSION     = 2;
  710.     my $preamble    = "$Dest_dir/_h2ph_pre.ph";
  711.  
  712.     # Can we skip building the preamble file?
  713.     if (-r $preamble) {
  714.         # Extract version number from first line of preamble:
  715.         open  PREAMBLE, $preamble or die "Cannot open $preamble:  $!";
  716.             my $line = <PREAMBLE>;
  717.             $line =~ /(\b\d+\b)/;
  718.         close PREAMBLE            or die "Cannot close $preamble:  $!";
  719.  
  720.         # Don't build preamble if a compatible preamble exists:
  721.         return if $1 == $VERSION;
  722.     }
  723.  
  724.     my (%define) = _extract_cc_defines();
  725.  
  726.     open  PREAMBLE, ">$preamble" or die "Cannot open $preamble:  $!";
  727.         print PREAMBLE "# This file was created by h2ph version $VERSION\n";
  728.  
  729.         foreach (sort keys %define) {
  730.             if ($opt_D) {
  731.                 print PREAMBLE "# $_=$define{$_}\n";
  732.             }
  733.  
  734.             if ($define{$_} =~ /^(\d+)U?L{0,2}$/i) {
  735.                 print PREAMBLE
  736.                     "unless (defined &$_) { sub $_() { $1 } }\n\n";
  737.             } elsif ($define{$_} =~ /^\w+$/) {
  738.                 print PREAMBLE
  739.                     "unless (defined &$_) { sub $_() { &$define{$_} } }\n\n";
  740.             } else {
  741.                 print PREAMBLE
  742.                     "unless (defined &$_) { sub $_() { \"",
  743.                     quotemeta($define{$_}), "\" } }\n\n";
  744.             }
  745.         }
  746.     close PREAMBLE               or die "Cannot close $preamble:  $!";
  747. }
  748.  
  749.  
  750. # %Config contains information on macros that are pre-defined by the
  751. # system's compiler.  We need this information to make the .ph files
  752. # function with perl as the .h files do with cc.
  753. sub _extract_cc_defines
  754. {
  755.     my %define;
  756.     my $allsymbols  = join " ",
  757.         @Config{'ccsymbols', 'cppsymbols', 'cppccsymbols'};
  758.  
  759.     # Split compiler pre-definitions into `key=value' pairs:
  760.     foreach (split /\s+/, $allsymbols) {
  761.         /(.+?)=(.+)/ and $define{$1} = $2;
  762.  
  763.         if ($opt_D) {
  764.             print STDERR "$_:  $1 -> $2\n";
  765.         }
  766.     }
  767.  
  768.     return %define;
  769. }
  770.  
  771.  
  772. 1;
  773.  
  774. ##############################################################################
  775. __END__
  776.  
  777. =head1 NAME
  778.  
  779. h2ph - convert .h C header files to .ph Perl header files
  780.  
  781. =head1 SYNOPSIS
  782.  
  783. B<h2ph [-d destination directory] [-r | -a] [-l] [headerfiles]>
  784.  
  785. =head1 DESCRIPTION
  786.  
  787. I<h2ph>
  788. converts any C header files specified to the corresponding Perl header file
  789. format.
  790. It is most easily run while in /usr/include:
  791.  
  792.     cd /usr/include; h2ph * sys/*
  793.  
  794. or
  795.  
  796.     cd /usr/include; h2ph * sys/* arpa/* netinet/*
  797.  
  798. or
  799.  
  800.     cd /usr/include; h2ph -r -l .
  801.  
  802. The output files are placed in the hierarchy rooted at Perl's
  803. architecture dependent library directory.  You can specify a different
  804. hierarchy with a B<-d> switch.
  805.  
  806. If run with no arguments, filters standard input to standard output.
  807.  
  808. =head1 OPTIONS
  809.  
  810. =over 4
  811.  
  812. =item -d destination_dir
  813.  
  814. Put the resulting B<.ph> files beneath B<destination_dir>, instead of
  815. beneath the default Perl library location (C<$Config{'installsitsearch'}>).
  816.  
  817. =item -r
  818.  
  819. Run recursively; if any of B<headerfiles> are directories, then run I<h2ph>
  820. on all files in those directories (and their subdirectories, etc.).  B<-r>
  821. and B<-a> are mutually exclusive.
  822.  
  823. =item -a
  824.  
  825. Run automagically; convert B<headerfiles>, as well as any B<.h> files
  826. which they include.  This option will search for B<.h> files in all
  827. directories which your C compiler ordinarily uses.  B<-a> and B<-r> are
  828. mutually exclusive.
  829.  
  830. =item -l
  831.  
  832. Symbolic links will be replicated in the destination directory.  If B<-l>
  833. is not specified, then links are skipped over.
  834.  
  835. =item -h
  836.  
  837. Put ``hints'' in the .ph files which will help in locating problems with
  838. I<h2ph>.  In those cases when you B<require> a B<.ph> file containing syntax
  839. errors, instead of the cryptic
  840.  
  841.     [ some error condition ] at (eval mmm) line nnn
  842.  
  843. you will see the slightly more helpful
  844.  
  845.     [ some error condition ] at filename.ph line nnn
  846.  
  847. However, the B<.ph> files almost double in size when built using B<-h>.
  848.  
  849. =item -D
  850.  
  851. Include the code from the B<.h> file as a comment in the B<.ph> file.
  852. This is primarily used for debugging I<h2ph>.
  853.  
  854. =item -Q
  855.  
  856. ``Quiet'' mode; don't print out the names of the files being converted.
  857.  
  858. =back
  859.  
  860. =head1 ENVIRONMENT
  861.  
  862. No environment variables are used.
  863.  
  864. =head1 FILES
  865.  
  866.  /usr/include/*.h
  867.  /usr/include/sys/*.h
  868.  
  869. etc.
  870.  
  871. =head1 AUTHOR
  872.  
  873. Larry Wall
  874.  
  875. =head1 SEE ALSO
  876.  
  877. perl(1)
  878.  
  879. =head1 DIAGNOSTICS
  880.  
  881. The usual warnings if it can't read or write the files involved.
  882.  
  883. =head1 BUGS
  884.  
  885. Doesn't construct the %sizeof array for you.
  886.  
  887. It doesn't handle all C constructs, but it does attempt to isolate
  888. definitions inside evals so that you can get at the definitions
  889. that it can translate.
  890.  
  891. It's only intended as a rough tool.
  892. You may need to dicker with the files produced.
  893.  
  894. You have to run this program by hand; it's not run as part of the Perl
  895. installation.
  896.  
  897. Doesn't handle complicated expressions built piecemeal, a la:
  898.  
  899.     enum {
  900.         FIRST_VALUE,
  901.         SECOND_VALUE,
  902.     #ifdef ABC
  903.         THIRD_VALUE
  904.     #endif
  905.     };
  906.  
  907. Doesn't necessarily locate all of your C compiler's internally-defined
  908. symbols.
  909.  
  910. =cut
  911.  
  912.