Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
h2ph978 linesDownload Raw Back to core_perl
1#!/usr/bin/perl2    eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'3	if 0; # ^ Run only under a shell4 5BEGIN { pop @INC if $INC[-1] eq '.' }6 7use strict;8 9use Config;10use File::Path qw(mkpath);11use Getopt::Std;12 13# Make sure read permissions for all are set:14if (defined umask && (umask() & 0444)) {15    umask (umask() & ~0444);16}17 18getopts('Dd:rlhaQe');19use vars qw($opt_D $opt_d $opt_r $opt_l $opt_h $opt_a $opt_Q $opt_e);20die "-r and -a options are mutually exclusive\n" if ($opt_r and $opt_a);21my @inc_dirs = inc_dirs() if $opt_a;22 23my $Exit = 0;24 25my $Dest_dir = $opt_d || $Config{installsitearch};26die "Destination directory $Dest_dir doesn't exist or isn't a directory\n"27    unless -d $Dest_dir;28 29my @isatype = qw(30	char	uchar	u_char31	short	ushort	u_short32	int	uint	u_int33	long	ulong	u_long34	FILE	key_t	caddr_t35	float	double	size_t36);37 38my %isatype;39@isatype{@isatype} = (1) x @isatype;40my $inif = 0;41my %Is_converted;42my %bad_file = ();43 44@ARGV = ('-') unless @ARGV;45 46build_preamble_if_necessary();47 48sub reindent($) {49    my($text) = shift;50    $text =~ s/\n/\n    /g;51    $text =~ s/        /\t/g;52    $text;53}54 55my ($t, $tab, %curargs, $new, $eval_index, $dir, $name, $args, $outfile);56my ($incl, $incl_type, $incl_quote, $next);57while (defined (my $file = next_file())) {58    if (-l $file and -d $file) {59        link_if_possible($file) if ($opt_l);60        next;61    }62 63    # Recover from header files with unbalanced cpp directives64    $t = '';65    $tab = 0;66 67    # $eval_index goes into '#line' directives, to help locate syntax errors:68    $eval_index = 1;69 70    if ($file eq '-') {71	open(IN, "-");72	open(OUT, ">-");73    } else {74	($outfile = $file) =~ s/\.h$/.ph/ || next;75	print "$file -> $outfile\n" unless $opt_Q;76	if ($file =~ m|^(.*)/|) {77	    $dir = $1;78	    mkpath "$Dest_dir/$dir";79	}80 81	if ($opt_a) { # automagic mode:  locate header file in @inc_dirs82	    foreach (@inc_dirs) {83		chdir $_;84		last if -f $file;85	    }86	}87 88	open(IN, "<", "$file") || (($Exit = 1),(warn "Can't open $file: $!\n"),next);89	open(OUT, ">", "$Dest_dir/$outfile") || die "Can't create $outfile: $!\n";90    }91 92    print OUT93        "require '_h2ph_pre.ph';\n\n",94        "no warnings qw(redefine misc);\n\n";95 96    while (defined (local $_ = next_line($file))) {97	if (s/^\s*\#\s*//) {98	    if (s/^define\s+(\w+)//) {99		$name = $1;100		$new = '';101		s/\s+$//;102		s/\(\w+\s*\(\*\)\s*\(\w*\)\)\s*(-?\d+)/$1/; # (int (*)(foo_t))0103		if (s/^\(([\w,\s]*)\)//) {104		    $args = $1;105		    my $proto = '() ';106		    if ($args ne '') {107			$proto = '';108			foreach my $arg (split(/,\s*/,$args)) {109			    $arg =~ s/^\s*([^\s].*[^\s])\s*$/$1/;110			    $curargs{$arg} = 1;111			}112			$args =~ s/\b(\w)/\$$1/g;113			$args = "my($args) = \@_;\n$t    ";114		    }115		    s/^\s+//;116		    expr();117		    $new =~ s/(["\\])/\\$1/g;       #"]);118		    EMIT($proto);119		} else {120		    s/^\s+//;121		    expr();122 123		    $new = 1 if $new eq '';124 125		    # Shunt around such directives as '#define FOO FOO':126		    next if $new =~ /^\s*&\Q$name\E\s*\z/;127 128		    $new = reindent($new);129		    $args = reindent($args);130		    $new =~ s/(['\\])/\\$1/g;        #']);131 132	    	    print OUT $t, 'eval ';133		    if ($opt_h) {134			print OUT "\"\\n#line $eval_index $outfile\\n\" . ";135			$eval_index++;136		    }137		    print OUT "'sub $name () {$new;}' unless defined(&$name);\n";138		}139	    } elsif (/^(include|import|include_next)\s*([<\"])(.*)[>\"]/) {140                $incl_type = $1;141                $incl_quote = $2;142                $incl = $3;143                if (($incl_type eq 'include_next') ||144                    ($opt_e && exists($bad_file{$incl}))) {145                    $incl =~ s/\.h$/.ph/;146		print OUT ($t,147			   "eval {\n");148                $tab += 4;149                $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);150                    print OUT ($t, "my(\@REM);\n");151                    if ($incl_type eq 'include_next') {152		print OUT ($t,153			   "my(\%INCD) = map { \$INC{\$_} => 1 } ",154			           "(grep { \$_ eq \"$incl\" } ",155                                   "keys(\%INC));\n");156		print OUT ($t,157			           "\@REM = map { \"\$_/$incl\" } ",158			   "(grep { not exists(\$INCD{\"\$_/$incl\"})",159			           " and -f \"\$_/$incl\" } \@INC);\n");160                    } else {161                        print OUT ($t,162                                   "\@REM = map { \"\$_/$incl\" } ",163                                   "(grep {-r \"\$_/$incl\" } \@INC);\n");164                    }165		print OUT ($t,166			   "require \"\$REM[0]\" if \@REM;\n");167                $tab -= 4;168                $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);169                print OUT ($t,170			   "};\n");171		print OUT ($t,172			   "warn(\$\@) if \$\@;\n");173                } else {174                    $incl =~ s/\.h$/.ph/;175                    # copy the prefix in the quote syntax (#include "x.h") case176                    if ($incl !~ m|/| && $incl_quote eq q{"} && $file =~ m|^(.*)/|) {177                        $incl = "$1/$incl";178                    }179		    print OUT $t,"require '$incl';\n";180                }181	    } elsif (/^ifdef\s+(\w+)/) {182		print OUT $t,"if(defined(&$1)) {\n";183		$tab += 4;184		$t = "\t" x ($tab / 8) . ' ' x ($tab % 8);185	    } elsif (/^ifndef\s+(\w+)/) {186		print OUT $t,"unless(defined(&$1)) {\n";187		$tab += 4;188		$t = "\t" x ($tab / 8) . ' ' x ($tab % 8);189	    } elsif (s/^if\s+//) {190		$new = '';191		$inif = 1;192		expr();193		$inif = 0;194		print OUT $t,"if($new) {\n";195		$tab += 4;196		$t = "\t" x ($tab / 8) . ' ' x ($tab % 8);197	    } elsif (s/^elif\s+//) {198		$new = '';199		$inif = 1;200		expr();201		$inif = 0;202		$tab -= 4;203		$t = "\t" x ($tab / 8) . ' ' x ($tab % 8);204		print OUT $t,"}\n elsif($new) {\n";205		$tab += 4;206		$t = "\t" x ($tab / 8) . ' ' x ($tab % 8);207	    } elsif (/^else/) {208		$tab -= 4;209		$t = "\t" x ($tab / 8) . ' ' x ($tab % 8);210		print OUT $t,"} else {\n";211		$tab += 4;212		$t = "\t" x ($tab / 8) . ' ' x ($tab % 8);213	    } elsif (/^endif/) {214		$tab -= 4;215		$t = "\t" x ($tab / 8) . ' ' x ($tab % 8);216		print OUT $t,"}\n";217	    } elsif(/^undef\s+(\w+)/) {218		print OUT $t, "undef(&$1) if defined(&$1);\n";219	    } elsif(/^error\s+(".*")/) {220		print OUT $t, "die($1);\n";221	    } elsif(/^error\s+(.*)/) {222		print OUT $t, "die(\"", quotemeta($1), "\");\n";223	    } elsif(/^warning\s+(.*)/) {224		print OUT $t, "warn(\"", quotemeta($1), "\");\n";225	    } elsif(/^ident\s+(.*)/) {226		print OUT $t, "# $1\n";227	    }228	} elsif (/^\s*(typedef\s*)?enum\s*(\s+[a-zA-Z_]\w*\s*)?/) { # { for vi229	    until(/\{[^}]*\}.*;/ || /;/) {230		last unless defined ($next = next_line($file));231		chomp $next;232		# drop "#define FOO FOO" in enums233		$next =~ s/^\s*#\s*define\s+(\w+)\s+\1\s*$//;234		# #defines in enums (aliases)235		$next =~ s/^\s*#\s*define\s+(\w+)\s+(\w+)\s*$/$1 = $2,/;236		$_ .= $next;237		print OUT "# $next\n" if $opt_D;238	    }239	    s/#\s*if.*?#\s*endif//g; # drop #ifdefs240	    s@/\*.*?\*/@@g;241	    s/\s+/ /g;242	    next unless /^\s?(typedef\s?)?enum\s?([a-zA-Z_]\w*)?\s?\{(.*)\}\s?([a-zA-Z_]\w*)?\s?;/;243	    (my $enum_subs = $3) =~ s/\s//g;244	    my @enum_subs = split(/,/, $enum_subs);245	    my $enum_val = -1;246	    foreach my $enum (@enum_subs) {247		my ($enum_name, $enum_value) = $enum =~ /^([a-zA-Z_]\w*)(=.+)?$/;248		$enum_name or next;249		$enum_value =~ s/^=//;250		$enum_val = (length($enum_value) ? $enum_value : $enum_val + 1);251		if ($opt_h) {252		    print OUT ($t,253			       "eval(\"\\n#line $eval_index $outfile\\n",254			       "sub $enum_name () \{ $enum_val; \}\") ",255			       "unless defined(\&$enum_name);\n");256		    ++ $eval_index;257		} else {258		    print OUT ($t,259			       "eval(\"sub $enum_name () \{ $enum_val; \}\") ",260			       "unless defined(\&$enum_name);\n");261		}262	    }263	} elsif (/^(?:__extension__\s+)?(?:extern|static)\s+(?:__)?inline(?:__)?\s+/264	    and !/;\s*$/ and !/{\s*}\s*$/)265	{ # { for vi266	    # This is a hack to parse the inline functions in the glibc headers.267	    # Warning: massive kludge ahead. We suppose inline functions268	    # are mainly constructed like macros.269	    while (1) {270		last unless defined ($next = next_line($file));271		chomp $next;272		undef $_, last if $next =~ /__THROW\s*;/273			       or $next =~ /^(__extension__|extern|static)\b/;274		$_ .= " $next";275		print OUT "# $next\n" if $opt_D;276		last if $next =~ /^}|^{.*}\s*$/;277	    }278	    next if not defined; # because it's only a prototype279	    s/\b(__extension__|extern|static|(?:__)?inline(?:__)?)\b//g;280	    # violently drop #ifdefs281	    s/#\s*if.*?#\s*endif//g282		and print OUT "# some #ifdef were dropped here -- fill in the blanks\n";283	    if (s/^(?:\w|\s|\*)*\s(\w+)\s*//) {284		$name = $1;285	    } else {286		warn "name not found"; next; # shouldn't occur...287	    }288	    my @args;289	    if (s/^\(([^()]*)\)\s*(\w+\s*)*//) {290		for my $arg (split /,/, $1) {291		    if ($arg =~ /(\w+)\s*$/) {292			$curargs{$1} = 1;293			push @args, $1;294		    }295		}296	    }297	    $args = (298		@args299		? "my(" . (join ',', map "\$$_", @args) . ") = \@_;\n$t    "300		: ""301	    );302	    my $proto = @args ? '' : '() ';303	    $new = '';304	    s/\breturn\b//g; # "return" doesn't occur in macros usually...305	    expr();306	    # try to find and perlify local C variables307	    our @local_variables = (); # needs to be a our(): (?{...}) bug workaround308	    {309		use re "eval";310		my $typelist = join '|', keys %isatype;311		$new =~ s['312		  (?:(?:__)?const(?:__)?\s+)?313		  (?:(?:un)?signed\s+)?314		  (?:long\s+)?315		  (?:$typelist)\s+316		  (\w+)317		  (?{ push @local_variables, $1 })318		  ']319		 [my \$$1]gx;320		$new =~ s['321		  (?:(?:__)?const(?:__)?\s+)?322		  (?:(?:un)?signed\s+)?323		  (?:long\s+)?324		  (?:$typelist)\s+325		  ' \s+ &(\w+) \s* ;326		  (?{ push @local_variables, $1 })327		  ]328		 [my \$$1;]gx;329	     }330	    $new =~ s/&$_\b/\$$_/g for @local_variables;331	    $new =~ s/(["\\])/\\$1/g;       #"]);332	    # now that's almost like a macro (we hope)333	    EMIT($proto);334	}335    }336    $Is_converted{$file} = 1;337    if ($opt_e && exists($bad_file{$file})) {338        unlink($Dest_dir . '/' . $outfile);339        $next = '';340    } else {341        print OUT "1;\n";342	queue_includes_from($file) if $opt_a;343    }344}345 346if ($opt_e && (scalar(keys %bad_file) > 0)) {347    warn "Was unable to convert the following files:\n";348    warn "\t" . join("\n\t",sort(keys %bad_file)) . "\n";349}350 351exit $Exit;352 353sub EMIT {354    my $proto = shift;355 356    $new = reindent($new);357    $args = reindent($args);358    $new =~ s/(['\\])/\\$1/g;   #']);359    if ($opt_h) {360        print OUT $t,361                    "eval \"\\n#line $eval_index $outfile\\n\" . 'sub $name $proto\{\n$t    ${args}eval q($new);\n$t}' unless defined(\&$name);\n";362                    $eval_index++;363    } else {364        print OUT $t,365                    "eval 'sub $name $proto\{\n$t    ${args}eval q($new);\n$t}' unless defined(\&$name);\n";366    }367    %curargs = ();368    return;369}370 371sub expr {372    if (/\b__asm__\b/) {	# freak out373	$new = '"(assembly code)"';374	return375    }376    my $joined_args;377    if(keys(%curargs)) {378	$joined_args = join('|', keys(%curargs));379    }380    while ($_ ne '') {381	s/^\&\&// && do { $new .= " &&"; next;}; # handle && operator382	s/^\&([\(a-z\)]+)/$1/i;	# hack for things that take the address of383	s/^(\s+)//		&& do {$new .= ' '; next;};384	s/^0X([0-9A-F]+)[UL]*//i385	    && do {my $hex = $1;386		   $hex =~ s/^0+//;387		   if (length $hex > 8 && !$Config{use64bitint}) {388		       # Croak if nv_preserves_uv_bits < 64 ?389		       $new .=         hex(substr($hex, -8)) +390			       2**32 * hex(substr($hex,  0, -8));391		       # The above will produce "erroneous" code392		       # if the hex constant was e.g. inside UINT64_C393		       # macro, but then again, h2ph is an approximation.394		   } else {395		       $new .= lc("0x$hex");396		   }397		   next;};398	s/^(-?\d+\.\d+E[-+]?\d+)[FL]?//i	&& do {$new .= $1; next;};399	s/^(\d+)\s*[LU]*//i	&& do {$new .= $1; next;};400	s/^("(\\"|[^"])*")//	&& do {$new .= $1; next;};401	s/^'((\\"|[^"])*)'//	&& do {402	    if ($curargs{$1}) {403		$new .= "ord('\$$1')";404	    } else {405		$new .= "ord('$1')";406	    }407	    next;408	};409        # replace "sizeof(foo)" with "{foo}"410        # also, remove * (C dereference operator) to avoid perl syntax411        # problems.  Where the %sizeof array comes from is anyone's412        # guess (c2ph?), but this at least avoids fatal syntax errors.413        # Behavior is undefined if sizeof() delimiters are unbalanced.414        # This code was modified to able to handle constructs like this:415        #   sizeof(*(p)), which appear in the HP-UX 10.01 header files.416        s/^sizeof\s*\(// && do {417            $new .= '$sizeof';418            my $lvl = 1;  # already saw one open paren419            # tack { on the front, and skip it in the loop420            $_ = "{" . "$_";421            my $index = 1;422            # find balanced closing paren423            while ($index <= length($_) && $lvl > 0) {424                $lvl++ if substr($_, $index, 1) eq "(";425                $lvl-- if substr($_, $index, 1) eq ")";426                $index++;427            }428            # tack } on the end, replacing )429            substr($_, $index - 1, 1) = "}";430            # remove pesky * operators within the sizeof argument431            substr($_, 0, $index - 1) =~ s/\*//g;432            next;433        };434	# Eliminate typedefs435	/\(([\w\s]+)[\*\s]*\)\s*[\w\(]/ && do {436	    my $doit = 1;437	    foreach (split /\s+/, $1) {  # Make sure all the words are types,438	        unless($isatype{$_} or $_ eq 'struct' or $_ eq 'union'){439		    $doit = 0;440		    last;441		}442	    }443	    if( $doit ){444		s/\([\w\s]+[\*\s]*\)// && next;      # then eliminate them.445	    }446	};447	# struct/union member, including arrays:448	s/^([_A-Z]\w*(\[[^\]]+\])?((\.|->)[_A-Z]\w*(\[[^\]]+\])?)+)//i && do {449	    my $id = $1;450	    $id =~ s/(\.|(->))([^\.\-]*)/->\{$3\}/g;451	    $id =~ s/\b([^\$])($joined_args)/$1\$$2/g if length($joined_args);452	    while($id =~ /\[\s*([^\$\&\d\]]+)\]/) {453		my($index) = $1;454		$index =~ s/\s//g;455		if(exists($curargs{$index})) {456		    $index = "\$$index";457		} else {458		    $index = "&$index";459		}460		$id =~ s/\[\s*([^\$\&\d\]]+)\]/[$index]/;461	    }462	    $new .= " (\$$id)";463	};464	s/^([_a-zA-Z]\w*)//	&& do {465	    my $id = $1;466	    if ($id eq 'struct' || $id eq 'union') {467		s/^\s+(\w+)//;468		$id .= ' ' . $1;469		$isatype{$id} = 1;470	    } elsif ($id =~ /^((un)?signed)|(long)|(short)$/) {471		while (s/^\s+(\w+)//) { $id .= ' ' . $1; }472		$isatype{$id} = 1;473	    }474	    if ($curargs{$id}) {475		$new .= "\$$id";476		$new .= '->' if /^[\[\{]/;477	    } elsif ($id eq 'defined') {478		$new .= 'defined';479	    } elsif (/^\s*\(/) {480		s/^\s*\((\w),/("$1",/ if $id =~ /^_IO[WR]*$/i;	# cheat481		$new .= " &$id";482	    } elsif ($isatype{$id}) {483		if ($new =~ /\{\s*$/) {484		    $new .= "'$id'";485		} elsif ($new =~ /\(\s*$/ && /^[\s*]*\)/) {486		    $new =~ s/\(\s*$//;487		    s/^[\s*]*\)//;488		} else {489		    $new .= q(').$id.q(');490		}491	    } else {492		if ($inif) {493		    if ($new =~ /defined\s*$/) {494			$new .= '(&' . $id . ')';495		    } elsif ($new =~ /defined\s*\($/) {496			$new .= '&' . $id;497		    } else {498			$new .= '(defined(&' . $id . ') ? &' . $id . ' : undef)';499		    }500		} elsif (/^\[/) {501		    $new .= " \$$id";502		} else {503		    $new .= ' &' . $id;504		}505	    }506	    next;507	};508	s/^(.)// && do { if ($1 ne '#') { $new .= $1; } next;};509    }510}511 512 513sub next_line514{515    my $file = shift;516    my ($in, $out);517    my $pre_sub_tri_graphs = 1;518 519    READ: while (not eof IN) {520        $in  .= <IN>;521        chomp $in;522        next unless length $in;523 524        while (length $in) {525            if ($pre_sub_tri_graphs) {526                # Preprocess all tri-graphs527                # including things stuck in quoted string constants.528                $in =~ s/\?\?=/#/g;                         # | ??=|  #|529                $in =~ s/\?\?\!/|/g;                        # | ??!|  ||530                $in =~ s/\?\?'/^/g;                         # | ??'|  ^|531                $in =~ s/\?\?\(/[/g;                        # | ??(|  [|532                $in =~ s/\?\?\)/]/g;                        # | ??)|  ]|533                $in =~ s/\?\?\-/~/g;                        # | ??-|  ~|534                $in =~ s/\?\?\//\\/g;                       # | ??/|  \|535                $in =~ s/\?\?</{/g;                         # | ??<|  {|536                $in =~ s/\?\?>/}/g;                         # | ??>|  }|537            }538	    if ($in =~ /^\#ifdef __LANGUAGE_PASCAL__/) {539		# Tru64 disassembler.h evilness: mixed C and Pascal.540		while (<IN>) {541		    last if /^\#endif/;542		}543		$in = "";544		next READ;545	    }546	    if ($in =~ /^extern inline / && # Inlined assembler.547		$^O eq 'linux' && $file =~ m!(?:^|/)asm/[^/]+\.h$!) {548		while (<IN>) {549		    last if /^}/;550		}551		$in = "";552		next READ;553	    }554            if ($in =~ s/\\$//) {                           # \-newline555                $out    .= ' ';556                next READ;557            } elsif ($in =~ s/^([^"'\\\/]+)//) {            # Passthrough558                $out    .= $1;559            } elsif ($in =~ s/^(\\.)//) {                   # \...560                $out    .= $1;561            } elsif ($in =~ /^'/) {                         # '...562                if ($in =~ s/^('(\\.|[^'\\])*')//) {563                    $out    .= $1;564                } else {565                    next READ;566                }567            } elsif ($in =~ /^"/) {                         # "...568                if ($in =~ s/^("(\\.|[^"\\])*")//) {569                    $out    .= $1;570                } else {571                    next READ;572                }573            } elsif ($in =~ s/^\/\/.*//) {                  # //...574                # fall through575            } elsif ($in =~ m/^\/\*/) {                     # /*...576                # C comment removal adapted from perlfaq6:577                if ($in =~ s/^\/\*[^*]*\*+([^\/*][^*]*\*+)*\///) {578                    $out    .= ' ';579                } else {                                    # Incomplete /* */580                    next READ;581                }582            } elsif ($in =~ s/^(\/)//) {                    # /...583                $out    .= $1;584            } elsif ($in =~ s/^([^\'\"\\\/]+)//) {585                $out    .= $1;586            } elsif ($^O eq 'linux' &&587                     $file =~ m!(?:^|/)linux/byteorder/pdp_endian\.h$! &&588                     $in   =~ s!\'T KNOW!!) {589                $out    =~ s!I DON$!I_DO_NOT_KNOW!;590            } else {591                if ($opt_e) {592                    warn "Cannot parse $file:\n$in\n";593                    $bad_file{$file} = 1;594                    $in = '';595                    $out = undef;596                    last READ;597                } else {598		die "Cannot parse:\n$in\n";599                }600            }601        }602 603        last READ if $out =~ /\S/;604    }605 606    return $out;607}608 609 610# Handle recursive subdirectories without getting a grotesquely big stack.611# Could this be implemented using File::Find?612sub next_file613{614    my $file;615 616    while (@ARGV) {617        $file = shift @ARGV;618 619        if ($file eq '-' or -f $file or -l $file) {620            return $file;621        } elsif (-d $file) {622            if ($opt_r) {623                expand_glob($file);624            } else {625                print STDERR "Skipping directory '$file'\n";626            }627        } elsif ($opt_a) {628            return $file;629        } else {630            print STDERR "Skipping '$file':  not a file or directory\n";631        }632    }633 634    return undef;635}636 637 638# Put all the files in $directory into @ARGV for processing.639sub expand_glob640{641    my ($directory)  = @_;642 643    $directory =~ s:/$::;644 645    opendir DIR, $directory;646        foreach (readdir DIR) {647            next if ($_ eq '.' or $_ eq '..');648 649            # expand_glob() is going to be called until $ARGV[0] isn't a650            # directory; so push directories, and unshift everything else.651            if (-d "$directory/$_") { push    @ARGV, "$directory/$_" }652            else                    { unshift @ARGV, "$directory/$_" }653        }654    closedir DIR;655}656 657 658# Given $file, a symbolic link to a directory in the C include directory,659# make an equivalent symbolic link in $Dest_dir, if we can figure out how.660# Otherwise, just duplicate the file or directory.661sub link_if_possible662{663    my ($dirlink)  = @_;664    my $target  = eval 'readlink($dirlink)';665 666    if ($target =~ m:^\.\./: or $target =~ m:^/:) {667        # The target of a parent or absolute link could leave the $Dest_dir668        # hierarchy, so let's put all of the contents of $dirlink (actually,669        # the contents of $target) into @ARGV; as a side effect down the670        # line, $dirlink will get created as an _actual_ directory.671        expand_glob($dirlink);672    } else {673        if (-l "$Dest_dir/$dirlink") {674            unlink "$Dest_dir/$dirlink" or675                print STDERR "Could not remove link $Dest_dir/$dirlink:  $!\n";676        }677 678        if (eval 'symlink($target, "$Dest_dir/$dirlink")') {679            print "Linking $target -> $Dest_dir/$dirlink\n";680 681            # Make sure that the link _links_ to something:682            if (! -e "$Dest_dir/$target") {683                mkpath("$Dest_dir/$target", 0755) or684                    print STDERR "Could not create $Dest_dir/$target/\n";685            }686        } else {687            print STDERR "Could not symlink $target -> $Dest_dir/$dirlink:  $!\n";688        }689    }690}691 692 693# Push all #included files in $file onto our stack, except for STDIN694# and files we've already processed.695sub queue_includes_from696{697    my ($file)    = @_;698    my $line;699 700    return if ($file eq "-");701 702    open HEADER, "<", $file or return;703        while (defined($line = <HEADER>)) {704            while (/\\$/) { # Handle continuation lines705                chop $line;706                $line .= <HEADER>;707            }708 709            if ($line =~ /^#\s*include\s+([<"])(.*?)[>"]/) {710                my ($delimiter, $new_file) = ($1, $2);711                # copy the prefix in the quote syntax (#include "x.h") case712                if ($delimiter eq q{"} && $file =~ m|^(.*)/|) {713                    $new_file = "$1/$new_file";714                }715                push(@ARGV, $new_file) unless $Is_converted{$new_file};716            }717        }718    close HEADER;719}720 721 722# Determine include directories; $Config{usrinc} should be enough for (all723# non-GCC?) C compilers, but gcc uses additional include directories.724sub inc_dirs725{726    my $from_gcc   = `LC_ALL=C $Config{cc} -v -E - < /dev/null 2>&1 | awk '/^#include/, /^End of search list/' | grep '^ '`;727    length($from_gcc) ? (split(' ', $from_gcc), $Config{usrinc}) : ($Config{usrinc});728}729 730 731# Create "_h2ph_pre.ph", if it doesn't exist or was built by a different732# version of h2ph.733sub build_preamble_if_necessary734{735    # Increment $VERSION every time this function is modified:736    my $VERSION     = 5;737    my $preamble    = "$Dest_dir/_h2ph_pre.ph";738 739    # Can we skip building the preamble file?740    if (-r $preamble) {741        # Extract version number from first line of preamble:742        open  PREAMBLE, "<", $preamble or die "Cannot open $preamble:  $!";743            my $line = <PREAMBLE>;744            $line =~ /(\b\d+\b)/;745        close PREAMBLE            or die "Cannot close $preamble:  $!";746 747        # Don't build preamble if a compatible preamble exists:748        return if $1 == $VERSION;749    }750 751    my (%define) = _extract_cc_defines();752 753    open  PREAMBLE, ">", $preamble or die "Cannot open $preamble:  $!";754	print PREAMBLE "# This file was created by h2ph version $VERSION\n";755        # Prevent non-portable hex constants from warning.756        #757        # We still produce an overflow warning if we can't represent758        # a hex constant as an integer.759        print PREAMBLE "no warnings qw(portable);\n";760 761	foreach (sort keys %define) {762	    if ($opt_D) {763		print PREAMBLE "# $_=$define{$_}\n";764	    }765	    if ($define{$_} =~ /^\((.*)\)$/) {766		# parenthesized value:  d=(v)767		$define{$_} = $1;768	    }769	    if (/^(\w+)\((\w)\)$/) {770		my($macro, $arg) = ($1, $2);771		my $def = $define{$_};772		$def =~ s/$arg/\$\{$arg\}/g;773		print PREAMBLE <<DEFINE;774sub $macro(\$) { my (\$$arg) = \@_; \"$def\" }775 776DEFINE777	    } elsif778		($define{$_} =~ /^([+-]?(\d+)?\.\d+([eE][+-]?\d+)?)[FL]?$/) {779		# float:780		print PREAMBLE "sub $_() { $1 }\n\n";781	    } elsif ($define{$_} =~ /^([+-]?\d+)U?L{0,2}$/i) {782		# integer:783		print PREAMBLE "sub $_() { $1 }\n\n";784            } elsif ($define{$_} =~ /^([+-]?0x[\da-f]+)U?L{0,2}$/i) {785                # hex integer786                # Special cased, since perl warns on hex integers787                # that can't be represented in a UV.788                #789                # This way we get the warning at time of use, so the user790                # only gets the warning if they happen to use this791                # platform-specific definition.792                my $code = $1;793                $code = "hex('$code')" if length $code > 10;794                print PREAMBLE "sub $_() { $code }\n\n";795	    } elsif ($define{$_} =~ /^\w+$/) {796		my $def = $define{$_};797		if ($isatype{$def}) {798		  print PREAMBLE "sub $_() { \"$def\" }\n\n";799		} else {800		  print PREAMBLE "sub $_() { &$def }\n\n";801	        }802	    } else {803		print PREAMBLE "sub $_() { \"\Q$define{$_}\E\" }\n\n";804	    }805	}806	print PREAMBLE "\n1;\n";  # avoid 'did not return a true value' when empty807    close PREAMBLE               or die "Cannot close $preamble:  $!";808}809 810 811# %Config contains information on macros that are pre-defined by the812# system's compiler.  We need this information to make the .ph files813# function with perl as the .h files do with cc.814sub _extract_cc_defines815{816    my %define;817    my $allsymbols  = join " ",818	@Config{'ccsymbols', 'cppsymbols', 'cppccsymbols'};819 820    # Split compiler pre-definitions into 'key=value' pairs:821    while ($allsymbols =~ /([^\s]+)=((\\\s|[^\s])+)/g) {822	$define{$1} = $2;823	if ($opt_D) {824	    print STDERR "$_:  $1 -> $2\n";825	}826    }827 828    return %define;829}830 831 8321;833 834##############################################################################835__END__836 837=head1 NAME838 839h2ph - convert .h C header files to .ph Perl header files840 841=head1 SYNOPSIS842 843B<h2ph [-d destination directory] [-r | -a] [-l] [-h] [-e] [-D] [-Q]844[headerfiles]>845 846=head1 DESCRIPTION847 848I<h2ph>849converts any C header files specified to the corresponding Perl header file850format.851It is most easily run while in /usr/include:852 853	cd /usr/include; h2ph * sys/*854 855or856 857	cd /usr/include; h2ph * sys/* arpa/* netinet/*858 859or860 861	cd /usr/include; h2ph -r -l .862 863The output files are placed in the hierarchy rooted at Perl's864architecture dependent library directory.  You can specify a different865hierarchy with a B<-d> switch.866 867If run with no arguments, filters standard input to standard output.868 869=head1 OPTIONS870 871=over 4872 873=item -d destination_dir874 875Put the resulting B<.ph> files beneath B<destination_dir>, instead of876beneath the default Perl library location (C<$Config{'installsitearch'}>).877 878=item -r879 880Run recursively; if any of B<headerfiles> are directories, then run I<h2ph>881on all files in those directories (and their subdirectories, etc.).  B<-r>882and B<-a> are mutually exclusive.883 884=item -a885 886Run automagically; convert B<headerfiles>, as well as any B<.h> files887which they include.  This option will search for B<.h> files in all888directories which your C compiler ordinarily uses.  B<-a> and B<-r> are889mutually exclusive.890 891=item -l892 893Symbolic links will be replicated in the destination directory.  If B<-l>894is not specified, then links are skipped over.895 896=item -h897 898Put 'hints' in the .ph files which will help in locating problems with899I<h2ph>.  In those cases when you B<require> a B<.ph> file containing syntax900errors, instead of the cryptic901 902	[ some error condition ] at (eval mmm) line nnn903 904you will see the slightly more helpful905 906	[ some error condition ] at filename.ph line nnn907 908However, the B<.ph> files almost double in size when built using B<-h>.909 910=item -e911 912If an error is encountered during conversion, output file will be removed and913a warning emitted instead of terminating the conversion immediately.914 915=item -D916 917Include the code from the B<.h> file as a comment in the B<.ph> file.918This is primarily used for debugging I<h2ph>.919 920=item -Q921 922'Quiet' mode; don't print out the names of the files being converted.923 924=back925 926=head1 ENVIRONMENT927 928No environment variables are used.929 930=head1 FILES931 932 /usr/include/*.h933 /usr/include/sys/*.h934 935etc.936 937=head1 AUTHOR938 939Larry Wall940 941=head1 SEE ALSO942 943perl(1)944 945=head1 DIAGNOSTICS946 947The usual warnings if it can't read or write the files involved.948 949=head1 BUGS950 951Doesn't construct the %sizeof array for you.952 953It doesn't handle all C constructs, but it does attempt to isolate954definitions inside evals so that you can get at the definitions955that it can translate.956 957It's only intended as a rough tool.958You may need to dicker with the files produced.959 960You have to run this program by hand; it's not run as part of the Perl961installation.962 963Doesn't handle complicated expressions built piecemeal, a la:964 965    enum {966	FIRST_VALUE,967	SECOND_VALUE,968    #ifdef ABC969	THIRD_VALUE970    #endif971    };972 973Doesn't necessarily locate all of your C compiler's internally-defined974symbols.975 976=cut977 978 
codekingpro/portable-devtools · Team Ai