1#!./perl
2
3BEGIN {
4    require Config; import Config;
5    if ($^O ne 'VMS' and $Config{'extensions'} !~ /\bPOSIX\b/) {
6	print "1..0\n";
7	exit 0;
8    }
9    unshift @INC, "../../t";
10    require 'loc_tools.pl';
11}
12
13use Test::More tests => 96;
14
15use POSIX qw(fcntl_h signal_h limits_h _exit getcwd open read strftime write
16	     errno localeconv dup dup2 lseek access);
17use strict 'subs';
18
19sub next_test {
20    my $builder = Test::More->builder;
21    $builder->current_test($builder->current_test() + 1);
22}
23
24$| = 1;
25
26$Is_W32     = $^O eq 'MSWin32';
27$Is_Dos     = $^O eq 'dos';
28$Is_VMS     = $^O eq 'VMS';
29$Is_OS2     = $^O eq 'os2';
30$Is_UWin    = $^O eq 'uwin';
31$Is_OS390   = $^O eq 'os390';
32
33my $vms_unix_rpt = 0;
34my $vms_efs = 0;
35my $unix_mode = 1;
36
37if ($Is_VMS) {
38    $unix_mode = 0;
39    if (eval 'require VMS::Feature') {
40        $vms_unix_rpt = VMS::Feature::current("filename_unix_report");
41        $vms_efs = VMS::Feature::current("efs_charset");
42    } else {
43        my $unix_rpt = $ENV{'DECC$FILENAME_UNIX_REPORT'} || '';
44        my $efs_charset = $ENV{'DECC$EFS_CHARSET'} || '';
45        $vms_unix_rpt = $unix_rpt =~ /^[ET1]/i;
46        $vms_efs = $efs_charset =~ /^[ET1]/i;
47    }
48
49    # Traditional VMS mode only if VMS is not in UNIX compatible mode.
50    $unix_mode = ($vms_efs && $vms_unix_rpt);
51
52}
53
54my $testfd = open("Makefile.PL", O_RDONLY, 0);
55like($testfd, qr/\A\d+\z/, 'O_RDONLY with open');
56read($testfd, $buffer, 4) if $testfd > 2;
57is( $buffer, "# Ex",                      '    with read' );
58
59TODO:
60{
61    local $TODO = "read to array element not working";
62
63    read($testfd, $buffer[1], 5) if $testfd > 2;
64    is( $buffer[1], "perl\n",	               '    read to array element' );
65}
66
67my $test = next_test();
68write(1,"ok $test\nnot ok $test\n", 5);
69
70SKIP: {
71    skip("no pipe() support on DOS", 2) if $Is_Dos;
72
73    @fds = POSIX::pipe();
74    cmp_ok($fds[0], '>', $testfd, 'POSIX::pipe');
75
76    CORE::open($reader = \*READER, "<&=".$fds[0]);
77    CORE::open($writer = \*WRITER, ">&=".$fds[1]);
78    my $test = next_test();
79    print $writer "ok $test\n";
80    close $writer;
81    print <$reader>;
82    close $reader;
83}
84
85SKIP: {
86    skip("no sigaction support on win32/dos", 6) if $Is_W32 || $Is_Dos;
87
88    my $sigset = new POSIX::SigSet 1, 3;
89    $sigset->delset(1);
90    ok(! $sigset->ismember(1),  'POSIX::SigSet->delset' );
91    ok(  $sigset->ismember(3),  'POSIX::SigSet->ismember' );
92
93    my $sigint_called = 0;
94
95    my $mask   = new POSIX::SigSet &SIGINT;
96    my $action = new POSIX::SigAction 'main::SigHUP', $mask, 0;
97    sigaction(&SIGHUP, $action);
98    $SIG{'INT'} = 'SigINT';
99
100    # At least OpenBSD/i386 3.3 is okay, as is NetBSD 1.5.
101    # But not NetBSD 1.6 & 1.6.1: the test makes perl crash.
102    # So the kill() must not be done with this config in order to
103    # finish the test.
104    # For others (darwin & freebsd), let the test fail without crashing.
105    # the test passes at least from freebsd 8.1
106    my $todo = $^O eq 'netbsd' && $Config{osvers}=~/^1\.6/;
107    my $why_todo = "# TODO $^O $Config{osvers} seems to lose blocked signals";
108    if (!$todo) {
109      kill 'HUP', $$;
110    } else {
111      print "not ok 9 - sigaction SIGHUP ",$why_todo,"\n";
112      print "not ok 10 - sig mask delayed SIGINT ",$why_todo,"\n";
113    }
114    sleep 1;
115
116    $todo = 1 if ($^O eq 'freebsd' && $Config{osvers} < 8)
117              || ($^O eq 'darwin' && $Config{osvers} < '6.6');
118    printf "%s 11 - masked SIGINT received %s\n",
119        $sigint_called ? "ok" : "not ok",
120        $todo ? $why_todo : '';
121
122    print "ok 12 - signal masks successful\n";
123
124    sub SigHUP {
125        print "ok 9 - sigaction SIGHUP\n";
126        kill 'INT', $$;
127        sleep 2;
128        print "ok 10 - sig mask delayed SIGINT\n";
129    }
130
131    sub SigINT {
132        $sigint_called++;
133    }
134
135    # The order of the above tests is very important, so
136    # we use literal prints and hard coded numbers.
137    next_test() for 1..4;
138}
139
140SKIP: {
141    skip("_POSIX_OPEN_MAX undefined ($fds[1])",  1) unless &_POSIX_OPEN_MAX;
142
143    cmp_ok(&_POSIX_OPEN_MAX, '>=', 16,
144	   "The minimum allowed values according to susv2" );
145
146}
147
148my $pat;
149if ( $unix_mode ) {
150    $pat = qr#[\\/]POSIX$#i;
151}
152else {
153    $pat = qr/\.POSIX\]/i;
154}
155like( getcwd(), qr/$pat/, 'getcwd' );
156
157# Check string conversion functions.
158my $weasel_words = "(though differences may be beyond the displayed digits)";
159
160SKIP: {
161    skip("strtod() not present", 3) unless $Config{d_strtod};
162
163    if (locales_enabled('LC_NUMERIC')) {
164        $lc = &POSIX::setlocale(&POSIX::LC_NUMERIC);
165        &POSIX::setlocale(&POSIX::LC_NUMERIC, 'C');
166    }
167
168    # we're just checking that strtod works, not how accurate it is
169    ($n, $x) = &POSIX::strtod('3.14159_OR_SO');
170    cmp_ok(abs("3.14159" - $n), '<', 1e-6, 'strtod works');
171    is($x, 6, 'strtod works');
172
173    # If $Config{nvtype} is 'double' we check that strtod assigns the same value as
174    # perl for the input 8.87359152e-6.
175    # We check that value as it is known to have produced discrepancies in the past.
176    # If this check fails then perl's buggy atof has probably assigned the value,
177    # instead of the preferred Perl_strtod function.
178
179    $n = &POSIX::strtod('8.87359152e-6');
180    if($Config{nvtype} eq 'double' || ($Config{nvtype} eq 'long double' && $Config{longdblkind} == 0)) {
181      cmp_ok($n, '==', 8.87359152e-6, "strtod and perl agree $weasel_words");
182    }
183    else {
184      cmp_ok($n, '!=', 8.87359152e-6, "strtod and perl should differ $weasel_words");
185    }
186
187    &POSIX::setlocale(&POSIX::LC_NUMERIC, $lc) if locales_enabled('LC_NUMERIC');
188}
189
190SKIP: {
191    skip("strtold() not present", 3) unless $Config{d_strtold};
192
193    if (locales_enabled('LC_NUMERIC')) {
194        $lc = &POSIX::setlocale(&POSIX::LC_NUMERIC);
195        &POSIX::setlocale(&POSIX::LC_NUMERIC, 'C');
196    }
197
198    # we're just checking that strtold works, not how accurate it is
199    ($n, $x) = &POSIX::strtold('2.718_ISH');
200    cmp_ok(abs("2.718" - $n), '<', 1e-6, 'strtold works');
201    is($x, 4, 'strtold works');
202
203    # If $Config{nvtype} is 'long double' we check that strtold assigns the same value as
204    # perl for the input 9.81256119e4.
205    # We check that value as it is known to have produced discrepancies in the past.
206    # If this check fails then perl's buggy atof has probably assigned the value,
207    # instead of the preferred Perl_strtod function.
208
209    if($Config{nvtype} eq 'long double') {
210      $n = &POSIX::strtold('9.81256119e4820');
211      cmp_ok($n, '==', 9.81256119e4820, "strtold and perl agree $weasel_words");
212    }
213    elsif($Config{nvtype} eq '__float128') {
214      $n = &POSIX::strtold('9.81256119e4820');
215      if($Config{longdblkind} == 1 || $Config{longdblkind} == 2) {
216        cmp_ok($n, '==', 9.81256119e4820, "strtold and perl agree $weasel_words");
217      }
218      else {
219        cmp_ok($n, '!=', 9.81256119e4820, "strtold and perl should differ $weasel_words");
220      }
221    }
222    else { # nvtype is double ... don't try and make this into a meaningful test
223      cmp_ok(1, '==', 1, 'skipping comparison between strtold amd perl');
224    }
225
226    &POSIX::setlocale(&POSIX::LC_NUMERIC, $lc) if locales_enabled('LC_NUMERIC');
227}
228
229SKIP: {
230    # We don't yet have a POSIX::strtoflt128 - but let's at least check that
231    # Perl_strtod, not perl's atof, is assigning the values on quadmath builds.
232    # Do this by checking that 3329232e296 (which is known to be assigned
233    # incorrectly by perl's atof) is assigned to its correct value.
234
235    skip("not a -Dusequadmath build", 1) unless $Config{nvtype} eq '__float128';
236    cmp_ok(scalar(reverse(unpack("h*", pack("F<", 3329232e296)))),
237           'eq','43ebf120d02ce967d48e180409b3f958',
238           '3329232e296 is assigned correctly');
239}
240
241SKIP: {
242    skip("strtol() not present", 2) unless $Config{d_strtol};
243
244    ($n, $x) = &POSIX::strtol('21_PENGUINS');
245    is($n, 21, 'strtol() number');
246    is($x, 9,  '         unparsed chars');
247}
248
249SKIP: {
250    skip("strtoul() not present", 2) unless $Config{d_strtoul};
251
252    ($n, $x) = &POSIX::strtoul('88_TEARS');
253    is($n, 88, 'strtoul() number');
254    is($x, 6,  '          unparsed chars');
255}
256
257# Pick up whether we're really able to dynamically load everything.
258cmp_ok(&POSIX::acos(1.0), '==', 0.0, 'dynamic loading');
259
260# This can coredump if struct tm has a timezone field and we
261# didn't detect it.  If this fails, try adding
262# -DSTRUCT_TM_HASZONE to your cflags when compiling ext/POSIX/POSIX.c.
263# See ext/POSIX/hints/sunos_4.pl and ext/POSIX/hints/linux.pl
264$test = next_test();
265print POSIX::strftime("ok $test # %H:%M, on %m/%d/%y\n", localtime());
266
267# If that worked, validate the mini_mktime() routine's normalisation of
268# input fields to strftime().
269sub try_strftime {
270    my $expect = shift;
271    my $got = POSIX::strftime("%a %b %d %H:%M:%S %Y %j", @_);
272    is($got, $expect, "validating mini_mktime() and strftime(): $expect");
273}
274
275if (locales_enabled('LC_TIME')) {
276    $lc = &POSIX::setlocale(&POSIX::LC_TIME);
277    &POSIX::setlocale(&POSIX::LC_TIME, 'C');
278}
279
280try_strftime("Wed Feb 28 00:00:00 1996 059", 0,0,0, 28,1,96);
281SKIP: {
282    skip("VC++ 8 and Vista's CRTs regard 60 seconds as an invalid parameter", 1)
283	if ($Is_W32
284	    and (($Config{cc} eq 'cl' and
285		    $Config{ccversion} =~ /^(\d+)/ and $1 >= 14)
286		or ($Config{cc} eq 'icl' and
287		    `cl --version 2>&1` =~ /^.*Version\s+([\d.]+)/ and $1 >= 14)
288		or (Win32::GetOSVersion())[1] >= 6));
289
290    try_strftime("Thu Feb 29 00:00:60 1996 060", 60,0,-24, 30,1,96);
291}
292try_strftime("Fri Mar 01 00:00:00 1996 061", 0,0,-24, 31,1,96);
293try_strftime("Sun Feb 28 00:00:00 1999 059", 0,0,0, 28,1,99);
294try_strftime("Mon Mar 01 00:00:00 1999 060", 0,0,24, 28,1,99);
295try_strftime("Mon Feb 28 00:00:00 2000 059", 0,0,0, 28,1,100);
296try_strftime("Tue Feb 29 00:00:00 2000 060", 0,0,0, 0,2,100);
297try_strftime("Wed Mar 01 00:00:00 2000 061", 0,0,0, 1,2,100);
298try_strftime("Fri Mar 31 00:00:00 2000 091", 0,0,0, 31,2,100);
299
300{ # rt 72232
301
302  # Std C/POSIX allows day/month to be negative and requires that
303  # wday/yday be adjusted as needed
304  # previously mini_mktime() would allow yday to dominate if mday and
305  # month were both non-positive
306  # check that yday doesn't dominate
307  try_strftime("Thu Dec 30 00:00:00 1999 364", 0,0,0, -1,0,100);
308  try_strftime("Thu Dec 30 00:00:00 1999 364", 0,0,0, -1,0,100,-1,10);
309  # it would also allow a positive wday to override the calculated value
310  # check that wday is recalculated too
311  try_strftime("Thu Dec 30 00:00:00 1999 364", 0,0,0, -1,0,100,0,10);
312}
313
314&POSIX::setlocale(&POSIX::LC_TIME, $lc) if locales_enabled('LC_TIME');
315
316{
317    for my $test (0, 1) {
318	$! = 0;
319	# POSIX::errno is autoloaded.
320	# Autoloading requires many system calls.
321	# errno() looks at $! to generate its result.
322	# Autoloading should not munge the value.
323	my $foo  = $!;
324	my $errno = POSIX::errno();
325
326        # Force numeric context.
327	is( $errno + 0, $foo + 0,     'autoloading and errno() mix' );
328    }
329}
330
331is (eval "kill 0", 0, "check we have CORE::kill")
332  or print "\$\@ is " . _qq($@) . "\n";
333
334# Check that we can import the POSIX kill routine
335POSIX->import ('kill');
336my $result = eval "kill 0";
337is ($result, undef, "we should now have POSIX::kill");
338# Check usage.
339like ($@, qr/^Usage: POSIX::kill\(pid, sig\)/, "check its usage message");
340
341# Check unimplemented.
342$result = eval {POSIX::offsetof};
343is ($result, undef, "offsetof should fail");
344like ($@, qr/^Unimplemented: POSIX::offsetof\(\): C-specific/,
345      "check its unimplemented message");
346
347# Check reimplemented.
348$result = eval {POSIX::fgets};
349is ($result, undef, "fgets should fail");
350like ($@, qr/^Unimplemented: POSIX::fgets\(\): Use method IO::Handle::gets\(\) instead/,
351      "check its redef message");
352
353eval { use strict; POSIX->import("S_ISBLK"); my $x = S_ISBLK };
354unlike( $@, qr/Can't use string .* as a symbol ref/, "Can import autoloaded constants" );
355
356SKIP: {
357    skip("locales not available", 26) unless locales_enabled(qw(NUMERIC MONETARY));
358    skip("localeconv() not available", 26) unless $Config{d_locconv};
359    my $conv = localeconv;
360    is(ref $conv, 'HASH', 'localeconv returns a hash reference');
361
362    foreach (qw(decimal_point thousands_sep grouping int_curr_symbol
363		currency_symbol mon_decimal_point mon_thousands_sep
364		mon_grouping positive_sign negative_sign)) {
365    SKIP: {
366	    skip("localeconv has no result for $_", 1)
367		unless exists $conv->{$_};
368	    unlike(delete $conv->{$_}, qr/\A\z/,
369		   "localeconv returned a non-empty string for $_");
370	}
371    }
372
373    my @lconv = qw(
374        int_frac_digits frac_digits
375        p_cs_precedes   p_sep_by_space
376        n_cs_precedes   n_sep_by_space
377        p_sign_posn     n_sign_posn
378    );
379
380    SKIP: {
381        skip('No HAS_LC_MONETARY_2008', 6) unless $Config{d_lc_monetary_2008};
382
383        push @lconv, qw(
384            int_p_cs_precedes int_p_sep_by_space
385            int_n_cs_precedes int_n_sep_by_space
386            int_p_sign_posn   int_n_sign_posn
387        );
388    }
389
390    foreach (@lconv) {
391    SKIP: {
392	    skip("localeconv has no result for $_", 1)
393		unless exists $conv->{$_};
394	    like(delete $conv->{$_}, qr/\A-?\d+\z/,
395		 "localeconv returned an integer for $_");
396	}
397    }
398    is_deeply([%$conv], [], 'no unexpected keys returned by localeconv');
399}
400
401my $fd1 = open("Makefile.PL", O_RDONLY, 0);
402like($fd1, qr/\A\d+\z/, 'O_RDONLY with open');
403cmp_ok($fd1, '>', $testfd);
404my $fd2 = dup($fd1);
405like($fd2, qr/\A\d+\z/, 'dup');
406cmp_ok($fd2, '>', $fd1);
407is(POSIX::close($fd1), '0 but true', 'close');
408is(POSIX::close($testfd), '0 but true', 'close');
409$! = 0;
410undef $buffer;
411is(read($fd1, $buffer, 4), undef, 'read on closed file handle fails');
412cmp_ok($!, '==', POSIX::EBADF);
413undef $buffer;
414read($fd2, $buffer, 4) if $fd2 > 2;
415is($buffer, "# Ex", 'read');
416# The descriptor $testfd was using is now free, and is lower than that which
417# $fd1 was using. Hence if dup2() behaves as dup(), we'll know :-)
418{
419    $testfd = dup2($fd2, $fd1);
420    is($testfd, $fd1, 'dup2');
421    undef $buffer;
422    read($testfd, $buffer, 4) if $testfd > 2;
423    is($buffer, 'pect', 'read');
424    is(lseek($testfd, 0, 0), 0, 'lseek back');
425    # The two should share file position:
426    undef $buffer;
427    read($fd2, $buffer, 4) if $fd2 > 2;
428    is($buffer, "# Ex", 'read');
429}
430
431# The FreeBSD man page warns:
432# The access() system call is a potential security hole due to race
433# conditions and should never be used.
434is(access('Makefile.PL', POSIX::F_OK), '0 but true', 'access');
435is(access('Makefile.PL', POSIX::R_OK), '0 but true', 'access');
436$! = 0;
437is(access('no such file', POSIX::F_OK), undef, 'access on missing file');
438cmp_ok($!, '==', POSIX::ENOENT);
439is(access('Makefile.PL/nonsense', POSIX::F_OK), undef,
440   'access on not-a-directory');
441SKIP: {
442    skip("$^O is insufficiently POSIX", 1)
443	if $Is_W32 || $Is_VMS;
444    cmp_ok($!, '==', POSIX::ENOTDIR);
445}
446
447{   # tmpnam() has been removed as unsafe
448    my $x = eval { POSIX::tmpnam() };
449    is($x, undef, 'tmpnam has been removed');
450    like($@, qr/use File::Temp/, 'tmpnam advises File::Temp');
451}
452
453# Check that output is not flushed by _exit. This test should be last
454# in the file, and is not counted in the total number of tests.
455if ($^O eq 'vos') {
456 print "# TODO - hit VOS bug posix-885 - _exit flushes output buffers.\n";
457} else {
458 $| = 0;
459 # The following line assumes buffered output, which may be not true:
460 print '@#!*$@(!@#$' unless ($Is_OS2 || $Is_UWin || $Is_OS390 ||
461                            $Is_VMS ||
462			    (defined $ENV{PERLIO} &&
463			     $ENV{PERLIO} eq 'unix' &&
464			     $Config::Config{useperlio}));
465 _exit(0);
466}
467