diff options
author | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2022-09-29 16:16:15 +0200 |
---|---|---|
committer | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2022-11-09 10:04:06 +0000 |
commit | a95a7417ad456115a1ef2da4bb8320531c0821f1 (patch) | |
tree | edcd59279e486d2fd4a8f88a7ed025bcf925c6e6 /chromium/net/disk_cache | |
parent | 33fc33aa94d4add0878ec30dc818e34e1dd3cc2a (diff) | |
download | qtwebengine-chromium-a95a7417ad456115a1ef2da4bb8320531c0821f1.tar.gz |
BASELINE: Update Chromium to 106.0.5249.126
Change-Id: Ib0bb21c437a7d1686e21c33f2d329f2ac425b7ab
Reviewed-on: https://codereview.qt-project.org/c/qt/qtwebengine-chromium/+/438936
Reviewed-by: Allan Sandfeld Jensen <allan.jensen@qt.io>
Diffstat (limited to 'chromium/net/disk_cache')
61 files changed, 822 insertions, 703 deletions
diff --git a/chromium/net/disk_cache/backend_cleanup_tracker.cc b/chromium/net/disk_cache/backend_cleanup_tracker.cc index f01ecec8f6e..d4c44913f9e 100644 --- a/chromium/net/disk_cache/backend_cleanup_tracker.cc +++ b/chromium/net/disk_cache/backend_cleanup_tracker.cc @@ -49,8 +49,9 @@ scoped_refptr<BackendCleanupTracker> BackendCleanupTracker::TryCreate( all_trackers->map.insert( std::pair<base::FilePath, BackendCleanupTracker*>(path, nullptr)); if (insert_result.second) { - insert_result.first->second = new BackendCleanupTracker(path); - return insert_result.first->second; + auto tracker = base::WrapRefCounted(new BackendCleanupTracker(path)); + insert_result.first->second = tracker.get(); + return tracker; } else { insert_result.first->second->AddPostCleanupCallbackImpl( std::move(retry_closure)); @@ -67,8 +68,8 @@ void BackendCleanupTracker::AddPostCleanupCallback(base::OnceClosure cb) { } void BackendCleanupTracker::AddPostCleanupCallbackImpl(base::OnceClosure cb) { - post_cleanup_cbs_.push_back( - std::make_pair(base::SequencedTaskRunnerHandle::Get(), std::move(cb))); + post_cleanup_cbs_.emplace_back(base::SequencedTaskRunnerHandle::Get(), + std::move(cb)); } BackendCleanupTracker::BackendCleanupTracker(const base::FilePath& path) diff --git a/chromium/net/disk_cache/backend_unittest.cc b/chromium/net/disk_cache/backend_unittest.cc index 9be7d47ccf5..16ac64f3042 100644 --- a/chromium/net/disk_cache/backend_unittest.cc +++ b/chromium/net/disk_cache/backend_unittest.cc @@ -107,8 +107,8 @@ std::unique_ptr<disk_cache::BackendImpl> CreateExistingEntryCache( /* cache_thread = */ nullptr, net::DISK_CACHE, /* net_log = */ nullptr)); - int rv = cache->Init(cb.callback()); - if (cb.GetResult(rv) != net::OK) + cache->Init(cb.callback()); + if (cb.WaitForResult() != net::OK) return nullptr; TestEntryResultCompletionCallback cb2; @@ -222,6 +222,7 @@ class DiskCacheBackendTest : public DiskCacheTestWithCache { void BackendOpenOrCreateEntry(); void BackendDeadOpenNextEntry(); void BackendIteratorConcurrentDoom(); + void BackendValidateMigrated(); }; void DiskCacheBackendTest::CreateKeyAndCheck(disk_cache::Backend* cache, @@ -584,7 +585,7 @@ TEST_F(DiskCacheBackendTest, ShaderCacheKeying) { } TEST_F(DiskCacheTest, CreateBackend) { - net::TestCompletionCallback cb; + TestBackendResultCompletionCallback cb; { ASSERT_TRUE(CleanupCacheDir()); @@ -596,44 +597,47 @@ TEST_F(DiskCacheTest, CreateBackend) { cache.reset(); // Now test the public API. - int rv = disk_cache::CreateCacheBackend( + + disk_cache::BackendResult rv = disk_cache::CreateCacheBackend( net::DISK_CACHE, net::CACHE_BACKEND_DEFAULT, /*file_operations=*/nullptr, cache_path_, 0, - disk_cache::ResetHandling::kNeverReset, nullptr, &cache, cb.callback()); - ASSERT_THAT(cb.GetResult(rv), IsOk()); - ASSERT_TRUE(cache.get()); - cache.reset(); + disk_cache::ResetHandling::kNeverReset, nullptr, cb.callback()); + rv = cb.GetResult(std::move(rv)); + ASSERT_THAT(rv.net_error, IsOk()); + ASSERT_TRUE(rv.backend); + rv.backend.reset(); rv = disk_cache::CreateCacheBackend( net::MEMORY_CACHE, net::CACHE_BACKEND_DEFAULT, /*file_operations=*/nullptr, base::FilePath(), 0, - disk_cache::ResetHandling::kNeverReset, nullptr, &cache, cb.callback()); - ASSERT_THAT(cb.GetResult(rv), IsOk()); - ASSERT_TRUE(cache.get()); - cache.reset(); + disk_cache::ResetHandling::kNeverReset, nullptr, cb.callback()); + rv = cb.GetResult(std::move(rv)); + ASSERT_THAT(rv.net_error, IsOk()); + ASSERT_TRUE(rv.backend); + rv.backend.reset(); } base::RunLoop().RunUntilIdle(); } TEST_F(DiskCacheTest, MemBackendPostCleanupCallback) { - net::TestCompletionCallback cb; + TestBackendResultCompletionCallback cb; net::TestClosure on_cleanup; - std::unique_ptr<disk_cache::Backend> cache; - int rv = disk_cache::CreateCacheBackend( + disk_cache::BackendResult rv = disk_cache::CreateCacheBackend( net::MEMORY_CACHE, net::CACHE_BACKEND_DEFAULT, /*file_operations=*/nullptr, base::FilePath(), 0, - disk_cache::ResetHandling::kNeverReset, nullptr, &cache, - on_cleanup.closure(), cb.callback()); - ASSERT_THAT(cb.GetResult(rv), IsOk()); - ASSERT_TRUE(cache.get()); + disk_cache::ResetHandling::kNeverReset, nullptr, on_cleanup.closure(), + cb.callback()); + rv = cb.GetResult(std::move(rv)); + ASSERT_THAT(rv.net_error, IsOk()); + ASSERT_TRUE(rv.backend); // The callback should be posted after backend is destroyed. base::RunLoop().RunUntilIdle(); EXPECT_FALSE(on_cleanup.have_result()); - cache.reset(); + rv.backend.reset(); EXPECT_FALSE(on_cleanup.have_result()); base::RunLoop().RunUntilIdle(); @@ -643,33 +647,34 @@ TEST_F(DiskCacheTest, MemBackendPostCleanupCallback) { TEST_F(DiskCacheTest, CreateBackendDouble) { // Make sure that creation for the second backend for same path happens // after the first one completes. - net::TestCompletionCallback cb, cb2; + TestBackendResultCompletionCallback cb, cb2; - std::unique_ptr<disk_cache::Backend> cache, cache2; - - int rv = disk_cache::CreateCacheBackend( + disk_cache::BackendResult rv = disk_cache::CreateCacheBackend( net::APP_CACHE, net::CACHE_BACKEND_DEFAULT, /*file_operations=*/nullptr, - cache_path_, 0, disk_cache::ResetHandling::kNeverReset, nullptr, &cache, - cb.callback()); + cache_path_, 0, disk_cache::ResetHandling::kNeverReset, + /*net_log=*/nullptr, cb.callback()); - int rv2 = disk_cache::CreateCacheBackend( + disk_cache::BackendResult rv2 = disk_cache::CreateCacheBackend( net::APP_CACHE, net::CACHE_BACKEND_DEFAULT, /*file_operations=*/nullptr, - cache_path_, 0, disk_cache::ResetHandling::kNeverReset, nullptr, &cache2, - cb2.callback()); + cache_path_, 0, disk_cache::ResetHandling::kNeverReset, + /*net_log=*/nullptr, cb2.callback()); - EXPECT_THAT(cb.GetResult(rv), IsOk()); - EXPECT_TRUE(cache.get()); + rv = cb.GetResult(std::move(rv)); + EXPECT_THAT(rv.net_error, IsOk()); + EXPECT_TRUE(rv.backend); disk_cache::FlushCacheThreadForTesting(); - // No cache 2 yet. - EXPECT_EQ(net::ERR_IO_PENDING, rv2); + // No rv2.backend yet. + EXPECT_EQ(net::ERR_IO_PENDING, rv2.net_error); + EXPECT_FALSE(rv2.backend); EXPECT_FALSE(cb2.have_result()); - cache.reset(); + rv.backend.reset(); - // Now cache2 should exist. - EXPECT_THAT(cb2.GetResult(rv2), IsOk()); - EXPECT_TRUE(cache2.get()); + // Now rv2.backend should exist. + rv2 = cb2.GetResult(std::move(rv2)); + EXPECT_THAT(rv2.net_error, IsOk()); + EXPECT_TRUE(rv2.backend); } TEST_F(DiskCacheBackendTest, CreateBackendDoubleOpenEntry) { @@ -682,35 +687,35 @@ TEST_F(DiskCacheBackendTest, CreateBackendDoubleOpenEntry) { // Make sure that creation for the second backend for same path happens // after the first one completes, and all of its ops complete. - net::TestCompletionCallback cb, cb2; - - std::unique_ptr<disk_cache::Backend> cache, cache2; + TestBackendResultCompletionCallback cb, cb2; - int rv = disk_cache::CreateCacheBackend( + disk_cache::BackendResult rv = disk_cache::CreateCacheBackend( net::APP_CACHE, net::CACHE_BACKEND_SIMPLE, /*file_operations=*/nullptr, - cache_path_, 0, disk_cache::ResetHandling::kNeverReset, nullptr, &cache, - cb.callback()); + cache_path_, 0, disk_cache::ResetHandling::kNeverReset, + /*net_log=*/nullptr, cb.callback()); - int rv2 = disk_cache::CreateCacheBackend( + disk_cache::BackendResult rv2 = disk_cache::CreateCacheBackend( net::APP_CACHE, net::CACHE_BACKEND_SIMPLE, /*file_operations=*/nullptr, - cache_path_, 0, disk_cache::ResetHandling::kNeverReset, nullptr, &cache2, - cb2.callback()); + cache_path_, 0, disk_cache::ResetHandling::kNeverReset, + /*net_log=*/nullptr, cb2.callback()); - EXPECT_THAT(cb.GetResult(rv), IsOk()); - ASSERT_TRUE(cache.get()); + rv = cb.GetResult(std::move(rv)); + EXPECT_THAT(rv.net_error, IsOk()); + ASSERT_TRUE(rv.backend); disk_cache::FlushCacheThreadForTesting(); // No cache 2 yet. - EXPECT_EQ(net::ERR_IO_PENDING, rv2); + EXPECT_EQ(net::ERR_IO_PENDING, rv2.net_error); + EXPECT_FALSE(rv2.backend); EXPECT_FALSE(cb2.have_result()); TestEntryResultCompletionCallback cb3; EntryResult entry_result = - cache->CreateEntry("key", net::HIGHEST, cb3.callback()); + rv.backend->CreateEntry("key", net::HIGHEST, cb3.callback()); entry_result = cb3.GetResult(std::move(entry_result)); ASSERT_EQ(net::OK, entry_result.net_error()); - cache.reset(); + rv.backend.reset(); // Still doesn't exist. EXPECT_FALSE(cb2.have_result()); @@ -718,8 +723,9 @@ TEST_F(DiskCacheBackendTest, CreateBackendDoubleOpenEntry) { entry_result.ReleaseEntry()->Close(); // Now should exist. - EXPECT_THAT(cb2.GetResult(rv2), IsOk()); - EXPECT_TRUE(cache2.get()); + rv2 = cb2.GetResult(std::move(rv2)); + EXPECT_THAT(rv2.net_error, IsOk()); + EXPECT_TRUE(rv2.backend); } TEST_F(DiskCacheBackendTest, CreateBackendPostCleanup) { @@ -735,25 +741,26 @@ TEST_F(DiskCacheBackendTest, CreateBackendPostCleanup) { CleanupCacheDir(); base::RunLoop run_loop; - net::TestCompletionCallback cb; - std::unique_ptr<disk_cache::Backend> cache; + TestBackendResultCompletionCallback cb; - int rv = disk_cache::CreateCacheBackend( + disk_cache::BackendResult rv = disk_cache::CreateCacheBackend( net::APP_CACHE, net::CACHE_BACKEND_SIMPLE, /*file_operations=*/nullptr, - cache_path_, 0, disk_cache::ResetHandling::kNeverReset, nullptr, &cache, - run_loop.QuitClosure(), cb.callback()); - EXPECT_THAT(cb.GetResult(rv), IsOk()); - ASSERT_TRUE(cache.get()); + cache_path_, 0, disk_cache::ResetHandling::kNeverReset, + /*net_log=*/nullptr, run_loop.QuitClosure(), cb.callback()); + rv = cb.GetResult(std::move(rv)); + EXPECT_THAT(rv.net_error, IsOk()); + ASSERT_TRUE(rv.backend); TestEntryResultCompletionCallback cb2; - EntryResult result = cache->CreateEntry("key", net::HIGHEST, cb2.callback()); + EntryResult result = + rv.backend->CreateEntry("key", net::HIGHEST, cb2.callback()); result = cb2.GetResult(std::move(result)); ASSERT_EQ(net::OK, result.net_error()); disk_cache::Entry* entry = result.ReleaseEntry(); EXPECT_EQ(kBufSize, WriteData(entry, 0, 0, buffer.get(), kBufSize, false)); entry->Close(); - cache.reset(); + rv.backend.reset(); // Wait till the post-cleanup callback. run_loop.Run(); @@ -781,29 +788,29 @@ TEST_F(DiskCacheBackendTest, SimpleCreateBackendRecoveryAppCache) { CleanupCacheDir(); base::RunLoop run_loop; - net::TestCompletionCallback cb; - std::unique_ptr<disk_cache::Backend> cache; + TestBackendResultCompletionCallback cb; // Create a backend with post-cleanup callback specified, in order to know // when the index has been written back (so it can be deleted race-free). - int rv = disk_cache::CreateCacheBackend( + disk_cache::BackendResult rv = disk_cache::CreateCacheBackend( net::APP_CACHE, net::CACHE_BACKEND_SIMPLE, /*file_operations=*/nullptr, - cache_path_, 0, disk_cache::ResetHandling::kNeverReset, nullptr, &cache, - run_loop.QuitClosure(), cb.callback()); - EXPECT_THAT(cb.GetResult(rv), IsOk()); - ASSERT_TRUE(cache.get()); + cache_path_, 0, disk_cache::ResetHandling::kNeverReset, + /*net_log=*/nullptr, run_loop.QuitClosure(), cb.callback()); + rv = cb.GetResult(std::move(rv)); + EXPECT_THAT(rv.net_error, IsOk()); + ASSERT_TRUE(rv.backend); // Create an entry. TestEntryResultCompletionCallback cb2; disk_cache::EntryResult result = - cache->CreateEntry("key", net::HIGHEST, cb2.callback()); + rv.backend->CreateEntry("key", net::HIGHEST, cb2.callback()); result = cb2.GetResult(std::move(result)); ASSERT_EQ(net::OK, result.net_error()); disk_cache::Entry* entry = result.ReleaseEntry(); EXPECT_EQ(kBufSize, WriteData(entry, 0, 0, buffer.get(), kBufSize, false)); entry->Close(); - cache.reset(); + rv.backend.reset(); // Wait till the post-cleanup callback. run_loop.Run(); @@ -835,8 +842,8 @@ TEST_F(DiskCacheBackendTest, CreateBackend_MissingFile) { std::unique_ptr<disk_cache::BackendImpl> cache( std::make_unique<disk_cache::BackendImpl>(cache_path_, nullptr, nullptr, net::DISK_CACHE, nullptr)); - int rv = cache->Init(cb.callback()); - EXPECT_THAT(cb.GetResult(rv), IsError(net::ERR_FAILED)); + cache->Init(cb.callback()); + EXPECT_THAT(cb.WaitForResult(), IsError(net::ERR_FAILED)); disallow_blocking.reset(); cache.reset(); @@ -960,23 +967,24 @@ TEST_F(DiskCacheBackendTest, MultipleInstancesWithPendingFileIO) { ASSERT_TRUE(store.CreateUniqueTempDir()); net::TestCompletionCallback cb; - std::unique_ptr<disk_cache::Backend> extra_cache; - int rv = disk_cache::CreateCacheBackend( + TestBackendResultCompletionCallback create_cb; + disk_cache::BackendResult backend_rv = disk_cache::CreateCacheBackend( net::DISK_CACHE, net::CACHE_BACKEND_DEFAULT, /*file_operations=*/nullptr, store.GetPath(), 0, disk_cache::ResetHandling::kNeverReset, - /* net_log = */ nullptr, &extra_cache, cb.callback()); - ASSERT_THAT(cb.GetResult(rv), IsOk()); - ASSERT_TRUE(extra_cache.get() != nullptr); + /* net_log = */ nullptr, create_cb.callback()); + backend_rv = create_cb.GetResult(std::move(backend_rv)); + ASSERT_THAT(backend_rv.net_error, IsOk()); + ASSERT_TRUE(backend_rv.backend); ASSERT_TRUE(CleanupCacheDir()); SetNewEviction(); // Match the expected behavior for integrity verification. UseCurrentThread(); CreateBackend(disk_cache::kNoBuffering); - rv = GeneratePendingIO(&cb); + int rv = GeneratePendingIO(&cb); - // cache_ has a pending operation, and extra_cache will go away. - extra_cache.reset(); + // cache_ has a pending operation, and backend_rv.backend will go away. + backend_rv.backend.reset(); if (rv == net::ERR_IO_PENDING) EXPECT_FALSE(cb.have_result()); @@ -1107,16 +1115,16 @@ TEST_F(DiskCacheTest, TruncatedIndex) { base::FilePath index = cache_path_.AppendASCII("index"); ASSERT_EQ(5, base::WriteFile(index, "hello", 5)); - net::TestCompletionCallback cb; + TestBackendResultCompletionCallback cb; - std::unique_ptr<disk_cache::Backend> backend; - int rv = disk_cache::CreateCacheBackend( + disk_cache::BackendResult rv = disk_cache::CreateCacheBackend( net::DISK_CACHE, net::CACHE_BACKEND_BLOCKFILE, /*file_operations=*/nullptr, cache_path_, 0, - disk_cache::ResetHandling::kNeverReset, nullptr, &backend, cb.callback()); - ASSERT_NE(net::OK, cb.GetResult(rv)); - - ASSERT_FALSE(backend); + disk_cache::ResetHandling::kNeverReset, /*net_log=*/nullptr, + cb.callback()); + rv = cb.GetResult(std::move(rv)); + ASSERT_NE(net::OK, rv.net_error); + ASSERT_FALSE(rv.backend); } #endif @@ -1198,9 +1206,9 @@ void DiskCacheBackendTest::BackendLoad() { srand(seed); disk_cache::Entry* entries[kLargeNumEntries]; - for (int i = 0; i < kLargeNumEntries; i++) { + for (auto*& entry : entries) { std::string key = GenerateKey(true); - ASSERT_THAT(CreateEntry(key, &entries[i]), IsOk()); + ASSERT_THAT(CreateEntry(key, &entry), IsOk()); } EXPECT_EQ(kLargeNumEntries, cache_->GetEntryCount()); @@ -1212,13 +1220,13 @@ void DiskCacheBackendTest::BackendLoad() { entries[source2] = temp; } - for (int i = 0; i < kLargeNumEntries; i++) { - disk_cache::Entry* entry; - ASSERT_THAT(OpenEntry(entries[i]->GetKey(), &entry), IsOk()); - EXPECT_TRUE(entry == entries[i]); + for (auto* entry : entries) { + disk_cache::Entry* new_entry; + ASSERT_THAT(OpenEntry(entry->GetKey(), &new_entry), IsOk()); + EXPECT_TRUE(new_entry == entry); + new_entry->Close(); + entry->Doom(); entry->Close(); - entries[i]->Doom(); - entries[i]->Close(); } FlushQueueForTest(); EXPECT_EQ(0, cache_->GetEntryCount()); @@ -1472,9 +1480,9 @@ void DiskCacheBackendTest::BackendInvalidEntryWithLoad() { const int kNumEntries = 100; disk_cache::Entry* entries[kNumEntries]; - for (int i = 0; i < kNumEntries; i++) { + for (auto*& entry : entries) { std::string key = GenerateKey(true); - ASSERT_THAT(CreateEntry(key, &entries[i]), IsOk()); + ASSERT_THAT(CreateEntry(key, &entry), IsOk()); } EXPECT_EQ(kNumEntries, cache_->GetEntryCount()); @@ -2519,8 +2527,8 @@ TEST_F(DiskCacheTest, WrongVersion) { std::unique_ptr<disk_cache::BackendImpl> cache( std::make_unique<disk_cache::BackendImpl>(cache_path_, nullptr, nullptr, net::DISK_CACHE, nullptr)); - int rv = cache->Init(cb.callback()); - ASSERT_THAT(cb.GetResult(rv), IsError(net::ERR_FAILED)); + cache->Init(cb.callback()); + ASSERT_THAT(cb.WaitForResult(), IsError(net::ERR_FAILED)); } // Tests that the disk cache successfully joins the control group, dropping the @@ -2538,15 +2546,15 @@ TEST_F(DiskCacheTest, SimpleCacheControlJoin) { // ExperimentControl group. base::FieldTrialList::CreateFieldTrial("SimpleCacheTrial", "ExperimentControl"); - net::TestCompletionCallback cb; - std::unique_ptr<disk_cache::Backend> base_cache; - int rv = disk_cache::CreateCacheBackend( + TestBackendResultCompletionCallback cb; + disk_cache::BackendResult rv = disk_cache::CreateCacheBackend( net::DISK_CACHE, net::CACHE_BACKEND_BLOCKFILE, /*file_operations=*/nullptr, cache_path_, 0, - disk_cache::ResetHandling::kResetOnError, nullptr, &base_cache, + disk_cache::ResetHandling::kResetOnError, /*net_log=*/nullptr, cb.callback()); - ASSERT_THAT(cb.GetResult(rv), IsOk()); - EXPECT_EQ(0, base_cache->GetEntryCount()); + rv = cb.GetResult(std::move(rv)); + ASSERT_THAT(rv.net_error, IsOk()); + EXPECT_EQ(0, rv.backend->GetEntryCount()); } #endif @@ -2568,8 +2576,8 @@ TEST_F(DiskCacheTest, SimpleCacheControlRestart) { for (int i = 0; i < kRestartCount; ++i) { cache = std::make_unique<disk_cache::BackendImpl>( cache_path_, nullptr, nullptr, net::DISK_CACHE, nullptr); - int rv = cache->Init(cb.callback()); - ASSERT_THAT(cb.GetResult(rv), IsOk()); + cache->Init(cb.callback()); + ASSERT_THAT(cb.WaitForResult(), IsOk()); EXPECT_EQ(1, cache->GetEntryCount()); TestEntryResultCompletionCallback cb2; @@ -2604,8 +2612,8 @@ TEST_F(DiskCacheTest, SimpleCacheControlLeave) { std::unique_ptr<disk_cache::BackendImpl> cache( std::make_unique<disk_cache::BackendImpl>(cache_path_, nullptr, nullptr, net::DISK_CACHE, nullptr)); - int rv = cache->Init(cb.callback()); - ASSERT_THAT(cb.GetResult(rv), IsOk()); + cache->Init(cb.callback()); + ASSERT_THAT(cb.WaitForResult(), IsOk()); EXPECT_EQ(1, cache->GetEntryCount()); TestEntryResultCompletionCallback cb2; @@ -2625,19 +2633,19 @@ TEST_F(DiskCacheBackendTest, DeleteOld) { ASSERT_TRUE(CopyTestCache("wrong_version")); SetNewEviction(); - net::TestCompletionCallback cb; + TestBackendResultCompletionCallback cb; { base::ScopedDisallowBlocking disallow_blocking; base::FilePath path(cache_path_); - int rv = disk_cache::CreateCacheBackend( + disk_cache::BackendResult rv = disk_cache::CreateCacheBackend( net::DISK_CACHE, net::CACHE_BACKEND_BLOCKFILE, /*file_operations=*/nullptr, path, 0, - disk_cache::ResetHandling::kResetOnError, nullptr, &cache_, + disk_cache::ResetHandling::kResetOnError, /*net_log=*/nullptr, cb.callback()); path.clear(); // Make sure path was captured by the previous call. - ASSERT_THAT(cb.GetResult(rv), IsOk()); + rv = cb.GetResult(std::move(rv)); + ASSERT_THAT(rv.net_error, IsOk()); } - cache_.reset(); EXPECT_TRUE(CheckCacheIntegrity(cache_path_, new_eviction_, /*max_size = */ 0, mask_)); } @@ -3727,30 +3735,33 @@ TEST_F(DiskCacheTest, MultipleInstances) { ASSERT_TRUE(store1.CreateUniqueTempDir()); ASSERT_TRUE(store2.CreateUniqueTempDir()); - net::TestCompletionCallback cb; + TestBackendResultCompletionCallback cb; const int kNumberOfCaches = 2; - std::unique_ptr<disk_cache::Backend> cache[kNumberOfCaches]; + std::unique_ptr<disk_cache::Backend> caches[kNumberOfCaches]; - int rv = disk_cache::CreateCacheBackend( + disk_cache::BackendResult rv = disk_cache::CreateCacheBackend( net::DISK_CACHE, net::CACHE_BACKEND_DEFAULT, /*file_operations=*/nullptr, - store1.GetPath(), 0, disk_cache::ResetHandling::kNeverReset, nullptr, - &cache[0], cb.callback()); - ASSERT_THAT(cb.GetResult(rv), IsOk()); + store1.GetPath(), 0, disk_cache::ResetHandling::kNeverReset, + /*net_log=*/nullptr, cb.callback()); + rv = cb.GetResult(std::move(rv)); + ASSERT_THAT(rv.net_error, IsOk()); + caches[0] = std::move(rv.backend); rv = disk_cache::CreateCacheBackend( net::GENERATED_BYTE_CODE_CACHE, net::CACHE_BACKEND_DEFAULT, /*file_operations=*/nullptr, store2.GetPath(), 0, - disk_cache::ResetHandling::kNeverReset, nullptr, &cache[1], + disk_cache::ResetHandling::kNeverReset, /*net_log=*/nullptr, cb.callback()); - ASSERT_THAT(cb.GetResult(rv), IsOk()); + rv = cb.GetResult(std::move(rv)); + ASSERT_THAT(rv.net_error, IsOk()); + caches[1] = std::move(rv.backend); - ASSERT_TRUE(cache[0].get() != nullptr && cache[1].get() != nullptr); + ASSERT_TRUE(caches[0].get() != nullptr && caches[1].get() != nullptr); std::string key("the first key"); - for (int i = 0; i < kNumberOfCaches; i++) { + for (auto& cache : caches) { TestEntryResultCompletionCallback cb2; - EntryResult result = - cache[i]->CreateEntry(key, net::HIGHEST, cb2.callback()); + EntryResult result = cache->CreateEntry(key, net::HIGHEST, cb2.callback()); result = cb2.GetResult(std::move(result)); ASSERT_THAT(result.net_error(), IsOk()); result.ReleaseEntry()->Close(); @@ -3886,7 +3897,7 @@ TEST_F(DiskCacheBackendTest, FileSharing) { base::FilePath name = cache_impl_->GetFileName(address); { - scoped_refptr<disk_cache::File> file(new disk_cache::File(false)); + auto file = base::MakeRefCounted<disk_cache::File>(false); file->Init(name); #if BUILDFLAG(IS_WIN) @@ -4135,8 +4146,8 @@ TEST_F(DiskCacheBackendTest, SimpleCacheOverBlockfileCache) { /*file_operations_factory=*/nullptr, cache_path_, nullptr, nullptr, 0, net::DISK_CACHE, nullptr); net::TestCompletionCallback cb; - int rv = simple_cache->Init(cb.callback()); - EXPECT_NE(net::OK, cb.GetResult(rv)); + simple_cache->Init(cb.callback()); + EXPECT_NE(net::OK, cb.WaitForResult()); simple_cache.reset(); DisableIntegrityCheck(); } @@ -4158,13 +4169,13 @@ TEST_F(DiskCacheBackendTest, BlockfileCacheOverSimpleCache) { cache_.reset(); // Check that the |BackendImpl| does not favor this structure. - disk_cache::BackendImpl* cache = new disk_cache::BackendImpl( + auto cache = std::make_unique<disk_cache::BackendImpl>( cache_path_, nullptr, nullptr, net::DISK_CACHE, nullptr); cache->SetUnitTestMode(); net::TestCompletionCallback cb; - int rv = cache->Init(cb.callback()); - EXPECT_NE(net::OK, cb.GetResult(rv)); - delete cache; + cache->Init(cb.callback()); + EXPECT_NE(net::OK, cb.WaitForResult()); + cache.reset(); DisableIntegrityCheck(); } @@ -4630,8 +4641,8 @@ TEST_F(DiskCacheBackendTest, SimpleFdLimit) { histogram_tester.ExpectBucketCount("SimpleCache.FileDescriptorLimiterAction", disk_cache::FD_LIMIT_FAIL_REOPEN_FILE, 0); - for (int i = 0; i < kLargeNumEntries; ++i) { - entries[i]->Close(); + for (auto* entry : entries) { + entry->Close(); RunUntilIdle(); } alt_entry->Close(); @@ -4914,16 +4925,15 @@ TEST_F(DiskCacheBackendTest, EmptyCorruptSimpleCacheRecovery) { ASSERT_EQ(static_cast<int>(kCorruptData.length()), base::WriteFile(index, kCorruptData.data(), kCorruptData.length())); - base::RunLoop run_loop; - std::unique_ptr<disk_cache::Backend> cache; - net::TestCompletionCallback cb; + TestBackendResultCompletionCallback cb; // Simple cache should be able to recover. - int rv = disk_cache::CreateCacheBackend( + disk_cache::BackendResult rv = disk_cache::CreateCacheBackend( net::APP_CACHE, net::CACHE_BACKEND_SIMPLE, /*file_operations=*/nullptr, - cache_path_, 0, disk_cache::ResetHandling::kNeverReset, nullptr, &cache, - cb.callback()); - EXPECT_THAT(cb.GetResult(rv), IsOk()); + cache_path_, 0, disk_cache::ResetHandling::kNeverReset, + /*net_log=*/nullptr, cb.callback()); + rv = cb.GetResult(std::move(rv)); + EXPECT_THAT(rv.net_error, IsOk()); } TEST_F(DiskCacheBackendTest, MAYBE_NonEmptyCorruptSimpleCacheDoesNotRecover) { @@ -4938,16 +4948,15 @@ TEST_F(DiskCacheBackendTest, MAYBE_NonEmptyCorruptSimpleCacheDoesNotRecover) { ASSERT_EQ(static_cast<int>(kCorruptData.length()), base::WriteFile(index, kCorruptData.data(), kCorruptData.length())); - base::RunLoop run_loop; - std::unique_ptr<disk_cache::Backend> cache; - net::TestCompletionCallback cb; + TestBackendResultCompletionCallback cb; // Simple cache should not be able to recover when there are entry files. - int rv = disk_cache::CreateCacheBackend( + disk_cache::BackendResult rv = disk_cache::CreateCacheBackend( net::APP_CACHE, net::CACHE_BACKEND_SIMPLE, /*file_operations=*/nullptr, - cache_path_, 0, disk_cache::ResetHandling::kNeverReset, nullptr, &cache, - cb.callback()); - EXPECT_THAT(cb.GetResult(rv), IsError(net::ERR_FAILED)); + cache_path_, 0, disk_cache::ResetHandling::kNeverReset, + /*net_log=*/nullptr, cb.callback()); + rv = cb.GetResult(std::move(rv)); + EXPECT_THAT(rv.net_error, IsError(net::ERR_FAILED)); } TEST_F(DiskCacheBackendTest, SimpleOwnershipTransferBackendDestroyRace) { @@ -5014,15 +5023,16 @@ TEST_F(DiskCacheBackendTest, SimpleCacheSoftResetKeepsValues) { CleanupCacheDir(); { // Do the initial cache creation then delete the values. - std::unique_ptr<disk_cache::Backend> cache; - net::TestCompletionCallback cb; + TestBackendResultCompletionCallback cb; // Create an initial back-end and wait for indexing - int rv = disk_cache::CreateCacheBackend( + disk_cache::BackendResult rv = disk_cache::CreateCacheBackend( net::APP_CACHE, net::CACHE_BACKEND_SIMPLE, /*file_operations=*/nullptr, - cache_path_, 0, disk_cache::ResetHandling::kNeverReset, nullptr, &cache, - cb.callback()); - EXPECT_THAT(cb.GetResult(rv), IsOk()); + cache_path_, 0, disk_cache::ResetHandling::kNeverReset, + /*net_log=*/nullptr, cb.callback()); + rv = cb.GetResult(std::move(rv)); + EXPECT_THAT(rv.net_error, IsOk()); + std::unique_ptr<disk_cache::Backend> cache = std::move(rv.backend); ASSERT_TRUE(cache.get()); WaitForSimpleCacheIndexAndCheck(cache.get()); @@ -5033,14 +5043,15 @@ TEST_F(DiskCacheBackendTest, SimpleCacheSoftResetKeepsValues) { RunUntilIdle(); { // Do the second cache creation with no reset flag, preserving entries. - std::unique_ptr<disk_cache::Backend> cache; - net::TestCompletionCallback cb; + TestBackendResultCompletionCallback cb; - int rv = disk_cache::CreateCacheBackend( + disk_cache::BackendResult rv = disk_cache::CreateCacheBackend( net::APP_CACHE, net::CACHE_BACKEND_SIMPLE, /*file_operations=*/nullptr, - cache_path_, 0, disk_cache::ResetHandling::kNeverReset, nullptr, &cache, - cb.callback()); - EXPECT_THAT(cb.GetResult(rv), IsOk()); + cache_path_, 0, disk_cache::ResetHandling::kNeverReset, + /*net_log=*/nullptr, cb.callback()); + rv = cb.GetResult(std::move(rv)); + EXPECT_THAT(rv.net_error, IsOk()); + std::unique_ptr<disk_cache::Backend> cache = std::move(rv.backend); ASSERT_TRUE(cache.get()); WaitForSimpleCacheIndexAndCheck(cache.get()); @@ -5059,14 +5070,15 @@ TEST_F(DiskCacheBackendTest, SimpleCacheHardResetDropsValues) { CleanupCacheDir(); { // Create the initial back-end. - net::TestCompletionCallback cb; - std::unique_ptr<disk_cache::Backend> cache; + TestBackendResultCompletionCallback cb; - int rv = disk_cache::CreateCacheBackend( + disk_cache::BackendResult rv = disk_cache::CreateCacheBackend( net::APP_CACHE, net::CACHE_BACKEND_SIMPLE, /*file_operations=*/nullptr, - cache_path_, 0, disk_cache::ResetHandling::kNeverReset, nullptr, &cache, - cb.callback()); - EXPECT_THAT(cb.GetResult(rv), IsOk()); + cache_path_, 0, disk_cache::ResetHandling::kNeverReset, + /*net_log=*/nullptr, cb.callback()); + rv = cb.GetResult(std::move(rv)); + EXPECT_THAT(rv.net_error, IsOk()); + std::unique_ptr<disk_cache::Backend> cache = std::move(rv.backend); ASSERT_TRUE(cache.get()); WaitForSimpleCacheIndexAndCheck(cache.get()); @@ -5077,14 +5089,15 @@ TEST_F(DiskCacheBackendTest, SimpleCacheHardResetDropsValues) { RunUntilIdle(); { // Re-load cache with a reset flag, which should ignore existing entries. - net::TestCompletionCallback cb; - std::unique_ptr<disk_cache::Backend> cache; + TestBackendResultCompletionCallback cb; - int rv = disk_cache::CreateCacheBackend( + disk_cache::BackendResult rv = disk_cache::CreateCacheBackend( net::APP_CACHE, net::CACHE_BACKEND_SIMPLE, /*file_operations=*/nullptr, - cache_path_, 0, disk_cache::ResetHandling::kReset, nullptr, &cache, + cache_path_, 0, disk_cache::ResetHandling::kReset, /*net_log=*/nullptr, cb.callback()); - EXPECT_THAT(cb.GetResult(rv), IsOk()); + rv = cb.GetResult(std::move(rv)); + EXPECT_THAT(rv.net_error, IsOk()); + std::unique_ptr<disk_cache::Backend> cache = std::move(rv.backend); ASSERT_TRUE(cache.get()); WaitForSimpleCacheIndexAndCheck(cache.get()); @@ -5435,3 +5448,44 @@ TEST_F(DiskCacheBackendTest, SimpleDoomAfterBackendDestruction) { entry->Doom(); entry->Close(); } + +void DiskCacheBackendTest::BackendValidateMigrated() { + // Blockfile 3.0 migration test. + DisableFirstCleanup(); // started from copied dir, not cleaned dir. + InitCache(); + + // The total size comes straight from the headers, and is expected to be 1258 + // for either set of testdata. + EXPECT_EQ(1258, CalculateSizeOfAllEntries()); + EXPECT_EQ(1, cache_->GetEntryCount()); + + disk_cache::Entry* entry = nullptr; + ASSERT_THAT(OpenEntry("https://example.org/data", &entry), IsOk()); + + // Size of the actual payload. + EXPECT_EQ(1234, entry->GetDataSize(1)); + + entry->Close(); +} + +TEST_F(DiskCacheBackendTest, BlockfileMigrate20) { + ASSERT_TRUE(CopyTestCache("good_2_0")); + BackendValidateMigrated(); +} + +TEST_F(DiskCacheBackendTest, BlockfileMigrate21) { + ASSERT_TRUE(CopyTestCache("good_2_1")); + BackendValidateMigrated(); +} + +TEST_F(DiskCacheBackendTest, BlockfileMigrateNewEviction20) { + ASSERT_TRUE(CopyTestCache("good_2_0")); + SetNewEviction(); + BackendValidateMigrated(); +} + +TEST_F(DiskCacheBackendTest, BlockfileMigrateNewEviction21) { + ASSERT_TRUE(CopyTestCache("good_2_1")); + SetNewEviction(); + BackendValidateMigrated(); +} diff --git a/chromium/net/disk_cache/blockfile/backend_impl.cc b/chromium/net/disk_cache/blockfile/backend_impl.cc index 171551db4b2..25d81dce762 100644 --- a/chromium/net/disk_cache/blockfile/backend_impl.cc +++ b/chromium/net/disk_cache/blockfile/backend_impl.cc @@ -207,9 +207,8 @@ BackendImpl::~BackendImpl() { } } -net::Error BackendImpl::Init(CompletionOnceCallback callback) { +void BackendImpl::Init(CompletionOnceCallback callback) { background_queue_.Init(std::move(callback)); - return net::ERR_IO_PENDING; } int BackendImpl::SyncInit() { @@ -412,7 +411,7 @@ int BackendImpl::SyncDoomEntriesBetween(const base::Time initial_time, return net::ERR_FAILED; scoped_refptr<EntryImpl> node; - std::unique_ptr<Rankings::Iterator> iterator(new Rankings::Iterator()); + auto iterator = std::make_unique<Rankings::Iterator>(); scoped_refptr<EntryImpl> next = OpenNextEntryImpl(iterator.get()); if (!next) return net::OK; @@ -454,7 +453,7 @@ int BackendImpl::SyncDoomEntriesSince(const base::Time initial_time) { stats_.OnEvent(Stats::DOOM_RECENT); for (;;) { - std::unique_ptr<Rankings::Iterator> iterator(new Rankings::Iterator()); + auto iterator = std::make_unique<Rankings::Iterator>(); scoped_refptr<EntryImpl> entry = OpenNextEntryImpl(iterator.get()); if (!entry) return net::OK; @@ -514,7 +513,7 @@ scoped_refptr<EntryImpl> BackendImpl::OpenEntryImpl(const std::string& key) { cache_entry = nullptr; } - int current_size = data_->header.num_bytes / (1024 * 1024); + int64_t current_size = data_->header.num_bytes / (1024 * 1024); int64_t total_hours = stats_.GetCounter(Stats::TIMER) / 120; int64_t no_use_hours = stats_.GetCounter(Stats::LAST_REPORT_TIMER) / 120; int64_t use_hours = total_hours - no_use_hours; @@ -594,8 +593,8 @@ scoped_refptr<EntryImpl> BackendImpl::CreateEntryImpl(const std::string& key) { return nullptr; } - scoped_refptr<EntryImpl> cache_entry( - new EntryImpl(this, entry_address, false)); + auto cache_entry = + base::MakeRefCounted<EntryImpl>(this, entry_address, false); IncreaseNumRefs(); if (!cache_entry->CreateEntry(node_address, key, hash)) { @@ -1297,8 +1296,7 @@ class BackendImpl::IteratorImpl : public Backend::Iterator { public: explicit IteratorImpl(base::WeakPtr<InFlightBackendIO> background_queue) : background_queue_(background_queue), - iterator_(new Rankings::Iterator()) { - } + iterator_(std::make_unique<Rankings::Iterator>()) {} ~IteratorImpl() override { if (background_queue_) @@ -1318,8 +1316,7 @@ class BackendImpl::IteratorImpl : public Backend::Iterator { }; std::unique_ptr<Backend::Iterator> BackendImpl::CreateIterator() { - return std::unique_ptr<Backend::Iterator>( - new IteratorImpl(GetBackgroundQueue())); + return std::make_unique<IteratorImpl>(GetBackgroundQueue()); } void BackendImpl::GetStats(StatsItems* stats) { @@ -1364,11 +1361,6 @@ bool BackendImpl::CreateBackingStore(disk_cache::File* file) { IndexHeader header; header.table_len = DesiredIndexTableLen(max_size_); - - // We need file version 2.1 for the new eviction algorithm. - if (new_eviction_) - header.version = 0x20001; - header.create_time = Time::Now().ToInternalValue(); if (!file->Write(&header, sizeof(header), 0)) @@ -1390,7 +1382,7 @@ bool BackendImpl::CreateBackingStore(disk_cache::File* file) { static_assert(sizeof(disk_cache::IndexHeader) < kPageSize, "Code below assumes it wouldn't overwrite header by starting " "at kPageSize"); - std::unique_ptr<char[]> page(new char[kPageSize]); + auto page = std::make_unique<char[]>(kPageSize); memset(page.get(), 0, kPageSize); for (size_t offset = kPageSize; offset < size; offset += kPageSize) { @@ -1417,8 +1409,7 @@ bool BackendImpl::InitBackingStore(bool* file_created) { bool ret = true; *file_created = base_file.created(); - scoped_refptr<disk_cache::File> file( - new disk_cache::File(std::move(base_file))); + auto file = base::MakeRefCounted<disk_cache::File>(std::move(base_file)); if (*file_created) ret = CreateBackingStore(file.get()); @@ -1426,7 +1417,7 @@ bool BackendImpl::InitBackingStore(bool* file_created) { if (!ret) return false; - index_ = new MappedFile(); + index_ = base::MakeRefCounted<MappedFile>(); data_ = static_cast<Index*>(index_->Init(index_name, 0)); if (!data_) { LOG(ERROR) << "Unable to map Index file"; @@ -1498,7 +1489,7 @@ bool BackendImpl::InitStats() { if (!file) return false; - std::unique_ptr<char[]> data(new char[size]); + auto data = std::make_unique<char[]>(size); size_t offset = address.start_block() * address.BlockSize() + kBlockHeaderSize; if (!file->Read(data.get(), size, offset)) @@ -1513,7 +1504,7 @@ bool BackendImpl::InitStats() { void BackendImpl::StoreStats() { int size = stats_.StorageSize(); - std::unique_ptr<char[]> data(new char[size]); + auto data = std::make_unique<char[]>(size); Addr address; size = stats_.SerializeStats(data.get(), size, &address); DCHECK(size); @@ -1593,8 +1584,7 @@ int BackendImpl::NewEntry(Addr address, scoped_refptr<EntryImpl>* entry) { return ERR_INVALID_ADDRESS; } - scoped_refptr<EntryImpl> cache_entry( - new EntryImpl(this, address, read_only_)); + auto cache_entry = base::MakeRefCounted<EntryImpl>(this, address, read_only_); IncreaseNumRefs(); *entry = nullptr; @@ -1878,14 +1868,14 @@ void BackendImpl::LogStats() { StatsItems stats; GetStats(&stats); - for (size_t index = 0; index < stats.size(); index++) - VLOG(1) << stats[index].first << ": " << stats[index].second; + for (const auto& stat : stats) + VLOG(1) << stat.first << ": " << stat.second; } void BackendImpl::ReportStats() { CACHE_UMA(COUNTS, "Entries", 0, data_->header.num_entries); - int current_size = data_->header.num_bytes / (1024 * 1024); + int64_t current_size = data_->header.num_bytes / (1024 * 1024); int max_size = max_size_ / (1024 * 1024); int hit_ratio_as_percentage = stats_.GetHitRatio(); @@ -1958,7 +1948,7 @@ void BackendImpl::ReportStats() { int64_t trim_rate = stats_.GetCounter(Stats::TRIM_ENTRY) / use_hours; CACHE_UMA(COUNTS, "TrimRate", 0, static_cast<int>(trim_rate)); - int avg_size = data_->header.num_bytes / GetEntryCount(); + int64_t avg_size = data_->header.num_bytes / GetEntryCount(); CACHE_UMA(COUNTS, "EntrySize", 0, avg_size); CACHE_UMA(COUNTS, "EntriesFull", 0, data_->header.num_entries); @@ -1988,11 +1978,19 @@ void BackendImpl::ReportStats() { void BackendImpl::UpgradeTo2_1() { // 2.1 is basically the same as 2.0, except that new fields are actually // updated by the new eviction algorithm. - DCHECK(0x20000 == data_->header.version); - data_->header.version = 0x20001; + DCHECK_EQ(kVersion2_0, data_->header.version); + data_->header.version = kVersion2_1; data_->header.lru.sizes[Rankings::NO_USE] = data_->header.num_entries; } +void BackendImpl::UpgradeTo3_0() { + // 3.0 uses a 64-bit size field. + DCHECK(kVersion2_0 == data_->header.version || + kVersion2_1 == data_->header.version); + data_->header.version = kVersion3_0; + data_->header.num_bytes = data_->header.old_v2_num_bytes; +} + bool BackendImpl::CheckIndex() { DCHECK(data_); @@ -2002,23 +2000,25 @@ bool BackendImpl::CheckIndex() { return false; } - if (new_eviction_) { - // We support versions 2.0 and 2.1, upgrading 2.0 to 2.1. - if (kIndexMagic != data_->header.magic || - kCurrentVersion >> 16 != data_->header.version >> 16) { - LOG(ERROR) << "Invalid file version or magic"; - return false; - } - if (kCurrentVersion == data_->header.version) { - // We need file version 2.1 for the new eviction algorithm. - UpgradeTo2_1(); - } - } else { - if (kIndexMagic != data_->header.magic || - kCurrentVersion != data_->header.version) { - LOG(ERROR) << "Invalid file version or magic"; - return false; - } + if (data_->header.magic != kIndexMagic) { + LOG(ERROR) << "Invalid file magic"; + return false; + } + + // 2.0 + new_eviction needs conversion to 2.1. + if (data_->header.version == kVersion2_0 && new_eviction_) { + UpgradeTo2_1(); + } + + // 2.0 or 2.1 can be upgraded to 3.0 + if (data_->header.version == kVersion2_0 || + data_->header.version == kVersion2_1) { + UpgradeTo3_0(); + } + + if (kCurrentVersion != data_->header.version) { + LOG(ERROR) << "Invalid file version"; + return false; } if (!data_->header.table_len) { @@ -2111,18 +2111,17 @@ bool BackendImpl::CheckEntry(EntryImpl* cache_entry) { } int BackendImpl::MaxBuffersSize() { - static int64_t total_memory = base::SysInfo::AmountOfPhysicalMemory(); + static uint64_t total_memory = base::SysInfo::AmountOfPhysicalMemory(); static bool done = false; if (!done) { - const int kMaxBuffersSize = 30 * 1024 * 1024; + done = true; - // We want to use up to 2% of the computer's memory. + // We want to use up to 2% of the computer's memory, limit 30 MB. total_memory = total_memory * 2 / 100; - if (total_memory > kMaxBuffersSize || total_memory <= 0) + constexpr uint64_t kMaxBuffersSize = 30 * 1024 * 1024; + if (total_memory > kMaxBuffersSize || total_memory == 0) total_memory = kMaxBuffersSize; - - done = true; } return static_cast<int>(total_memory); diff --git a/chromium/net/disk_cache/blockfile/backend_impl.h b/chromium/net/disk_cache/blockfile/backend_impl.h index 30129114e94..7190c3bd8c9 100644 --- a/chromium/net/disk_cache/blockfile/backend_impl.h +++ b/chromium/net/disk_cache/blockfile/backend_impl.h @@ -73,7 +73,8 @@ class NET_EXPORT_PRIVATE BackendImpl : public Backend { ~BackendImpl() override; // Performs general initialization for this current instance of the cache. - net::Error Init(CompletionOnceCallback callback); + // `callback` is always invoked asynchronously. + void Init(CompletionOnceCallback callback); // Performs the actual initialization and final cleanup on destruction. int SyncInit(); @@ -374,9 +375,13 @@ class NET_EXPORT_PRIVATE BackendImpl : public Backend { // Send UMA stats. void ReportStats(); - // Upgrades the index file to version 2.1. + // Upgrades the index file to version 2.1 (from 2.0) void UpgradeTo2_1(); + // Upgrades the index file to version 3.0 + // (from 2.1/2.0 depending on eviction algorithm) + void UpgradeTo3_0(); + // Performs basic checks on the index file. Returns false on failure. bool CheckIndex(); diff --git a/chromium/net/disk_cache/blockfile/bitmap.cc b/chromium/net/disk_cache/blockfile/bitmap.cc index a78dedac206..245d3df33f7 100644 --- a/chromium/net/disk_cache/blockfile/bitmap.cc +++ b/chromium/net/disk_cache/blockfile/bitmap.cc @@ -24,11 +24,13 @@ int FindLSBNonEmpty(uint32_t word, bool value) { namespace disk_cache { +Bitmap::Bitmap() = default; + Bitmap::Bitmap(int num_bits, bool clear_bits) : num_bits_(num_bits), array_size_(RequiredArraySize(num_bits)), - alloc_(true) { - map_ = new uint32_t[array_size_]; + allocated_map_(std::make_unique<uint32_t[]>(array_size_)) { + map_ = allocated_map_.get(); // Initialize all of the bits. if (clear_bits) @@ -36,34 +38,28 @@ Bitmap::Bitmap(int num_bits, bool clear_bits) } Bitmap::Bitmap(uint32_t* map, int num_bits, int num_words) - : map_(map), - num_bits_(num_bits), + : num_bits_(num_bits), // If size is larger than necessary, trim because array_size_ is used // as a bound by various methods. array_size_(std::min(RequiredArraySize(num_bits), num_words)), - alloc_(false) {} + map_(map) {} -Bitmap::~Bitmap() { - if (alloc_) - delete [] map_; -} +Bitmap::~Bitmap() = default; void Bitmap::Resize(int num_bits, bool clear_bits) { - DCHECK(alloc_ || !map_); + DCHECK(allocated_map_ || !map_); const int old_maxsize = num_bits_; const int old_array_size = array_size_; array_size_ = RequiredArraySize(num_bits); if (array_size_ != old_array_size) { - uint32_t* new_map = new uint32_t[array_size_]; + auto new_map = std::make_unique<uint32_t[]>(array_size_); // Always clear the unused bits in the last word. new_map[array_size_ - 1] = 0; - memcpy(new_map, map_, + memcpy(new_map.get(), map_, sizeof(*map_) * std::min(array_size_, old_array_size)); - if (alloc_) - delete[] map_; // No need to check for NULL. - map_ = new_map; - alloc_ = true; + allocated_map_ = std::move(new_map); + map_ = allocated_map_.get(); } num_bits_ = num_bits; diff --git a/chromium/net/disk_cache/blockfile/bitmap.h b/chromium/net/disk_cache/blockfile/bitmap.h index 71c5a4f9d75..9ffa98b9864 100644 --- a/chromium/net/disk_cache/blockfile/bitmap.h +++ b/chromium/net/disk_cache/blockfile/bitmap.h @@ -8,6 +8,8 @@ #include <stdint.h> #include <string.h> +#include <memory> + #include "base/memory/raw_ptr.h" #include "net/base/net_export.h" @@ -16,7 +18,7 @@ namespace disk_cache { // This class provides support for simple maps of bits. class NET_EXPORT_PRIVATE Bitmap { public: - Bitmap() : map_(nullptr), num_bits_(0), array_size_(0), alloc_(false) {} + Bitmap(); // This constructor will allocate on a uint32_t boundary. If |clear_bits| is // false, the bitmap bits will not be initialized. @@ -129,10 +131,10 @@ class NET_EXPORT_PRIVATE Bitmap { // stored in the same word, and len < kIntBits. void SetWordBits(int start, int len, bool value); - raw_ptr<uint32_t> map_; // The bitmap. - int num_bits_; // The upper bound of the bitmap. - int array_size_; // The physical size (in uint32s) of the bitmap. - bool alloc_; // Whether or not we allocated the memory. + int num_bits_ = 0; // The upper bound of the bitmap. + int array_size_ = 0; // The physical size (in uint32s) of the bitmap. + std::unique_ptr<uint32_t[]> allocated_map_; // The allocated data. + raw_ptr<uint32_t> map_ = nullptr; // The bitmap. }; } // namespace disk_cache diff --git a/chromium/net/disk_cache/blockfile/block_files.cc b/chromium/net/disk_cache/blockfile/block_files.cc index 0297e67e3ed..afb9a5f95b2 100644 --- a/chromium/net/disk_cache/blockfile/block_files.cc +++ b/chromium/net/disk_cache/blockfile/block_files.cc @@ -394,8 +394,8 @@ bool BlockFiles::IsValid(Addr address) { static bool read_contents = false; if (read_contents) { - std::unique_ptr<char[]> buffer; - buffer.reset(new char[Addr::BlockSizeForFileType(BLOCK_4K) * 4]); + auto buffer = + std::make_unique<char[]>(Addr::BlockSizeForFileType(BLOCK_4K) * 4); size_t size = address.BlockSize() * address.num_blocks(); size_t offset = address.start_block() * address.BlockSize() + kBlockHeaderSize; @@ -412,7 +412,7 @@ bool BlockFiles::CreateBlockFile(int index, FileType file_type, bool force) { int flags = force ? base::File::FLAG_CREATE_ALWAYS : base::File::FLAG_CREATE; flags |= base::File::FLAG_WRITE | base::File::FLAG_WIN_EXCLUSIVE_WRITE; - scoped_refptr<File> file(new File(base::File(name, flags))); + auto file = base::MakeRefCounted<File>(base::File(name, flags)); if (!file->IsValid()) return false; @@ -435,7 +435,7 @@ bool BlockFiles::OpenBlockFile(int index) { } base::FilePath name = Name(index); - scoped_refptr<MappedFile> file(new MappedFile()); + auto file = base::MakeRefCounted<MappedFile>(); if (!file->Init(name, kBlockHeaderSize)) { LOG(ERROR) << "Failed to open " << name.value(); @@ -593,7 +593,7 @@ bool BlockFiles::RemoveEmptyFile(FileType block_type) { // We get a new handle to the file and release the old one so that the // file gets unmmaped... so we can delete it. base::FilePath name = Name(file_index); - scoped_refptr<File> this_file(new File(false)); + auto this_file = base::MakeRefCounted<File>(false); this_file->Init(name); block_files_[file_index] = nullptr; diff --git a/chromium/net/disk_cache/blockfile/block_files_unittest.cc b/chromium/net/disk_cache/blockfile/block_files_unittest.cc index f674383381a..a2168ea9c86 100644 --- a/chromium/net/disk_cache/blockfile/block_files_unittest.cc +++ b/chromium/net/disk_cache/blockfile/block_files_unittest.cc @@ -47,8 +47,8 @@ TEST_F(DiskCacheTest, MAYBE_BlockFiles_Grow) { Addr address[kMaxSize]; // Fill up the 32-byte block file (use three files). - for (int i = 0; i < kMaxSize; i++) { - EXPECT_TRUE(files.CreateBlock(RANKINGS, 4, &address[i])); + for (auto& addr : address) { + EXPECT_TRUE(files.CreateBlock(RANKINGS, 4, &addr)); } EXPECT_EQ(6, NumberOfFiles(cache_path_)); @@ -73,13 +73,13 @@ TEST_F(DiskCacheTest, BlockFiles_Shrink) { Addr address[kMaxSize]; // Fill up the 32-byte block file (use three files). - for (int i = 0; i < kMaxSize; i++) { - EXPECT_TRUE(files.CreateBlock(RANKINGS, 4, &address[i])); + for (auto& addr : address) { + EXPECT_TRUE(files.CreateBlock(RANKINGS, 4, &addr)); } // Now delete all the blocks, so that we can delete the two extra files. - for (int i = 0; i < kMaxSize; i++) { - files.DeleteBlock(address[i], false); + for (const auto& addr : address) { + files.DeleteBlock(addr, false); } EXPECT_EQ(4, NumberOfFiles(cache_path_)); } @@ -97,11 +97,11 @@ TEST_F(DiskCacheTest, BlockFiles_Recover) { int seed = static_cast<int>(Time::Now().ToInternalValue()); srand(seed); - for (int i = 0; i < kNumEntries; i++) { + for (auto& entry : entries) { Addr address(0); int size = (rand() % 4) + 1; EXPECT_TRUE(files.CreateBlock(RANKINGS, size, &address)); - entries[i] = address.value(); + entry = address.value(); } for (int i = 0; i < kNumEntries; i++) { @@ -173,7 +173,7 @@ TEST_F(DiskCacheTest, BlockFiles_ZeroSizeFile) { files.CloseFiles(); // Truncate one of the files. { - scoped_refptr<File> file(new File); + auto file = base::MakeRefCounted<File>(); ASSERT_TRUE(file->Init(filename)); EXPECT_TRUE(file->SetLength(0)); } @@ -196,7 +196,7 @@ TEST_F(DiskCacheTest, BlockFiles_TruncatedFile) { files.CloseFiles(); // Truncate one of the files. { - scoped_refptr<File> file(new File); + auto file = base::MakeRefCounted<File>(); ASSERT_TRUE(file->Init(filename)); EXPECT_TRUE(file->SetLength(15000)); } diff --git a/chromium/net/disk_cache/blockfile/disk_format.cc b/chromium/net/disk_cache/blockfile/disk_format.cc index 4d398c28aa6..475c57f2cc4 100644 --- a/chromium/net/disk_cache/blockfile/disk_format.cc +++ b/chromium/net/disk_cache/blockfile/disk_format.cc @@ -6,6 +6,8 @@ namespace disk_cache { +static_assert(sizeof(IndexHeader) == 368); + IndexHeader::IndexHeader() { memset(this, 0, sizeof(*this)); magic = kIndexMagic; diff --git a/chromium/net/disk_cache/blockfile/disk_format.h b/chromium/net/disk_cache/blockfile/disk_format.h index a621ec17c56..94786f05279 100644 --- a/chromium/net/disk_cache/blockfile/disk_format.h +++ b/chromium/net/disk_cache/blockfile/disk_format.h @@ -56,7 +56,10 @@ namespace disk_cache { const int kIndexTablesize = 0x10000; const uint32_t kIndexMagic = 0xC103CAC3; -const uint32_t kCurrentVersion = 0x20000; // Version 2.0. +const uint32_t kVersion2_0 = 0x20000; +const uint32_t kVersion2_1 = 0x20001; +const uint32_t kVersion3_0 = 0x30000; +const uint32_t kCurrentVersion = kVersion3_0; struct LruData { int32_t pad1[2]; @@ -77,7 +80,7 @@ struct NET_EXPORT_PRIVATE IndexHeader { uint32_t magic; uint32_t version; int32_t num_entries; // Number of entries currently stored. - int32_t num_bytes; // Total size of the stored data. + int32_t old_v2_num_bytes; // Total size of the stored data, in versions 2.x int32_t last_file; // Last external file created. int32_t this_id; // Id for all entries being changed (dirty flag). CacheAddr stats; // Storage for usage data. @@ -85,7 +88,8 @@ struct NET_EXPORT_PRIVATE IndexHeader { int32_t crash; // Signals a previous crash. int32_t experiment; // Id of an ongoing test. uint64_t create_time; // Creation time for this set of files. - int32_t pad[52]; + int64_t num_bytes; // Total size of the stored data, in version 3.0 + int32_t pad[50]; LruData lru; // Eviction control data. }; diff --git a/chromium/net/disk_cache/blockfile/entry_impl.cc b/chromium/net/disk_cache/blockfile/entry_impl.cc index 01859badd06..019c3aacd8f 100644 --- a/chromium/net/disk_cache/blockfile/entry_impl.cc +++ b/chromium/net/disk_cache/blockfile/entry_impl.cc @@ -319,9 +319,6 @@ EntryImpl::EntryImpl(BackendImpl* backend, Addr address, bool read_only) backend_(backend->GetWeakPtr()), read_only_(read_only) { entry_.LazyInit(backend->File(address), address); - for (int i = 0; i < kNumStreams; i++) { - unreported_size_[i] = 0; - } } void EntryImpl::DoomImpl() { @@ -1307,7 +1304,7 @@ File* EntryImpl::GetExternalFile(Addr address, int index) { DCHECK(index >= 0 && index <= kKeyFileIndex); if (!files_[index].get()) { // For a key file, use mixed mode IO. - scoped_refptr<File> file(new File(kKeyFileIndex == index)); + auto file = base::MakeRefCounted<File>(kKeyFileIndex == index); if (file->Init(backend_->GetFileName(address))) files_[index].swap(file); } @@ -1563,7 +1560,7 @@ int EntryImpl::InitSparseData() { return net::OK; // Use a local variable so that sparse_ never goes from 'valid' to NULL. - std::unique_ptr<SparseControl> sparse(new SparseControl(this)); + auto sparse = std::make_unique<SparseControl>(this); int result = sparse->Init(); if (net::OK == result) sparse_.swap(sparse); @@ -1580,7 +1577,9 @@ uint32_t EntryImpl::GetEntryFlags() { return entry_.Data()->flags; } -void EntryImpl::GetData(int index, char** buffer, Addr* address) { +void EntryImpl::GetData(int index, + std::unique_ptr<char[]>* buffer, + Addr* address) { DCHECK(backend_.get()); if (user_buffers_[index].get() && user_buffers_[index]->Size() && !user_buffers_[index]->Start()) { @@ -1588,8 +1587,8 @@ void EntryImpl::GetData(int index, char** buffer, Addr* address) { int data_len = entry_.Data()->data_size[index]; if (data_len <= user_buffers_[index]->Size()) { DCHECK(!user_buffers_[index]->Start()); - *buffer = new char[data_len]; - memcpy(*buffer, user_buffers_[index]->Data(), data_len); + *buffer = std::make_unique<char[]>(data_len); + memcpy(buffer->get(), user_buffers_[index]->Data(), data_len); return; } } diff --git a/chromium/net/disk_cache/blockfile/entry_impl.h b/chromium/net/disk_cache/blockfile/entry_impl.h index b758719b7f6..40ad359c067 100644 --- a/chromium/net/disk_cache/blockfile/entry_impl.h +++ b/chromium/net/disk_cache/blockfile/entry_impl.h @@ -291,7 +291,7 @@ class NET_EXPORT_PRIVATE EntryImpl // responsible for deleting the block (or file) from the backing store at some // point; there is no need to report any storage-size change, only to do the // actual cleanup. - void GetData(int index, char** buffer, Addr* address); + void GetData(int index, std::unique_ptr<char[]>* buffer, Addr* address); // |net_log_| should be early since some field destructors (at least // ~SparseControl) can touch it. @@ -304,7 +304,8 @@ class NET_EXPORT_PRIVATE EntryImpl // Files to store external user data and key. scoped_refptr<File> files_[kNumStreams + 1]; mutable std::string key_; // Copy of the key. - int unreported_size_[kNumStreams]; // Bytes not reported yet to the backend. + // Bytes not reported yet to the backend. + int unreported_size_[kNumStreams] = {}; bool doomed_ = false; // True if this entry was removed from the cache. bool read_only_; // True if not yet writing. bool dirty_ = false; // True if we detected that this is a dirty entry. diff --git a/chromium/net/disk_cache/blockfile/file.h b/chromium/net/disk_cache/blockfile/file.h index 6e02091d473..94b16d4acf2 100644 --- a/chromium/net/disk_cache/blockfile/file.h +++ b/chromium/net/disk_cache/blockfile/file.h @@ -27,7 +27,7 @@ class FileIOCallback { virtual void OnFileIOComplete(int bytes_copied) = 0; protected: - virtual ~FileIOCallback() {} + virtual ~FileIOCallback() = default; }; // Simple wrapper around a file that allows asynchronous operations. diff --git a/chromium/net/disk_cache/blockfile/file_block.h b/chromium/net/disk_cache/blockfile/file_block.h index 4250dd1b492..cf9e4f793ca 100644 --- a/chromium/net/disk_cache/blockfile/file_block.h +++ b/chromium/net/disk_cache/blockfile/file_block.h @@ -16,7 +16,7 @@ namespace disk_cache { // Used to simplify loading / storing the block from disk. class FileBlock { public: - virtual ~FileBlock() {} + virtual ~FileBlock() = default; // Returns a pointer to the actual data. virtual void* buffer() const = 0; diff --git a/chromium/net/disk_cache/blockfile/file_ios.cc b/chromium/net/disk_cache/blockfile/file_ios.cc index c325d17a278..c910da3c82f 100644 --- a/chromium/net/disk_cache/blockfile/file_ios.cc +++ b/chromium/net/disk_cache/blockfile/file_ios.cc @@ -70,12 +70,12 @@ class FileBackgroundIO : public disk_cache::BackgroundIO { // The specialized controller that keeps track of current operations. class FileInFlightIO : public disk_cache::InFlightIO { public: - FileInFlightIO() {} + FileInFlightIO() = default; FileInFlightIO(const FileInFlightIO&) = delete; FileInFlightIO& operator=(const FileInFlightIO&) = delete; - ~FileInFlightIO() override {} + ~FileInFlightIO() override = default; // These methods start an asynchronous operation. The arguments have the same // semantics of the File asynchronous operations, with the exception that the @@ -118,8 +118,8 @@ void FileBackgroundIO::Write() { void FileInFlightIO::PostRead(disk_cache::File *file, void* buf, size_t buf_len, size_t offset, disk_cache::FileIOCallback *callback) { - scoped_refptr<FileBackgroundIO> operation( - new FileBackgroundIO(file, buf, buf_len, offset, callback, this)); + auto operation = base::MakeRefCounted<FileBackgroundIO>( + file, buf, buf_len, offset, callback, this); file->AddRef(); // Balanced on OnOperationComplete() base::ThreadPool::PostTask( @@ -132,8 +132,8 @@ void FileInFlightIO::PostRead(disk_cache::File *file, void* buf, size_t buf_len, void FileInFlightIO::PostWrite(disk_cache::File* file, const void* buf, size_t buf_len, size_t offset, disk_cache::FileIOCallback* callback) { - scoped_refptr<FileBackgroundIO> operation( - new FileBackgroundIO(file, buf, buf_len, offset, callback, this)); + auto operation = base::MakeRefCounted<FileBackgroundIO>( + file, buf, buf_len, offset, callback, this); file->AddRef(); // Balanced on OnOperationComplete() base::ThreadPool::PostTask( @@ -157,7 +157,7 @@ void FileInFlightIO::OnOperationComplete(disk_cache::BackgroundIO* operation, } // A static object that will broker all async operations. -FileInFlightIO* s_file_operations = NULL; +FileInFlightIO* s_file_operations = nullptr; // Returns the current FileInFlightIO. FileInFlightIO* GetFileInFlightIO() { @@ -171,7 +171,7 @@ FileInFlightIO* GetFileInFlightIO() { void DeleteFileInFlightIO() { DCHECK(s_file_operations); delete s_file_operations; - s_file_operations = NULL; + s_file_operations = nullptr; } } // namespace @@ -285,8 +285,7 @@ void File::DropPendingIO() { DeleteFileInFlightIO(); } -File::~File() { -} +File::~File() = default; base::PlatformFile File::platform_file() const { return base_file_.GetPlatformFile(); diff --git a/chromium/net/disk_cache/blockfile/file_win.cc b/chromium/net/disk_cache/blockfile/file_win.cc index 6f5724d8c24..61c98814383 100644 --- a/chromium/net/disk_cache/blockfile/file_win.cc +++ b/chromium/net/disk_cache/blockfile/file_win.cc @@ -63,7 +63,8 @@ class CompletionHandler : public base::MessagePumpForIO::IOHandler, class CompletionHandlerHolder { public: - CompletionHandlerHolder() { completion_handler_ = new CompletionHandler; } + CompletionHandlerHolder() + : completion_handler_(base::MakeRefCounted<CompletionHandler>()) {} CompletionHandler* completion_handler() { return completion_handler_.get(); } @@ -215,8 +216,7 @@ bool File::Write(const void* buffer, size_t buffer_len, size_t offset, return AsyncWrite(buffer, buffer_len, offset, callback, completed); } -File::~File() { -} +File::~File() = default; base::PlatformFile File::platform_file() const { DCHECK(init_); diff --git a/chromium/net/disk_cache/blockfile/in_flight_backend_io.cc b/chromium/net/disk_cache/blockfile/in_flight_backend_io.cc index 0f18911f4f2..98bb1ec43ae 100644 --- a/chromium/net/disk_cache/blockfile/in_flight_backend_io.cc +++ b/chromium/net/disk_cache/blockfile/in_flight_backend_io.cc @@ -86,7 +86,7 @@ void BackendIO::OnDone(bool cancel) { if (ReturnsEntry() && result_ == net::OK) { static_cast<EntryImpl*>(out_entry_)->OnEntryCreated(backend_); if (cancel) - out_entry_->Close(); + out_entry_.ExtractAsDangling()->Close(); } } @@ -319,6 +319,9 @@ void BackendIO::ExecuteBackendOperation() { result_ = backend_->SyncOpenNextEntry(iterator_, &entry); out_entry_ = LeakEntryImpl(std::move(entry)); out_entry_opened_ = true; + // `iterator_` is a proxied argument and not needed beyond this point. Set + // it to nullptr so as to not leave a dangling pointer around. + iterator_ = nullptr; break; } case OP_END_ENUMERATION: @@ -407,47 +410,47 @@ InFlightBackendIO::InFlightBackendIO( InFlightBackendIO::~InFlightBackendIO() = default; void InFlightBackendIO::Init(net::CompletionOnceCallback callback) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, std::move(callback))); + auto operation = + base::MakeRefCounted<BackendIO>(this, backend_, std::move(callback)); operation->Init(); PostOperation(FROM_HERE, operation.get()); } void InFlightBackendIO::OpenOrCreateEntry(const std::string& key, EntryResultCallback callback) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, std::move(callback))); + auto operation = + base::MakeRefCounted<BackendIO>(this, backend_, std::move(callback)); operation->OpenOrCreateEntry(key); PostOperation(FROM_HERE, operation.get()); } void InFlightBackendIO::OpenEntry(const std::string& key, EntryResultCallback callback) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, std::move(callback))); + auto operation = + base::MakeRefCounted<BackendIO>(this, backend_, std::move(callback)); operation->OpenEntry(key); PostOperation(FROM_HERE, operation.get()); } void InFlightBackendIO::CreateEntry(const std::string& key, EntryResultCallback callback) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, std::move(callback))); + auto operation = + base::MakeRefCounted<BackendIO>(this, backend_, std::move(callback)); operation->CreateEntry(key); PostOperation(FROM_HERE, operation.get()); } void InFlightBackendIO::DoomEntry(const std::string& key, net::CompletionOnceCallback callback) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, std::move(callback))); + auto operation = + base::MakeRefCounted<BackendIO>(this, backend_, std::move(callback)); operation->DoomEntry(key); PostOperation(FROM_HERE, operation.get()); } void InFlightBackendIO::DoomAllEntries(net::CompletionOnceCallback callback) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, std::move(callback))); + auto operation = + base::MakeRefCounted<BackendIO>(this, backend_, std::move(callback)); operation->DoomAllEntries(); PostOperation(FROM_HERE, operation.get()); } @@ -456,76 +459,76 @@ void InFlightBackendIO::DoomEntriesBetween( const base::Time initial_time, const base::Time end_time, net::CompletionOnceCallback callback) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, std::move(callback))); + auto operation = + base::MakeRefCounted<BackendIO>(this, backend_, std::move(callback)); operation->DoomEntriesBetween(initial_time, end_time); PostOperation(FROM_HERE, operation.get()); } void InFlightBackendIO::CalculateSizeOfAllEntries( net::CompletionOnceCallback callback) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, std::move(callback))); + auto operation = + base::MakeRefCounted<BackendIO>(this, backend_, std::move(callback)); operation->CalculateSizeOfAllEntries(); PostOperation(FROM_HERE, operation.get()); } void InFlightBackendIO::DoomEntriesSince(const base::Time initial_time, net::CompletionOnceCallback callback) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, std::move(callback))); + auto operation = + base::MakeRefCounted<BackendIO>(this, backend_, std::move(callback)); operation->DoomEntriesSince(initial_time); PostOperation(FROM_HERE, operation.get()); } void InFlightBackendIO::OpenNextEntry(Rankings::Iterator* iterator, EntryResultCallback callback) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, std::move(callback))); + auto operation = + base::MakeRefCounted<BackendIO>(this, backend_, std::move(callback)); operation->OpenNextEntry(iterator); PostOperation(FROM_HERE, operation.get()); } void InFlightBackendIO::EndEnumeration( std::unique_ptr<Rankings::Iterator> iterator) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, net::CompletionOnceCallback())); + auto operation = base::MakeRefCounted<BackendIO>( + this, backend_, net::CompletionOnceCallback()); operation->EndEnumeration(std::move(iterator)); PostOperation(FROM_HERE, operation.get()); } void InFlightBackendIO::OnExternalCacheHit(const std::string& key) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, net::CompletionOnceCallback())); + auto operation = base::MakeRefCounted<BackendIO>( + this, backend_, net::CompletionOnceCallback()); operation->OnExternalCacheHit(key); PostOperation(FROM_HERE, operation.get()); } void InFlightBackendIO::CloseEntryImpl(EntryImpl* entry) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, net::CompletionOnceCallback())); + auto operation = base::MakeRefCounted<BackendIO>( + this, backend_, net::CompletionOnceCallback()); operation->CloseEntryImpl(entry); PostOperation(FROM_HERE, operation.get()); } void InFlightBackendIO::DoomEntryImpl(EntryImpl* entry) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, net::CompletionOnceCallback())); + auto operation = base::MakeRefCounted<BackendIO>( + this, backend_, net::CompletionOnceCallback()); operation->DoomEntryImpl(entry); PostOperation(FROM_HERE, operation.get()); } void InFlightBackendIO::FlushQueue(net::CompletionOnceCallback callback) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, std::move(callback))); + auto operation = + base::MakeRefCounted<BackendIO>(this, backend_, std::move(callback)); operation->FlushQueue(); PostOperation(FROM_HERE, operation.get()); } void InFlightBackendIO::RunTask(base::OnceClosure task, net::CompletionOnceCallback callback) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, std::move(callback))); + auto operation = + base::MakeRefCounted<BackendIO>(this, backend_, std::move(callback)); operation->RunTask(std::move(task)); PostOperation(FROM_HERE, operation.get()); } @@ -536,8 +539,8 @@ void InFlightBackendIO::ReadData(EntryImpl* entry, net::IOBuffer* buf, int buf_len, net::CompletionOnceCallback callback) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, std::move(callback))); + auto operation = + base::MakeRefCounted<BackendIO>(this, backend_, std::move(callback)); operation->ReadData(entry, index, offset, buf, buf_len); PostOperation(FROM_HERE, operation.get()); } @@ -549,8 +552,8 @@ void InFlightBackendIO::WriteData(EntryImpl* entry, int buf_len, bool truncate, net::CompletionOnceCallback callback) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, std::move(callback))); + auto operation = + base::MakeRefCounted<BackendIO>(this, backend_, std::move(callback)); operation->WriteData(entry, index, offset, buf, buf_len, truncate); PostOperation(FROM_HERE, operation.get()); } @@ -560,8 +563,8 @@ void InFlightBackendIO::ReadSparseData(EntryImpl* entry, net::IOBuffer* buf, int buf_len, net::CompletionOnceCallback callback) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, std::move(callback))); + auto operation = + base::MakeRefCounted<BackendIO>(this, backend_, std::move(callback)); operation->ReadSparseData(entry, offset, buf, buf_len); PostOperation(FROM_HERE, operation.get()); } @@ -571,8 +574,8 @@ void InFlightBackendIO::WriteSparseData(EntryImpl* entry, net::IOBuffer* buf, int buf_len, net::CompletionOnceCallback callback) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, std::move(callback))); + auto operation = + base::MakeRefCounted<BackendIO>(this, backend_, std::move(callback)); operation->WriteSparseData(entry, offset, buf, buf_len); PostOperation(FROM_HERE, operation.get()); } @@ -581,23 +584,23 @@ void InFlightBackendIO::GetAvailableRange(EntryImpl* entry, int64_t offset, int len, RangeResultCallback callback) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, std::move(callback))); + auto operation = + base::MakeRefCounted<BackendIO>(this, backend_, std::move(callback)); operation->GetAvailableRange(entry, offset, len); PostOperation(FROM_HERE, operation.get()); } void InFlightBackendIO::CancelSparseIO(EntryImpl* entry) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, net::CompletionOnceCallback())); + auto operation = base::MakeRefCounted<BackendIO>( + this, backend_, net::CompletionOnceCallback()); operation->CancelSparseIO(entry); PostOperation(FROM_HERE, operation.get()); } void InFlightBackendIO::ReadyForSparseIO(EntryImpl* entry, net::CompletionOnceCallback callback) { - scoped_refptr<BackendIO> operation( - new BackendIO(this, backend_, std::move(callback))); + auto operation = + base::MakeRefCounted<BackendIO>(this, backend_, std::move(callback)); operation->ReadyForSparseIO(entry); PostOperation(FROM_HERE, operation.get()); } diff --git a/chromium/net/disk_cache/blockfile/in_flight_backend_io.h b/chromium/net/disk_cache/blockfile/in_flight_backend_io.h index 7c67dc98031..180f3ef8289 100644 --- a/chromium/net/disk_cache/blockfile/in_flight_backend_io.h +++ b/chromium/net/disk_cache/blockfile/in_flight_backend_io.h @@ -154,7 +154,7 @@ class BackendIO : public BackgroundIO { void ExecuteBackendOperation(); void ExecuteEntryOperation(); - raw_ptr<BackendImpl> backend_; + raw_ptr<BackendImpl, DanglingUntriaged> backend_; net::CompletionOnceCallback callback_; Operation operation_ = OP_NONE; diff --git a/chromium/net/disk_cache/blockfile/in_flight_io.h b/chromium/net/disk_cache/blockfile/in_flight_io.h index 320775a3948..cc83583d340 100644 --- a/chromium/net/disk_cache/blockfile/in_flight_io.h +++ b/chromium/net/disk_cache/blockfile/in_flight_io.h @@ -68,7 +68,7 @@ class BackgroundIO : public base::RefCountedThreadSafe<BackgroundIO> { // An event to signal when the operation completes. base::WaitableEvent io_completed_; - raw_ptr<InFlightIO> + raw_ptr<InFlightIO, DanglingUntriaged> controller_; // The controller that tracks all operations. base::Lock controller_lock_; // A lock protecting clearing of controller_. }; diff --git a/chromium/net/disk_cache/blockfile/mapped_file.cc b/chromium/net/disk_cache/blockfile/mapped_file.cc index b2fedd2c787..7cac41e5d48 100644 --- a/chromium/net/disk_cache/blockfile/mapped_file.cc +++ b/chromium/net/disk_cache/blockfile/mapped_file.cc @@ -23,7 +23,7 @@ bool MappedFile::Store(const FileBlock* block) { bool MappedFile::Preload() { size_t file_len = GetLength(); - std::unique_ptr<char[]> buf(new char[file_len]); + auto buf = std::make_unique<char[]>(file_len); if (!Read(buf.get(), file_len, 0)) return false; return true; diff --git a/chromium/net/disk_cache/blockfile/mapped_file_posix.cc b/chromium/net/disk_cache/blockfile/mapped_file_posix.cc index 7921ffdf40f..bc94afc7d80 100644 --- a/chromium/net/disk_cache/blockfile/mapped_file_posix.cc +++ b/chromium/net/disk_cache/blockfile/mapped_file_posix.cc @@ -31,7 +31,7 @@ void* MappedFile::Init(const base::FilePath& name, size_t size) { buffer_ = nullptr; // Make sure we detect hardware failures reading the headers. - std::unique_ptr<char[]> temp(new char[temp_len]); + auto temp = std::make_unique<char[]>(temp_len); if (!Read(temp.get(), temp_len, 0)) return nullptr; diff --git a/chromium/net/disk_cache/blockfile/mapped_file_unittest.cc b/chromium/net/disk_cache/blockfile/mapped_file_unittest.cc index b9147fd0e89..d8bfb6eca48 100644 --- a/chromium/net/disk_cache/blockfile/mapped_file_unittest.cc +++ b/chromium/net/disk_cache/blockfile/mapped_file_unittest.cc @@ -44,7 +44,7 @@ void FileCallbackTest::OnFileIOComplete(int bytes_copied) { TEST_F(DiskCacheTest, MappedFile_SyncIO) { base::FilePath filename = cache_path_.AppendASCII("a_test"); - scoped_refptr<disk_cache::MappedFile> file(new disk_cache::MappedFile); + auto file = base::MakeRefCounted<disk_cache::MappedFile>(); ASSERT_TRUE(CreateCacheTestFile(filename)); ASSERT_TRUE(file->Init(filename, 8192)); @@ -59,7 +59,7 @@ TEST_F(DiskCacheTest, MappedFile_SyncIO) { TEST_F(DiskCacheTest, MappedFile_AsyncIO) { base::FilePath filename = cache_path_.AppendASCII("a_test"); - scoped_refptr<disk_cache::MappedFile> file(new disk_cache::MappedFile); + auto file = base::MakeRefCounted<disk_cache::MappedFile>(); ASSERT_TRUE(CreateCacheTestFile(filename)); ASSERT_TRUE(file->Init(filename, 8192)); diff --git a/chromium/net/disk_cache/blockfile/mapped_file_win.cc b/chromium/net/disk_cache/blockfile/mapped_file_win.cc index 5829dcc4a28..3cc771e4951 100644 --- a/chromium/net/disk_cache/blockfile/mapped_file_win.cc +++ b/chromium/net/disk_cache/blockfile/mapped_file_win.cc @@ -32,7 +32,7 @@ void* MappedFile::Init(const base::FilePath& name, size_t size) { // Make sure we detect hardware failures reading the headers. size_t temp_len = size ? size : 4096; - std::unique_ptr<char[]> temp(new char[temp_len]); + auto temp = std::make_unique<char[]>(temp_len); if (!Read(temp.get(), temp_len, 0)) return nullptr; diff --git a/chromium/net/disk_cache/blockfile/rankings.cc b/chromium/net/disk_cache/blockfile/rankings.cc index 0b8a06875ee..d7bb61fdbf7 100644 --- a/chromium/net/disk_cache/blockfile/rankings.cc +++ b/chromium/net/disk_cache/blockfile/rankings.cc @@ -212,8 +212,9 @@ Rankings::Iterator::Iterator() { void Rankings::Iterator::Reset() { if (my_rankings) { - for (int i = 0; i < 3; i++) - ScopedRankingsBlock(my_rankings, nodes[i]); + for (auto* node : nodes) { + ScopedRankingsBlock(my_rankings, node); + } } memset(this, 0, sizeof(Iterator)); } @@ -875,9 +876,9 @@ bool Rankings::IsTail(CacheAddr addr, List* list) const { // of cache iterators and update all that are pointing to the given node. void Rankings::UpdateIterators(CacheRankingsBlock* node) { CacheAddr address = node->address().value(); - for (auto it = iterators_.begin(); it != iterators_.end(); ++it) { - if (it->first == address && it->second->HasData()) { - CacheRankingsBlock* other = it->second; + for (auto& iterator : iterators_) { + if (iterator.first == address && iterator.second->HasData()) { + CacheRankingsBlock* other = iterator.second; if (other != node) *other->Data() = *node->Data(); } @@ -887,10 +888,10 @@ void Rankings::UpdateIterators(CacheRankingsBlock* node) { void Rankings::UpdateIteratorsForRemoved(CacheAddr address, CacheRankingsBlock* next) { CacheAddr next_addr = next->address().value(); - for (auto it = iterators_.begin(); it != iterators_.end(); ++it) { - if (it->first == address) { - it->first = next_addr; - it->second->CopyFrom(next); + for (auto& iterator : iterators_) { + if (iterator.first == address) { + iterator.first = next_addr; + iterator.second->CopyFrom(next); } } } diff --git a/chromium/net/disk_cache/blockfile/sparse_control.cc b/chromium/net/disk_cache/blockfile/sparse_control.cc index 96cb03cf840..6fe761e39e6 100644 --- a/chromium/net/disk_cache/blockfile/sparse_control.cc +++ b/chromium/net/disk_cache/blockfile/sparse_control.cc @@ -77,7 +77,7 @@ class ChildrenDeleter // Two ways of deleting the children: if we have the children map, use Start() // directly, otherwise pass the data address to ReadData(). - void Start(char* buffer, int len); + void Start(std::unique_ptr<char[]> buffer, int len); void ReadData(disk_cache::Addr address, int len); private: @@ -95,19 +95,18 @@ class ChildrenDeleter // This is the callback of the file operation. void ChildrenDeleter::OnFileIOComplete(int bytes_copied) { - char* buffer = buffer_.release(); - Start(buffer, bytes_copied); + Start(std::move(buffer_), bytes_copied); } -void ChildrenDeleter::Start(char* buffer, int len) { - buffer_.reset(buffer); +void ChildrenDeleter::Start(std::unique_ptr<char[]> buffer, int len) { + buffer_ = std::move(buffer); if (len < static_cast<int>(sizeof(disk_cache::SparseData))) return Release(); // Just copy the information from |buffer|, delete |buffer| and start deleting // the child entries. disk_cache::SparseData* data = - reinterpret_cast<disk_cache::SparseData*>(buffer); + reinterpret_cast<disk_cache::SparseData*>(buffer_.get()); signature_ = data->header.signature; int num_bits = (len - sizeof(disk_cache::SparseHeader)) * 8; @@ -130,7 +129,7 @@ void ChildrenDeleter::ReadData(disk_cache::Addr address, int len) { size_t file_offset = address.start_block() * address.BlockSize() + disk_cache::kBlockHeaderSize; - buffer_.reset(new char[len]); + buffer_ = std::make_unique<char[]>(len); bool completed; if (!file->Read(buffer_.get(), len, file_offset, this, &completed)) return Release(); @@ -375,7 +374,7 @@ void SparseControl::DeleteChildren(EntryImpl* entry) { if (map_len > kMaxMapSize || map_len % 4) return; - char* buffer; + std::unique_ptr<char[]> buffer; Addr address; entry->GetData(kSparseIndex, &buffer, &address); if (!buffer && !address.is_initialized()) @@ -391,8 +390,8 @@ void SparseControl::DeleteChildren(EntryImpl* entry) { if (buffer) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::BindOnce(&ChildrenDeleter::Start, deleter, buffer, data_len)); + FROM_HERE, base::BindOnce(&ChildrenDeleter::Start, deleter, + std::move(buffer), data_len)); } else { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, diff --git a/chromium/net/disk_cache/blockfile/stats.cc b/chromium/net/disk_cache/blockfile/stats.cc index fc867fdc41a..5023bc4a056 100644 --- a/chromium/net/disk_cache/blockfile/stats.cc +++ b/chromium/net/disk_cache/blockfile/stats.cc @@ -139,11 +139,11 @@ void Stats::InitSizeHistogram() { return; first_time = false; - for (int i = 0; i < kDataSizesLength; i++) { + for (int& data_size : data_sizes_) { // This is a good time to fix any inconsistent data. The count should be // always positive, but if it's not, reset the value now. - if (data_sizes_[i] < 0) - data_sizes_[i] = 0; + if (data_size < 0) + data_size = 0; } } diff --git a/chromium/net/disk_cache/blockfile/stats_unittest.cc b/chromium/net/disk_cache/blockfile/stats_unittest.cc index afe31d9f40e..be15cbf93aa 100644 --- a/chromium/net/disk_cache/blockfile/stats_unittest.cc +++ b/chromium/net/disk_cache/blockfile/stats_unittest.cc @@ -17,7 +17,7 @@ TEST(DiskCacheStatsTest, Init) { TEST(DiskCacheStatsTest, InitWithEmptyBuffer) { disk_cache::Stats stats; int required_len = stats.StorageSize(); - std::unique_ptr<char[]> storage(new char[required_len]); + auto storage = std::make_unique<char[]>(required_len); memset(storage.get(), 0, required_len); ASSERT_TRUE(stats.Init(storage.get(), required_len, disk_cache::Addr())); @@ -27,7 +27,7 @@ TEST(DiskCacheStatsTest, InitWithEmptyBuffer) { TEST(DiskCacheStatsTest, FailsInit) { disk_cache::Stats stats; int required_len = stats.StorageSize(); - std::unique_ptr<char[]> storage(new char[required_len]); + auto storage = std::make_unique<char[]>(required_len); memset(storage.get(), 0, required_len); // Try a small buffer. @@ -41,7 +41,7 @@ TEST(DiskCacheStatsTest, FailsInit) { } TEST(DiskCacheStatsTest, SaveRestore) { - std::unique_ptr<disk_cache::Stats> stats(new disk_cache::Stats); + auto stats = std::make_unique<disk_cache::Stats>(); disk_cache::Addr addr(5); ASSERT_TRUE(stats->Init(nullptr, 0, addr)); @@ -52,7 +52,7 @@ TEST(DiskCacheStatsTest, SaveRestore) { stats->OnEvent(disk_cache::Stats::DOOM_RECENT); int required_len = stats->StorageSize(); - std::unique_ptr<char[]> storage(new char[required_len]); + auto storage = std::make_unique<char[]>(required_len); disk_cache::Addr out_addr; int real_len = stats->SerializeStats(storage.get(), required_len, &out_addr); EXPECT_GE(required_len, real_len); diff --git a/chromium/net/disk_cache/blockfile/storage_block.h b/chromium/net/disk_cache/blockfile/storage_block.h index f0bb68c05a9..e367c3bb0fa 100644 --- a/chromium/net/disk_cache/blockfile/storage_block.h +++ b/chromium/net/disk_cache/blockfile/storage_block.h @@ -39,7 +39,7 @@ class StorageBlock : public FileBlock { StorageBlock(const StorageBlock&) = delete; StorageBlock& operator=(const StorageBlock&) = delete; - virtual ~StorageBlock(); + ~StorageBlock() override; // Deeps copies from another block. Neither this nor |other| should be // |modified|. diff --git a/chromium/net/disk_cache/blockfile/storage_block_unittest.cc b/chromium/net/disk_cache/blockfile/storage_block_unittest.cc index 9992edc4d60..7d7c13befaf 100644 --- a/chromium/net/disk_cache/blockfile/storage_block_unittest.cc +++ b/chromium/net/disk_cache/blockfile/storage_block_unittest.cc @@ -14,7 +14,7 @@ typedef disk_cache::StorageBlock<disk_cache::EntryStore> CacheEntryBlock; TEST_F(DiskCacheTest, StorageBlock_LoadStore) { base::FilePath filename = cache_path_.AppendASCII("a_test"); - scoped_refptr<disk_cache::MappedFile> file(new disk_cache::MappedFile); + auto file = base::MakeRefCounted<disk_cache::MappedFile>(); ASSERT_TRUE(CreateCacheTestFile(filename)); ASSERT_TRUE(file->Init(filename, 8192)); @@ -34,7 +34,7 @@ TEST_F(DiskCacheTest, StorageBlock_LoadStore) { TEST_F(DiskCacheTest, StorageBlock_SetData) { base::FilePath filename = cache_path_.AppendASCII("a_test"); - scoped_refptr<disk_cache::MappedFile> file(new disk_cache::MappedFile); + auto file = base::MakeRefCounted<disk_cache::MappedFile>(); ASSERT_TRUE(CreateCacheTestFile(filename)); ASSERT_TRUE(file->Init(filename, 8192)); @@ -54,17 +54,17 @@ TEST_F(DiskCacheTest, StorageBlock_SetData) { TEST_F(DiskCacheTest, StorageBlock_SetModified) { base::FilePath filename = cache_path_.AppendASCII("a_test"); - scoped_refptr<disk_cache::MappedFile> file(new disk_cache::MappedFile); + auto file = base::MakeRefCounted<disk_cache::MappedFile>(); ASSERT_TRUE(CreateCacheTestFile(filename)); ASSERT_TRUE(file->Init(filename, 8192)); - CacheEntryBlock* entry1 = - new CacheEntryBlock(file.get(), disk_cache::Addr(0xa0010003)); + auto entry1 = std::make_unique<CacheEntryBlock>(file.get(), + disk_cache::Addr(0xa0010003)); EXPECT_TRUE(entry1->Load()); EXPECT_TRUE(0 == entry1->Data()->hash); entry1->Data()->hash = 0x45687912; entry1->set_modified(); - delete entry1; + entry1.reset(); CacheEntryBlock entry2(file.get(), disk_cache::Addr(0xa0010003)); EXPECT_TRUE(entry2.Load()); diff --git a/chromium/net/disk_cache/disk_cache.cc b/chromium/net/disk_cache/disk_cache.cc index 6f820bdd079..b31892c1890 100644 --- a/chromium/net/disk_cache/disk_cache.cc +++ b/chromium/net/disk_cache/disk_cache.cc @@ -47,17 +47,20 @@ class CacheCreator { base::android::ApplicationStatusListener* app_status_listener, #endif net::NetLog* net_log, - std::unique_ptr<disk_cache::Backend>* backend, base::OnceClosure post_cleanup_callback, - net::CompletionOnceCallback callback); + disk_cache::BackendResultCallback callback); CacheCreator(const CacheCreator&) = delete; CacheCreator& operator=(const CacheCreator&) = delete; + // Wait for any previous backends for given path to finish clean up and then + // attempt to create a new one. This will never succeed synchronously, though + // it may fail synchronously. net::Error TryCreateCleanupTrackerAndRun(); // Creates the backend, the cleanup context for it having been already - // established... or purposefully left as null. + // established... or purposefully left as null. This will never succeed + // synchronously, though it may fail synchronously. net::Error Run(); private: @@ -80,9 +83,8 @@ class CacheCreator { #if BUILDFLAG(IS_ANDROID) raw_ptr<base::android::ApplicationStatusListener> app_status_listener_; #endif - raw_ptr<std::unique_ptr<disk_cache::Backend>> backend_; base::OnceClosure post_cleanup_callback_; - net::CompletionOnceCallback callback_; + disk_cache::BackendResultCallback callback_; std::unique_ptr<disk_cache::Backend> created_cache_; raw_ptr<net::NetLog> net_log_; scoped_refptr<disk_cache::BackendCleanupTracker> cleanup_tracker_; @@ -99,9 +101,8 @@ CacheCreator::CacheCreator( base::android::ApplicationStatusListener* app_status_listener, #endif net::NetLog* net_log, - std::unique_ptr<disk_cache::Backend>* backend, base::OnceClosure post_cleanup_callback, - net::CompletionOnceCallback callback) + disk_cache::BackendResultCallback callback) : path_(path), reset_handling_(reset_handling), max_bytes_(max_bytes), @@ -111,7 +112,6 @@ CacheCreator::CacheCreator( #if BUILDFLAG(IS_ANDROID) app_status_listener_(app_status_listener), #endif - backend_(backend), post_cleanup_callback_(std::move(post_cleanup_callback)), callback_(std::move(callback)), net_log_(net_log) { @@ -136,32 +136,33 @@ net::Error CacheCreator::Run() { if (backend_type_ == net::CACHE_BACKEND_SIMPLE || (backend_type_ == net::CACHE_BACKEND_DEFAULT && kSimpleBackendIsDefault)) { - disk_cache::SimpleBackendImpl* simple_cache = - new disk_cache::SimpleBackendImpl( - file_operations_factory_, path_, cleanup_tracker_.get(), - /* file_tracker = */ nullptr, max_bytes_, type_, net_log_); - created_cache_.reset(simple_cache); + auto cache = std::make_unique<disk_cache::SimpleBackendImpl>( + file_operations_factory_, path_, cleanup_tracker_.get(), + /* file_tracker = */ nullptr, max_bytes_, type_, net_log_); + disk_cache::SimpleBackendImpl* simple_cache = cache.get(); + created_cache_ = std::move(cache); #if BUILDFLAG(IS_ANDROID) if (app_status_listener_) simple_cache->set_app_status_listener(app_status_listener_); #endif - return simple_cache->Init( + simple_cache->Init( base::BindOnce(&CacheCreator::OnIOComplete, base::Unretained(this))); + return net::ERR_IO_PENDING; } // Avoid references to blockfile functions on Android to reduce binary size. #if BUILDFLAG(IS_ANDROID) return net::ERR_FAILED; #else - disk_cache::BackendImpl* new_cache = - new disk_cache::BackendImpl(path_, cleanup_tracker_.get(), - /*cache_thread = */ nullptr, type_, net_log_); - created_cache_.reset(new_cache); + auto cache = std::make_unique<disk_cache::BackendImpl>( + path_, cleanup_tracker_.get(), + /*cache_thread = */ nullptr, type_, net_log_); + disk_cache::BackendImpl* new_cache = cache.get(); + created_cache_ = std::move(cache); new_cache->SetMaxSize(max_bytes_); - net::Error rv = new_cache->Init( + new_cache->Init( base::BindOnce(&CacheCreator::OnIOComplete, base::Unretained(this))); - DCHECK_EQ(net::ERR_IO_PENDING, rv); - return rv; + return net::ERR_IO_PENDING; #endif } @@ -195,15 +196,18 @@ net::Error CacheCreator::TryCreateCleanupTrackerAndRun() { return Run(); } -void CacheCreator::DoCallback(int result) { - DCHECK_NE(net::ERR_IO_PENDING, result); - if (result == net::OK) { - *backend_ = std::move(created_cache_); +void CacheCreator::DoCallback(int net_error) { + DCHECK_NE(net::ERR_IO_PENDING, net_error); + disk_cache::BackendResult result; + if (net_error == net::OK) { + result = disk_cache::BackendResult::Make(std::move(created_cache_)); } else { LOG(ERROR) << "Unable to create cache"; + result = disk_cache::BackendResult::MakeError( + static_cast<net::Error>(net_error)); created_cache_.reset(); } - std::move(callback_).Run(result); + std::move(callback_).Run(std::move(result)); delete this; } @@ -281,7 +285,29 @@ class UnboundTrivialFileOperations namespace disk_cache { -net::Error CreateCacheBackendImpl( +BackendResult::BackendResult() = default; +BackendResult::~BackendResult() = default; +BackendResult::BackendResult(BackendResult&&) = default; +BackendResult& BackendResult::operator=(BackendResult&&) = default; + +// static +BackendResult BackendResult::MakeError(net::Error error_in) { + DCHECK_NE(error_in, net::OK); + BackendResult result; + result.net_error = error_in; + return result; +} + +// static +BackendResult BackendResult::Make(std::unique_ptr<Backend> backend_in) { + DCHECK(backend_in); + BackendResult result; + result.net_error = net::OK; + result.backend = std::move(backend_in); + return result; +} + +BackendResult CreateCacheBackendImpl( net::CacheType type, net::BackendType backend_type, scoped_refptr<BackendFileOperationsFactory> file_operations, @@ -292,9 +318,8 @@ net::Error CreateCacheBackendImpl( base::android::ApplicationStatusListener* app_status_listener, #endif net::NetLog* net_log, - std::unique_ptr<Backend>* backend, base::OnceClosure post_cleanup_callback, - net::CompletionOnceCallback callback) { + BackendResultCallback callback) { DCHECK(!callback.is_null()); if (type == net::MEMORY_CACHE) { @@ -303,13 +328,12 @@ net::Error CreateCacheBackendImpl( if (mem_backend_impl) { mem_backend_impl->SetPostCleanupCallback( std::move(post_cleanup_callback)); - *backend = std::move(mem_backend_impl); - return net::OK; + return BackendResult::Make(std::move(mem_backend_impl)); } else { if (!post_cleanup_callback.is_null()) base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, std::move(post_cleanup_callback)); - return net::ERR_FAILED; + return BackendResult::MakeError(net::ERR_FAILED); } } @@ -320,16 +344,16 @@ net::Error CreateCacheBackendImpl( #if BUILDFLAG(IS_ANDROID) std::move(app_status_listener), #endif - net_log, backend, std::move(post_cleanup_callback), std::move(callback)); + net_log, std::move(post_cleanup_callback), std::move(callback)); if (type == net::DISK_CACHE) { DCHECK(!had_post_cleanup_callback); - return creator->Run(); + return BackendResult::MakeError(creator->Run()); } - return creator->TryCreateCleanupTrackerAndRun(); + return BackendResult::MakeError(creator->TryCreateCleanupTrackerAndRun()); } -net::Error CreateCacheBackend( +BackendResult CreateCacheBackend( net::CacheType type, net::BackendType backend_type, scoped_refptr<BackendFileOperationsFactory> file_operations, @@ -337,19 +361,18 @@ net::Error CreateCacheBackend( int64_t max_bytes, ResetHandling reset_handling, net::NetLog* net_log, - std::unique_ptr<Backend>* backend, - net::CompletionOnceCallback callback) { + BackendResultCallback callback) { return CreateCacheBackendImpl(type, backend_type, std::move(file_operations), path, max_bytes, reset_handling, #if BUILDFLAG(IS_ANDROID) nullptr, #endif - net_log, backend, base::OnceClosure(), + net_log, base::OnceClosure(), std::move(callback)); } #if BUILDFLAG(IS_ANDROID) -NET_EXPORT net::Error CreateCacheBackend( +NET_EXPORT BackendResult CreateCacheBackend( net::CacheType type, net::BackendType backend_type, scoped_refptr<BackendFileOperationsFactory> file_operations, @@ -357,17 +380,16 @@ NET_EXPORT net::Error CreateCacheBackend( int64_t max_bytes, ResetHandling reset_handling, net::NetLog* net_log, - std::unique_ptr<Backend>* backend, - net::CompletionOnceCallback callback, + BackendResultCallback callback, base::android::ApplicationStatusListener* app_status_listener) { - return CreateCacheBackendImpl( - type, backend_type, std::move(file_operations), path, max_bytes, - reset_handling, std::move(app_status_listener), net_log, backend, - base::OnceClosure(), std::move(callback)); + return CreateCacheBackendImpl(type, backend_type, std::move(file_operations), + path, max_bytes, reset_handling, + std::move(app_status_listener), net_log, + base::OnceClosure(), std::move(callback)); } #endif -net::Error CreateCacheBackend( +BackendResult CreateCacheBackend( net::CacheType type, net::BackendType backend_type, scoped_refptr<BackendFileOperationsFactory> file_operations, @@ -375,16 +397,15 @@ net::Error CreateCacheBackend( int64_t max_bytes, ResetHandling reset_handling, net::NetLog* net_log, - std::unique_ptr<Backend>* backend, base::OnceClosure post_cleanup_callback, - net::CompletionOnceCallback callback) { - return CreateCacheBackendImpl( - type, backend_type, std::move(file_operations), path, max_bytes, - reset_handling, + BackendResultCallback callback) { + return CreateCacheBackendImpl(type, backend_type, std::move(file_operations), + path, max_bytes, reset_handling, #if BUILDFLAG(IS_ANDROID) - nullptr, + nullptr, #endif - net_log, backend, std::move(post_cleanup_callback), std::move(callback)); + net_log, std::move(post_cleanup_callback), + std::move(callback)); } void FlushCacheThreadForTesting() { diff --git a/chromium/net/disk_cache/disk_cache.h b/chromium/net/disk_cache/disk_cache.h index 88f140d750f..31f548b2a46 100644 --- a/chromium/net/disk_cache/disk_cache.h +++ b/chromium/net/disk_cache/disk_cache.h @@ -54,6 +54,26 @@ using RangeResultCallback = base::OnceCallback<void(const RangeResult&)>; // See CreateCacheBackend() for its usage. enum class ResetHandling { kReset, kResetOnError, kNeverReset }; +struct NET_EXPORT BackendResult { + BackendResult(); + ~BackendResult(); + BackendResult(BackendResult&&); + BackendResult& operator=(BackendResult&&); + + BackendResult(const BackendResult&) = delete; + BackendResult& operator=(const BackendResult&) = delete; + + // `error_in` should not be net::OK for MakeError(). + static BackendResult MakeError(net::Error error_in); + // `backend_in` should not be nullptr for Make(). + static BackendResult Make(std::unique_ptr<Backend> backend_in); + + net::Error net_error = net::ERR_FAILED; + std::unique_ptr<Backend> backend; +}; + +using BackendResultCallback = base::OnceCallback<void(BackendResult)>; + // Returns an instance of a Backend of the given `type`. `file_operations` // (nullable) is used to broker file operations in sandboxed environments. // Currently `file_operations` is only used for the simple backend. @@ -71,28 +91,27 @@ enum class ResetHandling { kReset, kResetOnError, kNeverReset }; // cache creation will fail if there is a problem with cache initialization. // // `max_bytes` is the maximum size the cache can grow to. If zero is passed in -// as `max_bytes`, the cache will determine the value to use. The returned -// pointer can be nullptr if a fatal error is found. The actual return value of -// the function is a net error code. If this function returns ERR_IO_PENDING, -// the `callback` will be invoked when a backend is available or a fatal error -// condition is reached. The pointer to receive the `backend` must remain valid -// until the operation completes (the callback is notified). -NET_EXPORT net::Error CreateCacheBackend( - net::CacheType type, - net::BackendType backend_type, - scoped_refptr<BackendFileOperationsFactory> file_operations, - const base::FilePath& path, - int64_t max_bytes, - ResetHandling reset_handling, - net::NetLog* net_log, - std::unique_ptr<Backend>* backend, - net::CompletionOnceCallback callback); +// as `max_bytes`, the cache will determine the value to use. +// +// `net_error` in return value of the function is a net error code. If it is +// ERR_IO_PENDING, the `callback` will be invoked when a backend is available or +// a fatal error condition is reached. `backend` in return value or parameter +// to callback can be nullptr if a fatal error is found. +NET_EXPORT BackendResult +CreateCacheBackend(net::CacheType type, + net::BackendType backend_type, + scoped_refptr<BackendFileOperationsFactory> file_operations, + const base::FilePath& path, + int64_t max_bytes, + ResetHandling reset_handling, + net::NetLog* net_log, + BackendResultCallback callback); #if BUILDFLAG(IS_ANDROID) // Similar to the function above, but takes an |app_status_listener| which is // used to listen for when the Android application status changes, so we can // flush the cache to disk when the app goes to the background. -NET_EXPORT net::Error CreateCacheBackend( +NET_EXPORT BackendResult CreateCacheBackend( net::CacheType type, net::BackendType backend_type, scoped_refptr<BackendFileOperationsFactory> file_operations, @@ -100,8 +119,7 @@ NET_EXPORT net::Error CreateCacheBackend( int64_t max_bytes, ResetHandling reset_handling, net::NetLog* net_log, - std::unique_ptr<Backend>* backend, - net::CompletionOnceCallback callback, + BackendResultCallback callback, base::android::ApplicationStatusListener* app_status_listener); #endif @@ -114,17 +132,16 @@ NET_EXPORT net::Error CreateCacheBackend( // // Note that this will not wait for |post_cleanup_callback| of a previous // instance for |path| to run. -NET_EXPORT net::Error CreateCacheBackend( - net::CacheType type, - net::BackendType backend_type, - scoped_refptr<BackendFileOperationsFactory> file_operations, - const base::FilePath& path, - int64_t max_bytes, - ResetHandling reset_handling, - net::NetLog* net_log, - std::unique_ptr<Backend>* backend, - base::OnceClosure post_cleanup_callback, - net::CompletionOnceCallback callback); +NET_EXPORT BackendResult +CreateCacheBackend(net::CacheType type, + net::BackendType backend_type, + scoped_refptr<BackendFileOperationsFactory> file_operations, + const base::FilePath& path, + int64_t max_bytes, + ResetHandling reset_handling, + net::NetLog* net_log, + base::OnceClosure post_cleanup_callback, + BackendResultCallback callback); // This will flush any internal threads used by backends created w/o an // externally injected thread specified, so tests can be sure that all I/O @@ -146,7 +163,7 @@ class NET_EXPORT Backend { class Iterator { public: - virtual ~Iterator() {} + virtual ~Iterator() = default; // OpenNextEntry returns a result with net_error() |net::OK| and provided // entry if there is an entry to enumerate which it can return immediately. @@ -175,8 +192,8 @@ class NET_EXPORT Backend { // on what will succeed and what will fail. In particular the blockfile // backend will leak entries closed after backend deletion, while others // handle it properly. - Backend(net::CacheType cache_type) : cache_type_(cache_type) {} - virtual ~Backend() {} + explicit Backend(net::CacheType cache_type) : cache_type_(cache_type) {} + virtual ~Backend() = default; // Returns the type of this cache. net::CacheType GetCacheType() const { return cache_type_; } @@ -464,7 +481,7 @@ class NET_EXPORT Entry { virtual void SetLastUsedTimeForTest(base::Time time) = 0; protected: - virtual ~Entry() {} + virtual ~Entry() = default; }; struct EntryDeleter { diff --git a/chromium/net/disk_cache/disk_cache_fuzzer.cc b/chromium/net/disk_cache/disk_cache_fuzzer.cc index 2e0bd143a3f..e111cbe9894 100644 --- a/chromium/net/disk_cache/disk_cache_fuzzer.cc +++ b/chromium/net/disk_cache/disk_cache_fuzzer.cc @@ -1151,8 +1151,9 @@ void DiskCacheLPMFuzzer::CreateBackend( bool simple_cache_wait_for_index) { if (cache_backend == disk_cache_fuzzer::FuzzCommands::IN_MEMORY) { MAYBE_PRINT << "Using in-memory cache." << std::endl; - mem_cache_ = new disk_cache::MemBackendImpl(nullptr); - cache_.reset(mem_cache_); + auto cache = std::make_unique<disk_cache::MemBackendImpl>(nullptr); + mem_cache_ = cache.get(); + cache_ = std::move(cache); CHECK(cache_); } else if (cache_backend == disk_cache_fuzzer::FuzzCommands::SIMPLE) { MAYBE_PRINT << "Using simple cache." << std::endl; @@ -1162,13 +1163,12 @@ void DiskCacheLPMFuzzer::CreateBackend( if (!simple_file_tracker_) simple_file_tracker_ = std::make_unique<disk_cache::SimpleFileTracker>(kMaxFdsSimpleCache); - std::unique_ptr<disk_cache::SimpleBackendImpl> simple_backend = - std::make_unique<disk_cache::SimpleBackendImpl>( - /*file_operations=*/nullptr, cache_path_, - /*cleanup_tracker=*/nullptr, simple_file_tracker_.get(), max_size_, - type, /*net_log=*/nullptr); - int rv = simple_backend->Init(cb.callback()); - CHECK_EQ(cb.GetResult(rv), net::OK); + auto simple_backend = std::make_unique<disk_cache::SimpleBackendImpl>( + /*file_operations=*/nullptr, cache_path_, + /*cleanup_tracker=*/nullptr, simple_file_tracker_.get(), max_size_, + type, /*net_log=*/nullptr); + simple_backend->Init(cb.callback()); + CHECK_EQ(cb.WaitForResult(), net::OK); simple_cache_impl_ = simple_backend.get(); cache_ = std::move(simple_backend); @@ -1178,25 +1178,28 @@ void DiskCacheLPMFuzzer::CreateBackend( net::TestCompletionCallback wait_for_index_cb; simple_cache_impl_->index()->ExecuteWhenReady( wait_for_index_cb.callback()); - rv = wait_for_index_cb.WaitForResult(); + int rv = wait_for_index_cb.WaitForResult(); CHECK_EQ(rv, net::OK); } } else { MAYBE_PRINT << "Using blockfile cache"; - + std::unique_ptr<disk_cache::BackendImpl> cache; if (mask) { MAYBE_PRINT << ", mask = " << mask << std::endl; - block_impl_ = new disk_cache::BackendImpl(cache_path_, mask, - /* runner = */ nullptr, type, - /* net_log = */ nullptr); + cache = std::make_unique<disk_cache::BackendImpl>( + cache_path_, mask, + /* runner = */ nullptr, type, + /* net_log = */ nullptr); } else { MAYBE_PRINT << "." << std::endl; - block_impl_ = new disk_cache::BackendImpl(cache_path_, - /* cleanup_tracker = */ nullptr, - /* runner = */ nullptr, type, - /* net_log = */ nullptr); + cache = std::make_unique<disk_cache::BackendImpl>( + cache_path_, + /* cleanup_tracker = */ nullptr, + /* runner = */ nullptr, type, + /* net_log = */ nullptr); } - cache_.reset(block_impl_); + block_impl_ = cache.get(); + cache_ = std::move(cache); CHECK(cache_); // TODO(mpdenton) kNoRandom or not? It does a lot of waiting for IO. May be // good for avoiding leaks but tests a less realistic cache. @@ -1204,8 +1207,8 @@ void DiskCacheLPMFuzzer::CreateBackend( // TODO(mpdenton) should I always wait here? net::TestCompletionCallback cb; - int rv = block_impl_->Init(cb.callback()); - CHECK_EQ(cb.GetResult(rv), net::OK); + block_impl_->Init(cb.callback()); + CHECK_EQ(cb.WaitForResult(), net::OK); } } diff --git a/chromium/net/disk_cache/disk_cache_perftest.cc b/chromium/net/disk_cache/disk_cache_perftest.cc index 14ce27d2d76..0a2501e475a 100644 --- a/chromium/net/disk_cache/disk_cache_perftest.cc +++ b/chromium/net/disk_cache/disk_cache_perftest.cc @@ -277,9 +277,10 @@ class ReadHandler { what_to_read_(what_to_read), cache_(cache), final_callback_(std::move(final_callback)) { - for (int i = 0; i < kMaxParallelOperations; ++i) - read_buffers_[i] = base::MakeRefCounted<net::IOBuffer>( + for (auto& read_buffer : read_buffers_) { + read_buffer = base::MakeRefCounted<net::IOBuffer>( std::max(kHeadersSize, kChunkSize)); + } } void Run(); @@ -547,10 +548,9 @@ TEST_F(DiskCachePerfTest, BlockFilesPerformance) { base::ElapsedTimer sequential_timer; // Fill up the 32-byte block file (use three files). - for (int i = 0; i < kNumBlocks; i++) { + for (auto& addr : address) { int block_size = base::RandInt(1, 4); - EXPECT_TRUE( - files.CreateBlock(disk_cache::RANKINGS, block_size, &address[i])); + EXPECT_TRUE(files.CreateBlock(disk_cache::RANKINGS, block_size, &addr)); } reporter.AddResult(kMetricFillBlocksTimeMs, @@ -629,9 +629,8 @@ TEST_F(DiskCachePerfTest, SimpleCacheInitialReadPortion) { VerifyRvAndCallClosure, base::Unretained(&barrier), kHeadersSize)); base::ElapsedTimer timer_early; - for (int e = 0; e < kBatchSize; ++e) { - int rv = - cache_entry[e]->ReadData(0, 0, buffer1.get(), kHeadersSize, cb_batch); + for (auto* entry : cache_entry) { + int rv = entry->ReadData(0, 0, buffer1.get(), kHeadersSize, cb_batch); if (rv != net::ERR_IO_PENDING) { barrier.Run(); ASSERT_EQ(kHeadersSize, rv); @@ -645,8 +644,8 @@ TEST_F(DiskCachePerfTest, SimpleCacheInitialReadPortion) { } // Cleanup - for (int i = 0; i < kBatchSize; ++i) - cache_entry[i]->Close(); + for (auto* entry : cache_entry) + entry->Close(); disk_cache::FlushCacheThreadForTesting(); base::RunLoop().RunUntilIdle(); diff --git a/chromium/net/disk_cache/disk_cache_test_base.cc b/chromium/net/disk_cache/disk_cache_test_base.cc index 792e751049b..9e36dd91212 100644 --- a/chromium/net/disk_cache/disk_cache_test_base.cc +++ b/chromium/net/disk_cache/disk_cache_test_base.cc @@ -352,8 +352,9 @@ void DiskCacheTestWithCache::TearDown() { } void DiskCacheTestWithCache::InitMemoryCache() { - mem_cache_ = new disk_cache::MemBackendImpl(nullptr); - cache_.reset(mem_cache_); + auto cache = std::make_unique<disk_cache::MemBackendImpl>(nullptr); + mem_cache_ = cache.get(); + cache_ = std::move(cache); ASSERT_TRUE(cache_); if (size_) @@ -390,28 +391,32 @@ void DiskCacheTestWithCache::CreateBackend(uint32_t flags) { /*file_operations=*/nullptr, cache_path_, /* cleanup_tracker = */ nullptr, simple_file_tracker_.get(), size_, type_, /*net_log = */ nullptr); - int rv = simple_backend->Init(cb.callback()); - ASSERT_THAT(cb.GetResult(rv), IsOk()); + simple_backend->Init(cb.callback()); + ASSERT_THAT(cb.WaitForResult(), IsOk()); simple_cache_impl_ = simple_backend.get(); cache_ = std::move(simple_backend); if (simple_cache_wait_for_index_) { net::TestCompletionCallback wait_for_index_cb; simple_cache_impl_->index()->ExecuteWhenReady( wait_for_index_cb.callback()); - rv = wait_for_index_cb.WaitForResult(); + int rv = wait_for_index_cb.WaitForResult(); ASSERT_THAT(rv, IsOk()); } return; } - if (mask_) - cache_impl_ = new disk_cache::BackendImpl(cache_path_, mask_, runner, type_, - /* net_log = */ nullptr); - else - cache_impl_ = new disk_cache::BackendImpl( + std::unique_ptr<disk_cache::BackendImpl> cache; + if (mask_) { + cache = std::make_unique<disk_cache::BackendImpl>(cache_path_, mask_, + runner, type_, + /* net_log = */ nullptr); + } else { + cache = std::make_unique<disk_cache::BackendImpl>( cache_path_, /* cleanup_tracker = */ nullptr, runner, type_, /* net_log = */ nullptr); - cache_.reset(cache_impl_); + } + cache_impl_ = cache.get(); + cache_ = std::move(cache); ASSERT_TRUE(cache_); if (size_) EXPECT_TRUE(cache_impl_->SetMaxSize(size_)); @@ -419,6 +424,6 @@ void DiskCacheTestWithCache::CreateBackend(uint32_t flags) { cache_impl_->SetNewEviction(); cache_impl_->SetFlags(flags); net::TestCompletionCallback cb; - int rv = cache_impl_->Init(cb.callback()); - ASSERT_THAT(cb.GetResult(rv), IsOk()); + cache_impl_->Init(cb.callback()); + ASSERT_THAT(cb.WaitForResult(), IsOk()); } diff --git a/chromium/net/disk_cache/disk_cache_test_util.cc b/chromium/net/disk_cache/disk_cache_test_util.cc index ad1fb222ee6..7256850af5a 100644 --- a/chromium/net/disk_cache/disk_cache_test_util.cc +++ b/chromium/net/disk_cache/disk_cache_test_util.cc @@ -62,9 +62,9 @@ bool CheckCacheIntegrity(const base::FilePath& path, bool new_eviction, int max_size, uint32_t mask) { - std::unique_ptr<disk_cache::BackendImpl> cache(new disk_cache::BackendImpl( + auto cache = std::make_unique<disk_cache::BackendImpl>( path, mask, base::ThreadTaskRunnerHandle::Get(), net::DISK_CACHE, - nullptr)); + nullptr); if (max_size) cache->SetMaxSize(max_size); if (!cache.get()) @@ -78,6 +78,17 @@ bool CheckCacheIntegrity(const base::FilePath& path, } // ----------------------------------------------------------------------- +TestBackendResultCompletionCallback::TestBackendResultCompletionCallback() = + default; + +TestBackendResultCompletionCallback::~TestBackendResultCompletionCallback() = + default; + +disk_cache::BackendResultCallback +TestBackendResultCompletionCallback::callback() { + return base::BindOnce(&TestBackendResultCompletionCallback::SetResult, + base::Unretained(this)); +} TestEntryResultCompletionCallback::TestEntryResultCompletionCallback() = default; diff --git a/chromium/net/disk_cache/disk_cache_test_util.h b/chromium/net/disk_cache/disk_cache_test_util.h index c3586a17df7..548fefbef07 100644 --- a/chromium/net/disk_cache/disk_cache_test_util.h +++ b/chromium/net/disk_cache/disk_cache_test_util.h @@ -39,6 +39,31 @@ bool CheckCacheIntegrity(const base::FilePath& path, // ----------------------------------------------------------------------- +// Like net::TestCompletionCallback, but for BackendResultCallback. +struct BackendResultIsPendingHelper { + bool operator()(const disk_cache::BackendResult& result) const { + return result.net_error == net::ERR_IO_PENDING; + } +}; +using TestBackendResultCompletionCallbackBase = + net::internal::TestCompletionCallbackTemplate<disk_cache::BackendResult, + BackendResultIsPendingHelper>; + +class TestBackendResultCompletionCallback + : public TestBackendResultCompletionCallbackBase { + public: + TestBackendResultCompletionCallback(); + + TestBackendResultCompletionCallback( + const TestBackendResultCompletionCallback&) = delete; + TestBackendResultCompletionCallback& operator=( + const TestBackendResultCompletionCallback&) = delete; + + ~TestBackendResultCompletionCallback() override; + + disk_cache::BackendResultCallback callback(); +}; + // Like net::TestCompletionCallback, but for EntryResultCallback. struct EntryResultIsPendingHelper { diff --git a/chromium/net/disk_cache/entry_unittest.cc b/chromium/net/disk_cache/entry_unittest.cc index a3290992bc2..d5a444bf1d9 100644 --- a/chromium/net/disk_cache/entry_unittest.cc +++ b/chromium/net/disk_cache/entry_unittest.cc @@ -606,9 +606,9 @@ void DiskCacheEntryTest::StreamAccess() { const int kBufferSize = 1024; const int kNumStreams = 3; scoped_refptr<net::IOBuffer> reference_buffers[kNumStreams]; - for (int i = 0; i < kNumStreams; i++) { - reference_buffers[i] = base::MakeRefCounted<net::IOBuffer>(kBufferSize); - CacheTestFillBuffer(reference_buffers[i]->data(), kBufferSize, false); + for (auto& reference_buffer : reference_buffers) { + reference_buffer = base::MakeRefCounted<net::IOBuffer>(kBufferSize); + CacheTestFillBuffer(reference_buffer->data(), kBufferSize, false); } scoped_refptr<net::IOBuffer> buffer1 = base::MakeRefCounted<net::IOBuffer>(kBufferSize); @@ -2552,7 +2552,7 @@ TEST_F(DiskCacheEntryTest, SparseClipEnd) { // Blockfile refuses to deal with sparse indices over 64GiB. SparseClipEnd(std::numeric_limits<int64_t>::max(), - /* expect_unsupported = */ true); + /*expected_unsupported=*/true); } TEST_F(DiskCacheEntryTest, SparseClipEnd2) { @@ -2561,7 +2561,7 @@ TEST_F(DiskCacheEntryTest, SparseClipEnd2) { const int64_t kLimit = 64ll * 1024 * 1024 * 1024; // Separate test for blockfile for indices right at the edge of its address // space limit. kLimit must match kMaxEndOffset in sparse_control.cc - SparseClipEnd(kLimit, /* expect_unsupported = */ false); + SparseClipEnd(kLimit, /*expected_unsupported=*/false); // Test with things after kLimit, too, which isn't an issue for backends // supporting the entire 64-bit offset range. @@ -2594,14 +2594,14 @@ TEST_F(DiskCacheEntryTest, MemoryOnlySparseClipEnd) { SetMemoryOnlyMode(); InitCache(); SparseClipEnd(std::numeric_limits<int64_t>::max(), - /* expect_unsupported = */ false); + /* expected_unsupported = */ false); } TEST_F(DiskCacheEntryTest, SimpleSparseClipEnd) { SetSimpleCacheMode(); InitCache(); SparseClipEnd(std::numeric_limits<int64_t>::max(), - /* expect_unsupported = */ false); + /* expected_unsupported = */ false); } // Tests that corrupt sparse children are removed automatically. @@ -2625,16 +2625,16 @@ TEST_F(DiskCacheEntryTest, CleanupSparseEntry) { std::unique_ptr<TestIterator> iter = CreateIterator(); int count = 0; - std::string child_key[2]; + std::string child_keys[2]; while (iter->OpenNextEntry(&entry) == net::OK) { ASSERT_TRUE(entry != nullptr); // Writing to an entry will alter the LRU list and invalidate the iterator. if (entry->GetKey() != key && count < 2) - child_key[count++] = entry->GetKey(); + child_keys[count++] = entry->GetKey(); entry->Close(); } - for (int i = 0; i < 2; i++) { - ASSERT_THAT(OpenEntry(child_key[i], &entry), IsOk()); + for (const auto& child_key : child_keys) { + ASSERT_THAT(OpenEntry(child_key, &entry), IsOk()); // Overwrite the header's magic and signature. EXPECT_EQ(12, WriteData(entry, 2, 0, buf1.get(), 12, false)); entry->Close(); diff --git a/chromium/net/disk_cache/memory/mem_backend_impl.cc b/chromium/net/disk_cache/memory/mem_backend_impl.cc index 993792e49b2..ab9f0416f96 100644 --- a/chromium/net/disk_cache/memory/mem_backend_impl.cc +++ b/chromium/net/disk_cache/memory/mem_backend_impl.cc @@ -76,9 +76,9 @@ bool MemBackendImpl::Init() { if (max_size_) return true; - int64_t total_memory = base::SysInfo::AmountOfPhysicalMemory(); + uint64_t total_memory = base::SysInfo::AmountOfPhysicalMemory(); - if (total_memory <= 0) { + if (total_memory == 0) { max_size_ = kDefaultInMemoryCacheSize; return true; } @@ -86,7 +86,7 @@ bool MemBackendImpl::Init() { // We want to use up to 2% of the computer's memory, with a limit of 50 MB, // reached on system with more than 2.5 GB of RAM. total_memory = total_memory * 2 / 100; - if (total_memory > kDefaultInMemoryCacheSize * 5) + if (total_memory > static_cast<uint64_t>(kDefaultInMemoryCacheSize) * 5) max_size_ = kDefaultInMemoryCacheSize * 5; else max_size_ = static_cast<int32_t>(total_memory); @@ -308,8 +308,7 @@ class MemBackendImpl::MemIterator final : public Backend::Iterator { }; std::unique_ptr<Backend::Iterator> MemBackendImpl::CreateIterator() { - return std::unique_ptr<Backend::Iterator>( - new MemIterator(weak_factory_.GetWeakPtr())); + return std::make_unique<MemIterator>(weak_factory_.GetWeakPtr()); } void MemBackendImpl::OnExternalCacheHit(const std::string& key) { diff --git a/chromium/net/disk_cache/memory/mem_entry_impl.cc b/chromium/net/disk_cache/memory/mem_entry_impl.cc index a045f72e727..38ab5bf418a 100644 --- a/chromium/net/disk_cache/memory/mem_entry_impl.cc +++ b/chromium/net/disk_cache/memory/mem_entry_impl.cc @@ -58,7 +58,7 @@ std::string GenerateChildName(const std::string& base_name, int64_t child_id) { // Returns NetLog parameters for the creation of a MemEntryImpl. A separate // function is needed because child entries don't store their key(). base::Value NetLogEntryCreationParams(const MemEntryImpl* entry) { - base::Value dict(base::Value::Type::DICTIONARY); + base::Value::Dict dict; std::string key; switch (entry->type()) { case MemEntryImpl::EntryType::kParent: @@ -68,9 +68,9 @@ base::Value NetLogEntryCreationParams(const MemEntryImpl* entry) { key = GenerateChildName(entry->parent()->key(), entry->child_id()); break; } - dict.SetStringKey("key", key); - dict.SetBoolKey("created", true); - return dict; + dict.Set("key", key); + dict.Set("created", true); + return base::Value(std::move(dict)); } } // namespace diff --git a/chromium/net/disk_cache/net_log_parameters.cc b/chromium/net/disk_cache/net_log_parameters.cc index 89c1245a3fb..9745df6856f 100644 --- a/chromium/net/disk_cache/net_log_parameters.cc +++ b/chromium/net/disk_cache/net_log_parameters.cc @@ -19,39 +19,39 @@ base::Value NetLogReadWriteDataParams(int index, int offset, int buf_len, bool truncate) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("index", index); - dict.SetIntKey("offset", offset); - dict.SetIntKey("buf_len", buf_len); + base::Value::Dict dict; + dict.Set("index", index); + dict.Set("offset", offset); + dict.Set("buf_len", buf_len); if (truncate) - dict.SetBoolKey("truncate", truncate); - return dict; + dict.Set("truncate", truncate); + return base::Value(std::move(dict)); } base::Value NetLogReadWriteCompleteParams(int bytes_copied) { DCHECK_NE(bytes_copied, net::ERR_IO_PENDING); - base::Value dict(base::Value::Type::DICTIONARY); + base::Value::Dict dict; if (bytes_copied < 0) { - dict.SetIntKey("net_error", bytes_copied); + dict.Set("net_error", bytes_copied); } else { - dict.SetIntKey("bytes_copied", bytes_copied); + dict.Set("bytes_copied", bytes_copied); } - return dict; + return base::Value(std::move(dict)); } base::Value NetLogSparseOperationParams(int64_t offset, int buf_len) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetKey("offset", net::NetLogNumberValue(offset)); - dict.SetIntKey("buf_len", buf_len); - return dict; + base::Value::Dict dict; + dict.Set("offset", net::NetLogNumberValue(offset)); + dict.Set("buf_len", buf_len); + return base::Value(std::move(dict)); } base::Value NetLogSparseReadWriteParams(const net::NetLogSource& source, int child_len) { - base::Value dict(base::Value::Type::DICTIONARY); - source.AddToEventParameters(&dict); - dict.SetIntKey("child_len", child_len); - return dict; + base::Value::Dict dict; + source.AddToEventParameters(dict); + dict.Set("child_len", child_len); + return base::Value(std::move(dict)); } } // namespace @@ -61,10 +61,10 @@ namespace disk_cache { base::Value CreateNetLogParametersEntryCreationParams(const Entry* entry, bool created) { DCHECK(entry); - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("key", entry->GetKey()); - dict.SetBoolKey("created", created); - return dict; + base::Value::Dict dict; + dict.Set("key", entry->GetKey()); + dict.Set("created", created); + return base::Value(std::move(dict)); } void NetLogReadWriteData(const net::NetLogWithSource& net_log, @@ -109,14 +109,14 @@ void NetLogSparseReadWrite(const net::NetLogWithSource& net_log, base::Value CreateNetLogGetAvailableRangeResultParams( disk_cache::RangeResult result) { - base::Value dict(base::Value::Type::DICTIONARY); + base::Value::Dict dict; if (result.net_error == net::OK) { - dict.SetIntKey("length", result.available_len); - dict.SetKey("start", net::NetLogNumberValue(result.start)); + dict.Set("length", result.available_len); + dict.Set("start", net::NetLogNumberValue(result.start)); } else { - dict.SetIntKey("net_error", result.net_error); + dict.Set("net_error", result.net_error); } - return dict; + return base::Value(std::move(dict)); } } // namespace disk_cache diff --git a/chromium/net/disk_cache/simple/post_doom_waiter.cc b/chromium/net/disk_cache/simple/post_doom_waiter.cc index 8814efbfb0e..717adda347d 100644 --- a/chromium/net/disk_cache/simple/post_doom_waiter.cc +++ b/chromium/net/disk_cache/simple/post_doom_waiter.cc @@ -11,7 +11,7 @@ namespace disk_cache { -SimplePostDoomWaiter::SimplePostDoomWaiter() {} +SimplePostDoomWaiter::SimplePostDoomWaiter() = default; SimplePostDoomWaiter::SimplePostDoomWaiter(base::OnceClosure to_run_post_doom) : run_post_doom(std::move(to_run_post_doom)) {} @@ -20,7 +20,7 @@ SimplePostDoomWaiter::SimplePostDoomWaiter(SimplePostDoomWaiter&& other) = default; SimplePostDoomWaiter& SimplePostDoomWaiter::operator=( SimplePostDoomWaiter&& other) = default; -SimplePostDoomWaiter::~SimplePostDoomWaiter() {} +SimplePostDoomWaiter::~SimplePostDoomWaiter() = default; SimplePostDoomWaiterTable::SimplePostDoomWaiterTable(net::CacheType cache_type) : cache_type_(cache_type) {} diff --git a/chromium/net/disk_cache/simple/post_doom_waiter.h b/chromium/net/disk_cache/simple/post_doom_waiter.h index 01c563c8607..3fde99253e3 100644 --- a/chromium/net/disk_cache/simple/post_doom_waiter.h +++ b/chromium/net/disk_cache/simple/post_doom_waiter.h @@ -19,7 +19,7 @@ namespace disk_cache { struct SimplePostDoomWaiter { SimplePostDoomWaiter(); explicit SimplePostDoomWaiter(base::OnceClosure to_run_post_doom); - explicit SimplePostDoomWaiter(SimplePostDoomWaiter&& other); + SimplePostDoomWaiter(SimplePostDoomWaiter&& other); ~SimplePostDoomWaiter(); SimplePostDoomWaiter& operator=(SimplePostDoomWaiter&& other); diff --git a/chromium/net/disk_cache/simple/simple_backend_impl.cc b/chromium/net/disk_cache/simple/simple_backend_impl.cc index cec9824dbc1..e0be60eb39b 100644 --- a/chromium/net/disk_cache/simple/simple_backend_impl.cc +++ b/chromium/net/disk_cache/simple/simple_backend_impl.cc @@ -22,6 +22,7 @@ #include "base/files/file_util.h" #include "base/lazy_instance.h" #include "base/location.h" +#include "base/memory/ptr_util.h" #include "base/metrics/field_trial.h" #include "base/metrics/field_trial_params.h" #include "base/metrics/histogram_functions.h" @@ -192,9 +193,7 @@ class SimpleBackendImpl::ActiveEntryProxy static std::unique_ptr<SimpleEntryImpl::ActiveEntryProxy> Create( int64_t entry_hash, SimpleBackendImpl* backend) { - std::unique_ptr<SimpleEntryImpl::ActiveEntryProxy> proxy( - new ActiveEntryProxy(entry_hash, backend)); - return proxy; + return base::WrapUnique(new ActiveEntryProxy(entry_hash, backend)); } private: @@ -248,7 +247,7 @@ void SimpleBackendImpl::SetTaskRunnerForTesting( std::move(task_runner)); } -net::Error SimpleBackendImpl::Init(CompletionOnceCallback completion_callback) { +void SimpleBackendImpl::Init(CompletionOnceCallback completion_callback) { auto index_task_runner = base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::WithBaseSyncPrimitives(), base::TaskPriority::USER_BLOCKING, @@ -273,7 +272,6 @@ net::Error SimpleBackendImpl::Init(CompletionOnceCallback completion_callback) { GetCacheType()), base::BindOnce(&SimpleBackendImpl::InitializeIndex, AsWeakPtr(), std::move(completion_callback))); - return net::ERR_IO_PENDING; } bool SimpleBackendImpl::SetMaxSize(int64_t max_bytes) { @@ -301,8 +299,7 @@ scoped_refptr<SimplePostDoomWaiterTable> SimpleBackendImpl::OnDoomStart( void SimpleBackendImpl::DoomEntries(std::vector<uint64_t>* entry_hashes, net::CompletionOnceCallback callback) { - std::unique_ptr<std::vector<uint64_t>> mass_doom_entry_hashes( - new std::vector<uint64_t>()); + auto mass_doom_entry_hashes = std::make_unique<std::vector<uint64_t>>(); mass_doom_entry_hashes->swap(*entry_hashes); std::vector<uint64_t> to_doom_individually_hashes; @@ -629,7 +626,7 @@ class SimpleBackendImpl::SimpleIterator final : public Iterator { }; std::unique_ptr<Backend::Iterator> SimpleBackendImpl::CreateIterator() { - return std::unique_ptr<Iterator>(new SimpleIterator(AsWeakPtr())); + return std::make_unique<SimpleIterator>(AsWeakPtr()); } void SimpleBackendImpl::GetStats(base::StringPairs* stats) { @@ -780,7 +777,7 @@ SimpleBackendImpl::CreateOrFindActiveOrDoomedEntry( return nullptr; std::pair<EntryMap::iterator, bool> insert_result = - active_entries_.insert(EntryMap::value_type(entry_hash, NULL)); + active_entries_.insert(EntryMap::value_type(entry_hash, nullptr)); EntryMap::iterator& it = insert_result.first; const bool did_insert = insert_result.second; if (did_insert) { @@ -841,9 +838,6 @@ EntryResult SimpleBackendImpl::OpenEntryFromHash(uint64_t entry_hash, net::Error SimpleBackendImpl::DoomEntryFromHash( uint64_t entry_hash, CompletionOnceCallback callback) { - Entry** entry = new Entry*(); - std::unique_ptr<Entry*> scoped_entry(entry); - std::vector<SimplePostDoomWaiter>* post_doom = post_doom_waiting_->Find(entry_hash); if (post_doom) { diff --git a/chromium/net/disk_cache/simple/simple_backend_impl.h b/chromium/net/disk_cache/simple/simple_backend_impl.h index 46859670b34..84ca265f3ef 100644 --- a/chromium/net/disk_cache/simple/simple_backend_impl.h +++ b/chromium/net/disk_cache/simple/simple_backend_impl.h @@ -63,6 +63,7 @@ class NET_EXPORT_PRIVATE SimpleBackendImpl : public Backend, // Note: only pass non-nullptr for |file_tracker| if you don't want the global // one (which things other than tests would want). |file_tracker| must outlive // the backend and all the entries, including their asynchronous close. + // |Init()| must be called to finish the initialization process. SimpleBackendImpl( scoped_refptr<BackendFileOperationsFactory> file_operations_factory, const base::FilePath& path, @@ -79,7 +80,8 @@ class NET_EXPORT_PRIVATE SimpleBackendImpl : public Backend, void SetTaskRunnerForTesting( scoped_refptr<base::SequencedTaskRunner> task_runner); - net::Error Init(CompletionOnceCallback completion_callback); + // Finishes initialization. Always asynchronous. + void Init(CompletionOnceCallback completion_callback); // Sets the maximum size for the total amount of data stored by this instance. bool SetMaxSize(int64_t max_bytes); diff --git a/chromium/net/disk_cache/simple/simple_entry_format_history.h b/chromium/net/disk_cache/simple/simple_entry_format_history.h index 3bcb8b44917..5936c8807d3 100644 --- a/chromium/net/disk_cache/simple/simple_entry_format_history.h +++ b/chromium/net/disk_cache/simple/simple_entry_format_history.h @@ -9,9 +9,7 @@ #include "net/base/net_export.h" -namespace disk_cache { - -namespace simplecache_v5 { +namespace disk_cache::simplecache_v5 { const uint64_t kSimpleInitialMagicNumber = UINT64_C(0xfcfb6d1ba7725c30); const uint64_t kSimpleFinalMagicNumber = UINT64_C(0xf4fa6f45970d41d8); @@ -55,8 +53,6 @@ struct NET_EXPORT_PRIVATE SimpleFileEOF { uint32_t stream_size; }; -} // namespace simplecache_v5 - -} // namespace disk_cache +} // namespace disk_cache::simplecache_v5 #endif // NET_DISK_CACHE_SIMPLE_SIMPLE_ENTRY_FORMAT_HISTORY_H_ diff --git a/chromium/net/disk_cache/simple/simple_entry_impl.cc b/chromium/net/disk_cache/simple/simple_entry_impl.cc index 116ce16838c..02d2005d86e 100644 --- a/chromium/net/disk_cache/simple/simple_entry_impl.cc +++ b/chromium/net/disk_cache/simple/simple_entry_impl.cc @@ -788,9 +788,8 @@ void SimpleEntryImpl::OpenEntryInternal( DCHECK(!synchronous_entry_); state_ = STATE_IO_PENDING; const base::TimeTicks start_time = base::TimeTicks::Now(); - std::unique_ptr<SimpleEntryCreationResults> results( - new SimpleEntryCreationResults(SimpleEntryStat( - last_used_, last_modified_, data_size_, sparse_data_size_))); + auto results = std::make_unique<SimpleEntryCreationResults>(SimpleEntryStat( + last_used_, last_modified_, data_size_, sparse_data_size_)); int32_t trailer_prefetch_size = -1; base::Time last_used_time; @@ -846,9 +845,8 @@ void SimpleEntryImpl::CreateEntryInternal( last_used_ = last_modified_ = base::Time::Now(); const base::TimeTicks start_time = base::TimeTicks::Now(); - std::unique_ptr<SimpleEntryCreationResults> results( - new SimpleEntryCreationResults(SimpleEntryStat( - last_used_, last_modified_, data_size_, sparse_data_size_))); + auto results = std::make_unique<SimpleEntryCreationResults>(SimpleEntryStat( + last_used_, last_modified_, data_size_, sparse_data_size_)); OnceClosure task = base::BindOnce(&SimpleSynchronousEntry::CreateEntry, cache_type_, path_, @@ -897,9 +895,8 @@ void SimpleEntryImpl::OpenOrCreateEntryInternal( DCHECK(!synchronous_entry_); state_ = STATE_IO_PENDING; const base::TimeTicks start_time = base::TimeTicks::Now(); - std::unique_ptr<SimpleEntryCreationResults> results( - new SimpleEntryCreationResults(SimpleEntryStat( - last_used_, last_modified_, data_size_, sparse_data_size_))); + auto results = std::make_unique<SimpleEntryCreationResults>(SimpleEntryStat( + last_used_, last_modified_, data_size_, sparse_data_size_)); int32_t trailer_prefetch_size = -1; base::Time last_used_time; @@ -937,8 +934,7 @@ void SimpleEntryImpl::CloseInternal() { } typedef SimpleSynchronousEntry::CRCRecord CRCRecord; - std::unique_ptr<std::vector<CRCRecord>> crc32s_to_write( - new std::vector<CRCRecord>()); + auto crc32s_to_write = std::make_unique<std::vector<CRCRecord>>(); net_log_.AddEvent(net::NetLogEventType::SIMPLE_CACHE_ENTRY_CLOSE_BEGIN); @@ -959,8 +955,7 @@ void SimpleEntryImpl::CloseInternal() { DCHECK(STATE_UNINITIALIZED == state_ || STATE_FAILURE == state_); } - std::unique_ptr<SimpleEntryCloseResults> results = - std::make_unique<SimpleEntryCloseResults>(); + auto results = std::make_unique<SimpleEntryCloseResults>(); if (synchronous_entry_) { OnceClosure task = base::BindOnce( &SimpleSynchronousEntry::Close, base::Unretained(synchronous_entry_), @@ -1049,10 +1044,9 @@ int SimpleEntryImpl::ReadDataInternal(bool sync_possible, read_req.request_verify_crc = !have_written_[stream_index]; } - std::unique_ptr<SimpleSynchronousEntry::ReadResult> result = - std::make_unique<SimpleSynchronousEntry::ReadResult>(); - std::unique_ptr<SimpleEntryStat> entry_stat(new SimpleEntryStat( - last_used_, last_modified_, data_size_, sparse_data_size_)); + auto result = std::make_unique<SimpleSynchronousEntry::ReadResult>(); + auto entry_stat = std::make_unique<SimpleEntryStat>( + last_used_, last_modified_, data_size_, sparse_data_size_); OnceClosure task = base::BindOnce( &SimpleSynchronousEntry::ReadData, base::Unretained(synchronous_entry_), read_req, entry_stat.get(), base::RetainedRef(buf), result.get()); @@ -1139,8 +1133,8 @@ void SimpleEntryImpl::WriteDataInternal(int stream_index, } // |entry_stat| needs to be initialized before modifying |data_size_|. - std::unique_ptr<SimpleEntryStat> entry_stat(new SimpleEntryStat( - last_used_, last_modified_, data_size_, sparse_data_size_)); + auto entry_stat = std::make_unique<SimpleEntryStat>( + last_used_, last_modified_, data_size_, sparse_data_size_); if (truncate) { data_size_[stream_index] = offset + buf_len; } else { @@ -1148,8 +1142,7 @@ void SimpleEntryImpl::WriteDataInternal(int stream_index, GetDataSize(stream_index)); } - std::unique_ptr<SimpleSynchronousEntry::WriteResult> write_result = - std::make_unique<SimpleSynchronousEntry::WriteResult>(); + auto write_result = std::make_unique<SimpleSynchronousEntry::WriteResult>(); // Since we don't know the correct values for |last_used_| and // |last_modified_| yet, we make this approximation. @@ -1212,8 +1205,8 @@ void SimpleEntryImpl::ReadSparseDataInternal( DCHECK_EQ(STATE_READY, state_); state_ = STATE_IO_PENDING; - std::unique_ptr<int> result(new int()); - std::unique_ptr<base::Time> last_used(new base::Time()); + auto result = std::make_unique<int>(); + auto last_used = std::make_unique<base::Time>(); OnceClosure task = base::BindOnce( &SimpleSynchronousEntry::ReadSparseData, base::Unretained(synchronous_entry_), @@ -1263,12 +1256,12 @@ void SimpleEntryImpl::WriteSparseDataInternal( max_sparse_data_size = max_cache_size / kMaxSparseDataSizeDivisor; } - std::unique_ptr<SimpleEntryStat> entry_stat(new SimpleEntryStat( - last_used_, last_modified_, data_size_, sparse_data_size_)); + auto entry_stat = std::make_unique<SimpleEntryStat>( + last_used_, last_modified_, data_size_, sparse_data_size_); last_used_ = last_modified_ = base::Time::Now(); - std::unique_ptr<int> result(new int()); + auto result = std::make_unique<int>(); OnceClosure task = base::BindOnce( &SimpleSynchronousEntry::WriteSparseData, base::Unretained(synchronous_entry_), @@ -1405,8 +1398,8 @@ void SimpleEntryImpl::CreationOperationComplete( // If this is a successful creation (rather than open), mark all streams to be // saved on close. if (in_results->created) { - for (int i = 0; i < kSimpleEntryStreamCount; ++i) - have_written_[i] = true; + for (bool& have_written : have_written_) + have_written = true; } // Make sure to keep the index up-to-date. We likely already did this when @@ -1460,9 +1453,15 @@ void SimpleEntryImpl::CreationOperationComplete( net_log_.AddEvent(end_event_type); + const bool created = in_results->created; + + // We need to release `in_results` before going out of scope, because + // `operation_runner` destruction might call a close operation, that will + // ultimately release `in_results->sync_entry`, and thus leading to having a + // dangling pointer here. + in_results = nullptr; if (result_state == SimpleEntryOperation::ENTRY_NEEDS_CALLBACK) { - ReturnEntryToCallerAsync(!in_results->created, - std::move(completion_callback)); + ReturnEntryToCallerAsync(!created, std::move(completion_callback)); } } @@ -1657,9 +1656,8 @@ void SimpleEntryImpl::UpdateDataFromEntryStat( int64_t SimpleEntryImpl::GetDiskUsage() const { int64_t file_size = 0; - for (int i = 0; i < kSimpleEntryStreamCount; ++i) { - file_size += - simple_util::GetFileSizeFromDataSize(key_.size(), data_size_[i]); + for (int data_size : data_size_) { + file_size += simple_util::GetFileSizeFromDataSize(key_.size(), data_size); } file_size += sparse_data_size_; return file_size; diff --git a/chromium/net/disk_cache/simple/simple_file_tracker.cc b/chromium/net/disk_cache/simple/simple_file_tracker.cc index 45a783052a3..7560a8622cc 100644 --- a/chromium/net/disk_cache/simple/simple_file_tracker.cc +++ b/chromium/net/disk_cache/simple/simple_file_tracker.cc @@ -63,7 +63,7 @@ void SimpleFileTracker::Register(const SimpleSynchronousEntry* owner, } if (!owners_files) { - candidates.emplace_back(new TrackedFiles()); + candidates.emplace_back(std::make_unique<TrackedFiles>()); owners_files = candidates.back().get(); owners_files->owner = owner; owners_files->key = owner->entry_file_key(); diff --git a/chromium/net/disk_cache/simple/simple_file_tracker.h b/chromium/net/disk_cache/simple/simple_file_tracker.h index d9bf2d0682c..3262bd75b00 100644 --- a/chromium/net/disk_cache/simple/simple_file_tracker.h +++ b/chromium/net/disk_cache/simple/simple_file_tracker.h @@ -75,7 +75,7 @@ class NET_EXPORT_PRIVATE SimpleFileTracker { }; struct EntryFileKey { - EntryFileKey() {} + EntryFileKey() = default; explicit EntryFileKey(uint64_t hash) : entry_hash(hash) {} uint64_t entry_hash = 0; @@ -90,7 +90,7 @@ class NET_EXPORT_PRIVATE SimpleFileTracker { // The default limit here is half of what's available on our target OS where // Chrome has the lowest limit. - SimpleFileTracker(int file_limit = 512); + explicit SimpleFileTracker(int file_limit = 512); SimpleFileTracker(const SimpleFileTracker&) = delete; SimpleFileTracker& operator=(const SimpleFileTracker&) = delete; diff --git a/chromium/net/disk_cache/simple/simple_file_tracker_unittest.cc b/chromium/net/disk_cache/simple/simple_file_tracker_unittest.cc index ec501d7d631..0708ac9f31c 100644 --- a/chromium/net/disk_cache/simple/simple_file_tracker_unittest.cc +++ b/chromium/net/disk_cache/simple/simple_file_tracker_unittest.cc @@ -38,7 +38,8 @@ class SimpleFileTrackerTest : public DiskCacheTest { // create/delete SimpleSynchronousEntry objects. class SyncEntryDeleter { public: - SyncEntryDeleter(SimpleFileTrackerTest* fixture) : fixture_(fixture) {} + explicit SyncEntryDeleter(SimpleFileTrackerTest* fixture) + : fixture_(fixture) {} void operator()(SimpleSynchronousEntry* entry) { fixture_->DeleteSyncEntry(entry); } @@ -230,8 +231,8 @@ TEST_F(SimpleFileTrackerTest, PointerStability) { borrow->Write(0, msg.data(), msg.size())); } - for (int i = 0; i < kEntries; ++i) - file_tracker_.Close(entries[i].get(), SimpleFileTracker::SubFile::FILE_0); + for (const auto& entry : entries) + file_tracker_.Close(entry.get(), SimpleFileTracker::SubFile::FILE_0); // Verify the file. std::string verify; diff --git a/chromium/net/disk_cache/simple/simple_index.cc b/chromium/net/disk_cache/simple/simple_index.cc index 044df008225..10f9e62153e 100644 --- a/chromium/net/disk_cache/simple/simple_index.cc +++ b/chromium/net/disk_cache/simple/simple_index.cc @@ -193,10 +193,8 @@ SimpleIndex::~SimpleIndex() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Fail all callbacks waiting for the index to come up. - for (auto it = to_run_when_initialized_.begin(), - end = to_run_when_initialized_.end(); - it != end; ++it) { - std::move(*it).Run(net::ERR_ABORTED); + for (auto& callback : to_run_when_initialized_) { + std::move(callback).Run(net::ERR_ABORTED); } } @@ -215,12 +213,13 @@ void SimpleIndex::Initialize(base::Time cache_mtime) { } #endif - SimpleIndexLoadResult* load_result = new SimpleIndexLoadResult(); - std::unique_ptr<SimpleIndexLoadResult> load_result_scoped(load_result); - base::OnceClosure reply = + auto load_result = std::make_unique<SimpleIndexLoadResult>(); + auto* load_result_ptr = load_result.get(); + index_file_->LoadIndexEntries( + cache_mtime, base::BindOnce(&SimpleIndex::MergeInitializingSet, AsWeakPtr(), - std::move(load_result_scoped)); - index_file_->LoadIndexEntries(cache_mtime, std::move(reply), load_result); + std::move(load_result)), + load_result_ptr); } void SimpleIndex::SetMaxSize(uint64_t max_bytes) { @@ -258,7 +257,7 @@ std::unique_ptr<SimpleIndex::HashList> SimpleIndex::GetEntriesBetween( end_time += EntryMetadata::GetUpperEpsilonForTimeComparisons(); DCHECK(end_time >= initial_time); - std::unique_ptr<HashList> ret_hashes(new HashList()); + auto ret_hashes = std::make_unique<HashList>(); for (const auto& entry : entries_set_) { const EntryMetadata& metadata = entry.second; base::Time entry_time = metadata.GetLastUsedTime(); @@ -546,25 +545,23 @@ void SimpleIndex::MergeInitializingSet( EntrySet* index_file_entries = &load_result->entries; - for (auto it = removed_entries_.begin(); it != removed_entries_.end(); ++it) { - index_file_entries->erase(*it); + for (uint64_t removed_entry : removed_entries_) { + index_file_entries->erase(removed_entry); } removed_entries_.clear(); - for (EntrySet::const_iterator it = entries_set_.begin(); - it != entries_set_.end(); ++it) { - const uint64_t entry_hash = it->first; + for (const auto& it : entries_set_) { + const uint64_t entry_hash = it.first; std::pair<EntrySet::iterator, bool> insert_result = index_file_entries->insert(EntrySet::value_type(entry_hash, EntryMetadata())); EntrySet::iterator& possibly_inserted_entry = insert_result.first; - possibly_inserted_entry->second = it->second; + possibly_inserted_entry->second = it.second; } uint64_t merged_cache_size = 0; - for (auto it = index_file_entries->begin(); it != index_file_entries->end(); - ++it) { - merged_cache_size += it->second.GetEntrySize(); + for (const auto& index_file_entry : *index_file_entries) { + merged_cache_size += index_file_entry.second.GetEntrySize(); } entries_set_.swap(*index_file_entries); @@ -587,10 +584,9 @@ void SimpleIndex::MergeInitializingSet( static_cast<base::HistogramBase::Sample>(max_size_ / kBytesInKb)); // Run all callbacks waiting for the index to come up. - for (auto it = to_run_when_initialized_.begin(), - end = to_run_when_initialized_.end(); - it != end; ++it) { - task_runner_->PostTask(FROM_HERE, base::BindOnce(std::move(*it), net::OK)); + for (auto& callback : to_run_when_initialized_) { + task_runner_->PostTask(FROM_HERE, + base::BindOnce(std::move(callback), net::OK)); } to_run_when_initialized_.clear(); } diff --git a/chromium/net/disk_cache/simple/simple_index_delegate.h b/chromium/net/disk_cache/simple/simple_index_delegate.h index 0ff77c29a08..00e02a8c987 100644 --- a/chromium/net/disk_cache/simple/simple_index_delegate.h +++ b/chromium/net/disk_cache/simple/simple_index_delegate.h @@ -16,7 +16,7 @@ namespace disk_cache { class NET_EXPORT_PRIVATE SimpleIndexDelegate { public: - virtual ~SimpleIndexDelegate() {} + virtual ~SimpleIndexDelegate() = default; // Dooms all entries in |entries|, calling |callback| with the result // asynchronously. |entries| is mutated in an undefined way by this call, diff --git a/chromium/net/disk_cache/simple/simple_index_file.cc b/chromium/net/disk_cache/simple/simple_index_file.cc index c60d833fe4d..bc36558d2cc 100644 --- a/chromium/net/disk_cache/simple/simple_index_file.cc +++ b/chromium/net/disk_cache/simple/simple_index_file.cc @@ -518,9 +518,9 @@ std::unique_ptr<base::Pickle> SimpleIndexFile::Serialize( std::unique_ptr<base::Pickle> pickle = std::make_unique<SimpleIndexPickle>(); index_metadata.Serialize(pickle.get()); - for (auto it = entries.begin(); it != entries.end(); ++it) { - pickle->WriteUInt64(it->first); - it->second.Serialize(cache_type, pickle.get()); + for (const auto& entry : entries) { + pickle->WriteUInt64(entry.first); + entry.second.Serialize(cache_type, pickle.get()); } return pickle; } diff --git a/chromium/net/disk_cache/simple/simple_index_file_unittest.cc b/chromium/net/disk_cache/simple/simple_index_file_unittest.cc index ebf2de335e8..7802c98675f 100644 --- a/chromium/net/disk_cache/simple/simple_index_file_unittest.cc +++ b/chromium/net/disk_cache/simple/simple_index_file_unittest.cc @@ -493,8 +493,8 @@ TEST_F(SimpleIndexFileTest, WriteThenLoadIndex) { EXPECT_FALSE(load_index_result.flush_required); EXPECT_EQ(kNumHashes, load_index_result.entries.size()); - for (size_t i = 0; i < kNumHashes; ++i) - EXPECT_EQ(1U, load_index_result.entries.count(kHashes[i])); + for (uint64_t hash : kHashes) + EXPECT_EQ(1U, load_index_result.entries.count(hash)); } TEST_F(SimpleIndexFileTest, LoadCorruptIndex) { @@ -603,10 +603,10 @@ TEST_F(SimpleIndexFileTest, SimpleCacheUpgrade) { /*file_tracker=*/nullptr, 0, net::DISK_CACHE, /*net_log=*/nullptr); net::TestCompletionCallback cb; - int rv = simple_cache->Init(cb.callback()); - EXPECT_THAT(cb.GetResult(rv), IsOk()); + simple_cache->Init(cb.callback()); + EXPECT_THAT(cb.WaitForResult(), IsOk()); simple_cache->index()->ExecuteWhenReady(cb.callback()); - rv = cb.WaitForResult(); + int rv = cb.WaitForResult(); EXPECT_THAT(rv, IsOk()); simple_cache.reset(); cleanup_tracker = nullptr; diff --git a/chromium/net/disk_cache/simple/simple_index_unittest.cc b/chromium/net/disk_cache/simple/simple_index_unittest.cc index 92cde3b83ed..34d2266fed9 100644 --- a/chromium/net/disk_cache/simple/simple_index_unittest.cc +++ b/chromium/net/disk_cache/simple/simple_index_unittest.cc @@ -114,8 +114,7 @@ class SimpleIndexTest : public net::TestWithTaskEnvironment, } void SetUp() override { - std::unique_ptr<MockSimpleIndexFile> index_file( - new MockSimpleIndexFile(CacheType())); + auto index_file = std::make_unique<MockSimpleIndexFile>(CacheType()); index_file_ = index_file->AsWeakPtr(); index_ = std::make_unique<SimpleIndex>(/* io_thread = */ nullptr, @@ -263,13 +262,13 @@ TEST_F(SimpleIndexTest, IndexSizeCorrectOnMerge) { index()->UpdateEntrySize(hashes_.at<4>(), 4u * kSizeResolution); EXPECT_EQ(9u * kSizeResolution, index()->cache_size_); { - std::unique_ptr<SimpleIndexLoadResult> result(new SimpleIndexLoadResult()); + auto result = std::make_unique<SimpleIndexLoadResult>(); result->did_load = true; index()->MergeInitializingSet(std::move(result)); } EXPECT_EQ(9u * kSizeResolution, index()->cache_size_); { - std::unique_ptr<SimpleIndexLoadResult> result(new SimpleIndexLoadResult()); + auto result = std::make_unique<SimpleIndexLoadResult>(); result->did_load = true; const uint64_t new_hash_key = hashes_.at<11>(); result->entries.insert(std::make_pair( diff --git a/chromium/net/disk_cache/simple/simple_net_log_parameters.cc b/chromium/net/disk_cache/simple/simple_net_log_parameters.cc index ee3241ba989..b6d06026193 100644 --- a/chromium/net/disk_cache/simple/simple_net_log_parameters.cc +++ b/chromium/net/disk_cache/simple/simple_net_log_parameters.cc @@ -20,20 +20,20 @@ namespace { base::Value NetLogSimpleEntryConstructionParams( const disk_cache::SimpleEntryImpl* entry) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("entry_hash", - base::StringPrintf("%#016" PRIx64, entry->entry_hash())); - return dict; + base::Value::Dict dict; + dict.Set("entry_hash", + base::StringPrintf("%#016" PRIx64, entry->entry_hash())); + return base::Value(std::move(dict)); } base::Value NetLogSimpleEntryCreationParams( const disk_cache::SimpleEntryImpl* entry, int net_error) { - base::Value dict(base::Value::Type::DICTIONARY); - dict.SetIntKey("net_error", net_error); + base::Value::Dict dict; + dict.Set("net_error", net_error); if (net_error == net::OK) - dict.SetStringKey("key", entry->key()); - return dict; + dict.Set("key", entry->key()); + return base::Value(std::move(dict)); } } // namespace diff --git a/chromium/net/disk_cache/simple/simple_synchronous_entry.cc b/chromium/net/disk_cache/simple/simple_synchronous_entry.cc index 4102a28ba2f..8ac5d028cdf 100644 --- a/chromium/net/disk_cache/simple/simple_synchronous_entry.cc +++ b/chromium/net/disk_cache/simple/simple_synchronous_entry.cc @@ -1067,8 +1067,8 @@ void SimpleSynchronousEntry::Close( base::ElapsedTimer close_time; DCHECK(stream_0_data); - for (auto it = crc32s_to_write->begin(); it != crc32s_to_write->end(); ++it) { - const int stream_index = it->index; + for (auto& crc_record : *crc32s_to_write) { + const int stream_index = crc_record.index; const int file_index = GetFileIndexFromStreamIndex(stream_index); if (empty_file_omitted_[file_index]) continue; @@ -1103,10 +1103,10 @@ void SimpleSynchronousEntry::Close( // Re-compute stream 0 CRC if the data got changed (we may be here even // if it didn't change if stream 0's position on disk got changed due to // stream 1 write). - if (!it->has_crc32) { - it->data_crc32 = + if (!crc_record.has_crc32) { + crc_record.data_crc32 = simple_util::Crc32(stream_0_data->data(), entry_stat.data_size(0)); - it->has_crc32 = true; + crc_record.has_crc32 = true; } out_results->estimated_trailer_prefetch_size = @@ -1117,11 +1117,11 @@ void SimpleSynchronousEntry::Close( eof_record.stream_size = entry_stat.data_size(stream_index); eof_record.final_magic_number = kSimpleFinalMagicNumber; eof_record.flags = 0; - if (it->has_crc32) + if (crc_record.has_crc32) eof_record.flags |= SimpleFileEOF::FLAG_HAS_CRC32; if (stream_index == 0) eof_record.flags |= SimpleFileEOF::FLAG_HAS_KEY_SHA256; - eof_record.data_crc32 = it->data_crc32; + eof_record.data_crc32 = crc_record.data_crc32; int eof_offset = entry_stat.GetEOFOffsetInFile(key_.size(), stream_index); // If stream 0 changed size, the file needs to be resized, otherwise the // next open will yield wrong stream sizes. On stream 1 and stream 2 proper @@ -1179,8 +1179,9 @@ SimpleSynchronousEntry::SimpleSynchronousEntry( file_tracker_(file_tracker), unbound_file_operations_(std::move(unbound_file_operations)), trailer_prefetch_size_(trailer_prefetch_size) { - for (int i = 0; i < kSimpleEntryNormalFileCount; ++i) - empty_file_omitted_[i] = false; + for (bool& empty_file_omitted : empty_file_omitted_) { + empty_file_omitted = false; + } } SimpleSynchronousEntry::~SimpleSynchronousEntry() { diff --git a/chromium/net/disk_cache/simple/simple_test_util.cc b/chromium/net/disk_cache/simple/simple_test_util.cc index 0251f3ad914..d62320e0690 100644 --- a/chromium/net/disk_cache/simple/simple_test_util.cc +++ b/chromium/net/disk_cache/simple/simple_test_util.cc @@ -10,8 +10,7 @@ #include "net/disk_cache/simple/simple_entry_format.h" #include "net/disk_cache/simple/simple_util.h" -namespace disk_cache { -namespace simple_util { +namespace disk_cache::simple_util { using base::File; using base::FilePath; @@ -131,5 +130,4 @@ bool CorruptStream0LengthFromEntry(const std::string& key, return true; } -} // namespace simple_util -} // namespace disk_cache +} // namespace disk_cache::simple_util diff --git a/chromium/net/disk_cache/simple/simple_test_util.h b/chromium/net/disk_cache/simple/simple_test_util.h index 36af9285b9c..701e1eb3a85 100644 --- a/chromium/net/disk_cache/simple/simple_test_util.h +++ b/chromium/net/disk_cache/simple/simple_test_util.h @@ -15,8 +15,7 @@ namespace base { class FilePath; } -namespace disk_cache { -namespace simple_util { +namespace disk_cache::simple_util { // Immutable array with compile-time bound-checking. template <typename T, size_t Size> @@ -24,7 +23,8 @@ class ImmutableArray { public: static const size_t size = Size; - ImmutableArray(const base::RepeatingCallback<T(size_t index)>& initializer) { + explicit ImmutableArray( + const base::RepeatingCallback<T(size_t index)>& initializer) { for (size_t i = 0; i < size; ++i) data_[i] = initializer.Run(i); } @@ -55,7 +55,6 @@ bool CorruptKeySHA256FromEntry(const std::string& key, bool CorruptStream0LengthFromEntry(const std::string& key, const base::FilePath& cache_path); -} // namespace simple_util -} // namespace disk_cache +} // namespace disk_cache::simple_util #endif // NET_DISK_CACHE_SIMPLE_SIMPLE_TEST_UTIL_H_ diff --git a/chromium/net/disk_cache/simple/simple_util.cc b/chromium/net/disk_cache/simple/simple_util.cc index d9fc89080fc..ed0b382221d 100644 --- a/chromium/net/disk_cache/simple/simple_util.cc +++ b/chromium/net/disk_cache/simple/simple_util.cc @@ -25,9 +25,7 @@ const size_t kEntryHashKeyAsHexStringSize = 2 * sizeof(uint64_t); } // namespace -namespace disk_cache { - -namespace simple_util { +namespace disk_cache::simple_util { std::string ConvertEntryHashKeyToHexString(uint64_t hash_key) { const std::string hash_key_str = base::StringPrintf("%016" PRIx64, hash_key); @@ -115,6 +113,4 @@ uint32_t IncrementalCrc32(uint32_t previous_crc, const char* data, int length) { return crc32(previous_crc, reinterpret_cast<const Bytef*>(data), length); } -} // namespace simple_util - -} // namespace disk_cache +} // namespace disk_cache::simple_util diff --git a/chromium/net/disk_cache/simple/simple_util.h b/chromium/net/disk_cache/simple/simple_util.h index b74632139ae..6860e39350d 100644 --- a/chromium/net/disk_cache/simple/simple_util.h +++ b/chromium/net/disk_cache/simple/simple_util.h @@ -17,9 +17,7 @@ namespace base { class FilePath; } -namespace disk_cache { - -namespace simple_util { +namespace disk_cache::simple_util { NET_EXPORT_PRIVATE std::string ConvertEntryHashKeyToHexString( uint64_t hash_key); @@ -83,8 +81,6 @@ uint32_t Crc32(const char* data, int length); uint32_t IncrementalCrc32(uint32_t previous_crc, const char* data, int length); -} // namespace simple_util - -} // namespace disk_cache +} // namespace disk_cache::simple_util #endif // NET_DISK_CACHE_SIMPLE_SIMPLE_UTIL_H_ diff --git a/chromium/net/disk_cache/simple/simple_util_posix.cc b/chromium/net/disk_cache/simple/simple_util_posix.cc index 129b9ee7cd7..0a72be27c39 100644 --- a/chromium/net/disk_cache/simple/simple_util_posix.cc +++ b/chromium/net/disk_cache/simple/simple_util_posix.cc @@ -6,12 +6,10 @@ #include "base/files/file_util.h" -namespace disk_cache { -namespace simple_util { +namespace disk_cache::simple_util { bool SimpleCacheDeleteFile(const base::FilePath& path) { return base::DeleteFile(path); } -} // namespace simple_util -} // namespace disk_cache +} // namespace disk_cache::simple_util |