xref: /openbsd-src/gnu/usr.bin/perl/t/op/stat.t (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
1#!./perl
2
3BEGIN {
4    chdir 't' if -d 't';
5    @INC = '../lib';
6    require './test.pl';	# for which_perl() etc
7}
8
9use Config;
10
11my ($Null, $Curdir);
12if(eval {require File::Spec; 1}) {
13    $Null = File::Spec->devnull;
14    $Curdir = File::Spec->curdir;
15} else {
16    die $@ unless is_miniperl();
17    $Curdir = '.';
18    diag("miniperl failed to load File::Spec, error is:\n$@");
19    diag("\ncontinuing, assuming '.' for current directory. Some tests will be skipped.");
20}
21
22
23plan tests => 113;
24
25my $Perl = which_perl();
26
27$ENV{LC_ALL}   = 'C';		# Forge English error messages.
28$ENV{LANGUAGE} = 'C';		# Ditto in GNU.
29
30$Is_Amiga   = $^O eq 'amigaos';
31$Is_Cygwin  = $^O eq 'cygwin';
32$Is_Darwin  = $^O eq 'darwin';
33$Is_Dos     = $^O eq 'dos';
34$Is_MSWin32 = $^O eq 'MSWin32';
35$Is_NetWare = $^O eq 'NetWare';
36$Is_OS2     = $^O eq 'os2';
37$Is_Solaris = $^O eq 'solaris';
38$Is_VMS     = $^O eq 'VMS';
39$Is_MPRAS   = $^O =~ /svr4/ && -f '/etc/.relid';
40$Is_Android = $^O =~ /android/;
41
42$Is_Dosish  = $Is_Dos || $Is_OS2 || $Is_MSWin32 || $Is_NetWare;
43
44$Is_UFS     = $Is_Darwin && (() = `df -t ufs . 2>/dev/null`) == 2;
45
46if ($Is_Cygwin && !is_miniperl) {
47  require Win32;
48  Win32->import;
49}
50
51my($DEV, $INO, $MODE, $NLINK, $UID, $GID, $RDEV, $SIZE,
52   $ATIME, $MTIME, $CTIME, $BLKSIZE, $BLOCKS) = (0..12);
53
54my $tmpfile = tempfile();
55my $tmpfile_link = tempfile();
56
57chmod 0666, $tmpfile;
58unlink_all $tmpfile;
59open(FOO, ">$tmpfile") || DIE("Can't open temp test file: $!");
60close FOO;
61
62open(FOO, ">$tmpfile") || DIE("Can't open temp test file: $!");
63
64my($nlink, $mtime, $ctime) = (stat(FOO))[$NLINK, $MTIME, $CTIME];
65
66# The clock on a network filesystem might be different from the
67# system clock.
68my $Filesystem_Time_Offset = abs($mtime - time);
69
70#nlink should if link support configured in Perl.
71SKIP: {
72    skip "No link count - Hard link support not built in.", 1
73	unless $Config{d_link};
74
75    is($nlink, 1, 'nlink on regular file');
76}
77
78SKIP: {
79  skip "mtime and ctime not reliable", 2
80    if $Is_MSWin32 or $Is_NetWare or $Is_Cygwin or $Is_Dos or $Is_Darwin;
81
82  ok( $mtime,           'mtime' );
83  is( $mtime, $ctime,   'mtime == ctime' );
84}
85
86
87# Cygwin seems to have a 3 second granularity on its timestamps.
88my $funky_FAT_timestamps = $Is_Cygwin;
89sleep 3 if $funky_FAT_timestamps;
90
91print FOO "Now is the time for all good men to come to.\n";
92close(FOO);
93
94sleep 2;
95
96my $has_link = 1;
97my $inaccurate_atime = 0;
98if (defined &Win32::IsWinNT && Win32::IsWinNT()) {
99    if (Win32::FsType() ne 'NTFS') {
100        $has_link            = 0;
101	$inaccurate_atime    = 1;
102    }
103}
104
105SKIP: {
106    skip "No link on this filesystem", 6 unless $has_link;
107    unlink $tmpfile_link;
108    my $lnk_result = eval { link $tmpfile, $tmpfile_link };
109    skip "link() unimplemented", 6 if $@ =~ /unimplemented/;
110
111    is( $@, '',         'link() implemented' );
112    ok( $lnk_result,    'linked tmp testfile' );
113    ok( chmod(0644, $tmpfile),             'chmoded tmp testfile' );
114
115    my($nlink, $mtime, $ctime) = (stat($tmpfile))[$NLINK, $MTIME, $CTIME];
116
117    SKIP: {
118        skip "No link count", 1 if $Config{dont_use_nlink};
119        skip "Cygwin9X fakes hard links by copying", 1
120          if $Config{myuname} =~ /^cygwin_(?:9\d|me)\b/i;
121
122        is($nlink, 2,     'Link count on hard linked file' );
123    }
124
125    SKIP: {
126	skip_if_miniperl("File::Spec not built for minitest", 2);
127        my $cwd = File::Spec->rel2abs($Curdir);
128        skip "Solaris tmpfs has different mtime/ctime link semantics", 2
129                                     if $Is_Solaris and $cwd =~ m#^/tmp# and
130                                        $mtime && $mtime == $ctime;
131        skip "AFS has different mtime/ctime link semantics", 2
132                                     if $cwd =~ m#$Config{'afsroot'}/#;
133        skip "AmigaOS has different mtime/ctime link semantics", 2
134                                     if $Is_Amiga;
135        # Win32 could pass $mtime test but as FAT and NTFS have
136        # no ctime concept $ctime is ALWAYS == $mtime
137        # expect netware to be the same ...
138        skip "No ctime concept on this OS", 2
139                                     if $Is_MSWin32 ||
140                                        ($Is_Darwin && $Is_UFS);
141
142        if( !ok($mtime, 'hard link mtime') ||
143            !isnt($mtime, $ctime, 'hard link ctime != mtime') ) {
144            print STDERR <<DIAG;
145# Check if you are on a tmpfs of some sort.  Building in /tmp sometimes
146# has this problem.  Building on the ClearCase VOBS filesystem may also
147# cause this failure.
148#
149# Darwin's UFS doesn't have a ctime concept, and thus is expected to fail
150# this test.
151DIAG
152        }
153    }
154
155}
156
157# truncate and touch $tmpfile.
158open(F, ">$tmpfile") || DIE("Can't open temp test file: $!");
159ok(-z \*F,     '-z on empty filehandle');
160ok(! -s \*F,   '   and -s');
161close F;
162
163ok(-z $tmpfile,     '-z on empty file');
164ok(! -s $tmpfile,   '   and -s');
165
166open(F, ">$tmpfile") || DIE("Can't open temp test file: $!");
167print F "hi\n";
168close F;
169
170open(F, "<$tmpfile") || DIE("Can't open temp test file: $!");
171ok(!-z *F,     '-z on empty filehandle');
172ok( -s *F,   '   and -s');
173close F;
174
175ok(! -z $tmpfile,   '-z on non-empty file');
176ok(-s $tmpfile,     '   and -s');
177
178
179# Strip all access rights from the file.
180ok( chmod(0000, $tmpfile),     'chmod 0000' );
181
182SKIP: {
183    skip "-r, -w and -x have different meanings on VMS", 3 if $Is_VMS;
184
185    SKIP: {
186        # Going to try to switch away from root.  Might not work.
187        my $olduid = $>;
188        eval { $> = 1; };
189	skip "Can't test if an admin user in miniperl", 2,
190	  if $Is_Cygwin && is_miniperl();
191        skip "Can't test -r or -w meaningfully if you're superuser", 2
192          if ($Is_Cygwin ? Win32::IsAdminUser : $> == 0);
193
194        SKIP: {
195            skip "Can't test -r meaningfully?", 1 if $Is_Dos;
196            ok(!-r $tmpfile,    "   -r");
197        }
198
199        ok(!-w $tmpfile,    "   -w");
200
201        # switch uid back (may not be implemented)
202        eval { $> = $olduid; };
203    }
204
205    ok(! -x $tmpfile,   '   -x');
206}
207
208
209
210ok(chmod(0700,$tmpfile),    'chmod 0700');
211ok(-r $tmpfile,     '   -r');
212ok(-w $tmpfile,     '   -w');
213
214SKIP: {
215    skip "-x simply determines if a file ends in an executable suffix", 1
216      if $Is_Dosish;
217
218    ok(-x $tmpfile,     '   -x');
219}
220
221ok(  -f $tmpfile,   '   -f');
222ok(! -d $tmpfile,   '   !-d');
223
224# Is this portable?
225ok(  -d '.',          '-d cwd' );
226ok(! -f '.',          '!-f cwd' );
227
228
229SKIP: {
230    unlink($tmpfile_link);
231    my $symlink_rslt = eval { symlink $tmpfile, $tmpfile_link };
232    skip "symlink not implemented", 3 if $@ =~ /unimplemented/;
233
234    is( $@, '',     'symlink() implemented' );
235    ok( $symlink_rslt,      'symlink() ok' );
236    ok(-l $tmpfile_link,    '-l');
237}
238
239ok(-o $tmpfile,     '-o');
240
241ok(-e $tmpfile,     '-e');
242
243unlink($tmpfile_link);
244ok(! -e $tmpfile_link,  '   -e on unlinked file');
245
246SKIP: {
247    skip "No character, socket or block special files", 6
248      if $Is_MSWin32 || $Is_NetWare || $Is_Dos;
249    skip "/dev isn't available to test against", 6
250      unless -d '/dev' && -r '/dev' && -x '/dev';
251    skip "Skipping: unexpected ls output in MP-RAS", 6
252      if $Is_MPRAS;
253
254    # VMS problem:  If GNV or other UNIX like tool is installed, then
255    # sometimes Perl will find /bin/ls, and will try to run it.
256    # But since Perl on VMS does not know to run it under Bash, it will
257    # try to run the DCL verb LS.  And if the VMS product Language
258    # Sensitive Editor is installed, or some other LS verb, that will
259    # be run instead.  So do not do this until we can teach Perl
260    # when to use BASH on VMS.
261    skip "ls command not available to Perl in OpenVMS right now.", 6
262      if $Is_VMS;
263
264    delete $ENV{CLICOLOR_FORCE};
265    my $LS  = $Config{d_readlink} && !$Is_Android ? "ls -lL" : "ls -l";
266    my $CMD = "$LS /dev 2>/dev/null";
267    my $DEV = qx($CMD);
268
269    skip "$CMD failed", 6 if $DEV eq '';
270
271    my @DEV = do { my $dev; opendir($dev, "/dev") ? readdir($dev) : () };
272
273    skip "opendir failed: $!", 6 if @DEV == 0;
274
275    # /dev/stdout might be either character special or a named pipe,
276    # or a symlink, or a socket, depending on which OS and how are
277    # you running the test, so let's censor that one away.
278    # Similar remarks hold for stderr.
279    $DEV =~ s{^[cpls].+?\sstdout$}{}m;
280    @DEV =  grep { $_ ne 'stdout' } @DEV;
281    $DEV =~ s{^[cpls].+?\sstderr$}{}m;
282    @DEV =  grep { $_ ne 'stderr' } @DEV;
283
284    # /dev/printer is also naughty: in IRIX it shows up as
285    # Srwx-----, not srwx------.
286    $DEV =~ s{^.+?\sprinter$}{}m;
287    @DEV =  grep { $_ ne 'printer' } @DEV;
288
289    # If running as root, we will see .files in the ls result,
290    # and readdir() will see them always.  Potential for conflict,
291    # so let's weed them out.
292    $DEV =~ s{^.+?\s\..+?$}{}m;
293    @DEV =  grep { ! m{^\..+$} } @DEV;
294
295    # Irix ls -l marks sockets with 'S' while 's' is a 'XENIX semaphore'.
296    if ($^O eq 'irix') {
297        $DEV =~ s{^S(.+?)}{s$1}mg;
298    }
299
300    my $try = sub {
301	my @c1 = eval qq[\$DEV =~ /^$_[0].*/mg];
302	my @c2 = eval qq[grep { $_[1] "/dev/\$_" } \@DEV];
303	my $c1 = scalar @c1;
304	my $c2 = scalar @c2;
305	is($c1, $c2, "ls and $_[1] agreeing on /dev ($c1 $c2)");
306    };
307
308{
309    $try->('b', '-b');
310    $try->('c', '-c');
311    $try->('s', '-S');
312}
313
314ok(! -b $Curdir,    '!-b cwd');
315ok(! -c $Curdir,    '!-c cwd');
316ok(! -S $Curdir,    '!-S cwd');
317
318}
319
320SKIP: {
321    my($cnt, $uid);
322    $cnt = $uid = 0;
323
324    # Find a set of directories that's very likely to have setuid files
325    # but not likely to be *all* setuid files.
326    my @bin = grep {-d && -r && -x} qw(/sbin /usr/sbin /bin /usr/bin);
327    skip "Can't find a setuid file to test with", 3 unless @bin;
328
329    for my $bin (@bin) {
330        opendir BIN, $bin or die "Can't opendir $bin: $!";
331        while (defined($_ = readdir BIN)) {
332            $_ = "$bin/$_";
333            $cnt++;
334            $uid++ if -u;
335            last if $uid && $uid < $cnt;
336        }
337    }
338    closedir BIN;
339
340    skip "No setuid programs", 3 if $uid == 0;
341
342    isnt($cnt, 0,    'found some programs');
343    isnt($uid, 0,    '  found some setuid programs');
344    ok($uid < $cnt,  "    they're not all setuid");
345}
346
347
348# To assist in automated testing when a controlling terminal (/dev/tty)
349# may not be available (at, cron  rsh etc), the PERL_SKIP_TTY_TEST env var
350# can be set to skip the tests that need a tty.
351SKIP: {
352    skip "These tests require a TTY", 4 if $ENV{PERL_SKIP_TTY_TEST};
353
354    my $TTY = "/dev/tty";
355
356    SKIP: {
357        skip "Test uses unixisms", 2 if $Is_MSWin32 || $Is_NetWare;
358        skip "No TTY to test -t with", 2 unless -e $TTY;
359
360        open(TTY, $TTY) ||
361          warn "Can't open $TTY--run t/TEST outside of make.\n";
362        ok(-t TTY,  '-t');
363        ok(-c TTY,  'tty is -c');
364        close(TTY);
365    }
366    ok(! -t TTY,    '!-t on closed TTY filehandle');
367
368    {
369        local $TODO = 'STDIN not a tty when output is to pipe' if $Is_VMS;
370        ok(-t,          '-t on STDIN');
371    }
372}
373
374SKIP: {
375    skip "No null device to test with", 1 unless -e $Null;
376    skip "We know Win32 thinks '$Null' is a TTY", 1 if $Is_MSWin32;
377
378    open(NULL, $Null) or DIE("Can't open $Null: $!");
379    ok(! -t NULL,   'null device is not a TTY');
380    close(NULL);
381}
382
383
384# These aren't strictly "stat" calls, but so what?
385my $statfile = './op/stat.t';
386ok(  -T $statfile,    '-T');
387ok(! -B $statfile,    '!-B');
388ok(-B $Perl,      '-B');
389ok(! -T $Perl,    '!-T');
390
391open(FOO,$statfile);
392SKIP: {
393    eval { -T FOO; };
394    skip "-T/B on filehandle not implemented", 15 if $@ =~ /not implemented/;
395
396    is( $@, '',     '-T on filehandle causes no errors' );
397
398    ok(-T FOO,      '   -T');
399    ok(! -B FOO,    '   !-B');
400
401    $_ = <FOO>;
402    like($_, qr/perl/, 'after readline');
403    ok(-T FOO,      '   still -T');
404    ok(! -B FOO,    '   still -B');
405    close(FOO);
406
407    open(FOO,$statfile);
408    $_ = <FOO>;
409    like($_, qr/perl/,      'reopened and after readline');
410    ok(-T FOO,      '   still -T');
411    ok(! -B FOO,    '   still !-B');
412
413    ok(seek(FOO,0,0),   'after seek');
414    ok(-T FOO,          '   still -T');
415    ok(! -B FOO,        '   still !-B');
416
417    # It's documented this way in perlfunc *shrug*
418    () = <FOO>;
419    ok(eof FOO,         'at EOF');
420    ok(-T FOO,          '   still -T');
421    ok(-B FOO,          '   now -B');
422}
423close(FOO);
424
425
426SKIP: {
427    skip "No null device to test with", 2 unless -e $Null;
428
429    ok(-T $Null,  'null device is -T');
430    ok(-B $Null,  '    and -B');
431}
432
433
434# and now, a few parsing tests:
435$_ = $tmpfile;
436ok(-f,      'bare -f   uses $_');
437ok(-f(),    '     -f() "');
438
439unlink $tmpfile or print "# unlink failed: $!\n";
440
441# bug id 20011101.069
442my @r = \stat($Curdir);
443is(scalar @r, 13,   'stat returns full 13 elements');
444
445stat $0;
446eval { lstat _ };
447like( $@, qr/^The stat preceding lstat\(\) wasn't an lstat/,
448    'lstat _ croaks after stat' );
449eval { lstat *_ };
450like( $@, qr/^The stat preceding lstat\(\) wasn't an lstat/,
451    'lstat *_ croaks after stat' );
452eval { lstat \*_ };
453like( $@, qr/^The stat preceding lstat\(\) wasn't an lstat/,
454    'lstat \*_ croaks after stat' );
455eval { -l _ };
456like( $@, qr/^The stat preceding -l _ wasn't an lstat/,
457    '-l _ croaks after stat' );
458
459lstat $0;
460eval { lstat _ };
461is( "$@", "", "lstat _ ok after lstat" );
462eval { -l _ };
463is( "$@", "", "-l _ ok after lstat" );
464
465eval { lstat "test.pl" };
466{
467    open my $fh, "test.pl";
468    stat *$fh{IO};
469    eval { lstat _ }
470}
471like $@, qr/^The stat preceding lstat\(\) wasn't an lstat at /,
472'stat $ioref resets stat type';
473
474{
475    my @statbuf = stat STDOUT;
476    stat "test.pl";
477    my @lstatbuf = lstat *STDOUT{IO};
478    is "@lstatbuf", "@statbuf", 'lstat $ioref reverts to regular fstat';
479}
480
481SKIP: {
482    skip "No lstat", 2 unless $Config{d_lstat};
483
484    # bug id 20020124.004
485    # If we have d_lstat, we should have symlink()
486    my $linkname = 'stat-' . rand =~ y/.//dr;
487    my $target = $Perl;
488    $target =~ s/;\d+\z// if $Is_VMS; # symlinks don't like version numbers
489    symlink $target, $linkname or die "# Can't symlink $0: $!";
490    lstat $linkname;
491    -T _;
492    eval { lstat _ };
493    like( $@, qr/^The stat preceding lstat\(\) wasn't an lstat/,
494	'lstat croaks after -T _' );
495    eval { -l _ };
496    like( $@, qr/^The stat preceding -l _ wasn't an lstat/,
497	'-l _ croaks after -T _' );
498    unlink $linkname or print "# unlink $linkname failed: $!\n";
499}
500
501SKIP: {
502    skip "Too much clock skew between system and filesystem", 5
503	if ($Filesystem_Time_Offset > 5);
504    print "# Zzz...\n";
505    sleep($Filesystem_Time_Offset+1);
506    my $f = 'tstamp.tmp';
507    unlink $f;
508    ok (open(S, "> $f"), 'can create tmp file');
509    close S or die;
510    my @a = stat $f;
511    print "# time=$^T, stat=(@a)\n";
512    my @b = (-M _, -A _, -C _);
513    print "# -MAC=(@b)\n";
514    ok( (-M _) < 0, 'negative -M works');
515  SKIP:
516    {
517        skip "Access timestamps inaccurate", 1 if $inaccurate_atime;
518        ok( (-A _) < 0, 'negative -A works');
519    }
520    ok( (-C _) < 0, 'negative -C works');
521    ok(unlink($f), 'unlink tmp file');
522}
523
524# [perl #4253]
525{
526    ok(open(F, ">", $tmpfile), 'can create temp file');
527    close F;
528    chmod 0077, $tmpfile;
529    my @a = stat($tmpfile);
530    my $s1 = -s _;
531    -T _;
532    my $s2 = -s _;
533    is($s1, $s2, q(-T _ doesn't break the statbuffer));
534    SKIP: {
535	my $root_uid = $Is_Cygwin ? 18 : 0;
536	skip "No lstat", 1 unless $Config{d_lstat};
537	skip "uid=0", 1 if $< == $root_uid or $> == $root_uid;
538	skip "Can't check if admin user in miniperl", 1
539	  if $^O =~ /^(cygwin|MSWin32|msys)$/ && is_miniperl();
540	skip "Readable by group/other means readable by me on $^O", 1 if $^O eq 'VMS'
541          or ($^O =~ /^(cygwin|MSWin32|msys)$/ and Win32::IsAdminUser());
542	lstat($tmpfile);
543	-T _;
544	ok(eval { lstat _ },
545	   q(-T _ doesn't break lstat for unreadable file));
546    }
547    unlink $tmpfile;
548}
549
550SKIP: {
551    skip "No dirfd()", 9 unless $Config{d_dirfd} || $Config{d_dir_dd_fd};
552    ok(opendir(DIR, "."), 'Can open "." dir') || diag "Can't open '.':  $!";
553    ok(stat(DIR), "stat() on dirhandle works");
554    ok(-d -r _ , "chained -x's on dirhandle");
555    ok(-d DIR, "-d on a dirhandle works");
556
557    # And now for the ambiguous bareword case
558    {
559	no warnings 'deprecated';
560	ok(open(DIR, "TEST"), 'Can open "TEST" dir')
561	    || diag "Can't open 'TEST':  $!";
562    }
563    my $size = (stat(DIR))[7];
564    ok(defined $size, "stat() on bareword works");
565    is($size, -s "TEST", "size returned by stat of bareword is for the file");
566    ok(-f _, "ambiguous bareword uses file handle, not dir handle");
567    ok(-f DIR);
568    closedir DIR or die $!;
569    close DIR or die $!;
570}
571
572{
573    # RT #8244: *FILE{IO} does not behave like *FILE for stat() and -X() operators
574    ok(open(F, ">", $tmpfile), 'can create temp file');
575    my @thwap = stat *F{IO};
576    ok(@thwap, "stat(*F{IO}) works");
577    ok( -f *F{IO} , "single file tests work with *F{IO}");
578    close F;
579    unlink $tmpfile;
580
581    #PVIO's hold dirhandle information, so let's test them too.
582
583    SKIP: {
584        skip "No dirfd()", 9 unless $Config{d_dirfd} || $Config{d_dir_dd_fd};
585        ok(opendir(DIR, "."), 'Can open "." dir') || diag "Can't open '.':  $!";
586        ok(stat(*DIR{IO}), "stat() on *DIR{IO} works");
587	ok(-d _ , "The special file handle _ is set correctly");
588        ok(-d -r *DIR{IO} , "chained -x's on *DIR{IO}");
589
590	# And now for the ambiguous bareword case
591	{
592	    no warnings 'deprecated';
593	    ok(open(DIR, "TEST"), 'Can open "TEST" dir')
594		|| diag "Can't open 'TEST':  $!";
595	}
596	my $size = (stat(*DIR{IO}))[7];
597	ok(defined $size, "stat() on *THINGY{IO} works");
598	is($size, -s "TEST",
599	   "size returned by stat of *THINGY{IO} is for the file");
600	ok(-f _, "ambiguous *THINGY{IO} uses file handle, not dir handle");
601	ok(-f *DIR{IO});
602	closedir DIR or die $!;
603	close DIR or die $!;
604    }
605}
606
607# [perl #71002]
608{
609    local $^W = 1;
610    my $w;
611    local $SIG{__WARN__} = sub { warn shift; ++$w };
612    stat 'prepeinamehyparcheiarcheiometoonomaavto';
613    stat _;
614    is $w, undef, 'no unopened warning from stat _';
615}
616
617END {
618    chmod 0666, $tmpfile;
619    unlink_all $tmpfile;
620}
621