Fix TestLib::slurp_file() with offset on windows.
authorAndres Freund <[email protected]>
Mon, 4 Oct 2021 20:28:06 +0000 (13:28 -0700)
committerAndres Freund <[email protected]>
Mon, 4 Oct 2021 20:33:08 +0000 (13:33 -0700)
3c5b0685b921 used setFilePointer() to set the position of the filehandle, but
passed the wrong filehandle, always leaving the position at 0. Instead of just
fixing that, remove use of setFilePointer(), we have a perl fd at this point,
so we can just use perl's seek().

Additionally, the perl filehandle wasn't closed, just the windows filehandle.

Reviewed-By: Andrew Dunstan <[email protected]>
Author: Andres Freund <[email protected]>
Discussion: https://postgr.es/m/20211003173038[email protected]
Backpatch: 9.6-, like 3c5b0685b921

src/test/perl/TestLib.pm

index 610736aeb5b27edfb3fa925ccf48cf987b05b170..2320ead9d5863194f83068a4ef85285210290fff 100644 (file)
@@ -99,7 +99,7 @@ BEGIN
    if ($windows_os)
    {
        require Win32API::File;
-       Win32API::File->import(qw(createFile OsFHandleOpen CloseHandle setFilePointer));
+       Win32API::File->import(qw(createFile OsFHandleOpen CloseHandle));
    }
 }
 
@@ -280,33 +280,33 @@ sub slurp_file
    my ($filename, $offset) = @_;
    local $/;
    my $contents;
+   my $fh;
+
+   # On windows open file using win32 APIs, to allow us to set the
+   # FILE_SHARE_DELETE flag ("d" below), otherwise other accesses to the file
+   # may fail.
    if ($Config{osname} ne 'MSWin32')
    {
-       open(my $in, '<', $filename)
+       open($fh, '<', $filename)
          or die "could not read \"$filename\": $!";
-       if (defined($offset))
-       {
-           seek($in, $offset, SEEK_SET)
-             or die "could not seek \"$filename\": $!";
-       }
-       $contents = <$in>;
-       close $in;
    }
    else
    {
        my $fHandle = createFile($filename, "r", "rwd")
          or die "could not open \"$filename\": $^E";
-       OsFHandleOpen(my $fh = IO::Handle->new(), $fHandle, 'r')
+       OsFHandleOpen($fh = IO::Handle->new(), $fHandle, 'r')
          or die "could not read \"$filename\": $^E\n";
-       if (defined($offset))
-       {
-           setFilePointer($fh, $offset, qw(FILE_BEGIN))
-             or die "could not seek \"$filename\": $^E\n";
-       }
-       $contents = <$fh>;
-       CloseHandle($fHandle)
-         or die "could not close \"$filename\": $^E\n";
    }
+
+   if (defined($offset))
+   {
+       seek($fh, $offset, SEEK_SET)
+         or die "could not seek \"$filename\": $!";
+   }
+
+   $contents = <$fh>;
+   close $fh;
+
    $contents =~ s/\r\n/\n/g if $Config{osname} eq 'msys';
    return $contents;
 }