This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Change docs display for PERL_UNUSED_foo
[perl5.git] / regen / reentr.pl
1 #!/usr/bin/perl -w
2 #
3 # Regenerate (overwriting only if changed):
4 #
5 #    reentr.h
6 #    reentr.c
7 #
8 # from information stored in the DATA section of this file.
9 #
10 # With the -U option, it also unconditionally regenerates the relevant
11 # metaconfig units:
12 #
13 #    d_${func}_r.U
14 #
15 # Also accepts the standard regen_lib -q and -v args.
16 #
17 # This script is normally invoked from regen.pl.
18
19 BEGIN {
20     # Get function prototypes
21     require './regen/regen_lib.pl';
22 }
23
24 use strict;
25 use Getopt::Std;
26 my %opts;
27 getopts('Uv', \%opts);
28
29 my %map = (
30            V => "void",
31            A => "char*",        # as an input argument
32            B => "char*",        # as an output argument
33            C => "const char*",  # as a read-only input argument
34            I => "int",
35            L => "long",
36            W => "size_t",
37            H => "FILE**",
38            E => "int*",
39           );
40
41 # (See the definitions after __DATA__.)
42 # In func|inc|type|... a "S" means "type*", and a "R" means "type**".
43 # (The "types" are often structs, such as "struct passwd".)
44 #
45 # After the prototypes one can have |X=...|Y=... to define more types.
46 # A commonly used extra type is to define D to be equal to "type_data",
47 # for example "struct_hostent_data to" go with "struct hostent".
48 #
49 # Example #1: I_XSBWR means int  func_r(X, type, char*, size_t, type**)
50 # Example #2: S_SBIE  means type func_r(type, char*, int, int*)
51 # Example #3: S_CBI   means type func_r(const char*, char*, int)
52
53 sub open_print_header {
54     my ($file, $quote) = @_;
55     return open_new($file, '>',
56                     { by => 'regen/reentr.pl',
57                       from => 'data in regen/reentr.pl',
58                       file => $file, style => '*',
59                       copyright => [2002, 2003, 2005 .. 2007],
60                       quote => $quote });
61 }
62
63 my $h = open_print_header('reentr.h');
64 print $h <<EOF;
65 #ifndef PERL_REENTR_H_
66 #define PERL_REENTR_H_
67
68 /* If compiling for a threaded perl, we will macro-wrap the system/library
69  * interfaces (e.g. getpwent()) which have threaded versions
70  * (e.g. getpwent_r()), which will handle things correctly for
71  * the Perl interpreter.  This is done automatically for the perl core and
72  * extensions, but not generally for XS modules unless they
73  *    #define PERL_REENTRANT
74  * See L<perlxs/Thread-aware system interfaces>.
75  *
76  * For a function 'foo', use the compile-time directive
77  *    #ifdef PERL_REENTR_USING_FOO_R
78  * to test if the function actually did get replaced by the reentrant version.
79  * (If it isn't getting replaced, it might mean it uses a different prototype
80  * on the given platform than any we are expecting.  To fix that, add the
81  * prototype to the __DATA__ section of regen/reentr.pl.)
82  */
83
84 #ifndef PERL_REENTR_API
85 #  if defined(PERL_CORE) || defined(PERL_EXT) || defined(PERL_REENTRANT)
86 #    define PERL_REENTR_API 1
87 #  else
88 #    define PERL_REENTR_API 0
89 #  endif
90 #endif
91
92 #ifdef USE_REENTRANT_API
93
94 /* For thread-safe builds, alternative methods are used to make calls to this
95  * safe. */
96 #ifdef USE_THREAD_SAFE_LOCALE
97 #   undef HAS_SETLOCALE_R
98 #endif
99  
100 /* Deprecations: some platforms have the said reentrant interfaces
101  * but they are declared obsolete and are not to be used.  Often this
102  * means that the platform has threadsafed the interfaces (hopefully).
103  * All this is OS version dependent, so we are of course fooling ourselves.
104  * If you know of more deprecations on some platforms, please add your own
105  * (by editing reentr.pl, mind!) */
106
107 #  ifdef __hpux
108 #    undef HAS_CRYPT_R
109 #    undef HAS_ENDGRENT_R
110 #    undef HAS_ENDPWENT_R
111 #    undef HAS_GETGRENT_R
112 #    undef HAS_GETPWENT_R
113 #    undef HAS_SETLOCALE_R
114 #    undef HAS_STRERROR_R
115 #    define NETDB_R_OBSOLETE
116 #  endif
117
118 #  if defined(__osf__) && defined(__alpha) /* Tru64 aka Digital UNIX */
119 #    undef HAS_CRYPT_R
120 #    undef HAS_STRERROR_R
121 #    define NETDB_R_OBSOLETE
122 #  endif
123
124 #  if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 24))
125 #    undef HAS_READDIR_R
126 #    undef HAS_READDIR64_R
127 #  endif
128
129 /*
130  * As of OpenBSD 3.7, reentrant functions are now working, they just are
131  * incompatible with everyone else.  To make OpenBSD happy, we have to
132  * memzero out certain structures before calling the functions.
133  */
134 #  if defined(__OpenBSD__)
135 #    define REENTR_MEMZERO(a,b) memzero(a,b)
136 #  else
137 #    define REENTR_MEMZERO(a,b) 0
138 #  endif
139
140 #  ifdef NETDB_R_OBSOLETE
141 #    undef HAS_ENDHOSTENT_R
142 #    undef HAS_ENDNETENT_R
143 #    undef HAS_ENDPROTOENT_R
144 #    undef HAS_ENDSERVENT_R
145 #    undef HAS_GETHOSTBYADDR_R
146 #    undef HAS_GETHOSTBYNAME_R
147 #    undef HAS_GETHOSTENT_R
148 #    undef HAS_GETNETBYADDR_R
149 #    undef HAS_GETNETBYNAME_R
150 #    undef HAS_GETNETENT_R
151 #    undef HAS_GETPROTOBYNAME_R
152 #    undef HAS_GETPROTOBYNUMBER_R
153 #    undef HAS_GETPROTOENT_R
154 #    undef HAS_GETSERVBYNAME_R
155 #    undef HAS_GETSERVBYPORT_R
156 #    undef HAS_GETSERVENT_R
157 #    undef HAS_SETHOSTENT_R
158 #    undef HAS_SETNETENT_R
159 #    undef HAS_SETPROTOENT_R
160 #    undef HAS_SETSERVENT_R
161 #  endif
162
163 #  ifdef I_PWD
164 #    include <pwd.h>
165 #  endif
166 #  ifdef I_GRP
167 #    include <grp.h>
168 #  endif
169 #  ifdef I_NETDB
170 #    include <netdb.h>
171 #  endif
172 #  ifdef I_CRYPT
173 #    ifdef I_CRYPT
174 #      include <crypt.h>
175 #    endif
176 #  endif
177 #  ifdef HAS_GETSPNAM_R
178 #    ifdef I_SHADOW
179 #      include <shadow.h>
180 #    endif
181 #  endif
182
183 EOF
184
185 my %seenh; # the different prototypes signatures for this function
186 my %seena; # the different prototypes signatures for this function in order
187 my @seenf; # all the seen functions
188 my %seenp; # the different prototype signatures for all functions
189 my %seent; # the return type of this function
190 my %seens; # the type of this function's "S"
191 my %seend; # the type of this function's "D"
192 my %seenm; # all the types
193 my %seenu; # the length of the argument list of this function
194
195 while (<DATA>) { # Read in the protoypes.
196     next if /^\s+$/;
197     chomp;
198     my ($func, $hdr, $type, @p) = split(/\s*\|\s*/, $_, -1);
199     my $u;
200     # Split off the real function name and the argument list.
201     ($func, $u) = split(' ', $func);
202     $seenu{$func} = defined $u ? length $u : 0;
203     my $FUNC = uc $func; # for output.
204     push @seenf, $func;
205     my %m = %map;
206     if ($type) {
207         $m{S} = "$type*";
208         $m{R} = "$type**";
209     }
210
211     # Set any special mapping variables (like X=x_t)
212     if (@p) {
213         while ($p[-1] =~ /=/) {
214             my ($k, $v) = ($p[-1] =~ /^([A-Za-z])\s*=\s*(.*)/);
215             $m{$k} = $v;
216             pop @p;
217         }
218     }
219
220     # If given the -U option open up the metaconfig unit for this function.
221     if ($opts{U} && open(U, ">", "d_${func}_r.U"))  {
222         binmode U;
223     }
224
225     if ($opts{U}) {
226         # The metaconfig units needs prerequisite dependencies.
227         my $prereqs  = '';
228         my $prereqh  = '';
229         my $prereqsh = '';
230         if ($hdr ne 'stdio') { # There's no i_stdio.
231             $prereqs  = "i_$hdr";
232             $prereqh  = "$hdr.h";
233             $prereqsh = "\$$prereqs $prereqh";
234         }
235         my @prereq = qw(Inlibc Protochk Hasproto i_systypes usethreads);
236         push @prereq, $prereqs;
237         my $hdrs = "\$i_systypes sys/types.h define stdio.h $prereqsh";
238         if ($hdr eq 'time') {
239             $hdrs .= " \$i_systime sys/time.h";
240             push @prereq, 'i_systime';
241         }
242         # Output the metaconfig unit header.
243         print U <<"EOF";
244 ?RCS: \$Id: d_${func}_r.U,v $
245 ?RCS:
246 ?RCS: Copyright (c) 2002,2003 Jarkko Hietaniemi
247 ?RCS:
248 ?RCS: You may distribute under the terms of either the GNU General Public
249 ?RCS: License or the Artistic License, as specified in the README file.
250 ?RCS:
251 ?RCS: Generated by the reentr.pl from the Perl 5.8 distribution.
252 ?RCS:
253 ?MAKE:d_${func}_r ${func}_r_proto: @prereq
254 ?MAKE:  -pick add \$@ %<
255 ?S:d_${func}_r:
256 ?S:     This variable conditionally defines the HAS_${FUNC}_R symbol,
257 ?S:     which indicates to the C program that the ${func}_r()
258 ?S:     routine is available.
259 ?S:.
260 ?S:${func}_r_proto:
261 ?S:     This variable encodes the prototype of ${func}_r.
262 ?S:     It is zero if d_${func}_r is undef, and one of the
263 ?S:     REENTRANT_PROTO_T_ABC macros of reentr.h if d_${func}_r
264 ?S:     is defined.
265 ?S:.
266 ?C:HAS_${FUNC}_R:
267 ?C:     This symbol, if defined, indicates that the ${func}_r routine
268 ?C:     is available to ${func} re-entrantly.
269 ?C:.
270 ?C:${FUNC}_R_PROTO:
271 ?C:     This symbol encodes the prototype of ${func}_r.
272 ?C:     It is zero if d_${func}_r is undef, and one of the
273 ?C:     REENTRANT_PROTO_T_ABC macros of reentr.h if d_${func}_r
274 ?C:     is defined.
275 ?C:.
276 ?H:#\$d_${func}_r HAS_${FUNC}_R    /**/
277 ?H:#define ${FUNC}_R_PROTO \$${func}_r_proto       /**/
278 ?H:.
279 ?T:try hdrs d_${func}_r_proto
280 ?LINT:set d_${func}_r
281 ?LINT:set ${func}_r_proto
282 : see if ${func}_r exists
283 set ${func}_r d_${func}_r
284 eval \$inlibc
285 case "\$d_${func}_r" in
286 "\$define")
287 EOF
288         print U <<"EOF";
289         hdrs="$hdrs"
290         case "\$d_${func}_r_proto:\$usethreads" in
291         ":define")      d_${func}_r_proto=define
292                 set d_${func}_r_proto ${func}_r \$hdrs
293                 eval \$hasproto ;;
294         *)      ;;
295         esac
296         case "\$d_${func}_r_proto" in
297         define)
298 EOF
299     }
300     for my $p (@p) {
301         my ($r, $a) = ($p =~ /^(.)_(.+)/);
302         my $v = join(", ", map { $m{$_} } split '', $a);
303         if ($opts{U}) {
304             print U <<"EOF";
305         case "\$${func}_r_proto" in
306         ''|0) try='$m{$r} ${func}_r($v);'
307         ./protochk "extern \$try" \$hdrs && ${func}_r_proto=$p ;;
308         esac
309 EOF
310         }
311         $seenh{$func}->{$p}++;
312         push @{$seena{$func}}, $p;
313         $seenp{$p}++;
314         $seent{$func} = $type;
315         $seens{$func} = $m{S};
316         $seend{$func} = $m{D};
317         $seenm{$func} = \%m;
318     }
319     if ($opts{U}) {
320         print U <<"EOF";
321         case "\$${func}_r_proto" in
322         ''|0)   d_${func}_r=undef
323                 ${func}_r_proto=0
324                 echo "Disabling ${func}_r, cannot determine prototype." >&4 ;;
325         * )     case "\$${func}_r_proto" in
326                 REENTRANT_PROTO*) ;;
327                 *) ${func}_r_proto="REENTRANT_PROTO_\$${func}_r_proto" ;;
328                 esac
329                 echo "Prototype: \$try" ;;
330         esac
331         ;;
332         *)      case "\$usethreads" in
333                 define) echo "${func}_r has no prototype, not using it." >&4 ;;
334                 esac
335                 d_${func}_r=undef
336                 ${func}_r_proto=0
337                 ;;
338         esac
339         ;;
340 *)      ${func}_r_proto=0
341         ;;
342 esac
343
344 EOF
345         close(U);
346     }
347 }
348
349 close DATA;
350
351 {
352     # Write out all the known prototype signatures.
353     my $i = 1;
354     for my $p (sort keys %seenp) {
355         print $h "#  define REENTRANT_PROTO_${p}        ${i}\n";
356         $i++;
357     }
358 }
359
360 my @struct; # REENTR struct members
361 my @size;   # struct member buffer size initialization code
362 my @init;   # struct member buffer initialization (malloc) code
363 my @free;   # struct member buffer release (free) code
364 my @wrap;   # the wrapper (foo(a) -> foo_r(a,...)) cpp code
365 my @define; # defines for optional features
366
367 sub ifprotomatch {
368     my $FUNC = shift;
369     join " || ", map { "${FUNC}_R_PROTO == REENTRANT_PROTO_$_" } @_;
370 }
371
372 sub pushssif {
373     push @struct, @_;
374     push @size, @_;
375     push @init, @_;
376     push @free, @_;
377 }
378
379 sub pushinitfree {
380     my $func = shift;
381     push @init, <<EOF;
382         Newx(PL_reentrant_buffer->_${func}_buffer, PL_reentrant_buffer->_${func}_size, char);
383 EOF
384     push @free, <<EOF;
385         Safefree(PL_reentrant_buffer->_${func}_buffer);
386 EOF
387 }
388
389 sub define {
390     my ($n, $p, @F) = @_;
391     my @H;
392     my $H = uc $F[0];
393     push @define, <<EOF;
394 /* The @F using \L$n? */
395
396 EOF
397     my $GENFUNC;
398     for my $func (@F) {
399         my $FUNC = uc $func;
400         my $HAS = "${FUNC}_R_HAS_$n";
401         push @H, $HAS;
402         my @h = grep { /$p/ } @{$seena{$func}};
403         unless (defined $GENFUNC) {
404             $GENFUNC = $FUNC;
405             $GENFUNC =~ s/^GET//;
406         }
407         if (@h) {
408             push @define, "#  if defined(HAS_${FUNC}_R) && (" . join(" || ", map { "${FUNC}_R_PROTO == REENTRANT_PROTO_$_" } @h) . ")\n";
409
410             push @define, <<EOF;
411 #    define $HAS
412 #  else
413 #    undef  $HAS
414 #  endif
415 EOF
416         }
417     }
418     return if @F == 1;
419     push @define, <<EOF;
420
421 /* Any of the @F using \L$n? */
422
423 EOF
424     push @define, "#  if (" . join(" || ", map { "defined($_)" } @H) . ")\n";
425     push @define, <<EOF;
426 #    define USE_${GENFUNC}_$n
427 #  else
428 #    undef  USE_${GENFUNC}_$n
429 #  endif
430
431 EOF
432 }
433
434 define('BUFFER',  'B',
435        qw(getgrent getgrgid getgrnam));
436
437 define('PTR',  'R',
438        qw(getgrent getgrgid getgrnam));
439 define('PTR',  'R',
440        qw(getpwent getpwnam getpwuid));
441 define('PTR',  'R',
442        qw(getspent getspnam));
443
444 define('FPTR', 'H',
445        qw(getgrent getgrgid getgrnam setgrent endgrent));
446 define('FPTR', 'H',
447        qw(getpwent getpwnam getpwuid setpwent endpwent));
448
449 define('BUFFER',  'B',
450        qw(getpwent getpwgid getpwnam));
451
452 define('BUFFER',  'B',
453        qw(getspent getspnam));
454
455 define('PTR', 'R',
456        qw(gethostent gethostbyaddr gethostbyname));
457 define('PTR', 'R',
458        qw(getnetent getnetbyaddr getnetbyname));
459 define('PTR', 'R',
460        qw(getprotoent getprotobyname getprotobynumber));
461 define('PTR', 'R',
462        qw(getservent getservbyname getservbyport));
463
464 define('BUFFER', 'B',
465        qw(gethostent gethostbyaddr gethostbyname));
466 define('BUFFER', 'B',
467        qw(getnetent getnetbyaddr getnetbyname));
468 define('BUFFER', 'B',
469        qw(getprotoent getprotobyname getprotobynumber));
470 define('BUFFER', 'B',
471        qw(getservent getservbyname getservbyport));
472
473 define('ERRNO', 'E',
474        qw(gethostent gethostbyaddr gethostbyname));
475 define('ERRNO', 'E',
476        qw(getnetent getnetbyaddr getnetbyname));
477
478 # The following loop accumulates the "ssif" (struct, size, init, free)
479 # sections that declare the struct members (in reentr.h), and the buffer
480 # size initialization, buffer initialization (malloc), and buffer
481 # release (free) code (in reentr.c).
482 #
483 # The loop also contains a lot of intrinsic logic about groups of
484 # functions (since functions of certain kind operate the same way).
485
486 for my $func (@seenf) {
487     my $FUNC = uc $func;
488     my $ifdef = "#  ifdef HAS_${FUNC}_R\n";
489     my $endif = "#  endif /* HAS_${FUNC}_R */\n\n";
490     if (exists $seena{$func}) {
491         my @p = @{$seena{$func}};
492         if ($func =~ /^(asctime|ctime|getlogin|setlocale|strerror|ttyname)$/) {
493             pushssif $ifdef;
494             push @struct, <<EOF;
495         char*   _${func}_buffer;
496         size_t  _${func}_size;
497 EOF
498             my $size = ($func =~ /^(asctime|ctime)$/)
499                        ? 26
500                        : "REENTRANTSMALLSIZE";
501             push @size, <<EOF;
502         PL_reentrant_buffer->_${func}_size = $size;
503 EOF
504             pushinitfree $func;
505             pushssif $endif;
506         }
507         elsif ($func =~ /^(gm|local)time$/) {
508             pushssif $ifdef;
509             push @struct, <<EOF;    # Fixed size
510         $seent{$func} _${func}_struct;
511 EOF
512             pushssif $endif;
513         }
514         elsif ($func =~ /^(crypt)$/) {
515             pushssif $ifdef;
516             push @struct, <<EOF;
517 #  if CRYPT_R_PROTO == REENTRANT_PROTO_B_CCD
518         $seend{$func} _${func}_data;
519 #  else
520         $seent{$func} *_${func}_struct_buffer;
521 #  endif
522 EOF
523             push @init, <<EOF;
524 #  if CRYPT_R_PROTO != REENTRANT_PROTO_B_CCD
525         PL_reentrant_buffer->_${func}_struct_buffer = 0;
526 #  endif
527 EOF
528             push @free, <<EOF;
529 #  if CRYPT_R_PROTO != REENTRANT_PROTO_B_CCD
530         Safefree(PL_reentrant_buffer->_${func}_struct_buffer);
531 #  endif
532 EOF
533             pushssif $endif;
534         }
535         elsif ($func =~ /^(getgrnam|getpwnam|getspnam)$/) {
536             pushssif $ifdef;
537             # 'genfunc' can be read either as 'generic' or 'genre',
538             # it represents a group of functions.
539             my $genfunc = $func;
540             $genfunc =~ s/nam/ent/g;
541             $genfunc =~ s/^get//;
542             my $GENFUNC = uc $genfunc;
543             push @struct, <<EOF;
544         $seent{$func}   _${genfunc}_struct;
545         char*   _${genfunc}_buffer;
546         size_t  _${genfunc}_size;
547 EOF
548             push @struct, <<EOF;
549 #   ifdef USE_${GENFUNC}_PTR
550         $seent{$func}*  _${genfunc}_ptr;
551 #   endif
552 EOF
553             push @struct, <<EOF;
554 #   ifdef USE_${GENFUNC}_FPTR
555         FILE*   _${genfunc}_fptr;
556 #   endif
557 EOF
558             push @init, <<EOF;
559 #   ifdef USE_${GENFUNC}_FPTR
560         PL_reentrant_buffer->_${genfunc}_fptr = NULL;
561 #   endif
562 EOF
563             my $sc = $genfunc eq 'grent' ?
564                     '_SC_GETGR_R_SIZE_MAX' : '_SC_GETPW_R_SIZE_MAX';
565             my $sz = "_${genfunc}_size";
566             push @size, <<EOF;
567 #    if defined(HAS_SYSCONF) && defined($sc) && !defined(__GLIBC__)
568         PL_reentrant_buffer->$sz = sysconf($sc);
569         if (PL_reentrant_buffer->$sz == (size_t) -1)
570                 PL_reentrant_buffer->$sz = REENTRANTUSUALSIZE;
571 #    elif defined(__osf__) && defined(__alpha) && defined(SIABUFSIZ)
572         PL_reentrant_buffer->$sz = SIABUFSIZ;
573 #    elif defined(__sgi)
574         PL_reentrant_buffer->$sz = BUFSIZ;
575 #    else
576         PL_reentrant_buffer->$sz = REENTRANTUSUALSIZE;
577 #    endif
578 EOF
579             pushinitfree $genfunc;
580             pushssif $endif;
581         }
582         elsif ($func =~ /^(gethostbyname|getnetbyname|getservbyname|getprotobyname)$/) {
583             pushssif $ifdef;
584             my $genfunc = $func;
585             $genfunc =~ s/byname/ent/;
586             $genfunc =~ s/^get//;
587             my $GENFUNC = uc $genfunc;
588             my $D = ifprotomatch($FUNC, grep {/D/} @p);
589             my $d = $seend{$func};
590             $d =~ s/\*$//; # snip: we need the base type.
591             push @struct, <<EOF;
592         $seent{$func}   _${genfunc}_struct;
593 #   if $D
594         $d      _${genfunc}_data;
595 #   else
596         char*   _${genfunc}_buffer;
597         size_t  _${genfunc}_size;
598 #   endif
599 #   ifdef USE_${GENFUNC}_PTR
600         $seent{$func}*  _${genfunc}_ptr;
601 #   endif
602 EOF
603             push @struct, <<EOF;
604 #   ifdef USE_${GENFUNC}_ERRNO
605         int     _${genfunc}_errno;
606 #   endif
607 EOF
608             push @size, <<EOF;
609 #  if !($D)
610         PL_reentrant_buffer->_${genfunc}_size = REENTRANTUSUALSIZE;
611 #  endif
612 EOF
613             push @init, <<EOF;
614 #  if !($D)
615         Newx(PL_reentrant_buffer->_${genfunc}_buffer, PL_reentrant_buffer->_${genfunc}_size, char);
616 #  endif
617 EOF
618             push @free, <<EOF;
619 #  if !($D)
620         Safefree(PL_reentrant_buffer->_${genfunc}_buffer);
621 #  endif
622 EOF
623             pushssif $endif;
624         }
625         elsif ($func =~ /^(readdir|readdir64)$/) {
626             pushssif $ifdef;
627             my $R = ifprotomatch($FUNC, grep {/R/} @p);
628             push @struct, <<EOF;
629         $seent{$func}*  _${func}_struct;
630         size_t  _${func}_size;
631 #   if $R
632         $seent{$func}*  _${func}_ptr;
633 #   endif
634 EOF
635             push @size, <<EOF;
636         /* This is the size Solaris recommends.
637          * (though we go static, should use pathconf() instead) */
638         PL_reentrant_buffer->_${func}_size = sizeof($seent{$func}) + MAXPATHLEN + 1;
639 EOF
640             push @init, <<EOF;
641         PL_reentrant_buffer->_${func}_struct = ($seent{$func}*)safemalloc(PL_reentrant_buffer->_${func}_size);
642 EOF
643             push @free, <<EOF;
644         Safefree(PL_reentrant_buffer->_${func}_struct);
645 EOF
646             pushssif $endif;
647         }
648
649         push @wrap, $ifdef;
650
651         push @wrap, <<EOF;
652 #    if defined(PERL_REENTR_API) && (PERL_REENTR_API+0 == 1)
653 #      undef $func
654 EOF
655
656         # Write out what we have learned.
657         
658         my @v = 'a'..'z';
659         my $v = join(", ", @v[0..$seenu{$func}-1]);
660         for my $p (@p) {
661             my ($r, $a) = split '_', $p;
662             my $test = $r eq 'I' ? ' == 0' : '';
663             my $true  = 1;
664             my $genfunc = $func;
665             if ($genfunc =~ /^(?:get|set|end)(pw|gr|host|net|proto|serv|sp)/) {
666                 $genfunc = "${1}ent";
667             }
668             my $b = $a;
669             my $w = '';
670             substr($b, 0, $seenu{$func}) = '';
671             if ($b =~ /R/) {
672                 $true = "PL_reentrant_buffer->_${genfunc}_ptr";
673             } elsif ($b =~ /S/) {
674                 if ($func =~ /^readdir/) {
675                     $true = "PL_reentrant_buffer->_${genfunc}_struct";
676                 } else {
677                     $true = "&PL_reentrant_buffer->_${genfunc}_struct";
678                 }
679             } elsif ($b =~ /B/) {
680                 $true = "PL_reentrant_buffer->_${genfunc}_buffer";
681             }
682             if (length $b) {
683                 $w = join ", ",
684                    map { $_ eq 'R'
685                          ?  "&PL_reentrant_buffer->_${genfunc}_ptr"
686                          : $_ eq 'E'
687                            ? "&PL_reentrant_buffer->_${genfunc}_errno"
688                            : $_ eq 'B'
689                              ? "PL_reentrant_buffer->_${genfunc}_buffer"
690                              : $_ =~ /^[WI]$/
691                              ? "PL_reentrant_buffer->_${genfunc}_size"
692                              : $_ eq 'H'
693                              ? "&PL_reentrant_buffer->_${genfunc}_fptr"
694                              : $_ eq 'D'
695                                ? "&PL_reentrant_buffer->_${genfunc}_data"
696                                : $_ eq 'S'
697                                  ? ($func =~ /^readdir\d*$/
698                                    ? "PL_reentrant_buffer->_${genfunc}_struct"
699                                    : $func =~ /^crypt$/
700                                      ? "PL_reentrant_buffer->_${genfunc}_struct_buffer"
701                                      : "&PL_reentrant_buffer->_${genfunc}_struct")
702                                  : $_
703                        } split '', $b;
704                 $w = ", $w" if length $v;
705             }
706
707             # This needs a special case, see its definition in config.h
708             my $setup = ($func eq 'localtime') ? "L_R_TZSET " : "";
709
710             my $call = "$setup${func}_r($v$w)";
711
712             # Must make OpenBSD happy
713             my $memzero = '';
714             if($p =~ /D$/ &&
715                 ($genfunc eq 'protoent' || $genfunc eq 'servent')) {
716                 $memzero = 'REENTR_MEMZERO(&PL_reentrant_buffer->_' . $genfunc . '_data, sizeof(PL_reentrant_buffer->_' . $genfunc . '_data)),';
717             }
718             push @wrap, <<EOF;
719 #      if !defined($func) && ${FUNC}_R_PROTO == REENTRANT_PROTO_$p
720 EOF
721             if ($r eq 'V' || $r eq 'B') {
722                 push @wrap, <<EOF;
723 #        define $func($v) $call
724 EOF
725             } else {
726                 if ($func =~ /^get/) {
727                     my $rv = $v ? ", $v" : "";
728                     if ($r eq 'I') {
729                         push @wrap, <<EOF;
730 #        define $func($v) ($memzero(PL_reentrant_retint = $call)$test ? $true : ((PL_reentrant_retint == ERANGE) ? ($seent{$func} *) Perl_reentrant_retry("$func"$rv) : 0))
731 EOF
732                     } else {
733                         push @wrap, <<EOF;
734 #        define $func($v) ($call$test ? $true : ((errno == ERANGE) ? ($seent{$func} *) Perl_reentrant_retry("$func"$rv) : 0))
735 EOF
736                     }
737                 } else {
738                     push @wrap, <<EOF;
739 #        define $func($v) ($call$test ? $true : 0)
740 EOF
741                 }
742             }
743             push @wrap, <<EOF;  #  !defined(xxx) && XXX_R_PROTO == REENTRANT_PROTO_Y_TS
744 #      endif
745 EOF
746         }
747                     push @wrap, <<EOF;
748 #      if defined($func)
749 #        define PERL_REENTR_USING_${FUNC}_R
750 #      endif
751 EOF
752
753             push @wrap, <<EOF;  #  defined(PERL_REENTR_API) && (PERL_REENTR_API+0 == 1)
754 #    endif
755 EOF
756
757         push @wrap, $endif, "\n";
758     }
759 }
760
761 local $" = '';
762
763 print $h <<EOF;
764
765 /* Defines for indicating which special features are supported. */
766
767 @define
768 typedef struct {
769
770 @struct
771     int dummy; /* cannot have empty structs */
772 } REENTR;
773
774 /* The wrappers. */
775
776 @wrap
777
778 /* Special case this; if others came along, could automate it */
779 #  ifdef HAS_GETSPNAM_R
780 #    define KEY_getspnam -1
781 #  endif
782
783 #endif /* USE_REENTRANT_API */
784
785 #endif
786 EOF
787
788 read_only_bottom_close_and_rename($h);
789
790 # Prepare to write the reentr.c.
791
792 my $c = open_print_header('reentr.c', <<'EOQ');
793  */
794
795 /*
796  * "Saruman," I said, standing away from him, "only one hand at a time can
797  *  wield the One, and you know that well, so do not trouble to say we!"
798  *
799  *     [p.260 of _The Lord of the Rings_, II/ii: "The Council of Elrond"]
800  */
801
802 /*
803  * This file contains a collection of automatically created wrappers
804  * (created by running reentr.pl) for reentrant (thread-safe) versions of
805  * various library calls, such as getpwent_r.  The wrapping is done so
806  * that other files like pp_sys.c calling those library functions need not
807  * care about the differences between various platforms' idiosyncrasies
808  * regarding these reentrant interfaces.
809  */
810 EOQ
811
812 print $c <<"EOF";
813 #include "EXTERN.h"
814 #define PERL_IN_REENTR_C
815 #include "perl.h"
816 #include "reentr.h"
817 #include "keywords.h"
818
819 #define RenewDouble(data_pointer, size_pointer, type) \\
820     STMT_START { \\
821         const size_t size = MAX(*(size_pointer), 1) * 2; \\
822         Renew((data_pointer), (size), type); \\
823         *(size_pointer) = size; \\
824     } STMT_END
825
826 void
827 Perl_reentrant_size(pTHX) {
828         PERL_UNUSED_CONTEXT;
829
830         /* Set the sizes of the reentrant buffers */
831
832 #ifdef USE_REENTRANT_API
833 #  define REENTRANTSMALLSIZE     256    /* Make something up. */
834 #  define REENTRANTUSUALSIZE    4096    /* Make something up. */
835
836 @size
837 #endif /* USE_REENTRANT_API */
838
839 }
840
841 void
842 Perl_reentrant_init(pTHX) {
843         PERL_UNUSED_CONTEXT;
844
845         /* Initialize the whole thing */
846
847 #ifdef USE_REENTRANT_API
848
849         Newx(PL_reentrant_buffer, 1, REENTR);
850         Perl_reentrant_size(aTHX);
851
852 @init
853 #endif /* USE_REENTRANT_API */
854
855 }
856
857 void
858 Perl_reentrant_free(pTHX) {
859         PERL_UNUSED_CONTEXT;
860
861         /* Tear down */
862
863 #ifdef USE_REENTRANT_API
864
865 @free
866         Safefree(PL_reentrant_buffer);
867
868 #endif /* USE_REENTRANT_API */
869 }
870
871 void*
872 Perl_reentrant_retry(const char *f, ...)
873 {
874     /* This function is set up to be called if the normal function returns
875      * failure with errno ERANGE, which indicates the buffer is too small.
876      * This function calls the failing one again with a larger buffer.
877      *
878      * What has happened is that, due to the magic of C preprocessor macro
879      * expansion, when the original code called function 'foo(args)', it was
880      * instead compiled into something like a call of 'foo_r(args, buffer)'
881      * Below we retry with 'foo', but the preprocessor has changed that into
882      * 'foo_r', so this function will end up calling itself recursively, each
883      * time with a larger buffer.  If PERL_REENTRANT_MAXSIZE is defined, it
884      * won't increase beyond that, instead failing. */
885
886     void *retptr = NULL;
887     va_list ap;
888
889     I32 key = 0;
890
891 #ifdef USE_REENTRANT_API
892
893     dTHX;
894
895     key = Perl_keyword (aTHX_ f, strlen(f), FALSE /* not feature enabled */);
896
897     /* Easier to special case this here than in embed.pl. (Look at what it
898        generates for proto.h) */
899     PERL_ARGS_ASSERT_REENTRANT_RETRY;
900
901 #endif
902
903     if (key == 0) {
904
905 #ifdef HAS_GETSPNAM_R
906
907         /* This is a #define as has no corresponding keyword */
908         if (strEQ(f, "getspnam")) {
909             key = KEY_getspnam;
910         }
911
912 #endif
913
914     }
915     else if (key < 0) {
916         key = -key;
917     }
918
919     va_start(ap, f);
920
921 #ifdef USE_REENTRANT_API
922
923     switch (key) {
924
925 #  ifdef USE_HOSTENT_BUFFER
926
927     case KEY_gethostbyaddr:
928     case KEY_gethostbyname:
929     case KEY_endhostent:
930         {
931             char * host_addr;
932             Size_t asize;
933             char * host_name;
934             int anint;
935
936 #    ifdef PERL_REENTRANT_MAXSIZE
937             if (PL_reentrant_buffer->_hostent_size <=
938                 PERL_REENTRANT_MAXSIZE / 2)
939 #    endif
940             RenewDouble(PL_reentrant_buffer->_hostent_buffer,
941                     &PL_reentrant_buffer->_hostent_size, char);
942             switch (key) {
943                 case KEY_gethostbyaddr:
944                     host_addr = va_arg(ap, char *);
945                     asize = va_arg(ap, Size_t);
946                     anint  = va_arg(ap, int);
947                     /* socklen_t is what Posix 2001 says this should be */
948                     retptr = gethostbyaddr(host_addr, (socklen_t) asize, anint); break;
949                 case KEY_gethostbyname:
950                     host_name = va_arg(ap, char *);
951                     retptr = gethostbyname(host_name); break;
952                 case KEY_endhostent:
953                     retptr = gethostent(); break;
954                 default:
955                     SETERRNO(ERANGE, LIB_INVARG);
956                     break;
957             }
958         }
959         break;
960
961 #  endif
962 #  ifdef USE_GRENT_BUFFER
963
964     case KEY_getgrent:
965     case KEY_getgrgid:
966     case KEY_getgrnam:
967         {
968             char * name;
969             Gid_t gid;
970
971 #    ifdef PERL_REENTRANT_MAXSIZE
972             if (PL_reentrant_buffer->_grent_size <=
973                 PERL_REENTRANT_MAXSIZE / 2)
974 #    endif
975             RenewDouble(PL_reentrant_buffer->_grent_buffer,
976                     &PL_reentrant_buffer->_grent_size, char);
977             switch (key) {
978                 case KEY_getgrnam:
979                     name = va_arg(ap, char *);
980                     retptr = getgrnam(name); break;
981                 case KEY_getgrgid:
982 #    if Gid_t_size < INTSIZE
983                     gid = (Gid_t)va_arg(ap, int);
984 #    else
985                     gid = va_arg(ap, Gid_t);
986 #    endif
987                     retptr = getgrgid(gid); break;
988                 case KEY_getgrent:
989                     retptr = getgrent(); break;
990                 default:
991                     SETERRNO(ERANGE, LIB_INVARG);
992                     break;
993             }
994         }
995         break;
996
997 #  endif
998 #  ifdef USE_NETENT_BUFFER
999
1000     case KEY_getnetbyaddr:
1001     case KEY_getnetbyname:
1002     case KEY_getnetent:
1003         {
1004             char * name;
1005             Netdb_net_t net;
1006             int anint;
1007
1008 #    ifdef PERL_REENTRANT_MAXSIZE
1009             if (PL_reentrant_buffer->_netent_size <=
1010                 PERL_REENTRANT_MAXSIZE / 2)
1011 #    endif
1012             RenewDouble(PL_reentrant_buffer->_netent_buffer,
1013                     &PL_reentrant_buffer->_netent_size, char);
1014             switch (key) {
1015                 case KEY_getnetbyaddr:
1016                     net = va_arg(ap, Netdb_net_t);
1017                     anint = va_arg(ap, int);
1018                     retptr = getnetbyaddr(net, anint); break;
1019                 case KEY_getnetbyname:
1020                     name = va_arg(ap, char *);
1021                     retptr = getnetbyname(name); break;
1022                 case KEY_getnetent:
1023                     retptr = getnetent(); break;
1024                 default:
1025                     SETERRNO(ERANGE, LIB_INVARG);
1026                     break;
1027             }
1028         }
1029         break;
1030
1031 #  endif
1032 #  ifdef USE_PWENT_BUFFER
1033
1034     case  KEY_getpwnam:
1035     case  KEY_getpwuid:
1036     case  KEY_getpwent:
1037         {
1038             Uid_t uid;
1039             char * name;
1040
1041 #    ifdef PERL_REENTRANT_MAXSIZE
1042             if (PL_reentrant_buffer->_pwent_size <=
1043                 PERL_REENTRANT_MAXSIZE / 2)
1044
1045 #    endif
1046             RenewDouble(PL_reentrant_buffer->_pwent_buffer,
1047                     &PL_reentrant_buffer->_pwent_size, char);
1048             switch (key) {
1049                 case KEY_getpwnam:
1050                     name = va_arg(ap, char *);
1051                     retptr = getpwnam(name); break;
1052                 case KEY_getpwuid:
1053
1054 #    if Uid_t_size < INTSIZE
1055                     uid = (Uid_t)va_arg(ap, int);
1056 #    else
1057                     uid = va_arg(ap, Uid_t);
1058 #    endif
1059                     retptr = getpwuid(uid); break;
1060
1061 #  if defined(HAS_GETPWENT) || defined(HAS_GETPWENT_R)
1062
1063                 case KEY_getpwent:
1064                     retptr = getpwent(); break;
1065 #  endif
1066                 default:
1067                     SETERRNO(ERANGE, LIB_INVARG);
1068                     break;
1069             }
1070         }
1071         break;
1072
1073 #  endif
1074 #  ifdef USE_SPENT_BUFFER
1075
1076     case KEY_getspnam:
1077         {
1078             char * name;
1079
1080 #    ifdef PERL_REENTRANT_MAXSIZE
1081             if (PL_reentrant_buffer->_spent_size <=
1082                 PERL_REENTRANT_MAXSIZE / 2)
1083
1084 #    endif
1085             RenewDouble(PL_reentrant_buffer->_spent_buffer,
1086                     &PL_reentrant_buffer->_spent_size, char);
1087             switch (key) {
1088                 case KEY_getspnam:
1089                     name = va_arg(ap, char *);
1090                     retptr = getspnam(name); break;
1091                 default:
1092                     SETERRNO(ERANGE, LIB_INVARG);
1093                     break;
1094             }
1095         }
1096         break;
1097
1098 #  endif
1099 #  ifdef USE_PROTOENT_BUFFER
1100
1101     case KEY_getprotobyname:
1102     case KEY_getprotobynumber:
1103     case KEY_getprotoent:
1104         {
1105             char * name;
1106             int anint;
1107
1108 #    ifdef PERL_REENTRANT_MAXSIZE
1109             if (PL_reentrant_buffer->_protoent_size <=
1110                 PERL_REENTRANT_MAXSIZE / 2)
1111 #    endif
1112             RenewDouble(PL_reentrant_buffer->_protoent_buffer,
1113                     &PL_reentrant_buffer->_protoent_size, char);
1114             switch (key) {
1115                 case KEY_getprotobyname:
1116                     name = va_arg(ap, char *);
1117                     retptr = getprotobyname(name); break;
1118                 case KEY_getprotobynumber:
1119                     anint = va_arg(ap, int);
1120                     retptr = getprotobynumber(anint); break;
1121                 case KEY_getprotoent:
1122                     retptr = getprotoent(); break;
1123                 default:
1124                     SETERRNO(ERANGE, LIB_INVARG);
1125                     break;
1126             }
1127         }
1128         break;
1129
1130 #  endif
1131 #  ifdef USE_SERVENT_BUFFER
1132
1133     case KEY_getservbyname:
1134     case KEY_getservbyport:
1135     case KEY_getservent:
1136         {
1137             char * name;
1138             char * proto;
1139             int anint;
1140
1141 #    ifdef PERL_REENTRANT_MAXSIZE
1142             if (PL_reentrant_buffer->_servent_size <=
1143                 PERL_REENTRANT_MAXSIZE / 2)
1144 #    endif
1145             RenewDouble(PL_reentrant_buffer->_servent_buffer,
1146                     &PL_reentrant_buffer->_servent_size, char);
1147             switch (key) {
1148                 case KEY_getservbyname:
1149                     name = va_arg(ap, char *);
1150                     proto = va_arg(ap, char *);
1151                     retptr = getservbyname(name, proto); break;
1152                 case KEY_getservbyport:
1153                     anint = va_arg(ap, int);
1154                     name = va_arg(ap, char *);
1155                     retptr = getservbyport(anint, name); break;
1156                 case KEY_getservent:
1157                     retptr = getservent(); break;
1158                 default:
1159                     SETERRNO(ERANGE, LIB_INVARG);
1160                     break;
1161             }
1162         }
1163         break;
1164
1165 #  endif
1166
1167     default:
1168         /* Not known how to retry, so just fail. */
1169         break;
1170     }
1171
1172 #else
1173
1174     PERL_UNUSED_ARG(f);
1175
1176 #endif
1177
1178     va_end(ap);
1179     return retptr;
1180 }
1181 EOF
1182
1183 read_only_bottom_close_and_rename($c);
1184
1185 # As of March 2020, the config.h entries that have reentrant prototypes that
1186 # aren't in this file are:
1187 #       drand48
1188 #       random
1189 #       srand48
1190 #       srandom
1191
1192 # The meanings of the flags are derivable from %map above
1193 # Fnc, arg flags| hdr   | ? struct type | prototypes...
1194 __DATA__
1195 asctime S       |time   |const struct tm|B_SB|B_SBI|I_SB|I_SBI
1196 crypt CC        |crypt  |struct crypt_data|B_CCS|B_CCD|D=CRYPTD*
1197 ctermid B       |stdio  |               |B_B
1198 ctime S         |time   |const time_t   |B_SB|B_SBI|I_SB|I_SBI
1199 endgrent        |grp    |               |I_H|V_H
1200 endhostent      |netdb  |               |I_D|V_D|D=struct hostent_data*
1201 endnetent       |netdb  |               |I_D|V_D|D=struct netent_data*
1202 endprotoent     |netdb  |               |I_D|V_D|D=struct protoent_data*
1203 endpwent        |pwd    |               |I_H|V_H
1204 endservent      |netdb  |               |I_D|V_D|D=struct servent_data*
1205 getgrent        |grp    |struct group   |I_SBWR|I_SBIR|S_SBW|S_SBI|I_SBI|I_SBIH
1206 getgrgid T      |grp    |struct group   |I_TSBWR|I_TSBIR|I_TSBI|S_TSBI|T=gid_t
1207 getgrnam C      |grp    |struct group   |I_CSBWR|I_CSBIR|S_CBI|I_CSBI|S_CSBI
1208 gethostbyaddr CWI       |netdb  |struct hostent |I_CWISBWRE|S_CWISBWIE|S_CWISBIE|S_TWISBIE|S_CIISBIE|S_CSBIE|S_TSBIE|I_CWISD|I_CIISD|I_CII|I_TsISBWRE|D=struct hostent_data*|T=const void*|s=socklen_t
1209 gethostbyname C |netdb  |struct hostent |I_CSBWRE|S_CSBIE|I_CSD|D=struct hostent_data*
1210 gethostent      |netdb  |struct hostent |I_SBWRE|I_SBIE|S_SBIE|S_SBI|I_SBI|I_SD|D=struct hostent_data*
1211 getlogin        |unistd |char           |I_BW|I_BI|B_BW|B_BI
1212 getnetbyaddr LI |netdb  |struct netent  |I_UISBWRE|I_LISBI|S_TISBI|S_LISBI|I_TISD|I_LISD|I_IISD|I_uISBWRE|D=struct netent_data*|T=in_addr_t|U=unsigned long|u=uint32_t
1213 getnetbyname C  |netdb  |struct netent  |I_CSBWRE|I_CSBI|S_CSBI|I_CSD|D=struct netent_data*
1214 getnetent       |netdb  |struct netent  |I_SBWRE|I_SBIE|S_SBIE|S_SBI|I_SBI|I_SD|D=struct netent_data*
1215 getprotobyname C|netdb  |struct protoent|I_CSBWR|S_CSBI|I_CSD|D=struct protoent_data*
1216 getprotobynumber I      |netdb  |struct protoent|I_ISBWR|S_ISBI|I_ISD|D=struct protoent_data*
1217 getprotoent     |netdb  |struct protoent|I_SBWR|I_SBI|S_SBI|I_SD|D=struct protoent_data*
1218 getpwent        |pwd    |struct passwd  |I_SBWR|I_SBIR|S_SBW|S_SBI|I_SBI|I_SBIH
1219 getpwnam C      |pwd    |struct passwd  |I_CSBWR|I_CSBIR|S_CSBI|I_CSBI
1220 getpwuid T      |pwd    |struct passwd  |I_TSBWR|I_TSBIR|I_TSBI|S_TSBI|T=uid_t
1221 getservbyname CC|netdb  |struct servent |I_CCSBWR|S_CCSBI|I_CCSD|D=struct servent_data*
1222 getservbyport IC|netdb  |struct servent |I_ICSBWR|S_ICSBI|I_ICSD|D=struct servent_data*
1223 getservent      |netdb  |struct servent |I_SBWR|I_SBI|S_SBI|I_SD|D=struct servent_data*
1224 getspnam C      |shadow |struct spwd    |I_CSBWR|S_CSBI
1225 gmtime T        |time   |struct tm      |S_TS|T=time_t*
1226 localtime T     |time   |struct tm      |S_TS|T=time_t*
1227 readdir T       |dirent |struct dirent  |I_TSR|I_TS|T=DIR*
1228 readdir64 T     |dirent |struct dirent64|I_TSR|I_TS|T=DIR*
1229 setgrent        |grp    |               |I_H|V_H
1230 sethostent I    |netdb  |               |I_ID|V_ID|D=struct hostent_data*
1231 setlocale IC    |locale |               |I_ICBI
1232 setnetent I     |netdb  |               |I_ID|V_ID|D=struct netent_data*
1233 setprotoent I   |netdb  |               |I_ID|V_ID|D=struct protoent_data*
1234 setpwent        |pwd    |               |I_H|V_H
1235 setservent I    |netdb  |               |I_ID|V_ID|D=struct servent_data*
1236 strerror I      |string |               |I_IBW|I_IBI|B_IBW
1237 tmpnam B        |stdio  |               |B_B
1238 ttyname I       |unistd |               |I_IBW|I_IBI|B_IBI