In addition to using an ancient development environment, with terrible UX, Greta also has the misfortune of working in Pascal.

Recently, she was diagnosing a bug. The program was reporting that files didn't exist when they definitely existed. She traced the problem down into the system library. Let's see if you can spot what's wrong:

{ Delphi / Kylix Cross-Platform Runtime Library                           }
{ System Utilities Unit                                                   }
{                                                                         }
{ Copyright (c) 1995-2001 Borland Softwrare Corporation                   }
...

function FileAge(const FileName: string): Integer;
{$IFDEF MSWINDOWS}
var
  Handle: THandle;
  FindData: TWin32FindData;
  LocalFileTime: TFileTime;
begin
  Handle := FindFirstFile(PChar(FileName), FindData);
  if Handle <> INVALID_HANDLE_VALUE then
  begin
    Windows.FindClose(Handle);
    if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then
    begin
      FileTimeToLocalFileTime(FindData.ftLastWriteTime, LocalFileTime);
      if FileTimeToDosDateTime(LocalFileTime, LongRec(Result).Hi,
        LongRec(Result).Lo) then Exit;
    end;
  end;
  Result := -1;
end;
{$ENDIF}

function FileExists(const FileName: string): Boolean;
{$IFDEF MSWINDOWS}
begin
  Result := FileAge(FileName) <> -1;
end;
{$ENDIF}

The first function here is FileAge, which returns the last modified timestamp on a file. Note the use of FileTimeToDosDateTime, which is a Windows API function. It converts LocalFileTime and stores the date part in the first output parameter (LongRec(Result).Hi) and the time part in the second output parameter (LongRec(Result).Lo). Result, in this case, is our return value. If anything goes wrong, we return -1.

The FileExists function then, simply calls FileAge. If it doesn't return a -1, there must be a file there.

That's an awkward, weird solution to the problem. There has to be a system call that can answer that question more obviously. But it doesn't seem like it should be blowing up- it looks like it should work.

But note that FileTimeToDosDateTime also returns a boolean value. If it succeeds, great, but if it fails, it returns false and sets an error code you can check. An error code that definitely isn't being checked.

And this brings us to the root cause of Greta's bug: the process that's writing the files isn't setting the "last write time", so while the file exists, the attempt to check its age fails, so FileExists believes that the file doesn't exist, just because it doesn't have a valid timestamp.

This is the kind of high quality softwrare that sometimes infects our system libraries.

[Advertisement] Keep the plebs out of prod. Restrict NuGet feed privileges with ProGet. Learn more.