filesystem-disk-test.c++ 29.1 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
// Copyright (c) 2016 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.

#include "filesystem.h"
#include "test.h"
24
#include "encoding.h"
25
#include <stdlib.h>
26 27 28 29
#if _WIN32
#include <windows.h>
#include "windows-sanity.h"
#else
30 31 32 33 34 35
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
36
#endif
37 38 39 40

namespace kj {
namespace {

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 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 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
bool isWine() KJ_UNUSED;

#if _WIN32

bool detectWine() {
  HMODULE hntdll = GetModuleHandle("ntdll.dll");
  if(hntdll == NULL) return false;
  return GetProcAddress(hntdll, "wine_get_version") != nullptr;
}

bool isWine() {
  static bool result = detectWine();
  return result;
}

template <typename Func>
static auto newTemp(Func&& create)
    -> Decay<decltype(*kj::_::readMaybe(create(Array<wchar_t>())))> {
  wchar_t wtmpdir[MAX_PATH + 1];
  DWORD len = GetTempPathW(kj::size(wtmpdir), wtmpdir);
  KJ_ASSERT(len < kj::size(wtmpdir));
  auto tmpdir = decodeWideString(arrayPtr(wtmpdir, len));

  static uint counter = 0;
  for (;;) {
    auto path = kj::str(tmpdir, "kj-filesystem-test.", GetCurrentProcessId(), ".", counter++);
    KJ_IF_MAYBE(result, create(encodeWideString(path, true))) {
      return kj::mv(*result);
    }
  }
}

static Own<File> newTempFile() {
  return newTemp([](Array<wchar_t> candidatePath) -> Maybe<Own<File>> {
    HANDLE handle;
    KJ_WIN32_HANDLE_ERRORS(handle = CreateFileW(
        candidatePath.begin(),
        FILE_GENERIC_READ | FILE_GENERIC_WRITE,
        0,
        NULL,
        CREATE_NEW,
        FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
        NULL)) {
      case ERROR_ALREADY_EXISTS:
      case ERROR_FILE_EXISTS:
        return nullptr;
      default:
        KJ_FAIL_WIN32("CreateFileW", error);
    }
    return newDiskFile(AutoCloseHandle(handle));
  });
}

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;
}

class TempDir {
public:
  TempDir(): filename(newTemp([](Array<wchar_t> candidatePath) -> Maybe<Array<wchar_t>> {
        KJ_WIN32_HANDLE_ERRORS(CreateDirectoryW(candidatePath.begin(), NULL)) {
          case ERROR_ALREADY_EXISTS:
          case ERROR_FILE_EXISTS:
            return nullptr;
          default:
            KJ_FAIL_WIN32("CreateDirectoryW", error);
        }
        return kj::mv(candidatePath);
      })) {}

  Own<Directory> get() {
    HANDLE handle;
    KJ_WIN32(handle = CreateFileW(
        filename.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 newDiskDirectory(AutoCloseHandle(handle));
  }

  ~TempDir() noexcept(false) {
    recursiveDelete(filename);
  }

private:
  Array<wchar_t> filename;

  static void recursiveDelete(ArrayPtr<const wchar_t> path) {
    // Recursively delete the temp dir, verifying that no .kj-tmp. files were left over.
    //
    // Mostly copied from rmrfChildren() in filesystem-win32.c++.

    auto glob = join16(path, L"\\*");

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
    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, path) { 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;
160
        }
161
      }
162

163 164
      String utf8Name = decodeWideString(arrayPtr(data.cFileName, wcslen(data.cFileName)));
      KJ_EXPECT(!utf8Name.startsWith(".kj-tmp."), "temp file not cleaned up", utf8Name);
165

166 167 168 169 170 171
      auto child = join16(path, data.cFileName);
      if ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
          !(data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
        recursiveDelete(child);
      } else {
        KJ_WIN32(DeleteFileW(child.begin()));
172
      }
173
    } while (FindNextFileW(handle, &data));
174

175 176 177
    auto error = GetLastError();
    if (error != ERROR_NO_MORE_FILES) {
      KJ_FAIL_WIN32("FindNextFile", error, path) { return; }
178 179
    }

180 181 182 183 184 185 186 187 188 189 190 191
    uint retryCount = 0;
  retry:
    KJ_WIN32_HANDLE_ERRORS(RemoveDirectoryW(path.begin())) {
      case ERROR_DIR_NOT_EMPTY:
        if (retryCount++ < 10) {
          Sleep(10);
          goto retry;
        }
        // fallthrough
      default:
        KJ_FAIL_WIN32("RemoveDirectory", error) { break; }
    }
192 193 194 195 196 197 198
  }
};

#else

bool isWine() { return false; }

199 200 201 202
#if __APPLE__
#define HOLES_NOT_SUPPORTED 1
#endif

203 204 205 206 207 208 209 210 211 212 213 214 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
static Own<File> newTempFile() {
  char filename[] = "/var/tmp/kj-filesystem-test.XXXXXX";
  int fd;
  KJ_SYSCALL(fd = mkstemp(filename));
  KJ_DEFER(KJ_SYSCALL(unlink(filename)));
  return newDiskFile(AutoCloseFd(fd));
}

class TempDir {
public:
  TempDir(): filename(heapString("/var/tmp/kj-filesystem-test.XXXXXX")) {
    if (mkdtemp(filename.begin()) == nullptr) {
      KJ_FAIL_SYSCALL("mkdtemp", errno, filename);
    }
  }

  Own<Directory> get() {
    int fd;
    KJ_SYSCALL(fd = open(filename.cStr(), O_RDONLY));
    return newDiskDirectory(AutoCloseFd(fd));
  }

  ~TempDir() noexcept(false) {
    recursiveDelete(filename);
  }

private:
  String filename;

  static void recursiveDelete(StringPtr path) {
    // Recursively delete the temp dir, verifying that no .kj-tmp. files were left over.

    {
      DIR* dir = opendir(path.cStr());
      KJ_ASSERT(dir != nullptr);
      KJ_DEFER(closedir(dir));

      for (;;) {
        auto entry = readdir(dir);
        if (entry == nullptr) break;

        StringPtr name = entry->d_name;
        if (name == "." || name == "..") continue;

        auto subPath = kj::str(path, '/', entry->d_name);

        KJ_EXPECT(!name.startsWith(".kj-tmp."), "temp file not cleaned up", subPath);

        struct stat stats;
        KJ_SYSCALL(lstat(subPath.cStr(), &stats));

        if (S_ISDIR(stats.st_mode)) {
          recursiveDelete(subPath);
        } else {
          KJ_SYSCALL(unlink(subPath.cStr()));
        }
      }
    }

    KJ_SYSCALL(rmdir(path.cStr()));
  }
};

266 267
#endif  // _WIN32, else

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 301 302 303 304 305 306 307 308 309 310 311 312
KJ_TEST("DiskFile") {
  auto file = newTempFile();

  KJ_EXPECT(file->readAllText() == "");

  file->writeAll("foo");
  KJ_EXPECT(file->readAllText() == "foo");

  file->write(3, StringPtr("bar").asBytes());
  KJ_EXPECT(file->readAllText() == "foobar");

  file->write(3, StringPtr("baz").asBytes());
  KJ_EXPECT(file->readAllText() == "foobaz");

  file->write(9, StringPtr("qux").asBytes());
  KJ_EXPECT(file->readAllText() == kj::StringPtr("foobaz\0\0\0qux", 12));

  file->truncate(6);
  KJ_EXPECT(file->readAllText() == "foobaz");

  file->truncate(18);
  KJ_EXPECT(file->readAllText() == kj::StringPtr("foobaz\0\0\0\0\0\0\0\0\0\0\0\0", 18));

  {
    auto mapping = file->mmap(0, 18);
    auto privateMapping = file->mmapPrivate(0, 18);
    auto writableMapping = file->mmapWritable(0, 18);

    KJ_EXPECT(mapping.size() == 18);
    KJ_EXPECT(privateMapping.size() == 18);
    KJ_EXPECT(writableMapping->get().size() == 18);

    KJ_EXPECT(writableMapping->get().begin() != mapping.begin());
    KJ_EXPECT(privateMapping.begin() != mapping.begin());
    KJ_EXPECT(writableMapping->get().begin() != privateMapping.begin());

    KJ_EXPECT(kj::str(mapping.slice(0, 6).asChars()) == "foobaz");
    KJ_EXPECT(kj::str(writableMapping->get().slice(0, 6).asChars()) == "foobaz");
    KJ_EXPECT(kj::str(privateMapping.slice(0, 6).asChars()) == "foobaz");

    privateMapping[0] = 'F';
    KJ_EXPECT(kj::str(mapping.slice(0, 6).asChars()) == "foobaz");
    KJ_EXPECT(kj::str(writableMapping->get().slice(0, 6).asChars()) == "foobaz");
    KJ_EXPECT(kj::str(privateMapping.slice(0, 6).asChars()) == "Foobaz");

313 314 315 316
    writableMapping->get()[1] = 'D';
    writableMapping->changed(writableMapping->get().slice(1, 2));
    KJ_EXPECT(kj::str(mapping.slice(0, 6).asChars()) == "fDobaz");
    KJ_EXPECT(kj::str(writableMapping->get().slice(0, 6).asChars()) == "fDobaz");
317 318 319 320 321 322 323 324 325 326
    KJ_EXPECT(kj::str(privateMapping.slice(0, 6).asChars()) == "Foobaz");

    file->write(0, StringPtr("qux").asBytes());
    KJ_EXPECT(kj::str(mapping.slice(0, 6).asChars()) == "quxbaz");
    KJ_EXPECT(kj::str(writableMapping->get().slice(0, 6).asChars()) == "quxbaz");
    KJ_EXPECT(kj::str(privateMapping.slice(0, 6).asChars()) == "Foobaz");

    file->write(12, StringPtr("corge").asBytes());
    KJ_EXPECT(kj::str(mapping.slice(12, 17).asChars()) == "corge");

327
#if !_WIN32  // Windows doesn't allow the file size to change while mapped.
328 329 330 331 332 333 334 335 336 337
    // Can shrink.
    file->truncate(6);
    KJ_EXPECT(kj::str(mapping.slice(12, 17).asChars()) == kj::StringPtr("\0\0\0\0\0", 5));

    // Can regrow.
    file->truncate(18);
    KJ_EXPECT(kj::str(mapping.slice(12, 17).asChars()) == kj::StringPtr("\0\0\0\0\0", 5));

    // Can even regrow past previous capacity.
    file->truncate(100);
338
#endif
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 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 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 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 494 495 496 497 498 499 500 501 502 503 504 505 506
  }

  file->truncate(6);

  KJ_EXPECT(file->readAllText() == "quxbaz");
  file->zero(3, 3);
  KJ_EXPECT(file->readAllText() == StringPtr("qux\0\0\0", 6));
}

KJ_TEST("DiskFile::copy()") {
  auto source = newTempFile();
  source->writeAll("foobarbaz");

  auto dest = newTempFile();
  dest->writeAll("quxcorge");

  KJ_EXPECT(dest->copy(3, *source, 6, kj::maxValue) == 3);
  KJ_EXPECT(dest->readAllText() == "quxbazge");

  KJ_EXPECT(dest->copy(0, *source, 3, 4) == 4);
  KJ_EXPECT(dest->readAllText() == "barbazge");

  KJ_EXPECT(dest->copy(0, *source, 128, kj::maxValue) == 0);

  KJ_EXPECT(dest->copy(4, *source, 3, 0) == 0);

  String bigString = strArray(repeat("foobar", 10000), "");
  source->truncate(bigString.size() + 1000);
  source->write(123, bigString.asBytes());

  dest->copy(321, *source, 123, bigString.size());
  KJ_EXPECT(dest->readAllText().slice(321) == bigString);
}

KJ_TEST("DiskDirectory") {
  TempDir tempDir;
  auto dir = tempDir.get();

  KJ_EXPECT(dir->listNames() == nullptr);
  KJ_EXPECT(dir->listEntries() == nullptr);
  KJ_EXPECT(!dir->exists(Path("foo")));
  KJ_EXPECT(dir->tryOpenFile(Path("foo")) == nullptr);
  KJ_EXPECT(dir->tryOpenFile(Path("foo"), WriteMode::MODIFY) == nullptr);

  {
    auto file = dir->openFile(Path("foo"), WriteMode::CREATE);
    file->writeAll("foobar");
  }

  KJ_EXPECT(dir->exists(Path("foo")));

  {
    auto stats = dir->lstat(Path("foo"));
    KJ_EXPECT(stats.type == FsNode::Type::FILE);
    KJ_EXPECT(stats.size == 6);
  }

  {
    auto list = dir->listNames();
    KJ_ASSERT(list.size() == 1);
    KJ_EXPECT(list[0] == "foo");
  }

  {
    auto list = dir->listEntries();
    KJ_ASSERT(list.size() == 1);
    KJ_EXPECT(list[0].name == "foo");
    KJ_EXPECT(list[0].type == FsNode::Type::FILE);
  }

  KJ_EXPECT(dir->openFile(Path("foo"))->readAllText() == "foobar");

  KJ_EXPECT(dir->tryOpenFile(Path({"foo", "bar"}), WriteMode::MODIFY) == nullptr);
  KJ_EXPECT(dir->tryOpenFile(Path({"bar", "baz"}), WriteMode::MODIFY) == nullptr);
  KJ_EXPECT_THROW_MESSAGE("parent is not a directory",
      dir->tryOpenFile(Path({"bar", "baz"}), WriteMode::CREATE));

  {
    auto file = dir->openFile(Path({"bar", "baz"}), WriteMode::CREATE | WriteMode::CREATE_PARENT);
    file->writeAll("bazqux");
  }

  KJ_EXPECT(dir->openFile(Path({"bar", "baz"}))->readAllText() == "bazqux");

  {
    auto stats = dir->lstat(Path("bar"));
    KJ_EXPECT(stats.type == FsNode::Type::DIRECTORY);
  }

  {
    auto list = dir->listNames();
    KJ_ASSERT(list.size() == 2);
    KJ_EXPECT(list[0] == "bar");
    KJ_EXPECT(list[1] == "foo");
  }

  {
    auto list = dir->listEntries();
    KJ_ASSERT(list.size() == 2);
    KJ_EXPECT(list[0].name == "bar");
    KJ_EXPECT(list[0].type == FsNode::Type::DIRECTORY);
    KJ_EXPECT(list[1].name == "foo");
    KJ_EXPECT(list[1].type == FsNode::Type::FILE);
  }

  {
    auto subdir = dir->openSubdir(Path("bar"));

    KJ_EXPECT(subdir->openFile(Path("baz"))->readAllText() == "bazqux");
  }

  auto subdir = dir->openSubdir(Path("corge"), WriteMode::CREATE);

  subdir->openFile(Path("grault"), WriteMode::CREATE)->writeAll("garply");

  KJ_EXPECT(dir->openFile(Path({"corge", "grault"}))->readAllText() == "garply");

  dir->openFile(Path({"corge", "grault"}), WriteMode::CREATE | WriteMode::MODIFY)
     ->write(0, StringPtr("rag").asBytes());
  KJ_EXPECT(dir->openFile(Path({"corge", "grault"}))->readAllText() == "ragply");

  KJ_EXPECT(dir->openSubdir(Path("corge"))->listNames().size() == 1);

  {
    auto replacer =
        dir->replaceFile(Path({"corge", "grault"}), WriteMode::CREATE | WriteMode::MODIFY);
    replacer->get().writeAll("rag");

    // temp file not in list
    KJ_EXPECT(dir->openSubdir(Path("corge"))->listNames().size() == 1);

    // Don't commit.
  }
  KJ_EXPECT(dir->openFile(Path({"corge", "grault"}))->readAllText() == "ragply");

  {
    auto replacer =
        dir->replaceFile(Path({"corge", "grault"}), WriteMode::CREATE | WriteMode::MODIFY);
    replacer->get().writeAll("rag");

    // temp file not in list
    KJ_EXPECT(dir->openSubdir(Path("corge"))->listNames().size() == 1);

    replacer->commit();
    KJ_EXPECT(dir->openFile(Path({"corge", "grault"}))->readAllText() == "rag");
  }

  KJ_EXPECT(dir->openFile(Path({"corge", "grault"}))->readAllText() == "rag");

  {
    auto appender = dir->appendFile(Path({"corge", "grault"}), WriteMode::MODIFY);
    appender->write("waldo", 5);
    appender->write("fred", 4);
  }

  KJ_EXPECT(dir->openFile(Path({"corge", "grault"}))->readAllText() == "ragwaldofred");

  KJ_EXPECT(dir->exists(Path("foo")));
  dir->remove(Path("foo"));
  KJ_EXPECT(!dir->exists(Path("foo")));
  KJ_EXPECT(!dir->tryRemove(Path("foo")));

  KJ_EXPECT(dir->exists(Path({"bar", "baz"})));
  dir->remove(Path({"bar", "baz"}));
  KJ_EXPECT(!dir->exists(Path({"bar", "baz"})));
  KJ_EXPECT(dir->exists(Path("bar")));
  KJ_EXPECT(!dir->tryRemove(Path({"bar", "baz"})));

507 508 509 510 511
#if _WIN32
  // On Windows, we can't delete a directory while we still have it open.
  subdir = nullptr;
#endif

512 513 514 515 516 517 518 519
  KJ_EXPECT(dir->exists(Path("corge")));
  KJ_EXPECT(dir->exists(Path({"corge", "grault"})));
  dir->remove(Path("corge"));
  KJ_EXPECT(!dir->exists(Path("corge")));
  KJ_EXPECT(!dir->exists(Path({"corge", "grault"})));
  KJ_EXPECT(!dir->tryRemove(Path("corge")));
}

520
#if !_WIN32  // Creating symlinks on Win32 requires admin privileges prior to Windows 10.
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
KJ_TEST("DiskDirectory symlinks") {
  TempDir tempDir;
  auto dir = tempDir.get();

  dir->symlink(Path("foo"), "bar/qux/../baz", WriteMode::CREATE);

  KJ_EXPECT(!dir->trySymlink(Path("foo"), "bar/qux/../baz", WriteMode::CREATE));

  {
    auto stats = dir->lstat(Path("foo"));
    KJ_EXPECT(stats.type == FsNode::Type::SYMLINK);
  }

  KJ_EXPECT(dir->readlink(Path("foo")) == "bar/qux/../baz");

  // Broken link into non-existing directory cannot be opened in any mode.
  KJ_EXPECT(dir->tryOpenFile(Path("foo")) == nullptr);
  KJ_EXPECT(dir->tryOpenFile(Path("foo"), WriteMode::CREATE) == nullptr);
  KJ_EXPECT(dir->tryOpenFile(Path("foo"), WriteMode::MODIFY) == nullptr);
  KJ_EXPECT_THROW_MESSAGE("parent is not a directory",
      dir->tryOpenFile(Path("foo"), WriteMode::CREATE | WriteMode::MODIFY));
  KJ_EXPECT_THROW_MESSAGE("parent is not a directory",
      dir->tryOpenFile(Path("foo"),
          WriteMode::CREATE | WriteMode::MODIFY | WriteMode::CREATE_PARENT));

  // Create the directory.
  auto subdir = dir->openSubdir(Path("bar"), WriteMode::CREATE);
  subdir->openSubdir(Path("qux"), WriteMode::CREATE);

  // Link still points to non-existing file so cannot be open in most modes.
  KJ_EXPECT(dir->tryOpenFile(Path("foo")) == nullptr);
  KJ_EXPECT(dir->tryOpenFile(Path("foo"), WriteMode::CREATE) == nullptr);
  KJ_EXPECT(dir->tryOpenFile(Path("foo"), WriteMode::MODIFY) == nullptr);

  // But... CREATE | MODIFY works.
  dir->openFile(Path("foo"), WriteMode::CREATE | WriteMode::MODIFY)
     ->writeAll("foobar");

  KJ_EXPECT(dir->openFile(Path({"bar", "baz"}))->readAllText() == "foobar");
  KJ_EXPECT(dir->openFile(Path("foo"))->readAllText() == "foobar");
  KJ_EXPECT(dir->openFile(Path("foo"), WriteMode::MODIFY)->readAllText() == "foobar");

  // operations that modify the symlink
  dir->symlink(Path("foo"), "corge", WriteMode::MODIFY);
  KJ_EXPECT(dir->openFile(Path({"bar", "baz"}))->readAllText() == "foobar");
  KJ_EXPECT(dir->readlink(Path("foo")) == "corge");
  KJ_EXPECT(!dir->exists(Path("foo")));
  KJ_EXPECT(dir->lstat(Path("foo")).type == FsNode::Type::SYMLINK);
  KJ_EXPECT(dir->tryOpenFile(Path("foo")) == nullptr);

  dir->remove(Path("foo"));
  KJ_EXPECT(!dir->exists(Path("foo")));
  KJ_EXPECT(dir->tryOpenFile(Path("foo")) == nullptr);
}
575
#endif
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628

KJ_TEST("DiskDirectory link") {
  TempDir tempDirSrc;
  TempDir tempDirDst;

  auto src = tempDirSrc.get();
  auto dst = tempDirDst.get();

  src->openFile(Path("foo"), WriteMode::CREATE | WriteMode::CREATE_PARENT)
     ->writeAll("foobar");

  dst->transfer(Path("link"), WriteMode::CREATE, *src, Path("foo"), TransferMode::LINK);

  KJ_EXPECT(dst->openFile(Path("link"))->readAllText() == "foobar");

  // Writing the old location modifies the new.
  src->openFile(Path("foo"), WriteMode::MODIFY)->writeAll("bazqux");
  KJ_EXPECT(dst->openFile(Path("link"))->readAllText() == "bazqux");

  // Replacing the old location doesn't modify the new.
  {
    auto replacer = src->replaceFile(Path("foo"), WriteMode::MODIFY);
    replacer->get().writeAll("corge");
    replacer->commit();
  }
  KJ_EXPECT(src->openFile(Path("foo"))->readAllText() == "corge");
  KJ_EXPECT(dst->openFile(Path("link"))->readAllText() == "bazqux");
}

KJ_TEST("DiskDirectory copy") {
  TempDir tempDirSrc;
  TempDir tempDirDst;

  auto src = tempDirSrc.get();
  auto dst = tempDirDst.get();

  src->openFile(Path({"foo", "bar"}), WriteMode::CREATE | WriteMode::CREATE_PARENT)
     ->writeAll("foobar");
  src->openFile(Path({"foo", "baz", "qux"}), WriteMode::CREATE | WriteMode::CREATE_PARENT)
     ->writeAll("bazqux");

  dst->transfer(Path("link"), WriteMode::CREATE, *src, Path("foo"), TransferMode::COPY);

  KJ_EXPECT(src->openFile(Path({"foo", "bar"}))->readAllText() == "foobar");
  KJ_EXPECT(src->openFile(Path({"foo", "baz", "qux"}))->readAllText() == "bazqux");
  KJ_EXPECT(dst->openFile(Path({"link", "bar"}))->readAllText() == "foobar");
  KJ_EXPECT(dst->openFile(Path({"link", "baz", "qux"}))->readAllText() == "bazqux");

  KJ_EXPECT(dst->exists(Path({"link", "bar"})));
  src->remove(Path({"foo", "bar"}));
  KJ_EXPECT(dst->openFile(Path({"link", "bar"}))->readAllText() == "foobar");
}

629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
KJ_TEST("DiskDirectory copy-replace") {
  TempDir tempDirSrc;
  TempDir tempDirDst;

  auto src = tempDirSrc.get();
  auto dst = tempDirDst.get();

  src->openFile(Path({"foo", "bar"}), WriteMode::CREATE | WriteMode::CREATE_PARENT)
     ->writeAll("foobar");
  src->openFile(Path({"foo", "baz", "qux"}), WriteMode::CREATE | WriteMode::CREATE_PARENT)
     ->writeAll("bazqux");

  dst->openFile(Path({"link", "corge"}), WriteMode::CREATE | WriteMode::CREATE_PARENT)
     ->writeAll("abcd");

  // CREATE fails.
  KJ_EXPECT(!dst->tryTransfer(Path("link"), WriteMode::CREATE,
                              *src, Path("foo"), TransferMode::COPY));

  // Verify nothing changed.
  KJ_EXPECT(dst->openFile(Path({"link", "corge"}))->readAllText() == "abcd");
  KJ_EXPECT(!dst->exists(Path({"foo", "bar"})));

  // Now try MODIFY.
  dst->transfer(Path("link"), WriteMode::MODIFY, *src, Path("foo"), TransferMode::COPY);

  KJ_EXPECT(src->openFile(Path({"foo", "bar"}))->readAllText() == "foobar");
  KJ_EXPECT(src->openFile(Path({"foo", "baz", "qux"}))->readAllText() == "bazqux");
  KJ_EXPECT(dst->openFile(Path({"link", "bar"}))->readAllText() == "foobar");
  KJ_EXPECT(dst->openFile(Path({"link", "baz", "qux"}))->readAllText() == "bazqux");
  KJ_EXPECT(!dst->exists(Path({"link", "corge"})));

  KJ_EXPECT(dst->exists(Path({"link", "bar"})));
  src->remove(Path({"foo", "bar"}));
  KJ_EXPECT(dst->openFile(Path({"link", "bar"}))->readAllText() == "foobar");
}

666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
KJ_TEST("DiskDirectory move") {
  TempDir tempDirSrc;
  TempDir tempDirDst;

  auto src = tempDirSrc.get();
  auto dst = tempDirDst.get();

  src->openFile(Path({"foo", "bar"}), WriteMode::CREATE | WriteMode::CREATE_PARENT)
     ->writeAll("foobar");
  src->openFile(Path({"foo", "baz", "qux"}), WriteMode::CREATE | WriteMode::CREATE_PARENT)
     ->writeAll("bazqux");

  dst->transfer(Path("link"), WriteMode::CREATE, *src, Path("foo"), TransferMode::MOVE);

  KJ_EXPECT(!src->exists(Path({"foo"})));
  KJ_EXPECT(dst->openFile(Path({"link", "bar"}))->readAllText() == "foobar");
  KJ_EXPECT(dst->openFile(Path({"link", "baz", "qux"}))->readAllText() == "bazqux");
}

685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
KJ_TEST("DiskDirectory move-replace") {
  TempDir tempDirSrc;
  TempDir tempDirDst;

  auto src = tempDirSrc.get();
  auto dst = tempDirDst.get();

  src->openFile(Path({"foo", "bar"}), WriteMode::CREATE | WriteMode::CREATE_PARENT)
     ->writeAll("foobar");
  src->openFile(Path({"foo", "baz", "qux"}), WriteMode::CREATE | WriteMode::CREATE_PARENT)
     ->writeAll("bazqux");

  dst->openFile(Path({"link", "corge"}), WriteMode::CREATE | WriteMode::CREATE_PARENT)
     ->writeAll("abcd");

  // CREATE fails.
  KJ_EXPECT(!dst->tryTransfer(Path("link"), WriteMode::CREATE,
                              *src, Path("foo"), TransferMode::MOVE));

  // Verify nothing changed.
  KJ_EXPECT(dst->openFile(Path({"link", "corge"}))->readAllText() == "abcd");
  KJ_EXPECT(!dst->exists(Path({"foo", "bar"})));
  KJ_EXPECT(src->exists(Path({"foo"})));

  // Now try MODIFY.
  dst->transfer(Path("link"), WriteMode::MODIFY, *src, Path("foo"), TransferMode::MOVE);

  KJ_EXPECT(!src->exists(Path({"foo"})));
  KJ_EXPECT(dst->openFile(Path({"link", "bar"}))->readAllText() == "foobar");
  KJ_EXPECT(dst->openFile(Path({"link", "baz", "qux"}))->readAllText() == "bazqux");
}

717 718 719 720 721 722 723 724 725
KJ_TEST("DiskDirectory createTemporary") {
  TempDir tempDir;
  auto dir = tempDir.get();
  auto file = dir->createTemporary();
  file->writeAll("foobar");
  KJ_EXPECT(file->readAllText() == "foobar");
  KJ_EXPECT(dir->listNames() == nullptr);
}

726 727 728 729 730 731 732 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
KJ_TEST("DiskDirectory replaceSubdir()") {
  TempDir tempDir;
  auto dir = tempDir.get();

  {
    auto replacer = dir->replaceSubdir(Path("foo"), WriteMode::CREATE);
    replacer->get().openFile(Path("bar"), WriteMode::CREATE)->writeAll("original");
    KJ_EXPECT(replacer->get().openFile(Path("bar"))->readAllText() == "original");
    KJ_EXPECT(!dir->exists(Path({"foo", "bar"})));

    replacer->commit();
    KJ_EXPECT(replacer->get().openFile(Path("bar"))->readAllText() == "original");
    KJ_EXPECT(dir->openFile(Path({"foo", "bar"}))->readAllText() == "original");
  }

  {
    // CREATE fails -- already exists.
    auto replacer = dir->replaceSubdir(Path("foo"), WriteMode::CREATE);
    replacer->get().openFile(Path("corge"), WriteMode::CREATE)->writeAll("bazqux");
    KJ_EXPECT(dir->listNames().size() == 1 && dir->listNames()[0] == "foo");
    KJ_EXPECT(!replacer->tryCommit());
  }

  // Unchanged.
  KJ_EXPECT(dir->openFile(Path({"foo", "bar"}))->readAllText() == "original");
  KJ_EXPECT(!dir->exists(Path({"foo", "corge"})));

  {
    // MODIFY succeeds.
    auto replacer = dir->replaceSubdir(Path("foo"), WriteMode::MODIFY);
    replacer->get().openFile(Path("corge"), WriteMode::CREATE)->writeAll("bazqux");
    KJ_EXPECT(dir->listNames().size() == 1 && dir->listNames()[0] == "foo");
    replacer->commit();
  }

  // Replaced with new contents.
  KJ_EXPECT(!dir->exists(Path({"foo", "bar"})));
  KJ_EXPECT(dir->openFile(Path({"foo", "corge"}))->readAllText() == "bazqux");
}

766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 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
KJ_TEST("DiskDirectory replace directory with file") {
  TempDir tempDir;
  auto dir = tempDir.get();

  dir->openFile(Path({"foo", "bar"}), WriteMode::CREATE | WriteMode::CREATE_PARENT)
     ->writeAll("foobar");

  {
    // CREATE fails -- already exists.
    auto replacer = dir->replaceFile(Path("foo"), WriteMode::CREATE);
    replacer->get().writeAll("bazqux");
    KJ_EXPECT(!replacer->tryCommit());
  }

  // Still a directory.
  KJ_EXPECT(dir->lstat(Path("foo")).type == FsNode::Type::DIRECTORY);

  {
    // MODIFY succeeds.
    auto replacer = dir->replaceFile(Path("foo"), WriteMode::MODIFY);
    replacer->get().writeAll("bazqux");
    replacer->commit();
  }

  // Replaced with file.
  KJ_EXPECT(dir->openFile(Path("foo"))->readAllText() == "bazqux");
}

KJ_TEST("DiskDirectory replace file with directory") {
  TempDir tempDir;
  auto dir = tempDir.get();

  dir->openFile(Path("foo"), WriteMode::CREATE)
     ->writeAll("foobar");

  {
    // CREATE fails -- already exists.
    auto replacer = dir->replaceSubdir(Path("foo"), WriteMode::CREATE);
    replacer->get().openFile(Path("bar"), WriteMode::CREATE)->writeAll("bazqux");
    KJ_EXPECT(dir->listNames().size() == 1 && dir->listNames()[0] == "foo");
    KJ_EXPECT(!replacer->tryCommit());
  }

  // Still a file.
  KJ_EXPECT(dir->openFile(Path("foo"))->readAllText() == "foobar");

  {
    // MODIFY succeeds.
    auto replacer = dir->replaceSubdir(Path("foo"), WriteMode::MODIFY);
    replacer->get().openFile(Path("bar"), WriteMode::CREATE)->writeAll("bazqux");
    KJ_EXPECT(dir->listNames().size() == 1 && dir->listNames()[0] == "foo");
    replacer->commit();
  }

  // Replaced with directory.
  KJ_EXPECT(dir->openFile(Path({"foo", "bar"}))->readAllText() == "bazqux");
}

#ifndef HOLES_NOT_SUPPORTED
KJ_TEST("DiskFile holes") {
826 827 828 829 830
  if (isWine()) {
    // WINE doesn't support sparse files.
    return;
  }

831 832 833 834
  TempDir tempDir;
  auto dir = tempDir.get();

  auto file = dir->openFile(Path("holes"), WriteMode::CREATE);
835 836 837 838 839 840 841 842 843 844 845 846

#if _WIN32
  FILE_SET_SPARSE_BUFFER sparseInfo;
  memset(&sparseInfo, 0, sizeof(sparseInfo));
  sparseInfo.SetSparse = TRUE;
  DWORD dummy;
  KJ_WIN32(DeviceIoControl(
      KJ_ASSERT_NONNULL(file->getWin32Handle()),
      FSCTL_SET_SPARSE, &sparseInfo, sizeof(sparseInfo),
      NULL, 0, &dummy, NULL));
#endif

847 848 849
  file->writeAll("foobar");
  file->write(1 << 20, StringPtr("foobar").asBytes());

850 851 852
  // Some filesystems, like BTRFS, report zero `spaceUsed` until synced.
  file->datasync();

853 854
  // Allow for block sizes as low as 512 bytes and as high as 64k.
  auto meta = file->stat();
855
  KJ_EXPECT(meta.spaceUsed >= 2 * 512, meta.spaceUsed);
856 857 858
  KJ_EXPECT(meta.spaceUsed <= 2 * 65536);

  byte buf[7];
859 860

#if !_WIN32  // Win32 CopyFile() does NOT preserve sparseness.
861 862 863 864 865 866 867 868 869 870 871 872 873 874
  {
    // Copy doesn't fill in holes.
    dir->transfer(Path("copy"), WriteMode::CREATE, Path("holes"), TransferMode::COPY);
    auto copy = dir->openFile(Path("copy"));
    KJ_EXPECT(copy->stat().spaceUsed == meta.spaceUsed);
    KJ_EXPECT(copy->read(0, buf) == 7);
    KJ_EXPECT(StringPtr(reinterpret_cast<char*>(buf), 6) == "foobar");

    KJ_EXPECT(copy->read(1 << 20, buf) == 6);
    KJ_EXPECT(StringPtr(reinterpret_cast<char*>(buf), 6) == "foobar");

    KJ_EXPECT(copy->read(1 << 19, buf) == 7);
    KJ_EXPECT(StringPtr(reinterpret_cast<char*>(buf), 6) == StringPtr("\0\0\0\0\0\0", 6));
  }
875
#endif
876 877

  file->truncate(1 << 21);
878
  file->datasync();
879 880 881 882
  KJ_EXPECT(file->stat().spaceUsed == meta.spaceUsed);
  KJ_EXPECT(file->read(1 << 20, buf) == 7);
  KJ_EXPECT(StringPtr(reinterpret_cast<char*>(buf), 6) == "foobar");

883
#if !_WIN32  // Win32 CopyFile() does NOT preserve sparseness.
884 885 886 887 888 889 890 891 892 893 894 895 896
  {
    dir->transfer(Path("copy"), WriteMode::MODIFY, Path("holes"), TransferMode::COPY);
    auto copy = dir->openFile(Path("copy"));
    KJ_EXPECT(copy->stat().spaceUsed == meta.spaceUsed);
    KJ_EXPECT(copy->read(0, buf) == 7);
    KJ_EXPECT(StringPtr(reinterpret_cast<char*>(buf), 6) == "foobar");

    KJ_EXPECT(copy->read(1 << 20, buf) == 7);
    KJ_EXPECT(StringPtr(reinterpret_cast<char*>(buf), 6) == "foobar");

    KJ_EXPECT(copy->read(1 << 19, buf) == 7);
    KJ_EXPECT(StringPtr(reinterpret_cast<char*>(buf), 6) == StringPtr("\0\0\0\0\0\0", 6));
  }
897 898 899 900
#endif

  // Try punching a hole with zero().
  file->zero(1 << 20, 4096);
901
  file->datasync();
902 903 904
#if !_WIN32
  // TODO(someday): This doesn't work on Windows. I don't know why. We're definitely using the
  //   proper ioctl. Oh well.
905
  KJ_EXPECT(file->stat().spaceUsed < meta.spaceUsed);
906 907 908
#endif
  KJ_EXPECT(file->read(1 << 20, buf) == 7);
  KJ_EXPECT(StringPtr(reinterpret_cast<char*>(buf), 6) == StringPtr("\0\0\0\0\0\0", 6));
909 910 911 912 913
}
#endif

}  // namespace
}  // namespace kj