This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Inline asIV and asUV, as each is only used once, and it distracts from
[perl5.git] / lib / Cwd.pm
1 package Cwd;
2
3 =head1 NAME
4
5 Cwd - get pathname of current working directory
6
7 =head1 SYNOPSIS
8
9     use Cwd;
10     my $dir = getcwd;
11
12     use Cwd 'abs_path';
13     my $abs_path = abs_path($file);
14
15 =head1 DESCRIPTION
16
17 This module provides functions for determining the pathname of the
18 current working directory.  It is recommended that getcwd (or another
19 *cwd() function) be used in I<all> code to ensure portability.
20
21 By default, it exports the functions cwd(), getcwd(), fastcwd(), and
22 fastgetcwd() (and, on Win32, getdcwd()) into the caller's namespace.  
23
24
25 =head2 getcwd and friends
26
27 Each of these functions are called without arguments and return the
28 absolute path of the current working directory.
29
30 =over 4
31
32 =item getcwd
33
34     my $cwd = getcwd();
35
36 Returns the current working directory.
37
38 Exposes the POSIX function getcwd(3) or re-implements it if it's not
39 available.
40
41 =item cwd
42
43     my $cwd = cwd();
44
45 The cwd() is the most natural form for the current architecture. For
46 most systems it is identical to `pwd` (but without the trailing line
47 terminator).
48
49 =item fastcwd
50
51     my $cwd = fastcwd();
52
53 A more dangerous version of getcwd(), but potentially faster.
54
55 It might conceivably chdir() you out of a directory that it can't
56 chdir() you back into.  If fastcwd encounters a problem it will return
57 undef but will probably leave you in a different directory.  For a
58 measure of extra security, if everything appears to have worked, the
59 fastcwd() function will check that it leaves you in the same directory
60 that it started in. If it has changed it will C<die> with the message
61 "Unstable directory path, current directory changed
62 unexpectedly". That should never happen.
63
64 =item fastgetcwd
65
66   my $cwd = fastgetcwd();
67
68 The fastgetcwd() function is provided as a synonym for cwd().
69
70 =item getdcwd
71
72     my $cwd = getdcwd();
73     my $cwd = getdcwd('C:');
74
75 The getdcwd() function is also provided on Win32 to get the current working
76 directory on the specified drive, since Windows maintains a separate current
77 working directory for each drive.  If no drive is specified then the current
78 drive is assumed.
79
80 This function simply calls the Microsoft C library _getdcwd() function.
81
82 =back
83
84
85 =head2 abs_path and friends
86
87 These functions are exported only on request.  They each take a single
88 argument and return the absolute pathname for it.  If no argument is
89 given they'll use the current working directory.
90
91 =over 4
92
93 =item abs_path
94
95   my $abs_path = abs_path($file);
96
97 Uses the same algorithm as getcwd().  Symbolic links and relative-path
98 components ("." and "..") are resolved to return the canonical
99 pathname, just like realpath(3).
100
101 =item realpath
102
103   my $abs_path = realpath($file);
104
105 A synonym for abs_path().
106
107 =item fast_abs_path
108
109   my $abs_path = fast_abs_path($file);
110
111 A more dangerous, but potentially faster version of abs_path.
112
113 =back
114
115 =head2 $ENV{PWD}
116
117 If you ask to override your chdir() built-in function, 
118
119   use Cwd qw(chdir);
120
121 then your PWD environment variable will be kept up to date.  Note that
122 it will only be kept up to date if all packages which use chdir import
123 it from Cwd.
124
125
126 =head1 NOTES
127
128 =over 4
129
130 =item *
131
132 Since the path seperators are different on some operating systems ('/'
133 on Unix, ':' on MacPerl, etc...) we recommend you use the File::Spec
134 modules wherever portability is a concern.
135
136 =item *
137
138 Actually, on Mac OS, the C<getcwd()>, C<fastgetcwd()> and C<fastcwd()>
139 functions  are all aliases for the C<cwd()> function, which, on Mac OS,
140 calls `pwd`. Likewise, the C<abs_path()> function is an alias for
141 C<fast_abs_path()>.
142
143 =back
144
145 =head1 AUTHOR
146
147 Originally by the perl5-porters.
148
149 Maintained by Ken Williams <KWILLIAMS@cpan.org>
150
151 =head1 COPYRIGHT
152
153 Copyright (c) 2004 by the Perl 5 Porters.  All rights reserved.
154
155 This program is free software; you can redistribute it and/or modify
156 it under the same terms as Perl itself.
157
158 Portions of the C code in this library are copyright (c) 1994 by the
159 Regents of the University of California.  All rights reserved.  The
160 license on this code is compatible with the licensing of the rest of
161 the distribution - please see the source code in F<Cwd.xs> for the
162 details.
163
164 =head1 SEE ALSO
165
166 L<File::chdir>
167
168 =cut
169
170 use strict;
171 use Exporter;
172 use vars qw(@ISA @EXPORT @EXPORT_OK $VERSION);
173
174 $VERSION = '3.14_02';
175
176 @ISA = qw/ Exporter /;
177 @EXPORT = qw(cwd getcwd fastcwd fastgetcwd);
178 push @EXPORT, qw(getdcwd) if $^O eq 'MSWin32';
179 @EXPORT_OK = qw(chdir abs_path fast_abs_path realpath fast_realpath);
180
181 # sys_cwd may keep the builtin command
182
183 # All the functionality of this module may provided by builtins,
184 # there is no sense to process the rest of the file.
185 # The best choice may be to have this in BEGIN, but how to return from BEGIN?
186
187 if ($^O eq 'os2') {
188     local $^W = 0;
189
190     *cwd                = defined &sys_cwd ? \&sys_cwd : \&_os2_cwd;
191     *getcwd             = \&cwd;
192     *fastgetcwd         = \&cwd;
193     *fastcwd            = \&cwd;
194
195     *fast_abs_path      = \&sys_abspath if defined &sys_abspath;
196     *abs_path           = \&fast_abs_path;
197     *realpath           = \&fast_abs_path;
198     *fast_realpath      = \&fast_abs_path;
199
200     return 1;
201 }
202
203 # If loading the XS stuff doesn't work, we can fall back to pure perl
204 eval {
205   if ( $] >= 5.006 ) {
206     require XSLoader;
207     XSLoader::load( __PACKAGE__, $VERSION );
208   } else {
209     require DynaLoader;
210     push @ISA, 'DynaLoader';
211     __PACKAGE__->bootstrap( $VERSION );
212   }
213 };
214
215 # Must be after the DynaLoader stuff:
216 $VERSION = eval $VERSION;
217
218 # Big nasty table of function aliases
219 my %METHOD_MAP =
220   (
221    VMS =>
222    {
223     cwd                 => '_vms_cwd',
224     getcwd              => '_vms_cwd',
225     fastcwd             => '_vms_cwd',
226     fastgetcwd          => '_vms_cwd',
227     abs_path            => '_vms_abs_path',
228     fast_abs_path       => '_vms_abs_path',
229    },
230
231    MSWin32 =>
232    {
233     # We assume that &_NT_cwd is defined as an XSUB or in the core.
234     cwd                 => '_NT_cwd',
235     getcwd              => '_NT_cwd',
236     fastcwd             => '_NT_cwd',
237     fastgetcwd          => '_NT_cwd',
238     abs_path            => 'fast_abs_path',
239     realpath            => 'fast_abs_path',
240    },
241
242    dos => 
243    {
244     cwd                 => '_dos_cwd',
245     getcwd              => '_dos_cwd',
246     fastgetcwd          => '_dos_cwd',
247     fastcwd             => '_dos_cwd',
248     abs_path            => 'fast_abs_path',
249    },
250
251    qnx =>
252    {
253     cwd                 => '_qnx_cwd',
254     getcwd              => '_qnx_cwd',
255     fastgetcwd          => '_qnx_cwd',
256     fastcwd             => '_qnx_cwd',
257     abs_path            => '_qnx_abs_path',
258     fast_abs_path       => '_qnx_abs_path',
259    },
260
261    cygwin =>
262    {
263     getcwd              => 'cwd',
264     fastgetcwd          => 'cwd',
265     fastcwd             => 'cwd',
266     abs_path            => 'fast_abs_path',
267     realpath            => 'fast_abs_path',
268    },
269
270    epoc =>
271    {
272     cwd                 => '_epoc_cwd',
273     getcwd              => '_epoc_cwd',
274     fastgetcwd          => '_epoc_cwd',
275     fastcwd             => '_epoc_cwd',
276     abs_path            => 'fast_abs_path',
277    },
278
279    MacOS =>
280    {
281     getcwd              => 'cwd',
282     fastgetcwd          => 'cwd',
283     fastcwd             => 'cwd',
284     abs_path            => 'fast_abs_path',
285    },
286   );
287
288 $METHOD_MAP{NT} = $METHOD_MAP{MSWin32};
289 $METHOD_MAP{nto} = $METHOD_MAP{qnx};
290
291
292 # Find the pwd command in the expected locations.  We assume these
293 # are safe.  This prevents _backtick_pwd() consulting $ENV{PATH}
294 # so everything works under taint mode.
295 my $pwd_cmd;
296 foreach my $try ('/bin/pwd',
297                  '/usr/bin/pwd',
298                  '/QOpenSys/bin/pwd', # OS/400 PASE.
299                 ) {
300
301     if( -x $try ) {
302         $pwd_cmd = $try;
303         last;
304     }
305 }
306 my $found_pwd_cmd = defined($pwd_cmd);
307 unless ($pwd_cmd) {
308     # Isn't this wrong?  _backtick_pwd() will fail if somenone has
309     # pwd in their path but it is not /bin/pwd or /usr/bin/pwd?
310     # See [perl #16774]. --jhi
311     $pwd_cmd = 'pwd';
312 }
313
314 # Lazy-load Carp
315 sub _carp  { require Carp; Carp::carp(@_)  }
316 sub _croak { require Carp; Carp::croak(@_) }
317
318 # The 'natural and safe form' for UNIX (pwd may be setuid root)
319 sub _backtick_pwd {
320     # Localize %ENV entries in a way that won't create new hash keys
321     my @localize = grep exists $ENV{$_}, qw(PATH IFS CDPATH ENV BASH_ENV);
322     local @ENV{@localize};
323     
324     my $cwd = `$pwd_cmd`;
325     # Belt-and-suspenders in case someone said "undef $/".
326     local $/ = "\n";
327     # `pwd` may fail e.g. if the disk is full
328     chomp($cwd) if defined $cwd;
329     $cwd;
330 }
331
332 # Since some ports may predefine cwd internally (e.g., NT)
333 # we take care not to override an existing definition for cwd().
334
335 unless ($METHOD_MAP{$^O}{cwd} or defined &cwd) {
336     # The pwd command is not available in some chroot(2)'ed environments
337     my $sep = $Config::Config{path_sep} || ':';
338     my $os = $^O;  # Protect $^O from tainting
339
340
341     # Try again to find a pwd, this time searching the whole PATH.
342     if (defined $ENV{PATH} and $os ne 'MSWin32') {  # no pwd on Windows
343         my @candidates = split($sep, $ENV{PATH});
344         while (!$found_pwd_cmd and @candidates) {
345             my $candidate = shift @candidates;
346             $found_pwd_cmd = 1 if -x "$candidate/pwd";
347         }
348     }
349
350     # MacOS has some special magic to make `pwd` work.
351     if( $os eq 'MacOS' || $found_pwd_cmd )
352     {
353         *cwd = \&_backtick_pwd;
354     }
355     else {
356         *cwd = \&getcwd;
357     }
358 }
359
360 # set a reasonable (and very safe) default for fastgetcwd, in case it
361 # isn't redefined later (20001212 rspier)
362 *fastgetcwd = \&cwd;
363
364 # By Brandon S. Allbery
365 #
366 # Usage: $cwd = getcwd();
367
368 sub _perl_getcwd
369 {
370     abs_path('.');
371 }
372
373 # By John Bazik
374 #
375 # Usage: $cwd = &fastcwd;
376 #
377 # This is a faster version of getcwd.  It's also more dangerous because
378 # you might chdir out of a directory that you can't chdir back into.
379     
380 sub fastcwd_ {
381     my($odev, $oino, $cdev, $cino, $tdev, $tino);
382     my(@path, $path);
383     local(*DIR);
384
385     my($orig_cdev, $orig_cino) = stat('.');
386     ($cdev, $cino) = ($orig_cdev, $orig_cino);
387     for (;;) {
388         my $direntry;
389         ($odev, $oino) = ($cdev, $cino);
390         CORE::chdir('..') || return undef;
391         ($cdev, $cino) = stat('.');
392         last if $odev == $cdev && $oino == $cino;
393         opendir(DIR, '.') || return undef;
394         for (;;) {
395             $direntry = readdir(DIR);
396             last unless defined $direntry;
397             next if $direntry eq '.';
398             next if $direntry eq '..';
399
400             ($tdev, $tino) = lstat($direntry);
401             last unless $tdev != $odev || $tino != $oino;
402         }
403         closedir(DIR);
404         return undef unless defined $direntry; # should never happen
405         unshift(@path, $direntry);
406     }
407     $path = '/' . join('/', @path);
408     if ($^O eq 'apollo') { $path = "/".$path; }
409     # At this point $path may be tainted (if tainting) and chdir would fail.
410     # Untaint it then check that we landed where we started.
411     $path =~ /^(.*)\z/s         # untaint
412         && CORE::chdir($1) or return undef;
413     ($cdev, $cino) = stat('.');
414     die "Unstable directory path, current directory changed unexpectedly"
415         if $cdev != $orig_cdev || $cino != $orig_cino;
416     $path;
417 }
418 if (not defined &fastcwd) { *fastcwd = \&fastcwd_ }
419
420
421 # Keeps track of current working directory in PWD environment var
422 # Usage:
423 #       use Cwd 'chdir';
424 #       chdir $newdir;
425
426 my $chdir_init = 0;
427
428 sub chdir_init {
429     if ($ENV{'PWD'} and $^O ne 'os2' and $^O ne 'dos' and $^O ne 'MSWin32') {
430         my($dd,$di) = stat('.');
431         my($pd,$pi) = stat($ENV{'PWD'});
432         if (!defined $dd or !defined $pd or $di != $pi or $dd != $pd) {
433             $ENV{'PWD'} = cwd();
434         }
435     }
436     else {
437         my $wd = cwd();
438         $wd = Win32::GetFullPathName($wd) if $^O eq 'MSWin32';
439         $ENV{'PWD'} = $wd;
440     }
441     # Strip an automounter prefix (where /tmp_mnt/foo/bar == /foo/bar)
442     if ($^O ne 'MSWin32' and $ENV{'PWD'} =~ m|(/[^/]+(/[^/]+/[^/]+))(.*)|s) {
443         my($pd,$pi) = stat($2);
444         my($dd,$di) = stat($1);
445         if (defined $pd and defined $dd and $di == $pi and $dd == $pd) {
446             $ENV{'PWD'}="$2$3";
447         }
448     }
449     $chdir_init = 1;
450 }
451
452 sub chdir {
453     my $newdir = @_ ? shift : '';       # allow for no arg (chdir to HOME dir)
454     $newdir =~ s|///*|/|g unless $^O eq 'MSWin32';
455     chdir_init() unless $chdir_init;
456     my $newpwd;
457     if ($^O eq 'MSWin32') {
458         # get the full path name *before* the chdir()
459         $newpwd = Win32::GetFullPathName($newdir);
460     }
461
462     return 0 unless CORE::chdir $newdir;
463
464     if ($^O eq 'VMS') {
465         return $ENV{'PWD'} = $ENV{'DEFAULT'}
466     }
467     elsif ($^O eq 'MacOS') {
468         return $ENV{'PWD'} = cwd();
469     }
470     elsif ($^O eq 'MSWin32') {
471         $ENV{'PWD'} = $newpwd;
472         return 1;
473     }
474
475     if ($newdir =~ m#^/#s) {
476         $ENV{'PWD'} = $newdir;
477     } else {
478         my @curdir = split(m#/#,$ENV{'PWD'});
479         @curdir = ('') unless @curdir;
480         my $component;
481         foreach $component (split(m#/#, $newdir)) {
482             next if $component eq '.';
483             pop(@curdir),next if $component eq '..';
484             push(@curdir,$component);
485         }
486         $ENV{'PWD'} = join('/',@curdir) || '/';
487     }
488     1;
489 }
490
491
492 sub _perl_abs_path
493 {
494     my $start = @_ ? shift : '.';
495     my($dotdots, $cwd, @pst, @cst, $dir, @tst);
496
497     unless (@cst = stat( $start ))
498     {
499         _carp("stat($start): $!");
500         return '';
501     }
502
503     unless (-d _) {
504         # Make sure we can be invoked on plain files, not just directories.
505         # NOTE that this routine assumes that '/' is the only directory separator.
506         
507         my ($dir, $file) = $start =~ m{^(.*)/(.+)$}
508             or return cwd() . '/' . $start;
509         
510         # Can't use "-l _" here, because the previous stat was a stat(), not an lstat().
511         if (-l $start) {
512             my $link_target = readlink($start);
513             die "Can't resolve link $start: $!" unless defined $link_target;
514             
515             require File::Spec;
516             $link_target = $dir . '/' . $link_target
517                 unless File::Spec->file_name_is_absolute($link_target);
518             
519             return abs_path($link_target);
520         }
521         
522         return $dir ? abs_path($dir) . "/$file" : "/$file";
523     }
524
525     $cwd = '';
526     $dotdots = $start;
527     do
528     {
529         $dotdots .= '/..';
530         @pst = @cst;
531         local *PARENT;
532         unless (opendir(PARENT, $dotdots))
533         {
534             _carp("opendir($dotdots): $!");
535             return '';
536         }
537         unless (@cst = stat($dotdots))
538         {
539             _carp("stat($dotdots): $!");
540             closedir(PARENT);
541             return '';
542         }
543         if ($pst[0] == $cst[0] && $pst[1] == $cst[1])
544         {
545             $dir = undef;
546         }
547         else
548         {
549             do
550             {
551                 unless (defined ($dir = readdir(PARENT)))
552                 {
553                     _carp("readdir($dotdots): $!");
554                     closedir(PARENT);
555                     return '';
556                 }
557                 $tst[0] = $pst[0]+1 unless (@tst = lstat("$dotdots/$dir"))
558             }
559             while ($dir eq '.' || $dir eq '..' || $tst[0] != $pst[0] ||
560                    $tst[1] != $pst[1]);
561         }
562         $cwd = (defined $dir ? "$dir" : "" ) . "/$cwd" ;
563         closedir(PARENT);
564     } while (defined $dir);
565     chop($cwd) unless $cwd eq '/'; # drop the trailing /
566     $cwd;
567 }
568
569
570 my $Curdir;
571 sub fast_abs_path {
572     local $ENV{PWD} = $ENV{PWD} || ''; # Guard against clobberage
573     my $cwd = getcwd();
574     require File::Spec;
575     my $path = @_ ? shift : ($Curdir ||= File::Spec->curdir);
576
577     # Detaint else we'll explode in taint mode.  This is safe because
578     # we're not doing anything dangerous with it.
579     ($path) = $path =~ /(.*)/;
580     ($cwd)  = $cwd  =~ /(.*)/;
581
582     unless (-e $path) {
583         _croak("$path: No such file or directory");
584     }
585
586     unless (-d _) {
587         # Make sure we can be invoked on plain files, not just directories.
588         
589         my ($vol, $dir, $file) = File::Spec->splitpath($path);
590         return File::Spec->catfile($cwd, $path) unless length $dir;
591
592         if (-l $path) {
593             my $link_target = readlink($path);
594             die "Can't resolve link $path: $!" unless defined $link_target;
595             
596             $link_target = File::Spec->catpath($vol, $dir, $link_target)
597                 unless File::Spec->file_name_is_absolute($link_target);
598             
599             return fast_abs_path($link_target);
600         }
601         
602         return $dir eq File::Spec->rootdir
603           ? File::Spec->catpath($vol, $dir, $file)
604           : fast_abs_path(File::Spec->catpath($vol, $dir, '')) . '/' . $file;
605     }
606
607     if (!CORE::chdir($path)) {
608         _croak("Cannot chdir to $path: $!");
609     }
610     my $realpath = getcwd();
611     if (! ((-d $cwd) && (CORE::chdir($cwd)))) {
612         _croak("Cannot chdir back to $cwd: $!");
613     }
614     $realpath;
615 }
616
617 # added function alias to follow principle of least surprise
618 # based on previous aliasing.  --tchrist 27-Jan-00
619 *fast_realpath = \&fast_abs_path;
620
621
622 # --- PORTING SECTION ---
623
624 # VMS: $ENV{'DEFAULT'} points to default directory at all times
625 # 06-Mar-1996  Charles Bailey  bailey@newman.upenn.edu
626 # Note: Use of Cwd::chdir() causes the logical name PWD to be defined
627 #   in the process logical name table as the default device and directory
628 #   seen by Perl. This may not be the same as the default device
629 #   and directory seen by DCL after Perl exits, since the effects
630 #   the CRTL chdir() function persist only until Perl exits.
631
632 sub _vms_cwd {
633     return $ENV{'DEFAULT'};
634 }
635
636 sub _vms_abs_path {
637     return $ENV{'DEFAULT'} unless @_;
638
639     # may need to turn foo.dir into [.foo]
640     my $path = VMS::Filespec::pathify($_[0]);
641     $path = $_[0] unless defined $path;
642
643     return VMS::Filespec::rmsexpand($path);
644 }
645
646 sub _os2_cwd {
647     $ENV{'PWD'} = `cmd /c cd`;
648     chomp $ENV{'PWD'};
649     $ENV{'PWD'} =~ s:\\:/:g ;
650     return $ENV{'PWD'};
651 }
652
653 sub _win32_cwd {
654     $ENV{'PWD'} = Win32::GetCwd();
655     $ENV{'PWD'} =~ s:\\:/:g ;
656     return $ENV{'PWD'};
657 }
658
659 *_NT_cwd = defined &Win32::GetCwd ? \&_win32_cwd : \&_os2_cwd;
660
661 sub _dos_cwd {
662     if (!defined &Dos::GetCwd) {
663         $ENV{'PWD'} = `command /c cd`;
664         chomp $ENV{'PWD'};
665         $ENV{'PWD'} =~ s:\\:/:g ;
666     } else {
667         $ENV{'PWD'} = Dos::GetCwd();
668     }
669     return $ENV{'PWD'};
670 }
671
672 sub _qnx_cwd {
673         local $ENV{PATH} = '';
674         local $ENV{CDPATH} = '';
675         local $ENV{ENV} = '';
676     $ENV{'PWD'} = `/usr/bin/fullpath -t`;
677     chomp $ENV{'PWD'};
678     return $ENV{'PWD'};
679 }
680
681 sub _qnx_abs_path {
682         local $ENV{PATH} = '';
683         local $ENV{CDPATH} = '';
684         local $ENV{ENV} = '';
685     my $path = @_ ? shift : '.';
686     local *REALPATH;
687
688     defined( open(REALPATH, '-|') || exec '/usr/bin/fullpath', '-t', $path ) or
689       die "Can't open /usr/bin/fullpath: $!";
690     my $realpath = <REALPATH>;
691     close REALPATH;
692     chomp $realpath;
693     return $realpath;
694 }
695
696 sub _epoc_cwd {
697     $ENV{'PWD'} = EPOC::getcwd();
698     return $ENV{'PWD'};
699 }
700
701
702 # Now that all the base-level functions are set up, alias the
703 # user-level functions to the right places
704
705 if (exists $METHOD_MAP{$^O}) {
706   my $map = $METHOD_MAP{$^O};
707   foreach my $name (keys %$map) {
708     local $^W = 0;  # assignments trigger 'subroutine redefined' warning
709     no strict 'refs';
710     *{$name} = \&{$map->{$name}};
711   }
712 }
713
714 # In case the XS version doesn't load.
715 *abs_path = \&_perl_abs_path unless defined &abs_path;
716 *getcwd = \&_perl_getcwd unless defined &getcwd;
717
718 # added function alias for those of us more
719 # used to the libc function.  --tchrist 27-Jan-00
720 *realpath = \&abs_path;
721
722 1;