4 use vars qw(@ISA @EXPORT @EXPORT_OK $VERSION);
7 my $xs_version = $VERSION;
10 @ISA = qw/ Exporter /;
11 @EXPORT = qw(cwd getcwd fastcwd fastgetcwd);
12 push @EXPORT, qw(getdcwd) if $^O eq 'MSWin32';
13 @EXPORT_OK = qw(chdir abs_path fast_abs_path realpath fast_realpath);
15 # sys_cwd may keep the builtin command
17 # All the functionality of this module may provided by builtins,
18 # there is no sense to process the rest of the file.
19 # The best choice may be to have this in BEGIN, but how to return from BEGIN?
24 *cwd = defined &sys_cwd ? \&sys_cwd : \&_os2_cwd;
29 *fast_abs_path = \&sys_abspath if defined &sys_abspath;
30 *abs_path = \&fast_abs_path;
31 *realpath = \&fast_abs_path;
32 *fast_realpath = \&fast_abs_path;
37 # Need to look up the feature settings on VMS. The preferred way is to use the
38 # VMS::Feature module, but that may not be available to dual life modules.
43 if (eval { local $SIG{__DIE__}; require VMS::Feature; }) {
49 # Need to look up the UNIX report mode. This may become a dynamic mode
53 if ($use_vms_feature) {
54 $unix_rpt = VMS::Feature::current("filename_unix_report");
56 my $env_unix_rpt = $ENV{'DECC$FILENAME_UNIX_REPORT'} || '';
57 $unix_rpt = $env_unix_rpt =~ /^[ET1]/i;
62 # Need to look up the EFS character set mode. This may become a dynamic
66 if ($use_vms_feature) {
67 $efs = VMS::Feature::current("efs_charset");
69 my $env_efs = $ENV{'DECC$EFS_CHARSET'} || '';
70 $efs = $env_efs =~ /^[ET1]/i;
76 # If loading the XS stuff doesn't work, we can fall back to pure perl
77 if(! defined &getcwd && defined &DynaLoader::boot_DynaLoader) {
78 eval {#eval is questionable since we are handling potential errors like
79 #"Cwd object version 3.48 does not match bootstrap parameter 3.50
80 #at lib/DynaLoader.pm line 216." by having this eval
83 XSLoader::load( __PACKAGE__, $xs_version);
86 push @ISA, 'DynaLoader';
87 __PACKAGE__->bootstrap( $xs_version );
92 # Big nasty table of function aliases
99 fastcwd => '_vms_cwd',
100 fastgetcwd => '_vms_cwd',
101 abs_path => '_vms_abs_path',
102 fast_abs_path => '_vms_abs_path',
107 # We assume that &_NT_cwd is defined as an XSUB or in the core.
110 fastcwd => '_NT_cwd',
111 fastgetcwd => '_NT_cwd',
112 abs_path => 'fast_abs_path',
113 realpath => 'fast_abs_path',
119 getcwd => '_dos_cwd',
120 fastgetcwd => '_dos_cwd',
121 fastcwd => '_dos_cwd',
122 abs_path => 'fast_abs_path',
125 # QNX4. QNX6 has a $os of 'nto'.
129 getcwd => '_qnx_cwd',
130 fastgetcwd => '_qnx_cwd',
131 fastcwd => '_qnx_cwd',
132 abs_path => '_qnx_abs_path',
133 fast_abs_path => '_qnx_abs_path',
141 abs_path => 'fast_abs_path',
142 realpath => 'fast_abs_path',
148 getcwd => '_epoc_cwd',
149 fastgetcwd => '_epoc_cwd',
150 fastcwd => '_epoc_cwd',
151 abs_path => 'fast_abs_path',
159 abs_path => 'fast_abs_path',
164 getcwd => '_backtick_pwd',
165 fastgetcwd => '_backtick_pwd',
166 fastcwd => '_backtick_pwd',
167 abs_path => 'fast_abs_path',
171 $METHOD_MAP{NT} = $METHOD_MAP{MSWin32};
174 # Find the pwd command in the expected locations. We assume these
175 # are safe. This prevents _backtick_pwd() consulting $ENV{PATH}
176 # so everything works under taint mode.
178 if($^O ne 'MSWin32') {
179 foreach my $try ('/bin/pwd',
181 '/QOpenSys/bin/pwd', # OS/400 PASE.
190 # Android has a built-in pwd. Using $pwd_cmd will DTRT if
191 # this perl was compiled with -Dd_useshellcmds, which is the
192 # default for Android, but the block below is needed for the
193 # miniperl running on the host when cross-compiling, and
194 # potentially for native builds with -Ud_useshellcmds.
195 if ($^O =~ /android/) {
196 # If targetsh is executable, then we're either a full
197 # perl, or a miniperl for a native build.
198 if (-x $Config::Config{targetsh}) {
199 $pwd_cmd = "$Config::Config{targetsh} -c pwd"
202 my $sh = $Config::Config{sh} || (-x '/system/bin/sh' ? '/system/bin/sh' : 'sh');
203 $pwd_cmd = "$sh -c pwd"
207 my $found_pwd_cmd = defined($pwd_cmd);
209 # Isn't this wrong? _backtick_pwd() will fail if someone has
210 # pwd in their path but it is not /bin/pwd or /usr/bin/pwd?
211 # See [perl #16774]. --jhi
216 sub _carp { require Carp; Carp::carp(@_) }
217 sub _croak { require Carp; Carp::croak(@_) }
219 # The 'natural and safe form' for UNIX (pwd may be setuid root)
222 # Localize %ENV entries in a way that won't create new hash keys.
223 # Under AmigaOS we don't want to localize as it stops perl from
224 # finding 'sh' in the PATH.
225 my @localize = grep exists $ENV{$_}, qw(PATH IFS CDPATH ENV BASH_ENV) if $^O ne "amigaos";
226 local @ENV{@localize} if @localize;
228 my $cwd = `$pwd_cmd`;
229 # Belt-and-suspenders in case someone said "undef $/".
231 # `pwd` may fail e.g. if the disk is full
232 chomp($cwd) if defined $cwd;
236 # Since some ports may predefine cwd internally (e.g., NT)
237 # we take care not to override an existing definition for cwd().
239 unless ($METHOD_MAP{$^O}{cwd} or defined &cwd) {
240 # The pwd command is not available in some chroot(2)'ed environments
241 my $sep = $Config::Config{path_sep} || ':';
242 my $os = $^O; # Protect $^O from tainting
245 # Try again to find a pwd, this time searching the whole PATH.
246 if (defined $ENV{PATH} and $os ne 'MSWin32') { # no pwd on Windows
247 my @candidates = split($sep, $ENV{PATH});
248 while (!$found_pwd_cmd and @candidates) {
249 my $candidate = shift @candidates;
250 $found_pwd_cmd = 1 if -x "$candidate/pwd";
254 # MacOS has some special magic to make `pwd` work.
255 if( $os eq 'MacOS' || $found_pwd_cmd )
257 *cwd = \&_backtick_pwd;
264 if ($^O eq 'cygwin') {
265 # We need to make sure cwd() is called with no args, because it's
266 # got an arg-less prototype and will die if args are present.
268 my $orig_cwd = \&cwd;
269 *cwd = sub { &$orig_cwd() }
273 # set a reasonable (and very safe) default for fastgetcwd, in case it
274 # isn't redefined later (20001212 rspier)
277 # A non-XS version of getcwd() - also used to bootstrap the perl build
278 # process, when miniperl is running and no XS loading happens.
286 # Usage: $cwd = &fastcwd;
288 # This is a faster version of getcwd. It's also more dangerous because
289 # you might chdir out of a directory that you can't chdir back into.
292 my($odev, $oino, $cdev, $cino, $tdev, $tino);
296 my($orig_cdev, $orig_cino) = stat('.');
297 ($cdev, $cino) = ($orig_cdev, $orig_cino);
300 ($odev, $oino) = ($cdev, $cino);
301 CORE::chdir('..') || return undef;
302 ($cdev, $cino) = stat('.');
303 last if $odev == $cdev && $oino == $cino;
304 opendir(DIR, '.') || return undef;
306 $direntry = readdir(DIR);
307 last unless defined $direntry;
308 next if $direntry eq '.';
309 next if $direntry eq '..';
311 ($tdev, $tino) = lstat($direntry);
312 last unless $tdev != $odev || $tino != $oino;
315 return undef unless defined $direntry; # should never happen
316 unshift(@path, $direntry);
318 $path = '/' . join('/', @path);
319 if ($^O eq 'apollo') { $path = "/".$path; }
320 # At this point $path may be tainted (if tainting) and chdir would fail.
321 # Untaint it then check that we landed where we started.
322 $path =~ /^(.*)\z/s # untaint
323 && CORE::chdir($1) or return undef;
324 ($cdev, $cino) = stat('.');
325 die "Unstable directory path, current directory changed unexpectedly"
326 if $cdev != $orig_cdev || $cino != $orig_cino;
329 if (not defined &fastcwd) { *fastcwd = \&fastcwd_ }
332 # Keeps track of current working directory in PWD environment var
340 if ($ENV{'PWD'} and $^O ne 'os2' and $^O ne 'dos' and $^O ne 'MSWin32') {
341 my($dd,$di) = stat('.');
342 my($pd,$pi) = stat($ENV{'PWD'});
343 if (!defined $dd or !defined $pd or $di != $pi or $dd != $pd) {
349 $wd = Win32::GetFullPathName($wd) if $^O eq 'MSWin32';
352 # Strip an automounter prefix (where /tmp_mnt/foo/bar == /foo/bar)
353 if ($^O ne 'MSWin32' and $ENV{'PWD'} =~ m|(/[^/]+(/[^/]+/[^/]+))(.*)|s) {
354 my($pd,$pi) = stat($2);
355 my($dd,$di) = stat($1);
356 if (defined $pd and defined $dd and $di == $pi and $dd == $pd) {
364 my $newdir = @_ ? shift : ''; # allow for no arg (chdir to HOME dir)
365 if ($^O eq "cygwin") {
366 $newdir =~ s|\A///+|//|;
367 $newdir =~ s|(?<=[^/])//+|/|g;
369 elsif ($^O ne 'MSWin32') {
370 $newdir =~ s|///*|/|g;
372 chdir_init() unless $chdir_init;
374 if ($^O eq 'MSWin32') {
375 # get the full path name *before* the chdir()
376 $newpwd = Win32::GetFullPathName($newdir);
379 return 0 unless CORE::chdir $newdir;
382 return $ENV{'PWD'} = $ENV{'DEFAULT'}
384 elsif ($^O eq 'MacOS') {
385 return $ENV{'PWD'} = cwd();
387 elsif ($^O eq 'MSWin32') {
388 $ENV{'PWD'} = $newpwd;
392 if (ref $newdir eq 'GLOB') { # in case a file/dir handle is passed in
394 } elsif ($newdir =~ m#^/#s) {
395 $ENV{'PWD'} = $newdir;
397 my @curdir = split(m#/#,$ENV{'PWD'});
398 @curdir = ('') unless @curdir;
400 foreach $component (split(m#/#, $newdir)) {
401 next if $component eq '.';
402 pop(@curdir),next if $component eq '..';
403 push(@curdir,$component);
405 $ENV{'PWD'} = join('/',@curdir) || '/';
413 my $start = @_ ? shift : '.';
414 my($dotdots, $cwd, @pst, @cst, $dir, @tst);
416 unless (@cst = stat( $start ))
418 _carp("stat($start): $!");
423 # Make sure we can be invoked on plain files, not just directories.
424 # NOTE that this routine assumes that '/' is the only directory separator.
426 my ($dir, $file) = $start =~ m{^(.*)/(.+)$}
427 or return cwd() . '/' . $start;
429 # Can't use "-l _" here, because the previous stat was a stat(), not an lstat().
431 my $link_target = readlink($start);
432 die "Can't resolve link $start: $!" unless defined $link_target;
435 $link_target = $dir . '/' . $link_target
436 unless File::Spec->file_name_is_absolute($link_target);
438 return abs_path($link_target);
441 return $dir ? abs_path($dir) . "/$file" : "/$file";
451 unless (opendir(PARENT, $dotdots))
453 # probably a permissions issue. Try the native command.
455 return File::Spec->rel2abs( $start, _backtick_pwd() );
457 unless (@cst = stat($dotdots))
459 _carp("stat($dotdots): $!");
463 if ($pst[0] == $cst[0] && $pst[1] == $cst[1])
471 unless (defined ($dir = readdir(PARENT)))
473 _carp("readdir($dotdots): $!");
477 $tst[0] = $pst[0]+1 unless (@tst = lstat("$dotdots/$dir"))
479 while ($dir eq '.' || $dir eq '..' || $tst[0] != $pst[0] ||
482 $cwd = (defined $dir ? "$dir" : "" ) . "/$cwd" ;
484 } while (defined $dir);
485 chop($cwd) unless $cwd eq '/'; # drop the trailing /
492 local $ENV{PWD} = $ENV{PWD} || ''; # Guard against clobberage
495 my $path = @_ ? shift : ($Curdir ||= File::Spec->curdir);
497 # Detaint else we'll explode in taint mode. This is safe because
498 # we're not doing anything dangerous with it.
499 ($path) = $path =~ /(.*)/s;
500 ($cwd) = $cwd =~ /(.*)/s;
503 _croak("$path: No such file or directory");
507 # Make sure we can be invoked on plain files, not just directories.
509 my ($vol, $dir, $file) = File::Spec->splitpath($path);
510 return File::Spec->catfile($cwd, $path) unless length $dir;
513 my $link_target = readlink($path);
514 die "Can't resolve link $path: $!" unless defined $link_target;
516 $link_target = File::Spec->catpath($vol, $dir, $link_target)
517 unless File::Spec->file_name_is_absolute($link_target);
519 return fast_abs_path($link_target);
522 return $dir eq File::Spec->rootdir
523 ? File::Spec->catpath($vol, $dir, $file)
524 : fast_abs_path(File::Spec->catpath($vol, $dir, '')) . '/' . $file;
527 if (!CORE::chdir($path)) {
528 _croak("Cannot chdir to $path: $!");
530 my $realpath = getcwd();
531 if (! ((-d $cwd) && (CORE::chdir($cwd)))) {
532 _croak("Cannot chdir back to $cwd: $!");
537 # added function alias to follow principle of least surprise
538 # based on previous aliasing. --tchrist 27-Jan-00
539 *fast_realpath = \&fast_abs_path;
542 # --- PORTING SECTION ---
544 # VMS: $ENV{'DEFAULT'} points to default directory at all times
545 # 06-Mar-1996 Charles Bailey bailey@newman.upenn.edu
546 # Note: Use of Cwd::chdir() causes the logical name PWD to be defined
547 # in the process logical name table as the default device and directory
548 # seen by Perl. This may not be the same as the default device
549 # and directory seen by DCL after Perl exits, since the effects
550 # the CRTL chdir() function persist only until Perl exits.
553 return $ENV{'DEFAULT'};
557 return $ENV{'DEFAULT'} unless @_;
561 my $unix_rpt = _vms_unix_rpt;
563 if (defined &VMS::Filespec::vmsrealpath) {
567 $path_unix = 1 if ($path =~ m#(?<=\^)/#);
568 $path_unix = 1 if ($path =~ /^\.\.?$/);
569 $path_vms = 1 if ($path =~ m#[\[<\]]#);
570 $path_vms = 1 if ($path =~ /^--?$/);
572 my $unix_mode = $path_unix;
574 # In case of a tie, the Unix report mode decides.
575 if ($path_vms == $path_unix) {
576 $unix_mode = $unix_rpt;
578 $unix_mode = 0 if $path_vms;
584 return VMS::Filespec::unixrealpath($path);
589 my $new_path = VMS::Filespec::vmsrealpath($path);
591 # Perl expects directories to be in directory format
592 $new_path = VMS::Filespec::pathify($new_path) if -d $path;
596 # Fallback to older algorithm if correct ones are not
600 my $link_target = readlink($path);
601 die "Can't resolve link $path: $!" unless defined $link_target;
603 return _vms_abs_path($link_target);
606 # may need to turn foo.dir into [.foo]
607 my $pathified = VMS::Filespec::pathify($path);
608 $path = $pathified if defined $pathified;
610 return VMS::Filespec::rmsexpand($path);
614 my $pwd = `cmd /c cd`;
621 sub _win32_cwd_simple {
631 $pwd = Win32::GetCwd();
637 *_NT_cwd = defined &Win32::GetCwd ? \&_win32_cwd : \&_win32_cwd_simple;
641 if (!defined &Dos::GetCwd) {
642 chomp($pwd = `command /c cd`);
645 $pwd = Dos::GetCwd();
652 local $ENV{PATH} = '';
653 local $ENV{CDPATH} = '';
654 local $ENV{ENV} = '';
655 my $pwd = `/usr/bin/fullpath -t`;
662 local $ENV{PATH} = '';
663 local $ENV{CDPATH} = '';
664 local $ENV{ENV} = '';
665 my $path = @_ ? shift : '.';
668 defined( open(REALPATH, '-|') || exec '/usr/bin/fullpath', '-t', $path ) or
669 die "Can't open /usr/bin/fullpath: $!";
670 my $realpath = <REALPATH>;
677 return $ENV{'PWD'} = EPOC::getcwd();
681 # Now that all the base-level functions are set up, alias the
682 # user-level functions to the right places
684 if (exists $METHOD_MAP{$^O}) {
685 my $map = $METHOD_MAP{$^O};
686 foreach my $name (keys %$map) {
687 local $^W = 0; # assignments trigger 'subroutine redefined' warning
689 *{$name} = \&{$map->{$name}};
693 # In case the XS version doesn't load.
694 *abs_path = \&_perl_abs_path unless defined &abs_path;
695 *getcwd = \&_perl_getcwd unless defined &getcwd;
697 # added function alias for those of us more
698 # used to the libc function. --tchrist 27-Jan-00
699 *realpath = \&abs_path;
706 Cwd - get pathname of current working directory
714 my $abs_path = abs_path($file);
718 This module provides functions for determining the pathname of the
719 current working directory. It is recommended that getcwd (or another
720 *cwd() function) be used in I<all> code to ensure portability.
722 By default, it exports the functions cwd(), getcwd(), fastcwd(), and
723 fastgetcwd() (and, on Win32, getdcwd()) into the caller's namespace.
726 =head2 getcwd and friends
728 Each of these functions are called without arguments and return the
729 absolute path of the current working directory.
737 Returns the current working directory.
739 Exposes the POSIX function getcwd(3) or re-implements it if it's not
746 The cwd() is the most natural form for the current architecture. For
747 most systems it is identical to `pwd` (but without the trailing line
754 A more dangerous version of getcwd(), but potentially faster.
756 It might conceivably chdir() you out of a directory that it can't
757 chdir() you back into. If fastcwd encounters a problem it will return
758 undef but will probably leave you in a different directory. For a
759 measure of extra security, if everything appears to have worked, the
760 fastcwd() function will check that it leaves you in the same directory
761 that it started in. If it has changed it will C<die> with the message
762 "Unstable directory path, current directory changed
763 unexpectedly". That should never happen.
767 my $cwd = fastgetcwd();
769 The fastgetcwd() function is provided as a synonym for cwd().
774 my $cwd = getdcwd('C:');
776 The getdcwd() function is also provided on Win32 to get the current working
777 directory on the specified drive, since Windows maintains a separate current
778 working directory for each drive. If no drive is specified then the current
781 This function simply calls the Microsoft C library _getdcwd() function.
786 =head2 abs_path and friends
788 These functions are exported only on request. They each take a single
789 argument and return the absolute pathname for it. If no argument is
790 given they'll use the current working directory.
796 my $abs_path = abs_path($file);
798 Uses the same algorithm as getcwd(). Symbolic links and relative-path
799 components ("." and "..") are resolved to return the canonical
800 pathname, just like realpath(3).
804 my $abs_path = realpath($file);
806 A synonym for abs_path().
810 my $abs_path = fast_abs_path($file);
812 A more dangerous, but potentially faster version of abs_path.
818 If you ask to override your chdir() built-in function,
822 then your PWD environment variable will be kept up to date. Note that
823 it will only be kept up to date if all packages which use chdir import
833 Since the path separators are different on some operating systems ('/'
834 on Unix, ':' on MacPerl, etc...) we recommend you use the File::Spec
835 modules wherever portability is a concern.
839 Actually, on Mac OS, the C<getcwd()>, C<fastgetcwd()> and C<fastcwd()>
840 functions are all aliases for the C<cwd()> function, which, on Mac OS,
841 calls `pwd`. Likewise, the C<abs_path()> function is an alias for
848 Originally by the perl5-porters.
850 Maintained by Ken Williams <KWILLIAMS@cpan.org>
854 Copyright (c) 2004 by the Perl 5 Porters. All rights reserved.
856 This program is free software; you can redistribute it and/or modify
857 it under the same terms as Perl itself.
859 Portions of the C code in this library are copyright (c) 1994 by the
860 Regents of the University of California. All rights reserved. The
861 license on this code is compatible with the licensing of the rest of
862 the distribution - please see the source code in F<Cwd.xs> for the