filesystem-disk-win32.c++ 57.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// Copyright (c) 2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#if _WIN32
// For Unix implementation, see filesystem-disk-unix.c++.

25 26 27 28 29 30
// Request Vista-level APIs.
#define WINVER 0x0600
#define _WIN32_WINNT 0x0600

#define WIN32_LEAN_AND_MEAN  // ::eyeroll::

31 32 33 34 35 36 37
#include "filesystem.h"
#include "debug.h"
#include "encoding.h"
#include "vector.h"
#include <algorithm>
#include <wchar.h>

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
#include <windows.h>
#include <winioctl.h>
#include "windows-sanity.h"

namespace kj {

static Own<ReadableDirectory> newDiskReadableDirectory(AutoCloseHandle fd, Path&& path);
static Own<Directory> newDiskDirectory(AutoCloseHandle fd, Path&& path);

static AutoCloseHandle* getHandlePointerHack(File& file) { return nullptr; }
static AutoCloseHandle* getHandlePointerHack(Directory& dir);
static Path* getPathPointerHack(File& file) { return nullptr; }
static Path* getPathPointerHack(Directory& dir);

namespace {

struct REPARSE_DATA_BUFFER {
  // From ntifs.h, which is part of the driver development kit so not necessarily available I
  // guess.
  ULONG ReparseTag;
  USHORT ReparseDataLength;
  USHORT Reserved;
60
  union {
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
    struct {
      USHORT SubstituteNameOffset;
      USHORT SubstituteNameLength;
      USHORT PrintNameOffset;
      USHORT PrintNameLength;
      ULONG Flags;
      WCHAR PathBuffer[1];
    } SymbolicLinkReparseBuffer;
    struct {
      USHORT SubstituteNameOffset;
      USHORT SubstituteNameLength;
      USHORT PrintNameOffset;
      USHORT PrintNameLength;
      WCHAR PathBuffer[1];
    } MountPointReparseBuffer;
    struct {
      UCHAR DataBuffer[1];
    } GenericReparseBuffer;
79
  };
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
};

#define HIDDEN_PREFIX ".kj-tmp."
// Prefix for temp files which should be hidden when listing a directory.
//
// If you change this, make sure to update the unit test.

static constexpr int64_t WIN32_EPOCH_OFFSET = 116444736000000000ull;
// Number of 100ns intervals from Jan 1, 1601 to Jan 1, 1970.

static Date toKjDate(FILETIME t) {
  int64_t value = (static_cast<uint64_t>(t.dwHighDateTime) << 32) | t.dwLowDateTime;
  return (value - WIN32_EPOCH_OFFSET) * (100 * kj::NANOSECONDS) + UNIX_EPOCH;
}

static FsNode::Type modeToType(DWORD attrs, DWORD reparseTag) {
  if ((attrs & FILE_ATTRIBUTE_REPARSE_POINT) &&
      reparseTag == IO_REPARSE_TAG_SYMLINK) {
    return FsNode::Type::SYMLINK;
  }
  if (attrs & FILE_ATTRIBUTE_DIRECTORY) return FsNode::Type::DIRECTORY;
  return FsNode::Type::FILE;
}

static FsNode::Metadata statToMetadata(const BY_HANDLE_FILE_INFORMATION& stats) {
  uint64_t size = (implicitCast<uint64_t>(stats.nFileSizeHigh) << 32) | stats.nFileSizeLow;

107 108 109 110 111 112
  // Assume file index is usually a small number, i.e. nFileIndexHigh is usually 0. So we try to
  // put the serial number in the upper 32 bits and the index in the lower.
  uint64_t hash = ((uint64_t(stats.dwVolumeSerialNumber) << 32)
                 ^ (uint64_t(stats.nFileIndexHigh) << 32))
                | (uint64_t(stats.nFileIndexLow));

113 114 115 116 117 118 119
  return FsNode::Metadata {
    modeToType(stats.dwFileAttributes, 0),
    size,
    // In theory, spaceUsed should be based on GetCompressedFileSize(), but requiring an extra
    // syscall for something rarely used would be sad.
    size,
    toKjDate(stats.ftLastWriteTime),
120 121
    stats.nNumberOfLinks,
    hash
122 123 124 125 126 127 128 129 130 131 132 133 134 135
  };
}

static FsNode::Metadata statToMetadata(const WIN32_FIND_DATAW& stats) {
  uint64_t size = (implicitCast<uint64_t>(stats.nFileSizeHigh) << 32) | stats.nFileSizeLow;

  return FsNode::Metadata {
    modeToType(stats.dwFileAttributes, stats.dwReserved0),
    size,
    // In theory, spaceUsed should be based on GetCompressedFileSize(), but requiring an extra
    // syscall for something rarely used would be sad.
    size,
    toKjDate(stats.ftLastWriteTime),
    // We can't get the number of links without opening the file, apparently. Meh.
136 137 138
    1,
    // We can't produce a reliable hashCode without opening the file.
    0
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
  };
}

static Array<wchar_t> join16(ArrayPtr<const wchar_t> path, const wchar_t* file) {
  // Assumes `path` ends with a NUL terminator (and `file` is of course NUL terminated as well).

  size_t len = wcslen(file) + 1;
  auto result = kj::heapArray<wchar_t>(path.size() + len);
  memcpy(result.begin(), path.begin(), path.asBytes().size() - sizeof(wchar_t));
  result[path.size() - 1] = '\\';
  memcpy(result.begin() + path.size(), file, len * sizeof(wchar_t));
  return result;
}

static String dbgStr(ArrayPtr<const wchar_t> wstr) {
  if (wstr.size() > 0 && wstr[wstr.size() - 1] == L'\0') {
    wstr = wstr.slice(0, wstr.size() - 1);
  }
  return decodeWideString(wstr);
}

static void rmrfChildren(ArrayPtr<const wchar_t> path) {
161
  auto glob = join16(path, L"*");
162

163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
  WIN32_FIND_DATAW data;
  HANDLE handle = FindFirstFileW(glob.begin(), &data);
  if (handle == INVALID_HANDLE_VALUE) {
    auto error = GetLastError();
    if (error == ERROR_FILE_NOT_FOUND) return;
    KJ_FAIL_WIN32("FindFirstFile", error, dbgStr(glob)) { return; }
  }
  KJ_DEFER(KJ_WIN32(FindClose(handle)) { break; });

  do {
    // Ignore "." and "..", ugh.
    if (data.cFileName[0] == L'.') {
      if (data.cFileName[1] == L'\0' ||
          (data.cFileName[1] == L'.' && data.cFileName[2] == L'\0')) {
        continue;
178
      }
179
    }
180

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
    auto child = join16(path, data.cFileName);
    // For rmrf purposes, we assume any "reparse points" are symlink-like, even if they aren't
    // actually the "symbolic link" reparse type, because we don't want to recursively delete any
    // shared content.
    if ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
        !(data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
      rmrfChildren(child);
      uint retryCount = 0;
    retry:
      KJ_WIN32_HANDLE_ERRORS(RemoveDirectoryW(child.begin())) {
        case ERROR_DIR_NOT_EMPTY:
          // On Windows, deleting a file actually only schedules it for deletion. Under heavy
          // load it may take a bit for the deletion to go through. Or, if another process has
          // the file open, it may not be deleted until that process closes it.
          //
          // We'll repeatedly retry for up to 100ms, then give up. This is awful but there's no
          // way to tell for sure if the system is just being slow or if someone has the file
          // open.
          if (retryCount++ < 10) {
            Sleep(10);
            goto retry;
          }
          // fallthrough
        default:
          KJ_FAIL_WIN32("RemoveDirectory", error, dbgStr(child)) { break; }
206
      }
207 208
    } else {
      KJ_WIN32(DeleteFileW(child.begin()));
209
    }
210
  } while (FindNextFileW(handle, &data));
211

212 213 214
  auto error = GetLastError();
  if (error != ERROR_NO_MORE_FILES) {
    KJ_FAIL_WIN32("FindNextFile", error, dbgStr(path)) { return; }
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
  }
}

static bool rmrf(ArrayPtr<const wchar_t> path) {
  // Figure out whether this is a file or a directory.
  //
  // We use FindFirstFileW() because in the case of symlinks it will return info about the
  // symlink rather than info about the target.
  WIN32_FIND_DATAW data;
  HANDLE handle = FindFirstFileW(path.begin(), &data);
  if (handle == INVALID_HANDLE_VALUE) {
    auto error = GetLastError();
    if (error == ERROR_FILE_NOT_FOUND) return false;
    KJ_FAIL_WIN32("FindFirstFile", error, dbgStr(path));
  }
  KJ_WIN32(FindClose(handle));

  // For remove purposes, we assume any "reparse points" are symlink-like, even if they aren't
  // actually the "symbolic link" reparse type, because we don't want to recursively delete any
  // shared content.
  if ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
      !(data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
    // directory
    rmrfChildren(path);
    KJ_WIN32(RemoveDirectoryW(path.begin()), dbgStr(path));
  } else {
    KJ_WIN32(DeleteFileW(path.begin()), dbgStr(path));
  }

  return true;
}

static Path getPathFromHandle(HANDLE handle) {
  DWORD tryLen = MAX_PATH;
  for (;;) {
    auto temp = kj::heapArray<wchar_t>(tryLen + 1);
    DWORD len = GetFinalPathNameByHandleW(handle, temp.begin(), tryLen, 0);
    if (len == 0) {
      KJ_FAIL_WIN32("GetFinalPathNameByHandleW", GetLastError());
    }
    if (len < temp.size()) {
      return Path::parseWin32Api(temp.slice(0, len));
    }
    // Try again with new length.
    tryLen = len;
  }
}

struct MmapRange {
  uint64_t offset;
  uint64_t size;
};

static size_t getAllocationGranularity() {
  SYSTEM_INFO info;
  GetSystemInfo(&info);
  return info.dwAllocationGranularity;
};

static MmapRange getMmapRange(uint64_t offset, uint64_t size) {
  // Rounds the given offset down to the nearest page boundary, and adjusts the size up to match.
  // (This is somewhat different from Unix: we do NOT round the size up to an even multiple of
  // pages.)
  static const uint64_t pageSize = getAllocationGranularity();
  uint64_t pageMask = pageSize - 1;

  uint64_t realOffset = offset & ~pageMask;

  uint64_t end = offset + size;

  return { realOffset, end - realOffset };
}

class MmapDisposer: public ArrayDisposer {
protected:
  void disposeImpl(void* firstElement, size_t elementSize, size_t elementCount,
                   size_t capacity, void (*destroyElement)(void*)) const {
    auto range = getMmapRange(reinterpret_cast<uintptr_t>(firstElement),
                              elementSize * elementCount);
    void* mapping = reinterpret_cast<void*>(range.offset);
    if (mapping != nullptr) {
      KJ_ASSERT(UnmapViewOfFile(mapping)) { break; }
    }
  }
};

301
#if _MSC_VER && _MSC_VER < 1910
302 303 304
// TODO(msvc): MSVC 2015 can't initialize a constexpr's vtable correctly.
const MmapDisposer mmapDisposer = MmapDisposer();
#else
305
constexpr MmapDisposer mmapDisposer = MmapDisposer();
306
#endif
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351

void* win32Mmap(HANDLE handle, MmapRange range, DWORD pageProtect, DWORD access) {
  HANDLE mappingHandle;
  mappingHandle = CreateFileMappingW(handle, NULL, pageProtect, 0, 0, NULL);
  if (mappingHandle == INVALID_HANDLE_VALUE) {
    auto error = GetLastError();
    if (error == ERROR_FILE_INVALID && range.size == 0) {
      // The documentation says that CreateFileMapping will fail with ERROR_FILE_INVALID if the
      // file size is zero. Ugh.
      return nullptr;
    }
    KJ_FAIL_WIN32("CreateFileMapping", error);
  }
  KJ_DEFER(KJ_WIN32(CloseHandle(mappingHandle)) { break; });

  void* mapping = MapViewOfFile(mappingHandle, access,
      static_cast<DWORD>(range.offset >> 32), static_cast<DWORD>(range.offset), range.size);
  if (mapping == nullptr) {
    KJ_FAIL_WIN32("MapViewOfFile", GetLastError());
  }

  // It's unclear from the documentation whether mappings will always start at a multiple of the
  // allocation granularity, but we depend on that later, so check it...
  KJ_ASSERT(getMmapRange(reinterpret_cast<uintptr_t>(mapping), 0).size == 0);

  return mapping;
}

class DiskHandle {
  // We need to implement each of ReadableFile, AppendableFile, File, ReadableDirectory, and
  // Directory for disk handles. There is a lot of implementation overlap between these, especially
  // stat(), sync(), etc. We can't have everything inherit from a common DiskFsNode that implements
  // these because then we get diamond inheritance which means we need to make all our inheritance
  // virtual which means downcasting requires RTTI which violates our goal of supporting compiling
  // with no RTTI. So instead we have the DiskHandle class which implements all the methods without
  // inheriting anything, and then we have DiskFile, DiskDirectory, etc. hold this and delegate to
  // it. Ugly, but works.

public:
  DiskHandle(AutoCloseHandle&& handle, Maybe<Path> dirPath)
      : handle(kj::mv(handle)), dirPath(kj::mv(dirPath)) {}

  AutoCloseHandle handle;
  kj::Maybe<Path> dirPath;  // needed for directories, empty for files

352
  Array<wchar_t> nativePath(PathPtr path) const {
353 354 355 356 357
    return KJ_ASSERT_NONNULL(dirPath).append(path).forWin32Api(true);
  }

  // OsHandle ------------------------------------------------------------------

358
  AutoCloseHandle clone() const {
359 360 361 362 363 364
    HANDLE newHandle;
    KJ_WIN32(DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), &newHandle,
                             0, FALSE, DUPLICATE_SAME_ACCESS));
    return AutoCloseHandle(newHandle);
  }

365
  HANDLE getWin32Handle() const {
366 367 368 369 370
    return handle.get();
  }

  // FsNode --------------------------------------------------------------------

371
  FsNode::Metadata stat() const {
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
    BY_HANDLE_FILE_INFORMATION stats;
    KJ_WIN32(GetFileInformationByHandle(handle, &stats));
    auto metadata = statToMetadata(stats);

    // Get space usage, e.g. for sparse files. Apparently the correct way to do this is to query
    // "compression".
    FILE_COMPRESSION_INFO compInfo;
    KJ_WIN32_HANDLE_ERRORS(GetFileInformationByHandleEx(
        handle, FileCompressionInfo, &compInfo, sizeof(compInfo))) {
      case ERROR_CALL_NOT_IMPLEMENTED:
        // Probably WINE.
        break;
      default:
        KJ_FAIL_WIN32("GetFileInformationByHandleEx(FileCompressionInfo)", error) { break; }
        break;
    } else {
      metadata.spaceUsed = compInfo.CompressedFileSize.QuadPart;
    }

    return metadata;
  }

394 395
  void sync() const { KJ_WIN32(FlushFileBuffers(handle)); }
  void datasync() const { KJ_WIN32(FlushFileBuffers(handle)); }
396 397 398

  // ReadableFile --------------------------------------------------------------

399
  size_t read(uint64_t offset, ArrayPtr<byte> buffer) const {
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
    // ReadFile() probably never returns short reads unless it hits EOF. Unfortunately, though,
    // this is not documented, and it's unclear whether we can rely on it.

    size_t total = 0;
    while (buffer.size() > 0) {
      // Apparently, the way to fake pread() on Windows is to provide an OVERLAPPED structure even
      // though we're not doing overlapped I/O.
      OVERLAPPED overlapped;
      memset(&overlapped, 0, sizeof(overlapped));
      overlapped.Offset = static_cast<DWORD>(offset);
      overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32);

      DWORD n;
      KJ_WIN32_HANDLE_ERRORS(ReadFile(handle, buffer.begin(), buffer.size(), &n, &overlapped)) {
        case ERROR_HANDLE_EOF:
          // The documentation claims this shouldn't happen for synchronous reads, but it seems
          // to happen for me, at least under WINE.
          n = 0;
          break;
        default:
          KJ_FAIL_WIN32("ReadFile", offset, buffer.size()) { return total; }
      }
      if (n == 0) break;
      total += n;
      offset += n;
      buffer = buffer.slice(n, buffer.size());
    }
    return total;
  }

430
  Array<const byte> mmap(uint64_t offset, uint64_t size) const {
431 432 433 434 435 436
    auto range = getMmapRange(offset, size);
    const void* mapping = win32Mmap(handle, range, PAGE_READONLY, FILE_MAP_READ);
    return Array<const byte>(reinterpret_cast<const byte*>(mapping) + (offset - range.offset),
                             size, mmapDisposer);
  }

437
  Array<byte> mmapPrivate(uint64_t offset, uint64_t size) const {
438 439 440 441 442 443 444 445
    auto range = getMmapRange(offset, size);
    void* mapping = win32Mmap(handle, range, PAGE_READONLY, FILE_MAP_COPY);
    return Array<byte>(reinterpret_cast<byte*>(mapping) + (offset - range.offset),
                       size, mmapDisposer);
  }

  // File ----------------------------------------------------------------------

446
  void write(uint64_t offset, ArrayPtr<const byte> data) const {
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
    // WriteFile() probably never returns short writes unless there's no space left on disk.
    // Unfortunately, though, this is not documented, and it's unclear whether we can rely on it.

    while (data.size() > 0) {
      // Apparently, the way to fake pwrite() on Windows is to provide an OVERLAPPED structure even
      // though we're not doing overlapped I/O.
      OVERLAPPED overlapped;
      memset(&overlapped, 0, sizeof(overlapped));
      overlapped.Offset = static_cast<DWORD>(offset);
      overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32);

      DWORD n;
      KJ_WIN32(WriteFile(handle, data.begin(), data.size(), &n, &overlapped));
      KJ_ASSERT(n > 0, "WriteFile() returned zero?");
      offset += n;
      data = data.slice(n, data.size());
    }
  }

466
  void zero(uint64_t offset, uint64_t size) const {
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
    FILE_ZERO_DATA_INFORMATION info;
    memset(&info, 0, sizeof(info));
    info.FileOffset.QuadPart = offset;
    info.BeyondFinalZero.QuadPart = offset + size;

    DWORD dummy;
    KJ_WIN32_HANDLE_ERRORS(DeviceIoControl(handle, FSCTL_SET_ZERO_DATA, &info,
                                           sizeof(info), NULL, 0, &dummy, NULL)) {
      case ERROR_NOT_SUPPORTED: {
        // Dang. Let's do it the hard way.
        static const byte ZEROS[4096] = { 0 };

        while (size > sizeof(ZEROS)) {
          write(offset, ZEROS);
          size -= sizeof(ZEROS);
          offset += sizeof(ZEROS);
        }
        write(offset, kj::arrayPtr(ZEROS, size));
        break;
      }

      default:
        KJ_FAIL_WIN32("DeviceIoControl(FSCTL_SET_ZERO_DATA)", error);
        break;
    }
  }

494
  void truncate(uint64_t size) const {
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
    // SetEndOfFile() would require seeking the file. It looks like SetFileInformationByHandle()
    // lets us avoid this!
    FILE_END_OF_FILE_INFO info;
    memset(&info, 0, sizeof(info));
    info.EndOfFile.QuadPart = size;
    KJ_WIN32_HANDLE_ERRORS(
        SetFileInformationByHandle(handle, FileEndOfFileInfo, &info, sizeof(info))) {
      case ERROR_CALL_NOT_IMPLEMENTED: {
        // Wine doesn't implement this. :(

        LONG currentHigh = 0;
        LONG currentLow = SetFilePointer(handle, 0, &currentHigh, FILE_CURRENT);
        if (currentLow == INVALID_SET_FILE_POINTER) {
          KJ_FAIL_WIN32("SetFilePointer", GetLastError());
        }
        uint64_t current = (uint64_t(currentHigh) << 32) | uint64_t((ULONG)currentLow);

        LONG endLow = size & 0x00000000ffffffffull;
        LONG endHigh = size >> 32;
        if (SetFilePointer(handle, endLow, &endHigh, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {
          KJ_FAIL_WIN32("SetFilePointer", GetLastError());
        }

        KJ_WIN32(SetEndOfFile(handle));

        if (current < size) {
          if (SetFilePointer(handle, currentLow, &currentHigh, FILE_BEGIN) ==
                  INVALID_SET_FILE_POINTER) {
            KJ_FAIL_WIN32("SetFilePointer", GetLastError());
          }
        }

        break;
      }
      default:
        KJ_FAIL_WIN32("SetFileInformationByHandle", error);
    }
  }

  class WritableFileMappingImpl final: public WritableFileMapping {
  public:
    WritableFileMappingImpl(Array<byte> bytes): bytes(kj::mv(bytes)) {}

538 539 540 541
    ArrayPtr<byte> get() const override {
      // const_cast OK because WritableFileMapping does indeed provide a writable view despite
      // being const itself.
      return arrayPtr(const_cast<byte*>(bytes.begin()), bytes.size());
542 543
    }

544
    void changed(ArrayPtr<byte> slice) const override {
545 546 547 548 549 550
      KJ_REQUIRE(slice.begin() >= bytes.begin() && slice.end() <= bytes.end(),
                 "byte range is not part of this mapping");

      // Nothing needed here -- NT tracks dirty pages.
    }

551
    void sync(ArrayPtr<byte> slice) const override {
552 553 554 555 556 557 558 559 560 561 562 563 564
      KJ_REQUIRE(slice.begin() >= bytes.begin() && slice.end() <= bytes.end(),
                 "byte range is not part of this mapping");

      // Zero is treated specially by FlushViewOfFile(), so check for it.
      if (slice.size() > 0) {
        KJ_WIN32(FlushViewOfFile(slice.begin(), slice.size()));
      }
    }

  private:
    Array<byte> bytes;
  };

565
  Own<const WritableFileMapping> mmapWritable(uint64_t offset, uint64_t size) const {
566 567 568 569 570 571 572 573 574 575 576 577
    auto range = getMmapRange(offset, size);
    void* mapping = win32Mmap(handle, range, PAGE_READWRITE, FILE_MAP_ALL_ACCESS);
    auto array = Array<byte>(reinterpret_cast<byte*>(mapping) + (offset - range.offset),
                             size, mmapDisposer);
    return heap<WritableFileMappingImpl>(kj::mv(array));
  }

  // copy() is not optimized on Windows.

  // ReadableDirectory ---------------------------------------------------------

  template <typename Func>
578
  auto list(bool needTypes, Func&& func) const
579 580
      -> Array<Decay<decltype(func(instance<StringPtr>(), instance<FsNode::Type>()))>> {
    PathPtr path = KJ_ASSERT_NONNULL(dirPath);
581
    auto glob = join16(path.forWin32Api(true), L"*");
582 583 584 585 586 587 588 589

    // TODO(perf): Use FindFileEx() with FindExInfoBasic? Not apparently supported on Vista.
    // TODO(someday): Use NtQueryDirectoryObject() instead? It's "internal", but so much cleaner.
    WIN32_FIND_DATAW data;
    HANDLE handle = FindFirstFileW(glob.begin(), &data);
    if (handle == INVALID_HANDLE_VALUE) {
      auto error = GetLastError();
      if (error == ERROR_FILE_NOT_FOUND) return nullptr;
590
      KJ_FAIL_WIN32("FindFirstFile", error, dbgStr(glob));
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
    }
    KJ_DEFER(KJ_WIN32(FindClose(handle)) { break; });

    typedef Decay<decltype(func(instance<StringPtr>(), instance<FsNode::Type>()))> Entry;
    kj::Vector<Entry> entries;

    do {
      auto name = decodeUtf16(
          arrayPtr(reinterpret_cast<char16_t*>(data.cFileName), wcslen(data.cFileName)));
      if (name != "." && name != ".." && !name.startsWith(HIDDEN_PREFIX)) {
        entries.add(func(name, modeToType(data.dwFileAttributes, data.dwReserved0)));
      }
    } while (FindNextFileW(handle, &data));

    auto error = GetLastError();
    if (error != ERROR_NO_MORE_FILES) {
      KJ_FAIL_WIN32("FindNextFile", error, path);
    }

    auto result = entries.releaseAsArray();
    std::sort(result.begin(), result.end());
    return result;
  }

615
  Array<String> listNames() const {
616 617 618
    return list(false, [](StringPtr name, FsNode::Type type) { return heapString(name); });
  }

619
  Array<ReadableDirectory::Entry> listEntries() const {
620 621 622 623 624
    return list(true, [](StringPtr name, FsNode::Type type) {
      return ReadableDirectory::Entry { type, heapString(name), };
    });
  }

625
  bool exists(PathPtr path) const {
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
    DWORD result = GetFileAttributesW(nativePath(path).begin());
    if (result == INVALID_FILE_ATTRIBUTES) {
      auto error = GetLastError();
      switch (error) {
        case ERROR_FILE_NOT_FOUND:
        case ERROR_PATH_NOT_FOUND:
          return false;
        default:
          KJ_FAIL_WIN32("GetFileAttributesEx(path)", error, path) { return false; }
      }
    } else {
      return true;
    }
  }

641
  Maybe<FsNode::Metadata> tryLstat(PathPtr path) const {
642 643 644 645 646 647 648 649 650 651 652 653 654 655
    // We use FindFirstFileW() because in the case of symlinks it will return info about the
    // symlink rather than info about the target.
    WIN32_FIND_DATAW data;
    HANDLE handle = FindFirstFileW(nativePath(path).begin(), &data);
    if (handle == INVALID_HANDLE_VALUE) {
      auto error = GetLastError();
      if (error == ERROR_FILE_NOT_FOUND) return nullptr;
      KJ_FAIL_WIN32("FindFirstFile", error, path);
    } else {
      KJ_WIN32(FindClose(handle));
      return statToMetadata(data);
    }
  }

656
  Maybe<Own<const ReadableFile>> tryOpenFile(PathPtr path) const {
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
    HANDLE newHandle;
    KJ_WIN32_HANDLE_ERRORS(newHandle = CreateFileW(
        nativePath(path).begin(),
        GENERIC_READ,
        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL)) {
      case ERROR_FILE_NOT_FOUND:
      case ERROR_PATH_NOT_FOUND:
        return nullptr;
      default:
        KJ_FAIL_WIN32("CreateFile(path, OPEN_EXISTING)", error, path) { return nullptr; }
    }

    return newDiskReadableFile(kj::AutoCloseHandle(newHandle));
  }

676
  Maybe<AutoCloseHandle> tryOpenSubdirInternal(PathPtr path) const {
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
    HANDLE newHandle;
    KJ_WIN32_HANDLE_ERRORS(newHandle = CreateFileW(
        nativePath(path).begin(),
        GENERIC_READ,
        // When opening directories, we do NOT use FILE_SHARE_DELETE, because we need the directory
        // path to remain vaild.
        //
        // TODO(someday): Use NtCreateFile() and related "internal" APIs that allow for
        //   openat()-like behavior?
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        OPEN_EXISTING,
        FILE_FLAG_BACKUP_SEMANTICS,  // apparently, this flag is required for directories
        NULL)) {
      case ERROR_FILE_NOT_FOUND:
      case ERROR_PATH_NOT_FOUND:
        return nullptr;
      default:
        KJ_FAIL_WIN32("CreateFile(directoryPath, OPEN_EXISTING)", error, path) { return nullptr; }
    }

    kj::AutoCloseHandle ownHandle(newHandle);

    BY_HANDLE_FILE_INFORMATION info;
    KJ_WIN32(GetFileInformationByHandle(ownHandle, &info));

    KJ_REQUIRE(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY, "not a directory", path);
    return kj::mv(ownHandle);
  }

707
  Maybe<Own<const ReadableDirectory>> tryOpenSubdir(PathPtr path) const {
708 709 710 711 712
    return tryOpenSubdirInternal(path).map([&](AutoCloseHandle&& handle) {
      return newDiskReadableDirectory(kj::mv(handle), KJ_ASSERT_NONNULL(dirPath).append(path));
    });
  }

713
  Maybe<String> tryReadlink(PathPtr path) const {
714 715 716 717 718 719
    // Windows symlinks work differently from Unix. Generally they are set up by the system
    // administrator and apps are expected to treat them transparently. Hence, on Windows, we act
    // as if nothing is a symlink by always returning null here.
    // TODO(someday): If we want to treat Windows symlinks more like Unix ones, start by reverting
    //   the comment that added this comment.
    return nullptr;
720 721 722 723 724 725 726 727 728 729 730 731
  }

  // Directory -----------------------------------------------------------------

  static LPSECURITY_ATTRIBUTES makeSecAttr(WriteMode mode) {
    if (has(mode, WriteMode::PRIVATE)) {
      KJ_UNIMPLEMENTED("WriteMode::PRIVATE on Win32 is not implemented");
    }

    return nullptr;
  }

732
  bool tryMkdir(PathPtr path, WriteMode mode, bool noThrow) const {
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
    // Internal function to make a directory.

    auto filename = nativePath(path);

    KJ_WIN32_HANDLE_ERRORS(CreateDirectoryW(filename.begin(), makeSecAttr(mode))) {
      case ERROR_ALREADY_EXISTS:
      case ERROR_FILE_EXISTS: {
        // Apparently this path exists.
        if (!has(mode, WriteMode::MODIFY)) {
          // Require exclusive create.
          return false;
        }

        // MODIFY is allowed, so we just need to check whether the existing entry is a directory.
        DWORD attr = GetFileAttributesW(filename.begin());
        if (attr == INVALID_FILE_ATTRIBUTES) {
          // CreateDirectory() says it already exists but we can't get attributes. Maybe it's a
          // dangling link, or maybe we can't access it for some reason. Assume failure.
          //
          // TODO(someday): Maybe we should be creating the directory at the target of the
          //   link?
          goto failed;
        }
        return attr & FILE_ATTRIBUTE_DIRECTORY;
      }
      case ERROR_PATH_NOT_FOUND:
        if (has(mode, WriteMode::CREATE_PARENT) && path.size() > 0 &&
            tryMkdir(path.parent(), WriteMode::CREATE | WriteMode::MODIFY |
                                    WriteMode::CREATE_PARENT, true)) {
          // Retry, but make sure we don't try to create the parent again.
          return tryMkdir(path, mode - WriteMode::CREATE_PARENT, noThrow);
        } else {
          goto failed;
        }
      default:
      failed:
        if (noThrow) {
          // Caller requested no throwing.
          return false;
        } else {
          KJ_FAIL_WIN32("CreateDirectory", error, path);
        }
    }

    return true;
  }

  kj::Maybe<Array<wchar_t>> createNamedTemporary(
      PathPtr finalName, WriteMode mode, Path& kjTempPath,
782
      Function<BOOL(const wchar_t*)> tryCreate) const {
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
    // Create a temporary file which will eventually replace `finalName`.
    //
    // Calls `tryCreate` to actually create the temporary, passing in the desired path. tryCreate()
    // is expected to behave like a win32 call, returning a BOOL and setting `GetLastError()` on
    // error. tryCreate() MUST fail with ERROR_{FILE,ALREADY}_EXISTS if the path exists -- this is
    // not checked in advance, since it needs to be checked atomically. In the case of
    // ERROR_*_EXISTS, tryCreate() will be called again with a new path.
    //
    // Returns the temporary path that succeeded. Only returns nullptr if there was an exception
    // but we're compiled with -fno-exceptions.
    //
    // The optional parameter `kjTempPath` is filled in with the KJ Path of the temporary.

    if (finalName.size() == 0) {
      KJ_FAIL_REQUIRE("can't replace self") { break; }
      return nullptr;
    }

    static uint counter = 0;
    static const DWORD pid = GetCurrentProcessId();
    auto tempName = kj::str(HIDDEN_PREFIX, pid, '.', counter++, '.',
                            finalName.basename()[0], ".partial");
    kjTempPath = finalName.parent().append(tempName);
    auto path = nativePath(kjTempPath);

    KJ_WIN32_HANDLE_ERRORS(tryCreate(path.begin())) {
      case ERROR_ALREADY_EXISTS:
      case ERROR_FILE_EXISTS:
        // Try again with a new counter value.
        return createNamedTemporary(finalName, mode, kj::mv(tryCreate));
      case ERROR_PATH_NOT_FOUND:
        if (has(mode, WriteMode::CREATE_PARENT) && finalName.size() > 1 &&
            tryMkdir(finalName.parent(), WriteMode::CREATE | WriteMode::MODIFY |
                                         WriteMode::CREATE_PARENT, true)) {
          // Retry, but make sure we don't try to create the parent again.
          mode = mode - WriteMode::CREATE_PARENT;
          return createNamedTemporary(finalName, mode, kj::mv(tryCreate));
        }
        // fallthrough
      default:
        KJ_FAIL_WIN32("create(path)", error, path) { break; }
        return nullptr;
    }

    return kj::mv(path);
  }

  kj::Maybe<Array<wchar_t>> createNamedTemporary(
831
      PathPtr finalName, WriteMode mode, Function<BOOL(const wchar_t*)> tryCreate) const {
832 833 834 835
    Path dummy = nullptr;
    return createNamedTemporary(finalName, mode, dummy, kj::mv(tryCreate));
  }

836 837
  bool tryReplaceNode(PathPtr path, WriteMode mode,
                      Function<BOOL(const wchar_t*)> tryCreate) const {
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
    // Replaces the given path with an object created by calling tryCreate().
    //
    // tryCreate() must behave like a win32 call which creates the node at the path passed to it,
    // returning FALSE error. If the path passed to tryCreate already exists, it MUST fail with
    // ERROR_{FILE,ALREADY}_EXISTS.
    //
    // When `mode` includes MODIFY, replaceNode() reacts to ERROR_*_EXISTS by creating the
    // node in a temporary location and then rename()ing it into place.

    if (path.size() == 0) {
      KJ_FAIL_REQUIRE("can't replace self") { return false; }
    }

    auto filename = nativePath(path);

    if (has(mode, WriteMode::CREATE)) {
      // First try just cerating the node in-place.
      KJ_WIN32_HANDLE_ERRORS(tryCreate(filename.begin())) {
        case ERROR_ALREADY_EXISTS:
        case ERROR_FILE_EXISTS:
          // Target exists.
          if (has(mode, WriteMode::MODIFY)) {
            // Fall back to MODIFY path, below.
            break;
          } else {
            return false;
          }
        case ERROR_PATH_NOT_FOUND:
          if (has(mode, WriteMode::CREATE_PARENT) && path.size() > 0 &&
              tryMkdir(path.parent(), WriteMode::CREATE | WriteMode::MODIFY |
                                      WriteMode::CREATE_PARENT, true)) {
            // Retry, but make sure we don't try to create the parent again.
            return tryReplaceNode(path, mode - WriteMode::CREATE_PARENT, kj::mv(tryCreate));
          }
872
          // fallthrough
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
        default:
          KJ_FAIL_WIN32("create(path)", error, path) { return false; }
      } else {
        // Success.
        return true;
      }
    }

    // Either we don't have CREATE mode or the target already exists. We need to perform a
    // replacement instead.

    KJ_IF_MAYBE(tempPath, createNamedTemporary(path, mode, kj::mv(tryCreate))) {
      if (tryCommitReplacement(path, *tempPath, mode)) {
        return true;
      } else {
        KJ_WIN32_HANDLE_ERRORS(DeleteFileW(tempPath->begin())) {
          case ERROR_FILE_NOT_FOUND:
            // meh
            break;
          default:
            KJ_FAIL_WIN32("DeleteFile(tempPath)", error, dbgStr(*tempPath));
        }
        return false;
      }
    } else {
      // threw, but exceptions are disabled
      return false;
    }
  }

903
  Maybe<AutoCloseHandle> tryOpenFileInternal(PathPtr path, WriteMode mode, bool append) const {
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
    DWORD disposition;
    if (has(mode, WriteMode::MODIFY)) {
      if (has(mode, WriteMode::CREATE)) {
        disposition = OPEN_ALWAYS;
      } else {
        disposition = OPEN_EXISTING;
      }
    } else {
      if (has(mode, WriteMode::CREATE)) {
        disposition = CREATE_NEW;
      } else {
        // Neither CREATE nor MODIFY -- impossible to satisfy preconditions.
        return nullptr;
      }
    }

    DWORD access = GENERIC_READ | GENERIC_WRITE;
    if (append) {
      // FILE_GENERIC_WRITE includes both FILE_APPEND_DATA and FILE_WRITE_DATA, but we only want
      // the former. There are also a zillion other bits that we need, annoyingly.
      access = (FILE_READ_ATTRIBUTES | FILE_GENERIC_WRITE) & ~FILE_WRITE_DATA;
    }

    auto filename = path.toString();

    HANDLE newHandle;
    KJ_WIN32_HANDLE_ERRORS(newHandle = CreateFileW(
        nativePath(path).begin(),
        access,
        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
        makeSecAttr(mode),
        disposition,
        FILE_ATTRIBUTE_NORMAL,
        NULL)) {
      case ERROR_PATH_NOT_FOUND:
        if (has(mode, WriteMode::CREATE)) {
          // A parent directory didn't exist. Maybe cerate it.
          if (has(mode, WriteMode::CREATE_PARENT) && path.size() > 0 &&
              tryMkdir(path.parent(), WriteMode::CREATE | WriteMode::MODIFY |
                                      WriteMode::CREATE_PARENT, true)) {
            // Retry, but make sure we don't try to create the parent again.
            return tryOpenFileInternal(path, mode - WriteMode::CREATE_PARENT, append);
          }

          KJ_FAIL_REQUIRE("parent is not a directory", path) { return nullptr; }
        } else {
          // MODIFY-only mode. ERROR_PATH_NOT_FOUND = parent path doesn't exist = return null.
          return nullptr;
        }
      case ERROR_FILE_NOT_FOUND:
        if (!has(mode, WriteMode::CREATE)) {
          // MODIFY-only mode. ERROR_FILE_NOT_FOUND = doesn't exist = return null.
          return nullptr;
        }
        goto failed;
      case ERROR_ALREADY_EXISTS:
      case ERROR_FILE_EXISTS:
        if (!has(mode, WriteMode::MODIFY)) {
          // CREATE-only mode. ERROR_ALREADY_EXISTS = already exists = return null.
          return nullptr;
        }
        goto failed;
      default:
      failed:
        KJ_FAIL_WIN32("CreateFile", error, path) { return nullptr; }
    }

    return kj::AutoCloseHandle(newHandle);
  }

  bool tryCommitReplacement(
      PathPtr toPath, ArrayPtr<const wchar_t> fromPath,
976
      WriteMode mode, kj::Maybe<kj::PathPtr> pathForCreatingParents = nullptr) const {
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
    // Try to use MoveFileEx() to replace `toPath` with `fromPath`.

    auto wToPath = nativePath(toPath);

    DWORD flags = has(mode, WriteMode::MODIFY) ? MOVEFILE_REPLACE_EXISTING : 0;

    if (!has(mode, WriteMode::CREATE)) {
      // Non-atomically verify that target exists. There's no way to make this atomic.
      DWORD result = GetFileAttributesW(wToPath.begin());
      if (result == INVALID_FILE_ATTRIBUTES) {
        auto error = GetLastError();
        switch (error) {
          case ERROR_FILE_NOT_FOUND:
          case ERROR_PATH_NOT_FOUND:
            return false;
          default:
            KJ_FAIL_WIN32("GetFileAttributesEx(toPath)", error, toPath) { return false; }
        }
      }
    }

    KJ_WIN32_HANDLE_ERRORS(MoveFileExW(fromPath.begin(), wToPath.begin(), flags)) {
      case ERROR_ALREADY_EXISTS:
      case ERROR_FILE_EXISTS:
        // We must not be in MODIFY mode.
        return false;
      case ERROR_PATH_NOT_FOUND:
        KJ_IF_MAYBE(p, pathForCreatingParents) {
          if (has(mode, WriteMode::CREATE_PARENT) &&
              p->size() > 0 && tryMkdir(p->parent(),
                  WriteMode::CREATE | WriteMode::MODIFY | WriteMode::CREATE_PARENT, true)) {
            // Retry, but make sure we don't try to create the parent again.
            return tryCommitReplacement(toPath, fromPath, mode - WriteMode::CREATE_PARENT);
          }
        }
        goto default_;

      case ERROR_ACCESS_DENIED: {
        // This often means that the target already exists and cannot be replaced, e.g. because
        // it is a directory. Move it out of the way first, then move our replacement in, then
        // delete the old thing.

        if (has(mode, WriteMode::MODIFY)) {
          KJ_IF_MAYBE(tempName,
1021 1022
              createNamedTemporary(toPath, WriteMode::CREATE, [&](const wchar_t* tempName2) {
            return MoveFileW(wToPath.begin(), tempName2);
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
          })) {
            KJ_WIN32_HANDLE_ERRORS(MoveFileW(fromPath.begin(), wToPath.begin())) {
              default:
                // Try to move back.
                MoveFileW(tempName->begin(), wToPath.begin());
                KJ_FAIL_WIN32("MoveFile", error, dbgStr(fromPath), dbgStr(wToPath)) {
                  return false;
                }
            }

            // Succeded, delete temporary.
            rmrf(*tempName);
            return true;
          } else {
            // createNamedTemporary() threw exception but exceptions are disabled.
            return false;
          }
        } else {
          // Not MODIFY, so no overwrite allowed. If the file really does exist, we need to return
          // false.
          if (GetFileAttributesW(wToPath.begin()) != INVALID_FILE_ATTRIBUTES) {
            return false;
          }
        }

        goto default_;
      }

      default:
      default_:
        KJ_FAIL_WIN32("MoveFileEx", error, dbgStr(wToPath), dbgStr(fromPath)) { return false; }
    }

    return true;
  }

  template <typename T>
  class ReplacerImpl final: public Directory::Replacer<T> {
  public:
1062
    ReplacerImpl(Own<T>&& object, const DiskHandle& parentDirectory,
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
                 Array<wchar_t>&& tempPath, Path&& path, WriteMode mode)
        : Directory::Replacer<T>(mode),
          object(kj::mv(object)), parentDirectory(parentDirectory),
          tempPath(kj::mv(tempPath)), path(kj::mv(path)) {}

    ~ReplacerImpl() noexcept(false) {
      if (!committed) {
        object = Own<T>();  // Force close of handle before trying to delete.

        if (kj::isSameType<T, File>()) {
          KJ_WIN32(DeleteFileW(tempPath.begin())) { break; }
        } else {
          rmrfChildren(tempPath);
          KJ_WIN32(RemoveDirectoryW(tempPath.begin())) { break; }
        }
      }
    }

1081
    const T& get() override {
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
      return *object;
    }

    bool tryCommit() override {
      KJ_ASSERT(!committed, "already committed") { return false; }

      // For directories, we intentionally don't use FILE_SHARE_DELETE on our handle because if the
      // directory name changes our paths would be wrong. But, this means we can't rename the
      // directory here to commit it. So, we need to close the handle and then re-open it
      // afterwards. Ick.
      AutoCloseHandle* objectHandle = getHandlePointerHack(*object);
      if (kj::isSameType<T, Directory>()) {
        *objectHandle = nullptr;
      }
      KJ_DEFER({
        if (kj::isSameType<T, Directory>()) {
Ivan Shynkarenka's avatar
Ivan Shynkarenka committed
1098
          HANDLE newHandle = nullptr;
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
          KJ_WIN32(newHandle = CreateFileW(
              committed ? parentDirectory.nativePath(path).begin() : tempPath.begin(),
              GENERIC_READ,
              FILE_SHARE_READ | FILE_SHARE_WRITE,
              NULL,
              OPEN_EXISTING,
              FILE_FLAG_BACKUP_SEMANTICS,  // apparently, this flag is required for directories
              NULL)) { return; }
          *objectHandle = AutoCloseHandle(newHandle);
          *getPathPointerHack(*object) = KJ_ASSERT_NONNULL(parentDirectory.dirPath).append(path);
        }
      });

      return committed = parentDirectory.tryCommitReplacement(
          path, tempPath, Directory::Replacer<T>::mode);
    }

  private:
    Own<T> object;
1118
    const DiskHandle& parentDirectory;
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
    Array<wchar_t> tempPath;
    Path path;
    bool committed = false;  // true if *successfully* committed (in which case tempPath is gone)
  };

  template <typename T>
  class BrokenReplacer final: public Directory::Replacer<T> {
    // For recovery path when exceptions are disabled.

  public:
1129
    BrokenReplacer(Own<const T> inner)
1130 1131 1132
        : Directory::Replacer<T>(WriteMode::CREATE | WriteMode::MODIFY),
          inner(kj::mv(inner)) {}

1133
    const T& get() override { return *inner; }
1134 1135 1136
    bool tryCommit() override { return false; }

  private:
1137
    Own<const T> inner;
1138 1139
  };

1140
  Maybe<Own<const File>> tryOpenFile(PathPtr path, WriteMode mode) const {
1141 1142 1143
    return tryOpenFileInternal(path, mode, false).map(newDiskFile);
  }

1144
  Own<Directory::Replacer<File>> replaceFile(PathPtr path, WriteMode mode) const {
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
    HANDLE newHandle_;
    KJ_IF_MAYBE(temp, createNamedTemporary(path, mode,
        [&](const wchar_t* candidatePath) {
      newHandle_ = CreateFileW(
          candidatePath,
          GENERIC_READ | GENERIC_WRITE,
          FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
          makeSecAttr(mode),
          CREATE_NEW,
          FILE_ATTRIBUTE_NORMAL,
          NULL);
      return newHandle_ != INVALID_HANDLE_VALUE;
    })) {
      AutoCloseHandle newHandle(newHandle_);
      return heap<ReplacerImpl<File>>(newDiskFile(kj::mv(newHandle)), *this, kj::mv(*temp),
                                      path.clone(), mode);
    } else {
      // threw, but exceptions are disabled
      return heap<BrokenReplacer<File>>(newInMemoryFile(nullClock()));
    }
  }

1167
  Own<const File> createTemporary() const {
1168 1169 1170 1171 1172 1173 1174
    HANDLE newHandle_;
    KJ_IF_MAYBE(temp, createNamedTemporary(Path("unnamed"), WriteMode::CREATE,
        [&](const wchar_t* candidatePath) {
      newHandle_ = CreateFileW(
          candidatePath,
          GENERIC_READ | GENERIC_WRITE,
          0,
1175
          NULL,   // TODO(someday): makeSecAttr(WriteMode::PRIVATE), when it's implemented
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
          CREATE_NEW,
          FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
          NULL);
      return newHandle_ != INVALID_HANDLE_VALUE;
    })) {
      AutoCloseHandle newHandle(newHandle_);
      return newDiskFile(kj::mv(newHandle));
    } else {
      // threw, but exceptions are disabled
      return newInMemoryFile(nullClock());
    }
  }

1189
  Maybe<Own<AppendableFile>> tryAppendFile(PathPtr path, WriteMode mode) const {
1190 1191 1192
    return tryOpenFileInternal(path, mode, true).map(newDiskAppendableFile);
  }

1193
  Maybe<Own<const Directory>> tryOpenSubdir(PathPtr path, WriteMode mode) const {
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
    // Must create before open.
    if (has(mode, WriteMode::CREATE)) {
      if (!tryMkdir(path, mode, false)) return nullptr;
    }

    return tryOpenSubdirInternal(path).map([&](AutoCloseHandle&& handle) {
      return newDiskDirectory(kj::mv(handle), KJ_ASSERT_NONNULL(dirPath).append(path));
    });
  }

1204
  Own<Directory::Replacer<Directory>> replaceSubdir(PathPtr path, WriteMode mode) const {
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
    Path kjTempPath = nullptr;
    KJ_IF_MAYBE(temp, createNamedTemporary(path, mode, kjTempPath,
        [&](const wchar_t* candidatePath) {
      return CreateDirectoryW(candidatePath, makeSecAttr(mode));
    })) {
      HANDLE subdirHandle_;
      KJ_WIN32_HANDLE_ERRORS(subdirHandle_ = CreateFileW(
          temp->begin(),
          GENERIC_READ,
          FILE_SHARE_READ | FILE_SHARE_WRITE,
          NULL,
          OPEN_EXISTING,
          FILE_FLAG_BACKUP_SEMANTICS,  // apparently, this flag is required for directories
          NULL)) {
        default:
          KJ_FAIL_WIN32("CreateFile(just-created-temporary, OPEN_EXISTING)", error, path) {
            goto fail;
          }
      }

      AutoCloseHandle subdirHandle(subdirHandle_);
      return heap<ReplacerImpl<Directory>>(
          newDiskDirectory(kj::mv(subdirHandle),
              KJ_ASSERT_NONNULL(dirPath).append(kj::mv(kjTempPath))),
          *this, kj::mv(*temp), path.clone(), mode);
    } else {
      // threw, but exceptions are disabled
    fail:
      return heap<BrokenReplacer<Directory>>(newInMemoryDirectory(nullClock()));
    }
  }

1237
  bool trySymlink(PathPtr linkpath, StringPtr content, WriteMode mode) const {
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
    // We can't really create symlinks on Windows. Reasons:
    // - We'd need to know whether the target is a file or a directory to pass the correct flags.
    //   That means we'd need to evaluate the link content and track down the target. What if the
    //   taget doesn't exist? It's unclear if this is even allowed on Windows.
    // - Apparently, creating symlinks is a privileged operation on Windows prior to Windows 10.
    //   The flag SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE is very new.
    KJ_UNIMPLEMENTED(
        "Creating symbolic links is not supported on Windows due to semantic differences.");
  }

  bool tryTransfer(PathPtr toPath, WriteMode toMode,
1249 1250
                   const Directory& fromDirectory, PathPtr fromPath,
                   TransferMode mode, const Directory& self) const {
1251 1252 1253 1254 1255 1256 1257
    KJ_REQUIRE(toPath.size() > 0, "can't replace self") { return false; }

    // Try to get the "from" path.
    Array<wchar_t> rawFromPath;
#if !KJ_NO_RTTI
    // Oops, dynamicDowncastIfAvailable() doesn't work since this isn't a downcast, it's a
    // side-cast...
1258
    if (auto dh = dynamic_cast<const DiskHandle*>(&fromDirectory)) {
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
      rawFromPath = dh->nativePath(fromPath);
    } else
#endif
    KJ_IF_MAYBE(h, fromDirectory.getWin32Handle()) {
      // Can't downcast to DiskHandle, but getWin32Handle() returns a handle... maybe RTTI is
      // disabled? Or maybe this is some kind of wrapper?
      rawFromPath = getPathFromHandle(*h).append(fromPath).forWin32Api(true);
    } else {
      // Not a disk directory, so fall back to default implementation.
      return self.Directory::tryTransfer(toPath, toMode, fromDirectory, fromPath, mode);
    }

    if (mode == TransferMode::LINK) {
      return tryReplaceNode(toPath, toMode, [&](const wchar_t* candidatePath) {
        return CreateHardLinkW(candidatePath, rawFromPath.begin(), NULL);
      });
    } else if (mode == TransferMode::MOVE) {
      return tryCommitReplacement(toPath, rawFromPath, toMode, toPath);
    } else if (mode == TransferMode::COPY) {
      // We can accellerate copies on Windows.

      if (!has(toMode, WriteMode::CREATE)) {
        // Non-atomically verify that target exists. There's no way to make this atomic.
        if (!exists(toPath)) return false;
      }

      bool failIfExists = !has(toMode, WriteMode::MODIFY);
      KJ_WIN32_HANDLE_ERRORS(
          CopyFileW(rawFromPath.begin(), nativePath(toPath).begin(), failIfExists)) {
        case ERROR_ALREADY_EXISTS:
        case ERROR_FILE_EXISTS:
        case ERROR_FILE_NOT_FOUND:
        case ERROR_PATH_NOT_FOUND:
          return false;
        case ERROR_ACCESS_DENIED:
          // This usually means that fromPath was a directory or toPath was a direcotry. Fall back
          // to default implementation.
          break;
        default:
          KJ_FAIL_WIN32("CopyFile", error, fromPath, toPath) { return false; }
      } else {
        // Copy succeded.
        return true;
      }
    }

    // OK, we can't do anything efficient using the OS. Fall back to default implementation.
    return self.Directory::tryTransfer(toPath, toMode, fromDirectory, fromPath, mode);
  }

1309
  bool tryRemove(PathPtr path) const {
1310 1311 1312 1313
    return rmrf(nativePath(path));
  }
};

1314 1315 1316 1317 1318 1319
#define FSNODE_METHODS                                              \
  Maybe<void*> getWin32Handle() const override { return DiskHandle::getWin32Handle(); } \
                                                                    \
  Metadata stat() const override { return DiskHandle::stat(); }     \
  void sync() const override { DiskHandle::sync(); }                \
  void datasync() const override { DiskHandle::datasync(); }
1320 1321 1322 1323 1324

class DiskReadableFile final: public ReadableFile, public DiskHandle {
public:
  DiskReadableFile(AutoCloseHandle&& handle): DiskHandle(kj::mv(handle), nullptr) {}

1325
  Own<const FsNode> cloneFsNode() const override {
1326 1327 1328 1329 1330
    return heap<DiskReadableFile>(DiskHandle::clone());
  }

  FSNODE_METHODS

1331
  size_t read(uint64_t offset, ArrayPtr<byte> buffer) const override {
1332 1333
    return DiskHandle::read(offset, buffer);
  }
1334
  Array<const byte> mmap(uint64_t offset, uint64_t size) const override {
1335 1336
    return DiskHandle::mmap(offset, size);
  }
1337
  Array<byte> mmapPrivate(uint64_t offset, uint64_t size) const override {
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
    return DiskHandle::mmapPrivate(offset, size);
  }
};

class DiskAppendableFile final: public AppendableFile, public DiskHandle {
public:
  DiskAppendableFile(AutoCloseHandle&& handle)
      : DiskHandle(kj::mv(handle), nullptr),
        stream(DiskHandle::handle.get()) {}

1348
  Own<const FsNode> cloneFsNode() const override {
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
    return heap<DiskAppendableFile>(DiskHandle::clone());
  }

  FSNODE_METHODS

  void write(const void* buffer, size_t size) override { stream.write(buffer, size); }
  void write(ArrayPtr<const ArrayPtr<const byte>> pieces) override {
    implicitCast<OutputStream&>(stream).write(pieces);
  }

private:
  HandleOutputStream stream;
};

class DiskFile final: public File, public DiskHandle {
public:
  DiskFile(AutoCloseHandle&& handle): DiskHandle(kj::mv(handle), nullptr) {}

1367
  Own<const FsNode> cloneFsNode() const override {
1368 1369 1370 1371 1372
    return heap<DiskFile>(DiskHandle::clone());
  }

  FSNODE_METHODS

1373
  size_t read(uint64_t offset, ArrayPtr<byte> buffer) const override {
1374 1375
    return DiskHandle::read(offset, buffer);
  }
1376
  Array<const byte> mmap(uint64_t offset, uint64_t size) const override {
1377 1378
    return DiskHandle::mmap(offset, size);
  }
1379
  Array<byte> mmapPrivate(uint64_t offset, uint64_t size) const override {
1380 1381 1382
    return DiskHandle::mmapPrivate(offset, size);
  }

1383
  void write(uint64_t offset, ArrayPtr<const byte> data) const override {
1384 1385
    DiskHandle::write(offset, data);
  }
1386
  void zero(uint64_t offset, uint64_t size) const override {
1387 1388
    DiskHandle::zero(offset, size);
  }
1389
  void truncate(uint64_t size) const override {
1390 1391
    DiskHandle::truncate(size);
  }
1392
  Own<const WritableFileMapping> mmapWritable(uint64_t offset, uint64_t size) const override {
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
    return DiskHandle::mmapWritable(offset, size);
  }
  // copy() is not optimized on Windows.
};

class DiskReadableDirectory final: public ReadableDirectory, public DiskHandle {
public:
  DiskReadableDirectory(AutoCloseHandle&& handle, Path&& path)
      : DiskHandle(kj::mv(handle), kj::mv(path)) {}

1403
  Own<const FsNode> cloneFsNode() const override {
1404 1405 1406 1407 1408
    return heap<DiskReadableDirectory>(DiskHandle::clone(), KJ_ASSERT_NONNULL(dirPath).clone());
  }

  FSNODE_METHODS

1409 1410 1411 1412 1413 1414 1415
  Array<String> listNames() const override { return DiskHandle::listNames(); }
  Array<Entry> listEntries() const override { return DiskHandle::listEntries(); }
  bool exists(PathPtr path) const override { return DiskHandle::exists(path); }
  Maybe<FsNode::Metadata> tryLstat(PathPtr path) const override {
    return DiskHandle::tryLstat(path);
  }
  Maybe<Own<const ReadableFile>> tryOpenFile(PathPtr path) const override {
1416 1417
    return DiskHandle::tryOpenFile(path);
  }
1418
  Maybe<Own<const ReadableDirectory>> tryOpenSubdir(PathPtr path) const override {
1419 1420
    return DiskHandle::tryOpenSubdir(path);
  }
1421
  Maybe<String> tryReadlink(PathPtr path) const override { return DiskHandle::tryReadlink(path); }
1422 1423 1424 1425 1426 1427 1428
};

class DiskDirectoryBase: public Directory, public DiskHandle {
public:
  DiskDirectoryBase(AutoCloseHandle&& handle, Path&& path)
      : DiskHandle(kj::mv(handle), kj::mv(path)) {}

1429 1430 1431
  bool exists(PathPtr path) const override { return DiskHandle::exists(path); }
  Maybe<FsNode::Metadata> tryLstat(PathPtr path) const override { return DiskHandle::tryLstat(path); }
  Maybe<Own<const ReadableFile>> tryOpenFile(PathPtr path) const override {
1432 1433
    return DiskHandle::tryOpenFile(path);
  }
1434
  Maybe<Own<const ReadableDirectory>> tryOpenSubdir(PathPtr path) const override {
1435 1436
    return DiskHandle::tryOpenSubdir(path);
  }
1437
  Maybe<String> tryReadlink(PathPtr path) const override { return DiskHandle::tryReadlink(path); }
1438

1439
  Maybe<Own<const File>> tryOpenFile(PathPtr path, WriteMode mode) const override {
1440 1441
    return DiskHandle::tryOpenFile(path, mode);
  }
1442
  Own<Replacer<File>> replaceFile(PathPtr path, WriteMode mode) const override {
1443 1444
    return DiskHandle::replaceFile(path, mode);
  }
1445
  Maybe<Own<AppendableFile>> tryAppendFile(PathPtr path, WriteMode mode) const override {
1446 1447
    return DiskHandle::tryAppendFile(path, mode);
  }
1448
  Maybe<Own<const Directory>> tryOpenSubdir(PathPtr path, WriteMode mode) const override {
1449 1450
    return DiskHandle::tryOpenSubdir(path, mode);
  }
1451
  Own<Replacer<Directory>> replaceSubdir(PathPtr path, WriteMode mode) const override {
1452 1453
    return DiskHandle::replaceSubdir(path, mode);
  }
1454
  bool trySymlink(PathPtr linkpath, StringPtr content, WriteMode mode) const override {
1455 1456 1457
    return DiskHandle::trySymlink(linkpath, content, mode);
  }
  bool tryTransfer(PathPtr toPath, WriteMode toMode,
1458 1459
                   const Directory& fromDirectory, PathPtr fromPath,
                   TransferMode mode) const override {
1460 1461 1462
    return DiskHandle::tryTransfer(toPath, toMode, fromDirectory, fromPath, mode, *this);
  }
  // tryTransferTo() not implemented because we have nothing special we can do.
1463
  bool tryRemove(PathPtr path) const override {
1464 1465 1466 1467 1468 1469 1470 1471 1472
    return DiskHandle::tryRemove(path);
  }
};

class DiskDirectory final: public DiskDirectoryBase {
public:
  DiskDirectory(AutoCloseHandle&& handle, Path&& path)
      : DiskDirectoryBase(kj::mv(handle), kj::mv(path)) {}

1473
  Own<const FsNode> cloneFsNode() const override {
1474 1475 1476 1477 1478
    return heap<DiskDirectory>(DiskHandle::clone(), KJ_ASSERT_NONNULL(dirPath).clone());
  }

  FSNODE_METHODS

1479 1480 1481
  Array<String> listNames() const override { return DiskHandle::listNames(); }
  Array<Entry> listEntries() const override { return DiskHandle::listEntries(); }
  Own<const File> createTemporary() const override {
1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
    return DiskHandle::createTemporary();
  }
};

class RootDiskDirectory final: public DiskDirectoryBase {
  // On Windows, the root directory is special.
  //
  // HACK: We only override a few functions of DiskDirectory, and we rely on the fact that
  //   Path::forWin32Api(true) throws an exception complaining about missing drive letter if the
  //   path is totally empty.

public:
  RootDiskDirectory(): DiskDirectoryBase(nullptr, Path(nullptr)) {}

1496
  Own<const FsNode> cloneFsNode() const override {
1497 1498 1499
    return heap<RootDiskDirectory>();
  }

1500
  Metadata stat() const override {
1501
    return { Type::DIRECTORY, 0, 0, UNIX_EPOCH, 1, 0 };
1502
  }
1503 1504
  void sync() const override {}
  void datasync() const override {}
1505

1506
  Array<String> listNames() const override {
1507 1508
    return KJ_MAP(e, listEntries()) { return kj::mv(e.name); };
  }
1509
  Array<Entry> listEntries() const override {
1510 1511 1512 1513 1514 1515 1516 1517
    DWORD drives = GetLogicalDrives();
    if (drives == 0) {
      KJ_FAIL_WIN32("GetLogicalDrives()", GetLastError()) { return nullptr; }
    }

    Vector<Entry> results;
    for (uint i = 0; i < 26; i++) {
      if (drives & (1 << i)) {
Crunkle's avatar
Crunkle committed
1518
        char name[2] = { static_cast<char>('A' + i), ':' };
1519 1520 1521 1522 1523 1524 1525
        results.add(Entry { FsNode::Type::DIRECTORY, kj::heapString(name, 2) });
      }
    }

    return results.releaseAsArray();
  }

1526
  Own<const File> createTemporary() const override {
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
    KJ_FAIL_REQUIRE("can't create temporaries in Windows pseudo-root directory (the drive list)");
  }
};

class DiskFilesystem final: public Filesystem {
public:
  DiskFilesystem()
      : DiskFilesystem(computeCurrentPath()) {}
  DiskFilesystem(Path currentPath)
      : current(KJ_ASSERT_NONNULL(root.tryOpenSubdirInternal(currentPath),
                      "path returned by GetCurrentDirectory() doesn't exist?"),
                kj::mv(currentPath)) {}

1540
  const Directory& getRoot() const override {
1541 1542 1543
    return root;
  }

1544
  const Directory& getCurrent() const override {
1545 1546 1547
    return current;
  }

1548
  PathPtr getCurrentPath() const override {
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
    return KJ_ASSERT_NONNULL(current.dirPath);
  }

private:
  RootDiskDirectory root;
  DiskDirectory current;

  static Path computeCurrentPath() {
    DWORD tryLen = MAX_PATH;
    for (;;) {
      auto temp = kj::heapArray<wchar_t>(tryLen + 1);
      DWORD len = GetCurrentDirectoryW(temp.size(), temp.begin());
      if (len == 0) {
        KJ_FAIL_WIN32("GetCurrentDirectory", GetLastError()) { break; }
        return Path(".");
      }
      if (len < temp.size()) {
        return Path::parseWin32Api(temp.slice(0, len));
      }
      // Try again with new length.
      tryLen = len;
    }
  }
};

} // namespace

Own<ReadableFile> newDiskReadableFile(AutoCloseHandle fd) {
  return heap<DiskReadableFile>(kj::mv(fd));
}
Own<AppendableFile> newDiskAppendableFile(AutoCloseHandle fd) {
  return heap<DiskAppendableFile>(kj::mv(fd));
}
Own<File> newDiskFile(AutoCloseHandle fd) {
  return heap<DiskFile>(kj::mv(fd));
}
Own<ReadableDirectory> newDiskReadableDirectory(AutoCloseHandle fd) {
  return heap<DiskReadableDirectory>(kj::mv(fd), getPathFromHandle(fd));
}
static Own<ReadableDirectory> newDiskReadableDirectory(AutoCloseHandle fd, Path&& path) {
  return heap<DiskReadableDirectory>(kj::mv(fd), kj::mv(path));
}
Own<Directory> newDiskDirectory(AutoCloseHandle fd) {
  return heap<DiskDirectory>(kj::mv(fd), getPathFromHandle(fd));
}
static Own<Directory> newDiskDirectory(AutoCloseHandle fd, Path&& path) {
  return heap<DiskDirectory>(kj::mv(fd), kj::mv(path));
}

Own<Filesystem> newDiskFilesystem() {
  return heap<DiskFilesystem>();
}

static AutoCloseHandle* getHandlePointerHack(Directory& dir) {
  return &static_cast<DiskDirectoryBase&>(dir).handle;
}
static Path* getPathPointerHack(Directory& dir) {
  return &KJ_ASSERT_NONNULL(static_cast<DiskDirectoryBase&>(dir).dirPath);
}

} // namespace kj

#endif  // _WIN32