Skip to content

Commit

Permalink
ls: avoid invalid closedir() (#801)
Browse files Browse the repository at this point in the history
* When temporarily enabling warnings.pm I observed a warning in DirEntries(): closedir() attempted on invalid dirhandle $dh
* The way the code was written, opendir() was always called even if the file was not a directory
* Delay the opendir() call until we know that we don't want to list a regular file
* opendir() should not happen if running "ls -d", or if the argument to DirEntries() is not a directory
  • Loading branch information
mknos authored Nov 12, 2024
1 parent 0c0305a commit c67fc0d
Showing 1 changed file with 5 additions and 2 deletions.
7 changes: 5 additions & 2 deletions bin/ls
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,8 @@ sub DirEntries {
my @Entries = (); # entries in original order
my $Name = ""; # entry name

if (!opendir($dh, $_[0]) || exists($Options{'d'})) {
if (exists $Options{'d'} || ! -d $_[0]) {
if (-e $_[0]) {
closedir($dh) if (defined($dh));
push(@Entries, $_[0]);
$Attributes{$_[0]} = stat($_[0]);
push(@Entries, \%Attributes);
Expand All @@ -161,6 +160,10 @@ sub DirEntries {
warn "$Program: can't access '$_[0]': $!\n";
return ();
}
unless (opendir $dh, $_[0]) {
warn "$Program: failed to open directory '$_[0]': $!\n";
return ();
}
while ($Name = readdir($dh)) {
next if (!exists($Options->{'a'}) &&
$Name =~ m/^\./o);
Expand Down

0 comments on commit c67fc0d

Please sign in to comment.