Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1858 lines
48 KiB

  1. @rem = '--*-Perl-*--
  2. @echo off
  3. if "%OS%" == "Windows_NT" goto WinNT
  4. perl -x -S "%0" %1 %2 %3 %4 %5 %6 %7 %8 %9
  5. goto endofperl
  6. :WinNT
  7. perl -x -S %0 %*
  8. if NOT "%COMSPEC%" == "%SystemRoot%\system32\cmd.exe" goto endofperl
  9. if %errorlevel% == 9009 echo You do not have Perl in your PATH.
  10. if errorlevel 1 goto script_failed_so_exit_with_non_zero_val 2>nul
  11. goto endofperl
  12. @rem ';
  13. #!perl
  14. #line 15
  15. eval 'exec C:\Perl\bin\perl.exe -S $0 ${1+"$@"}'
  16. if $running_under_some_shell;
  17. =head1 NAME
  18. h2xs - convert .h C header files to Perl extensions
  19. =head1 SYNOPSIS
  20. B<h2xs> [B<-ACOPXacdfkmx>] [B<-F> addflags] [B<-M> fmask] [B<-n> module_name] [B<-o> tmask] [B<-p> prefix] [B<-s> subs] [B<-v> version] [headerfile ... [extra_libraries]]
  21. B<h2xs> B<-h>
  22. =head1 DESCRIPTION
  23. I<h2xs> builds a Perl extension from C header files. The extension
  24. will include functions which can be used to retrieve the value of any
  25. #define statement which was in the C header files.
  26. The I<module_name> will be used for the name of the extension. If
  27. module_name is not supplied then the name of the first header file
  28. will be used, with the first character capitalized.
  29. If the extension might need extra libraries, they should be included
  30. here. The extension Makefile.PL will take care of checking whether
  31. the libraries actually exist and how they should be loaded.
  32. The extra libraries should be specified in the form -lm -lposix, etc,
  33. just as on the cc command line. By default, the Makefile.PL will
  34. search through the library path determined by Configure. That path
  35. can be augmented by including arguments of the form B<-L/another/library/path>
  36. in the extra-libraries argument.
  37. =head1 OPTIONS
  38. =over 5
  39. =item B<-A>
  40. Omit all autoload facilities. This is the same as B<-c> but also removes the
  41. S<C<use AutoLoader>> statement from the .pm file.
  42. =item B<-C>
  43. Omits creation of the F<Changes> file, and adds a HISTORY section to
  44. the POD template.
  45. =item B<-F> I<addflags>
  46. Additional flags to specify to C preprocessor when scanning header for
  47. function declarations. Should not be used without B<-x>.
  48. =item B<-M> I<regular expression>
  49. selects functions/macros to process.
  50. =item B<-O>
  51. Allows a pre-existing extension directory to be overwritten.
  52. =item B<-P>
  53. Omit the autogenerated stub POD section.
  54. =item B<-X>
  55. Omit the XS portion. Used to generate templates for a module which is not
  56. XS-based. C<-c> and C<-f> are implicitly enabled.
  57. =item B<-a>
  58. Generate an accessor method for each element of structs and unions. The
  59. generated methods are named after the element name; will return the current
  60. value of the element if called without additional arguments; and will set
  61. the element to the supplied value (and return the new value) if called with
  62. an additional argument. Embedded structures and unions are returned as a
  63. pointer rather than the complete structure, to facilitate chained calls.
  64. These methods all apply to the Ptr type for the structure; additionally
  65. two methods are constructed for the structure type itself, C<_to_ptr>
  66. which returns a Ptr type pointing to the same structure, and a C<new>
  67. method to construct and return a new structure, initialised to zeroes.
  68. =item B<-c>
  69. Omit C<constant()> from the .xs file and corresponding specialised
  70. C<AUTOLOAD> from the .pm file.
  71. =item B<-d>
  72. Turn on debugging messages.
  73. =item B<-f>
  74. Allows an extension to be created for a header even if that header is
  75. not found in standard include directories.
  76. =item B<-h>
  77. Print the usage, help and version for this h2xs and exit.
  78. =item B<-k>
  79. For function arguments declared as C<const>, omit the const attribute in the
  80. generated XS code.
  81. =item B<-m>
  82. B<Experimental>: for each variable declared in the header file(s), declare
  83. a perl variable of the same name magically tied to the C variable.
  84. =item B<-n> I<module_name>
  85. Specifies a name to be used for the extension, e.g., S<-n RPC::DCE>
  86. =item B<-o> I<regular expression>
  87. Use "opaque" data type for the C types matched by the regular
  88. expression, even if these types are C<typedef>-equivalent to types
  89. from typemaps. Should not be used without B<-x>.
  90. This may be useful since, say, types which are C<typedef>-equivalent
  91. to integers may represent OS-related handles, and one may want to work
  92. with these handles in OO-way, as in C<$handle-E<gt>do_something()>.
  93. Use C<-o .> if you want to handle all the C<typedef>ed types as opaque types.
  94. The type-to-match is whitewashed (except for commas, which have no
  95. whitespace before them, and multiple C<*> which have no whitespace
  96. between them).
  97. =item B<-p> I<prefix>
  98. Specify a prefix which should be removed from the Perl function names, e.g., S<-p sec_rgy_>
  99. This sets up the XS B<PREFIX> keyword and removes the prefix from functions that are
  100. autoloaded via the C<constant()> mechanism.
  101. =item B<-s> I<sub1,sub2>
  102. Create a perl subroutine for the specified macros rather than autoload with the constant() subroutine.
  103. These macros are assumed to have a return type of B<char *>, e.g., S<-s sec_rgy_wildcard_name,sec_rgy_wildcard_sid>.
  104. =item B<-v> I<version>
  105. Specify a version number for this extension. This version number is added
  106. to the templates. The default is 0.01.
  107. =item B<-x>
  108. Automatically generate XSUBs basing on function declarations in the
  109. header file. The package C<C::Scan> should be installed. If this
  110. option is specified, the name of the header file may look like
  111. C<NAME1,NAME2>. In this case NAME1 is used instead of the specified string,
  112. but XSUBs are emitted only for the declarations included from file NAME2.
  113. Note that some types of arguments/return-values for functions may
  114. result in XSUB-declarations/typemap-entries which need
  115. hand-editing. Such may be objects which cannot be converted from/to a
  116. pointer (like C<long long>), pointers to functions, or arrays. See
  117. also the section on L<LIMITATIONS of B<-x>>.
  118. =item B<-b> I<version>
  119. Generates a .pm file which is backwards compatible with the specified
  120. perl version.
  121. For versions < 5.6.0, the changes are.
  122. - no use of 'our' (uses 'use vars' instead)
  123. - no 'use warnings'
  124. Specifying a compatibility version higher than the version of perl you
  125. are using to run h2xs will have no effect.
  126. =back
  127. =head1 EXAMPLES
  128. # Default behavior, extension is Rusers
  129. h2xs rpcsvc/rusers
  130. # Same, but extension is RUSERS
  131. h2xs -n RUSERS rpcsvc/rusers
  132. # Extension is rpcsvc::rusers. Still finds <rpcsvc/rusers.h>
  133. h2xs rpcsvc::rusers
  134. # Extension is ONC::RPC. Still finds <rpcsvc/rusers.h>
  135. h2xs -n ONC::RPC rpcsvc/rusers
  136. # Without constant() or AUTOLOAD
  137. h2xs -c rpcsvc/rusers
  138. # Creates templates for an extension named RPC
  139. h2xs -cfn RPC
  140. # Extension is ONC::RPC.
  141. h2xs -cfn ONC::RPC
  142. # Makefile.PL will look for library -lrpc in
  143. # additional directory /opt/net/lib
  144. h2xs rpcsvc/rusers -L/opt/net/lib -lrpc
  145. # Extension is DCE::rgynbase
  146. # prefix "sec_rgy_" is dropped from perl function names
  147. h2xs -n DCE::rgynbase -p sec_rgy_ dce/rgynbase
  148. # Extension is DCE::rgynbase
  149. # prefix "sec_rgy_" is dropped from perl function names
  150. # subroutines are created for sec_rgy_wildcard_name and sec_rgy_wildcard_sid
  151. h2xs -n DCE::rgynbase -p sec_rgy_ \
  152. -s sec_rgy_wildcard_name,sec_rgy_wildcard_sid dce/rgynbase
  153. # Make XS without defines in perl.h, but with function declarations
  154. # visible from perl.h. Name of the extension is perl1.
  155. # When scanning perl.h, define -DEXT=extern -DdEXT= -DINIT(x)=
  156. # Extra backslashes below because the string is passed to shell.
  157. # Note that a directory with perl header files would
  158. # be added automatically to include path.
  159. h2xs -xAn perl1 -F "-DEXT=extern -DdEXT= -DINIT\(x\)=" perl.h
  160. # Same with function declaration in proto.h as visible from perl.h.
  161. h2xs -xAn perl2 perl.h,proto.h
  162. # Same but select only functions which match /^av_/
  163. h2xs -M '^av_' -xAn perl2 perl.h,proto.h
  164. # Same but treat SV* etc as "opaque" types
  165. h2xs -o '^[S]V \*$' -M '^av_' -xAn perl2 perl.h,proto.h
  166. =head2 Extension based on F<.h> and F<.c> files
  167. Suppose that you have some C files implementing some functionality,
  168. and the corresponding header files. How to create an extension which
  169. makes this functionality accessable in Perl? The example below
  170. assumes that the header files are F<interface_simple.h> and
  171. I<interface_hairy.h>, and you want the perl module be named as
  172. C<Ext::Ension>. If you need some preprocessor directives and/or
  173. linking with external libraries, see the flags C<-F>, C<-L> and C<-l>
  174. in L<"OPTIONS">.
  175. =over
  176. =item Find the directory name
  177. Start with a dummy run of h2xs:
  178. h2xs -Afn Ext::Ension
  179. The only purpose of this step is to create the needed directories, and
  180. let you know the names of these directories. From the output you can
  181. see that the directory for the extension is F<Ext/Ension>.
  182. =item Copy C files
  183. Copy your header files and C files to this directory F<Ext/Ension>.
  184. =item Create the extension
  185. Run h2xs, overwriting older autogenerated files:
  186. h2xs -Oxan Ext::Ension interface_simple.h interface_hairy.h
  187. h2xs looks for header files I<after> changing to the extension
  188. directory, so it will find your header files OK.
  189. =item Archive and test
  190. As usual, run
  191. cd Ext/Ension
  192. perl Makefile.PL
  193. make dist
  194. make
  195. make test
  196. =item Hints
  197. It is important to do C<make dist> as early as possible. This way you
  198. can easily merge(1) your changes to autogenerated files if you decide
  199. to edit your C<.h> files and rerun h2xs.
  200. Do not forget to edit the documentation in the generated F<.pm> file.
  201. Consider the autogenerated files as skeletons only, you may invent
  202. better interfaces than what h2xs could guess.
  203. Consider this section as a guideline only, some other options of h2xs
  204. may better suit your needs.
  205. =back
  206. =head1 ENVIRONMENT
  207. No environment variables are used.
  208. =head1 AUTHOR
  209. Larry Wall and others
  210. =head1 SEE ALSO
  211. L<perl>, L<perlxstut>, L<ExtUtils::MakeMaker>, and L<AutoLoader>.
  212. =head1 DIAGNOSTICS
  213. The usual warnings if it cannot read or write the files involved.
  214. =head1 LIMITATIONS of B<-x>
  215. F<h2xs> would not distinguish whether an argument to a C function
  216. which is of the form, say, C<int *>, is an input, output, or
  217. input/output parameter. In particular, argument declarations of the
  218. form
  219. int
  220. foo(n)
  221. int *n
  222. should be better rewritten as
  223. int
  224. foo(n)
  225. int &n
  226. if C<n> is an input parameter.
  227. Additionally, F<h2xs> has no facilities to intuit that a function
  228. int
  229. foo(addr,l)
  230. char *addr
  231. int l
  232. takes a pair of address and length of data at this address, so it is better
  233. to rewrite this function as
  234. int
  235. foo(sv)
  236. SV *addr
  237. PREINIT:
  238. STRLEN len;
  239. char *s;
  240. CODE:
  241. s = SvPV(sv,len);
  242. RETVAL = foo(s, len);
  243. OUTPUT:
  244. RETVAL
  245. or alternately
  246. static int
  247. my_foo(SV *sv)
  248. {
  249. STRLEN len;
  250. char *s = SvPV(sv,len);
  251. return foo(s, len);
  252. }
  253. MODULE = foo PACKAGE = foo PREFIX = my_
  254. int
  255. foo(sv)
  256. SV *sv
  257. See L<perlxs> and L<perlxstut> for additional details.
  258. =cut
  259. use strict;
  260. my( $H2XS_VERSION ) = ' $Revision: 1.21 $ ' =~ /\$Revision:\s+([^\s]+)/;
  261. my $TEMPLATE_VERSION = '0.01';
  262. my @ARGS = @ARGV;
  263. my $compat_version = $];
  264. use Getopt::Std;
  265. sub usage{
  266. warn "@_\n" if @_;
  267. die "h2xs [-ACOPXacdfhkmx] [-F addflags] [-M fmask] [-n module_name] [-o tmask] [-p prefix] [-s subs] [-v version] [headerfile [extra_libraries]]
  268. version: $H2XS_VERSION
  269. -A Omit all autoloading facilities (implies -c).
  270. -C Omit creating the Changes file, add HISTORY heading to stub POD.
  271. -F Additional flags for C preprocessor (used with -x).
  272. -M Mask to select C functions/macros (default is select all).
  273. -O Allow overwriting of a pre-existing extension directory.
  274. -P Omit the stub POD section.
  275. -X Omit the XS portion (implies both -c and -f).
  276. -a Generate get/set accessors for struct and union members (used with -x).
  277. -c Omit the constant() function and specialised AUTOLOAD from the XS file.
  278. -d Turn on debugging messages.
  279. -f Force creation of the extension even if the C header does not exist.
  280. -h Display this help message
  281. -k Omit 'const' attribute on function arguments (used with -x).
  282. -m Generate tied variables for access to declared variables.
  283. -n Specify a name to use for the extension (recommended).
  284. -o Regular expression for \"opaque\" types.
  285. -p Specify a prefix which should be removed from the Perl function names.
  286. -s Create subroutines for specified macros.
  287. -v Specify a version number for this extension.
  288. -x Autogenerate XSUBs using C::Scan.
  289. -b Specify a perl version to be backwards compatibile with
  290. extra_libraries
  291. are any libraries that might be needed for loading the
  292. extension, e.g. -lm would try to link in the math library.
  293. ";
  294. }
  295. getopts("ACF:M:OPXacdfhkmn:o:p:s:v:xb:") || usage;
  296. use vars qw($opt_A $opt_C $opt_F $opt_M $opt_O $opt_P $opt_X $opt_a $opt_c $opt_d
  297. $opt_f $opt_h $opt_k $opt_m $opt_n $opt_o $opt_p $opt_s $opt_v $opt_x
  298. $opt_b);
  299. usage if $opt_h;
  300. if( $opt_b ){
  301. usage "You cannot use -b and -m at the same time.\n" if ($opt_b && $opt_m);
  302. $opt_b =~ /^\d+\.\d+\.\d+/ ||
  303. usage "You must provide the backwards compatibility version in X.Y.Z form. " .
  304. "(i.e. 5.5.0)\n";
  305. my ($maj,$min,$sub) = split(/\./,$opt_b,3);
  306. $compat_version = sprintf("%d.%03d%02d",$maj,$min,$sub);
  307. }
  308. if( $opt_v ){
  309. $TEMPLATE_VERSION = $opt_v;
  310. }
  311. # -A implies -c.
  312. $opt_c = 1 if $opt_A;
  313. # -X implies -c and -f
  314. $opt_c = $opt_f = 1 if $opt_X;
  315. my %const_xsub = map { $_,1 } split(/,+/, $opt_s) if $opt_s;
  316. my $extralibs;
  317. my @path_h;
  318. while (my $arg = shift) {
  319. if ($arg =~ /^-l/i) {
  320. $extralibs = "$arg @ARGV";
  321. last;
  322. }
  323. push(@path_h, $arg);
  324. }
  325. usage "Must supply header file or module name\n"
  326. unless (@path_h or $opt_n);
  327. my $fmask;
  328. my $tmask;
  329. $fmask = qr{$opt_M} if defined $opt_M;
  330. $tmask = qr{$opt_o} if defined $opt_o;
  331. my $tmask_all = $tmask && $opt_o eq '.';
  332. if ($opt_x) {
  333. eval {require C::Scan; 1}
  334. or die <<EOD;
  335. C::Scan required if you use -x option.
  336. To install C::Scan, execute
  337. perl -MCPAN -e "install C::Scan"
  338. EOD
  339. unless ($tmask_all) {
  340. $C::Scan::VERSION >= 0.70
  341. or die <<EOD;
  342. C::Scan v. 0.70 or later required unless you use -o . option.
  343. You have version $C::Scan::VERSION installed as $INC{'C/Scan.pm'}.
  344. To install C::Scan, execute
  345. perl -MCPAN -e "install C::Scan"
  346. EOD
  347. }
  348. if (($opt_m || $opt_a) && $C::Scan::VERSION < 0.73) {
  349. die <<EOD;
  350. C::Scan v. 0.73 or later required to use -m or -a options.
  351. You have version $C::Scan::VERSION installed as $INC{'C/Scan.pm'}.
  352. To install C::Scan, execute
  353. perl -MCPAN -e "install C::Scan"
  354. EOD
  355. }
  356. }
  357. elsif ($opt_o or $opt_F) {
  358. warn <<EOD;
  359. Options -o and -F do not make sense without -x.
  360. EOD
  361. }
  362. my @path_h_ini = @path_h;
  363. my ($name, %fullpath, %prefix, %seen_define, %prefixless, %const_names);
  364. my $module = $opt_n;
  365. if( @path_h ){
  366. use Config;
  367. use File::Spec;
  368. my @paths;
  369. if ($^O eq 'VMS') { # Consider overrides of default location
  370. # XXXX This is not equivalent to what the older version did:
  371. # it was looking at $hadsys header-file per header-file...
  372. my($hadsys) = grep s!^sys/!!i , @path_h;
  373. @paths = qw( Sys$Library VAXC$Include );
  374. push @paths, ($hadsys ? 'GNU_CC_Include[vms]' : 'GNU_CC_Include[000000]');
  375. push @paths, qw( DECC$Library_Include DECC$System_Include );
  376. }
  377. else {
  378. @paths = (File::Spec->curdir(), $Config{usrinc},
  379. (split ' ', $Config{locincpth}), '/usr/include');
  380. }
  381. foreach my $path_h (@path_h) {
  382. $name ||= $path_h;
  383. $module ||= do {
  384. $name =~ s/\.h$//;
  385. if ( $name !~ /::/ ) {
  386. $name =~ s#^.*/##;
  387. $name = "\u$name";
  388. }
  389. $name;
  390. };
  391. if( $path_h =~ s#::#/#g && $opt_n ){
  392. warn "Nesting of headerfile ignored with -n\n";
  393. }
  394. $path_h .= ".h" unless $path_h =~ /\.h$/;
  395. my $fullpath = $path_h;
  396. $path_h =~ s/,.*$// if $opt_x;
  397. $fullpath{$path_h} = $fullpath;
  398. # Minor trickery: we can't chdir() before we processed the headers
  399. # (so know the name of the extension), but the header may be in the
  400. # extension directory...
  401. my $tmp_path_h = $path_h;
  402. my $rel_path_h = $path_h;
  403. my @dirs = @paths;
  404. if (not -f $path_h) {
  405. my $found;
  406. for my $dir (@paths) {
  407. $found++, last
  408. if -f ($path_h = File::Spec->catfile($dir, $tmp_path_h));
  409. }
  410. if ($found) {
  411. $rel_path_h = $path_h;
  412. } else {
  413. (my $epath = $module) =~ s,::,/,g;
  414. $epath = File::Spec->catdir('ext', $epath) if -d 'ext';
  415. $rel_path_h = File::Spec->catfile($epath, $tmp_path_h);
  416. $path_h = $tmp_path_h; # Used during -x
  417. push @dirs, $epath;
  418. }
  419. }
  420. if (!$opt_c) {
  421. die "Can't find $tmp_path_h in @dirs\n"
  422. if ( ! $opt_f && ! -f "$rel_path_h" );
  423. # Scan the header file (we should deal with nested header files)
  424. # Record the names of simple #define constants into const_names
  425. # Function prototypes are processed below.
  426. open(CH, "<$rel_path_h") || die "Can't open $rel_path_h: $!\n";
  427. defines:
  428. while (<CH>) {
  429. if (/^[ \t]*#[ \t]*define\s+([\$\w]+)\b(?!\()\s*(?=[^" \t])(.*)/) {
  430. my $def = $1;
  431. my $rest = $2;
  432. $rest =~ s!/\*.*?(\*/|\n)|//.*!!g; # Remove comments
  433. $rest =~ s/^\s+//;
  434. $rest =~ s/\s+$//;
  435. # Cannot do: (-1) and ((LHANDLE)3) are OK:
  436. #print("Skip non-wordy $def => $rest\n"),
  437. # next defines if $rest =~ /[^\w\$]/;
  438. if ($rest =~ /"/) {
  439. print("Skip stringy $def => $rest\n") if $opt_d;
  440. next defines;
  441. }
  442. print "Matched $_ ($def)\n" if $opt_d;
  443. $seen_define{$def} = $rest;
  444. $_ = $def;
  445. next if /^_.*_h_*$/i; # special case, but for what?
  446. if (defined $opt_p) {
  447. if (!/^$opt_p(\d)/) {
  448. ++$prefix{$_} if s/^$opt_p//;
  449. }
  450. else {
  451. warn "can't remove $opt_p prefix from '$_'!\n";
  452. }
  453. }
  454. $prefixless{$def} = $_;
  455. if (!$fmask or /$fmask/) {
  456. print "... Passes mask of -M.\n" if $opt_d and $fmask;
  457. $const_names{$_}++;
  458. }
  459. }
  460. }
  461. close(CH);
  462. }
  463. }
  464. }
  465. my ($ext, $nested, @modparts, $modfname, $modpname);
  466. (chdir 'ext', $ext = 'ext/') if -d 'ext';
  467. if( $module =~ /::/ ){
  468. $nested = 1;
  469. @modparts = split(/::/,$module);
  470. $modfname = $modparts[-1];
  471. $modpname = join('/',@modparts);
  472. }
  473. else {
  474. $nested = 0;
  475. @modparts = ();
  476. $modfname = $modpname = $module;
  477. }
  478. if ($opt_O) {
  479. warn "Overwriting existing $ext$modpname!!!\n" if -e $modpname;
  480. }
  481. else {
  482. die "Won't overwrite existing $ext$modpname\n" if -e $modpname;
  483. }
  484. if( $nested ){
  485. my $modpath = "";
  486. foreach (@modparts){
  487. mkdir("$modpath$_", 0777);
  488. $modpath .= "$_/";
  489. }
  490. }
  491. mkdir($modpname, 0777);
  492. chdir($modpname) || die "Can't chdir $ext$modpname: $!\n";
  493. my %types_seen;
  494. my %std_types;
  495. my $fdecls = [];
  496. my $fdecls_parsed = [];
  497. my $typedef_rex;
  498. my %typedefs_pre;
  499. my %known_fnames;
  500. my %structs;
  501. my @fnames;
  502. my @fnames_no_prefix;
  503. my %vdecl_hash;
  504. my @vdecls;
  505. if( ! $opt_X ){ # use XS, unless it was disabled
  506. open(XS, ">$modfname.xs") || die "Can't create $ext$modpname/$modfname.xs: $!\n";
  507. if ($opt_x) {
  508. require Config; # Run-time directive
  509. warn "Scanning typemaps...\n";
  510. get_typemap();
  511. my @td;
  512. my @good_td;
  513. my $addflags = $opt_F || '';
  514. foreach my $filename (@path_h) {
  515. my $c;
  516. my $filter;
  517. if ($fullpath{$filename} =~ /,/) {
  518. $filename = $`;
  519. $filter = $';
  520. }
  521. warn "Scanning $filename for functions...\n";
  522. $c = new C::Scan 'filename' => $filename, 'filename_filter' => $filter,
  523. 'add_cppflags' => $addflags, 'c_styles' => [qw(C++ C9X)];
  524. $c->set('includeDirs' => ["$Config::Config{archlib}/CORE"]);
  525. push @$fdecls_parsed, @{ $c->get('parsed_fdecls') };
  526. push(@$fdecls, @{$c->get('fdecls')});
  527. push @td, @{$c->get('typedefs_maybe')};
  528. if ($opt_a) {
  529. my $structs = $c->get('typedef_structs');
  530. @structs{keys %$structs} = values %$structs;
  531. }
  532. if ($opt_m) {
  533. %vdecl_hash = %{ $c->get('vdecl_hash') };
  534. @vdecls = sort keys %vdecl_hash;
  535. for (local $_ = 0; $_ < @vdecls; ++$_) {
  536. my $var = $vdecls[$_];
  537. my($type, $post) = @{ $vdecl_hash{$var} };
  538. if (defined $post) {
  539. warn "Can't handle variable '$type $var $post', skipping.\n";
  540. splice @vdecls, $_, 1;
  541. redo;
  542. }
  543. $type = normalize_type($type);
  544. $vdecl_hash{$var} = $type;
  545. }
  546. }
  547. unless ($tmask_all) {
  548. warn "Scanning $filename for typedefs...\n";
  549. my $td = $c->get('typedef_hash');
  550. # eval {require 'dumpvar.pl'; ::dumpValue($td)} or warn $@ if $opt_d;
  551. my @f_good_td = grep $td->{$_}[1] eq '', keys %$td;
  552. push @good_td, @f_good_td;
  553. @typedefs_pre{@f_good_td} = map $_->[0], @$td{@f_good_td};
  554. }
  555. }
  556. { local $" = '|';
  557. $typedef_rex = qr(\b(?<!struct )(?:@good_td)\b) if @good_td;
  558. }
  559. %known_fnames = map @$_[1,3], @$fdecls_parsed; # [1,3] is NAME, FULLTEXT
  560. if ($fmask) {
  561. my @good;
  562. for my $i (0..$#$fdecls_parsed) {
  563. next unless $fdecls_parsed->[$i][1] =~ /$fmask/; # [1] is NAME
  564. push @good, $i;
  565. print "... Function $fdecls_parsed->[$i][1] passes -M mask.\n"
  566. if $opt_d;
  567. }
  568. $fdecls = [@$fdecls[@good]];
  569. $fdecls_parsed = [@$fdecls_parsed[@good]];
  570. }
  571. @fnames = sort map $_->[1], @$fdecls_parsed; # 1 is NAME
  572. # Sort declarations:
  573. {
  574. my %h = map( ($_->[1], $_), @$fdecls_parsed);
  575. $fdecls_parsed = [ @h{@fnames} ];
  576. }
  577. @fnames_no_prefix = @fnames;
  578. @fnames_no_prefix
  579. = sort map { ++$prefix{$_} if s/^$opt_p(?!\d)//; $_ } @fnames_no_prefix;
  580. # Remove macros which expand to typedefs
  581. print "Typedefs are @td.\n" if $opt_d;
  582. my %td = map {($_, $_)} @td;
  583. # Add some other possible but meaningless values for macros
  584. for my $k (qw(char double float int long short unsigned signed void)) {
  585. $td{"$_$k"} = "$_$k" for ('', 'signed ', 'unsigned ');
  586. }
  587. # eval {require 'dumpvar.pl'; ::dumpValue( [\@td, \%td] ); 1} or warn $@;
  588. my $n = 0;
  589. my %bad_macs;
  590. while (keys %td > $n) {
  591. $n = keys %td;
  592. my ($k, $v);
  593. while (($k, $v) = each %seen_define) {
  594. # print("found '$k'=>'$v'\n"),
  595. $bad_macs{$k} = $td{$k} = $td{$v} if exists $td{$v};
  596. }
  597. }
  598. # Now %bad_macs contains names of bad macros
  599. for my $k (keys %bad_macs) {
  600. delete $const_names{$prefixless{$k}};
  601. print "Ignoring macro $k which expands to a typedef name '$bad_macs{$k}'\n" if $opt_d;
  602. }
  603. }
  604. }
  605. my @const_names = sort keys %const_names;
  606. open(PM, ">$modfname.pm") || die "Can't create $ext$modpname/$modfname.pm: $!\n";
  607. $" = "\n\t";
  608. warn "Writing $ext$modpname/$modfname.pm\n";
  609. if ( $compat_version < 5.006 ) {
  610. print PM <<"END";
  611. package $module;
  612. use $compat_version;
  613. use strict;
  614. END
  615. }
  616. else {
  617. print PM <<"END";
  618. package $module;
  619. use 5.006;
  620. use strict;
  621. use warnings;
  622. END
  623. }
  624. unless( $opt_X || $opt_c || $opt_A ){
  625. # we'll have an AUTOLOAD(), and it will have $AUTOLOAD and
  626. # will want Carp.
  627. print PM <<'END';
  628. use Carp;
  629. END
  630. }
  631. print PM <<'END';
  632. require Exporter;
  633. END
  634. print PM <<"END" if ! $opt_X; # use DynaLoader, unless XS was disabled
  635. require DynaLoader;
  636. END
  637. # Are we using AutoLoader or not?
  638. unless ($opt_A) { # no autoloader whatsoever.
  639. unless ($opt_c) { # we're doing the AUTOLOAD
  640. print PM "use AutoLoader;\n";
  641. }
  642. else {
  643. print PM "use AutoLoader qw(AUTOLOAD);\n"
  644. }
  645. }
  646. if ( $compat_version < 5.006 ) {
  647. if ( $opt_X || $opt_c || $opt_A ) {
  648. print PM 'use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);';
  649. } else {
  650. print PM 'use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $AUTOLOAD);';
  651. }
  652. }
  653. # Determine @ISA.
  654. my $myISA = 'our @ISA = qw(Exporter'; # We seem to always want this.
  655. $myISA .= ' DynaLoader' unless $opt_X; # no XS
  656. $myISA .= ');';
  657. $myISA =~ s/^our // if $compat_version < 5.006;
  658. print PM "\n$myISA\n\n";
  659. my @exported_names = (@const_names, @fnames_no_prefix, map '$'.$_, @vdecls);
  660. my $tmp=<<"END";
  661. # Items to export into callers namespace by default. Note: do not export
  662. # names by default without a very good reason. Use EXPORT_OK instead.
  663. # Do not simply export all your public functions/methods/constants.
  664. # This allows declaration use $module ':all';
  665. # If you do not need this, moving things directly into \@EXPORT or \@EXPORT_OK
  666. # will save memory.
  667. our %EXPORT_TAGS = ( 'all' => [ qw(
  668. @exported_names
  669. ) ] );
  670. our \@EXPORT_OK = ( \@{ \$EXPORT_TAGS{'all'} } );
  671. our \@EXPORT = qw(
  672. @const_names
  673. );
  674. our \$VERSION = '$TEMPLATE_VERSION';
  675. END
  676. $tmp =~ s/^our //mg if $compat_version < 5.006;
  677. print PM $tmp;
  678. if (@vdecls) {
  679. printf PM "our(@{[ join ', ', map '$'.$_, @vdecls ]});\n\n";
  680. }
  681. $tmp = ( $compat_version < 5.006 ? "" : "our \$AUTOLOAD;" );
  682. print PM <<"END" unless $opt_c or $opt_X;
  683. sub AUTOLOAD {
  684. # This AUTOLOAD is used to 'autoload' constants from the constant()
  685. # XS function. If a constant is not found then control is passed
  686. # to the AUTOLOAD in AutoLoader.
  687. my \$constname;
  688. $tmp
  689. (\$constname = \$AUTOLOAD) =~ s/.*:://;
  690. croak "&$module::constant not defined" if \$constname eq 'constant';
  691. my \$val = constant(\$constname, \@_ ? \$_[0] : 0);
  692. if (\$! != 0) {
  693. if (\$! =~ /Invalid/ || \$!{EINVAL}) {
  694. \$AutoLoader::AUTOLOAD = \$AUTOLOAD;
  695. goto &AutoLoader::AUTOLOAD;
  696. }
  697. else {
  698. croak "Your vendor has not defined $module macro \$constname";
  699. }
  700. }
  701. {
  702. no strict 'refs';
  703. # Fixed between 5.005_53 and 5.005_61
  704. if (\$] >= 5.00561) {
  705. *\$AUTOLOAD = sub () { \$val };
  706. }
  707. else {
  708. *\$AUTOLOAD = sub { \$val };
  709. }
  710. }
  711. goto &\$AUTOLOAD;
  712. }
  713. END
  714. if( ! $opt_X ){ # print bootstrap, unless XS is disabled
  715. print PM <<"END";
  716. bootstrap $module \$VERSION;
  717. END
  718. }
  719. # tying the variables can happen only after bootstrap
  720. if (@vdecls) {
  721. printf PM <<END;
  722. {
  723. @{[ join "\n", map " _tievar_$_(\$$_);", @vdecls ]}
  724. }
  725. END
  726. }
  727. my $after;
  728. if( $opt_P ){ # if POD is disabled
  729. $after = '__END__';
  730. }
  731. else {
  732. $after = '=cut';
  733. }
  734. print PM <<"END";
  735. # Preloaded methods go here.
  736. END
  737. print PM <<"END" unless $opt_A;
  738. # Autoload methods go after $after, and are processed by the autosplit program.
  739. END
  740. print PM <<"END";
  741. 1;
  742. __END__
  743. END
  744. my $author = "A. U. Thor";
  745. my $email = '[email protected]';
  746. my $revhist = '';
  747. $revhist = <<EOT if $opt_C;
  748. #
  749. #=head1 HISTORY
  750. #
  751. #=over 8
  752. #
  753. #=item $TEMPLATE_VERSION
  754. #
  755. #Original version; created by h2xs $H2XS_VERSION with options
  756. #
  757. # @ARGS
  758. #
  759. #=back
  760. #
  761. EOT
  762. my $exp_doc = <<EOD;
  763. #
  764. #=head2 EXPORT
  765. #
  766. #None by default.
  767. #
  768. EOD
  769. if (@const_names and not $opt_P) {
  770. $exp_doc .= <<EOD;
  771. #=head2 Exportable constants
  772. #
  773. # @{[join "\n ", @const_names]}
  774. #
  775. EOD
  776. }
  777. if (defined $fdecls and @$fdecls and not $opt_P) {
  778. $exp_doc .= <<EOD;
  779. #=head2 Exportable functions
  780. #
  781. EOD
  782. # $exp_doc .= <<EOD if $opt_p;
  783. #When accessing these functions from Perl, prefix C<$opt_p> should be removed.
  784. #
  785. #EOD
  786. $exp_doc .= <<EOD;
  787. # @{[join "\n ", @known_fnames{@fnames}]}
  788. #
  789. EOD
  790. }
  791. my $meth_doc = '';
  792. if ($opt_x && $opt_a) {
  793. my($name, $struct);
  794. $meth_doc .= accessor_docs($name, $struct)
  795. while ($name, $struct) = each %structs;
  796. }
  797. my $pod = <<"END" unless $opt_P;
  798. ## Below is stub documentation for your module. You better edit it!
  799. #
  800. #=head1 NAME
  801. #
  802. #$module - Perl extension for blah blah blah
  803. #
  804. #=head1 SYNOPSIS
  805. #
  806. # use $module;
  807. # blah blah blah
  808. #
  809. #=head1 DESCRIPTION
  810. #
  811. #Stub documentation for $module, created by h2xs. It looks like the
  812. #author of the extension was negligent enough to leave the stub
  813. #unedited.
  814. #
  815. #Blah blah blah.
  816. $exp_doc$meth_doc$revhist
  817. #=head1 AUTHOR
  818. #
  819. #$author, E<lt>${email}E<gt>
  820. #
  821. #=head1 SEE ALSO
  822. #
  823. #L<perl>.
  824. #
  825. #=cut
  826. END
  827. $pod =~ s/^\#//gm unless $opt_P;
  828. print PM $pod unless $opt_P;
  829. close PM;
  830. if( ! $opt_X ){ # print XS, unless it is disabled
  831. warn "Writing $ext$modpname/$modfname.xs\n";
  832. print XS <<"END";
  833. #include "EXTERN.h"
  834. #include "perl.h"
  835. #include "XSUB.h"
  836. END
  837. if( @path_h ){
  838. foreach my $path_h (@path_h_ini) {
  839. my($h) = $path_h;
  840. $h =~ s#^/usr/include/##;
  841. if ($^O eq 'VMS') { $h =~ s#.*vms\]#sys/# or $h =~ s#.*[:>\]]##; }
  842. print XS qq{#include <$h>\n};
  843. }
  844. print XS "\n";
  845. }
  846. my %pointer_typedefs;
  847. my %struct_typedefs;
  848. sub td_is_pointer {
  849. my $type = shift;
  850. my $out = $pointer_typedefs{$type};
  851. return $out if defined $out;
  852. my $otype = $type;
  853. $out = ($type =~ /\*$/);
  854. # This converts only the guys which do not have trailing part in the typedef
  855. if (not $out
  856. and $typedef_rex and $type =~ s/($typedef_rex)/$typedefs_pre{$1}/go) {
  857. $type = normalize_type($type);
  858. print "Is-Pointer: Type mutation via typedefs: $otype ==> $type\n"
  859. if $opt_d;
  860. $out = td_is_pointer($type);
  861. }
  862. return ($pointer_typedefs{$otype} = $out);
  863. }
  864. sub td_is_struct {
  865. my $type = shift;
  866. my $out = $struct_typedefs{$type};
  867. return $out if defined $out;
  868. my $otype = $type;
  869. $out = ($type =~ /^(struct|union)\b/) && !td_is_pointer($type);
  870. # This converts only the guys which do not have trailing part in the typedef
  871. if (not $out
  872. and $typedef_rex and $type =~ s/($typedef_rex)/$typedefs_pre{$1}/go) {
  873. $type = normalize_type($type);
  874. print "Is-Struct: Type mutation via typedefs: $otype ==> $type\n"
  875. if $opt_d;
  876. $out = td_is_struct($type);
  877. }
  878. return ($struct_typedefs{$otype} = $out);
  879. }
  880. # Some macros will bomb if you try to return them from a double-returning func.
  881. # Say, ((char *)0), or strlen (if somebody #define STRLEN strlen).
  882. # Fortunately, we can detect both these cases...
  883. sub protect_convert_to_double {
  884. my $in = shift;
  885. my $val;
  886. return '' unless defined ($val = $seen_define{$in});
  887. return '(IV)' if $known_fnames{$val};
  888. # OUT_t of ((OUT_t)-1):
  889. return '' unless $val =~ /^\s*(\(\s*)?\(\s*([^()]*?)\s*\)/;
  890. td_is_pointer($2) ? '(IV)' : '';
  891. }
  892. # For each of the generated functions, length($pref) leading
  893. # letters are already checked. Moreover, it is recommended that
  894. # the generated functions uses switch on letter at offset at least
  895. # $off + length($pref).
  896. #
  897. # The given list has length($pref) chars removed at front, it is
  898. # guarantied that $off leading chars in the rest are the same for all
  899. # elts of the list.
  900. #
  901. # Returns: how at which offset it was decided to make a switch, or -1 if none.
  902. sub write_const;
  903. sub write_const {
  904. my ($fh, $pref, $off, $list) = (shift,shift,shift,shift);
  905. my %leading;
  906. my $offarg = length $pref;
  907. if (@$list == 0) { # Can happen on the initial iteration only
  908. print $fh <<"END";
  909. static double
  910. constant(char *name, int len, int arg)
  911. {
  912. errno = EINVAL;
  913. return 0;
  914. }
  915. END
  916. return -1;
  917. }
  918. if (@$list == 1) { # Can happen on the initial iteration only
  919. my $protect = protect_convert_to_double("$pref$list->[0]");
  920. print $fh <<"END";
  921. static double
  922. constant(char *name, int len, int arg)
  923. {
  924. errno = 0;
  925. if (strEQ(name + $offarg, "$list->[0]")) { /* $pref removed */
  926. #ifdef $pref$list->[0]
  927. return $protect$pref$list->[0];
  928. #else
  929. errno = ENOENT;
  930. return 0;
  931. #endif
  932. }
  933. errno = EINVAL;
  934. return 0;
  935. }
  936. END
  937. return -1;
  938. }
  939. for my $n (@$list) {
  940. my $c = substr $n, $off, 1;
  941. $leading{$c} = [] unless exists $leading{$c};
  942. push @{$leading{$c}}, substr $n, $off + 1;
  943. }
  944. if (keys(%leading) == 1) {
  945. return 1 + write_const $fh, $pref, $off + 1, $list;
  946. }
  947. my $leader = substr $list->[0], 0, $off;
  948. foreach my $letter (keys %leading) {
  949. write_const $fh, "$pref$leader$letter", 0, $leading{$letter}
  950. if @{$leading{$letter}} > 1;
  951. }
  952. my $npref = "_$pref";
  953. $npref = '' if $pref eq '';
  954. print $fh <<"END";
  955. static double
  956. constant$npref(char *name, int len, int arg)
  957. {
  958. END
  959. print $fh <<"END" if $npref eq '';
  960. errno = 0;
  961. END
  962. if ($off) {
  963. my $null = 0;
  964. foreach my $letter (keys %leading) {
  965. if ($letter eq '') {
  966. $null = 1;
  967. last;
  968. }
  969. }
  970. my $cmp = $null ? '>' : '>=';
  971. print $fh <<"END"
  972. if ($offarg + $off $cmp len ) {
  973. errno = EINVAL;
  974. return 0;
  975. }
  976. END
  977. }
  978. print $fh <<"END";
  979. switch (name[$offarg + $off]) {
  980. END
  981. foreach my $letter (sort keys %leading) {
  982. my $let = $letter;
  983. $let = '\0' if $letter eq '';
  984. print $fh <<EOP;
  985. case '$let':
  986. EOP
  987. if (@{$leading{$letter}} > 1) {
  988. # It makes sense to call a function
  989. if ($off) {
  990. print $fh <<EOP;
  991. if (!strnEQ(name + $offarg,"$leader", $off))
  992. break;
  993. EOP
  994. }
  995. print $fh <<EOP;
  996. return constant_$pref$leader$letter(name, len, arg);
  997. EOP
  998. }
  999. else {
  1000. # Do it ourselves
  1001. my $protect
  1002. = protect_convert_to_double("$pref$leader$letter$leading{$letter}[0]");
  1003. print $fh <<EOP;
  1004. if (strEQ(name + $offarg, "$leader$letter$leading{$letter}[0]")) { /* $pref removed */
  1005. #ifdef $pref$leader$letter$leading{$letter}[0]
  1006. return $protect$pref$leader$letter$leading{$letter}[0];
  1007. #else
  1008. goto not_there;
  1009. #endif
  1010. }
  1011. EOP
  1012. }
  1013. }
  1014. print $fh <<"END";
  1015. }
  1016. errno = EINVAL;
  1017. return 0;
  1018. not_there:
  1019. errno = ENOENT;
  1020. return 0;
  1021. }
  1022. END
  1023. }
  1024. if( ! $opt_c ) {
  1025. print XS <<"END";
  1026. static int
  1027. not_here(char *s)
  1028. {
  1029. croak("$module::%s not implemented on this architecture", s);
  1030. return -1;
  1031. }
  1032. END
  1033. write_const(\*XS, '', 0, \@const_names);
  1034. }
  1035. print_tievar_subs(\*XS, $_, $vdecl_hash{$_}) for @vdecls;
  1036. my $prefix;
  1037. $prefix = "PREFIX = $opt_p" if defined $opt_p;
  1038. # Now switch from C to XS by issuing the first MODULE declaration:
  1039. print XS <<"END";
  1040. MODULE = $module PACKAGE = $module $prefix
  1041. END
  1042. foreach (sort keys %const_xsub) {
  1043. print XS <<"END";
  1044. char *
  1045. $_()
  1046. CODE:
  1047. #ifdef $_
  1048. RETVAL = $_;
  1049. #else
  1050. croak("Your vendor has not defined the $module macro $_");
  1051. #endif
  1052. OUTPUT:
  1053. RETVAL
  1054. END
  1055. }
  1056. # If a constant() function was written then output a corresponding
  1057. # XS declaration:
  1058. print XS <<"END" unless $opt_c;
  1059. double
  1060. constant(sv,arg)
  1061. PREINIT:
  1062. STRLEN len;
  1063. INPUT:
  1064. SV * sv
  1065. char * s = SvPV(sv, len);
  1066. int arg
  1067. CODE:
  1068. RETVAL = constant(s,len,arg);
  1069. OUTPUT:
  1070. RETVAL
  1071. END
  1072. my %seen_decl;
  1073. my %typemap;
  1074. sub print_decl {
  1075. my $fh = shift;
  1076. my $decl = shift;
  1077. my ($type, $name, $args) = @$decl;
  1078. return if $seen_decl{$name}++; # Need to do the same for docs as well?
  1079. my @argnames = map {$_->[1]} @$args;
  1080. my @argtypes = map { normalize_type( $_->[0], 1 ) } @$args;
  1081. if ($opt_k) {
  1082. s/^\s*const\b\s*// for @argtypes;
  1083. }
  1084. my @argarrays = map { $_->[4] || '' } @$args;
  1085. my $numargs = @$args;
  1086. if ($numargs and $argtypes[-1] eq '...') {
  1087. $numargs--;
  1088. $argnames[-1] = '...';
  1089. }
  1090. local $" = ', ';
  1091. $type = normalize_type($type, 1);
  1092. print $fh <<"EOP";
  1093. $type
  1094. $name(@argnames)
  1095. EOP
  1096. for my $arg (0 .. $numargs - 1) {
  1097. print $fh <<"EOP";
  1098. $argtypes[$arg] $argnames[$arg]$argarrays[$arg]
  1099. EOP
  1100. }
  1101. }
  1102. sub print_tievar_subs {
  1103. my($fh, $name, $type) = @_;
  1104. print $fh <<END;
  1105. I32
  1106. _get_$name(IV index, SV *sv) {
  1107. dSP;
  1108. PUSHMARK(SP);
  1109. XPUSHs(sv);
  1110. PUTBACK;
  1111. (void)call_pv("$module\::_get_$name", G_DISCARD);
  1112. return (I32)0;
  1113. }
  1114. I32
  1115. _set_$name(IV index, SV *sv) {
  1116. dSP;
  1117. PUSHMARK(SP);
  1118. XPUSHs(sv);
  1119. PUTBACK;
  1120. (void)call_pv("$module\::_set_$name", G_DISCARD);
  1121. return (I32)0;
  1122. }
  1123. END
  1124. }
  1125. sub print_tievar_xsubs {
  1126. my($fh, $name, $type) = @_;
  1127. print $fh <<END;
  1128. void
  1129. _tievar_$name(sv)
  1130. SV* sv
  1131. PREINIT:
  1132. struct ufuncs uf;
  1133. CODE:
  1134. uf.uf_val = &_get_$name;
  1135. uf.uf_set = &_set_$name;
  1136. uf.uf_index = (IV)&_get_$name;
  1137. sv_magic(sv, 0, 'U', (char*)&uf, sizeof(uf));
  1138. void
  1139. _get_$name(THIS)
  1140. $type THIS = NO_INIT
  1141. CODE:
  1142. THIS = $name;
  1143. OUTPUT:
  1144. SETMAGIC: DISABLE
  1145. THIS
  1146. void
  1147. _set_$name(THIS)
  1148. $type THIS
  1149. CODE:
  1150. $name = THIS;
  1151. END
  1152. }
  1153. sub print_accessors {
  1154. my($fh, $name, $struct) = @_;
  1155. return unless defined $struct && $name !~ /\s|_ANON/;
  1156. $name = normalize_type($name);
  1157. my $ptrname = normalize_type("$name *");
  1158. print $fh <<"EOF";
  1159. MODULE = $module PACKAGE = ${name} $prefix
  1160. $name *
  1161. _to_ptr(THIS)
  1162. $name THIS = NO_INIT
  1163. PROTOTYPE: \$
  1164. CODE:
  1165. if (sv_derived_from(ST(0), "$name")) {
  1166. STRLEN len;
  1167. char *s = SvPV((SV*)SvRV(ST(0)), len);
  1168. if (len != sizeof(THIS))
  1169. croak("Size \%d of packed data != expected \%d",
  1170. len, sizeof(THIS));
  1171. RETVAL = ($name *)s;
  1172. }
  1173. else
  1174. croak("THIS is not of type $name");
  1175. OUTPUT:
  1176. RETVAL
  1177. $name
  1178. new(CLASS)
  1179. char *CLASS = NO_INIT
  1180. PROTOTYPE: \$
  1181. CODE:
  1182. Zero((void*)&RETVAL, sizeof(RETVAL), char);
  1183. OUTPUT:
  1184. RETVAL
  1185. MODULE = $module PACKAGE = ${name}Ptr $prefix
  1186. EOF
  1187. my @items = @$struct;
  1188. while (@items) {
  1189. my $item = shift @items;
  1190. if ($item->[0] =~ /_ANON/) {
  1191. if (defined $item->[2]) {
  1192. push @items, map [
  1193. @$_[0, 1], "$item->[2]_$_->[2]", "$item->[2].$_->[2]",
  1194. ], @{ $structs{$item->[0]} };
  1195. } else {
  1196. push @items, @{ $structs{$item->[0]} };
  1197. }
  1198. } else {
  1199. my $type = normalize_type($item->[0]);
  1200. my $ttype = $structs{$type} ? normalize_type("$type *") : $type;
  1201. print $fh <<"EOF";
  1202. $ttype
  1203. $item->[2](THIS, __value = NO_INIT)
  1204. $ptrname THIS
  1205. $type __value
  1206. PROTOTYPE: \$;\$
  1207. CODE:
  1208. if (items > 1)
  1209. THIS->$item->[-1] = __value;
  1210. RETVAL = @{[
  1211. $type eq $ttype ? "THIS->$item->[-1]" : "&(THIS->$item->[-1])"
  1212. ]};
  1213. OUTPUT:
  1214. RETVAL
  1215. EOF
  1216. }
  1217. }
  1218. }
  1219. sub accessor_docs {
  1220. my($name, $struct) = @_;
  1221. return unless defined $struct && $name !~ /\s|_ANON/;
  1222. $name = normalize_type($name);
  1223. my $ptrname = $name . 'Ptr';
  1224. my @items = @$struct;
  1225. my @list;
  1226. while (@items) {
  1227. my $item = shift @items;
  1228. if ($item->[0] =~ /_ANON/) {
  1229. if (defined $item->[2]) {
  1230. push @items, map [
  1231. @$_[0, 1], "$item->[2]_$_->[2]", "$item->[2].$_->[2]",
  1232. ], @{ $structs{$item->[0]} };
  1233. } else {
  1234. push @items, @{ $structs{$item->[0]} };
  1235. }
  1236. } else {
  1237. push @list, $item->[2];
  1238. }
  1239. }
  1240. my $methods = (join '(...)>, C<', @list) . '(...)';
  1241. my $pod = <<"EOF";
  1242. #
  1243. #=head2 Object and class methods for C<$name>/C<$ptrname>
  1244. #
  1245. #The principal Perl representation of a C object of type C<$name> is an
  1246. #object of class C<$ptrname> which is a reference to an integer
  1247. #representation of a C pointer. To create such an object, one may use
  1248. #a combination
  1249. #
  1250. # my \$buffer = $name->new();
  1251. # my \$obj = \$buffer->_to_ptr();
  1252. #
  1253. #This exersizes the following two methods, and an additional class
  1254. #C<$name>, the internal representation of which is a reference to a
  1255. #packed string with the C structure. Keep in mind that \$buffer should
  1256. #better survive longer than \$obj.
  1257. #
  1258. #=over
  1259. #
  1260. #=item C<\$object_of_type_$name-E<gt>_to_ptr()>
  1261. #
  1262. #Converts an object of type C<$name> to an object of type C<$ptrname>.
  1263. #
  1264. #=item C<$name-E<gt>new()>
  1265. #
  1266. #Creates an empty object of type C<$name>. The corresponding packed
  1267. #string is zeroed out.
  1268. #
  1269. #=item C<$methods>
  1270. #
  1271. #return the current value of the corresponding element if called
  1272. #without additional arguments. Set the element to the supplied value
  1273. #(and return the new value) if called with an additional argument.
  1274. #
  1275. #Applicable to objects of type C<$ptrname>.
  1276. #
  1277. #=back
  1278. #
  1279. EOF
  1280. $pod =~ s/^\#//gm;
  1281. return $pod;
  1282. }
  1283. # Should be called before any actual call to normalize_type().
  1284. sub get_typemap {
  1285. # We do not want to read ./typemap by obvios reasons.
  1286. my @tm = qw(../../../typemap ../../typemap ../typemap);
  1287. my $stdtypemap = "$Config::Config{privlib}/ExtUtils/typemap";
  1288. unshift @tm, $stdtypemap;
  1289. my $proto_re = "[" . quotemeta('\$%&*@;') . "]" ;
  1290. # Start with useful default values
  1291. $typemap{float} = 'T_DOUBLE';
  1292. foreach my $typemap (@tm) {
  1293. next unless -e $typemap ;
  1294. # skip directories, binary files etc.
  1295. warn " Scanning $typemap\n";
  1296. warn("Warning: ignoring non-text typemap file '$typemap'\n"), next
  1297. unless -T $typemap ;
  1298. open(TYPEMAP, $typemap)
  1299. or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
  1300. my $mode = 'Typemap';
  1301. while (<TYPEMAP>) {
  1302. next if /^\s*\#/;
  1303. if (/^INPUT\s*$/) { $mode = 'Input'; next; }
  1304. elsif (/^OUTPUT\s*$/) { $mode = 'Output'; next; }
  1305. elsif (/^TYPEMAP\s*$/) { $mode = 'Typemap'; next; }
  1306. elsif ($mode eq 'Typemap') {
  1307. next if /^\s*($|\#)/ ;
  1308. my ($type, $image);
  1309. if ( ($type, $image) =
  1310. /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/o
  1311. # This may reference undefined functions:
  1312. and not ($image eq 'T_PACKED' and $typemap eq $stdtypemap)) {
  1313. $typemap{normalize_type($type)} = $image;
  1314. }
  1315. }
  1316. }
  1317. close(TYPEMAP) or die "Cannot close $typemap: $!";
  1318. }
  1319. %std_types = %types_seen;
  1320. %types_seen = ();
  1321. }
  1322. sub normalize_type { # Second arg: do not strip const's before \*
  1323. my $type = shift;
  1324. my $do_keep_deep_const = shift;
  1325. # If $do_keep_deep_const this is heuristical only
  1326. my $keep_deep_const = ($do_keep_deep_const ? '\b(?![^(,)]*\*)' : '');
  1327. my $ignore_mods
  1328. = "(?:\\b(?:(?:__const__|const)$keep_deep_const|static|inline|__inline__)\\b\\s*)*";
  1329. if ($do_keep_deep_const) { # Keep different compiled /RExen/o separately!
  1330. $type =~ s/$ignore_mods//go;
  1331. }
  1332. else {
  1333. $type =~ s/$ignore_mods//go;
  1334. }
  1335. $type =~ s/([^\s\w])/ \1 /g;
  1336. $type =~ s/\s+$//;
  1337. $type =~ s/^\s+//;
  1338. $type =~ s/\s+/ /g;
  1339. $type =~ s/\* (?=\*)/*/g;
  1340. $type =~ s/\. \. \./.../g;
  1341. $type =~ s/ ,/,/g;
  1342. $types_seen{$type}++
  1343. unless $type eq '...' or $type eq 'void' or $std_types{$type};
  1344. $type;
  1345. }
  1346. my $need_opaque;
  1347. sub assign_typemap_entry {
  1348. my $type = shift;
  1349. my $otype = $type;
  1350. my $entry;
  1351. if ($tmask and $type =~ /$tmask/) {
  1352. print "Type $type matches -o mask\n" if $opt_d;
  1353. $entry = (td_is_struct($type) ? "T_OPAQUE_STRUCT" : "T_PTROBJ");
  1354. }
  1355. elsif ($typedef_rex and $type =~ s/($typedef_rex)/$typedefs_pre{$1}/go) {
  1356. $type = normalize_type $type;
  1357. print "Type mutation via typedefs: $otype ==> $type\n" if $opt_d;
  1358. $entry = assign_typemap_entry($type);
  1359. }
  1360. $entry ||= $typemap{$otype}
  1361. || (td_is_struct($type) ? "T_OPAQUE_STRUCT" : "T_PTROBJ");
  1362. $typemap{$otype} = $entry;
  1363. $need_opaque = 1 if $entry eq "T_OPAQUE_STRUCT";
  1364. return $entry;
  1365. }
  1366. for (@vdecls) {
  1367. print_tievar_xsubs(\*XS, $_, $vdecl_hash{$_});
  1368. }
  1369. if ($opt_x) {
  1370. for my $decl (@$fdecls_parsed) { print_decl(\*XS, $decl) }
  1371. if ($opt_a) {
  1372. while (my($name, $struct) = each %structs) {
  1373. print_accessors(\*XS, $name, $struct);
  1374. }
  1375. }
  1376. }
  1377. close XS;
  1378. if (%types_seen) {
  1379. my $type;
  1380. warn "Writing $ext$modpname/typemap\n";
  1381. open TM, ">typemap" or die "Cannot open typemap file for write: $!";
  1382. for $type (sort keys %types_seen) {
  1383. my $entry = assign_typemap_entry $type;
  1384. print TM $type, "\t" x (5 - int((length $type)/8)), "\t$entry\n"
  1385. }
  1386. print TM <<'EOP' if $need_opaque; # Older Perls do not have correct entry
  1387. #############################################################################
  1388. INPUT
  1389. T_OPAQUE_STRUCT
  1390. if (sv_derived_from($arg, \"${ntype}\")) {
  1391. STRLEN len;
  1392. char *s = SvPV((SV*)SvRV($arg), len);
  1393. if (len != sizeof($var))
  1394. croak(\"Size %d of packed data != expected %d\",
  1395. len, sizeof($var));
  1396. $var = *($type *)s;
  1397. }
  1398. else
  1399. croak(\"$var is not of type ${ntype}\")
  1400. #############################################################################
  1401. OUTPUT
  1402. T_OPAQUE_STRUCT
  1403. sv_setref_pvn($arg, \"${ntype}\", (char *)&$var, sizeof($var));
  1404. EOP
  1405. close TM or die "Cannot close typemap file for write: $!";
  1406. }
  1407. } # if( ! $opt_X )
  1408. warn "Writing $ext$modpname/Makefile.PL\n";
  1409. open(PL, ">Makefile.PL") || die "Can't create $ext$modpname/Makefile.PL: $!\n";
  1410. print PL <<END;
  1411. use ExtUtils::MakeMaker;
  1412. # See lib/ExtUtils/MakeMaker.pm for details of how to influence
  1413. # the contents of the Makefile that is written.
  1414. WriteMakefile(
  1415. 'NAME' => '$module',
  1416. 'VERSION_FROM' => '$modfname.pm', # finds \$VERSION
  1417. 'PREREQ_PM' => {}, # e.g., Module::Name => 1.1
  1418. (\$] >= 5.005 ? ## Add these new keywords supported since 5.005
  1419. (ABSTRACT_FROM => '$modfname.pm', # retrieve abstract from module
  1420. AUTHOR => '$author <$email>') : ()),
  1421. END
  1422. if (!$opt_X) { # print C stuff, unless XS is disabled
  1423. $opt_F = '' unless defined $opt_F;
  1424. my $I = (((glob '*.h') || (glob '*.hh')) ? '-I.' : '');
  1425. my $Ihelp = ($I ? '-I. ' : '');
  1426. my $Icomment = ($I ? '' : <<EOC);
  1427. # Insert -I. if you add *.h files later:
  1428. EOC
  1429. print PL <<END;
  1430. 'LIBS' => ['$extralibs'], # e.g., '-lm'
  1431. 'DEFINE' => '$opt_F', # e.g., '-DHAVE_SOMETHING'
  1432. $Icomment 'INC' => '$I', # e.g., '$Ihelp-I/usr/include/other'
  1433. END
  1434. my $C = grep $_ ne "$modfname.c", (glob '*.c'), (glob '*.cc'), (glob '*.C');
  1435. my $Cpre = ($C ? '' : '# ');
  1436. my $Ccomment = ($C ? '' : <<EOC);
  1437. # Un-comment this if you add C files to link with later:
  1438. EOC
  1439. print PL <<END;
  1440. $Ccomment $Cpre\'OBJECT' => '\$(O_FILES)', # link all the C files too
  1441. END
  1442. }
  1443. print PL ");\n";
  1444. close(PL) || die "Can't close $ext$modpname/Makefile.PL: $!\n";
  1445. # Create a simple README since this is a CPAN requirement
  1446. # and it doesnt hurt to have one
  1447. warn "Writing $ext$modpname/README\n";
  1448. open(RM, ">README") || die "Can't create $ext$modpname/README:$!\n";
  1449. my $thisyear = (gmtime)[5] + 1900;
  1450. my $rmhead = "$modpname version $TEMPLATE_VERSION";
  1451. my $rmheadeq = "=" x length($rmhead);
  1452. print RM <<_RMEND_;
  1453. $rmhead
  1454. $rmheadeq
  1455. The README is used to introduce the module and provide instructions on
  1456. how to install the module, any machine dependencies it may have (for
  1457. example C compilers and installed libraries) and any other information
  1458. that should be provided before the module is installed.
  1459. A README file is required for CPAN modules since CPAN extracts the
  1460. README file from a module distribution so that people browsing the
  1461. archive can use it get an idea of the modules uses. It is usually a
  1462. good idea to provide version information here so that people can
  1463. decide whether fixes for the module are worth downloading.
  1464. INSTALLATION
  1465. To install this module type the following:
  1466. perl Makefile.PL
  1467. make
  1468. make test
  1469. make install
  1470. DEPENDENCIES
  1471. This module requires these other modules and libraries:
  1472. blah blah blah
  1473. COPYRIGHT AND LICENCE
  1474. Put the correct copyright and licence information here.
  1475. Copyright (C) $thisyear $author
  1476. This library is free software; you can redistribute it and/or modify
  1477. it under the same terms as Perl itself.
  1478. _RMEND_
  1479. close(RM) || die "Can't close $ext$modpname/README: $!\n";
  1480. warn "Writing $ext$modpname/test.pl\n";
  1481. open(EX, ">test.pl") || die "Can't create $ext$modpname/test.pl: $!\n";
  1482. print EX <<'_END_';
  1483. # Before `make install' is performed this script should be runnable with
  1484. # `make test'. After `make install' it should work as `perl test.pl'
  1485. #########################
  1486. # change 'tests => 1' to 'tests => last_test_to_print';
  1487. use Test;
  1488. BEGIN { plan tests => 1 };
  1489. _END_
  1490. print EX <<_END_;
  1491. use $module;
  1492. _END_
  1493. print EX <<'_END_';
  1494. ok(1); # If we made it this far, we're ok.
  1495. #########################
  1496. # Insert your test code below, the Test module is use()ed here so read
  1497. # its man page ( perldoc Test ) for help writing this test script.
  1498. _END_
  1499. close(EX) || die "Can't close $ext$modpname/test.pl: $!\n";
  1500. unless ($opt_C) {
  1501. warn "Writing $ext$modpname/Changes\n";
  1502. $" = ' ';
  1503. open(EX, ">Changes") || die "Can't create $ext$modpname/Changes: $!\n";
  1504. @ARGS = map {/[\s\"\'\`\$*?^|&<>\[\]\{\}\(\)]/ ? "'$_'" : $_} @ARGS;
  1505. print EX <<EOP;
  1506. Revision history for Perl extension $module.
  1507. $TEMPLATE_VERSION @{[scalar localtime]}
  1508. \t- original version; created by h2xs $H2XS_VERSION with options
  1509. \t\t@ARGS
  1510. EOP
  1511. close(EX) || die "Can't close $ext$modpname/Changes: $!\n";
  1512. }
  1513. warn "Writing $ext$modpname/MANIFEST\n";
  1514. open(MANI,'>MANIFEST') or die "Can't create MANIFEST: $!";
  1515. my @files = <*>;
  1516. if (!@files) {
  1517. eval {opendir(D,'.');};
  1518. unless ($@) { @files = readdir(D); closedir(D); }
  1519. }
  1520. if (!@files) { @files = map {chomp && $_} `ls`; }
  1521. if ($^O eq 'VMS') {
  1522. foreach (@files) {
  1523. # Clip trailing '.' for portability -- non-VMS OSs don't expect it
  1524. s%\.$%%;
  1525. # Fix up for case-sensitive file systems
  1526. s/$modfname/$modfname/i && next;
  1527. $_ = "\U$_" if $_ eq 'manifest' or $_ eq 'changes';
  1528. $_ = 'Makefile.PL' if $_ eq 'makefile.pl';
  1529. }
  1530. }
  1531. print MANI join("\n",@files), "\n";
  1532. close MANI;
  1533. __END__
  1534. :endofperl