diff options
author | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2018-10-24 11:30:15 +0200 |
---|---|---|
committer | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2018-10-30 12:56:19 +0000 |
commit | 6036726eb981b6c4b42047513b9d3f4ac865daac (patch) | |
tree | 673593e70678e7789766d1f732eb51f613a2703b /chromium/storage/browser | |
parent | 466052c4e7c052268fd931888cd58961da94c586 (diff) | |
download | qtwebengine-chromium-6036726eb981b6c4b42047513b9d3f4ac865daac.tar.gz |
BASELINE: Update Chromium to 70.0.3538.78
Change-Id: Ie634710bf039e26c1957f4ae45e101bd4c434ae7
Reviewed-by: Michael BrĂ¼ning <michael.bruning@qt.io>
Diffstat (limited to 'chromium/storage/browser')
108 files changed, 2009 insertions, 1666 deletions
diff --git a/chromium/storage/browser/BUILD.gn b/chromium/storage/browser/BUILD.gn index 4b2d919699b..4e5f9628c9c 100644 --- a/chromium/storage/browser/BUILD.gn +++ b/chromium/storage/browser/BUILD.gn @@ -112,6 +112,8 @@ component("browser") { "fileapi/file_system_usage_cache.h", "fileapi/file_writer_delegate.cc", "fileapi/file_writer_delegate.h", + "fileapi/file_writer_impl.cc", + "fileapi/file_writer_impl.h", "fileapi/isolated_context.cc", "fileapi/isolated_context.h", "fileapi/isolated_file_system_backend.cc", @@ -175,6 +177,7 @@ component("browser") { "quota/quota_client.h", "quota/quota_database.cc", "quota/quota_database.h", + "quota/quota_macros.h", "quota/quota_manager.cc", "quota/quota_manager.h", "quota/quota_manager_proxy.cc", @@ -274,6 +277,7 @@ source_set("unittests") { "fileapi/file_system_url_unittest.cc", "fileapi/file_system_usage_cache_unittest.cc", "fileapi/file_writer_delegate_unittest.cc", + "fileapi/file_writer_impl_unittest.cc", "fileapi/isolated_context_unittest.cc", "fileapi/local_file_stream_reader_unittest.cc", "fileapi/local_file_stream_writer_unittest.cc", @@ -311,6 +315,7 @@ source_set("unittests") { "//sql:test_support", "//testing/gtest", "//third_party/leveldatabase", + "//third_party/sqlite", ] } diff --git a/chromium/storage/browser/blob/blob_builder_from_stream.cc b/chromium/storage/browser/blob/blob_builder_from_stream.cc index 2f31fdce9a0..1dac8b1d2fe 100644 --- a/chromium/storage/browser/blob/blob_builder_from_stream.cc +++ b/chromium/storage/browser/blob/blob_builder_from_stream.cc @@ -7,7 +7,7 @@ #include "base/containers/span.h" #include "base/guid.h" #include "base/metrics/histogram_macros.h" -#include "base/task_scheduler/post_task.h" +#include "base/task/post_task.h" #include "storage/browser/blob/blob_data_item.h" #include "storage/browser/blob/blob_storage_context.h" #include "storage/browser/blob/shareable_file_reference.h" diff --git a/chromium/storage/browser/blob/blob_builder_from_stream_unittest.cc b/chromium/storage/browser/blob/blob_builder_from_stream_unittest.cc index 3c8f167c95d..4940825bde5 100644 --- a/chromium/storage/browser/blob/blob_builder_from_stream_unittest.cc +++ b/chromium/storage/browser/blob/blob_builder_from_stream_unittest.cc @@ -8,8 +8,8 @@ #include "base/files/scoped_temp_dir.h" #include "base/rand_util.h" #include "base/run_loop.h" -#include "base/task_scheduler/post_task.h" -#include "base/task_scheduler/task_scheduler.h" +#include "base/task/post_task.h" +#include "base/task/task_scheduler/task_scheduler.h" #include "base/test/bind_test_util.h" #include "base/test/scoped_task_environment.h" #include "mojo/public/cpp/bindings/associated_binding.h" diff --git a/chromium/storage/browser/blob/blob_impl_unittest.cc b/chromium/storage/browser/blob/blob_impl_unittest.cc index c903d408343..3295c4eb257 100644 --- a/chromium/storage/browser/blob/blob_impl_unittest.cc +++ b/chromium/storage/browser/blob/blob_impl_unittest.cc @@ -7,7 +7,7 @@ #include <memory> #include "base/run_loop.h" -#include "base/task_scheduler/post_task.h" +#include "base/task/post_task.h" #include "base/test/scoped_task_environment.h" #include "mojo/public/cpp/system/data_pipe_drainer.h" #include "net/base/net_errors.h" diff --git a/chromium/storage/browser/blob/blob_reader.cc b/chromium/storage/browser/blob/blob_reader.cc index 9cf4fe38075..eca4a83265d 100644 --- a/chromium/storage/browser/blob/blob_reader.cc +++ b/chromium/storage/browser/blob/blob_reader.cc @@ -14,8 +14,9 @@ #include "base/bind.h" #include "base/callback_helpers.h" +#include "base/debug/alias.h" #include "base/memory/ptr_util.h" -#include "base/task_scheduler/post_task.h" +#include "base/task/post_task.h" #include "base/time/time.h" #include "base/trace_event/trace_event.h" #include "net/base/io_buffer.h" @@ -89,6 +90,7 @@ BlobReader::BlobReader(const BlobDataHandle* blob_handle) BlobReader::~BlobReader() = default; BlobReader::Status BlobReader::CalculateSize(net::CompletionOnceCallback done) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!total_size_calculated_); DCHECK(size_callback_.is_null()); if (!blob_handle_.get()) @@ -110,6 +112,8 @@ BlobReader::Status BlobReader::CalculateSize(net::CompletionOnceCallback done) { } bool BlobReader::has_side_data() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (!blob_data_.get()) return false; const auto& items = blob_data_->items(); @@ -127,6 +131,8 @@ bool BlobReader::has_side_data() const { } BlobReader::Status BlobReader::ReadSideData(const StatusCallback& done) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (!has_side_data()) return ReportError(net::ERR_FILE_NOT_FOUND); const BlobDataItem* item = blob_data_->items()[0].get(); @@ -151,6 +157,7 @@ BlobReader::Status BlobReader::ReadSideData(const StatusCallback& done) { void BlobReader::DidReadDiskCacheEntrySideData(const StatusCallback& done, int expected_size, int result) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (result >= 0) { DCHECK_EQ(expected_size, result); if (result > 0) @@ -163,6 +170,8 @@ void BlobReader::DidReadDiskCacheEntrySideData(const StatusCallback& done, } BlobReader::Status BlobReader::SetReadRange(uint64_t offset, uint64_t length) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (!blob_handle_.get()) return ReportError(net::ERR_FILE_NOT_FOUND); if (blob_handle_->IsBroken()) { @@ -202,6 +211,7 @@ BlobReader::Status BlobReader::Read(net::IOBuffer* buffer, size_t dest_size, int* bytes_read, net::CompletionOnceCallback done) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(bytes_read); DCHECK_GE(remaining_bytes_, 0ul); DCHECK(read_callback_.is_null()); @@ -216,6 +226,14 @@ BlobReader::Status BlobReader::Read(net::IOBuffer* buffer, if (net_error_ != net::OK) return Status::NET_ERROR; + // TODO(https://crbug.com/864351): Temporary diagnostics. + base::debug::Alias(&buffer); + base::debug::Alias(&dest_size); + uint64_t remaining_bytes = remaining_bytes_; + base::debug::Alias(&remaining_bytes); + const char* buffer_data = buffer->data(); + base::debug::Alias(&buffer_data); + DCHECK_GE(dest_size, 0ul); if (remaining_bytes_ < static_cast<uint64_t>(dest_size)) dest_size = static_cast<int>(remaining_bytes_); @@ -238,11 +256,15 @@ BlobReader::Status BlobReader::Read(net::IOBuffer* buffer, } void BlobReader::Kill() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DeleteCurrentFileReader(); weak_factory_.InvalidateWeakPtrs(); } bool BlobReader::IsInMemory() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (blob_handle_ && blob_handle_->IsBeingBuilt()) { return false; } @@ -259,6 +281,8 @@ bool BlobReader::IsInMemory() const { void BlobReader::InvalidateCallbacksAndDone(int net_error, net::CompletionOnceCallback done) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + net_error_ = net_error; weak_factory_.InvalidateWeakPtrs(); size_callback_.Reset(); @@ -268,12 +292,16 @@ void BlobReader::InvalidateCallbacksAndDone(int net_error, } BlobReader::Status BlobReader::ReportError(int net_error) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + net_error_ = net_error; return Status::NET_ERROR; } void BlobReader::AsyncCalculateSize(net::CompletionOnceCallback done, BlobStatus status) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (BlobStatusIsError(status)) { InvalidateCallbacksAndDone(ConvertBlobErrorToNetError(status), std::move(done)); @@ -298,6 +326,7 @@ void BlobReader::AsyncCalculateSize(net::CompletionOnceCallback done, BlobReader::Status BlobReader::CalculateSizeImpl( net::CompletionOnceCallback* done) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!total_size_calculated_); DCHECK(size_callback_.is_null()); @@ -344,6 +373,8 @@ BlobReader::Status BlobReader::CalculateSizeImpl( } bool BlobReader::AddItemLength(size_t index, uint64_t item_length) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (item_length > std::numeric_limits<uint64_t>::max() - total_size_) return false; @@ -357,6 +388,7 @@ bool BlobReader::AddItemLength(size_t index, uint64_t item_length) { bool BlobReader::ResolveFileItemLength(const BlobDataItem& item, int64_t total_length, uint64_t* output_length) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(IsFileType(item.type())); DCHECK(output_length); uint64_t file_length = total_length; @@ -380,6 +412,8 @@ bool BlobReader::ResolveFileItemLength(const BlobDataItem& item, } void BlobReader::DidGetFileItemLength(size_t index, int64_t result) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + // Do nothing if we have encountered an error. if (net_error_) return; @@ -408,6 +442,7 @@ void BlobReader::DidGetFileItemLength(size_t index, int64_t result) { } void BlobReader::DidCountSize() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!net_error_); total_size_calculated_ = true; remaining_bytes_ = total_size_; @@ -417,6 +452,8 @@ void BlobReader::DidCountSize() { } BlobReader::Status BlobReader::ReadLoop(int* bytes_read) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + // Read until we encounter an error or could not get the data immediately. while (remaining_bytes_ > 0 && read_buf_->BytesRemaining() > 0) { Status read_status = ReadItem(); @@ -430,6 +467,12 @@ BlobReader::Status BlobReader::ReadLoop(int* bytes_read) { } BlobReader::Status BlobReader::ReadItem() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + // TODO(https://crbug.com/864351): Temporary diagnostics. + uint64_t remaining_bytes = remaining_bytes_; + base::debug::Alias(&remaining_bytes); + // Are we done with reading all the blob data? if (remaining_bytes_ == 0) return Status::DONE; @@ -451,7 +494,29 @@ BlobReader::Status BlobReader::ReadItem() { // Do the reading. const BlobDataItem& item = *items.at(current_item_index_); + + // TODO(https://crbug.com/864351): Temporary diagnostics. + const BlobDataItem* item_ptr = &item; + base::debug::Alias(&item_ptr); + uint64_t item_offset = item.offset(); + base::debug::Alias(&item_offset); + uint64_t item_length = item.length(); + base::debug::Alias(&item_length); + int buf_bytes_remaining = read_buf_->BytesRemaining(); + base::debug::Alias(&buf_bytes_remaining); + base::debug::Alias(&bytes_to_read); + if (item.type() == BlobDataItem::Type::kBytes) { + // TODO(https://crbug.com/864351): Temporary diagnostics. + const char* item_bytes = item.bytes().data(); + base::debug::Alias(&item_bytes); + const char* read_buf_bytes = read_buf_->data(); + base::debug::Alias(&read_buf_bytes); + int read_buf_size = read_buf_->size(); + base::debug::Alias(&read_buf_size); + int read_buf_remaining = read_buf_->BytesRemaining(); + base::debug::Alias(&read_buf_remaining); + ReadBytesItem(item, bytes_to_read); return Status::DONE; } @@ -470,6 +535,8 @@ BlobReader::Status BlobReader::ReadItem() { } void BlobReader::AdvanceItem() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + // Close the file if the current item is a file. DeleteCurrentFileReader(); @@ -479,6 +546,7 @@ void BlobReader::AdvanceItem() { } void BlobReader::AdvanceBytesRead(int result) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK_GT(result, 0); // Do we finish reading the current item? @@ -496,6 +564,7 @@ void BlobReader::AdvanceBytesRead(int result) { } void BlobReader::ReadBytesItem(const BlobDataItem& item, int bytes_to_read) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); TRACE_EVENT1("Blob", "BlobReader::ReadBytesItem", "uuid", blob_data_->uuid()); DCHECK_GE(read_buf_->BytesRemaining(), bytes_to_read); @@ -508,6 +577,7 @@ void BlobReader::ReadBytesItem(const BlobDataItem& item, int bytes_to_read) { BlobReader::Status BlobReader::ReadFileItem(FileStreamReader* reader, int bytes_to_read) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!io_pending_) << "Can't begin IO while another IO operation is pending."; DCHECK_GE(read_buf_->BytesRemaining(), bytes_to_read); @@ -529,12 +599,15 @@ BlobReader::Status BlobReader::ReadFileItem(FileStreamReader* reader, } void BlobReader::DidReadFile(int result) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); TRACE_EVENT_ASYNC_END1("Blob", "BlobRequest::ReadFileItem", this, "uuid", blob_data_->uuid()); DidReadItem(result); } void BlobReader::ContinueAsyncReadLoop() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + int bytes_read = 0; Status read_status = ReadLoop(&bytes_read); switch (read_status) { @@ -556,6 +629,7 @@ void BlobReader::DeleteCurrentFileReader() { BlobReader::Status BlobReader::ReadDiskCacheEntryItem(const BlobDataItem& item, int bytes_to_read) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!io_pending_) << "Can't begin IO while another IO operation is pending."; TRACE_EVENT_ASYNC_BEGIN1("Blob", "BlobRequest::ReadDiskCacheItem", this, @@ -581,6 +655,7 @@ BlobReader::Status BlobReader::ReadDiskCacheEntryItem(const BlobDataItem& item, } void BlobReader::DidReadDiskCacheEntry(int result) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); TRACE_EVENT_ASYNC_END1("Blob", "BlobRequest::ReadDiskCacheItem", this, "uuid", blob_data_->uuid()); if (result > 0) @@ -589,6 +664,7 @@ void BlobReader::DidReadDiskCacheEntry(int result) { } void BlobReader::DidReadItem(int result) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(io_pending_) << "Asynchronous IO completed while IO wasn't pending?"; io_pending_ = false; if (result <= 0) { @@ -600,12 +676,14 @@ void BlobReader::DidReadItem(int result) { } int BlobReader::BytesReadCompleted() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); int bytes_read = read_buf_->BytesConsumed(); read_buf_ = nullptr; return bytes_read; } int BlobReader::ComputeBytesToRead() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); uint64_t current_item_length = item_length_list_[current_item_index_]; uint64_t item_remaining = current_item_length - current_item_offset_; @@ -620,6 +698,8 @@ int BlobReader::ComputeBytesToRead() const { } FileStreamReader* BlobReader::GetOrCreateFileReaderAtIndex(size_t index) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + const auto& items = blob_data_->items(); DCHECK_LT(index, items.size()); const BlobDataItem& item = *items.at(index); @@ -641,6 +721,7 @@ FileStreamReader* BlobReader::GetOrCreateFileReaderAtIndex(size_t index) { std::unique_ptr<FileStreamReader> BlobReader::CreateFileStreamReader( const BlobDataItem& item, uint64_t additional_offset) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(IsFileType(item.type())); switch (item.type()) { @@ -684,6 +765,7 @@ std::unique_ptr<FileStreamReader> BlobReader::CreateFileStreamReader( void BlobReader::SetFileReaderAtIndex( size_t index, std::unique_ptr<FileStreamReader> reader) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (reader) index_to_reader_[index] = std::move(reader); else diff --git a/chromium/storage/browser/blob/blob_reader.h b/chromium/storage/browser/blob/blob_reader.h index 61beacb53be..15f4a0827d0 100644 --- a/chromium/storage/browser/blob/blob_reader.h +++ b/chromium/storage/browser/blob/blob_reader.h @@ -15,6 +15,7 @@ #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" +#include "base/sequence_checker.h" #include "net/base/completion_once_callback.h" #include "storage/browser/storage_browser_export.h" #include "storage/common/blob_storage/blob_storage_constants.h" @@ -94,7 +95,10 @@ class STORAGE_EXPORT BlobReader { Status ReadSideData(const StatusCallback& done); // Returns the side data which has been already read with ReadSideData(). - net::IOBufferWithSize* side_data() const { return side_data_.get(); } + net::IOBufferWithSize* side_data() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return side_data_.get(); + } // Used to set the read position. // * This should be called after CalculateSize and before Read. @@ -124,14 +128,21 @@ class STORAGE_EXPORT BlobReader { // Returns the remaining bytes to be read in the blob. This is populated // after CalculateSize, and is modified by SetReadRange. - uint64_t remaining_bytes() const { return remaining_bytes_; } + uint64_t remaining_bytes() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return remaining_bytes_; + } // Returns the net error code if there was an error. Defaults to net::OK. - int net_error() const { return net_error_; } + int net_error() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return net_error_; + } // Returns the total size of the blob. This is populated after CalculateSize // is called. uint64_t total_size() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(total_size_calculated_); return total_size_; } @@ -144,10 +155,14 @@ class STORAGE_EXPORT BlobReader { BlobReader(const BlobDataHandle* blob_handle); - bool total_size_calculated() const { return total_size_calculated_; } + bool total_size_calculated() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return total_size_calculated_; + } void SetFileStreamProviderForTesting( std::unique_ptr<FileStreamReaderProvider> file_stream_provider) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); file_stream_provider_for_testing_ = std::move(file_stream_provider); } @@ -191,7 +206,7 @@ class STORAGE_EXPORT BlobReader { int BytesReadCompleted(); // Returns a FileStreamReader for a blob item at |index|. - // If the item at |index| is not of file this returns NULL. + // If the item at |index| is not of file this returns nullptr. FileStreamReader* GetOrCreateFileReaderAtIndex(size_t index); // If the reader is null, then this basically performs a delete operation. void SetFileReaderAtIndex(size_t index, @@ -226,6 +241,8 @@ class STORAGE_EXPORT BlobReader { net::CompletionOnceCallback size_callback_; net::CompletionOnceCallback read_callback_; + SEQUENCE_CHECKER(sequence_checker_); + base::WeakPtrFactory<BlobReader> weak_factory_; DISALLOW_COPY_AND_ASSIGN(BlobReader); }; diff --git a/chromium/storage/browser/blob/blob_reader_unittest.cc b/chromium/storage/browser/blob/blob_reader_unittest.cc index c7bc7b25947..af47daaf0bf 100644 --- a/chromium/storage/browser/blob/blob_reader_unittest.cc +++ b/chromium/storage/browser/blob/blob_reader_unittest.cc @@ -22,7 +22,7 @@ #include "base/test/scoped_task_environment.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" -#include "net/base/completion_callback.h" +#include "net/base/completion_once_callback.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/base/test_completion_callback.h" @@ -215,15 +215,15 @@ void SetValue(T* address, T value) { class FakeFileStreamReader : public FileStreamReader { public: explicit FakeFileStreamReader(const std::string& contents) - : buffer_(new DrainableIOBuffer( - new net::StringIOBuffer( + : buffer_(base::MakeRefCounted<DrainableIOBuffer>( + base::MakeRefCounted<net::StringIOBuffer>( std::unique_ptr<std::string>(new std::string(contents))), contents.size())), net_error_(net::OK), size_(contents.size()) {} FakeFileStreamReader(const std::string& contents, uint64_t size) - : buffer_(new DrainableIOBuffer( - new net::StringIOBuffer( + : buffer_(base::MakeRefCounted<DrainableIOBuffer>( + base::MakeRefCounted<net::StringIOBuffer>( std::unique_ptr<std::string>(new std::string(contents))), contents.size())), net_error_(net::OK), @@ -239,12 +239,12 @@ class FakeFileStreamReader : public FileStreamReader { int Read(net::IOBuffer* buf, int buf_length, - const net::CompletionCallback& done) override { + net::CompletionOnceCallback done) override { DCHECK(buf); // When async_task_runner_ is not set, return synchronously. if (!async_task_runner_.get()) { if (net_error_ == net::OK) { - return ReadImpl(buf, buf_length, net::CompletionCallback()); + return ReadImpl(buf, buf_length, net::CompletionOnceCallback()); } else { return net_error_; } @@ -256,15 +256,15 @@ class FakeFileStreamReader : public FileStreamReader { FROM_HERE, base::BindOnce(base::IgnoreResult(&FakeFileStreamReader::ReadImpl), base::Unretained(this), base::WrapRefCounted(buf), - buf_length, done)); + buf_length, std::move(done))); } else { - async_task_runner_->PostTask(FROM_HERE, base::BindOnce(done, net_error_)); + async_task_runner_->PostTask(FROM_HERE, + base::BindOnce(std::move(done), net_error_)); } return net::ERR_IO_PENDING; } - int64_t GetLength( - const net::Int64CompletionCallback& size_callback) override { + int64_t GetLength(net::Int64CompletionOnceCallback size_callback) override { // When async_task_runner_ is not set, return synchronously. if (!async_task_runner_.get()) { if (net_error_ == net::OK) { @@ -274,12 +274,12 @@ class FakeFileStreamReader : public FileStreamReader { } } if (net_error_ == net::OK) { - async_task_runner_->PostTask(FROM_HERE, - base::BindOnce(size_callback, size_)); + async_task_runner_->PostTask( + FROM_HERE, base::BindOnce(std::move(size_callback), size_)); } else { async_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(size_callback, static_cast<int64_t>(net_error_))); + FROM_HERE, base::BindOnce(std::move(size_callback), + static_cast<int64_t>(net_error_))); } return net::ERR_IO_PENDING; } @@ -287,7 +287,7 @@ class FakeFileStreamReader : public FileStreamReader { private: int ReadImpl(scoped_refptr<net::IOBuffer> buf, int buf_length, - const net::CompletionCallback& done) { + net::CompletionOnceCallback done) { CHECK_GE(buf_length, 0); int length = std::min(buf_length, buffer_->BytesRemaining()); memcpy(buf->data(), buffer_->data(), length); @@ -295,7 +295,7 @@ class FakeFileStreamReader : public FileStreamReader { if (done.is_null()) { return length; } - done.Run(length); + std::move(done).Run(length); return net::ERR_IO_PENDING; } diff --git a/chromium/storage/browser/blob/blob_registry_impl_unittest.cc b/chromium/storage/browser/blob/blob_registry_impl_unittest.cc index 0a39bfb488d..d8b94809afb 100644 --- a/chromium/storage/browser/blob/blob_registry_impl_unittest.cc +++ b/chromium/storage/browser/blob/blob_registry_impl_unittest.cc @@ -11,7 +11,7 @@ #include "base/rand_util.h" #include "base/run_loop.h" #include "base/sequenced_task_runner.h" -#include "base/task_scheduler/post_task.h" +#include "base/task/post_task.h" #include "base/test/bind_test_util.h" #include "base/test/scoped_task_environment.h" #include "base/threading/thread_restrictions.h" diff --git a/chromium/storage/browser/blob/blob_storage_context.cc b/chromium/storage/browser/blob/blob_storage_context.cc index 40819ab6af8..0564dcb541f 100644 --- a/chromium/storage/browser/blob/blob_storage_context.cc +++ b/chromium/storage/browser/blob/blob_storage_context.cc @@ -25,6 +25,7 @@ #include "base/threading/thread_task_runner_handle.h" #include "base/trace_event/memory_dump_manager.h" #include "base/trace_event/trace_event.h" +#include "mojo/public/cpp/bindings/callback_helpers.h" #include "storage/browser/blob/blob_data_builder.h" #include "storage/browser/blob/blob_data_item.h" #include "storage/browser/blob/blob_data_snapshot.h" @@ -75,6 +76,26 @@ std::unique_ptr<BlobDataHandle> BlobStorageContext::GetBlobDataFromPublicURL( return CreateHandle(uuid, entry); } +void BlobStorageContext::GetBlobDataFromBlobPtr( + blink::mojom::BlobPtr blob, + base::OnceCallback<void(std::unique_ptr<BlobDataHandle>)> callback) { + DCHECK(blob); + blink::mojom::Blob* raw_blob = blob.get(); + raw_blob->GetInternalUUID(mojo::WrapCallbackWithDefaultInvokeIfNotRun( + base::BindOnce( + [](blink::mojom::BlobPtr, base::WeakPtr<BlobStorageContext> context, + base::OnceCallback<void(std::unique_ptr<BlobDataHandle>)> callback, + const std::string& uuid) { + if (!context || uuid.empty()) { + std::move(callback).Run(nullptr); + return; + } + std::move(callback).Run(context->GetBlobDataFromUUID(uuid)); + }, + std::move(blob), AsWeakPtr(), std::move(callback)), + "")); +} + std::unique_ptr<BlobDataHandle> BlobStorageContext::AddFinishedBlob( std::unique_ptr<BlobDataBuilder> external_builder) { TRACE_EVENT0("Blob", "Context::AddFinishedBlob"); diff --git a/chromium/storage/browser/blob/blob_storage_context.h b/chromium/storage/browser/blob/blob_storage_context.h index 86a4556c0aa..e0bb90aff3e 100644 --- a/chromium/storage/browser/blob/blob_storage_context.h +++ b/chromium/storage/browser/blob/blob_storage_context.h @@ -25,6 +25,7 @@ #include "storage/browser/blob/blob_storage_registry.h" #include "storage/browser/storage_browser_export.h" #include "storage/common/blob_storage/blob_storage_constants.h" +#include "third_party/blink/public/mojom/blob/blob.mojom.h" class GURL; @@ -57,8 +58,15 @@ class STORAGE_EXPORT BlobStorageContext scoped_refptr<base::TaskRunner> file_runner); ~BlobStorageContext() override; + // The following three methods all lookup a BlobDataHandle based on some + // input. If no blob matching the input exists these methods return null. std::unique_ptr<BlobDataHandle> GetBlobDataFromUUID(const std::string& uuid); std::unique_ptr<BlobDataHandle> GetBlobDataFromPublicURL(const GURL& url); + // If this BlobStorageContext is deleted before this method finishes, the + // callback will still be called with null. + void GetBlobDataFromBlobPtr( + blink::mojom::BlobPtr blob, + base::OnceCallback<void(std::unique_ptr<BlobDataHandle>)> callback); // Always returns a handle to a blob. Use BlobStatus::GetBlobStatus() and // BlobStatus::RunOnConstructionComplete(callback) to determine construction diff --git a/chromium/storage/browser/blob/blob_transport_strategy_unittest.cc b/chromium/storage/browser/blob/blob_transport_strategy_unittest.cc index 3000df34920..f4946338655 100644 --- a/chromium/storage/browser/blob/blob_transport_strategy_unittest.cc +++ b/chromium/storage/browser/blob/blob_transport_strategy_unittest.cc @@ -11,7 +11,7 @@ #include "base/rand_util.h" #include "base/run_loop.h" #include "base/sequenced_task_runner.h" -#include "base/task_scheduler/post_task.h" +#include "base/task/post_task.h" #include "base/test/scoped_task_environment.h" #include "base/threading/thread_restrictions.h" #include "mojo/core/embedder/embedder.h" diff --git a/chromium/storage/browser/blob/blob_url_request_job_factory.cc b/chromium/storage/browser/blob/blob_url_request_job_factory.cc index c8f8345de15..270cc8f99e8 100644 --- a/chromium/storage/browser/blob/blob_url_request_job_factory.cc +++ b/chromium/storage/browser/blob/blob_url_request_job_factory.cc @@ -95,7 +95,7 @@ BlobDataHandle* BlobProtocolHandler::LookupBlobHandle( if (blob_data_handle) return blob_data_handle; if (!context_.get()) - return NULL; + return nullptr; // Support looking up based on uuid, the FeedbackExtensionAPI relies on this. // TODO(michaeln): Replace this use case and others like it with a BlobReader @@ -103,7 +103,7 @@ BlobDataHandle* BlobProtocolHandler::LookupBlobHandle( const std::string kPrefix("blob:uuid/"); if (!base::StartsWith(request->url().spec(), kPrefix, base::CompareCase::SENSITIVE)) - return NULL; + return nullptr; std::string uuid = request->url().spec().substr(kPrefix.length()); std::unique_ptr<BlobDataHandle> handle = context_->GetBlobDataFromUUID(uuid); BlobDataHandle* handle_ptr = handle.get(); diff --git a/chromium/storage/browser/blob/mojo_blob_reader.cc b/chromium/storage/browser/blob/mojo_blob_reader.cc index 2e0cd6ba6ca..3f11019b39e 100644 --- a/chromium/storage/browser/blob/mojo_blob_reader.cc +++ b/chromium/storage/browser/blob/mojo_blob_reader.cc @@ -4,6 +4,7 @@ #include "storage/browser/blob/mojo_blob_reader.h" +#include "base/debug/alias.h" #include "base/trace_event/trace_event.h" #include "net/base/io_buffer.h" #include "services/network/public/cpp/net_adapters.h" @@ -39,11 +40,14 @@ MojoBlobReader::MojoBlobReader(const BlobDataHandle* handle, } MojoBlobReader::~MojoBlobReader() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); TRACE_EVENT_ASYNC_END1("Blob", "BlobReader", this, "bytes_written", total_written_bytes_); } void MojoBlobReader::Start() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (blob_reader_->net_error()) { NotifyCompletedAndDeleteIfNeeded(blob_reader_->net_error()); return; @@ -69,6 +73,8 @@ void MojoBlobReader::Start() { } void MojoBlobReader::NotifyCompletedAndDeleteIfNeeded(int result) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + blob_reader_ = nullptr; if (!notified_completed_) { delegate_->OnComplete(static_cast<net::Error>(result), @@ -82,6 +88,8 @@ void MojoBlobReader::NotifyCompletedAndDeleteIfNeeded(int result) { } void MojoBlobReader::DidCalculateSize(int result) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (result != net::OK) { TRACE_EVENT_ASYNC_END1("Blob", "BlobReader::CountSize", this, "result", "error"); @@ -92,17 +100,28 @@ void MojoBlobReader::DidCalculateSize(int result) { TRACE_EVENT_ASYNC_END2("Blob", "BlobReader::CountSize", this, "result", "success", "size", blob_reader_->total_size()); + // TODO(https://crbug.com/864351): Temporary diagnostics. + net::HttpByteRange pre_bounds_range = byte_range_; + base::debug::Alias(&pre_bounds_range); + // Apply the range requirement. if (!byte_range_.ComputeBounds(blob_reader_->total_size())) { NotifyCompletedAndDeleteIfNeeded(net::ERR_REQUEST_RANGE_NOT_SATISFIABLE); return; } + // TODO(https://crbug.com/864351): Temporary diagnostics. + net::HttpByteRange post_bounds_range = byte_range_; + base::debug::Alias(&post_bounds_range); + DCHECK_LE(byte_range_.first_byte_position(), byte_range_.last_byte_position() + 1); uint64_t length = base::checked_cast<uint64_t>( byte_range_.last_byte_position() - byte_range_.first_byte_position() + 1); + // TODO(https://crbug.com/864351): Temporary diagnostics. + base::debug::Alias(&length); + if (blob_reader_->SetReadRange(byte_range_.first_byte_position(), length) != BlobReader::Status::DONE) { NotifyCompletedAndDeleteIfNeeded(blob_reader_->net_error()); @@ -126,6 +145,8 @@ void MojoBlobReader::DidCalculateSize(int result) { } void MojoBlobReader::DidReadSideData(BlobReader::Status status) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (status != BlobReader::Status::DONE) { NotifyCompletedAndDeleteIfNeeded(blob_reader_->net_error()); return; @@ -135,6 +156,9 @@ void MojoBlobReader::DidReadSideData(BlobReader::Status status) { } void MojoBlobReader::StartReading() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(!response_body_stream_); + response_body_stream_ = delegate_->PassDataPipe(); peer_closed_handle_watcher_.Watch( response_body_stream_.get(), MOJO_HANDLE_SIGNAL_PEER_CLOSED, @@ -152,9 +176,11 @@ void MojoBlobReader::StartReading() { } void MojoBlobReader::ReadMore() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!pending_write_.get()); + DCHECK(response_body_stream_); - uint32_t num_bytes; + uint32_t num_bytes = 0; // TODO: we should use the abstractions in MojoAsyncResourceHandler. MojoResult result = network::NetToMojoPendingBuffer::BeginWrite( &response_body_stream_, &pending_write_, &num_bytes); @@ -172,9 +198,10 @@ void MojoBlobReader::ReadMore() { TRACE_EVENT_ASYNC_BEGIN0("Blob", "BlobReader::ReadMore", this); CHECK_GT(static_cast<uint32_t>(std::numeric_limits<int>::max()), num_bytes); + DCHECK(pending_write_); auto buf = base::MakeRefCounted<network::NetToMojoIOBuffer>(pending_write_.get()); - int bytes_read; + int bytes_read = 0; BlobReader::Status read_status = blob_reader_->Read( buf.get(), static_cast<int>(num_bytes), &bytes_read, base::BindOnce(&MojoBlobReader::DidRead, base::Unretained(this), false)); @@ -192,6 +219,8 @@ void MojoBlobReader::ReadMore() { } void MojoBlobReader::DidRead(bool completed_synchronously, int num_bytes) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (num_bytes < 0) { TRACE_EVENT_ASYNC_END2("Blob", "BlobReader::ReadMore", this, "result", "error", "net_error", num_bytes); @@ -223,12 +252,16 @@ void MojoBlobReader::DidRead(bool completed_synchronously, int num_bytes) { } void MojoBlobReader::OnResponseBodyStreamClosed(MojoResult result) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + response_body_stream_.reset(); pending_write_ = nullptr; NotifyCompletedAndDeleteIfNeeded(net::ERR_ABORTED); } void MojoBlobReader::OnResponseBodyStreamReady(MojoResult result) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (result == MOJO_RESULT_FAILED_PRECONDITION) { OnResponseBodyStreamClosed(MOJO_RESULT_OK); return; diff --git a/chromium/storage/browser/blob/mojo_blob_reader.h b/chromium/storage/browser/blob/mojo_blob_reader.h index ced13b04d4c..3ac46630fd7 100644 --- a/chromium/storage/browser/blob/mojo_blob_reader.h +++ b/chromium/storage/browser/blob/mojo_blob_reader.h @@ -7,6 +7,7 @@ #include <memory> #include "base/memory/ref_counted.h" +#include "base/sequence_checker.h" #include "mojo/public/cpp/system/data_pipe.h" #include "mojo/public/cpp/system/simple_watcher.h" #include "net/base/net_errors.h" @@ -38,7 +39,7 @@ class STORAGE_EXPORT MojoBlobReader { public: enum RequestSideData { REQUEST_SIDE_DATA, DONT_REQUEST_SIDE_DATA }; - virtual ~Delegate() {} + virtual ~Delegate() = default; // Called when the blob being read has been fully constructed and its size // is known. |total_size| is the total size of the blob, while @@ -99,7 +100,7 @@ class STORAGE_EXPORT MojoBlobReader { void OnResponseBodyStreamClosed(MojoResult result); void OnResponseBodyStreamReady(MojoResult result); - std::unique_ptr<Delegate> delegate_; + const std::unique_ptr<Delegate> delegate_; // The range of the blob that should be read. Could be unbounded if the entire // blob is being read. @@ -130,6 +131,8 @@ class STORAGE_EXPORT MojoBlobReader { // sure OnComplete isn't called more than once. bool notified_completed_ = false; + SEQUENCE_CHECKER(sequence_checker_); + base::WeakPtrFactory<MojoBlobReader> weak_factory_; DISALLOW_COPY_AND_ASSIGN(MojoBlobReader); diff --git a/chromium/storage/browser/blob/shareable_file_reference.cc b/chromium/storage/browser/blob/shareable_file_reference.cc index 9b5c5cec912..e147ccfcca9 100644 --- a/chromium/storage/browser/blob/shareable_file_reference.cc +++ b/chromium/storage/browser/blob/shareable_file_reference.cc @@ -72,7 +72,7 @@ scoped_refptr<ShareableFileReference> ShareableFileReference::Get( const base::FilePath& path) { ShareableFileMap::iterator found = g_file_map.Get().Find(path); ShareableFileReference* reference = - (found == g_file_map.Get().End()) ? NULL : found->second; + (found == g_file_map.Get().End()) ? nullptr : found->second; return scoped_refptr<ShareableFileReference>(reference); } @@ -120,12 +120,12 @@ void ShareableFileReference::AddFinalReleaseCallback( #if DCHECK_IS_ON() g_file_map.Get().AssertCalledOnValidSequence(); #endif // DCHECK_IS_ON() - scoped_file_.AddScopeOutCallback(std::move(callback), NULL); + scoped_file_.AddScopeOutCallback(std::move(callback), nullptr); } ShareableFileReference::ShareableFileReference(ScopedFile scoped_file) : scoped_file_(std::move(scoped_file)) { - DCHECK(g_file_map.Get().Find(path())->second == NULL); + DCHECK(g_file_map.Get().Find(path())->second == nullptr); } ShareableFileReference::~ShareableFileReference() { diff --git a/chromium/storage/browser/blob/shareable_file_reference.h b/chromium/storage/browser/blob/shareable_file_reference.h index 7b935a0fb08..1e10c58c0da 100644 --- a/chromium/storage/browser/blob/shareable_file_reference.h +++ b/chromium/storage/browser/blob/shareable_file_reference.h @@ -26,7 +26,7 @@ class STORAGE_EXPORT ShareableFileReference : public BlobDataItem::DataHandle { }; // Returns a ShareableFileReference for the given path, if no reference - // for this path exists returns NULL. + // for this path exists returns nullptr. static scoped_refptr<ShareableFileReference> Get(const base::FilePath& path); // Returns a ShareableFileReference for the given path, creating a new @@ -43,7 +43,7 @@ class STORAGE_EXPORT ShareableFileReference : public BlobDataItem::DataHandle { // If there's a pre-existing reference for the path, the scope out policy // and scope-out-callbacks of the given |scoped_file| is ignored. // If the given scoped_file has an empty path (e.g. maybe already - // released) this returns NULL reference. + // released) this returns nullptr reference. // // TODO(kinuko): Make sure if this behavior is ok, we could alternatively // merge callbacks to the existing one. diff --git a/chromium/storage/browser/blob/view_blob_internals_job.cc b/chromium/storage/browser/blob/view_blob_internals_job.cc index e18a815e001..00e9e051476 100644 --- a/chromium/storage/browser/blob/view_blob_internals_job.cc +++ b/chromium/storage/browser/blob/view_blob_internals_job.cc @@ -180,11 +180,10 @@ void ViewBlobInternalsJob::Kill() { weak_factory_.InvalidateWeakPtrs(); } -int ViewBlobInternalsJob::GetData( - std::string* mime_type, - std::string* charset, - std::string* data, - const net::CompletionCallback& callback) const { +int ViewBlobInternalsJob::GetData(std::string* mime_type, + std::string* charset, + std::string* data, + net::CompletionOnceCallback callback) const { mime_type->assign("text/html"); charset->assign("UTF-8"); diff --git a/chromium/storage/browser/blob/view_blob_internals_job.h b/chromium/storage/browser/blob/view_blob_internals_job.h index 746361cb930..4ad9a2b5ff5 100644 --- a/chromium/storage/browser/blob/view_blob_internals_job.h +++ b/chromium/storage/browser/blob/view_blob_internals_job.h @@ -9,6 +9,7 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" +#include "net/base/completion_once_callback.h" #include "net/url_request/url_request_simple_job.h" #include "storage/browser/storage_browser_export.h" @@ -34,7 +35,7 @@ class STORAGE_EXPORT ViewBlobInternalsJob int GetData(std::string* mime_type, std::string* charset, std::string* data, - const net::CompletionCallback& callback) const override; + net::CompletionOnceCallback callback) const override; bool IsRedirectResponse(GURL* location, int* http_status_code, bool* insecure_scheme_was_upgraded) override; diff --git a/chromium/storage/browser/database/database_quota_client.cc b/chromium/storage/browser/database/database_quota_client.cc index beae9b2f4d3..84bb06cc974 100644 --- a/chromium/storage/browser/database/database_quota_client.cc +++ b/chromium/storage/browser/database/database_quota_client.cc @@ -62,8 +62,8 @@ void GetOriginsForHostOnDBThread(DatabaseTracker* db_tracker, } } -void DidGetOrigins(QuotaClient::GetOriginsCallback callback, - std::set<url::Origin>* origins_ptr) { +void DidGetQuotaClientOrigins(QuotaClient::GetOriginsCallback callback, + std::set<url::Origin>* origins_ptr) { std::move(callback).Run(*origins_ptr); } @@ -145,7 +145,7 @@ void DatabaseQuotaClient::GetOriginsForType(StorageType type, FROM_HERE, base::BindOnce(&GetOriginsOnDBThread, base::RetainedRef(db_tracker_), base::Unretained(origins_ptr)), - base::BindOnce(&DidGetOrigins, std::move(callback), + base::BindOnce(&DidGetQuotaClientOrigins, std::move(callback), base::Owned(origins_ptr))); } @@ -167,7 +167,7 @@ void DatabaseQuotaClient::GetOriginsForHost(StorageType type, base::BindOnce(&GetOriginsForHostOnDBThread, base::RetainedRef(db_tracker_), base::Unretained(origins_ptr), host), - base::BindOnce(&DidGetOrigins, std::move(callback), + base::BindOnce(&DidGetQuotaClientOrigins, std::move(callback), base::Owned(origins_ptr))); } diff --git a/chromium/storage/browser/database/database_quota_client_unittest.cc b/chromium/storage/browser/database/database_quota_client_unittest.cc index 0fbe1e29a3e..3d9986dae85 100644 --- a/chromium/storage/browser/database/database_quota_client_unittest.cc +++ b/chromium/storage/browser/database/database_quota_client_unittest.cc @@ -5,6 +5,7 @@ #include <stdint.h> #include <map> +#include <utility> #include "base/bind.h" #include "base/callback_helpers.h" @@ -15,7 +16,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/test/scoped_task_environment.h" #include "base/threading/thread_task_runner_handle.h" -#include "net/base/completion_callback.h" +#include "net/base/completion_once_callback.h" #include "net/base/net_errors.h" #include "storage/browser/database/database_quota_client.h" #include "storage/browser/database/database_tracker.h" @@ -70,20 +71,20 @@ class MockDatabaseTracker : public DatabaseTracker { } int DeleteDataForOrigin(const std::string& origin_identifier, - const net::CompletionCallback& callback) override { + net::CompletionOnceCallback callback) override { ++delete_called_count_; if (async_delete()) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&MockDatabaseTracker::AsyncDeleteDataForOrigin, this, - callback)); + std::move(callback))); return net::ERR_IO_PENDING; } return net::OK; } - void AsyncDeleteDataForOrigin(const net::CompletionCallback& callback) { - callback.Run(net::OK); + void AsyncDeleteDataForOrigin(net::CompletionOnceCallback callback) { + std::move(callback).Run(net::OK); } void AddMockDatabase(const url::Origin& origin, const char* name, int size) { diff --git a/chromium/storage/browser/database/database_tracker.cc b/chromium/storage/browser/database/database_tracker.cc index 2b415cceb6c..e18b8180bb5 100644 --- a/chromium/storage/browser/database/database_tracker.cc +++ b/chromium/storage/browser/database/database_tracker.cc @@ -14,9 +14,9 @@ #include "base/files/file_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" -#include "base/task_scheduler/post_task.h" +#include "base/task/post_task.h" #include "net/base/net_errors.h" -#include "sql/connection.h" +#include "sql/database.h" #include "sql/meta_table.h" #include "sql/transaction.h" #include "storage/browser/database/database_quota_client.h" @@ -37,8 +37,8 @@ const base::FilePath::CharType kIncognitoDatabaseDirectoryName[] = FILE_PATH_LITERAL("databases-incognito"); const base::FilePath::CharType kTrackerDatabaseFileName[] = FILE_PATH_LITERAL("Databases.db"); -static const int kCurrentVersion = 2; -static const int kCompatibleVersion = 1; +static const int kDatabaseTrackerCurrentSchemaVersion = 2; +static const int kDatabaseTrackerCompatibleVersion = 1; const base::FilePath::CharType kTemporaryDirectoryPrefix[] = FILE_PATH_LITERAL("DeleteMe"); @@ -86,7 +86,7 @@ DatabaseTracker::DatabaseTracker( db_dir_(is_incognito_ ? profile_path_.Append(kIncognitoDatabaseDirectoryName) : profile_path_.Append(kDatabaseDirectoryName)), - db_(new sql::Connection()), + db_(new sql::Database()), special_storage_policy_(special_storage_policy), quota_manager_proxy_(quota_manager_proxy), task_runner_(base::CreateSequencedTaskRunnerWithTraits( @@ -176,7 +176,7 @@ void DatabaseTracker::HandleSqliteError( // a small optimization, see WebDatabaseObserverImpl::HandleSqliteError. if (error == SQLITE_CORRUPT || error == SQLITE_NOTADB) { DeleteDatabase(origin_identifier, database_name, - net::CompletionCallback()); + net::CompletionOnceCallback()); } } @@ -222,8 +222,7 @@ void DatabaseTracker::DeleteDatabaseIfNeeded( if (databases.empty()) { callback->second.erase(found_origin); if (callback->second.empty()) { - net::CompletionCallback cb = callback->first; - cb.Run(net::OK); + std::move(callback->first).Run(net::OK); callback = deletion_callbacks_.erase(callback); continue; } @@ -357,7 +356,7 @@ bool DatabaseTracker::DeleteClosedDatabase( // Try to delete the file on the hard drive. base::FilePath db_file = GetFullDBFilePath(origin_identifier, database_name); - if (!sql::Connection::Delete(db_file)) + if (!sql::Database::Delete(db_file)) return false; if (quota_manager_proxy_.get() && db_file_size) @@ -500,13 +499,15 @@ bool DatabaseTracker::UpgradeToCurrentVersion() { DCHECK(task_runner_->RunsTasksInCurrentSequence()); sql::Transaction transaction(db_.get()); if (!transaction.Begin() || - !meta_table_->Init(db_.get(), kCurrentVersion, kCompatibleVersion) || - (meta_table_->GetCompatibleVersionNumber() > kCurrentVersion) || + !meta_table_->Init(db_.get(), kDatabaseTrackerCurrentSchemaVersion, + kDatabaseTrackerCompatibleVersion) || + (meta_table_->GetCompatibleVersionNumber() > + kDatabaseTrackerCurrentSchemaVersion) || !databases_table_->Init()) return false; - if (meta_table_->GetVersionNumber() < kCurrentVersion) - meta_table_->SetVersionNumber(kCurrentVersion); + if (meta_table_->GetVersionNumber() < kDatabaseTrackerCurrentSchemaVersion) + meta_table_->SetVersionNumber(kDatabaseTrackerCurrentSchemaVersion); return transaction.Commit(); } @@ -640,11 +641,12 @@ void DatabaseTracker::ScheduleDatabaseForDeletion( void DatabaseTracker::ScheduleDatabasesForDeletion( const DatabaseSet& databases, - const net::CompletionCallback& callback) { + net::CompletionOnceCallback callback) { DCHECK(!databases.empty()); if (!callback.is_null()) - deletion_callbacks_.push_back(std::make_pair(callback, databases)); + deletion_callbacks_.push_back( + std::make_pair(std::move(callback), databases)); for (const auto& origin_dbs : databases) { for (const base::string16& db : origin_dbs.second) ScheduleDatabaseForDeletion(origin_dbs.first, db); @@ -653,7 +655,7 @@ void DatabaseTracker::ScheduleDatabasesForDeletion( int DatabaseTracker::DeleteDatabase(const std::string& origin_identifier, const base::string16& database_name, - const net::CompletionCallback& callback) { + net::CompletionOnceCallback callback) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); if (!LazyInit()) return net::ERR_FAILED; @@ -663,7 +665,7 @@ int DatabaseTracker::DeleteDatabase(const std::string& origin_identifier, if (!callback.is_null()) { DatabaseSet set; set[origin_identifier].insert(database_name); - deletion_callbacks_.emplace_back(callback, set); + deletion_callbacks_.emplace_back(std::move(callback), set); } ScheduleDatabaseForDeletion(origin_identifier, database_name); return net::ERR_IO_PENDING; @@ -674,7 +676,7 @@ int DatabaseTracker::DeleteDatabase(const std::string& origin_identifier, int DatabaseTracker::DeleteDataModifiedSince( const base::Time& cutoff, - const net::CompletionCallback& callback) { + net::CompletionOnceCallback callback) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); if (!LazyInit()) return net::ERR_FAILED; @@ -715,14 +717,14 @@ int DatabaseTracker::DeleteDataModifiedSince( return rv; if (!to_be_deleted.empty()) { - ScheduleDatabasesForDeletion(to_be_deleted, callback); + ScheduleDatabasesForDeletion(to_be_deleted, std::move(callback)); return net::ERR_IO_PENDING; } return net::OK; } -int DatabaseTracker::DeleteDataForOrigin( - const std::string& origin, const net::CompletionCallback& callback) { +int DatabaseTracker::DeleteDataForOrigin(const std::string& origin, + net::CompletionOnceCallback callback) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); if (!LazyInit()) return net::ERR_FAILED; @@ -742,7 +744,7 @@ int DatabaseTracker::DeleteDataForOrigin( } if (!to_be_deleted.empty()) { - ScheduleDatabasesForDeletion(to_be_deleted, callback); + ScheduleDatabasesForDeletion(to_be_deleted, std::move(callback)); return net::ERR_IO_PENDING; } return net::OK; diff --git a/chromium/storage/browser/database/database_tracker.h b/chromium/storage/browser/database/database_tracker.h index e8863de292b..ef67fec1daa 100644 --- a/chromium/storage/browser/database/database_tracker.h +++ b/chromium/storage/browser/database/database_tracker.h @@ -21,7 +21,7 @@ #include "base/strings/string16.h" #include "base/strings/string_util.h" #include "base/time/time.h" -#include "net/base/completion_callback.h" +#include "net/base/completion_once_callback.h" #include "storage/browser/storage_browser_export.h" #include "storage/common/database/database_connections.h" @@ -31,7 +31,7 @@ class MockDatabaseTracker; } namespace sql { -class Connection; +class Database; class MetaTable; } @@ -145,7 +145,7 @@ class STORAGE_EXPORT DatabaseTracker // if non-null. int DeleteDatabase(const std::string& origin_identifier, const base::string16& database_name, - const net::CompletionCallback& callback); + net::CompletionOnceCallback callback); // Delete any databases that have been touched since the cutoff date that's // supplied, omitting any that match IDs within |protected_origins|. @@ -154,14 +154,14 @@ class STORAGE_EXPORT DatabaseTracker // if non-null. Protected origins, according the the SpecialStoragePolicy, // are not deleted by this method. int DeleteDataModifiedSince(const base::Time& cutoff, - const net::CompletionCallback& callback); + net::CompletionOnceCallback callback); // Delete all databases that belong to the given origin. Returns net::OK on // success, net::FAILED if not all databases could be deleted, and // net::ERR_IO_PENDING and |callback| is invoked upon completion, if non-null. // virtual for unit testing only virtual int DeleteDataForOrigin(const std::string& origin_identifier, - const net::CompletionCallback& callback); + net::CompletionOnceCallback callback); bool IsIncognitoProfile() const { return is_incognito_; } @@ -179,13 +179,19 @@ class STORAGE_EXPORT DatabaseTracker base::SequencedTaskRunner* task_runner() const { return task_runner_.get(); } + // TODO(jsbell): Remove this; tests should use the normal task runner. + void set_task_runner_for_testing( + scoped_refptr<base::SequencedTaskRunner> task_runner) { + task_runner_ = std::move(task_runner); + } + private: friend class base::RefCountedThreadSafe<DatabaseTracker>; friend class content::DatabaseTracker_TestHelper_Test; friend class content::MockDatabaseTracker; // for testing typedef std::map<std::string, std::set<base::string16> > DatabaseSet; - typedef std::vector<std::pair<net::CompletionCallback, DatabaseSet> > + typedef std::vector<std::pair<net::CompletionOnceCallback, DatabaseSet>> PendingDeletionCallbacks; typedef std::map<base::string16, base::File*> FileHandlesMap; typedef std::map<std::string, base::string16> OriginDirectoriesMap; @@ -267,17 +273,11 @@ class STORAGE_EXPORT DatabaseTracker // Schedule a set of open databases for deletion. If non-null, callback is // invoked upon completion. void ScheduleDatabasesForDeletion(const DatabaseSet& databases, - const net::CompletionCallback& callback); + net::CompletionOnceCallback callback); // Returns the directory where all DB files for the given origin are stored. base::string16 GetOriginDirectory(const std::string& origin_identifier); - // TODO(jsbell): Remove this; tests should use the normal task runner. - void set_task_runner_for_testing( - scoped_refptr<base::SequencedTaskRunner> task_runner) { - task_runner_ = std::move(task_runner); - } - bool is_initialized_ = false; const bool is_incognito_; bool force_keep_session_state_ = false; @@ -289,10 +289,10 @@ class STORAGE_EXPORT DatabaseTracker // Thread-safety argument: The member is immutable. const base::FilePath db_dir_; - std::unique_ptr<sql::Connection> db_; + std::unique_ptr<sql::Database> db_; std::unique_ptr<DatabasesTable> databases_table_; std::unique_ptr<sql::MetaTable> meta_table_; - base::ObserverList<Observer, true> observers_; + base::ObserverList<Observer, true>::Unchecked observers_; std::map<std::string, CachedOriginInfo> origins_info_map_; DatabaseConnections database_connections_; diff --git a/chromium/storage/browser/database/database_tracker_unittest.cc b/chromium/storage/browser/database/database_tracker_unittest.cc index f213778c2de..b9a194be637 100644 --- a/chromium/storage/browser/database/database_tracker_unittest.cc +++ b/chromium/storage/browser/database/database_tracker_unittest.cc @@ -475,7 +475,7 @@ class DatabaseTracker_TestHelper_Test { tracker->DatabaseClosed(kOriginId, kName); EXPECT_TRUE(test_quota_proxy->WasAccessNotified(kOrigin)); EXPECT_EQ(net::OK, tracker->DeleteDatabase(kOriginId, kName, - net::CompletionCallback())); + net::CompletionOnceCallback())); EXPECT_TRUE(test_quota_proxy->WasModificationNotified(kOrigin, -100)); test_quota_proxy->reset(); @@ -494,9 +494,9 @@ class DatabaseTracker_TestHelper_Test { EXPECT_TRUE(test_quota_proxy->WasModificationNotified(kOrigin, 100)); test_quota_proxy->reset(); - EXPECT_EQ( - net::ERR_IO_PENDING, - tracker->DeleteDatabase(kOriginId, kName, net::CompletionCallback())); + EXPECT_EQ(net::ERR_IO_PENDING, + tracker->DeleteDatabase(kOriginId, kName, + net::CompletionOnceCallback())); EXPECT_FALSE(test_quota_proxy->WasModificationNotified(kOrigin, -100)); tracker->DatabaseClosed(kOriginId, kName); @@ -728,7 +728,7 @@ class DatabaseTracker_TestHelper_Test { // Deleting it should return to the initial state. EXPECT_EQ(net::OK, tracker->DeleteDatabase(kOriginId, kEmptyName, - net::CompletionCallback())); + net::CompletionOnceCallback())); infos.clear(); EXPECT_TRUE(tracker->GetAllOriginsInfo(&infos)); EXPECT_TRUE(infos.empty()); diff --git a/chromium/storage/browser/database/databases_table.h b/chromium/storage/browser/database/databases_table.h index 6dce97c7a47..c622b807c1b 100644 --- a/chromium/storage/browser/database/databases_table.h +++ b/chromium/storage/browser/database/databases_table.h @@ -13,7 +13,7 @@ #include "storage/browser/storage_browser_export.h" namespace sql { -class Connection; +class Database; } namespace storage { @@ -31,7 +31,7 @@ struct STORAGE_EXPORT DatabaseDetails { class STORAGE_EXPORT DatabasesTable { public: - explicit DatabasesTable(sql::Connection* db) : db_(db) { } + explicit DatabasesTable(sql::Database* db) : db_(db) {} bool Init(); int64_t GetDatabaseID(const std::string& origin_identifier, @@ -49,7 +49,7 @@ class STORAGE_EXPORT DatabasesTable { std::vector<DatabaseDetails>* details); bool DeleteOriginIdentifier(const std::string& origin_identifier); private: - sql::Connection* db_; + sql::Database* db_; }; } // namespace storage diff --git a/chromium/storage/browser/database/databases_table_unittest.cc b/chromium/storage/browser/database/databases_table_unittest.cc index c26e92154e5..a2bd792cb8d 100644 --- a/chromium/storage/browser/database/databases_table_unittest.cc +++ b/chromium/storage/browser/database/databases_table_unittest.cc @@ -7,7 +7,7 @@ #include "base/bind.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" -#include "sql/connection.h" +#include "sql/database.h" #include "sql/statement.h" #include "sql/test/scoped_error_expecter.h" #include "storage/browser/database/databases_table.h" @@ -28,7 +28,7 @@ static void CheckDetailsAreEqual(const DatabaseDetails& d1, EXPECT_EQ(d1.estimated_size, d2.estimated_size); } -static bool DatabasesTableIsEmpty(sql::Connection* db) { +static bool DatabasesTableIsEmpty(sql::Database* db) { sql::Statement statement( db->GetCachedStatement(SQL_FROM_HERE, "SELECT COUNT(*) FROM Databases")); return (statement.is_valid() && statement.Step() && !statement.ColumnInt(0)); @@ -36,7 +36,7 @@ static bool DatabasesTableIsEmpty(sql::Connection* db) { TEST(DatabasesTableTest, TestIt) { // Initialize the 'Databases' table. - sql::Connection db; + sql::Database db; sql::test::ScopedErrorExpecter expecter; // TODO(shess): Suppressing SQLITE_CONSTRAINT because the code diff --git a/chromium/storage/browser/fileapi/copy_or_move_file_validator.h b/chromium/storage/browser/fileapi/copy_or_move_file_validator.h index e1fe7211bd4..e2c05cc2086 100644 --- a/chromium/storage/browser/fileapi/copy_or_move_file_validator.h +++ b/chromium/storage/browser/fileapi/copy_or_move_file_validator.h @@ -41,7 +41,7 @@ class CopyOrMoveFileValidatorFactory { public: virtual ~CopyOrMoveFileValidatorFactory() {} - // This method must always return a non-NULL validator. |src_url| is needed + // This method must always return a non-null validator. |src_url| is needed // in addition to |platform_path| because in the obfuscated file system // case, |platform_path| will be an obfuscated filename and extension. virtual CopyOrMoveFileValidator* CreateCopyOrMoveFileValidator( diff --git a/chromium/storage/browser/fileapi/copy_or_move_file_validator_unittest.cc b/chromium/storage/browser/fileapi/copy_or_move_file_validator_unittest.cc index 37ce98c5fd0..2d1cd422e31 100644 --- a/chromium/storage/browser/fileapi/copy_or_move_file_validator_unittest.cc +++ b/chromium/storage/browser/fileapi/copy_or_move_file_validator_unittest.cc @@ -56,7 +56,7 @@ class CopyOrMoveFileValidatorTestHelper { : origin_(origin), src_type_(src_type), dest_type_(dest_type) {} ~CopyOrMoveFileValidatorTestHelper() { - file_system_context_ = NULL; + file_system_context_ = nullptr; base::RunLoop().RunUntilIdle(); } @@ -64,7 +64,7 @@ class CopyOrMoveFileValidatorTestHelper { ASSERT_TRUE(base_.CreateUniqueTempDir()); base::FilePath base_dir = base_.GetPath(); - file_system_context_ = CreateFileSystemContextForTesting(NULL, base_dir); + file_system_context_ = CreateFileSystemContextForTesting(nullptr, base_dir); // Set up TestFileSystemBackend to require CopyOrMoveFileValidator. storage::FileSystemBackend* test_file_system_backend = diff --git a/chromium/storage/browser/fileapi/copy_or_move_operation_delegate.cc b/chromium/storage/browser/fileapi/copy_or_move_operation_delegate.cc index 3d6686781eb..2f871b38fcd 100644 --- a/chromium/storage/browser/fileapi/copy_or_move_operation_delegate.cc +++ b/chromium/storage/browser/fileapi/copy_or_move_operation_delegate.cc @@ -224,7 +224,7 @@ class SnapshotCopyOrMoveImpl return; } - // |validator_| is NULL when the destination filesystem does not do + // |validator_| is nullptr when the destination filesystem does not do // validation. if (!validator_) { // No validation is needed. @@ -661,7 +661,8 @@ void CopyOrMoveOperationDelegate::StreamCopyHelper::DidRead( return; } - Write(callback, new net::DrainableIOBuffer(io_buffer_.get(), result)); + Write(callback, + base::MakeRefCounted<net::DrainableIOBuffer>(io_buffer_, result)); } void CopyOrMoveOperationDelegate::StreamCopyHelper::Write( diff --git a/chromium/storage/browser/fileapi/copy_or_move_operation_delegate_unittest.cc b/chromium/storage/browser/fileapi/copy_or_move_operation_delegate_unittest.cc index f70d69c1436..48684f6fbe3 100644 --- a/chromium/storage/browser/fileapi/copy_or_move_operation_delegate_unittest.cc +++ b/chromium/storage/browser/fileapi/copy_or_move_operation_delegate_unittest.cc @@ -186,10 +186,10 @@ class CopyOrMoveOperationTestHelper { base::test::ScopedTaskEnvironment::MainThreadType::IO) {} ~CopyOrMoveOperationTestHelper() { - file_system_context_ = NULL; + file_system_context_ = nullptr; quota_manager_proxy_->SimulateQuotaManagerDestroyed(); - quota_manager_ = NULL; - quota_manager_proxy_ = NULL; + quota_manager_ = nullptr; + quota_manager_proxy_ = nullptr; scoped_task_environment_.RunUntilIdle(); } @@ -208,7 +208,7 @@ class CopyOrMoveOperationTestHelper { quota_manager_ = new MockQuotaManager(false /* is_incognito */, base_dir, base::ThreadTaskRunnerHandle::Get().get(), - NULL /* special storage policy */); + nullptr /* special storage policy */); quota_manager_proxy_ = new MockQuotaManagerProxy( quota_manager_.get(), base::ThreadTaskRunnerHandle::Get().get()); file_system_context_ = @@ -252,13 +252,13 @@ class CopyOrMoveOperationTestHelper { int64_t GetSourceUsage() { int64_t usage = 0; - GetUsageAndQuota(src_type_, &usage, NULL); + GetUsageAndQuota(src_type_, &usage, nullptr); return usage; } int64_t GetDestUsage() { int64_t usage = 0; - GetUsageAndQuota(dest_type_, &usage, NULL); + GetUsageAndQuota(dest_type_, &usage, nullptr); return usage; } diff --git a/chromium/storage/browser/fileapi/dragged_file_util.cc b/chromium/storage/browser/fileapi/dragged_file_util.cc index e9b432aff54..5ddd3940d5e 100644 --- a/chromium/storage/browser/fileapi/dragged_file_util.cc +++ b/chromium/storage/browser/fileapi/dragged_file_util.cc @@ -69,7 +69,8 @@ base::File::Error DraggedFileUtil::GetFileInfo( if (url.path().empty()) { // The root directory case. // For now we leave three time fields (modified/accessed/creation time) - // NULL as it is not really clear what to be set for this virtual directory. + // nullptr as it is not really clear what to be set for this virtual + // directory. // TODO(kinuko): Maybe we want to set the time when this filesystem is // created (i.e. when the files/directories are dropped). file_info->is_directory = true; diff --git a/chromium/storage/browser/fileapi/dragged_file_util_unittest.cc b/chromium/storage/browser/fileapi/dragged_file_util_unittest.cc index 7f0f5fe05b0..994f0a040c3 100644 --- a/chromium/storage/browser/fileapi/dragged_file_util_unittest.cc +++ b/chromium/storage/browser/fileapi/dragged_file_util_unittest.cc @@ -110,7 +110,7 @@ class DraggedFileUtilTest : public testing::Test { SimulateDropFiles(); file_system_context_ = CreateFileSystemContextForTesting( - NULL /* quota_manager */, partition_dir_.GetPath()); + nullptr /* quota_manager */, partition_dir_.GetPath()); isolated_context()->AddReference(filesystem_id_); } @@ -270,7 +270,7 @@ class DraggedFileUtilTest : public testing::Test { base::FilePath root = root_path().Append( kRootPaths[(root_path_index++) % arraysize(kRootPaths)]); toplevel_root_map_[toplevel] = root; - toplevels.AddPath(root.Append(path), NULL); + toplevels.AddPath(root.Append(path), nullptr); } SetUpOneFileSystemTestCase(toplevel_root_map_[toplevel], test_case); diff --git a/chromium/storage/browser/fileapi/dump_file_system.cc b/chromium/storage/browser/fileapi/dump_file_system.cc index 03595909cf0..d7c59304e91 100644 --- a/chromium/storage/browser/fileapi/dump_file_system.cc +++ b/chromium/storage/browser/fileapi/dump_file_system.cc @@ -80,7 +80,7 @@ static void DumpDirectoryTree(const std::string& origin_name, if (!base::DirectoryExists(origin_dir)) return; - SandboxDirectoryDatabase directory_db(origin_dir, NULL); + SandboxDirectoryDatabase directory_db(origin_dir, nullptr); SandboxDirectoryDatabase::FileId root_id; if (!directory_db.GetFileWithPath(StringToFilePath("/"), &root_id)) return; @@ -143,7 +143,7 @@ static base::FilePath GetOriginDir(const base::FilePath& file_system_dir, SandboxPrioritizedOriginDatabase::kPrimaryDirectory); } - SandboxOriginDatabase origin_db(file_system_dir, NULL); + SandboxOriginDatabase origin_db(file_system_dir, nullptr); base::FilePath origin_dir; if (!origin_db.HasOriginPath(origin_name)) { ShowMessageAndExit("Origin " + origin_name + " is not in " + @@ -165,7 +165,7 @@ static void DumpOrigin(const base::FilePath& file_system_dir, } static void DumpFileSystem(const base::FilePath& file_system_dir) { - SandboxOriginDatabase origin_db(file_system_dir, NULL); + SandboxOriginDatabase origin_db(file_system_dir, nullptr); std::vector<SandboxOriginDatabase::OriginRecord> origins; origin_db.ListAllOrigins(&origins); for (size_t i = 0; i < origins.size(); i++) { diff --git a/chromium/storage/browser/fileapi/external_mount_points_unittest.cc b/chromium/storage/browser/fileapi/external_mount_points_unittest.cc index 59be8624c40..7e6007e6de3 100644 --- a/chromium/storage/browser/fileapi/external_mount_points_unittest.cc +++ b/chromium/storage/browser/fileapi/external_mount_points_unittest.cc @@ -37,76 +37,76 @@ TEST(ExternalMountPointsTest, AddMountPoint) { const base::FilePath::CharType* const path; // Whether the mount point registration should succeed. bool success; - // Path returned by GetRegisteredPath. NULL if the method is expected to + // Path returned by GetRegisteredPath. nullptr if the method is expected to // fail. const base::FilePath::CharType* const registered_path; }; const TestCase kTestCases[] = { // Valid mount point. - { "test", DRIVE FPL("/foo/test"), true, DRIVE FPL("/foo/test") }, + {"test", DRIVE FPL("/foo/test"), true, DRIVE FPL("/foo/test")}, // Valid mount point with only one path component. - { "bbb", DRIVE FPL("/bbb"), true, DRIVE FPL("/bbb") }, + {"bbb", DRIVE FPL("/bbb"), true, DRIVE FPL("/bbb")}, // Existing mount point path is substring of the mount points path. - { "test11", DRIVE FPL("/foo/test11"), true, DRIVE FPL("/foo/test11") }, + {"test11", DRIVE FPL("/foo/test11"), true, DRIVE FPL("/foo/test11")}, // Path substring of an existing path. - { "test1", DRIVE FPL("/foo/test1"), true, DRIVE FPL("/foo/test1") }, + {"test1", DRIVE FPL("/foo/test1"), true, DRIVE FPL("/foo/test1")}, // Empty mount point name and path. - { "", DRIVE FPL(""), false, NULL }, + {"", DRIVE FPL(""), false, nullptr}, // Empty mount point name. - { "", DRIVE FPL("/ddd"), false, NULL }, + {"", DRIVE FPL("/ddd"), false, nullptr}, // Empty mount point path. - { "empty_path", FPL(""), true, FPL("") }, + {"empty_path", FPL(""), true, FPL("")}, // Name different from path's base name. - { "not_base_name", DRIVE FPL("/x/y/z"), true, DRIVE FPL("/x/y/z") }, + {"not_base_name", DRIVE FPL("/x/y/z"), true, DRIVE FPL("/x/y/z")}, // References parent. - { "invalid", DRIVE FPL("../foo/invalid"), false, NULL }, + {"invalid", DRIVE FPL("../foo/invalid"), false, nullptr}, // Relative path. - { "relative", DRIVE FPL("foo/relative"), false, NULL }, + {"relative", DRIVE FPL("foo/relative"), false, nullptr}, // Existing mount point path. - { "path_exists", DRIVE FPL("/foo/test"), false, NULL }, + {"path_exists", DRIVE FPL("/foo/test"), false, nullptr}, // Mount point with the same name exists. - { "test", DRIVE FPL("/foo/a/test_name_exists"), false, - DRIVE FPL("/foo/test") }, + {"test", DRIVE FPL("/foo/a/test_name_exists"), false, + DRIVE FPL("/foo/test")}, // Child of an existing mount point. - { "a1", DRIVE FPL("/foo/test/a"), false, NULL }, + {"a1", DRIVE FPL("/foo/test/a"), false, nullptr}, // Parent of an existing mount point. - { "foo1", DRIVE FPL("/foo"), false, NULL }, + {"foo1", DRIVE FPL("/foo"), false, nullptr}, // Bit bigger depth. - { "g", DRIVE FPL("/foo/a/b/c/d/e/f/g"), true, - DRIVE FPL("/foo/a/b/c/d/e/f/g") }, + {"g", DRIVE FPL("/foo/a/b/c/d/e/f/g"), true, + DRIVE FPL("/foo/a/b/c/d/e/f/g")}, // Sibling mount point (with similar name) exists. - { "ff", DRIVE FPL("/foo/a/b/c/d/e/ff"), true, - DRIVE FPL("/foo/a/b/c/d/e/ff") }, + {"ff", DRIVE FPL("/foo/a/b/c/d/e/ff"), true, + DRIVE FPL("/foo/a/b/c/d/e/ff")}, // Lexicographically last among existing mount points. - { "yyy", DRIVE FPL("/zzz/yyy"), true, DRIVE FPL("/zzz/yyy") }, + {"yyy", DRIVE FPL("/zzz/yyy"), true, DRIVE FPL("/zzz/yyy")}, // Parent of the lexicographically last mount point. - { "zzz1", DRIVE FPL("/zzz"), false, NULL }, + {"zzz1", DRIVE FPL("/zzz"), false, nullptr}, // Child of the lexicographically last mount point. - { "xxx1", DRIVE FPL("/zzz/yyy/xxx"), false, NULL }, + {"xxx1", DRIVE FPL("/zzz/yyy/xxx"), false, nullptr}, // Lexicographically first among existing mount points. - { "b", DRIVE FPL("/a/b"), true, DRIVE FPL("/a/b") }, + {"b", DRIVE FPL("/a/b"), true, DRIVE FPL("/a/b")}, // Parent of lexicographically first mount point. - { "a2", DRIVE FPL("/a"), false, NULL }, + {"a2", DRIVE FPL("/a"), false, nullptr}, // Child of lexicographically last mount point. - { "c1", DRIVE FPL("/a/b/c"), false, NULL }, + {"c1", DRIVE FPL("/a/b/c"), false, nullptr}, // Parent to all of the mount points. - { "root", DRIVE FPL("/"), false, NULL }, + {"root", DRIVE FPL("/"), false, nullptr}, // Path contains .. component. - { "funky", DRIVE FPL("/tt/fun/../funky"), false, NULL }, + {"funky", DRIVE FPL("/tt/fun/../funky"), false, nullptr}, // Windows separators. #if defined(FILE_PATH_USES_WIN_SEPARATORS) - { "win", DRIVE FPL("\\try\\separators\\win"), true, - DRIVE FPL("\\try\\separators\\win") }, - { "win1", DRIVE FPL("\\try/separators\\win1"), true, - DRIVE FPL("\\try/separators\\win1") }, - { "win2", DRIVE FPL("\\try/separators\\win"), false, NULL }, + {"win", DRIVE FPL("\\try\\separators\\win"), true, + DRIVE FPL("\\try\\separators\\win")}, + {"win1", DRIVE FPL("\\try/separators\\win1"), true, + DRIVE FPL("\\try/separators\\win1")}, + {"win2", DRIVE FPL("\\try/separators\\win"), false, nullptr}, #else - { "win", DRIVE FPL("\\separators\\win"), false, NULL }, - { "win1", DRIVE FPL("\\try/separators\\win1"), false, NULL }, + {"win", DRIVE FPL("\\separators\\win"), false, nullptr}, + {"win1", DRIVE FPL("\\try/separators\\win1"), false, nullptr}, #endif // Win separators, but relative path. - { "win2", DRIVE FPL("try\\separators\\win2"), false, NULL }, + {"win2", DRIVE FPL("try\\separators\\win2"), false, nullptr}, }; // Test adding mount points. @@ -124,7 +124,7 @@ TEST(ExternalMountPointsTest, AddMountPoint) { // Test that final mount point presence state is as expected. for (size_t i = 0; i < arraysize(kTestCases); ++i) { base::FilePath found_path; - EXPECT_EQ(kTestCases[i].registered_path != NULL, + EXPECT_EQ(kTestCases[i].registered_path != nullptr, mount_points->GetRegisteredPath(kTestCases[i].name, &found_path)) << "Test case: " << i; diff --git a/chromium/storage/browser/fileapi/file_stream_reader.h b/chromium/storage/browser/fileapi/file_stream_reader.h index d7abbf2e23b..99fba8ce7b4 100644 --- a/chromium/storage/browser/fileapi/file_stream_reader.h +++ b/chromium/storage/browser/fileapi/file_stream_reader.h @@ -9,7 +9,7 @@ #include "base/compiler_specific.h" #include "base/files/file.h" -#include "net/base/completion_callback.h" +#include "net/base/completion_once_callback.h" #include "storage/browser/storage_browser_export.h" namespace base { @@ -80,8 +80,9 @@ class FileStreamReader { // // If the stream is deleted while it has an in-flight Read operation // |callback| will not be called. - virtual int Read(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) = 0; + virtual int Read(net::IOBuffer* buf, + int buf_len, + net::CompletionOnceCallback callback) = 0; // Returns the length of the file if it could successfully retrieve the // file info *and* its last modification time equals to @@ -92,7 +93,7 @@ class FileStreamReader { // Note that the return type is int64_t to return a larger file's size (a file // larger than 2G) but an error code should fit in the int range (may be // smaller than int64_t range). - virtual int64_t GetLength(const net::Int64CompletionCallback& callback) = 0; + virtual int64_t GetLength(net::Int64CompletionOnceCallback callback) = 0; }; } // namespace storage diff --git a/chromium/storage/browser/fileapi/file_stream_writer.h b/chromium/storage/browser/fileapi/file_stream_writer.h index bfbdbf52dc6..83fc07113c6 100644 --- a/chromium/storage/browser/fileapi/file_stream_writer.h +++ b/chromium/storage/browser/fileapi/file_stream_writer.h @@ -7,7 +7,7 @@ #include <stdint.h> -#include "net/base/completion_callback.h" +#include "net/base/completion_once_callback.h" #include "storage/browser/storage_browser_export.h" namespace base { @@ -59,8 +59,9 @@ class FileStreamWriter { // or there is not enough room left on the disk. // // It is invalid to call Write while there is an in-flight async operation. - virtual int Write(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) = 0; + virtual int Write(net::IOBuffer* buf, + int buf_len, + net::CompletionOnceCallback callback) = 0; // Cancels an in-flight async operation. // @@ -74,7 +75,7 @@ class FileStreamWriter { // In either case, the callback function passed to the in-flight async // operation is dismissed immediately when Cancel() is called, and thus // will never be called. - virtual int Cancel(const net::CompletionCallback& callback) = 0; + virtual int Cancel(net::CompletionOnceCallback callback) = 0; // Flushes the data written so far. // @@ -84,7 +85,7 @@ class FileStreamWriter { // called when the flush has completed. // // It is invalid to call Flush while there is an in-flight async operation. - virtual int Flush(const net::CompletionCallback& callback) = 0; + virtual int Flush(net::CompletionOnceCallback callback) = 0; }; } // namespace storage diff --git a/chromium/storage/browser/fileapi/file_system_backend.h b/chromium/storage/browser/fileapi/file_system_backend.h index cb81fd63aae..31afaaffa5f 100644 --- a/chromium/storage/browser/fileapi/file_system_backend.h +++ b/chromium/storage/browser/fileapi/file_system_backend.h @@ -83,7 +83,7 @@ class STORAGE_EXPORT FileSystemBackend { virtual WatcherManager* GetWatcherManager(FileSystemType type) = 0; // Returns the specialized CopyOrMoveFileValidatorFactory for this backend - // and |type|. If |error_code| is File::FILE_OK and the result is NULL, + // and |type|. If |error_code| is File::FILE_OK and the result is nullptr, // then no validator is required. virtual CopyOrMoveFileValidatorFactory* GetCopyOrMoveFileValidatorFactory( FileSystemType type, base::File::Error* error_code) = 0; @@ -135,20 +135,20 @@ class STORAGE_EXPORT FileSystemBackend { FileSystemContext* context) const = 0; // Returns the specialized FileSystemQuotaUtil for this backend. - // This could return NULL if this backend does not support quota. + // This could return nullptr if this backend does not support quota. virtual FileSystemQuotaUtil* GetQuotaUtil() = 0; - // Returns the update observer list for |type|. It may return NULL when no + // Returns the update observer list for |type|. It may return nullptr when no // observers are added. virtual const UpdateObserverList* GetUpdateObservers( FileSystemType type) const = 0; - // Returns the change observer list for |type|. It may return NULL when no + // Returns the change observer list for |type|. It may return nullptr when no // observers are added. virtual const ChangeObserverList* GetChangeObservers( FileSystemType type) const = 0; - // Returns the access observer list for |type|. It may return NULL when no + // Returns the access observer list for |type|. It may return nullptr when no // observers are added. virtual const AccessObserverList* GetAccessObservers( FileSystemType type) const = 0; diff --git a/chromium/storage/browser/fileapi/file_system_context.cc b/chromium/storage/browser/fileapi/file_system_context.cc index bd0519890b5..2764e3876cd 100644 --- a/chromium/storage/browser/fileapi/file_system_context.cc +++ b/chromium/storage/browser/fileapi/file_system_context.cc @@ -100,6 +100,7 @@ int FileSystemContext::GetPermissionPolicy(FileSystemType type) { case kFileSystemTypeCloudDevice: case kFileSystemTypeProvided: case kFileSystemTypeDeviceMediaAsFileStorage: + case kFileSystemTypeDriveFs: return FILE_PERMISSION_USE_FILE_PERMISSION; case kFileSystemTypeRestrictedNativeLocal: @@ -256,7 +257,7 @@ FileSystemQuotaUtil* FileSystemContext::GetQuotaUtil(FileSystemType type) const { FileSystemBackend* backend = GetFileSystemBackend(type); if (!backend) - return NULL; + return nullptr; return backend->GetQuotaUtil(); } @@ -264,7 +265,7 @@ AsyncFileUtil* FileSystemContext::GetAsyncFileUtil( FileSystemType type) const { FileSystemBackend* backend = GetFileSystemBackend(type); if (!backend) - return NULL; + return nullptr; return backend->GetAsyncFileUtil(type); } @@ -275,7 +276,7 @@ FileSystemContext::GetCopyOrMoveFileValidatorFactory( *error_code = base::File::FILE_OK; FileSystemBackend* backend = GetFileSystemBackend(type); if (!backend) - return NULL; + return nullptr; return backend->GetCopyOrMoveFileValidatorFactory( type, error_code); } @@ -286,14 +287,14 @@ FileSystemBackend* FileSystemContext::GetFileSystemBackend( if (found != backend_map_.end()) return found->second; NOTREACHED() << "Unknown filesystem type: " << type; - return NULL; + return nullptr; } WatcherManager* FileSystemContext::GetWatcherManager( FileSystemType type) const { FileSystemBackend* backend = GetFileSystemBackend(type); if (!backend) - return NULL; + return nullptr; return backend->GetWatcherManager(type); } @@ -524,14 +525,14 @@ FileSystemOperation* FileSystemContext::CreateFileSystemOperation( if (!url.is_valid()) { if (error_code) *error_code = base::File::FILE_ERROR_INVALID_URL; - return NULL; + return nullptr; } FileSystemBackend* backend = GetFileSystemBackend(url.type()); if (!backend) { if (error_code) *error_code = base::File::FILE_ERROR_FAILED; - return NULL; + return nullptr; } base::File::Error fs_error = base::File::FILE_OK; diff --git a/chromium/storage/browser/fileapi/file_system_context.h b/chromium/storage/browser/fileapi/file_system_context.h index 24f576c0f3b..9fc86106716 100644 --- a/chromium/storage/browser/fileapi/file_system_context.h +++ b/chromium/storage/browser/fileapi/file_system_context.h @@ -108,8 +108,8 @@ class STORAGE_EXPORT FileSystemContext // does). // // |external_mount_points| contains non-system external mount points available - // in the context. If not NULL, it will be used during URL cracking. - // |external_mount_points| may be NULL only on platforms different from + // in the context. If not nullptr, it will be used during URL cracking. + // |external_mount_points| may be nullptr only on platforms different from // ChromeOS (i.e. platforms that don't use external_mount_point_provider). // // |additional_backends| are added to the internal backend map @@ -134,7 +134,7 @@ class STORAGE_EXPORT FileSystemContext bool DeleteDataForOriginOnFileTaskRunner(const GURL& origin_url); // Creates a new QuotaReservation for the given |origin_url| and |type|. - // Returns NULL if |type| does not support quota or reservation fails. + // Returns nullptr if |type| does not support quota or reservation fails. // This should be run on |default_file_task_runner_| and the returned value // should be destroyed on the runner. scoped_refptr<QuotaReservation> CreateQuotaReservationOnFileTaskRunner( @@ -149,7 +149,7 @@ class STORAGE_EXPORT FileSystemContext void Shutdown(); // Returns a quota util for a given filesystem type. This may - // return NULL if the type does not support the usage tracking or + // return nullptr if the type does not support the usage tracking or // it is not a quota-managed storage. FileSystemQuotaUtil* GetQuotaUtil(FileSystemType type) const; @@ -157,23 +157,23 @@ class STORAGE_EXPORT FileSystemContext AsyncFileUtil* GetAsyncFileUtil(FileSystemType type) const; // Returns the appropriate CopyOrMoveFileValidatorFactory for the given - // |type|. If |error_code| is File::FILE_OK and the result is NULL, + // |type|. If |error_code| is File::FILE_OK and the result is nullptr, // then no validator is required. CopyOrMoveFileValidatorFactory* GetCopyOrMoveFileValidatorFactory( FileSystemType type, base::File::Error* error_code) const; // Returns the file system backend instance for the given |type|. - // This may return NULL if it is given an invalid or unsupported filesystem + // This may return nullptr if it is given an invalid or unsupported filesystem // type. FileSystemBackend* GetFileSystemBackend( FileSystemType type) const; // Returns the watcher manager for the given |type|. - // This may return NULL if the type does not support watching. + // This may return nullptr if the type does not support watching. WatcherManager* GetWatcherManager(FileSystemType type) const; // Returns true for sandboxed filesystems. Currently this does - // the same as GetQuotaUtil(type) != NULL. (In an assumption that + // the same as GetQuotaUtil(type) != nullptr. (In an assumption that // all sandboxed filesystems must cooperate with QuotaManager so that // they can get deleted) bool IsSandboxFileSystem(FileSystemType type) const; diff --git a/chromium/storage/browser/fileapi/file_system_context_unittest.cc b/chromium/storage/browser/fileapi/file_system_context_unittest.cc index d1d9059f73b..213db6ef41b 100644 --- a/chromium/storage/browser/fileapi/file_system_context_unittest.cc +++ b/chromium/storage/browser/fileapi/file_system_context_unittest.cc @@ -101,12 +101,12 @@ class FileSystemContextTest : public testing::Test { scoped_refptr<MockQuotaManager> mock_quota_manager_; }; -// It is not valid to pass NULL ExternalMountPoints to FileSystemContext on +// It is not valid to pass nullptr ExternalMountPoints to FileSystemContext on // ChromeOS. #if !defined(OS_CHROMEOS) TEST_F(FileSystemContextTest, NullExternalMountPoints) { scoped_refptr<FileSystemContext> file_system_context( - CreateFileSystemContextForTest(NULL)); + CreateFileSystemContextForTest(nullptr)); // Cracking system external mount and isolated mount points should work. std::string isolated_name = "root"; @@ -171,7 +171,7 @@ TEST_F(FileSystemContextTest, FileSystemContextKeepsMountPointsAlive) { CreateFileSystemContextForTest(mount_points.get())); // Release a MountPoints reference created in the test. - mount_points = NULL; + mount_points = nullptr; // FileSystemContext should keep a reference to the |mount_points|, so it // should be able to resolve the URL. diff --git a/chromium/storage/browser/fileapi/file_system_dir_url_request_job_unittest.cc b/chromium/storage/browser/fileapi/file_system_dir_url_request_job_unittest.cc index fd57b21b7d1..c7dac7e1908 100644 --- a/chromium/storage/browser/fileapi/file_system_dir_url_request_job_unittest.cc +++ b/chromium/storage/browser/fileapi/file_system_dir_url_request_job_unittest.cc @@ -133,7 +133,7 @@ class FileSystemDirURLRequestJobTest : public testing::Test { special_storage_policy_ = new MockSpecialStoragePolicy; file_system_context_ = - CreateFileSystemContextForTesting(NULL, temp_dir_.GetPath()); + CreateFileSystemContextForTesting(nullptr, temp_dir_.GetPath()); file_system_context_->OpenFileSystem( GURL("http://remote/"), storage::kFileSystemTypeTemporary, @@ -145,8 +145,8 @@ class FileSystemDirURLRequestJobTest : public testing::Test { void TearDown() override { // NOTE: order matters, request must die before delegate - request_.reset(NULL); - delegate_.reset(NULL); + request_.reset(nullptr); + delegate_.reset(nullptr); } void SetUpAutoMountContext(base::FilePath* mnt_point) { @@ -162,7 +162,8 @@ class FileSystemDirURLRequestJobTest : public testing::Test { handlers.push_back(base::Bind(&TestAutoMountForURLRequest)); file_system_context_ = CreateFileSystemContextWithAutoMountersForTesting( - NULL, std::move(additional_providers), handlers, temp_dir_.GetPath()); + nullptr, std::move(additional_providers), handlers, + temp_dir_.GetPath()); } void OnOpenFileSystem(const GURL& root_url, @@ -225,8 +226,9 @@ class FileSystemDirURLRequestJobTest : public testing::Test { void EnsureFileExists(const base::StringPiece file_name) { base::FilePath path = base::FilePath().AppendASCII(file_name); std::unique_ptr<FileSystemOperationContext> context(NewOperationContext()); - ASSERT_EQ(base::File::FILE_OK, file_util()->EnsureFileExists( - context.get(), CreateURL(path), NULL)); + ASSERT_EQ( + base::File::FILE_OK, + file_util()->EnsureFileExists(context.get(), CreateURL(path), nullptr)); } void TruncateFile(const base::StringPiece file_name, int64_t length) { @@ -375,7 +377,7 @@ TEST_F(FileSystemDirURLRequestJobTest, Incognito) { CreateDirectory("foo"); scoped_refptr<FileSystemContext> file_system_context = - CreateIncognitoFileSystemContextForTesting(NULL, temp_dir_.GetPath()); + CreateIncognitoFileSystemContextForTesting(nullptr, temp_dir_.GetPath()); TestRequestWithContext(CreateFileSystemURL("/"), file_system_context.get()); diff --git a/chromium/storage/browser/fileapi/file_system_file_stream_reader.cc b/chromium/storage/browser/fileapi/file_system_file_stream_reader.cc index 78d91e36cc2..8511e2107a4 100644 --- a/chromium/storage/browser/fileapi/file_system_file_stream_reader.cc +++ b/chromium/storage/browser/fileapi/file_system_file_stream_reader.cc @@ -6,6 +6,8 @@ #include <stdint.h> +#include <utility> + #include "base/single_thread_task_runner.h" #include "net/base/file_stream.h" #include "net/base/io_buffer.h" @@ -28,88 +30,53 @@ FileStreamReader* FileStreamReader::CreateForFileSystemFile( file_system_context, url, initial_offset, expected_modification_time); } -} // namespace storage - -namespace storage { - -namespace { - -void ReadAdapter(base::WeakPtr<FileSystemFileStreamReader> reader, - net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) { - if (!reader.get()) - return; - int rv = reader->Read(buf, buf_len, callback); - if (rv != net::ERR_IO_PENDING) - callback.Run(rv); -} - -void GetLengthAdapter(base::WeakPtr<FileSystemFileStreamReader> reader, - const net::Int64CompletionCallback& callback) { - if (!reader.get()) - return; - int rv = reader->GetLength(callback); - if (rv != net::ERR_IO_PENDING) - callback.Run(rv); -} - -void Int64CallbackAdapter(const net::Int64CompletionCallback& callback, - int value) { - callback.Run(value); -} - -} // namespace - -FileSystemFileStreamReader::~FileSystemFileStreamReader() = default; - -int FileSystemFileStreamReader::Read( - net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) { - if (local_file_reader_) - return local_file_reader_->Read(buf, buf_len, callback); - return CreateSnapshot(base::Bind(&ReadAdapter, weak_factory_.GetWeakPtr(), - base::RetainedRef(buf), buf_len, callback), - callback); -} - -int64_t FileSystemFileStreamReader::GetLength( - const net::Int64CompletionCallback& callback) { - if (local_file_reader_) - return local_file_reader_->GetLength(callback); - return CreateSnapshot( - base::Bind(&GetLengthAdapter, weak_factory_.GetWeakPtr(), callback), - base::Bind(&Int64CallbackAdapter, callback)); -} - FileSystemFileStreamReader::FileSystemFileStreamReader( FileSystemContext* file_system_context, const FileSystemURL& url, int64_t initial_offset, const base::Time& expected_modification_time) - : file_system_context_(file_system_context), + : read_buf_(nullptr), + read_buf_len_(0), + file_system_context_(file_system_context), url_(url), initial_offset_(initial_offset), expected_modification_time_(expected_modification_time), has_pending_create_snapshot_(false), weak_factory_(this) {} -int FileSystemFileStreamReader::CreateSnapshot( - const base::Closure& callback, - const net::CompletionCallback& error_callback) { +FileSystemFileStreamReader::~FileSystemFileStreamReader() = default; + +int FileSystemFileStreamReader::Read(net::IOBuffer* buf, + int buf_len, + net::CompletionOnceCallback callback) { + if (local_file_reader_) + return local_file_reader_->Read(buf, buf_len, std::move(callback)); + + read_buf_ = buf; + read_buf_len_ = buf_len; + read_callback_ = std::move(callback); + return CreateSnapshot(); +} + +int64_t FileSystemFileStreamReader::GetLength( + net::Int64CompletionOnceCallback callback) { + if (local_file_reader_) + return local_file_reader_->GetLength(std::move(callback)); + + get_length_callback_ = std::move(callback); + return CreateSnapshot(); +} + +int FileSystemFileStreamReader::CreateSnapshot() { DCHECK(!has_pending_create_snapshot_); has_pending_create_snapshot_ = true; file_system_context_->operation_runner()->CreateSnapshotFile( - url_, - base::Bind(&FileSystemFileStreamReader::DidCreateSnapshot, - weak_factory_.GetWeakPtr(), - callback, - error_callback)); + url_, base::BindOnce(&FileSystemFileStreamReader::DidCreateSnapshot, + weak_factory_.GetWeakPtr())); return net::ERR_IO_PENDING; } void FileSystemFileStreamReader::DidCreateSnapshot( - const base::Closure& callback, - const net::CompletionCallback& error_callback, base::File::Error file_error, const base::File::Info& file_info, const base::FilePath& platform_path, @@ -119,19 +86,44 @@ void FileSystemFileStreamReader::DidCreateSnapshot( has_pending_create_snapshot_ = false; if (file_error != base::File::FILE_OK) { - error_callback.Run(net::FileErrorToNetError(file_error)); + if (read_callback_) { + DCHECK(!get_length_callback_); + std::move(read_callback_).Run(net::FileErrorToNetError(file_error)); + return; + } + std::move(get_length_callback_).Run(net::FileErrorToNetError(file_error)); return; } // Keep the reference (if it's non-null) so that the file won't go away. snapshot_ref_ = std::move(file_ref); - local_file_reader_.reset( - FileStreamReader::CreateForLocalFile( - file_system_context_->default_file_task_runner(), - platform_path, initial_offset_, expected_modification_time_)); + local_file_reader_.reset(FileStreamReader::CreateForLocalFile( + file_system_context_->default_file_task_runner(), platform_path, + initial_offset_, expected_modification_time_)); + + if (read_callback_) { + DCHECK(!get_length_callback_); + int rv = Read(read_buf_, read_buf_len_, + base::BindOnce(&FileSystemFileStreamReader::OnRead, + weak_factory_.GetWeakPtr())); + if (rv != net::ERR_IO_PENDING) + std::move(read_callback_).Run(rv); + return; + } + + int rv = local_file_reader_->GetLength(base::BindOnce( + &FileSystemFileStreamReader::OnGetLength, weak_factory_.GetWeakPtr())); + if (rv != net::ERR_IO_PENDING) + std::move(get_length_callback_).Run(rv); +} + +void FileSystemFileStreamReader::OnRead(int rv) { + std::move(read_callback_).Run(rv); +} - callback.Run(); +void FileSystemFileStreamReader::OnGetLength(int64_t rv) { + std::move(get_length_callback_).Run(rv); } } // namespace storage diff --git a/chromium/storage/browser/fileapi/file_system_file_stream_reader.h b/chromium/storage/browser/fileapi/file_system_file_stream_reader.h index e6bd8e3c755..78ff4e92521 100644 --- a/chromium/storage/browser/fileapi/file_system_file_stream_reader.h +++ b/chromium/storage/browser/fileapi/file_system_file_stream_reader.h @@ -14,6 +14,7 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/time/time.h" +#include "net/base/completion_once_callback.h" #include "storage/browser/blob/shareable_file_reference.h" #include "storage/browser/fileapi/file_stream_reader.h" #include "storage/browser/fileapi/file_system_url.h" @@ -44,8 +45,8 @@ class STORAGE_EXPORT FileSystemFileStreamReader // FileStreamReader overrides. int Read(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) override; - int64_t GetLength(const net::Int64CompletionCallback& callback) override; + net::CompletionOnceCallback callback) override; + int64_t GetLength(net::Int64CompletionOnceCallback callback) override; private: friend class storage::FileStreamReader; @@ -56,16 +57,19 @@ class STORAGE_EXPORT FileSystemFileStreamReader int64_t initial_offset, const base::Time& expected_modification_time); - int CreateSnapshot(const base::Closure& callback, - const net::CompletionCallback& error_callback); + int CreateSnapshot(); void DidCreateSnapshot( - const base::Closure& callback, - const net::CompletionCallback& error_callback, base::File::Error file_error, const base::File::Info& file_info, const base::FilePath& platform_path, scoped_refptr<storage::ShareableFileReference> file_ref); + void OnRead(int rv); + void OnGetLength(int64_t rv); + net::IOBuffer* read_buf_; + int read_buf_len_; + net::CompletionOnceCallback read_callback_; + net::Int64CompletionOnceCallback get_length_callback_; scoped_refptr<FileSystemContext> file_system_context_; FileSystemURL url_; const int64_t initial_offset_; diff --git a/chromium/storage/browser/fileapi/file_system_file_stream_reader_unittest.cc b/chromium/storage/browser/fileapi/file_system_file_stream_reader_unittest.cc index 067efc3a870..444f2aef70c 100644 --- a/chromium/storage/browser/fileapi/file_system_file_stream_reader_unittest.cc +++ b/chromium/storage/browser/fileapi/file_system_file_stream_reader_unittest.cc @@ -44,8 +44,8 @@ void ReadFromReader(storage::FileSystemFileStreamReader* reader, std::string* data, size_t size, int* result) { - ASSERT_TRUE(reader != NULL); - ASSERT_TRUE(result != NULL); + ASSERT_TRUE(reader != nullptr); + ASSERT_TRUE(result != nullptr); *result = net::OK; net::TestCompletionCallback callback; size_t total_bytes_read = 0; @@ -76,7 +76,7 @@ class FileSystemFileStreamReaderTest : public testing::Test { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); file_system_context_ = - CreateFileSystemContextForTesting(NULL, temp_dir_.GetPath()); + CreateFileSystemContextForTesting(nullptr, temp_dir_.GetPath()); file_system_context_->OpenFileSystem( GURL(kURLOrigin), storage::kFileSystemTypeTemporary, @@ -156,7 +156,7 @@ TEST_F(FileSystemFileStreamReaderTest, NonExistent) { TEST_F(FileSystemFileStreamReaderTest, Empty) { const char kFileName[] = "empty"; - WriteFile(kFileName, NULL, 0, NULL); + WriteFile(kFileName, nullptr, 0, nullptr); std::unique_ptr<FileSystemFileStreamReader> reader( CreateFileReader(kFileName, 0, base::Time())); @@ -196,7 +196,7 @@ TEST_F(FileSystemFileStreamReaderTest, GetLengthAfterModified) { result = callback.WaitForResult(); ASSERT_EQ(net::ERR_UPLOAD_FILE_CHANGED, result); - // With NULL expected modification time this should work. + // With nullptr expected modification time this should work. reader.reset(CreateFileReader(kTestFileName, 0, base::Time())); result = reader->GetLength(callback.callback()); if (result == net::ERR_IO_PENDING) @@ -238,7 +238,7 @@ TEST_F(FileSystemFileStreamReaderTest, ReadAfterModified) { ASSERT_EQ(net::ERR_UPLOAD_FILE_CHANGED, result); ASSERT_EQ(0U, data.size()); - // With NULL expected modification time this should work. + // With nullptr expected modification time this should work. data.clear(); reader.reset(CreateFileReader(kTestFileName, 0, base::Time())); ReadFromReader(reader.get(), &data, kTestDataSize, &result); diff --git a/chromium/storage/browser/fileapi/file_system_file_util.h b/chromium/storage/browser/fileapi/file_system_file_util.h index f38e000d061..bd0d0a9c0cb 100644 --- a/chromium/storage/browser/fileapi/file_system_file_util.h +++ b/chromium/storage/browser/fileapi/file_system_file_util.h @@ -125,14 +125,17 @@ class STORAGE_EXPORT FileSystemFileUtil { const FileSystemURL& url, int64_t length) = 0; - // Copies or moves a single file from |src_url| to |dest_url|. - // The filesystem type of |src_url| and |dest_url| MUST be same. - // For |option|, please see file_system_operation.h + // Copies a single file or moves a single file or directory from |src_url| to + // |dest_url|. Whether moving a directory is supported is + // implementation-defined. The filesystem type of |src_url| and |dest_url| + // MUST be same. For |option|, please see file_system_operation.h // // This returns: // - File::FILE_ERROR_NOT_FOUND if |src_url| // or the parent directory of |dest_url| does not exist. - // - File::FILE_ERROR_NOT_A_FILE if |src_url| exists but is not a file. + // - File::FILE_ERROR_NOT_A_FILE if |src_url| exists but is not a file and the + // operation is copy or the implementation does not support moving + // directories. // - File::FILE_ERROR_INVALID_OPERATION if |dest_url| exists and // is not a file. // - File::FILE_ERROR_FAILED if |dest_url| does not exist and diff --git a/chromium/storage/browser/fileapi/file_system_operation.h b/chromium/storage/browser/fileapi/file_system_operation.h index 55a613a2080..dc8288d4ae5 100644 --- a/chromium/storage/browser/fileapi/file_system_operation.h +++ b/chromium/storage/browser/fileapi/file_system_operation.h @@ -15,6 +15,7 @@ #include "base/files/file_path.h" #include "base/process/process.h" #include "components/services/filesystem/public/interfaces/types.mojom.h" +#include "storage/browser/blob/blob_reader.h" #include "storage/browser/fileapi/file_system_operation_context.h" #include "storage/browser/storage_browser_export.h" @@ -22,10 +23,6 @@ namespace base { class Time; } -namespace net { -class URLRequest; -} - namespace storage { class ShareableFileReference; } @@ -106,13 +103,13 @@ class FileSystemOperation { // snapshot file. It can be set to let the chromium backend take // care of the life time of the snapshot file. Otherwise (if the returned // file does not require any handling) the implementation can just - // return NULL. In a more complex case, the implementaiton can manage + // return nullptr. In a more complex case, the implementation can manage // the lifetime of the snapshot file on its own (e.g. by its cache system) // but also can be notified via the reference when the file becomes no // longer necessary in the javascript world. // Please see the comment for ShareableFileReference for details. // - using SnapshotFileCallback = base::Callback<void( + using SnapshotFileCallback = base::OnceCallback<void( base::File::Error result, const base::File::Info& file_info, const base::FilePath& platform_path, @@ -321,10 +318,10 @@ class FileSystemOperation { virtual void Remove(const FileSystemURL& path, bool recursive, const StatusCallback& callback) = 0; - // Writes the data read from |blob_request| using |writer_delegate|. + // Writes the data read from |blob_reader| using |writer_delegate|. virtual void Write(const FileSystemURL& url, std::unique_ptr<FileWriterDelegate> writer_delegate, - std::unique_ptr<net::URLRequest> blob_request, + std::unique_ptr<BlobReader> blob_reader, const WriteCallback& callback) = 0; // Truncates a file at |path| to |length|. If |length| is larger than @@ -386,7 +383,7 @@ class FileSystemOperation { // temporary file. Or if the implementaiton already has the local cache // data for |path| it can simply return the path to the cache. virtual void CreateSnapshotFile(const FileSystemURL& path, - const SnapshotFileCallback& callback) = 0; + SnapshotFileCallback callback) = 0; // Copies in a single file from a different filesystem. // diff --git a/chromium/storage/browser/fileapi/file_system_operation_impl.cc b/chromium/storage/browser/fileapi/file_system_operation_impl.cc index fb7c6d70213..a7bc40018c3 100644 --- a/chromium/storage/browser/fileapi/file_system_operation_impl.cc +++ b/chromium/storage/browser/fileapi/file_system_operation_impl.cc @@ -191,12 +191,12 @@ void FileSystemOperationImpl::Remove(const FileSystemURL& url, void FileSystemOperationImpl::Write( const FileSystemURL& url, std::unique_ptr<FileWriterDelegate> writer_delegate, - std::unique_ptr<net::URLRequest> blob_request, + std::unique_ptr<BlobReader> blob_reader, const WriteCallback& callback) { DCHECK(SetPendingOperationType(kOperationWrite)); file_writer_delegate_ = std::move(writer_delegate); file_writer_delegate_->Start( - std::move(blob_request), + std::move(blob_reader), base::Bind(&FileSystemOperationImpl::DidWrite, weak_factory_.GetWeakPtr(), url, callback)); } @@ -277,10 +277,10 @@ void FileSystemOperationImpl::Cancel(const StatusCallback& cancel_callback) { void FileSystemOperationImpl::CreateSnapshotFile( const FileSystemURL& url, - const SnapshotFileCallback& callback) { + SnapshotFileCallback callback) { DCHECK(SetPendingOperationType(kOperationCreateSnapshotFile)); async_file_util_->CreateSnapshotFile(std::move(operation_context_), url, - callback); + std::move(callback)); } void FileSystemOperationImpl::CopyInForeignFile( @@ -377,9 +377,11 @@ FileSystemOperationImpl::FileSystemOperationImpl( std::unique_ptr<FileSystemOperationContext> operation_context) : file_system_context_(file_system_context), operation_context_(std::move(operation_context)), - async_file_util_(NULL), + async_file_util_(nullptr), pending_operation_(kOperationNone), weak_factory_(this) { + weak_ptr_ = weak_factory_.GetWeakPtr(); + DCHECK(operation_context_.get()); operation_context_->DetachFromSequence(); async_file_util_ = file_system_context_->GetAsyncFileUtil(url.type()); @@ -407,7 +409,7 @@ void FileSystemOperationImpl::GetUsageAndQuotaThenRunTask( quota_manager_proxy->quota_manager()->GetUsageAndQuota( url.origin(), FileSystemTypeToQuotaStorageType(url.type()), base::BindOnce(&FileSystemOperationImpl::DidGetUsageAndQuotaAndRunTask, - weak_factory_.GetWeakPtr(), task, error_callback)); + weak_ptr_, task, error_callback)); } void FileSystemOperationImpl::DidGetUsageAndQuotaAndRunTask( @@ -435,7 +437,7 @@ void FileSystemOperationImpl::DoCreateFile( base::BindOnce( exclusive ? &FileSystemOperationImpl::DidEnsureFileExistsExclusive : &FileSystemOperationImpl::DidEnsureFileExistsNonExclusive, - weak_factory_.GetWeakPtr(), callback)); + weak_ptr_, callback)); } void FileSystemOperationImpl::DoCreateDirectory( @@ -444,8 +446,8 @@ void FileSystemOperationImpl::DoCreateDirectory( bool exclusive, bool recursive) { async_file_util_->CreateDirectory( std::move(operation_context_), url, exclusive, recursive, - base::BindOnce(&FileSystemOperationImpl::DidFinishOperation, - weak_factory_.GetWeakPtr(), callback)); + base::BindOnce(&FileSystemOperationImpl::DidFinishOperation, weak_ptr_, + callback)); } void FileSystemOperationImpl::DoCopyFileLocal( @@ -457,8 +459,8 @@ void FileSystemOperationImpl::DoCopyFileLocal( async_file_util_->CopyFileLocal( std::move(operation_context_), src_url, dest_url, option, progress_callback, - base::BindOnce(&FileSystemOperationImpl::DidFinishOperation, - weak_factory_.GetWeakPtr(), callback)); + base::BindOnce(&FileSystemOperationImpl::DidFinishOperation, weak_ptr_, + callback)); } void FileSystemOperationImpl::DoMoveFileLocal( @@ -468,8 +470,8 @@ void FileSystemOperationImpl::DoMoveFileLocal( const StatusCallback& callback) { async_file_util_->MoveFileLocal( std::move(operation_context_), src_url, dest_url, option, - base::BindOnce(&FileSystemOperationImpl::DidFinishOperation, - weak_factory_.GetWeakPtr(), callback)); + base::BindOnce(&FileSystemOperationImpl::DidFinishOperation, weak_ptr_, + callback)); } void FileSystemOperationImpl::DoCopyInForeignFile( @@ -478,8 +480,8 @@ void FileSystemOperationImpl::DoCopyInForeignFile( const StatusCallback& callback) { async_file_util_->CopyInForeignFile( std::move(operation_context_), src_local_disk_file_path, dest_url, - base::BindOnce(&FileSystemOperationImpl::DidFinishOperation, - weak_factory_.GetWeakPtr(), callback)); + base::BindOnce(&FileSystemOperationImpl::DidFinishOperation, weak_ptr_, + callback)); } void FileSystemOperationImpl::DoTruncate(const FileSystemURL& url, @@ -487,8 +489,8 @@ void FileSystemOperationImpl::DoTruncate(const FileSystemURL& url, int64_t length) { async_file_util_->Truncate( std::move(operation_context_), url, length, - base::BindOnce(&FileSystemOperationImpl::DidFinishOperation, - weak_factory_.GetWeakPtr(), callback)); + base::BindOnce(&FileSystemOperationImpl::DidFinishOperation, weak_ptr_, + callback)); } void FileSystemOperationImpl::DoOpenFile(const FileSystemURL& url, @@ -496,8 +498,7 @@ void FileSystemOperationImpl::DoOpenFile(const FileSystemURL& url, int file_flags) { async_file_util_->CreateOrOpen( std::move(operation_context_), url, file_flags, - base::BindOnce(&DidOpenFile, file_system_context_, - weak_factory_.GetWeakPtr(), callback)); + base::BindOnce(&DidOpenFile, file_system_context_, weak_ptr_, callback)); } void FileSystemOperationImpl::DidEnsureFileExistsExclusive( @@ -557,11 +558,10 @@ void FileSystemOperationImpl::DidDeleteRecursively( if (rv == base::File::FILE_ERROR_INVALID_OPERATION) { // Recursive removal is not supported on this platform. DCHECK(!recursive_operation_delegate_); - recursive_operation_delegate_.reset( - new RemoveOperationDelegate( - file_system_context(), url, - base::Bind(&FileSystemOperationImpl::DidFinishOperation, - weak_factory_.GetWeakPtr(), callback))); + recursive_operation_delegate_.reset(new RemoveOperationDelegate( + file_system_context(), url, + base::Bind(&FileSystemOperationImpl::DidFinishOperation, weak_ptr_, + callback))); recursive_operation_delegate_->RunRecursively(); return; } diff --git a/chromium/storage/browser/fileapi/file_system_operation_impl.h b/chromium/storage/browser/fileapi/file_system_operation_impl.h index 6b4df8486a1..cc683906472 100644 --- a/chromium/storage/browser/fileapi/file_system_operation_impl.h +++ b/chromium/storage/browser/fileapi/file_system_operation_impl.h @@ -64,7 +64,7 @@ class STORAGE_EXPORT FileSystemOperationImpl : public FileSystemOperation { const StatusCallback& callback) override; void Write(const FileSystemURL& url, std::unique_ptr<FileWriterDelegate> writer_delegate, - std::unique_ptr<net::URLRequest> blob_request, + std::unique_ptr<BlobReader> blob_reader, const WriteCallback& callback) override; void Truncate(const FileSystemURL& url, int64_t length, @@ -78,7 +78,7 @@ class STORAGE_EXPORT FileSystemOperationImpl : public FileSystemOperation { const OpenFileCallback& callback) override; void Cancel(const StatusCallback& cancel_callback) override; void CreateSnapshotFile(const FileSystemURL& path, - const SnapshotFileCallback& callback) override; + SnapshotFileCallback callback) override; void CopyInForeignFile(const base::FilePath& src_local_disk_path, const FileSystemURL& dest_url, const StatusCallback& callback) override; @@ -198,6 +198,7 @@ class STORAGE_EXPORT FileSystemOperationImpl : public FileSystemOperation { // A flag to make sure we call operation only once per instance. OperationType pending_operation_; + base::WeakPtr<FileSystemOperationImpl> weak_ptr_; base::WeakPtrFactory<FileSystemOperationImpl> weak_factory_; DISALLOW_COPY_AND_ASSIGN(FileSystemOperationImpl); diff --git a/chromium/storage/browser/fileapi/file_system_operation_impl_unittest.cc b/chromium/storage/browser/fileapi/file_system_operation_impl_unittest.cc index 7352c9ce23d..bc6eb31cf9a 100644 --- a/chromium/storage/browser/fileapi/file_system_operation_impl_unittest.cc +++ b/chromium/storage/browser/fileapi/file_system_operation_impl_unittest.cc @@ -73,7 +73,7 @@ class FileSystemOperationImplTest quota_manager_ = new MockQuotaManager(false /* is_incognito */, base_dir, base::ThreadTaskRunnerHandle::Get().get(), - NULL /* special storage policy */); + nullptr /* special storage policy */); quota_manager_proxy_ = new MockQuotaManagerProxy( quota_manager(), base::ThreadTaskRunnerHandle::Get().get()); sandbox_file_system_.SetUp(base_dir, quota_manager_proxy_.get()); @@ -85,8 +85,8 @@ class FileSystemOperationImplTest void TearDown() override { // Let the client go away before dropping a ref of the quota manager proxy. quota_manager_proxy()->SimulateQuotaManagerDestroyed(); - quota_manager_ = NULL; - quota_manager_proxy_ = NULL; + quota_manager_ = nullptr; + quota_manager_proxy_ = nullptr; sandbox_file_system_.TearDown(); } @@ -203,10 +203,8 @@ class FileSystemOperationImplTest FileSystemOperation::SnapshotFileCallback RecordSnapshotFileCallback( const base::Closure& closure, base::File::Error* status) { - return base::Bind(&FileSystemOperationImplTest::DidCreateSnapshotFile, - weak_factory_.GetWeakPtr(), - closure, - status); + return base::BindOnce(&FileSystemOperationImplTest::DidCreateSnapshotFile, + weak_factory_.GetWeakPtr(), closure, status); } void DidFinish(const base::Closure& closure, @@ -265,7 +263,7 @@ class FileSystemOperationImplTest int64_t ComputePathCost(const FileSystemURL& url) { int64_t base_usage; - GetUsageAndQuota(&base_usage, NULL); + GetUsageAndQuota(&base_usage, nullptr); AsyncFileTestHelper::CreateFile( sandbox_file_system_.file_system_context(), url); @@ -274,13 +272,13 @@ class FileSystemOperationImplTest change_observer()->ResetCount(); int64_t total_usage; - GetUsageAndQuota(&total_usage, NULL); + GetUsageAndQuota(&total_usage, nullptr); return total_usage - base_usage; } void GrantQuotaForCurrentUsage() { int64_t usage; - GetUsageAndQuota(&usage, NULL); + GetUsageAndQuota(&usage, nullptr); quota_manager()->SetQuota(sandbox_file_system_.origin(), sandbox_file_system_.storage_type(), usage); @@ -288,13 +286,13 @@ class FileSystemOperationImplTest int64_t GetUsage() { int64_t usage = 0; - GetUsageAndQuota(&usage, NULL); + GetUsageAndQuota(&usage, nullptr); return usage; } void AddQuota(int64_t quota_delta) { int64_t quota; - GetUsageAndQuota(NULL, "a); + GetUsageAndQuota(nullptr, "a); quota_manager()->SetQuota(sandbox_file_system_.origin(), sandbox_file_system_.storage_type(), quota + quota_delta); @@ -834,7 +832,7 @@ TEST_F(FileSystemOperationImplTest, TestCopyInForeignFileSuccess) { FileSystemURL dest_dir(CreateDirectory("dest")); int64_t before_usage; - GetUsageAndQuota(&before_usage, NULL); + GetUsageAndQuota(&before_usage, nullptr); // Check that the file copied and corresponding usage increased. EXPECT_EQ( @@ -844,7 +842,7 @@ TEST_F(FileSystemOperationImplTest, TestCopyInForeignFileSuccess) { EXPECT_EQ(1, change_observer()->create_file_count()); EXPECT_TRUE(FileExists("dest/file")); int64_t after_usage; - GetUsageAndQuota(&after_usage, NULL); + GetUsageAndQuota(&after_usage, nullptr); EXPECT_GT(after_usage, before_usage); // Compare contents of src and copied file. @@ -1206,7 +1204,7 @@ TEST_F(FileSystemOperationImplTest, TestCreateSnapshotFile) { // The FileSystemOpration implementation does not create a // shareable file reference. - EXPECT_EQ(NULL, shareable_file_ref()); + EXPECT_EQ(nullptr, shareable_file_ref()); } TEST_F(FileSystemOperationImplTest, diff --git a/chromium/storage/browser/fileapi/file_system_operation_impl_write_unittest.cc b/chromium/storage/browser/fileapi/file_system_operation_impl_write_unittest.cc index a7c51e0e74b..70b2bfb54c4 100644 --- a/chromium/storage/browser/fileapi/file_system_operation_impl_write_unittest.cc +++ b/chromium/storage/browser/fileapi/file_system_operation_impl_write_unittest.cc @@ -73,7 +73,7 @@ class FileSystemOperationImplWriteTest : public testing::Test { quota_manager_ = new MockQuotaManager(false /* is_incognito */, dir_.GetPath(), base::ThreadTaskRunnerHandle::Get().get(), - NULL /* special storage policy */); + nullptr /* special storage policy */); virtual_path_ = base::FilePath(FILE_PATH_LITERAL("temporary file")); file_system_context_ = CreateFileSystemContextForTesting( @@ -90,8 +90,8 @@ class FileSystemOperationImplWriteTest : public testing::Test { } void TearDown() override { - quota_manager_ = NULL; - file_system_context_ = NULL; + quota_manager_ = nullptr; + file_system_context_ = nullptr; base::RunLoop().RunUntilIdle(); } @@ -178,9 +178,9 @@ class FileSystemOperationImplWriteTest : public testing::Test { TEST_F(FileSystemOperationImplWriteTest, TestWriteSuccess) { ScopedTextBlob blob(url_request_context(), "blob-id:success", "Hello, world!\n"); - file_system_context_->operation_runner()->Write( - &url_request_context(), URLForPath(virtual_path_), - blob.GetBlobDataHandle(), 0, RecordWriteCallback()); + file_system_context_->operation_runner()->Write(URLForPath(virtual_path_), + blob.GetBlobDataHandle(), 0, + RecordWriteCallback()); base::RunLoop().Run(); EXPECT_EQ(14, bytes_written()); @@ -192,9 +192,9 @@ TEST_F(FileSystemOperationImplWriteTest, TestWriteSuccess) { TEST_F(FileSystemOperationImplWriteTest, TestWriteZero) { ScopedTextBlob blob(url_request_context(), "blob_id:zero", ""); - file_system_context_->operation_runner()->Write( - &url_request_context(), URLForPath(virtual_path_), - blob.GetBlobDataHandle(), 0, RecordWriteCallback()); + file_system_context_->operation_runner()->Write(URLForPath(virtual_path_), + blob.GetBlobDataHandle(), 0, + RecordWriteCallback()); base::RunLoop().Run(); EXPECT_EQ(0, bytes_written()); @@ -204,11 +204,11 @@ TEST_F(FileSystemOperationImplWriteTest, TestWriteZero) { EXPECT_EQ(1, change_observer()->get_and_reset_modify_file_count()); } -TEST_F(FileSystemOperationImplWriteTest, TestWriteInvalidBlobUrl) { +TEST_F(FileSystemOperationImplWriteTest, TestWriteInvalidBlob) { std::unique_ptr<storage::BlobDataHandle> null_handle; - file_system_context_->operation_runner()->Write( - &url_request_context(), URLForPath(virtual_path_), std::move(null_handle), - 0, RecordWriteCallback()); + file_system_context_->operation_runner()->Write(URLForPath(virtual_path_), + std::move(null_handle), 0, + RecordWriteCallback()); base::RunLoop().Run(); EXPECT_EQ(0, bytes_written()); @@ -222,7 +222,6 @@ TEST_F(FileSystemOperationImplWriteTest, TestWriteInvalidFile) { ScopedTextBlob blob(url_request_context(), "blob_id:writeinvalidfile", "It\'ll not be written."); file_system_context_->operation_runner()->Write( - &url_request_context(), URLForPath(base::FilePath(FILE_PATH_LITERAL("nonexist"))), blob.GetBlobDataHandle(), 0, RecordWriteCallback()); base::RunLoop().Run(); @@ -242,9 +241,9 @@ TEST_F(FileSystemOperationImplWriteTest, TestWriteDir) { ScopedTextBlob blob(url_request_context(), "blob:writedir", "It\'ll not be written, too."); - file_system_context_->operation_runner()->Write( - &url_request_context(), URLForPath(virtual_dir_path), - blob.GetBlobDataHandle(), 0, RecordWriteCallback()); + file_system_context_->operation_runner()->Write(URLForPath(virtual_dir_path), + blob.GetBlobDataHandle(), 0, + RecordWriteCallback()); base::RunLoop().Run(); EXPECT_EQ(0, bytes_written()); @@ -262,9 +261,9 @@ TEST_F(FileSystemOperationImplWriteTest, TestWriteFailureByQuota) { ScopedTextBlob blob(url_request_context(), "blob:success", "Hello, world!\n"); quota_manager_->SetQuota( kOrigin, FileSystemTypeToQuotaStorageType(kFileSystemType), 10); - file_system_context_->operation_runner()->Write( - &url_request_context(), URLForPath(virtual_path_), - blob.GetBlobDataHandle(), 0, RecordWriteCallback()); + file_system_context_->operation_runner()->Write(URLForPath(virtual_path_), + blob.GetBlobDataHandle(), 0, + RecordWriteCallback()); base::RunLoop().Run(); EXPECT_EQ(10, bytes_written()); @@ -277,9 +276,9 @@ TEST_F(FileSystemOperationImplWriteTest, TestWriteFailureByQuota) { TEST_F(FileSystemOperationImplWriteTest, TestImmediateCancelSuccessfulWrite) { ScopedTextBlob blob(url_request_context(), "blob:success", "Hello, world!\n"); FileSystemOperationRunner::OperationID id = - file_system_context_->operation_runner()->Write( - &url_request_context(), URLForPath(virtual_path_), - blob.GetBlobDataHandle(), 0, RecordWriteCallback()); + file_system_context_->operation_runner()->Write(URLForPath(virtual_path_), + blob.GetBlobDataHandle(), + 0, RecordWriteCallback()); file_system_context_->operation_runner()->Cancel(id, RecordCancelCallback()); // We use RunAllPendings() instead of Run() here, because we won't dispatch // callbacks after Cancel() is issued (so no chance to Quit) nor do we need @@ -301,7 +300,6 @@ TEST_F(FileSystemOperationImplWriteTest, TestImmediateCancelFailingWrite) { "It\'ll not be written."); FileSystemOperationRunner::OperationID id = file_system_context_->operation_runner()->Write( - &url_request_context(), URLForPath(base::FilePath(FILE_PATH_LITERAL("nonexist"))), blob.GetBlobDataHandle(), 0, RecordWriteCallback()); file_system_context_->operation_runner()->Cancel(id, RecordCancelCallback()); diff --git a/chromium/storage/browser/fileapi/file_system_operation_runner.cc b/chromium/storage/browser/fileapi/file_system_operation_runner.cc index fbda72b3cdf..75330e48169 100644 --- a/chromium/storage/browser/fileapi/file_system_operation_runner.cc +++ b/chromium/storage/browser/fileapi/file_system_operation_runner.cc @@ -10,6 +10,7 @@ #include <tuple> #include <utility> +#include "base/auto_reset.h" #include "base/bind.h" #include "base/macros.h" #include "base/memory/ptr_util.h" @@ -27,21 +28,6 @@ namespace storage { using OperationID = FileSystemOperationRunner::OperationID; -class FileSystemOperationRunner::BeginOperationScoper - : public base::SupportsWeakPtr< - FileSystemOperationRunner::BeginOperationScoper> { - public: - BeginOperationScoper() = default; - - private: - DISALLOW_COPY_AND_ASSIGN(BeginOperationScoper); -}; - -FileSystemOperationRunner::OperationHandle::OperationHandle() = default; -FileSystemOperationRunner::OperationHandle::OperationHandle( - const OperationHandle& other) = default; -FileSystemOperationRunner::OperationHandle::~OperationHandle() = default; - FileSystemOperationRunner::~FileSystemOperationRunner() = default; void FileSystemOperationRunner::Shutdown() { @@ -58,19 +44,17 @@ OperationID FileSystemOperationRunner::CreateFile( std::unique_ptr<FileSystemOperation> operation = base::WrapUnique( file_system_context_->CreateFileSystemOperation(url, &error)); FileSystemOperation* operation_raw = operation.get(); - BeginOperationScoper scope; - OperationHandle handle = - BeginOperation(std::move(operation), scope.AsWeakPtr()); + OperationID id = BeginOperation(std::move(operation)); + base::AutoReset<bool> beginning(&is_beginning_operation_, true); if (!operation_raw) { - DidFinish(handle, callback, error); - return handle.id; + DidFinish(id, callback, error); + return id; } - PrepareForWrite(handle.id, url); - operation_raw->CreateFile( - url, exclusive, - base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), - handle, callback)); - return handle.id; + PrepareForWrite(id, url); + operation_raw->CreateFile(url, exclusive, + base::Bind(&FileSystemOperationRunner::DidFinish, + weak_ptr_, id, callback)); + return id; } OperationID FileSystemOperationRunner::CreateDirectory( @@ -82,19 +66,18 @@ OperationID FileSystemOperationRunner::CreateDirectory( std::unique_ptr<FileSystemOperation> operation = base::WrapUnique( file_system_context_->CreateFileSystemOperation(url, &error)); FileSystemOperation* operation_raw = operation.get(); - BeginOperationScoper scope; - OperationHandle handle = - BeginOperation(std::move(operation), scope.AsWeakPtr()); + OperationID id = BeginOperation(std::move(operation)); + base::AutoReset<bool> beginning(&is_beginning_operation_, true); if (!operation_raw) { - DidFinish(handle, callback, error); - return handle.id; + DidFinish(id, callback, error); + return id; } - PrepareForWrite(handle.id, url); + PrepareForWrite(id, url); operation_raw->CreateDirectory( url, exclusive, recursive, - base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), - handle, callback)); - return handle.id; + base::Bind(&FileSystemOperationRunner::DidFinish, weak_ptr_, id, + callback)); + return id; } OperationID FileSystemOperationRunner::Copy( @@ -108,23 +91,23 @@ OperationID FileSystemOperationRunner::Copy( std::unique_ptr<FileSystemOperation> operation = base::WrapUnique( file_system_context_->CreateFileSystemOperation(dest_url, &error)); FileSystemOperation* operation_raw = operation.get(); - BeginOperationScoper scope; - OperationHandle handle = - BeginOperation(std::move(operation), scope.AsWeakPtr()); + OperationID id = BeginOperation(std::move(operation)); + base::AutoReset<bool> beginning(&is_beginning_operation_, true); if (!operation_raw) { - DidFinish(handle, callback, error); - return handle.id; - } - PrepareForWrite(handle.id, dest_url); - PrepareForRead(handle.id, src_url); - operation_raw->Copy(src_url, dest_url, option, error_behavior, - progress_callback.is_null() - ? CopyProgressCallback() - : base::Bind(&FileSystemOperationRunner::OnCopyProgress, - AsWeakPtr(), handle, progress_callback), - base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), - handle, callback)); - return handle.id; + DidFinish(id, callback, error); + return id; + } + PrepareForWrite(id, dest_url); + PrepareForRead(id, src_url); + operation_raw->Copy( + src_url, dest_url, option, error_behavior, + progress_callback.is_null() + ? CopyProgressCallback() + : base::Bind(&FileSystemOperationRunner::OnCopyProgress, weak_ptr_, + id, progress_callback), + base::Bind(&FileSystemOperationRunner::DidFinish, weak_ptr_, id, + callback)); + return id; } OperationID FileSystemOperationRunner::Move( @@ -136,20 +119,18 @@ OperationID FileSystemOperationRunner::Move( std::unique_ptr<FileSystemOperation> operation = base::WrapUnique( file_system_context_->CreateFileSystemOperation(dest_url, &error)); FileSystemOperation* operation_raw = operation.get(); - BeginOperationScoper scope; - OperationHandle handle = - BeginOperation(std::move(operation), scope.AsWeakPtr()); + OperationID id = BeginOperation(std::move(operation)); + base::AutoReset<bool> beginning(&is_beginning_operation_, true); if (!operation_raw) { - DidFinish(handle, callback, error); - return handle.id; + DidFinish(id, callback, error); + return id; } - PrepareForWrite(handle.id, dest_url); - PrepareForWrite(handle.id, src_url); - operation_raw->Move( - src_url, dest_url, option, - base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), - handle, callback)); - return handle.id; + PrepareForWrite(id, dest_url); + PrepareForWrite(id, src_url); + operation_raw->Move(src_url, dest_url, option, + base::Bind(&FileSystemOperationRunner::DidFinish, + weak_ptr_, id, callback)); + return id; } OperationID FileSystemOperationRunner::DirectoryExists( @@ -159,19 +140,17 @@ OperationID FileSystemOperationRunner::DirectoryExists( std::unique_ptr<FileSystemOperation> operation = base::WrapUnique( file_system_context_->CreateFileSystemOperation(url, &error)); FileSystemOperation* operation_raw = operation.get(); - BeginOperationScoper scope; - OperationHandle handle = - BeginOperation(std::move(operation), scope.AsWeakPtr()); + OperationID id = BeginOperation(std::move(operation)); + base::AutoReset<bool> beginning(&is_beginning_operation_, true); if (!operation_raw) { - DidFinish(handle, callback, error); - return handle.id; + DidFinish(id, callback, error); + return id; } - PrepareForRead(handle.id, url); + PrepareForRead(id, url); operation_raw->DirectoryExists( - url, - base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), - handle, callback)); - return handle.id; + url, base::Bind(&FileSystemOperationRunner::DidFinish, weak_ptr_, id, + callback)); + return id; } OperationID FileSystemOperationRunner::FileExists( @@ -181,19 +160,17 @@ OperationID FileSystemOperationRunner::FileExists( std::unique_ptr<FileSystemOperation> operation = base::WrapUnique( file_system_context_->CreateFileSystemOperation(url, &error)); FileSystemOperation* operation_raw = operation.get(); - BeginOperationScoper scope; - OperationHandle handle = - BeginOperation(std::move(operation), scope.AsWeakPtr()); + OperationID id = BeginOperation(std::move(operation)); + base::AutoReset<bool> beginning(&is_beginning_operation_, true); if (!operation_raw) { - DidFinish(handle, callback, error); - return handle.id; + DidFinish(id, callback, error); + return id; } - PrepareForRead(handle.id, url); + PrepareForRead(id, url); operation_raw->FileExists( - url, - base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), - handle, callback)); - return handle.id; + url, base::Bind(&FileSystemOperationRunner::DidFinish, weak_ptr_, id, + callback)); + return id; } OperationID FileSystemOperationRunner::GetMetadata( @@ -204,18 +181,18 @@ OperationID FileSystemOperationRunner::GetMetadata( std::unique_ptr<FileSystemOperation> operation = base::WrapUnique( file_system_context_->CreateFileSystemOperation(url, &error)); FileSystemOperation* operation_raw = operation.get(); - BeginOperationScoper scope; - OperationHandle handle = - BeginOperation(std::move(operation), scope.AsWeakPtr()); + OperationID id = BeginOperation(std::move(operation)); + base::AutoReset<bool> beginning(&is_beginning_operation_, true); if (!operation_raw) { - DidGetMetadata(handle, callback, error, base::File::Info()); - return handle.id; + DidGetMetadata(id, callback, error, base::File::Info()); + return id; } - PrepareForRead(handle.id, url); - operation_raw->GetMetadata(url, fields, - base::Bind(&FileSystemOperationRunner::DidGetMetadata, - AsWeakPtr(), handle, callback)); - return handle.id; + PrepareForRead(id, url); + operation_raw->GetMetadata( + url, fields, + base::Bind(&FileSystemOperationRunner::DidGetMetadata, weak_ptr_, id, + callback)); + return id; } OperationID FileSystemOperationRunner::ReadDirectory( @@ -225,19 +202,18 @@ OperationID FileSystemOperationRunner::ReadDirectory( std::unique_ptr<FileSystemOperation> operation = base::WrapUnique( file_system_context_->CreateFileSystemOperation(url, &error)); FileSystemOperation* operation_raw = operation.get(); - BeginOperationScoper scope; - OperationHandle handle = - BeginOperation(std::move(operation), scope.AsWeakPtr()); + OperationID id = BeginOperation(std::move(operation)); + base::AutoReset<bool> beginning(&is_beginning_operation_, true); if (!operation_raw) { - DidReadDirectory(handle, std::move(callback), error, + DidReadDirectory(id, std::move(callback), error, std::vector<filesystem::mojom::DirectoryEntry>(), false); - return handle.id; + return id; } - PrepareForRead(handle.id, url); + PrepareForRead(id, url); operation_raw->ReadDirectory( url, base::BindRepeating(&FileSystemOperationRunner::DidReadDirectory, - AsWeakPtr(), handle, callback)); - return handle.id; + weak_ptr_, id, callback)); + return id; } OperationID FileSystemOperationRunner::Remove( @@ -247,23 +223,20 @@ OperationID FileSystemOperationRunner::Remove( std::unique_ptr<FileSystemOperation> operation = base::WrapUnique( file_system_context_->CreateFileSystemOperation(url, &error)); FileSystemOperation* operation_raw = operation.get(); - BeginOperationScoper scope; - OperationHandle handle = - BeginOperation(std::move(operation), scope.AsWeakPtr()); + OperationID id = BeginOperation(std::move(operation)); + base::AutoReset<bool> beginning(&is_beginning_operation_, true); if (!operation_raw) { - DidFinish(handle, callback, error); - return handle.id; + DidFinish(id, callback, error); + return id; } - PrepareForWrite(handle.id, url); - operation_raw->Remove( - url, recursive, - base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), - handle, callback)); - return handle.id; + PrepareForWrite(id, url); + operation_raw->Remove(url, recursive, + base::Bind(&FileSystemOperationRunner::DidFinish, + weak_ptr_, id, callback)); + return id; } OperationID FileSystemOperationRunner::Write( - const net::URLRequestContext* url_request_context, const FileSystemURL& url, std::unique_ptr<storage::BlobDataHandle> blob, int64_t offset, @@ -272,34 +245,33 @@ OperationID FileSystemOperationRunner::Write( std::unique_ptr<FileSystemOperation> operation = base::WrapUnique( file_system_context_->CreateFileSystemOperation(url, &error)); FileSystemOperation* operation_raw = operation.get(); - BeginOperationScoper scope; - OperationHandle handle = - BeginOperation(std::move(operation), scope.AsWeakPtr()); + OperationID id = BeginOperation(std::move(operation)); + base::AutoReset<bool> beginning(&is_beginning_operation_, true); if (!operation_raw) { - DidWrite(handle, callback, error, 0, true); - return handle.id; + DidWrite(id, callback, error, 0, true); + return id; } std::unique_ptr<FileStreamWriter> writer( file_system_context_->CreateFileStreamWriter(url, offset)); if (!writer) { // Write is not supported. - DidWrite(handle, callback, base::File::FILE_ERROR_SECURITY, 0, true); - return handle.id; + DidWrite(id, callback, base::File::FILE_ERROR_SECURITY, 0, true); + return id; } std::unique_ptr<FileWriterDelegate> writer_delegate(new FileWriterDelegate( std::move(writer), url.mount_option().flush_policy())); - std::unique_ptr<net::URLRequest> blob_request( - storage::BlobProtocolHandler::CreateBlobRequest( - std::move(blob), url_request_context, writer_delegate.get())); + std::unique_ptr<BlobReader> blob_reader; + if (blob) + blob_reader = blob->CreateReader(); - PrepareForWrite(handle.id, url); - operation_raw->Write(url, std::move(writer_delegate), std::move(blob_request), - base::Bind(&FileSystemOperationRunner::DidWrite, AsWeakPtr(), - handle, callback)); - return handle.id; + PrepareForWrite(id, url); + operation_raw->Write(url, std::move(writer_delegate), std::move(blob_reader), + base::Bind(&FileSystemOperationRunner::DidWrite, + weak_ptr_, id, callback)); + return id; } OperationID FileSystemOperationRunner::Truncate( @@ -310,19 +282,17 @@ OperationID FileSystemOperationRunner::Truncate( std::unique_ptr<FileSystemOperation> operation = base::WrapUnique( file_system_context_->CreateFileSystemOperation(url, &error)); FileSystemOperation* operation_raw = operation.get(); - BeginOperationScoper scope; - OperationHandle handle = - BeginOperation(std::move(operation), scope.AsWeakPtr()); + OperationID id = BeginOperation(std::move(operation)); + base::AutoReset<bool> beginning(&is_beginning_operation_, true); if (!operation_raw) { - DidFinish(handle, callback, error); - return handle.id; + DidFinish(id, callback, error); + return id; } - PrepareForWrite(handle.id, url); - operation_raw->Truncate( - url, length, - base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), - handle, callback)); - return handle.id; + PrepareForWrite(id, url); + operation_raw->Truncate(url, length, + base::Bind(&FileSystemOperationRunner::DidFinish, + weak_ptr_, id, callback)); + return id; } void FileSystemOperationRunner::Cancel( @@ -352,19 +322,17 @@ OperationID FileSystemOperationRunner::TouchFile( std::unique_ptr<FileSystemOperation> operation = base::WrapUnique( file_system_context_->CreateFileSystemOperation(url, &error)); FileSystemOperation* operation_raw = operation.get(); - BeginOperationScoper scope; - OperationHandle handle = - BeginOperation(std::move(operation), scope.AsWeakPtr()); + OperationID id = BeginOperation(std::move(operation)); + base::AutoReset<bool> beginning(&is_beginning_operation_, true); if (!operation_raw) { - DidFinish(handle, callback, error); - return handle.id; + DidFinish(id, callback, error); + return id; } - PrepareForWrite(handle.id, url); - operation_raw->TouchFile( - url, last_access_time, last_modified_time, - base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), - handle, callback)); - return handle.id; + PrepareForWrite(id, url); + operation_raw->TouchFile(url, last_access_time, last_modified_time, + base::Bind(&FileSystemOperationRunner::DidFinish, + weak_ptr_, id, callback)); + return id; } OperationID FileSystemOperationRunner::OpenFile( @@ -375,12 +343,11 @@ OperationID FileSystemOperationRunner::OpenFile( std::unique_ptr<FileSystemOperation> operation = base::WrapUnique( file_system_context_->CreateFileSystemOperation(url, &error)); FileSystemOperation* operation_raw = operation.get(); - BeginOperationScoper scope; - OperationHandle handle = - BeginOperation(std::move(operation), scope.AsWeakPtr()); + OperationID id = BeginOperation(std::move(operation)); + base::AutoReset<bool> beginning(&is_beginning_operation_, true); if (!operation_raw) { - DidOpenFile(handle, callback, base::File(error), base::Closure()); - return handle.id; + DidOpenFile(id, callback, base::File(error), base::Closure()); + return id; } if (file_flags & (base::File::FLAG_CREATE | base::File::FLAG_OPEN_ALWAYS | @@ -388,38 +355,35 @@ OperationID FileSystemOperationRunner::OpenFile( base::File::FLAG_WRITE | base::File::FLAG_EXCLUSIVE_WRITE | base::File::FLAG_DELETE_ON_CLOSE | base::File::FLAG_WRITE_ATTRIBUTES)) { - PrepareForWrite(handle.id, url); + PrepareForWrite(id, url); } else { - PrepareForRead(handle.id, url); + PrepareForRead(id, url); } - operation_raw->OpenFile( - url, file_flags, - base::Bind(&FileSystemOperationRunner::DidOpenFile, AsWeakPtr(), - handle, callback)); - return handle.id; + operation_raw->OpenFile(url, file_flags, + base::Bind(&FileSystemOperationRunner::DidOpenFile, + weak_ptr_, id, callback)); + return id; } OperationID FileSystemOperationRunner::CreateSnapshotFile( const FileSystemURL& url, - const SnapshotFileCallback& callback) { + SnapshotFileCallback callback) { base::File::Error error = base::File::FILE_OK; std::unique_ptr<FileSystemOperation> operation = base::WrapUnique( file_system_context_->CreateFileSystemOperation(url, &error)); FileSystemOperation* operation_raw = operation.get(); - BeginOperationScoper scope; - OperationHandle handle = - BeginOperation(std::move(operation), scope.AsWeakPtr()); + OperationID id = BeginOperation(std::move(operation)); + base::AutoReset<bool> beginning(&is_beginning_operation_, true); if (!operation_raw) { - DidCreateSnapshot(handle, callback, error, base::File::Info(), - base::FilePath(), NULL); - return handle.id; + DidCreateSnapshot(id, std::move(callback), error, base::File::Info(), + base::FilePath(), nullptr); + return id; } - PrepareForRead(handle.id, url); + PrepareForRead(id, url); operation_raw->CreateSnapshotFile( - url, - base::Bind(&FileSystemOperationRunner::DidCreateSnapshot, AsWeakPtr(), - handle, callback)); - return handle.id; + url, base::BindOnce(&FileSystemOperationRunner::DidCreateSnapshot, + weak_ptr_, id, std::move(callback))); + return id; } OperationID FileSystemOperationRunner::CopyInForeignFile( @@ -430,19 +394,18 @@ OperationID FileSystemOperationRunner::CopyInForeignFile( std::unique_ptr<FileSystemOperation> operation = base::WrapUnique( file_system_context_->CreateFileSystemOperation(dest_url, &error)); FileSystemOperation* operation_raw = operation.get(); - BeginOperationScoper scope; - OperationHandle handle = - BeginOperation(std::move(operation), scope.AsWeakPtr()); + OperationID id = BeginOperation(std::move(operation)); + base::AutoReset<bool> beginning(&is_beginning_operation_, true); if (!operation_raw) { - DidFinish(handle, callback, error); - return handle.id; + DidFinish(id, callback, error); + return id; } - PrepareForWrite(handle.id, dest_url); + PrepareForWrite(id, dest_url); operation_raw->CopyInForeignFile( src_local_disk_path, dest_url, - base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), - handle, callback)); - return handle.id; + base::Bind(&FileSystemOperationRunner::DidFinish, weak_ptr_, id, + callback)); + return id; } OperationID FileSystemOperationRunner::RemoveFile( @@ -452,19 +415,17 @@ OperationID FileSystemOperationRunner::RemoveFile( std::unique_ptr<FileSystemOperation> operation = base::WrapUnique( file_system_context_->CreateFileSystemOperation(url, &error)); FileSystemOperation* operation_raw = operation.get(); - BeginOperationScoper scope; - OperationHandle handle = - BeginOperation(std::move(operation), scope.AsWeakPtr()); + OperationID id = BeginOperation(std::move(operation)); + base::AutoReset<bool> beginning(&is_beginning_operation_, true); if (!operation_raw) { - DidFinish(handle, callback, error); - return handle.id; + DidFinish(id, callback, error); + return id; } - PrepareForWrite(handle.id, url); + PrepareForWrite(id, url); operation_raw->RemoveFile( - url, - base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), - handle, callback)); - return handle.id; + url, base::Bind(&FileSystemOperationRunner::DidFinish, weak_ptr_, id, + callback)); + return id; } OperationID FileSystemOperationRunner::RemoveDirectory( @@ -474,19 +435,17 @@ OperationID FileSystemOperationRunner::RemoveDirectory( std::unique_ptr<FileSystemOperation> operation = base::WrapUnique( file_system_context_->CreateFileSystemOperation(url, &error)); FileSystemOperation* operation_raw = operation.get(); - BeginOperationScoper scope; - OperationHandle handle = - BeginOperation(std::move(operation), scope.AsWeakPtr()); + OperationID id = BeginOperation(std::move(operation)); + base::AutoReset<bool> beginning(&is_beginning_operation_, true); if (!operation_raw) { - DidFinish(handle, callback, error); - return handle.id; + DidFinish(id, callback, error); + return id; } - PrepareForWrite(handle.id, url); + PrepareForWrite(id, url); operation_raw->RemoveDirectory( - url, - base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), - handle, callback)); - return handle.id; + url, base::Bind(&FileSystemOperationRunner::DidFinish, weak_ptr_, id, + callback)); + return id; } OperationID FileSystemOperationRunner::CopyFileLocal( @@ -499,20 +458,18 @@ OperationID FileSystemOperationRunner::CopyFileLocal( std::unique_ptr<FileSystemOperation> operation = base::WrapUnique( file_system_context_->CreateFileSystemOperation(src_url, &error)); FileSystemOperation* operation_raw = operation.get(); - BeginOperationScoper scope; - OperationHandle handle = - BeginOperation(std::move(operation), scope.AsWeakPtr()); + OperationID id = BeginOperation(std::move(operation)); + base::AutoReset<bool> beginning(&is_beginning_operation_, true); if (!operation_raw) { - DidFinish(handle, callback, error); - return handle.id; + DidFinish(id, callback, error); + return id; } - PrepareForRead(handle.id, src_url); - PrepareForWrite(handle.id, dest_url); - operation_raw->CopyFileLocal( - src_url, dest_url, option, progress_callback, - base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), - handle, callback)); - return handle.id; + PrepareForRead(id, src_url); + PrepareForWrite(id, dest_url); + operation_raw->CopyFileLocal(src_url, dest_url, option, progress_callback, + base::Bind(&FileSystemOperationRunner::DidFinish, + weak_ptr_, id, callback)); + return id; } OperationID FileSystemOperationRunner::MoveFileLocal( @@ -524,20 +481,18 @@ OperationID FileSystemOperationRunner::MoveFileLocal( std::unique_ptr<FileSystemOperation> operation = base::WrapUnique( file_system_context_->CreateFileSystemOperation(src_url, &error)); FileSystemOperation* operation_raw = operation.get(); - BeginOperationScoper scope; - OperationHandle handle = - BeginOperation(std::move(operation), scope.AsWeakPtr()); + OperationID id = BeginOperation(std::move(operation)); + base::AutoReset<bool> beginning(&is_beginning_operation_, true); if (!operation_raw) { - DidFinish(handle, callback, error); - return handle.id; + DidFinish(id, callback, error); + return id; } - PrepareForWrite(handle.id, src_url); - PrepareForWrite(handle.id, dest_url); - operation_raw->MoveFileLocal( - src_url, dest_url, option, - base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), - handle, callback)); - return handle.id; + PrepareForWrite(id, src_url); + PrepareForWrite(id, dest_url); + operation_raw->MoveFileLocal(src_url, dest_url, option, + base::Bind(&FileSystemOperationRunner::DidFinish, + weak_ptr_, id, callback)); + return id; } base::File::Error FileSystemOperationRunner::SyncGetPlatformPath( @@ -553,126 +508,126 @@ base::File::Error FileSystemOperationRunner::SyncGetPlatformPath( FileSystemOperationRunner::FileSystemOperationRunner( FileSystemContext* file_system_context) - : file_system_context_(file_system_context) {} - -void FileSystemOperationRunner::DidFinish( - const OperationHandle& handle, - const StatusCallback& callback, - base::File::Error rv) { - if (handle.scope) { - finished_operations_.insert(handle.id); + : file_system_context_(file_system_context), weak_factory_(this) { + weak_ptr_ = weak_factory_.GetWeakPtr(); +} + +void FileSystemOperationRunner::DidFinish(const OperationID id, + const StatusCallback& callback, + base::File::Error rv) { + if (is_beginning_operation_) { + finished_operations_.insert(id); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&FileSystemOperationRunner::DidFinish, - AsWeakPtr(), handle, callback, rv)); + weak_ptr_, id, callback, rv)); return; } callback.Run(rv); - FinishOperation(handle.id); + FinishOperation(id); } void FileSystemOperationRunner::DidGetMetadata( - const OperationHandle& handle, + const OperationID id, const GetMetadataCallback& callback, base::File::Error rv, const base::File::Info& file_info) { - if (handle.scope) { - finished_operations_.insert(handle.id); + if (is_beginning_operation_) { + finished_operations_.insert(id); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::BindOnce(&FileSystemOperationRunner::DidGetMetadata, AsWeakPtr(), - handle, callback, rv, file_info)); + FROM_HERE, base::BindOnce(&FileSystemOperationRunner::DidGetMetadata, + weak_ptr_, id, callback, rv, file_info)); return; } callback.Run(rv, file_info); - FinishOperation(handle.id); + FinishOperation(id); } void FileSystemOperationRunner::DidReadDirectory( - const OperationHandle& handle, + const OperationID id, const ReadDirectoryCallback& callback, base::File::Error rv, std::vector<filesystem::mojom::DirectoryEntry> entries, bool has_more) { - if (handle.scope) { - finished_operations_.insert(handle.id); + if (is_beginning_operation_) { + finished_operations_.insert(id); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(&FileSystemOperationRunner::DidReadDirectory, - AsWeakPtr(), handle, callback, rv, - std::move(entries), has_more)); + FROM_HERE, + base::BindOnce(&FileSystemOperationRunner::DidReadDirectory, weak_ptr_, + id, callback, rv, std::move(entries), has_more)); return; } callback.Run(rv, std::move(entries), has_more); if (rv != base::File::FILE_OK || !has_more) - FinishOperation(handle.id); + FinishOperation(id); } -void FileSystemOperationRunner::DidWrite(const OperationHandle& handle, +void FileSystemOperationRunner::DidWrite(const OperationID id, const WriteCallback& callback, base::File::Error rv, int64_t bytes, bool complete) { - if (handle.scope) { - finished_operations_.insert(handle.id); + if (is_beginning_operation_) { + finished_operations_.insert(id); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindOnce(&FileSystemOperationRunner::DidWrite, AsWeakPtr(), - handle, callback, rv, bytes, complete)); + base::BindOnce(&FileSystemOperationRunner::DidWrite, weak_ptr_, id, + callback, rv, bytes, complete)); return; } callback.Run(rv, bytes, complete); if (rv != base::File::FILE_OK || complete) - FinishOperation(handle.id); + FinishOperation(id); } void FileSystemOperationRunner::DidOpenFile( - const OperationHandle& handle, + const OperationID id, const OpenFileCallback& callback, base::File file, base::OnceClosure on_close_callback) { - if (handle.scope) { - finished_operations_.insert(handle.id); + if (is_beginning_operation_) { + finished_operations_.insert(id); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::BindOnce(&FileSystemOperationRunner::DidOpenFile, AsWeakPtr(), - handle, callback, std::move(file), - std::move(on_close_callback))); + FROM_HERE, base::BindOnce(&FileSystemOperationRunner::DidOpenFile, + weak_ptr_, id, callback, std::move(file), + std::move(on_close_callback))); return; } callback.Run(std::move(file), std::move(on_close_callback)); - FinishOperation(handle.id); + FinishOperation(id); } void FileSystemOperationRunner::DidCreateSnapshot( - const OperationHandle& handle, - const SnapshotFileCallback& callback, + const OperationID id, + SnapshotFileCallback callback, base::File::Error rv, const base::File::Info& file_info, const base::FilePath& platform_path, scoped_refptr<storage::ShareableFileReference> file_ref) { - if (handle.scope) { - finished_operations_.insert(handle.id); + if (is_beginning_operation_) { + finished_operations_.insert(id); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(&FileSystemOperationRunner::DidCreateSnapshot, - AsWeakPtr(), handle, callback, rv, file_info, - platform_path, std::move(file_ref))); + FROM_HERE, + base::BindOnce(&FileSystemOperationRunner::DidCreateSnapshot, weak_ptr_, + id, std::move(callback), rv, file_info, platform_path, + std::move(file_ref))); return; } - callback.Run(rv, file_info, platform_path, std::move(file_ref)); - FinishOperation(handle.id); + std::move(callback).Run(rv, file_info, platform_path, std::move(file_ref)); + FinishOperation(id); } void FileSystemOperationRunner::OnCopyProgress( - const OperationHandle& handle, + const OperationID id, const CopyProgressCallback& callback, FileSystemOperation::CopyProgressType type, const FileSystemURL& source_url, const FileSystemURL& dest_url, int64_t size) { - if (handle.scope) { + if (is_beginning_operation_) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindOnce(&FileSystemOperationRunner::OnCopyProgress, AsWeakPtr(), - handle, callback, type, source_url, dest_url, size)); + base::BindOnce(&FileSystemOperationRunner::OnCopyProgress, weak_ptr_, + id, callback, type, source_url, dest_url, size)); return; } callback.Run(type, source_url, dest_url, size); @@ -695,15 +650,16 @@ void FileSystemOperationRunner::PrepareForRead(OperationID id, } } -FileSystemOperationRunner::OperationHandle -FileSystemOperationRunner::BeginOperation( - std::unique_ptr<FileSystemOperation> operation, - base::WeakPtr<BeginOperationScoper> scope) { - OperationHandle handle; - handle.id = next_operation_id_++; - operations_.emplace(handle.id, std::move(operation)); - handle.scope = scope; - return handle; +OperationID FileSystemOperationRunner::BeginOperation( + std::unique_ptr<FileSystemOperation> operation) { + OperationID id = next_operation_id_++; + + // TODO(https://crbug.com/864351): Diagnostic to determine whether OperationID + // wrap-around is occurring in the wild. + DCHECK(operations_.find(id) == operations_.end()); + + operations_.emplace(id, std::move(operation)); + return id; } void FileSystemOperationRunner::FinishOperation(OperationID id) { diff --git a/chromium/storage/browser/fileapi/file_system_operation_runner.h b/chromium/storage/browser/fileapi/file_system_operation_runner.h index a330f4802d5..c786c6e2571 100644 --- a/chromium/storage/browser/fileapi/file_system_operation_runner.h +++ b/chromium/storage/browser/fileapi/file_system_operation_runner.h @@ -21,10 +21,6 @@ #include "storage/browser/fileapi/file_system_url.h" #include "storage/browser/storage_browser_export.h" -namespace net { -class URLRequestContext; -} - namespace storage { class FileSystemURL; @@ -37,8 +33,7 @@ class FileSystemContext; // operation fails, in addition to dispatching the callback with an error // code (therefore in most cases the caller does not need to check the // returned operation ID). -class STORAGE_EXPORT FileSystemOperationRunner - : public base::SupportsWeakPtr<FileSystemOperationRunner> { +class STORAGE_EXPORT FileSystemOperationRunner { public: using GetMetadataCallback = FileSystemOperation::GetMetadataCallback; using ReadDirectoryCallback = FileSystemOperation::ReadDirectoryCallback; @@ -115,9 +110,7 @@ class STORAGE_EXPORT FileSystemOperationRunner const StatusCallback& callback); // Writes contents of |blob_url| to |url| at |offset|. - // |url_request_context| is used to read contents in |blob|. - OperationID Write(const net::URLRequestContext* url_request_context, - const FileSystemURL& url, + OperationID Write(const FileSystemURL& url, std::unique_ptr<storage::BlobDataHandle> blob, int64_t offset, const WriteCallback& callback); @@ -164,7 +157,7 @@ class STORAGE_EXPORT FileSystemOperationRunner // temporary file. Or if the implementaiton already has the local cache // data for |url| it can simply return the url to the cache. OperationID CreateSnapshotFile(const FileSystemURL& url, - const SnapshotFileCallback& callback); + SnapshotFileCallback callback); // Copies in a single file from a different filesystem. // @@ -246,50 +239,39 @@ class STORAGE_EXPORT FileSystemOperationRunner base::FilePath* platform_path); private: - class BeginOperationScoper; - - struct OperationHandle { - OperationID id; - base::WeakPtr<BeginOperationScoper> scope; - - OperationHandle(); - OperationHandle(const OperationHandle& other); - ~OperationHandle(); - }; - friend class FileSystemContext; explicit FileSystemOperationRunner(FileSystemContext* file_system_context); - void DidFinish(const OperationHandle& handle, + void DidFinish(const OperationID id, const StatusCallback& callback, base::File::Error rv); - void DidGetMetadata(const OperationHandle& handle, + void DidGetMetadata(const OperationID id, const GetMetadataCallback& callback, base::File::Error rv, const base::File::Info& file_info); - void DidReadDirectory(const OperationHandle& handle, + void DidReadDirectory(const OperationID id, const ReadDirectoryCallback& callback, base::File::Error rv, std::vector<filesystem::mojom::DirectoryEntry> entries, bool has_more); - void DidWrite(const OperationHandle& handle, + void DidWrite(const OperationID id, const WriteCallback& callback, base::File::Error rv, int64_t bytes, bool complete); - void DidOpenFile(const OperationHandle& handle, + void DidOpenFile(const OperationID id, const OpenFileCallback& callback, base::File file, base::OnceClosure on_close_callback); void DidCreateSnapshot( - const OperationHandle& handle, - const SnapshotFileCallback& callback, + const OperationID id, + SnapshotFileCallback callback, base::File::Error rv, const base::File::Info& file_info, const base::FilePath& platform_path, scoped_refptr<storage::ShareableFileReference> file_ref); - void OnCopyProgress(const OperationHandle& handle, + void OnCopyProgress(const OperationID id, const CopyProgressCallback& callback, FileSystemOperation::CopyProgressType type, const FileSystemURL& source_url, @@ -300,8 +282,7 @@ class STORAGE_EXPORT FileSystemOperationRunner void PrepareForRead(OperationID id, const FileSystemURL& url); // These must be called at the beginning and end of any async operations. - OperationHandle BeginOperation(std::unique_ptr<FileSystemOperation> operation, - base::WeakPtr<BeginOperationScoper> scope); + OperationID BeginOperation(std::unique_ptr<FileSystemOperation> operation); // Cleans up the FileSystemOperation for |id|, which may result in the // FileSystemContext, and |this| being deleted, by the time the call returns. void FinishOperation(OperationID id); @@ -314,6 +295,12 @@ class STORAGE_EXPORT FileSystemOperationRunner OperationID next_operation_id_ = 1; Operations operations_; + // Used to detect synchronous invocation of completion callbacks by the + // back-end, to re-post them to be notified asynchronously. Note that some + // operations are recursive, so this may already be true when BeginOperation + // is called. + bool is_beginning_operation_ = false; + // We keep track of the file to be modified by each operation so that // we can notify observers when we're done. using OperationToURLSet = std::map<OperationID, FileSystemURLSet>; @@ -325,6 +312,9 @@ class STORAGE_EXPORT FileSystemOperationRunner // Callbacks for stray cancels whose target operation is already finished. std::map<OperationID, StatusCallback> stray_cancel_callbacks_; + base::WeakPtr<FileSystemOperationRunner> weak_ptr_; + base::WeakPtrFactory<FileSystemOperationRunner> weak_factory_; + DISALLOW_COPY_AND_ASSIGN(FileSystemOperationRunner); }; diff --git a/chromium/storage/browser/fileapi/file_system_quota_client.cc b/chromium/storage/browser/fileapi/file_system_quota_client.cc index af56ba2dce3..fc30594ab0d 100644 --- a/chromium/storage/browser/fileapi/file_system_quota_client.cc +++ b/chromium/storage/browser/fileapi/file_system_quota_client.cc @@ -58,8 +58,9 @@ void GetOriginsForHostOnFileTaskRunner(FileSystemContext* context, origins_ptr->insert(url::Origin::Create(origin)); } -void DidGetOrigins(storage::QuotaClient::GetOriginsCallback callback, - std::set<url::Origin>* origins_ptr) { +void DidGetFileSystemQuotaClientOrigins( + storage::QuotaClient::GetOriginsCallback callback, + std::set<url::Origin>* origins_ptr) { std::move(callback).Run(*origins_ptr); } @@ -144,7 +145,7 @@ void FileSystemQuotaClient::GetOriginsForType(StorageType storage_type, base::BindOnce(&GetOriginsForTypeOnFileTaskRunner, base::RetainedRef(file_system_context_), storage_type, base::Unretained(origins_ptr)), - base::BindOnce(&DidGetOrigins, std::move(callback), + base::BindOnce(&DidGetFileSystemQuotaClientOrigins, std::move(callback), base::Owned(origins_ptr))); } @@ -166,7 +167,7 @@ void FileSystemQuotaClient::GetOriginsForHost(StorageType storage_type, base::BindOnce(&GetOriginsForHostOnFileTaskRunner, base::RetainedRef(file_system_context_), storage_type, host, base::Unretained(origins_ptr)), - base::BindOnce(&DidGetOrigins, std::move(callback), + base::BindOnce(&DidGetFileSystemQuotaClientOrigins, std::move(callback), base::Owned(origins_ptr))); } diff --git a/chromium/storage/browser/fileapi/file_system_quota_client_unittest.cc b/chromium/storage/browser/fileapi/file_system_quota_client_unittest.cc index 9676d049b2f..a6dc4243edd 100644 --- a/chromium/storage/browser/fileapi/file_system_quota_client_unittest.cc +++ b/chromium/storage/browser/fileapi/file_system_quota_client_unittest.cc @@ -52,7 +52,7 @@ class FileSystemQuotaClientTest : public testing::Test { void SetUp() override { ASSERT_TRUE(data_dir_.CreateUniqueTempDir()); file_system_context_ = - CreateFileSystemContextForTesting(NULL, data_dir_.GetPath()); + CreateFileSystemContextForTesting(nullptr, data_dir_.GetPath()); } struct TestFile { @@ -252,7 +252,7 @@ TEST_F(FileSystemQuotaClientTest, NoFileSystemTest) { TEST_F(FileSystemQuotaClientTest, NoFileTest) { std::unique_ptr<FileSystemQuotaClient> quota_client(NewQuotaClient(false)); const TestFile kFiles[] = { - {true, NULL, 0, kDummyURL1, kTemporary}, + {true, nullptr, 0, kDummyURL1, kTemporary}, }; InitializeOriginFiles(quota_client.get(), kFiles, arraysize(kFiles)); @@ -264,8 +264,8 @@ TEST_F(FileSystemQuotaClientTest, NoFileTest) { TEST_F(FileSystemQuotaClientTest, OneFileTest) { std::unique_ptr<FileSystemQuotaClient> quota_client(NewQuotaClient(false)); const TestFile kFiles[] = { - {true, NULL, 0, kDummyURL1, kTemporary}, - {false, "foo", 4921, kDummyURL1, kTemporary}, + {true, nullptr, 0, kDummyURL1, kTemporary}, + {false, "foo", 4921, kDummyURL1, kTemporary}, }; InitializeOriginFiles(quota_client.get(), kFiles, arraysize(kFiles)); const int64_t file_paths_cost = ComputeFilePathsCostForOriginAndType( @@ -280,9 +280,9 @@ TEST_F(FileSystemQuotaClientTest, OneFileTest) { TEST_F(FileSystemQuotaClientTest, TwoFilesTest) { std::unique_ptr<FileSystemQuotaClient> quota_client(NewQuotaClient(false)); const TestFile kFiles[] = { - {true, NULL, 0, kDummyURL1, kTemporary}, - {false, "foo", 10310, kDummyURL1, kTemporary}, - {false, "bar", 41, kDummyURL1, kTemporary}, + {true, nullptr, 0, kDummyURL1, kTemporary}, + {false, "foo", 10310, kDummyURL1, kTemporary}, + {false, "bar", 41, kDummyURL1, kTemporary}, }; InitializeOriginFiles(quota_client.get(), kFiles, arraysize(kFiles)); const int64_t file_paths_cost = ComputeFilePathsCostForOriginAndType( @@ -297,10 +297,10 @@ TEST_F(FileSystemQuotaClientTest, TwoFilesTest) { TEST_F(FileSystemQuotaClientTest, EmptyFilesTest) { std::unique_ptr<FileSystemQuotaClient> quota_client(NewQuotaClient(false)); const TestFile kFiles[] = { - {true, NULL, 0, kDummyURL1, kTemporary}, - {false, "foo", 0, kDummyURL1, kTemporary}, - {false, "bar", 0, kDummyURL1, kTemporary}, - {false, "baz", 0, kDummyURL1, kTemporary}, + {true, nullptr, 0, kDummyURL1, kTemporary}, + {false, "foo", 0, kDummyURL1, kTemporary}, + {false, "bar", 0, kDummyURL1, kTemporary}, + {false, "baz", 0, kDummyURL1, kTemporary}, }; InitializeOriginFiles(quota_client.get(), kFiles, arraysize(kFiles)); const int64_t file_paths_cost = ComputeFilePathsCostForOriginAndType( @@ -315,10 +315,10 @@ TEST_F(FileSystemQuotaClientTest, EmptyFilesTest) { TEST_F(FileSystemQuotaClientTest, SubDirectoryTest) { std::unique_ptr<FileSystemQuotaClient> quota_client(NewQuotaClient(false)); const TestFile kFiles[] = { - {true, NULL, 0, kDummyURL1, kTemporary}, - {true, "dirtest", 0, kDummyURL1, kTemporary}, - {false, "dirtest/foo", 11921, kDummyURL1, kTemporary}, - {false, "bar", 4814, kDummyURL1, kTemporary}, + {true, nullptr, 0, kDummyURL1, kTemporary}, + {true, "dirtest", 0, kDummyURL1, kTemporary}, + {false, "dirtest/foo", 11921, kDummyURL1, kTemporary}, + {false, "bar", 4814, kDummyURL1, kTemporary}, }; InitializeOriginFiles(quota_client.get(), kFiles, arraysize(kFiles)); const int64_t file_paths_cost = ComputeFilePathsCostForOriginAndType( @@ -333,14 +333,14 @@ TEST_F(FileSystemQuotaClientTest, SubDirectoryTest) { TEST_F(FileSystemQuotaClientTest, MultiTypeTest) { std::unique_ptr<FileSystemQuotaClient> quota_client(NewQuotaClient(false)); const TestFile kFiles[] = { - {true, NULL, 0, kDummyURL1, kTemporary}, - {true, "dirtest", 0, kDummyURL1, kTemporary}, - {false, "dirtest/foo", 133, kDummyURL1, kTemporary}, - {false, "bar", 14, kDummyURL1, kTemporary}, - {true, NULL, 0, kDummyURL1, kPersistent}, - {true, "dirtest", 0, kDummyURL1, kPersistent}, - {false, "dirtest/foo", 193, kDummyURL1, kPersistent}, - {false, "bar", 9, kDummyURL1, kPersistent}, + {true, nullptr, 0, kDummyURL1, kTemporary}, + {true, "dirtest", 0, kDummyURL1, kTemporary}, + {false, "dirtest/foo", 133, kDummyURL1, kTemporary}, + {false, "bar", 14, kDummyURL1, kTemporary}, + {true, nullptr, 0, kDummyURL1, kPersistent}, + {true, "dirtest", 0, kDummyURL1, kPersistent}, + {false, "dirtest/foo", 193, kDummyURL1, kPersistent}, + {false, "bar", 9, kDummyURL1, kPersistent}, }; InitializeOriginFiles(quota_client.get(), kFiles, arraysize(kFiles)); const int64_t file_paths_cost_temporary = @@ -361,22 +361,22 @@ TEST_F(FileSystemQuotaClientTest, MultiTypeTest) { TEST_F(FileSystemQuotaClientTest, MultiDomainTest) { std::unique_ptr<FileSystemQuotaClient> quota_client(NewQuotaClient(false)); const TestFile kFiles[] = { - {true, NULL, 0, kDummyURL1, kTemporary}, - {true, "dir1", 0, kDummyURL1, kTemporary}, - {false, "dir1/foo", 1331, kDummyURL1, kTemporary}, - {false, "bar", 134, kDummyURL1, kTemporary}, - {true, NULL, 0, kDummyURL1, kPersistent}, - {true, "dir2", 0, kDummyURL1, kPersistent}, - {false, "dir2/foo", 1903, kDummyURL1, kPersistent}, - {false, "bar", 19, kDummyURL1, kPersistent}, - {true, NULL, 0, kDummyURL2, kTemporary}, - {true, "dom", 0, kDummyURL2, kTemporary}, - {false, "dom/fan", 1319, kDummyURL2, kTemporary}, - {false, "bar", 113, kDummyURL2, kTemporary}, - {true, NULL, 0, kDummyURL2, kPersistent}, - {true, "dom", 0, kDummyURL2, kPersistent}, - {false, "dom/fan", 2013, kDummyURL2, kPersistent}, - {false, "baz", 18, kDummyURL2, kPersistent}, + {true, nullptr, 0, kDummyURL1, kTemporary}, + {true, "dir1", 0, kDummyURL1, kTemporary}, + {false, "dir1/foo", 1331, kDummyURL1, kTemporary}, + {false, "bar", 134, kDummyURL1, kTemporary}, + {true, nullptr, 0, kDummyURL1, kPersistent}, + {true, "dir2", 0, kDummyURL1, kPersistent}, + {false, "dir2/foo", 1903, kDummyURL1, kPersistent}, + {false, "bar", 19, kDummyURL1, kPersistent}, + {true, nullptr, 0, kDummyURL2, kTemporary}, + {true, "dom", 0, kDummyURL2, kTemporary}, + {false, "dom/fan", 1319, kDummyURL2, kTemporary}, + {false, "bar", 113, kDummyURL2, kTemporary}, + {true, nullptr, 0, kDummyURL2, kPersistent}, + {true, "dom", 0, kDummyURL2, kPersistent}, + {false, "dom/fan", 2013, kDummyURL2, kPersistent}, + {false, "baz", 18, kDummyURL2, kPersistent}, }; InitializeOriginFiles(quota_client.get(), kFiles, arraysize(kFiles)); const int64_t file_paths_cost_temporary1 = @@ -407,9 +407,9 @@ TEST_F(FileSystemQuotaClientTest, MultiDomainTest) { TEST_F(FileSystemQuotaClientTest, GetUsage_MultipleTasks) { std::unique_ptr<FileSystemQuotaClient> quota_client(NewQuotaClient(false)); const TestFile kFiles[] = { - {true, NULL, 0, kDummyURL1, kTemporary}, - {false, "foo", 11, kDummyURL1, kTemporary}, - {false, "bar", 22, kDummyURL1, kTemporary}, + {true, nullptr, 0, kDummyURL1, kTemporary}, + {false, "foo", 11, kDummyURL1, kTemporary}, + {false, "bar", 22, kDummyURL1, kTemporary}, }; InitializeOriginFiles(quota_client.get(), kFiles, arraysize(kFiles)); const int64_t file_paths_cost = ComputeFilePathsCostForOriginAndType( @@ -437,9 +437,9 @@ TEST_F(FileSystemQuotaClientTest, GetUsage_MultipleTasks) { TEST_F(FileSystemQuotaClientTest, GetOriginsForType) { std::unique_ptr<FileSystemQuotaClient> quota_client(NewQuotaClient(false)); const TestFile kFiles[] = { - {true, NULL, 0, kDummyURL1, kTemporary}, - {true, NULL, 0, kDummyURL2, kTemporary}, - {true, NULL, 0, kDummyURL3, kPersistent}, + {true, nullptr, 0, kDummyURL1, kTemporary}, + {true, nullptr, 0, kDummyURL2, kTemporary}, + {true, nullptr, 0, kDummyURL3, kPersistent}, }; InitializeOriginFiles(quota_client.get(), kFiles, arraysize(kFiles)); @@ -462,11 +462,11 @@ TEST_F(FileSystemQuotaClientTest, GetOriginsForHost) { const char* kURL4 = "http://foo2.com/"; const char* kURL5 = "http://foo.com:2/"; const TestFile kFiles[] = { - {true, NULL, 0, kURL1, kTemporary}, - {true, NULL, 0, kURL2, kTemporary}, - {true, NULL, 0, kURL3, kTemporary}, - {true, NULL, 0, kURL4, kTemporary}, - {true, NULL, 0, kURL5, kPersistent}, + {true, nullptr, 0, kURL1, kTemporary}, + {true, nullptr, 0, kURL2, kTemporary}, + {true, nullptr, 0, kURL3, kTemporary}, + {true, nullptr, 0, kURL4, kTemporary}, + {true, nullptr, 0, kURL5, kPersistent}, }; InitializeOriginFiles(quota_client.get(), kFiles, arraysize(kFiles)); @@ -485,8 +485,8 @@ TEST_F(FileSystemQuotaClientTest, GetOriginsForHost) { TEST_F(FileSystemQuotaClientTest, IncognitoTest) { std::unique_ptr<FileSystemQuotaClient> quota_client(NewQuotaClient(true)); const TestFile kFiles[] = { - {true, NULL, 0, kDummyURL1, kTemporary}, - {false, "foo", 10, kDummyURL1, kTemporary}, + {true, nullptr, 0, kDummyURL1, kTemporary}, + {false, "foo", 10, kDummyURL1, kTemporary}, }; InitializeOriginFiles(quota_client.get(), kFiles, arraysize(kFiles)); @@ -505,20 +505,20 @@ TEST_F(FileSystemQuotaClientTest, IncognitoTest) { TEST_F(FileSystemQuotaClientTest, DeleteOriginTest) { std::unique_ptr<FileSystemQuotaClient> quota_client(NewQuotaClient(false)); const TestFile kFiles[] = { - {true, NULL, 0, "http://foo.com/", kTemporary}, - {false, "a", 1, "http://foo.com/", kTemporary}, - {true, NULL, 0, "https://foo.com/", kTemporary}, - {false, "b", 2, "https://foo.com/", kTemporary}, - {true, NULL, 0, "http://foo.com/", kPersistent}, - {false, "c", 4, "http://foo.com/", kPersistent}, - {true, NULL, 0, "http://bar.com/", kTemporary}, - {false, "d", 8, "http://bar.com/", kTemporary}, - {true, NULL, 0, "http://bar.com/", kPersistent}, - {false, "e", 16, "http://bar.com/", kPersistent}, - {true, NULL, 0, "https://bar.com/", kPersistent}, - {false, "f", 32, "https://bar.com/", kPersistent}, - {true, NULL, 0, "https://bar.com/", kTemporary}, - {false, "g", 64, "https://bar.com/", kTemporary}, + {true, nullptr, 0, "http://foo.com/", kTemporary}, + {false, "a", 1, "http://foo.com/", kTemporary}, + {true, nullptr, 0, "https://foo.com/", kTemporary}, + {false, "b", 2, "https://foo.com/", kTemporary}, + {true, nullptr, 0, "http://foo.com/", kPersistent}, + {false, "c", 4, "http://foo.com/", kPersistent}, + {true, nullptr, 0, "http://bar.com/", kTemporary}, + {false, "d", 8, "http://bar.com/", kTemporary}, + {true, nullptr, 0, "http://bar.com/", kPersistent}, + {false, "e", 16, "http://bar.com/", kPersistent}, + {true, nullptr, 0, "https://bar.com/", kPersistent}, + {false, "f", 32, "https://bar.com/", kPersistent}, + {true, nullptr, 0, "https://bar.com/", kTemporary}, + {false, "g", 64, "https://bar.com/", kTemporary}, }; InitializeOriginFiles(quota_client.get(), kFiles, arraysize(kFiles)); const int64_t file_paths_cost_temporary_foo_https = diff --git a/chromium/storage/browser/fileapi/file_system_url_request_job.cc b/chromium/storage/browser/fileapi/file_system_url_request_job.cc index a2713177cd7..152d67f43e2 100644 --- a/chromium/storage/browser/fileapi/file_system_url_request_job.cc +++ b/chromium/storage/browser/fileapi/file_system_url_request_job.cc @@ -86,7 +86,7 @@ int FileSystemURLRequestJob::ReadRawData(net::IOBuffer* dest, int dest_size) { DCHECK_NE(dest_size, 0); DCHECK_GE(remaining_bytes_, 0); - if (reader_.get() == NULL) + if (reader_.get() == nullptr) return net::ERR_FAILED; if (remaining_bytes_ < dest_size) diff --git a/chromium/storage/browser/fileapi/file_system_url_request_job_unittest.cc b/chromium/storage/browser/fileapi/file_system_url_request_job_unittest.cc index 2caef9dfd5d..4e64cef7972 100644 --- a/chromium/storage/browser/fileapi/file_system_url_request_job_unittest.cc +++ b/chromium/storage/browser/fileapi/file_system_url_request_job_unittest.cc @@ -139,7 +139,7 @@ class FileSystemURLRequestJobTest : public testing::Test { // We use the main thread so that we can get the root path synchronously. // TODO(adamk): Run this on the FILE thread we've created as well. file_system_context_ = - CreateFileSystemContextForTesting(NULL, temp_dir_.GetPath()); + CreateFileSystemContextForTesting(nullptr, temp_dir_.GetPath()); file_system_context_->OpenFileSystem( GURL("http://remote/"), storage::kFileSystemTypeTemporary, @@ -168,7 +168,8 @@ class FileSystemURLRequestJobTest : public testing::Test { handlers.push_back(base::BindRepeating(&TestAutoMountForURLRequest)); file_system_context_ = CreateFileSystemContextWithAutoMountersForTesting( - NULL, std::move(additional_providers), handlers, temp_dir_.GetPath()); + nullptr, std::move(additional_providers), handlers, + temp_dir_.GetPath()); ASSERT_EQ(static_cast<int>(sizeof(kTestFileData)) - 1, base::WriteFile(mnt_point.AppendASCII("foo"), kTestFileData, @@ -204,12 +205,12 @@ class FileSystemURLRequestJobTest : public testing::Test { } void TestRequest(const GURL& url) { - TestRequestHelper(url, NULL, true, file_system_context_.get()); + TestRequestHelper(url, nullptr, true, file_system_context_.get()); } void TestRequestWithContext(const GURL& url, FileSystemContext* file_system_context) { - TestRequestHelper(url, NULL, true, file_system_context); + TestRequestHelper(url, nullptr, true, file_system_context); } void TestRequestWithHeaders(const GURL& url, @@ -218,7 +219,7 @@ class FileSystemURLRequestJobTest : public testing::Test { } void TestRequestNoRun(const GURL& url) { - TestRequestHelper(url, NULL, false, file_system_context_.get()); + TestRequestHelper(url, nullptr, false, file_system_context_.get()); } void CreateDirectory(const base::StringPiece& dir_name) { @@ -419,7 +420,7 @@ TEST_F(FileSystemURLRequestJobTest, Incognito) { // Creates a new filesystem context for incognito mode. scoped_refptr<FileSystemContext> file_system_context = - CreateIncognitoFileSystemContextForTesting(NULL, temp_dir_.GetPath()); + CreateIncognitoFileSystemContextForTesting(nullptr, temp_dir_.GetPath()); // The request should return NOT_FOUND error if it's in incognito mode. TestRequestWithContext(CreateFileSystemURL("file"), diff --git a/chromium/storage/browser/fileapi/file_writer_delegate.cc b/chromium/storage/browser/fileapi/file_writer_delegate.cc index 9237aeb7635..ed50b72e379 100644 --- a/chromium/storage/browser/fileapi/file_writer_delegate.cc +++ b/chromium/storage/browser/fileapi/file_writer_delegate.cc @@ -40,16 +40,35 @@ FileWriterDelegate::FileWriterDelegate( FileWriterDelegate::~FileWriterDelegate() = default; -void FileWriterDelegate::Start(std::unique_ptr<net::URLRequest> request, +void FileWriterDelegate::Start(std::unique_ptr<BlobReader> blob_reader, const DelegateWriteCallback& write_callback) { write_callback_ = write_callback; - request_ = std::move(request); - request_->Start(); + + if (!blob_reader) { + OnReadError(base::File::FILE_ERROR_FAILED); + return; + } + + blob_reader_ = std::move(blob_reader); + BlobReader::Status status = blob_reader_->CalculateSize(base::BindOnce( + &FileWriterDelegate::OnDidCalculateSize, weak_factory_.GetWeakPtr())); + switch (status) { + case BlobReader::Status::NET_ERROR: + OnDidCalculateSize(blob_reader_->net_error()); + return; + case BlobReader::Status::DONE: + OnDidCalculateSize(net::OK); + return; + case BlobReader::Status::IO_PENDING: + // Do nothing. + return; + } + NOTREACHED(); } void FileWriterDelegate::Cancel() { - // Destroy the request and invalidate weak ptrs to prevent pending callbacks. - request_.reset(); + // Destroy the reader and invalidate weak ptrs to prevent pending callbacks. + blob_reader_ = nullptr; weak_factory_.InvalidateWeakPtrs(); const int status = file_stream_writer_->Cancel( @@ -63,53 +82,21 @@ void FileWriterDelegate::Cancel() { } } -void FileWriterDelegate::OnReceivedRedirect( - net::URLRequest* request, - const net::RedirectInfo& redirect_info, - bool* defer_redirect) { - NOTREACHED(); - OnReadError(base::File::FILE_ERROR_SECURITY); -} - -void FileWriterDelegate::OnAuthRequired(net::URLRequest* request, - net::AuthChallengeInfo* auth_info) { - NOTREACHED(); - OnReadError(base::File::FILE_ERROR_SECURITY); -} - -void FileWriterDelegate::OnCertificateRequested( - net::URLRequest* request, - net::SSLCertRequestInfo* cert_request_info) { - NOTREACHED(); - OnReadError(base::File::FILE_ERROR_SECURITY); -} - -void FileWriterDelegate::OnSSLCertificateError(net::URLRequest* request, - const net::SSLInfo& ssl_info, - bool fatal) { - NOTREACHED(); - OnReadError(base::File::FILE_ERROR_SECURITY); -} - -void FileWriterDelegate::OnResponseStarted(net::URLRequest* request, - int net_error) { +void FileWriterDelegate::OnDidCalculateSize(int net_error) { DCHECK_NE(net::ERR_IO_PENDING, net_error); - DCHECK_EQ(request_.get(), request); - if (net_error != net::OK || request->GetResponseCode() != 200) { - OnReadError(base::File::FILE_ERROR_FAILED); + if (net_error != net::OK) { + OnReadError(NetErrorToFileError(net_error)); return; } Read(); } -void FileWriterDelegate::OnReadCompleted(net::URLRequest* request, - int bytes_read) { +void FileWriterDelegate::OnReadCompleted(int bytes_read) { DCHECK_NE(net::ERR_IO_PENDING, bytes_read); - DCHECK_EQ(request_.get(), request); if (bytes_read < 0) { - OnReadError(base::File::FILE_ERROR_FAILED); + OnReadError(NetErrorToFileError(bytes_read)); return; } OnDataReceived(bytes_read); @@ -117,17 +104,24 @@ void FileWriterDelegate::OnReadCompleted(net::URLRequest* request, void FileWriterDelegate::Read() { bytes_written_ = 0; - bytes_read_ = request_->Read(io_buffer_.get(), io_buffer_->size()); - if (bytes_read_ == net::ERR_IO_PENDING) - return; - - if (bytes_read_ >= 0) { - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(&FileWriterDelegate::OnDataReceived, - weak_factory_.GetWeakPtr(), bytes_read_)); - } else { - OnReadError(base::File::FILE_ERROR_FAILED); + BlobReader::Status status = + blob_reader_->Read(io_buffer_.get(), io_buffer_->size(), &bytes_read_, + base::BindOnce(&FileWriterDelegate::OnReadCompleted, + weak_factory_.GetWeakPtr())); + switch (status) { + case BlobReader::Status::NET_ERROR: + OnReadCompleted(blob_reader_->net_error()); + return; + case BlobReader::Status::DONE: + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(&FileWriterDelegate::OnReadCompleted, + weak_factory_.GetWeakPtr(), bytes_read_)); + return; + case BlobReader::Status::IO_PENDING: + // Do nothing. + return; } + NOTREACHED(); } void FileWriterDelegate::OnDataReceived(int bytes_read) { @@ -138,7 +132,8 @@ void FileWriterDelegate::OnDataReceived(int bytes_read) { // This could easily be optimized to rotate between a pool of buffers, so // that we could read and write at the same time. It's not yet clear that // it's necessary. - cursor_ = new net::DrainableIOBuffer(io_buffer_.get(), bytes_read_); + cursor_ = + base::MakeRefCounted<net::DrainableIOBuffer>(io_buffer_, bytes_read_); Write(); } } @@ -195,8 +190,8 @@ void FileWriterDelegate::OnReadError(base::File::Error error) { return; } - // Destroy the request and invalidate weak ptrs to prevent pending callbacks. - request_.reset(); + // Destroy the reader and invalidate weak ptrs to prevent pending callbacks. + blob_reader_.reset(); weak_factory_.InvalidateWeakPtrs(); if (writing_started_) @@ -206,8 +201,8 @@ void FileWriterDelegate::OnReadError(base::File::Error error) { } void FileWriterDelegate::OnWriteError(base::File::Error error) { - // Destroy the request and invalidate weak ptrs to prevent pending callbacks. - request_.reset(); + // Destroy the reader and invalidate weak ptrs to prevent pending callbacks. + blob_reader_.reset(); weak_factory_.InvalidateWeakPtrs(); // Errors when writing are not recoverable, so don't bother flushing. diff --git a/chromium/storage/browser/fileapi/file_writer_delegate.h b/chromium/storage/browser/fileapi/file_writer_delegate.h index ed134c1845c..3671c3b2856 100644 --- a/chromium/storage/browser/fileapi/file_writer_delegate.h +++ b/chromium/storage/browser/fileapi/file_writer_delegate.h @@ -16,7 +16,7 @@ #include "base/time/time.h" #include "net/base/file_stream.h" #include "net/base/io_buffer.h" -#include "net/url_request/url_request.h" +#include "storage/browser/blob/blob_reader.h" #include "storage/browser/storage_browser_export.h" namespace storage { @@ -24,7 +24,7 @@ namespace storage { class FileStreamWriter; enum class FlushPolicy; -class STORAGE_EXPORT FileWriterDelegate : public net::URLRequest::Delegate { +class STORAGE_EXPORT FileWriterDelegate { public: enum WriteProgressStatus { SUCCESS_IO_PENDING, @@ -40,9 +40,9 @@ class STORAGE_EXPORT FileWriterDelegate : public net::URLRequest::Delegate { FileWriterDelegate(std::unique_ptr<FileStreamWriter> file_writer, FlushPolicy flush_policy); - ~FileWriterDelegate() override; + virtual ~FileWriterDelegate(); - void Start(std::unique_ptr<net::URLRequest> request, + void Start(std::unique_ptr<BlobReader> blob_reader, const DelegateWriteCallback& write_callback); // Cancels the current write operation. This will synchronously or @@ -50,29 +50,15 @@ class STORAGE_EXPORT FileWriterDelegate : public net::URLRequest::Delegate { // deleting this). void Cancel(); - void OnReceivedRedirect(net::URLRequest* request, - const net::RedirectInfo& redirect_info, - bool* defer_redirect) override; - void OnAuthRequired(net::URLRequest* request, - net::AuthChallengeInfo* auth_info) override; - void OnCertificateRequested( - net::URLRequest* request, - net::SSLCertRequestInfo* cert_request_info) override; - void OnSSLCertificateError(net::URLRequest* request, - const net::SSLInfo& ssl_info, - bool fatal) override; - void OnResponseStarted(net::URLRequest* request, int net_error) override; - void OnReadCompleted(net::URLRequest* request, int bytes_read) override; - protected: // Virtual for tests. virtual void OnDataReceived(int bytes_read); private: - void OnGetFileInfoAndStartRequest(std::unique_ptr<net::URLRequest> request, - base::File::Error error, - const base::File::Info& file_info); + void OnDidCalculateSize(int net_error); + void Read(); + void OnReadCompleted(int bytes_read); void Write(); void OnDataWritten(int write_response); void OnReadError(base::File::Error error); @@ -101,7 +87,7 @@ class STORAGE_EXPORT FileWriterDelegate : public net::URLRequest::Delegate { base::File::Error saved_read_error_ = base::File::FILE_OK; scoped_refptr<net::IOBufferWithSize> io_buffer_; scoped_refptr<net::DrainableIOBuffer> cursor_; - std::unique_ptr<net::URLRequest> request_; + std::unique_ptr<BlobReader> blob_reader_; base::WeakPtrFactory<FileWriterDelegate> weak_factory_; diff --git a/chromium/storage/browser/fileapi/file_writer_delegate_unittest.cc b/chromium/storage/browser/fileapi/file_writer_delegate_unittest.cc index 2839396d8d6..eb78e5f40c7 100644 --- a/chromium/storage/browser/fileapi/file_writer_delegate_unittest.cc +++ b/chromium/storage/browser/fileapi/file_writer_delegate_unittest.cc @@ -14,9 +14,9 @@ #include "base/location.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/test/scoped_task_environment.h" #include "base/threading/thread_task_runner_handle.h" #include "net/base/io_buffer.h" #include "net/base/request_priority.h" @@ -27,6 +27,8 @@ #include "net/url_request/url_request_job.h" #include "net/url_request/url_request_job_factory.h" #include "net/url_request/url_request_status.h" +#include "storage/browser/blob/blob_data_builder.h" +#include "storage/browser/blob/blob_storage_context.h" #include "storage/browser/fileapi/file_system_context.h" #include "storage/browser/fileapi/file_system_quota_util.h" #include "storage/browser/fileapi/file_writer_delegate.h" @@ -92,7 +94,9 @@ class BlobURLRequestJobFactory; class FileWriterDelegateTest : public PlatformTest { public: - FileWriterDelegateTest() = default; + FileWriterDelegateTest() + : scoped_task_environment_( + base::test::ScopedTaskEnvironment::MainThreadType::IO) {} protected: void SetUp() override; @@ -146,157 +150,57 @@ class FileWriterDelegateTest : public PlatformTest { return base::BindRepeating(&Result::DidWrite, base::Unretained(result)); } - // Creates and sets up a FileWriterDelegate for writing the given |blob_url|, - // and creates a new FileWriterDelegate for the file. + // Creates and sets up a FileWriterDelegate for writing the given + // |blob_content|, and creates a new FileWriterDelegate for the file. void PrepareForWrite(const char* test_file_path, - const GURL& blob_url, int64_t offset, int64_t allowed_growth) { file_writer_delegate_ = CreateWriterDelegate(test_file_path, offset, allowed_growth); - request_ = empty_context_.CreateRequest(blob_url, net::DEFAULT_PRIORITY, - file_writer_delegate_.get(), - TRAFFIC_ANNOTATION_FOR_TESTS); + } + + std::unique_ptr<storage::BlobDataHandle> CreateBlob( + const std::string& contents) { + auto builder = std::make_unique<storage::BlobDataBuilder>("blob-uuid"); + builder->AppendData(contents); + return blob_context_->AddFinishedBlob(std::move(builder)); } // This should be alive until the very end of this instance. - base::MessageLoopForIO loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; scoped_refptr<storage::FileSystemContext> file_system_context_; + std::unique_ptr<storage::BlobStorageContext> blob_context_; - net::URLRequestContext empty_context_; std::unique_ptr<FileWriterDelegate> file_writer_delegate_; - std::unique_ptr<net::URLRequest> request_; - std::unique_ptr<BlobURLRequestJobFactory> job_factory_; base::ScopedTempDir dir_; - - static const char* content_; }; -const char* FileWriterDelegateTest::content_ = NULL; - -namespace { - -static std::string g_content; - -class FileWriterDelegateTestJob : public net::URLRequestJob { - public: - FileWriterDelegateTestJob(net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const std::string& content) - : net::URLRequestJob(request, network_delegate), - content_(content), - remaining_bytes_(content.length()), - cursor_(0), - weak_factory_(this) {} - - void Start() override { - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::BindOnce(&FileWriterDelegateTestJob::NotifyHeadersComplete, - weak_factory_.GetWeakPtr())); - } - - int ReadRawData(net::IOBuffer* buf, int buf_size) override { - if (remaining_bytes_ < buf_size) - buf_size = remaining_bytes_; - - for (int i = 0; i < buf_size; ++i) - buf->data()[i] = content_[cursor_++]; - remaining_bytes_ -= buf_size; - - return buf_size; - } - - void GetResponseInfo(net::HttpResponseInfo* info) override { - const char kStatus[] = "HTTP/1.1 200 OK\0"; - const size_t kStatusLen = arraysize(kStatus); - - info->headers = - new net::HttpResponseHeaders(std::string(kStatus, kStatusLen)); - } - - protected: - ~FileWriterDelegateTestJob() override = default; - - private: - std::string content_; - int remaining_bytes_; - int cursor_; - - base::WeakPtrFactory<FileWriterDelegateTestJob> weak_factory_; -}; - -class BlobURLRequestJobFactory : public net::URLRequestJobFactory { - public: - explicit BlobURLRequestJobFactory(const char** content_data) - : content_data_(content_data) { - } - - net::URLRequestJob* MaybeCreateJobWithProtocolHandler( - const std::string& scheme, - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const override { - return new FileWriterDelegateTestJob(request, network_delegate, - *content_data_); - } - - net::URLRequestJob* MaybeInterceptRedirect( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const GURL& location) const override { - return nullptr; - } - - net::URLRequestJob* MaybeInterceptResponse( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const override { - return nullptr; - } - - bool IsHandledProtocol(const std::string& scheme) const override { - return scheme == "blob"; - } - - bool IsSafeRedirectTarget(const GURL& location) const override { - return true; - } - - private: - const char** content_data_; - - DISALLOW_COPY_AND_ASSIGN(BlobURLRequestJobFactory); -}; - -} // namespace (anonymous) - void FileWriterDelegateTest::SetUp() { ASSERT_TRUE(dir_.CreateUniqueTempDir()); file_system_context_ = - CreateFileSystemContextForTesting(NULL, dir_.GetPath()); + CreateFileSystemContextForTesting(nullptr, dir_.GetPath()); ASSERT_EQ(base::File::FILE_OK, AsyncFileTestHelper::CreateFile(file_system_context_.get(), GetFileSystemURL("test"))); - job_factory_ = std::make_unique<BlobURLRequestJobFactory>(&content_); - empty_context_.set_job_factory(job_factory_.get()); + blob_context_ = std::make_unique<storage::BlobStorageContext>(); } void FileWriterDelegateTest::TearDown() { - file_system_context_ = NULL; + file_system_context_ = nullptr; base::RunLoop().RunUntilIdle(); } TEST_F(FileWriterDelegateTest, WriteSuccessWithoutQuotaLimit) { - const GURL kBlobURL("blob:nolimit"); - content_ = kData; + auto blob = CreateBlob(kData); - PrepareForWrite("test", kBlobURL, 0, std::numeric_limits<int64_t>::max()); + PrepareForWrite("test", 0, std::numeric_limits<int64_t>::max()); Result result; ASSERT_EQ(0, usage()); - file_writer_delegate_->Start(std::move(request_), GetWriteCallback(&result)); + file_writer_delegate_->Start(blob->CreateReader(), GetWriteCallback(&result)); base::RunLoop().Run(); ASSERT_EQ(FileWriterDelegate::SUCCESS_COMPLETED, result.write_status()); @@ -309,14 +213,13 @@ TEST_F(FileWriterDelegateTest, WriteSuccessWithoutQuotaLimit) { } TEST_F(FileWriterDelegateTest, WriteSuccessWithJustQuota) { - const GURL kBlobURL("blob:just"); - content_ = kData; + auto blob = CreateBlob(kData); const int64_t kAllowedGrowth = kDataSize; - PrepareForWrite("test", kBlobURL, 0, kAllowedGrowth); + PrepareForWrite("test", 0, kAllowedGrowth); Result result; ASSERT_EQ(0, usage()); - file_writer_delegate_->Start(std::move(request_), GetWriteCallback(&result)); + file_writer_delegate_->Start(blob->CreateReader(), GetWriteCallback(&result)); base::RunLoop().Run(); ASSERT_EQ(FileWriterDelegate::SUCCESS_COMPLETED, result.write_status()); file_writer_delegate_.reset(); @@ -329,14 +232,13 @@ TEST_F(FileWriterDelegateTest, WriteSuccessWithJustQuota) { } TEST_F(FileWriterDelegateTest, DISABLED_WriteFailureByQuota) { - const GURL kBlobURL("blob:failure"); - content_ = kData; + auto blob = CreateBlob(kData); const int64_t kAllowedGrowth = kDataSize - 1; - PrepareForWrite("test", kBlobURL, 0, kAllowedGrowth); + PrepareForWrite("test", 0, kAllowedGrowth); Result result; ASSERT_EQ(0, usage()); - file_writer_delegate_->Start(std::move(request_), GetWriteCallback(&result)); + file_writer_delegate_->Start(blob->CreateReader(), GetWriteCallback(&result)); base::RunLoop().Run(); ASSERT_EQ(FileWriterDelegate::ERROR_WRITE_STARTED, result.write_status()); file_writer_delegate_.reset(); @@ -350,14 +252,13 @@ TEST_F(FileWriterDelegateTest, DISABLED_WriteFailureByQuota) { } TEST_F(FileWriterDelegateTest, WriteZeroBytesSuccessfullyWithZeroQuota) { - const GURL kBlobURL("blob:zero"); - content_ = ""; + auto blob = CreateBlob(""); int64_t kAllowedGrowth = 0; - PrepareForWrite("test", kBlobURL, 0, kAllowedGrowth); + PrepareForWrite("test", 0, kAllowedGrowth); Result result; ASSERT_EQ(0, usage()); - file_writer_delegate_->Start(std::move(request_), GetWriteCallback(&result)); + file_writer_delegate_->Start(blob->CreateReader(), GetWriteCallback(&result)); base::RunLoop().Run(); ASSERT_EQ(FileWriterDelegate::SUCCESS_COMPLETED, result.write_status()); file_writer_delegate_.reset(); @@ -372,29 +273,24 @@ TEST_F(FileWriterDelegateTest, WriteZeroBytesSuccessfullyWithZeroQuota) { TEST_F(FileWriterDelegateTest, WriteSuccessWithoutQuotaLimitConcurrent) { std::unique_ptr<FileWriterDelegate> file_writer_delegate2; - std::unique_ptr<net::URLRequest> request2; ASSERT_EQ(base::File::FILE_OK, AsyncFileTestHelper::CreateFile(file_system_context_.get(), GetFileSystemURL("test2"))); - const GURL kBlobURL("blob:nolimitconcurrent"); - const GURL kBlobURL2("blob:nolimitconcurrent2"); - content_ = kData; + auto blob = CreateBlob(kData); - PrepareForWrite("test", kBlobURL, 0, std::numeric_limits<int64_t>::max()); + PrepareForWrite("test", 0, std::numeric_limits<int64_t>::max()); // Create another FileWriterDelegate for concurrent write. file_writer_delegate2 = CreateWriterDelegate("test2", 0, std::numeric_limits<int64_t>::max()); - request2 = empty_context_.CreateRequest(kBlobURL2, net::DEFAULT_PRIORITY, - file_writer_delegate2.get(), - TRAFFIC_ANNOTATION_FOR_TESTS); Result result, result2; ASSERT_EQ(0, usage()); - file_writer_delegate_->Start(std::move(request_), GetWriteCallback(&result)); - file_writer_delegate2->Start(std::move(request2), GetWriteCallback(&result2)); + file_writer_delegate_->Start(blob->CreateReader(), GetWriteCallback(&result)); + file_writer_delegate2->Start(blob->CreateReader(), + GetWriteCallback(&result2)); base::RunLoop().Run(); if (result.write_status() == FileWriterDelegate::SUCCESS_IO_PENDING || result2.write_status() == FileWriterDelegate::SUCCESS_IO_PENDING) @@ -415,19 +311,18 @@ TEST_F(FileWriterDelegateTest, WriteSuccessWithoutQuotaLimitConcurrent) { } TEST_F(FileWriterDelegateTest, WritesWithQuotaAndOffset) { - const GURL kBlobURL("blob:failure-with-updated-quota"); - content_ = kData; + auto blob = CreateBlob(kData); // Writing kDataSize (=45) bytes data while allowed_growth is 100. int64_t offset = 0; int64_t allowed_growth = 100; ASSERT_LT(kDataSize, allowed_growth); - PrepareForWrite("test", kBlobURL, offset, allowed_growth); + PrepareForWrite("test", offset, allowed_growth); { Result result; ASSERT_EQ(0, usage()); - file_writer_delegate_->Start(std::move(request_), + file_writer_delegate_->Start(blob->CreateReader(), GetWriteCallback(&result)); base::RunLoop().Run(); ASSERT_EQ(FileWriterDelegate::SUCCESS_COMPLETED, result.write_status()); @@ -442,11 +337,11 @@ TEST_F(FileWriterDelegateTest, WritesWithQuotaAndOffset) { // Trying to overwrite kDataSize bytes data while allowed_growth is 20. offset = 0; allowed_growth = 20; - PrepareForWrite("test", kBlobURL, offset, allowed_growth); + PrepareForWrite("test", offset, allowed_growth); { Result result; - file_writer_delegate_->Start(std::move(request_), + file_writer_delegate_->Start(blob->CreateReader(), GetWriteCallback(&result)); base::RunLoop().Run(); EXPECT_EQ(kDataSize, usage()); @@ -460,11 +355,11 @@ TEST_F(FileWriterDelegateTest, WritesWithQuotaAndOffset) { // allowed_growth is 55. offset = 25; allowed_growth = 55; - PrepareForWrite("test", kBlobURL, offset, allowed_growth); + PrepareForWrite("test", offset, allowed_growth); { Result result; - file_writer_delegate_->Start(std::move(request_), + file_writer_delegate_->Start(blob->CreateReader(), GetWriteCallback(&result)); base::RunLoop().Run(); ASSERT_EQ(FileWriterDelegate::SUCCESS_COMPLETED, result.write_status()); @@ -479,12 +374,12 @@ TEST_F(FileWriterDelegateTest, WritesWithQuotaAndOffset) { // Trying to overwrite 45 bytes data while allowed_growth is -20. offset = 0; allowed_growth = -20; - PrepareForWrite("test", kBlobURL, offset, allowed_growth); + PrepareForWrite("test", offset, allowed_growth); int64_t pre_write_usage = GetFileSizeOnDisk("test"); { Result result; - file_writer_delegate_->Start(std::move(request_), + file_writer_delegate_->Start(blob->CreateReader(), GetWriteCallback(&result)); base::RunLoop().Run(); ASSERT_EQ(FileWriterDelegate::SUCCESS_COMPLETED, result.write_status()); @@ -501,11 +396,11 @@ TEST_F(FileWriterDelegateTest, WritesWithQuotaAndOffset) { const int kOverlap = 20; offset = pre_write_usage - kOverlap; allowed_growth = 10; - PrepareForWrite("test", kBlobURL, offset, allowed_growth); + PrepareForWrite("test", offset, allowed_growth); { Result result; - file_writer_delegate_->Start(std::move(request_), + file_writer_delegate_->Start(blob->CreateReader(), GetWriteCallback(&result)); base::RunLoop().Run(); ASSERT_EQ(FileWriterDelegate::ERROR_WRITE_STARTED, result.write_status()); @@ -518,53 +413,4 @@ TEST_F(FileWriterDelegateTest, WritesWithQuotaAndOffset) { } } -class InterruptedFileWriterDelegate : public FileWriterDelegate { - public: - InterruptedFileWriterDelegate( - std::unique_ptr<storage::FileStreamWriter> file_writer, - storage::FlushPolicy flush_policy) - : FileWriterDelegate(std::move(file_writer), flush_policy) {} - ~InterruptedFileWriterDelegate() override = default; - - void OnDataReceived(int bytes_read) override { - // The base class will respond to OnDataReceived by performing an - // asynchronous write. Schedule a task now that will execute before the - // write completes which terminates the URLRequestJob. - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(IgnoreResult(&net::URLRequest::Cancel), - base::Unretained(request_))); - FileWriterDelegate::OnDataReceived(bytes_read); - } - - void set_request(net::URLRequest* request) { request_ = request; } - - private: - // The request is owned by the base class as a private member. - net::URLRequest* request_ = nullptr; -}; - -TEST_F(FileWriterDelegateTest, ReadFailureDuringAsyncWrite) { - const GURL kBlobURL("blob:async-fail"); - content_ = kData; - - auto writer = CreateWriter("test", 0, std::numeric_limits<int64_t>::max()); - auto file_writer_delegate = std::make_unique<InterruptedFileWriterDelegate>( - std::move(writer), storage::FlushPolicy::FLUSH_ON_COMPLETION); - auto request = empty_context_.CreateRequest(kBlobURL, net::DEFAULT_PRIORITY, - file_writer_delegate.get(), - TRAFFIC_ANNOTATION_FOR_TESTS); - file_writer_delegate->set_request(request.get()); - - Result result; - file_writer_delegate->Start(std::move(request), GetWriteCallback(&result)); - base::RunLoop().Run(); - - ASSERT_EQ(FileWriterDelegate::ERROR_WRITE_STARTED, result.write_status()); - file_writer_delegate_.reset(); - - // The write should still have flushed. - ASSERT_EQ(kDataSize, usage()); - EXPECT_EQ(GetFileSizeOnDisk("test"), usage()); -} - } // namespace content diff --git a/chromium/storage/browser/fileapi/file_writer_impl.cc b/chromium/storage/browser/fileapi/file_writer_impl.cc new file mode 100644 index 00000000000..4f62f86a568 --- /dev/null +++ b/chromium/storage/browser/fileapi/file_writer_impl.cc @@ -0,0 +1,98 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "storage/browser/fileapi/file_writer_impl.h" + +#include "base/callback_helpers.h" +#include "storage/browser/blob/blob_data_handle.h" +#include "storage/browser/blob/blob_storage_context.h" + +namespace storage { + +FileWriterImpl::FileWriterImpl( + FileSystemURL url, + std::unique_ptr<FileSystemOperationRunner> operation_runner, + base::WeakPtr<BlobStorageContext> blob_context) + : operation_runner_(std::move(operation_runner)), + blob_context_(std::move(blob_context)), + url_(std::move(url)) { + DCHECK(url_.is_valid()); +} + +FileWriterImpl::~FileWriterImpl() = default; + +void FileWriterImpl::Write(uint64_t position, + blink::mojom::BlobPtr blob, + WriteCallback callback) { + blob_context_->GetBlobDataFromBlobPtr( + std::move(blob), + base::BindOnce(&FileWriterImpl::DoWrite, base::Unretained(this), + std::move(callback), position)); +} + +void FileWriterImpl::Truncate(uint64_t length, TruncateCallback callback) { + operation_runner_->Truncate( + url_, length, + base::BindRepeating( + &FileWriterImpl::DidTruncate, base::Unretained(this), + base::AdaptCallbackForRepeating(std::move(callback)))); +} + +void FileWriterImpl::DoWrite(WriteCallback callback, + uint64_t position, + std::unique_ptr<BlobDataHandle> blob) { + if (!blob) { + std::move(callback).Run(base::File::FILE_ERROR_FAILED, 0); + return; + } + + // FileSystemOperationRunner assumes that positions passed to Write are always + // valid, and will NOTREACHED() if that is not the case, so first check the + // size of the file to make sure the position passed in from the renderer is + // in fact valid. + // Of course the file could still change between checking its size and the + // write operation being started, but this is at least a lot better than the + // old implementation where the renderer only checks against how big it thinks + // the file currently is. + operation_runner_->GetMetadata( + url_, FileSystemOperation::GET_METADATA_FIELD_SIZE, + base::BindRepeating(&FileWriterImpl::DoWriteWithFileInfo, + base::Unretained(this), + base::AdaptCallbackForRepeating(std::move(callback)), + position, base::Passed(std::move(blob)))); +} + +void FileWriterImpl::DoWriteWithFileInfo(WriteCallback callback, + uint64_t position, + std::unique_ptr<BlobDataHandle> blob, + base::File::Error result, + const base::File::Info& file_info) { + if (file_info.size < 0 || position > static_cast<uint64_t>(file_info.size)) { + std::move(callback).Run(base::File::FILE_ERROR_FAILED, 0); + return; + } + operation_runner_->Write( + url_, std::move(blob), position, + base::BindRepeating(&FileWriterImpl::DidWrite, base::Unretained(this), + base::AdaptCallbackForRepeating(std::move(callback)), + base::Owned(new WriteState()))); +} + +void FileWriterImpl::DidWrite(WriteCallback callback, + WriteState* state, + base::File::Error result, + int64_t bytes, + bool complete) { + DCHECK(state); + state->bytes_written += bytes; + if (complete) + std::move(callback).Run(result, state->bytes_written); +} + +void FileWriterImpl::DidTruncate(TruncateCallback callback, + base::File::Error result) { + std::move(callback).Run(result); +} + +} // namespace storage diff --git a/chromium/storage/browser/fileapi/file_writer_impl.h b/chromium/storage/browser/fileapi/file_writer_impl.h new file mode 100644 index 00000000000..5198134b59a --- /dev/null +++ b/chromium/storage/browser/fileapi/file_writer_impl.h @@ -0,0 +1,58 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_FILEAPI_FILE_WRITER_IMPL_H_ +#define STORAGE_BROWSER_FILEAPI_FILE_WRITER_IMPL_H_ + +#include "storage/browser/fileapi/file_system_operation_runner.h" +#include "storage/browser/fileapi/file_system_url.h" +#include "storage/browser/storage_browser_export.h" +#include "third_party/blink/public/mojom/filesystem/file_writer.mojom.h" + +namespace storage { + +// This class itself is stateless, but it uses the passed in +// FileSystemOperationRunner and BlobStorageContext so all methods should be +// called on the sequence those instances live on. In chromium that means all +// usage has to be on the IO thread. +class STORAGE_EXPORT FileWriterImpl : public blink::mojom::FileWriter { + public: + FileWriterImpl(FileSystemURL url, + std::unique_ptr<FileSystemOperationRunner> operation_runner, + base::WeakPtr<BlobStorageContext> blob_context); + ~FileWriterImpl() override; + + void Write(uint64_t position, + blink::mojom::BlobPtr blob, + WriteCallback callback) override; + void Truncate(uint64_t length, TruncateCallback callback) override; + + private: + void DoWrite(WriteCallback callback, + uint64_t position, + std::unique_ptr<BlobDataHandle> blob); + void DoWriteWithFileInfo(WriteCallback callback, + uint64_t position, + std::unique_ptr<BlobDataHandle> blob, + base::File::Error result, + const base::File::Info& file_info); + + struct WriteState { + uint64_t bytes_written = 0; + }; + void DidWrite(WriteCallback callback, + WriteState* state, + base::File::Error result, + int64_t bytes, + bool complete); + void DidTruncate(TruncateCallback callback, base::File::Error result); + + const std::unique_ptr<FileSystemOperationRunner> operation_runner_; + const base::WeakPtr<BlobStorageContext> blob_context_; + const FileSystemURL url_; +}; + +} // namespace storage + +#endif // STORAGE_BROWSER_FILEAPI_FILE_WRITER_IMPL_H_ diff --git a/chromium/storage/browser/fileapi/file_writer_impl_unittest.cc b/chromium/storage/browser/fileapi/file_writer_impl_unittest.cc new file mode 100644 index 00000000000..1593c0b38c9 --- /dev/null +++ b/chromium/storage/browser/fileapi/file_writer_impl_unittest.cc @@ -0,0 +1,208 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "storage/browser/fileapi/file_writer_impl.h" + +#include <limits> +#include "base/files/scoped_temp_dir.h" +#include "base/guid.h" +#include "base/test/bind_test_util.h" +#include "base/test/scoped_task_environment.h" +#include "net/base/io_buffer.h" +#include "net/base/net_errors.h" +#include "net/base/test_completion_callback.h" +#include "storage/browser/blob/blob_data_builder.h" +#include "storage/browser/blob/blob_impl.h" +#include "storage/browser/blob/blob_storage_context.h" +#include "storage/browser/fileapi/file_stream_reader.h" +#include "storage/browser/test/async_file_test_helper.h" +#include "storage/browser/test/test_file_system_context.h" +#include "testing/gtest/include/gtest/gtest.h" + +using content::AsyncFileTestHelper; +using content::CreateFileSystemContextForTesting; + +namespace storage { + +class FileWriterImplTest : public testing::Test { + public: + FileWriterImplTest() + : scoped_task_environment_( + base::test::ScopedTaskEnvironment::MainThreadType::IO) {} + + void SetUp() override { + ASSERT_TRUE(dir_.CreateUniqueTempDir()); + file_system_context_ = CreateFileSystemContextForTesting( + /*quota_manager_proxy=*/nullptr, dir_.GetPath()); + + test_url_ = file_system_context_->CreateCrackedFileSystemURL( + GURL("http://example.com"), kFileSystemTypeTest, + base::FilePath::FromUTF8Unsafe("test")); + + ASSERT_EQ(base::File::FILE_OK, AsyncFileTestHelper::CreateFile( + file_system_context_.get(), test_url_)); + + blob_context_ = std::make_unique<BlobStorageContext>(); + + writer_ = std::make_unique<FileWriterImpl>( + test_url_, file_system_context_->CreateFileSystemOperationRunner(), + blob_context_->AsWeakPtr()); + } + + blink::mojom::BlobPtr CreateBlob(const std::string& contents) { + auto builder = + std::make_unique<storage::BlobDataBuilder>(base::GenerateGUID()); + builder->AppendData(contents); + auto handle = blob_context_->AddFinishedBlob(std::move(builder)); + blink::mojom::BlobPtr result; + BlobImpl::Create(std::move(handle), MakeRequest(&result)); + return result; + } + + std::string ReadFile(const FileSystemURL& url) { + std::unique_ptr<FileStreamReader> reader = + file_system_context_->CreateFileStreamReader( + url, 0, std::numeric_limits<int64_t>::max(), base::Time()); + net::TestCompletionCallback callback; + std::string result; + while (true) { + auto buf = base::MakeRefCounted<net::IOBufferWithSize>(4096); + int rv = reader->Read(buf.get(), buf->size(), callback.callback()); + if (rv == net::ERR_IO_PENDING) + rv = callback.WaitForResult(); + EXPECT_GE(rv, 0); + if (rv < 0) + return "(read failure)"; + if (rv == 0) + return result; + result.append(buf->data(), rv); + } + } + + base::File::Error WriteSync(uint64_t position, + blink::mojom::BlobPtr blob, + uint64_t* bytes_written_out) { + base::RunLoop loop; + base::File::Error result_out; + writer_->Write(position, std::move(blob), + base::BindLambdaForTesting( + [&](base::File::Error result, uint64_t bytes_written) { + result_out = result; + *bytes_written_out = bytes_written; + loop.Quit(); + })); + loop.Run(); + return result_out; + } + + base::File::Error TruncateSync(uint64_t length) { + base::RunLoop loop; + base::File::Error result_out; + writer_->Truncate(length, + base::BindLambdaForTesting([&](base::File::Error result) { + result_out = result; + loop.Quit(); + })); + loop.Run(); + return result_out; + } + + protected: + base::test::ScopedTaskEnvironment scoped_task_environment_; + + base::ScopedTempDir dir_; + scoped_refptr<FileSystemContext> file_system_context_; + std::unique_ptr<BlobStorageContext> blob_context_; + + FileSystemURL test_url_; + + std::unique_ptr<FileWriterImpl> writer_; +}; + +TEST_F(FileWriterImplTest, WriteInvalidBlob) { + blink::mojom::BlobPtr blob; + MakeRequest(&blob); + + uint64_t bytes_written; + base::File::Error result = WriteSync(0, std::move(blob), &bytes_written); + EXPECT_EQ(result, base::File::FILE_ERROR_FAILED); + EXPECT_EQ(bytes_written, 0u); + + EXPECT_EQ("", ReadFile(test_url_)); +} + +TEST_F(FileWriterImplTest, WriteValidEmptyBlob) { + uint64_t bytes_written; + base::File::Error result = WriteSync(0, CreateBlob(""), &bytes_written); + EXPECT_EQ(result, base::File::FILE_OK); + EXPECT_EQ(bytes_written, 0u); + + EXPECT_EQ("", ReadFile(test_url_)); +} + +TEST_F(FileWriterImplTest, WriteValidBlob) { + uint64_t bytes_written; + base::File::Error result = + WriteSync(0, CreateBlob("1234567890"), &bytes_written); + EXPECT_EQ(result, base::File::FILE_OK); + EXPECT_EQ(bytes_written, 10u); + + EXPECT_EQ("1234567890", ReadFile(test_url_)); +} + +TEST_F(FileWriterImplTest, WriteWithOffsetInFile) { + uint64_t bytes_written; + base::File::Error result; + + result = WriteSync(0, CreateBlob("1234567890"), &bytes_written); + EXPECT_EQ(result, base::File::FILE_OK); + EXPECT_EQ(bytes_written, 10u); + + result = WriteSync(4, CreateBlob("abc"), &bytes_written); + EXPECT_EQ(result, base::File::FILE_OK); + EXPECT_EQ(bytes_written, 3u); + + EXPECT_EQ("1234abc890", ReadFile(test_url_)); +} + +TEST_F(FileWriterImplTest, WriteWithOffsetPastFile) { + uint64_t bytes_written; + base::File::Error result = WriteSync(4, CreateBlob("abc"), &bytes_written); + EXPECT_EQ(result, base::File::FILE_ERROR_FAILED); + EXPECT_EQ(bytes_written, 0u); + + EXPECT_EQ("", ReadFile(test_url_)); +} + +TEST_F(FileWriterImplTest, TruncateShrink) { + uint64_t bytes_written; + base::File::Error result; + + result = WriteSync(0, CreateBlob("1234567890"), &bytes_written); + EXPECT_EQ(result, base::File::FILE_OK); + EXPECT_EQ(bytes_written, 10u); + + result = TruncateSync(5); + EXPECT_EQ(result, base::File::FILE_OK); + + EXPECT_EQ("12345", ReadFile(test_url_)); +} + +TEST_F(FileWriterImplTest, TruncateGrow) { + uint64_t bytes_written; + base::File::Error result; + + result = WriteSync(0, CreateBlob("abc"), &bytes_written); + EXPECT_EQ(result, base::File::FILE_OK); + EXPECT_EQ(bytes_written, 3u); + + result = TruncateSync(5); + EXPECT_EQ(result, base::File::FILE_OK); + + EXPECT_EQ(std::string("abc\0\0", 5), ReadFile(test_url_)); +} + +// TODO(mek): More tests, particularly for error conditions. + +} // namespace storage diff --git a/chromium/storage/browser/fileapi/isolated_context_unittest.cc b/chromium/storage/browser/fileapi/isolated_context_unittest.cc index ec8eab82cf0..990a67c4cbc 100644 --- a/chromium/storage/browser/fileapi/isolated_context_unittest.cc +++ b/chromium/storage/browser/fileapi/isolated_context_unittest.cc @@ -127,7 +127,7 @@ TEST_F(IsolatedContextTest, RegisterAndRevokeTest) { std::string id2 = isolated_context()->RegisterFileSystemForPath( kFileSystemTypeNativeLocal, std::string(), - base::FilePath(DRIVE FPL("/foo")), NULL); + base::FilePath(DRIVE FPL("/foo")), nullptr); // Make sure the GetDraggedFileInfo returns false for both ones. ASSERT_FALSE(isolated_context()->GetDraggedFileInfo(id2, &toplevels)); @@ -139,11 +139,11 @@ TEST_F(IsolatedContextTest, RegisterAndRevokeTest) { // Try registering three more file systems for the same path as id2. std::string id3 = isolated_context()->RegisterFileSystemForPath( - kFileSystemTypeNativeLocal, std::string(), path, NULL); + kFileSystemTypeNativeLocal, std::string(), path, nullptr); std::string id4 = isolated_context()->RegisterFileSystemForPath( - kFileSystemTypeNativeLocal, std::string(), path, NULL); + kFileSystemTypeNativeLocal, std::string(), path, nullptr); std::string id5 = isolated_context()->RegisterFileSystemForPath( - kFileSystemTypeNativeLocal, std::string(), path, NULL); + kFileSystemTypeNativeLocal, std::string(), path, nullptr); // Remove file system for id4. isolated_context()->AddReference(id4); @@ -283,7 +283,8 @@ TEST_F(IsolatedContextTest, TestWithVirtualRoot) { // that has no corresponding platform directory. base::FilePath virtual_path = isolated_context()->CreateVirtualRootPath(id_); ASSERT_TRUE(isolated_context()->CrackVirtualPath( - virtual_path, &cracked_id, NULL, NULL, &cracked_path, &cracked_option)); + virtual_path, &cracked_id, nullptr, nullptr, &cracked_path, + &cracked_option)); ASSERT_EQ(FPL(""), cracked_path.value()); ASSERT_EQ(id_, cracked_id); @@ -292,7 +293,8 @@ TEST_F(IsolatedContextTest, TestWithVirtualRoot) { virtual_path = isolated_context()->CreateVirtualRootPath( id_).AppendASCII("foo"); ASSERT_FALSE(isolated_context()->CrackVirtualPath( - virtual_path, &cracked_id, NULL, NULL, &cracked_path, &cracked_option)); + virtual_path, &cracked_id, nullptr, nullptr, &cracked_path, + &cracked_option)); } TEST_F(IsolatedContextTest, CanHandleURL) { @@ -353,7 +355,7 @@ TEST_F(IsolatedContextTest, VirtualFileSystemTests) { std::string cracked_inner_id; FileSystemMountOption cracked_option; ASSERT_TRUE(isolated_context()->CrackVirtualPath( - whole_virtual_path, &cracked_id, NULL, &cracked_inner_id, + whole_virtual_path, &cracked_id, nullptr, &cracked_inner_id, &cracked_path, &cracked_option)); ASSERT_EQ(database_fsid, cracked_id); ASSERT_EQ(test_virtual_path, cracked_path); diff --git a/chromium/storage/browser/fileapi/isolated_file_system_backend.cc b/chromium/storage/browser/fileapi/isolated_file_system_backend.cc index 84c7665f704..13eb8a3c4b7 100644 --- a/chromium/storage/browser/fileapi/isolated_file_system_backend.cc +++ b/chromium/storage/browser/fileapi/isolated_file_system_backend.cc @@ -82,12 +82,12 @@ AsyncFileUtil* IsolatedFileSystemBackend::GetAsyncFileUtil( default: NOTREACHED(); } - return NULL; + return nullptr; } WatcherManager* IsolatedFileSystemBackend::GetWatcherManager( FileSystemType type) { - return NULL; + return nullptr; } CopyOrMoveFileValidatorFactory* @@ -95,7 +95,7 @@ IsolatedFileSystemBackend::GetCopyOrMoveFileValidatorFactory( FileSystemType type, base::File::Error* error_code) { DCHECK(error_code); *error_code = base::File::FILE_OK; - return NULL; + return nullptr; } FileSystemOperation* IsolatedFileSystemBackend::CreateFileSystemOperation( @@ -143,22 +143,22 @@ IsolatedFileSystemBackend::CreateFileStreamWriter( FileSystemQuotaUtil* IsolatedFileSystemBackend::GetQuotaUtil() { // No quota support. - return NULL; + return nullptr; } const UpdateObserverList* IsolatedFileSystemBackend::GetUpdateObservers( FileSystemType type) const { - return NULL; + return nullptr; } const ChangeObserverList* IsolatedFileSystemBackend::GetChangeObservers( FileSystemType type) const { - return NULL; + return nullptr; } const AccessObserverList* IsolatedFileSystemBackend::GetAccessObservers( FileSystemType type) const { - return NULL; + return nullptr; } } // namespace storage diff --git a/chromium/storage/browser/fileapi/local_file_stream_reader.cc b/chromium/storage/browser/fileapi/local_file_stream_reader.cc index f467be6cc52..c5acdaf2215 100644 --- a/chromium/storage/browser/fileapi/local_file_stream_reader.cc +++ b/chromium/storage/browser/fileapi/local_file_stream_reader.cc @@ -6,6 +6,8 @@ #include <stdint.h> +#include <utility> + #include "base/files/file_util.h" #include "base/location.h" #include "base/logging.h" @@ -61,24 +63,26 @@ FileStreamReader* FileStreamReader::CreateForLocalFile( LocalFileStreamReader::~LocalFileStreamReader() = default; -int LocalFileStreamReader::Read(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) { +int LocalFileStreamReader::Read(net::IOBuffer* buf, + int buf_len, + net::CompletionOnceCallback callback) { DCHECK(!has_pending_open_); + if (stream_impl_) - return stream_impl_->Read(buf, buf_len, callback); - return Open(base::Bind(&LocalFileStreamReader::DidOpenForRead, - weak_factory_.GetWeakPtr(), base::RetainedRef(buf), - buf_len, callback)); + return stream_impl_->Read(buf, buf_len, std::move(callback)); + return Open(base::BindOnce(&LocalFileStreamReader::DidOpenForRead, + weak_factory_.GetWeakPtr(), base::RetainedRef(buf), + buf_len, std::move(callback))); } int64_t LocalFileStreamReader::GetLength( - const net::Int64CompletionCallback& callback) { + net::Int64CompletionOnceCallback callback) { bool posted = base::PostTaskAndReplyWithResult( task_runner_.get(), FROM_HERE, base::BindOnce(&DoGetFileInfo, file_path_), base::BindOnce( &SendGetFileInfoResults, base::BindOnce(&LocalFileStreamReader::DidGetFileInfoForGetLength, - weak_factory_.GetWeakPtr(), callback))); + weak_factory_.GetWeakPtr(), std::move(callback)))); DCHECK(posted); return net::ERR_IO_PENDING; } @@ -95,98 +99,106 @@ LocalFileStreamReader::LocalFileStreamReader( has_pending_open_(false), weak_factory_(this) {} -int LocalFileStreamReader::Open(const net::CompletionCallback& callback) { +int LocalFileStreamReader::Open(net::CompletionOnceCallback callback) { DCHECK(!has_pending_open_); DCHECK(!stream_impl_.get()); has_pending_open_ = true; // Call GetLength first to make it perform last-modified-time verification, // and then call DidVerifyForOpen for do the rest. - return GetLength(base::Bind(&LocalFileStreamReader::DidVerifyForOpen, - weak_factory_.GetWeakPtr(), callback)); + return GetLength(base::BindOnce(&LocalFileStreamReader::DidVerifyForOpen, + weak_factory_.GetWeakPtr(), + std::move(callback))); } void LocalFileStreamReader::DidVerifyForOpen( - const net::CompletionCallback& callback, + net::CompletionOnceCallback callback, int64_t get_length_result) { if (get_length_result < 0) { - callback.Run(static_cast<int>(get_length_result)); + std::move(callback).Run(static_cast<int>(get_length_result)); return; } stream_impl_.reset(new net::FileStream(task_runner_)); + callback_ = std::move(callback); const int result = stream_impl_->Open( file_path_, kOpenFlagsForRead, base::BindOnce(&LocalFileStreamReader::DidOpenFileStream, - weak_factory_.GetWeakPtr(), callback)); + weak_factory_.GetWeakPtr())); if (result != net::ERR_IO_PENDING) - callback.Run(result); + std::move(callback_).Run(result); } void LocalFileStreamReader::DidOpenFileStream( - const net::CompletionCallback& callback, int result) { if (result != net::OK) { - callback.Run(result); + std::move(callback_).Run(result); return; } result = stream_impl_->Seek( initial_offset_, base::BindOnce(&LocalFileStreamReader::DidSeekFileStream, - weak_factory_.GetWeakPtr(), callback)); + weak_factory_.GetWeakPtr())); if (result != net::ERR_IO_PENDING) { - callback.Run(result); + std::move(callback_).Run(result); } } void LocalFileStreamReader::DidSeekFileStream( - const net::CompletionCallback& callback, int64_t seek_result) { if (seek_result < 0) { - callback.Run(static_cast<int>(seek_result)); + std::move(callback_).Run(static_cast<int>(seek_result)); return; } if (seek_result != initial_offset_) { - callback.Run(net::ERR_REQUEST_RANGE_NOT_SATISFIABLE); + std::move(callback_).Run(net::ERR_REQUEST_RANGE_NOT_SATISFIABLE); return; } - callback.Run(net::OK); + std::move(callback_).Run(net::OK); } -void LocalFileStreamReader::DidOpenForRead( - net::IOBuffer* buf, - int buf_len, - const net::CompletionCallback& callback, - int open_result) { +void LocalFileStreamReader::DidOpenForRead(net::IOBuffer* buf, + int buf_len, + net::CompletionOnceCallback callback, + int open_result) { DCHECK(has_pending_open_); has_pending_open_ = false; if (open_result != net::OK) { stream_impl_.reset(); - callback.Run(open_result); + std::move(callback).Run(open_result); return; } DCHECK(stream_impl_.get()); - const int read_result = stream_impl_->Read(buf, buf_len, callback); + + callback_ = std::move(callback); + const int read_result = + stream_impl_->Read(buf, buf_len, + base::BindOnce(&LocalFileStreamReader::OnRead, + weak_factory_.GetWeakPtr())); if (read_result != net::ERR_IO_PENDING) - callback.Run(read_result); + std::move(callback_).Run(read_result); } void LocalFileStreamReader::DidGetFileInfoForGetLength( - const net::Int64CompletionCallback& callback, + net::Int64CompletionOnceCallback callback, base::File::Error error, const base::File::Info& file_info) { if (file_info.is_directory) { - callback.Run(net::ERR_FILE_NOT_FOUND); + std::move(callback).Run(net::ERR_FILE_NOT_FOUND); return; } if (error != base::File::FILE_OK) { - callback.Run(net::FileErrorToNetError(error)); + std::move(callback).Run(net::FileErrorToNetError(error)); return; } if (!VerifySnapshotTime(expected_modification_time_, file_info)) { - callback.Run(net::ERR_UPLOAD_FILE_CHANGED); + std::move(callback).Run(net::ERR_UPLOAD_FILE_CHANGED); return; } - callback.Run(file_info.size); + std::move(callback).Run(file_info.size); +} + +void LocalFileStreamReader::OnRead(int read_result) { + std::move(callback_).Run(read_result); } } // namespace storage diff --git a/chromium/storage/browser/fileapi/local_file_stream_reader.h b/chromium/storage/browser/fileapi/local_file_stream_reader.h index 1cc8292a0dd..7705d1250c9 100644 --- a/chromium/storage/browser/fileapi/local_file_stream_reader.h +++ b/chromium/storage/browser/fileapi/local_file_stream_reader.h @@ -14,6 +14,7 @@ #include "base/files/file_path.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" +#include "net/base/completion_once_callback.h" #include "storage/browser/fileapi/file_stream_reader.h" #include "storage/browser/storage_browser_export.h" @@ -40,8 +41,8 @@ class STORAGE_EXPORT LocalFileStreamReader : public FileStreamReader { // FileStreamReader overrides. int Read(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) override; - int64_t GetLength(const net::Int64CompletionCallback& callback) override; + net::CompletionOnceCallback callback) override; + int64_t GetLength(net::Int64CompletionOnceCallback callback) override; private: friend class FileStreamReader; @@ -51,24 +52,24 @@ class STORAGE_EXPORT LocalFileStreamReader : public FileStreamReader { const base::FilePath& file_path, int64_t initial_offset, const base::Time& expected_modification_time); - int Open(const net::CompletionCallback& callback); + int Open(net::CompletionOnceCallback callback); // Callbacks that are chained from Open for Read. - void DidVerifyForOpen(const net::CompletionCallback& callback, + void DidVerifyForOpen(net::CompletionOnceCallback callback, int64_t get_length_result); - void DidOpenFileStream(const net::CompletionCallback& callback, - int result); - void DidSeekFileStream(const net::CompletionCallback& callback, - int64_t seek_result); + void DidOpenFileStream(int result); + void DidSeekFileStream(int64_t seek_result); void DidOpenForRead(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback, + net::CompletionOnceCallback callback, int open_result); + void OnRead(int read_result); - void DidGetFileInfoForGetLength(const net::Int64CompletionCallback& callback, + void DidGetFileInfoForGetLength(net::Int64CompletionOnceCallback callback, base::File::Error error, const base::File::Info& file_info); + net::CompletionOnceCallback callback_; scoped_refptr<base::TaskRunner> task_runner_; std::unique_ptr<net::FileStream> stream_impl_; const base::FilePath file_path_; diff --git a/chromium/storage/browser/fileapi/local_file_stream_reader_unittest.cc b/chromium/storage/browser/fileapi/local_file_stream_reader_unittest.cc index 7516d842e12..208a7d72fec 100644 --- a/chromium/storage/browser/fileapi/local_file_stream_reader_unittest.cc +++ b/chromium/storage/browser/fileapi/local_file_stream_reader_unittest.cc @@ -38,8 +38,8 @@ const int kTestDataSize = arraysize(kTestData) - 1; void ReadFromReader(LocalFileStreamReader* reader, std::string* data, size_t size, int* result) { - ASSERT_TRUE(reader != NULL); - ASSERT_TRUE(result != NULL); + ASSERT_TRUE(reader != nullptr); + ASSERT_TRUE(result != nullptr); *result = net::OK; net::TestCompletionCallback callback; size_t total_bytes_read = 0; @@ -186,7 +186,7 @@ TEST_F(LocalFileStreamReaderTest, GetLengthAfterModified) { result = callback.WaitForResult(); ASSERT_EQ(net::ERR_UPLOAD_FILE_CHANGED, result); - // With NULL expected modification time this should work. + // With nullptr expected modification time this should work. reader.reset(CreateFileReader(test_path(), 0, base::Time())); result = reader->GetLength(callback.callback()); if (result == net::ERR_IO_PENDING) @@ -246,7 +246,7 @@ TEST_F(LocalFileStreamReaderTest, ReadAfterModified) { EXPECT_EQ(net::OK, result); EXPECT_EQ(kTestData, data); - // And with NULL expected modification time this should work. + // And with nullptr expected modification time this should work. data.clear(); reader.reset(CreateFileReader(test_path(), 0, base::Time())); ReadFromReader(reader.get(), &data, kTestDataSize, &result); diff --git a/chromium/storage/browser/fileapi/local_file_stream_writer.cc b/chromium/storage/browser/fileapi/local_file_stream_writer.cc index 1e8d0f87778..5896bb143e5 100644 --- a/chromium/storage/browser/fileapi/local_file_stream_writer.cc +++ b/chromium/storage/browser/fileapi/local_file_stream_writer.cc @@ -42,34 +42,36 @@ LocalFileStreamWriter::~LocalFileStreamWriter() { // by its Open() method. } -int LocalFileStreamWriter::Write(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) { +int LocalFileStreamWriter::Write(net::IOBuffer* buf, + int buf_len, + net::CompletionOnceCallback callback) { DCHECK(!has_pending_operation_); + DCHECK(write_callback_.is_null()); DCHECK(cancel_callback_.is_null()); has_pending_operation_ = true; + write_callback_ = std::move(callback); if (stream_impl_) { - int result = InitiateWrite(buf, buf_len, callback); + int result = InitiateWrite(buf, buf_len); if (result != net::ERR_IO_PENDING) has_pending_operation_ = false; return result; } - return InitiateOpen( - callback, base::Bind(&LocalFileStreamWriter::ReadyToWrite, - weak_factory_.GetWeakPtr(), base::RetainedRef(buf), - buf_len, callback)); + return InitiateOpen(base::BindOnce(&LocalFileStreamWriter::ReadyToWrite, + weak_factory_.GetWeakPtr(), + base::RetainedRef(buf), buf_len)); } -int LocalFileStreamWriter::Cancel(const net::CompletionCallback& callback) { +int LocalFileStreamWriter::Cancel(net::CompletionOnceCallback callback) { if (!has_pending_operation_) return net::ERR_UNEXPECTED; DCHECK(!callback.is_null()); - cancel_callback_ = callback; + cancel_callback_ = std::move(callback); return net::ERR_IO_PENDING; } -int LocalFileStreamWriter::Flush(const net::CompletionCallback& callback) { +int LocalFileStreamWriter::Flush(net::CompletionOnceCallback callback) { DCHECK(!has_pending_operation_); DCHECK(cancel_callback_.is_null()); @@ -78,7 +80,7 @@ int LocalFileStreamWriter::Flush(const net::CompletionCallback& callback) { return net::OK; has_pending_operation_ = true; - int result = InitiateFlush(callback); + int result = InitiateFlush(std::move(callback)); if (result != net::ERR_IO_PENDING) has_pending_operation_ = false; return result; @@ -95,9 +97,7 @@ LocalFileStreamWriter::LocalFileStreamWriter(base::TaskRunner* task_runner, has_pending_operation_(false), weak_factory_(this) {} -int LocalFileStreamWriter::InitiateOpen( - const net::CompletionCallback& error_callback, - const base::Closure& main_operation) { +int LocalFileStreamWriter::InitiateOpen(base::OnceClosure main_operation) { DCHECK(has_pending_operation_); DCHECK(!stream_impl_.get()); @@ -113,16 +113,14 @@ int LocalFileStreamWriter::InitiateOpen( break; } - return stream_impl_->Open(file_path_, open_flags, - base::BindOnce(&LocalFileStreamWriter::DidOpen, - weak_factory_.GetWeakPtr(), - error_callback, main_operation)); + return stream_impl_->Open( + file_path_, open_flags, + base::BindOnce(&LocalFileStreamWriter::DidOpen, + weak_factory_.GetWeakPtr(), std::move(main_operation))); } -void LocalFileStreamWriter::DidOpen( - const net::CompletionCallback& error_callback, - const base::Closure& main_operation, - int result) { +void LocalFileStreamWriter::DidOpen(base::OnceClosure main_operation, + int result) { DCHECK(has_pending_operation_); DCHECK(stream_impl_.get()); @@ -131,40 +129,36 @@ void LocalFileStreamWriter::DidOpen( if (result != net::OK) { has_pending_operation_ = false; - stream_impl_.reset(NULL); - error_callback.Run(result); + stream_impl_.reset(nullptr); + std::move(write_callback_).Run(result); return; } - InitiateSeek(error_callback, main_operation); + InitiateSeek(std::move(main_operation)); } -void LocalFileStreamWriter::InitiateSeek( - const net::CompletionCallback& error_callback, - const base::Closure& main_operation) { +void LocalFileStreamWriter::InitiateSeek(base::OnceClosure main_operation) { DCHECK(has_pending_operation_); DCHECK(stream_impl_.get()); if (initial_offset_ == 0) { // No need to seek. - main_operation.Run(); + std::move(main_operation).Run(); return; } int result = stream_impl_->Seek( - initial_offset_, base::BindOnce(&LocalFileStreamWriter::DidSeek, - weak_factory_.GetWeakPtr(), - error_callback, main_operation)); + initial_offset_, + base::BindOnce(&LocalFileStreamWriter::DidSeek, + weak_factory_.GetWeakPtr(), std::move(main_operation))); if (result != net::ERR_IO_PENDING) { has_pending_operation_ = false; - error_callback.Run(result); + std::move(write_callback_).Run(result); } } -void LocalFileStreamWriter::DidSeek( - const net::CompletionCallback& error_callback, - const base::Closure& main_operation, - int64_t result) { +void LocalFileStreamWriter::DidSeek(base::OnceClosure main_operation, + int64_t result) { DCHECK(has_pending_operation_); if (CancelIfRequested()) @@ -177,64 +171,58 @@ void LocalFileStreamWriter::DidSeek( if (result < 0) { has_pending_operation_ = false; - error_callback.Run(static_cast<int>(result)); + std::move(write_callback_).Run(static_cast<int>(result)); return; } - main_operation.Run(); + std::move(main_operation).Run(); } -void LocalFileStreamWriter::ReadyToWrite( - net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) { +void LocalFileStreamWriter::ReadyToWrite(net::IOBuffer* buf, int buf_len) { DCHECK(has_pending_operation_); - int result = InitiateWrite(buf, buf_len, callback); + int result = InitiateWrite(buf, buf_len); if (result != net::ERR_IO_PENDING) { has_pending_operation_ = false; - callback.Run(result); + std::move(write_callback_).Run(result); } } -int LocalFileStreamWriter::InitiateWrite( - net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) { +int LocalFileStreamWriter::InitiateWrite(net::IOBuffer* buf, int buf_len) { DCHECK(has_pending_operation_); DCHECK(stream_impl_.get()); - return stream_impl_->Write( - buf, buf_len, - base::BindOnce(&LocalFileStreamWriter::DidWrite, - weak_factory_.GetWeakPtr(), callback)); + return stream_impl_->Write(buf, buf_len, + base::BindOnce(&LocalFileStreamWriter::DidWrite, + weak_factory_.GetWeakPtr())); } -void LocalFileStreamWriter::DidWrite(const net::CompletionCallback& callback, - int result) { +void LocalFileStreamWriter::DidWrite(int result) { DCHECK(has_pending_operation_); if (CancelIfRequested()) return; has_pending_operation_ = false; - callback.Run(result); + std::move(write_callback_).Run(result); } -int LocalFileStreamWriter::InitiateFlush( - const net::CompletionCallback& callback) { +int LocalFileStreamWriter::InitiateFlush(net::CompletionOnceCallback callback) { DCHECK(has_pending_operation_); DCHECK(stream_impl_.get()); - return stream_impl_->Flush(base::BindOnce( - &LocalFileStreamWriter::DidFlush, weak_factory_.GetWeakPtr(), callback)); + return stream_impl_->Flush(base::BindOnce(&LocalFileStreamWriter::DidFlush, + weak_factory_.GetWeakPtr(), + std::move(callback))); } -void LocalFileStreamWriter::DidFlush(const net::CompletionCallback& callback, +void LocalFileStreamWriter::DidFlush(net::CompletionOnceCallback callback, int result) { DCHECK(has_pending_operation_); if (CancelIfRequested()) return; has_pending_operation_ = false; - callback.Run(result); + std::move(callback).Run(result); } bool LocalFileStreamWriter::CancelIfRequested() { @@ -243,10 +231,8 @@ bool LocalFileStreamWriter::CancelIfRequested() { if (cancel_callback_.is_null()) return false; - net::CompletionCallback pending_cancel = cancel_callback_; has_pending_operation_ = false; - cancel_callback_.Reset(); - pending_cancel.Run(net::OK); + std::move(cancel_callback_).Run(net::OK); return true; } diff --git a/chromium/storage/browser/fileapi/local_file_stream_writer.h b/chromium/storage/browser/fileapi/local_file_stream_writer.h index 47821db1e56..38e8b472be2 100644 --- a/chromium/storage/browser/fileapi/local_file_stream_writer.h +++ b/chromium/storage/browser/fileapi/local_file_stream_writer.h @@ -37,9 +37,9 @@ class STORAGE_EXPORT LocalFileStreamWriter : public FileStreamWriter { // FileStreamWriter overrides. int Write(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) override; - int Cancel(const net::CompletionCallback& callback) override; - int Flush(const net::CompletionCallback& callback) override; + net::CompletionOnceCallback callback) override; + int Cancel(net::CompletionOnceCallback callback) override; + int Flush(net::CompletionOnceCallback callback) override; private: friend class content::LocalFileStreamWriterTest; @@ -51,32 +51,24 @@ class STORAGE_EXPORT LocalFileStreamWriter : public FileStreamWriter { // Opens |file_path_| and if it succeeds, proceeds to InitiateSeek(). // If failed, the error code is returned by calling |error_callback|. - int InitiateOpen(const net::CompletionCallback& error_callback, - const base::Closure& main_operation); - void DidOpen(const net::CompletionCallback& error_callback, - const base::Closure& main_operation, - int result); + int InitiateOpen(base::OnceClosure main_operation); + void DidOpen(base::OnceClosure main_operation, int result); // Seeks to |initial_offset_| and proceeds to |main_operation| if it succeeds. // If failed, the error code is returned by calling |error_callback|. - void InitiateSeek(const net::CompletionCallback& error_callback, - const base::Closure& main_operation); - void DidSeek(const net::CompletionCallback& error_callback, - const base::Closure& main_operation, - int64_t result); + void InitiateSeek(base::OnceClosure main_operation); + void DidSeek(base::OnceClosure main_operation, int64_t result); // Passed as the |main_operation| of InitiateOpen() function. - void ReadyToWrite(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback); + void ReadyToWrite(net::IOBuffer* buf, int buf_len); // Writes asynchronously to the file. - int InitiateWrite(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback); - void DidWrite(const net::CompletionCallback& callback, int result); + int InitiateWrite(net::IOBuffer* buf, int buf_len); + void DidWrite(int result); // Flushes asynchronously to the file. - int InitiateFlush(const net::CompletionCallback& callback); - void DidFlush(const net::CompletionCallback& callback, int result); + int InitiateFlush(net::CompletionOnceCallback callback); + void DidFlush(net::CompletionOnceCallback callback, int result); // Stops the in-flight operation and calls |cancel_callback_| if it has been // set by Cancel() for the current operation. @@ -91,7 +83,8 @@ class STORAGE_EXPORT LocalFileStreamWriter : public FileStreamWriter { // Current states of the operation. bool has_pending_operation_; std::unique_ptr<net::FileStream> stream_impl_; - net::CompletionCallback cancel_callback_; + net::CompletionOnceCallback write_callback_; + net::CompletionOnceCallback cancel_callback_; base::WeakPtrFactory<LocalFileStreamWriter> weak_factory_; DISALLOW_COPY_AND_ASSIGN(LocalFileStreamWriter); diff --git a/chromium/storage/browser/fileapi/local_file_stream_writer_unittest.cc b/chromium/storage/browser/fileapi/local_file_stream_writer_unittest.cc index 6a60af411b2..2470e710e14 100644 --- a/chromium/storage/browser/fileapi/local_file_stream_writer_unittest.cc +++ b/chromium/storage/browser/fileapi/local_file_stream_writer_unittest.cc @@ -49,9 +49,11 @@ class LocalFileStreamWriterTest : public testing::Test { int WriteStringToWriter(LocalFileStreamWriter* writer, const std::string& data) { - scoped_refptr<net::StringIOBuffer> buffer(new net::StringIOBuffer(data)); - scoped_refptr<net::DrainableIOBuffer> drainable( - new net::DrainableIOBuffer(buffer.get(), buffer->size())); + scoped_refptr<net::StringIOBuffer> buffer = + base::MakeRefCounted<net::StringIOBuffer>(data); + scoped_refptr<net::DrainableIOBuffer> drainable = + base::MakeRefCounted<net::DrainableIOBuffer>(std::move(buffer), + data.size()); while (drainable->BytesRemaining() > 0) { net::TestCompletionCallback callback; diff --git a/chromium/storage/browser/fileapi/local_file_util_unittest.cc b/chromium/storage/browser/fileapi/local_file_util_unittest.cc index 8a3bc2883d2..b0b58e635b1 100644 --- a/chromium/storage/browser/fileapi/local_file_util_unittest.cc +++ b/chromium/storage/browser/fileapi/local_file_util_unittest.cc @@ -51,11 +51,11 @@ class LocalFileUtilTest : public testing::Test { void SetUp() override { ASSERT_TRUE(data_dir_.CreateUniqueTempDir()); file_system_context_ = - CreateFileSystemContextForTesting(NULL, data_dir_.GetPath()); + CreateFileSystemContextForTesting(nullptr, data_dir_.GetPath()); } void TearDown() override { - file_system_context_ = NULL; + file_system_context_ = nullptr; base::RunLoop().RunUntilIdle(); } diff --git a/chromium/storage/browser/fileapi/native_file_util.cc b/chromium/storage/browser/fileapi/native_file_util.cc index 883281b3af6..1e57925d6db 100644 --- a/chromium/storage/browser/fileapi/native_file_util.cc +++ b/chromium/storage/browser/fileapi/native_file_util.cc @@ -253,15 +253,16 @@ base::File::Error NativeFileUtil::CopyOrMoveFile( base::File::Error error = NativeFileUtil::GetFileInfo(src_path, &info); if (error != base::File::FILE_OK) return error; - if (info.is_directory) + if (info.is_directory && mode != MOVE) return base::File::FILE_ERROR_NOT_A_FILE; + bool src_is_directory = info.is_directory; base::Time last_modified = info.last_modified; error = NativeFileUtil::GetFileInfo(dest_path, &info); if (error != base::File::FILE_OK && error != base::File::FILE_ERROR_NOT_FOUND) return error; - if (info.is_directory) + if (error == base::File::FILE_OK && (info.is_directory || src_is_directory)) return base::File::FILE_ERROR_INVALID_OPERATION; if (error == base::File::FILE_ERROR_NOT_FOUND) { error = NativeFileUtil::GetFileInfo(dest_path.DirName(), &info); diff --git a/chromium/storage/browser/fileapi/native_file_util_unittest.cc b/chromium/storage/browser/fileapi/native_file_util_unittest.cc index 424fbf9ad74..23404fdb539 100644 --- a/chromium/storage/browser/fileapi/native_file_util_unittest.cc +++ b/chromium/storage/browser/fileapi/native_file_util_unittest.cc @@ -326,10 +326,20 @@ TEST_F(NativeFileUtilTest, MoveFile) { Path("nonexists"), Path("file"), FileSystemOperation::OPTION_NONE, move)); - // Source is not a file. - EXPECT_EQ(base::File::FILE_ERROR_NOT_A_FILE, + base::FilePath dir2 = Path("dir2"); + ASSERT_EQ(base::File::FILE_OK, + NativeFileUtil::CreateDirectory(dir2, false, false)); + ASSERT_TRUE(base::DirectoryExists(dir2)); + // Source is a directory, destination is a file. + EXPECT_EQ(base::File::FILE_ERROR_INVALID_OPERATION, + NativeFileUtil::CopyOrMoveFile( + dir, to_file, FileSystemOperation::OPTION_NONE, move)); + + // Source is a directory, destination is a directory. + EXPECT_EQ(base::File::FILE_ERROR_INVALID_OPERATION, NativeFileUtil::CopyOrMoveFile( - dir, Path("file"), FileSystemOperation::OPTION_NONE, move)); + dir, dir2, FileSystemOperation::OPTION_NONE, move)); + ASSERT_EQ(base::File::FILE_OK, NativeFileUtil::EnsureFileExists(from_file, &created)); ASSERT_TRUE(FileExists(from_file)); @@ -353,6 +363,35 @@ TEST_F(NativeFileUtilTest, MoveFile) { FileSystemOperation::OPTION_NONE, move)); } +TEST_F(NativeFileUtilTest, MoveFile_Directory) { + base::FilePath from_directory = Path("fromdirectory"); + base::FilePath to_directory = Path("todirectory"); + base::FilePath from_file = from_directory.AppendASCII("fromfile"); + base::FilePath to_file = to_directory.AppendASCII("fromfile"); + ASSERT_TRUE(base::CreateDirectory(from_directory)); + const NativeFileUtil::CopyOrMoveMode move = NativeFileUtil::MOVE; + bool created = false; + ASSERT_EQ(base::File::FILE_OK, + NativeFileUtil::EnsureFileExists( + from_directory.AppendASCII("fromfile"), &created)); + ASSERT_TRUE(created); + + ASSERT_EQ(base::File::FILE_OK, NativeFileUtil::Truncate(from_file, 1020)); + + EXPECT_TRUE(FileExists(from_file)); + EXPECT_EQ(1020, GetSize(from_file)); + + ASSERT_EQ(base::File::FILE_OK, NativeFileUtil::CopyOrMoveFile( + from_directory, to_directory, + FileSystemOperation::OPTION_NONE, move)); + + EXPECT_FALSE(base::DirectoryExists(from_directory)); + EXPECT_FALSE(FileExists(from_file)); + EXPECT_TRUE(base::DirectoryExists(to_directory)); + EXPECT_TRUE(FileExists(to_file)); + EXPECT_EQ(1020, GetSize(to_file)); +} + TEST_F(NativeFileUtilTest, PreserveLastModified) { base::FilePath from_file = Path("fromfile"); base::FilePath to_file1 = Path("tofile1"); diff --git a/chromium/storage/browser/fileapi/obfuscated_file_util.cc b/chromium/storage/browser/fileapi/obfuscated_file_util.cc index 03f80cf39dc..49f5f3cb844 100644 --- a/chromium/storage/browser/fileapi/obfuscated_file_util.cc +++ b/chromium/storage/browser/fileapi/obfuscated_file_util.cc @@ -874,7 +874,8 @@ bool ObfuscatedFileUtil::DeleteDirectoryForOriginAndType( DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DestroyDirectoryDatabase(origin, type_string); - const base::FilePath origin_path = GetDirectoryForOrigin(origin, false, NULL); + const base::FilePath origin_path = + GetDirectoryForOrigin(origin, false, nullptr); if (origin_path.empty()) return true; @@ -1197,7 +1198,7 @@ SandboxDirectoryDatabase* ObfuscatedFileUtil::GetDirectoryDatabase( std::string key = GetDirectoryDatabaseKey( url.origin(), CallGetTypeStringForURL(url)); if (key.empty()) - return NULL; + return nullptr; auto iter = directories_.find(key); if (iter != directories_.end()) { @@ -1210,7 +1211,7 @@ SandboxDirectoryDatabase* ObfuscatedFileUtil::GetDirectoryDatabase( if (error != base::File::FILE_OK) { LOG(WARNING) << "Failed to get origin+type directory: " << url.DebugString() << " error:" << error; - return NULL; + return nullptr; } MarkUsed(); directories_[key] = diff --git a/chromium/storage/browser/fileapi/obfuscated_file_util.h b/chromium/storage/browser/fileapi/obfuscated_file_util.h index 748d30ea152..ce12c819f14 100644 --- a/chromium/storage/browser/fileapi/obfuscated_file_util.h +++ b/chromium/storage/browser/fileapi/obfuscated_file_util.h @@ -282,7 +282,7 @@ class STORAGE_EXPORT ObfuscatedFileUtil : public FileSystemFileUtil { std::string GetDirectoryDatabaseKey(const GURL& origin, const std::string& type_string); - // This returns NULL if |create| flag is false and a filesystem does not + // This returns nullptr if |create| flag is false and a filesystem does not // exist for the given |url|. // For read operations |create| should be false. SandboxDirectoryDatabase* GetDirectoryDatabase(const FileSystemURL& url, diff --git a/chromium/storage/browser/fileapi/obfuscated_file_util_unittest.cc b/chromium/storage/browser/fileapi/obfuscated_file_util_unittest.cc index fb67043ca92..1fecb7a3b53 100644 --- a/chromium/storage/browser/fileapi/obfuscated_file_util_unittest.cc +++ b/chromium/storage/browser/fileapi/obfuscated_file_util_unittest.cc @@ -192,7 +192,7 @@ class ObfuscatedFileUtilTest : public testing::Test { } void TearDown() override { - quota_manager_ = NULL; + quota_manager_ = nullptr; scoped_task_environment_.RunUntilIdle(); sandbox_file_system_.TearDown(); } @@ -248,7 +248,7 @@ class ObfuscatedFileUtilTest : public testing::Test { storage::SpecialStoragePolicy* storage_policy) { return std::unique_ptr<ObfuscatedFileUtil>( ObfuscatedFileUtil::CreateForTesting(storage_policy, data_dir_path(), - NULL)); + nullptr)); } ObfuscatedFileUtil* ofu() { @@ -300,7 +300,7 @@ class ObfuscatedFileUtilTest : public testing::Test { } bool PathExists(const FileSystemURL& url) { - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); base::File::Info file_info; base::FilePath platform_path; base::File::Error error = ofu()->GetFileInfo( @@ -330,7 +330,7 @@ class ObfuscatedFileUtilTest : public testing::Test { } void CheckFileAndCloseHandle(const FileSystemURL& url, base::File file) { - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); base::FilePath local_path; EXPECT_EQ(base::File::FILE_OK, ofu()->GetLocalFilePath(context.get(), url, &local_path)); @@ -357,7 +357,7 @@ class ObfuscatedFileUtilTest : public testing::Test { base::File::Info file_info1; EXPECT_EQ(length, GetSize(data_path)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->GetFileInfo(context.get(), url, &file_info1, &data_path)); EXPECT_EQ(data_path, local_path); @@ -370,12 +370,12 @@ class ObfuscatedFileUtilTest : public testing::Test { EXPECT_EQ(length, file_info1.size); EXPECT_LE(file_info0.last_modified, file_info1.last_modified); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->Truncate(context.get(), url, length * 2)); EXPECT_EQ(length * 2, GetSize(data_path)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->Truncate(context.get(), url, 0)); EXPECT_EQ(0, GetSize(data_path)); @@ -389,7 +389,7 @@ class ObfuscatedFileUtilTest : public testing::Test { std::set<base::FilePath::StringType>::const_iterator iter; for (iter = files.begin(); iter != files.end(); ++iter) { bool created = true; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); ASSERT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), FileSystemURLAppend(root_url, *iter), @@ -397,7 +397,7 @@ class ObfuscatedFileUtilTest : public testing::Test { ASSERT_FALSE(created); } for (iter = directories.begin(); iter != directories.end(); ++iter) { - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_TRUE(DirectoryExists( FileSystemURLAppend(root_url, *iter))); } @@ -473,7 +473,7 @@ class ObfuscatedFileUtilTest : public testing::Test { std::set<base::FilePath::StringType>::iterator iter; for (iter = files->begin(); iter != files->end(); ++iter) { bool created = false; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); ASSERT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), FileSystemURLAppend(root_url, *iter), @@ -483,7 +483,7 @@ class ObfuscatedFileUtilTest : public testing::Test { for (iter = directories->begin(); iter != directories->end(); ++iter) { bool exclusive = true; bool recursive = false; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->CreateDirectory(context.get(), FileSystemURLAppend(root_url, *iter), @@ -499,7 +499,7 @@ class ObfuscatedFileUtilTest : public testing::Test { std::unique_ptr<FileSystemOperationContext> context; std::vector<filesystem::mojom::DirectoryEntry> entries; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, AsyncFileTestHelper::ReadDirectory( file_system_context(), root_url, &entries)); @@ -523,7 +523,7 @@ class ObfuscatedFileUtilTest : public testing::Test { base::Time last_access_time = base::Time::Now(); base::Time last_modified_time = base::Time::Now(); - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->Touch(context.get(), url, last_access_time, last_modified_time)); @@ -531,7 +531,7 @@ class ObfuscatedFileUtilTest : public testing::Test { EXPECT_TRUE(change_observer()->HasNoChange()); base::FilePath local_path; base::File::Info file_info; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->GetFileInfo( context.get(), url, &file_info, &local_path)); // We compare as time_t here to lower our resolution, to avoid false @@ -539,14 +539,14 @@ class ObfuscatedFileUtilTest : public testing::Test { // representation and back. EXPECT_EQ(file_info.last_modified.ToTimeT(), last_modified_time.ToTimeT()); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); last_modified_time += base::TimeDelta::FromHours(1); last_access_time += base::TimeDelta::FromHours(14); EXPECT_EQ(base::File::FILE_OK, ofu()->Touch(context.get(), url, last_access_time, last_modified_time)); EXPECT_TRUE(change_observer()->HasNoChange()); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->GetFileInfo(context.get(), url, &file_info, &local_path)); EXPECT_EQ(file_info.last_modified.ToTimeT(), last_modified_time.ToTimeT()); @@ -572,7 +572,7 @@ class ObfuscatedFileUtilTest : public testing::Test { std::unique_ptr<FileSystemOperationContext> context; if (overwrite) { - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); bool created = false; EXPECT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), dest_url, &created)); @@ -587,14 +587,14 @@ class ObfuscatedFileUtilTest : public testing::Test { ObfuscatedFileUtil::ComputeFilePathCost(dest_url.path()); if (!overwrite) { // Verify that file creation requires sufficient quota for the path. - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); context->set_allowed_bytes_growth(path_cost + src_file_length - 1); EXPECT_EQ(base::File::FILE_ERROR_NO_SPACE, ofu()->CopyInForeignFile(context.get(), src_file_path, dest_url)); } - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); context->set_allowed_bytes_growth(path_cost + src_file_length); EXPECT_EQ(base::File::FILE_OK, ofu()->CopyInForeignFile(context.get(), @@ -603,7 +603,7 @@ class ObfuscatedFileUtilTest : public testing::Test { EXPECT_TRUE(PathExists(dest_url)); EXPECT_FALSE(DirectoryExists(dest_url)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); base::File::Info file_info; base::FilePath data_path; EXPECT_EQ(base::File::FILE_OK, @@ -618,17 +618,17 @@ class ObfuscatedFileUtilTest : public testing::Test { } void ClearTimestamp(const FileSystemURL& url) { - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->Touch(context.get(), url, base::Time(), base::Time())); EXPECT_EQ(base::Time(), GetModifiedTime(url)); } base::Time GetModifiedTime(const FileSystemURL& url) { - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); base::FilePath data_path; base::File::Info file_info; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->GetFileInfo(context.get(), url, &file_info, &data_path)); EXPECT_TRUE(change_observer()->HasNoChange()); @@ -649,19 +649,19 @@ class ObfuscatedFileUtilTest : public testing::Test { const FileSystemURL dest_file_url( FileSystemURLAppendUTF8(dest_dir_url, "fuga")); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->CreateDirectory(context.get(), src_dir_url, true, true)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->CreateDirectory(context.get(), dest_dir_url, true, true)); bool created = false; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), src_file_url, &created)); if (overwrite) { - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), dest_file_url, &created)); @@ -669,7 +669,7 @@ class ObfuscatedFileUtilTest : public testing::Test { ClearTimestamp(src_dir_url); ClearTimestamp(dest_dir_url); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->CopyOrMoveFile(context.get(), src_file_url, dest_file_url, @@ -684,9 +684,9 @@ class ObfuscatedFileUtilTest : public testing::Test { void MaybeDropDatabasesAliveCaseTestBody() { std::unique_ptr<ObfuscatedFileUtil> file_util = - CreateObfuscatedFileUtil(NULL); + CreateObfuscatedFileUtil(nullptr); file_util->InitOriginDatabase(GURL(), true /*create*/); - ASSERT_TRUE(file_util->origin_database_ != NULL); + ASSERT_TRUE(file_util->origin_database_ != nullptr); // Callback to Drop DB is called while ObfuscatedFileUtilTest is // still alive. @@ -694,7 +694,7 @@ class ObfuscatedFileUtilTest : public testing::Test { file_util->MarkUsed(); scoped_task_environment_.RunUntilIdle(); - ASSERT_TRUE(file_util->origin_database_ == NULL); + ASSERT_TRUE(file_util->origin_database_ == nullptr); } void MaybeDropDatabasesAlreadyDeletedCaseTestBody() { @@ -702,7 +702,7 @@ class ObfuscatedFileUtilTest : public testing::Test { // doesn't cause a crash for use after free. { std::unique_ptr<ObfuscatedFileUtil> file_util = - CreateObfuscatedFileUtil(NULL); + CreateObfuscatedFileUtil(nullptr); file_util->InitOriginDatabase(GURL(), true /*create*/); file_util->db_flush_delay_seconds_ = 0; file_util->MarkUsed(); @@ -722,7 +722,7 @@ class ObfuscatedFileUtilTest : public testing::Test { // Create DirectoryDatabase for isolated origin. SandboxDirectoryDatabase* db = file_util->GetDirectoryDatabase(url, true /* create */); - ASSERT_TRUE(db != NULL); + ASSERT_TRUE(db != nullptr); // Destory it. file_util->DestroyDirectoryDatabase( @@ -740,7 +740,7 @@ class ObfuscatedFileUtilTest : public testing::Test { // Create DirectoryDatabase for isolated origin. SandboxDirectoryDatabase* db = file_util->GetDirectoryDatabase(url, true /* create */); - ASSERT_TRUE(db != NULL); + ASSERT_TRUE(db != nullptr); ASSERT_EQ(1U, file_util->directories_.size()); // Remove isolated. @@ -829,14 +829,14 @@ class ObfuscatedFileUtilTest : public testing::Test { TEST_F(ObfuscatedFileUtilTest, TestCreateAndDeleteFile) { FileSystemURL url = CreateURLFromUTF8("fake/file"); - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); int file_flags = base::File::FLAG_CREATE | base::File::FLAG_WRITE; base::File file = ofu()->CreateOrOpen(context.get(), url, file_flags); EXPECT_FALSE(file.IsValid()); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file.error_details()); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, ofu()->DeleteFile(context.get(), url)); @@ -845,14 +845,14 @@ TEST_F(ObfuscatedFileUtilTest, TestCreateAndDeleteFile) { EXPECT_TRUE(change_observer()->HasNoChange()); // Verify that file creation requires sufficient quota for the path. - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); context->set_allowed_bytes_growth( ObfuscatedFileUtil::ComputeFilePathCost(url.path()) - 1); file = ofu()->CreateOrOpen(context.get(), url, file_flags); EXPECT_FALSE(file.IsValid()); ASSERT_EQ(base::File::FILE_ERROR_NO_SPACE, file.error_details()); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); context->set_allowed_bytes_growth( ObfuscatedFileUtil::ComputeFilePathCost(url.path())); file = ofu()->CreateOrOpen(context.get(), url, file_flags); @@ -862,7 +862,7 @@ TEST_F(ObfuscatedFileUtilTest, TestCreateAndDeleteFile) { CheckFileAndCloseHandle(url, std::move(file)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); base::FilePath local_path; EXPECT_EQ(base::File::FILE_OK, ofu()->GetLocalFilePath(context.get(), url, &local_path)); @@ -870,7 +870,7 @@ TEST_F(ObfuscatedFileUtilTest, TestCreateAndDeleteFile) { // Verify that deleting a file isn't stopped by zero quota, and that it frees // up quote from its path. - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); context->set_allowed_bytes_growth(0); EXPECT_EQ(base::File::FILE_OK, ofu()->DeleteFile(context.get(), url)); EXPECT_EQ(1, change_observer()->get_and_reset_remove_file_count()); @@ -878,7 +878,7 @@ TEST_F(ObfuscatedFileUtilTest, TestCreateAndDeleteFile) { EXPECT_EQ(ObfuscatedFileUtil::ComputeFilePathCost(url.path()), context->allowed_bytes_growth()); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); bool exclusive = true; bool recursive = true; FileSystemURL directory_url = CreateURLFromUTF8( @@ -890,7 +890,7 @@ TEST_F(ObfuscatedFileUtilTest, TestCreateAndDeleteFile) { // The oepration created 3 directories recursively. EXPECT_EQ(3, change_observer()->get_and_reset_create_directory_count()); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); file = ofu()->CreateOrOpen(context.get(), url, file_flags); ASSERT_TRUE(file.IsValid()); ASSERT_TRUE(file.created()); @@ -898,12 +898,12 @@ TEST_F(ObfuscatedFileUtilTest, TestCreateAndDeleteFile) { CheckFileAndCloseHandle(url, std::move(file)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->GetLocalFilePath(context.get(), url, &local_path)); EXPECT_TRUE(base::PathExists(local_path)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->DeleteFile(context.get(), url)); EXPECT_EQ(1, change_observer()->get_and_reset_remove_file_count()); EXPECT_FALSE(base::PathExists(local_path)); @@ -915,29 +915,29 @@ TEST_F(ObfuscatedFileUtilTest, TestCreateAndDeleteFile) { TEST_F(ObfuscatedFileUtilTest, TestTruncate) { bool created = false; FileSystemURL url = CreateURLFromUTF8("file"); - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, ofu()->Truncate(context.get(), url, 4)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); ASSERT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), url, &created)); ASSERT_TRUE(created); EXPECT_EQ(1, change_observer()->get_and_reset_create_file_count()); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); base::FilePath local_path; EXPECT_EQ(base::File::FILE_OK, ofu()->GetLocalFilePath(context.get(), url, &local_path)); EXPECT_EQ(0, GetSize(local_path)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->Truncate(context.get(), url, 10)); EXPECT_EQ(1, change_observer()->get_and_reset_modify_file_count()); EXPECT_EQ(10, GetSize(local_path)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->Truncate(context.get(), url, 1)); EXPECT_EQ(1, GetSize(local_path)); EXPECT_EQ(1, change_observer()->get_and_reset_modify_file_count()); @@ -1007,13 +1007,13 @@ TEST_F(ObfuscatedFileUtilTest, TestQuotaOnTruncation) { TEST_F(ObfuscatedFileUtilTest, TestEnsureFileExists) { FileSystemURL url = CreateURLFromUTF8("fake/file"); bool created = false; - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, ofu()->EnsureFileExists(context.get(), url, &created)); EXPECT_TRUE(change_observer()->HasNoChange()); // Verify that file creation requires sufficient quota for the path. - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); url = CreateURLFromUTF8("test file"); created = false; context->set_allowed_bytes_growth( @@ -1023,7 +1023,7 @@ TEST_F(ObfuscatedFileUtilTest, TestEnsureFileExists) { ASSERT_FALSE(created); EXPECT_TRUE(change_observer()->HasNoChange()); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); context->set_allowed_bytes_growth( ObfuscatedFileUtil::ComputeFilePathCost(url.path())); ASSERT_EQ(base::File::FILE_OK, @@ -1033,7 +1033,7 @@ TEST_F(ObfuscatedFileUtilTest, TestEnsureFileExists) { CheckFileAndCloseHandle(url, base::File()); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); ASSERT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), url, &created)); ASSERT_FALSE(created); @@ -1041,7 +1041,7 @@ TEST_F(ObfuscatedFileUtilTest, TestEnsureFileExists) { // Also test in a subdirectory. url = CreateURLFromUTF8("path/to/file.txt"); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); bool exclusive = true; bool recursive = true; EXPECT_EQ(base::File::FILE_OK, @@ -1050,7 +1050,7 @@ TEST_F(ObfuscatedFileUtilTest, TestEnsureFileExists) { // 2 directories: path/ and path/to. EXPECT_EQ(2, change_observer()->get_and_reset_create_directory_count()); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); ASSERT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), url, &created)); ASSERT_TRUE(created); @@ -1060,7 +1060,7 @@ TEST_F(ObfuscatedFileUtilTest, TestEnsureFileExists) { } TEST_F(ObfuscatedFileUtilTest, TestDirectoryOps) { - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); bool exclusive = false; bool recursive = false; @@ -1068,17 +1068,17 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryOps) { EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, ofu()->CreateDirectory(context.get(), url, exclusive, recursive)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, ofu()->DeleteDirectory(context.get(), url)); FileSystemURL root = CreateURLFromUTF8(std::string()); EXPECT_FALSE(DirectoryExists(url)); EXPECT_FALSE(PathExists(url)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_TRUE(ofu()->IsDirectoryEmpty(context.get(), root)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); exclusive = false; recursive = true; EXPECT_EQ(base::File::FILE_OK, @@ -1088,16 +1088,16 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryOps) { EXPECT_TRUE(DirectoryExists(url)); EXPECT_TRUE(PathExists(url)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_FALSE(ofu()->IsDirectoryEmpty(context.get(), root)); EXPECT_TRUE(DirectoryExists(FileSystemURLDirName(url))); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_FALSE(ofu()->IsDirectoryEmpty(context.get(), FileSystemURLDirName(url))); // Can't remove a non-empty directory. - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_ERROR_NOT_EMPTY, ofu()->DeleteDirectory(context.get(), FileSystemURLDirName(url))); @@ -1112,21 +1112,21 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryOps) { EXPECT_FALSE(file_info.is_symbolic_link); // Same create again should succeed, since exclusive is false. - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->CreateDirectory(context.get(), url, exclusive, recursive)); EXPECT_TRUE(change_observer()->HasNoChange()); exclusive = true; recursive = true; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_ERROR_EXISTS, ofu()->CreateDirectory(context.get(), url, exclusive, recursive)); EXPECT_TRUE(change_observer()->HasNoChange()); // Verify that deleting a directory isn't stopped by zero quota, and that it // frees up quota from its path. - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); context->set_allowed_bytes_growth(0); EXPECT_EQ(base::File::FILE_OK, ofu()->DeleteDirectory(context.get(), url)); EXPECT_EQ(1, change_observer()->get_and_reset_remove_directory_count()); @@ -1138,7 +1138,7 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryOps) { EXPECT_FALSE(DirectoryExists(url)); EXPECT_FALSE(PathExists(url)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_TRUE(ofu()->IsDirectoryEmpty(context.get(), url)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, ofu()->GetFileInfo(context.get(), url, &file_info, &local_path)); @@ -1146,14 +1146,14 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryOps) { // Verify that file creation requires sufficient quota for the path. exclusive = true; recursive = false; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); context->set_allowed_bytes_growth( ObfuscatedFileUtil::ComputeFilePathCost(url.path()) - 1); EXPECT_EQ(base::File::FILE_ERROR_NO_SPACE, ofu()->CreateDirectory(context.get(), url, exclusive, recursive)); EXPECT_TRUE(change_observer()->HasNoChange()); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); context->set_allowed_bytes_growth( ObfuscatedFileUtil::ComputeFilePathCost(url.path())); EXPECT_EQ(base::File::FILE_OK, @@ -1165,7 +1165,7 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryOps) { exclusive = true; recursive = false; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_ERROR_EXISTS, ofu()->CreateDirectory(context.get(), url, exclusive, recursive)); EXPECT_TRUE(change_observer()->HasNoChange()); @@ -1173,7 +1173,7 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryOps) { exclusive = true; recursive = false; url = CreateURLFromUTF8("foo"); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_ERROR_EXISTS, ofu()->CreateDirectory(context.get(), url, exclusive, recursive)); EXPECT_TRUE(change_observer()->HasNoChange()); @@ -1185,7 +1185,7 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryOps) { exclusive = true; recursive = false; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->CreateDirectory(context.get(), url, exclusive, recursive)); EXPECT_EQ(1, change_observer()->get_and_reset_create_directory_count()); @@ -1195,14 +1195,14 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryOps) { exclusive = true; recursive = false; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_ERROR_EXISTS, ofu()->CreateDirectory(context.get(), url, exclusive, recursive)); EXPECT_TRUE(change_observer()->HasNoChange()); } TEST_F(ObfuscatedFileUtilTest, TestReadDirectory) { - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); bool exclusive = true; bool recursive = true; FileSystemURL url = CreateURLFromUTF8("directory/to/use"); @@ -1221,7 +1221,7 @@ TEST_F(ObfuscatedFileUtilTest, TestReadRootWithEmptyString) { TEST_F(ObfuscatedFileUtilTest, TestReadDirectoryOnFile) { FileSystemURL url = CreateURLFromUTF8("file"); - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); bool created = false; ASSERT_EQ(base::File::FILE_OK, @@ -1238,7 +1238,7 @@ TEST_F(ObfuscatedFileUtilTest, TestReadDirectoryOnFile) { TEST_F(ObfuscatedFileUtilTest, TestTouch) { FileSystemURL url = CreateURLFromUTF8("file"); - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); base::Time last_access_time = base::Time::Now(); base::Time last_modified_time = base::Time::Now(); @@ -1249,7 +1249,7 @@ TEST_F(ObfuscatedFileUtilTest, TestTouch) { last_modified_time)); // OK, now create it. - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); bool created = false; ASSERT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), url, &created)); @@ -1257,7 +1257,7 @@ TEST_F(ObfuscatedFileUtilTest, TestTouch) { TestTouchHelper(url, true); // Now test a directory: - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); bool exclusive = true; bool recursive = false; url = CreateURLFromUTF8("dir"); @@ -1268,7 +1268,7 @@ TEST_F(ObfuscatedFileUtilTest, TestTouch) { TEST_F(ObfuscatedFileUtilTest, TestPathQuotas) { FileSystemURL url = CreateURLFromUTF8("fake/file"); - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); url = CreateURLFromUTF8("file name"); context->set_allowed_bytes_growth(5); @@ -1296,7 +1296,7 @@ TEST_F(ObfuscatedFileUtilTest, TestPathQuotas) { path_cost += ObfuscatedFileUtil::ComputeFilePathCost( base::FilePath(*iter)); } - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); context->set_allowed_bytes_growth(1024); EXPECT_EQ(base::File::FILE_OK, ofu()->CreateDirectory(context.get(), url, exclusive, recursive)); @@ -1306,7 +1306,7 @@ TEST_F(ObfuscatedFileUtilTest, TestPathQuotas) { TEST_F(ObfuscatedFileUtilTest, TestCopyOrMoveFileNotFound) { FileSystemURL source_url = CreateURLFromUTF8("path0.txt"); FileSystemURL dest_url = CreateURLFromUTF8("path1.txt"); - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); bool is_copy_not_move = false; EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, @@ -1314,7 +1314,7 @@ TEST_F(ObfuscatedFileUtilTest, TestCopyOrMoveFileNotFound) { FileSystemOperation::OPTION_NONE, is_copy_not_move)); EXPECT_TRUE(change_observer()->HasNoChange()); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); is_copy_not_move = true; EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, ofu()->CopyOrMoveFile(context.get(), source_url, dest_url, @@ -1324,7 +1324,7 @@ TEST_F(ObfuscatedFileUtilTest, TestCopyOrMoveFileNotFound) { source_url = CreateURLFromUTF8("dir/dir/file"); bool exclusive = true; bool recursive = true; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); ASSERT_EQ(base::File::FILE_OK, ofu()->CreateDirectory(context.get(), FileSystemURLDirName(source_url), @@ -1336,7 +1336,7 @@ TEST_F(ObfuscatedFileUtilTest, TestCopyOrMoveFileNotFound) { FileSystemOperation::OPTION_NONE, is_copy_not_move)); EXPECT_TRUE(change_observer()->HasNoChange()); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); is_copy_not_move = true; EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, ofu()->CopyOrMoveFile(context.get(), source_url, dest_url, @@ -1360,45 +1360,45 @@ TEST_F(ObfuscatedFileUtilTest, TestCopyOrMoveFileSuccess) { test_case.dest_path); SCOPED_TRACE(testing::Message() << "\t cause_overwrite " << test_case.cause_overwrite); - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); bool exclusive = false; bool recursive = true; FileSystemURL source_url = CreateURLFromUTF8(test_case.source_path); FileSystemURL dest_url = CreateURLFromUTF8(test_case.dest_path); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); ASSERT_EQ(base::File::FILE_OK, ofu()->CreateDirectory(context.get(), FileSystemURLDirName(source_url), exclusive, recursive)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); ASSERT_EQ(base::File::FILE_OK, ofu()->CreateDirectory(context.get(), FileSystemURLDirName(dest_url), exclusive, recursive)); bool created = false; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); ASSERT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), source_url, &created)); ASSERT_TRUE(created); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); ASSERT_EQ(base::File::FILE_OK, ofu()->Truncate(context.get(), source_url, kSourceLength)); if (test_case.cause_overwrite) { - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); created = false; ASSERT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), dest_url, &created)); ASSERT_TRUE(created); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); ASSERT_EQ(base::File::FILE_OK, ofu()->Truncate(context.get(), dest_url, kDestLength)); } - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->CopyOrMoveFile(context.get(), source_url, dest_url, FileSystemOperation::OPTION_NONE, @@ -1407,7 +1407,7 @@ TEST_F(ObfuscatedFileUtilTest, TestCopyOrMoveFileSuccess) { if (test_case.is_copy_not_move) { base::File::Info file_info; base::FilePath local_path; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->GetFileInfo(context.get(), source_url, &file_info, &local_path)); @@ -1417,7 +1417,7 @@ TEST_F(ObfuscatedFileUtilTest, TestCopyOrMoveFileSuccess) { } else { base::File::Info file_info; base::FilePath local_path; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, ofu()->GetFileInfo(context.get(), source_url, &file_info, &local_path)); @@ -1437,7 +1437,7 @@ TEST_F(ObfuscatedFileUtilTest, TestCopyOrMoveFileSuccess) { TEST_F(ObfuscatedFileUtilTest, TestCopyPathQuotas) { FileSystemURL src_url = CreateURLFromUTF8("src path"); FileSystemURL dest_url = CreateURLFromUTF8("destination path"); - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); bool created = false; ASSERT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), src_url, &created)); @@ -1449,7 +1449,7 @@ TEST_F(ObfuscatedFileUtilTest, TestCopyPathQuotas) { EXPECT_EQ(base::File::FILE_ERROR_NO_SPACE, ofu()->CopyOrMoveFile(context.get(), src_url, dest_url, FileSystemOperation::OPTION_NONE, is_copy)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); context->set_allowed_bytes_growth( ObfuscatedFileUtil::ComputeFilePathCost(dest_url.path())); EXPECT_EQ(base::File::FILE_OK, @@ -1457,7 +1457,7 @@ TEST_F(ObfuscatedFileUtilTest, TestCopyPathQuotas) { FileSystemOperation::OPTION_NONE, is_copy)); // Copy, with overwrite. - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); context->set_allowed_bytes_growth(0); EXPECT_EQ(base::File::FILE_OK, ofu()->CopyOrMoveFile(context.get(), src_url, dest_url, @@ -1467,21 +1467,21 @@ TEST_F(ObfuscatedFileUtilTest, TestCopyPathQuotas) { TEST_F(ObfuscatedFileUtilTest, TestMovePathQuotasWithRename) { FileSystemURL src_url = CreateURLFromUTF8("src path"); FileSystemURL dest_url = CreateURLFromUTF8("destination path"); - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); bool created = false; ASSERT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), src_url, &created)); bool is_copy = false; // Move, rename, no overwrite. - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); context->set_allowed_bytes_growth( ObfuscatedFileUtil::ComputeFilePathCost(dest_url.path()) - ObfuscatedFileUtil::ComputeFilePathCost(src_url.path()) - 1); EXPECT_EQ(base::File::FILE_ERROR_NO_SPACE, ofu()->CopyOrMoveFile(context.get(), src_url, dest_url, FileSystemOperation::OPTION_NONE, is_copy)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); context->set_allowed_bytes_growth( ObfuscatedFileUtil::ComputeFilePathCost(dest_url.path()) - ObfuscatedFileUtil::ComputeFilePathCost(src_url.path())); @@ -1489,12 +1489,12 @@ TEST_F(ObfuscatedFileUtilTest, TestMovePathQuotasWithRename) { ofu()->CopyOrMoveFile(context.get(), src_url, dest_url, FileSystemOperation::OPTION_NONE, is_copy)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); ASSERT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), src_url, &created)); // Move, rename, with overwrite. - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); context->set_allowed_bytes_growth(0); EXPECT_EQ(base::File::FILE_OK, ofu()->CopyOrMoveFile(context.get(), src_url, dest_url, @@ -1503,7 +1503,7 @@ TEST_F(ObfuscatedFileUtilTest, TestMovePathQuotasWithRename) { TEST_F(ObfuscatedFileUtilTest, TestMovePathQuotasWithoutRename) { FileSystemURL src_url = CreateURLFromUTF8("src path"); - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); bool created = false; ASSERT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), src_url, &created)); @@ -1511,7 +1511,7 @@ TEST_F(ObfuscatedFileUtilTest, TestMovePathQuotasWithoutRename) { bool exclusive = true; bool recursive = false; FileSystemURL dir_url = CreateURLFromUTF8("directory path"); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); ASSERT_EQ(base::File::FILE_OK, ofu()->CreateDirectory(context.get(), dir_url, exclusive, recursive)); @@ -1522,7 +1522,7 @@ TEST_F(ObfuscatedFileUtilTest, TestMovePathQuotasWithoutRename) { bool is_copy = false; int64_t allowed_bytes_growth = -1000; // Over quota, this should still work. // Move, no rename, no overwrite. - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); context->set_allowed_bytes_growth(allowed_bytes_growth); EXPECT_EQ(base::File::FILE_OK, ofu()->CopyOrMoveFile(context.get(), src_url, dest_url, @@ -1530,10 +1530,10 @@ TEST_F(ObfuscatedFileUtilTest, TestMovePathQuotasWithoutRename) { EXPECT_EQ(allowed_bytes_growth, context->allowed_bytes_growth()); // Move, no rename, with overwrite. - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); ASSERT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), src_url, &created)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); context->set_allowed_bytes_growth(allowed_bytes_growth); EXPECT_EQ(base::File::FILE_OK, ofu()->CopyOrMoveFile(context.get(), src_url, dest_url, @@ -1550,7 +1550,7 @@ TEST_F(ObfuscatedFileUtilTest, TestCopyInForeignFile) { } TEST_F(ObfuscatedFileUtilTest, TestEnumerator) { - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); FileSystemURL src_url = CreateURLFromUTF8("source dir"); bool exclusive = true; bool recursive = false; @@ -1669,7 +1669,7 @@ TEST_F(ObfuscatedFileUtilTest, TestOriginEnumerator) { } TEST_F(ObfuscatedFileUtilTest, TestRevokeUsageCache) { - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); int64_t expected_quota = 0; @@ -1724,14 +1724,14 @@ TEST_F(ObfuscatedFileUtilTest, TestInconsistency) { bool created = false; // Create a non-empty file. - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), kPath1, &created)); EXPECT_TRUE(created); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->Truncate(context.get(), kPath1, 10)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->GetFileInfo( context.get(), kPath1, &file_info, &data_path)); @@ -1742,18 +1742,18 @@ TEST_F(ObfuscatedFileUtilTest, TestInconsistency) { // Try to get file info of broken file. EXPECT_FALSE(PathExists(kPath1)); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), kPath1, &created)); EXPECT_TRUE(created); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->GetFileInfo( context.get(), kPath1, &file_info, &data_path)); EXPECT_EQ(0, file_info.size); // Make another broken file to |kPath2|. - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), kPath2, &created)); EXPECT_TRUE(created); @@ -1762,7 +1762,7 @@ TEST_F(ObfuscatedFileUtilTest, TestInconsistency) { ofu()->DestroyDirectoryDatabase(origin(), type_string()); // Repair broken |kPath1|. - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, ofu()->Touch(context.get(), kPath1, base::Time::Now(), base::Time::Now())); @@ -1771,14 +1771,14 @@ TEST_F(ObfuscatedFileUtilTest, TestInconsistency) { EXPECT_TRUE(created); // Copy from sound |kPath1| to broken |kPath2|. - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->CopyOrMoveFile(context.get(), kPath1, kPath2, FileSystemOperation::OPTION_NONE, true /* copy */)); ofu()->DestroyDirectoryDatabase(origin(), type_string()); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); base::File file = ofu()->CreateOrOpen(context.get(), kPath1, base::File::FLAG_READ | base::File::FLAG_CREATE); @@ -1800,7 +1800,7 @@ TEST_F(ObfuscatedFileUtilTest, TestIncompleteDirectoryReading) { for (size_t i = 0; i < arraysize(kPath); ++i) { bool created = false; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), kPath[i], &created)); EXPECT_TRUE(created); @@ -1825,7 +1825,7 @@ TEST_F(ObfuscatedFileUtilTest, TestIncompleteDirectoryReading) { } TEST_F(ObfuscatedFileUtilTest, TestDirectoryTimestampForCreation) { - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); const FileSystemURL dir_url = CreateURLFromUTF8("foo_dir"); // Create working directory. @@ -1836,7 +1836,7 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryTimestampForCreation) { FileSystemURL url(FileSystemURLAppendUTF8(dir_url, "EnsureFileExists_file")); bool created = false; ClearTimestamp(dir_url); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), url, &created)); EXPECT_TRUE(created); @@ -1845,7 +1845,7 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryTimestampForCreation) { // non create case. created = true; ClearTimestamp(dir_url); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), url, &created)); EXPECT_FALSE(created); @@ -1853,12 +1853,12 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryTimestampForCreation) { // fail case. url = FileSystemURLAppendUTF8(dir_url, "EnsureFileExists_dir"); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->CreateDirectory(context.get(), url, false, false)); ClearTimestamp(dir_url); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_ERROR_NOT_A_FILE, ofu()->EnsureFileExists(context.get(), url, &created)); EXPECT_EQ(base::Time(), GetModifiedTime(dir_url)); @@ -1866,7 +1866,7 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryTimestampForCreation) { // CreateOrOpen, create case. url = FileSystemURLAppendUTF8(dir_url, "CreateOrOpen_file"); ClearTimestamp(dir_url); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); base::File file = ofu()->CreateOrOpen(context.get(), url, base::File::FLAG_CREATE | base::File::FLAG_WRITE); @@ -1878,7 +1878,7 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryTimestampForCreation) { // open case. ClearTimestamp(dir_url); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); file = ofu()->CreateOrOpen(context.get(), url, base::File::FLAG_OPEN | base::File::FLAG_WRITE); EXPECT_TRUE(file.IsValid()); @@ -1888,7 +1888,7 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryTimestampForCreation) { // fail case ClearTimestamp(dir_url); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); file = ofu()->CreateOrOpen(context.get(), url, base::File::FLAG_CREATE | base::File::FLAG_WRITE); EXPECT_FALSE(file.IsValid()); @@ -1900,7 +1900,7 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryTimestampForCreation) { url = FileSystemURLAppendUTF8(dir_url, "CreateDirectory_dir"); FileSystemURL subdir_url(FileSystemURLAppendUTF8(url, "subdir")); ClearTimestamp(dir_url); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->CreateDirectory(context.get(), subdir_url, true /* exclusive */, true /* recursive */)); @@ -1911,7 +1911,7 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryTimestampForCreation) { subdir_url = FileSystemURLAppendUTF8(url, "subdir2"); ClearTimestamp(dir_url); ClearTimestamp(url); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->CreateDirectory(context.get(), subdir_url, true /* exclusive */, true /* recursive */)); @@ -1921,7 +1921,7 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryTimestampForCreation) { // fail case. url = FileSystemURLAppendUTF8(dir_url, "CreateDirectory_dir"); ClearTimestamp(dir_url); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_ERROR_EXISTS, ofu()->CreateDirectory(context.get(), url, true /* exclusive */, true /* recursive */)); @@ -1931,17 +1931,17 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryTimestampForCreation) { url = FileSystemURLAppendUTF8(dir_url, "CopyInForeignFile_file"); FileSystemURL src_path = FileSystemURLAppendUTF8( dir_url, "CopyInForeignFile_src_file"); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), src_path, &created)); EXPECT_TRUE(created); base::FilePath src_local_path; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->GetLocalFilePath(context.get(), src_path, &src_local_path)); ClearTimestamp(dir_url); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->CopyInForeignFile(context.get(), src_local_path, @@ -1950,7 +1950,7 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryTimestampForCreation) { } TEST_F(ObfuscatedFileUtilTest, TestDirectoryTimestampForDeletion) { - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); const FileSystemURL dir_url = CreateURLFromUTF8("foo_dir"); // Create working directory. @@ -1961,20 +1961,20 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryTimestampForDeletion) { FileSystemURL url = FileSystemURLAppendUTF8( dir_url, "DeleteFile_file"); bool created = false; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), url, &created)); EXPECT_TRUE(created); ClearTimestamp(dir_url); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->DeleteFile(context.get(), url)); EXPECT_NE(base::Time(), GetModifiedTime(dir_url)); // fail case. ClearTimestamp(dir_url); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, ofu()->DeleteFile(context.get(), url)); EXPECT_EQ(base::Time(), GetModifiedTime(dir_url)); @@ -1982,28 +1982,28 @@ TEST_F(ObfuscatedFileUtilTest, TestDirectoryTimestampForDeletion) { // DeleteDirectory, fail case. url = FileSystemURLAppendUTF8(dir_url, "DeleteDirectory_dir"); FileSystemURL file_path(FileSystemURLAppendUTF8(url, "pakeratta")); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->CreateDirectory(context.get(), url, true, true)); created = false; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), file_path, &created)); EXPECT_TRUE(created); ClearTimestamp(dir_url); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_ERROR_NOT_EMPTY, ofu()->DeleteDirectory(context.get(), url)); EXPECT_EQ(base::Time(), GetModifiedTime(dir_url)); // delete case. - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->DeleteFile(context.get(), file_path)); ClearTimestamp(dir_url); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->DeleteDirectory(context.get(), url)); EXPECT_NE(base::Time(), GetModifiedTime(dir_url)); } @@ -2024,40 +2024,40 @@ TEST_F(ObfuscatedFileUtilTest, TestFileEnumeratorTimestamp) { FileSystemURL url1 = FileSystemURLAppendUTF8(dir, "bar"); FileSystemURL url2 = FileSystemURLAppendUTF8(dir, "baz"); - std::unique_ptr<FileSystemOperationContext> context(NewContext(NULL)); + std::unique_ptr<FileSystemOperationContext> context(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->CreateDirectory(context.get(), dir, false, false)); bool created = false; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->EnsureFileExists(context.get(), url1, &created)); EXPECT_TRUE(created); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->CreateDirectory(context.get(), url2, false, false)); base::FilePath file_path; - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->GetLocalFilePath(context.get(), url1, &file_path)); EXPECT_FALSE(file_path.empty()); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); EXPECT_EQ(base::File::FILE_OK, ofu()->Touch(context.get(), url1, base::Time::Now() + base::TimeDelta::FromHours(1), base::Time())); - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); std::unique_ptr<storage::FileSystemFileUtil::AbstractFileEnumerator> file_enum(ofu()->CreateFileEnumerator(context.get(), dir, false)); int count = 0; base::FilePath file_path_each; while (!(file_path_each = file_enum->Next()).empty()) { - context.reset(NewContext(NULL)); + context.reset(NewContext(nullptr)); base::File::Info file_info; base::FilePath file_path; EXPECT_EQ(base::File::FILE_OK, diff --git a/chromium/storage/browser/fileapi/plugin_private_file_system_backend.cc b/chromium/storage/browser/fileapi/plugin_private_file_system_backend.cc index 0b09b98908d..44cc5ccef4c 100644 --- a/chromium/storage/browser/fileapi/plugin_private_file_system_backend.cc +++ b/chromium/storage/browser/fileapi/plugin_private_file_system_backend.cc @@ -106,7 +106,7 @@ PluginPrivateFileSystemBackend::PluginPrivateFileSystemBackend( special_storage_policy, base_path_, env_override, base::Bind(&FileSystemIDToPluginMap::GetPluginIDForURL, base::Owned(plugin_map_)), - std::set<std::string>(), NULL))); + std::set<std::string>(), nullptr))); } PluginPrivateFileSystemBackend::~PluginPrivateFileSystemBackend() { @@ -163,7 +163,7 @@ PluginPrivateFileSystemBackend::GetAsyncFileUtil(FileSystemType type) { WatcherManager* PluginPrivateFileSystemBackend::GetWatcherManager( FileSystemType type) { - return NULL; + return nullptr; } CopyOrMoveFileValidatorFactory* @@ -172,7 +172,7 @@ PluginPrivateFileSystemBackend::GetCopyOrMoveFileValidatorFactory( base::File::Error* error_code) { DCHECK(error_code); *error_code = base::File::FILE_OK; - return NULL; + return nullptr; } FileSystemOperation* PluginPrivateFileSystemBackend::CreateFileSystemOperation( @@ -345,17 +345,17 @@ PluginPrivateFileSystemBackend::CreateQuotaReservationOnFileTaskRunner( const UpdateObserverList* PluginPrivateFileSystemBackend::GetUpdateObservers( FileSystemType type) const { - return NULL; + return nullptr; } const ChangeObserverList* PluginPrivateFileSystemBackend::GetChangeObservers( FileSystemType type) const { - return NULL; + return nullptr; } const AccessObserverList* PluginPrivateFileSystemBackend::GetAccessObservers( FileSystemType type) const { - return NULL; + return nullptr; } ObfuscatedFileUtil* PluginPrivateFileSystemBackend::obfuscated_file_util() { diff --git a/chromium/storage/browser/fileapi/plugin_private_file_system_backend_unittest.cc b/chromium/storage/browser/fileapi/plugin_private_file_system_backend_unittest.cc index f4794ff6097..79dfbec7c05 100644 --- a/chromium/storage/browser/fileapi/plugin_private_file_system_backend_unittest.cc +++ b/chromium/storage/browser/fileapi/plugin_private_file_system_backend_unittest.cc @@ -50,8 +50,8 @@ class PluginPrivateFileSystemBackendTest : public testing::Test { protected: void SetUp() override { ASSERT_TRUE(data_dir_.CreateUniqueTempDir()); - context_ = CreateFileSystemContextForTesting(NULL /* quota_manager_proxy */, - data_dir_.GetPath()); + context_ = CreateFileSystemContextForTesting( + nullptr /* quota_manager_proxy */, data_dir_.GetPath()); } FileSystemURL CreateURL(const GURL& root_url, const std::string& relative) { @@ -222,8 +222,8 @@ TEST_F(PluginPrivateFileSystemBackendTest, DeleteOriginDirectory) { context_.get(), file2, AsyncFileTestHelper::kDontCheckSize)); // Delete data for kOrigin1. - error = backend()->DeleteOriginDataOnFileTaskRunner( - context_.get(), NULL, kOrigin1, kType); + error = backend()->DeleteOriginDataOnFileTaskRunner(context_.get(), nullptr, + kOrigin1, kType); EXPECT_EQ(base::File::FILE_OK, error); // Confirm 'foo' in kOrigin1 is deleted. diff --git a/chromium/storage/browser/fileapi/quota/quota_backend_impl_unittest.cc b/chromium/storage/browser/fileapi/quota/quota_backend_impl_unittest.cc index e4023ecc5ff..9367fe87fa3 100644 --- a/chromium/storage/browser/fileapi/quota/quota_backend_impl_unittest.cc +++ b/chromium/storage/browser/fileapi/quota/quota_backend_impl_unittest.cc @@ -46,7 +46,7 @@ bool DidReserveQuota(bool accepted, class MockQuotaManagerProxy : public storage::QuotaManagerProxy { public: MockQuotaManagerProxy() - : QuotaManagerProxy(NULL, NULL), + : QuotaManagerProxy(nullptr, nullptr), storage_modified_count_(0), usage_(0), quota_(0) {} @@ -101,7 +101,7 @@ class QuotaBackendImplTest : public testing::Test { ASSERT_TRUE(data_dir_.CreateUniqueTempDir()); in_memory_env_ = leveldb_chrome::NewMemEnv("quota"); file_util_.reset(ObfuscatedFileUtil::CreateForTesting( - NULL, data_dir_.GetPath(), in_memory_env_.get())); + nullptr, data_dir_.GetPath(), in_memory_env_.get())); backend_.reset(new QuotaBackendImpl(file_task_runner(), file_util_.get(), &file_system_usage_cache_, quota_manager_proxy_.get())); @@ -109,7 +109,7 @@ class QuotaBackendImplTest : public testing::Test { void TearDown() override { backend_.reset(); - quota_manager_proxy_ = NULL; + quota_manager_proxy_ = nullptr; file_util_.reset(); base::RunLoop().RunUntilIdle(); } @@ -119,7 +119,7 @@ class QuotaBackendImplTest : public testing::Test { storage::FileSystemType type) { ASSERT_TRUE( file_util_->InitOriginDatabase(origin.GetURL(), true /* create */)); - ASSERT_TRUE(file_util_->origin_database_ != NULL); + ASSERT_TRUE(file_util_->origin_database_ != nullptr); std::string type_string = SandboxFileSystemBackendDelegate::GetTypeString(type); diff --git a/chromium/storage/browser/fileapi/quota/quota_reservation_manager_unittest.cc b/chromium/storage/browser/fileapi/quota/quota_reservation_manager_unittest.cc index 06c97e044e9..1e73a3a42a5 100644 --- a/chromium/storage/browser/fileapi/quota/quota_reservation_manager_unittest.cc +++ b/chromium/storage/browser/fileapi/quota/quota_reservation_manager_unittest.cc @@ -255,7 +255,7 @@ TEST_F(QuotaReservationManagerTest, BasicTest) { EXPECT_EQ(3, fake_backend()->on_disk_usage()); EXPECT_EQ(3 + 5, fake_backend()->on_memory_usage()); - reservation = NULL; + reservation = nullptr; EXPECT_EQ(3, fake_backend()->on_memory_usage()); } @@ -289,7 +289,7 @@ TEST_F(QuotaReservationManagerTest, MultipleWriter) { fake_backend()->on_memory_usage()); EXPECT_EQ(kInitialFileSize + 20 + 30 + 40, fake_backend()->on_disk_usage()); - reservation = NULL; + reservation = nullptr; EXPECT_EQ(kInitialFileSize + 20 + 30 + 40, fake_backend()->on_disk_usage()); } @@ -333,10 +333,10 @@ TEST_F(QuotaReservationManagerTest, MultipleClient) { fake_backend()->on_memory_usage()); EXPECT_EQ(kInitialFileSize + 10 + 20, fake_backend()->on_disk_usage()); - reservation1 = NULL; + reservation1 = nullptr; EXPECT_EQ(kInitialFileSize + 10 + 20 + 3, fake_backend()->on_memory_usage()); - reservation2 = NULL; + reservation2 = nullptr; EXPECT_EQ(kInitialFileSize + 10 + 20, fake_backend()->on_memory_usage()); } @@ -357,13 +357,13 @@ TEST_F(QuotaReservationManagerTest, ClientCrash) { reservation1->OnClientCrash(); writer.ClearWithoutUsageReport(); } - reservation1 = NULL; + reservation1 = nullptr; EXPECT_EQ(kInitialFileSize + 10, GetFileSize(file_path())); EXPECT_EQ(kInitialFileSize + 15 + 20, fake_backend()->on_memory_usage()); EXPECT_EQ(kInitialFileSize + 10, fake_backend()->on_disk_usage()); - reservation2 = NULL; + reservation2 = nullptr; EXPECT_EQ(kInitialFileSize + 10, fake_backend()->on_memory_usage()); } diff --git a/chromium/storage/browser/fileapi/sandbox_directory_database.cc b/chromium/storage/browser/fileapi/sandbox_directory_database.cc index b2660c9992c..f9a2482d333 100644 --- a/chromium/storage/browser/fileapi/sandbox_directory_database.cc +++ b/chromium/storage/browser/fileapi/sandbox_directory_database.cc @@ -72,16 +72,17 @@ const base::FilePath::CharType kDirectoryDatabaseName[] = FILE_PATH_LITERAL("Paths"); const char kChildLookupPrefix[] = "CHILD_OF:"; const char kChildLookupSeparator[] = ":"; -const char kLastFileIdKey[] = "LAST_FILE_ID"; -const char kLastIntegerKey[] = "LAST_INTEGER"; -const int64_t kMinimumReportIntervalHours = 1; -const char kInitStatusHistogramLabel[] = "FileSystem.DirectoryDatabaseInit"; -const char kDatabaseRepairHistogramLabel[] = +const char kSandboxDirectoryLastFileIdKey[] = "LAST_FILE_ID"; +const char kSandboxDirectoryLastIntegerKey[] = "LAST_INTEGER"; +const int64_t kSandboxDirectoryMinimumReportIntervalHours = 1; +const char kSandboxDirectoryInitStatusHistogramLabel[] = + "FileSystem.DirectoryDatabaseInit"; +const char kSandboxDirectoryDatabaseRepairHistogramLabel[] = "FileSystem.DirectoryDatabaseRepair"; // These values are recorded in UMA. Changing existing values will invalidate // results for older Chrome releases. Only add new values. -enum InitStatus { +enum class SandboxDirectoryInitStatus { INIT_STATUS_OK = 0, INIT_STATUS_CORRUPTION, INIT_STATUS_IO_ERROR, @@ -91,7 +92,7 @@ enum InitStatus { // These values are recorded in UMA. Changing existing values will invalidate // results for older Chrome releases. Only add new values. -enum RepairResult { +enum class SandboxDirectoryRepairResult { DB_REPAIR_SUCCEEDED = 0, DB_REPAIR_FAILED, DB_REPAIR_MAX @@ -113,11 +114,11 @@ std::string GetChildListingKeyPrefix( } const char* LastFileIdKey() { - return kLastFileIdKey; + return kSandboxDirectoryLastFileIdKey; } const char* LastIntegerKey() { - return kLastIntegerKey; + return kSandboxDirectoryLastIntegerKey; } std::string GetFileLookupKey( @@ -213,7 +214,7 @@ bool DatabaseCheckHelper::ScanDatabase() { // key: "CHILD_OF:<parent_id>:<name>" // value: "<child_id>" ++num_hierarchy_links_in_db_; - } else if (key == kLastFileIdKey) { + } else if (key == kSandboxDirectoryLastFileIdKey) { // key: "LAST_FILE_ID" // value: "<last_file_id>" if (last_file_id_ >= 0 || @@ -222,7 +223,7 @@ bool DatabaseCheckHelper::ScanDatabase() { if (last_file_id_ < 0) return false; - } else if (key == kLastIntegerKey) { + } else if (key == kSandboxDirectoryLastIntegerKey) { // key: "LAST_INTEGER" // value: "<last_integer>" if (last_integer_ >= 0 || @@ -751,12 +752,15 @@ bool SandboxDirectoryDatabase::Init(RecoveryOption recovery_option) { LOG(WARNING) << "Corrupted SandboxDirectoryDatabase detected." << " Attempting to repair."; if (RepairDatabase(path)) { - UMA_HISTOGRAM_ENUMERATION(kDatabaseRepairHistogramLabel, - DB_REPAIR_SUCCEEDED, DB_REPAIR_MAX); + UMA_HISTOGRAM_ENUMERATION( + kSandboxDirectoryDatabaseRepairHistogramLabel, + SandboxDirectoryRepairResult::DB_REPAIR_SUCCEEDED, + SandboxDirectoryRepairResult::DB_REPAIR_MAX); return true; } - UMA_HISTOGRAM_ENUMERATION(kDatabaseRepairHistogramLabel, - DB_REPAIR_FAILED, DB_REPAIR_MAX); + UMA_HISTOGRAM_ENUMERATION(kSandboxDirectoryDatabaseRepairHistogramLabel, + SandboxDirectoryRepairResult::DB_REPAIR_FAILED, + SandboxDirectoryRepairResult::DB_REPAIR_MAX); LOG(WARNING) << "Failed to repair SandboxDirectoryDatabase."; FALLTHROUGH; case DELETE_ON_CORRUPTION: @@ -811,23 +815,29 @@ void SandboxDirectoryDatabase::ReportInitStatus( const leveldb::Status& status) { base::Time now = base::Time::Now(); const base::TimeDelta minimum_interval = - base::TimeDelta::FromHours(kMinimumReportIntervalHours); + base::TimeDelta::FromHours(kSandboxDirectoryMinimumReportIntervalHours); if (last_reported_time_ + minimum_interval >= now) return; last_reported_time_ = now; if (status.ok()) { - UMA_HISTOGRAM_ENUMERATION(kInitStatusHistogramLabel, - INIT_STATUS_OK, INIT_STATUS_MAX); + UMA_HISTOGRAM_ENUMERATION(kSandboxDirectoryInitStatusHistogramLabel, + SandboxDirectoryInitStatus::INIT_STATUS_OK, + SandboxDirectoryInitStatus::INIT_STATUS_MAX); } else if (status.IsCorruption()) { - UMA_HISTOGRAM_ENUMERATION(kInitStatusHistogramLabel, - INIT_STATUS_CORRUPTION, INIT_STATUS_MAX); + UMA_HISTOGRAM_ENUMERATION( + kSandboxDirectoryInitStatusHistogramLabel, + SandboxDirectoryInitStatus::INIT_STATUS_CORRUPTION, + SandboxDirectoryInitStatus::INIT_STATUS_MAX); } else if (status.IsIOError()) { - UMA_HISTOGRAM_ENUMERATION(kInitStatusHistogramLabel, - INIT_STATUS_IO_ERROR, INIT_STATUS_MAX); + UMA_HISTOGRAM_ENUMERATION(kSandboxDirectoryInitStatusHistogramLabel, + SandboxDirectoryInitStatus::INIT_STATUS_IO_ERROR, + SandboxDirectoryInitStatus::INIT_STATUS_MAX); } else { - UMA_HISTOGRAM_ENUMERATION(kInitStatusHistogramLabel, - INIT_STATUS_UNKNOWN_ERROR, INIT_STATUS_MAX); + UMA_HISTOGRAM_ENUMERATION( + kSandboxDirectoryInitStatusHistogramLabel, + SandboxDirectoryInitStatus::INIT_STATUS_UNKNOWN_ERROR, + SandboxDirectoryInitStatus::INIT_STATUS_MAX); } } diff --git a/chromium/storage/browser/fileapi/sandbox_directory_database_unittest.cc b/chromium/storage/browser/fileapi/sandbox_directory_database_unittest.cc index fb294e7afa6..dfaf01ed463 100644 --- a/chromium/storage/browser/fileapi/sandbox_directory_database_unittest.cc +++ b/chromium/storage/browser/fileapi/sandbox_directory_database_unittest.cc @@ -51,7 +51,7 @@ class SandboxDirectoryDatabaseTest : public testing::Test { // Call CloseDatabase() to avoid having multiple database instances for // single directory at once. CloseDatabase(); - db_.reset(new SandboxDirectoryDatabase(path(), NULL)); + db_.reset(new SandboxDirectoryDatabase(path(), nullptr)); } void CloseDatabase() { @@ -105,7 +105,7 @@ class SandboxDirectoryDatabaseTest : public testing::Test { db_.reset(); ASSERT_TRUE(base::DeleteFile(path(), true /* recursive */)); ASSERT_TRUE(base::CreateDirectory(path())); - db_.reset(new SandboxDirectoryDatabase(path(), NULL)); + db_.reset(new SandboxDirectoryDatabase(path(), nullptr)); } bool RepairDatabase() { @@ -524,10 +524,10 @@ TEST_F(SandboxDirectoryDatabaseTest, TestConsistencyCheck_Empty) { TEST_F(SandboxDirectoryDatabaseTest, TestConsistencyCheck_Consistent) { FileId dir_id; - CreateFile(0, FPL("foo"), FPL("hoge"), NULL); + CreateFile(0, FPL("foo"), FPL("hoge"), nullptr); CreateDirectory(0, FPL("bar"), &dir_id); - CreateFile(dir_id, FPL("baz"), FPL("fuga"), NULL); - CreateFile(dir_id, FPL("fizz"), FPL("buzz"), NULL); + CreateFile(dir_id, FPL("baz"), FPL("fuga"), nullptr); + CreateFile(dir_id, FPL("fizz"), FPL("buzz"), nullptr); EXPECT_TRUE(db()->IsFileSystemConsistent()); } @@ -535,17 +535,17 @@ TEST_F(SandboxDirectoryDatabaseTest, TestConsistencyCheck_Consistent) { TEST_F(SandboxDirectoryDatabaseTest, TestConsistencyCheck_BackingMultiEntry) { const base::FilePath::CharType kBackingFileName[] = FPL("the celeb"); - CreateFile(0, FPL("foo"), kBackingFileName, NULL); + CreateFile(0, FPL("foo"), kBackingFileName, nullptr); EXPECT_TRUE(db()->IsFileSystemConsistent()); ASSERT_TRUE(base::DeleteFile(path().Append(kBackingFileName), false)); - CreateFile(0, FPL("bar"), kBackingFileName, NULL); + CreateFile(0, FPL("bar"), kBackingFileName, nullptr); EXPECT_FALSE(db()->IsFileSystemConsistent()); } TEST_F(SandboxDirectoryDatabaseTest, TestConsistencyCheck_FileLost) { const base::FilePath::CharType kBackingFileName[] = FPL("hoge"); - CreateFile(0, FPL("foo"), kBackingFileName, NULL); + CreateFile(0, FPL("foo"), kBackingFileName, nullptr); EXPECT_TRUE(db()->IsFileSystemConsistent()); ASSERT_TRUE(base::DeleteFile(path().Append(kBackingFileName), false)); @@ -553,7 +553,7 @@ TEST_F(SandboxDirectoryDatabaseTest, TestConsistencyCheck_FileLost) { } TEST_F(SandboxDirectoryDatabaseTest, TestConsistencyCheck_OrphanFile) { - CreateFile(0, FPL("foo"), FPL("hoge"), NULL); + CreateFile(0, FPL("foo"), FPL("hoge"), nullptr); EXPECT_TRUE(db()->IsFileSystemConsistent()); @@ -601,7 +601,7 @@ TEST_F(SandboxDirectoryDatabaseTest, TestConsistencyCheck_WreckedEntries) { FileId dir2_id; CreateDirectory(0, FPL("foo"), &dir1_id); CreateDirectory(dir1_id, FPL("bar"), &dir2_id); - CreateFile(dir2_id, FPL("baz"), FPL("fizz/buzz"), NULL); + CreateFile(dir2_id, FPL("baz"), FPL("fizz/buzz"), nullptr); EXPECT_TRUE(db()->IsFileSystemConsistent()); DeleteHierarchyLink(dir2_id); // Delete link from |dir1_id| to |dir2_id|. @@ -612,7 +612,7 @@ TEST_F(SandboxDirectoryDatabaseTest, TestRepairDatabase_Success) { base::FilePath::StringType kFileName = FPL("bar"); FileId file_id_prev; - CreateFile(0, FPL("foo"), FPL("hoge"), NULL); + CreateFile(0, FPL("foo"), FPL("hoge"), nullptr); CreateFile(0, kFileName, FPL("fuga"), &file_id_prev); const base::FilePath kDatabaseDirectory = @@ -633,8 +633,8 @@ TEST_F(SandboxDirectoryDatabaseTest, TestRepairDatabase_Success) { TEST_F(SandboxDirectoryDatabaseTest, TestRepairDatabase_Failure) { base::FilePath::StringType kFileName = FPL("bar"); - CreateFile(0, FPL("foo"), FPL("hoge"), NULL); - CreateFile(0, kFileName, FPL("fuga"), NULL); + CreateFile(0, FPL("foo"), FPL("hoge"), nullptr); + CreateFile(0, kFileName, FPL("fuga"), nullptr); const base::FilePath kDatabaseDirectory = path().Append(kDirectoryDatabaseName); @@ -655,7 +655,7 @@ TEST_F(SandboxDirectoryDatabaseTest, TestRepairDatabase_MissingManifest) { base::FilePath::StringType kFileName = FPL("bar"); FileId file_id_prev; - CreateFile(0, FPL("foo"), FPL("hoge"), NULL); + CreateFile(0, FPL("foo"), FPL("hoge"), nullptr); CreateFile(0, kFileName, FPL("fuga"), &file_id_prev); const base::FilePath kDatabaseDirectory = diff --git a/chromium/storage/browser/fileapi/sandbox_file_stream_writer.cc b/chromium/storage/browser/fileapi/sandbox_file_stream_writer.cc index 44c3fb0d6d2..c1b2fffbb14 100644 --- a/chromium/storage/browser/fileapi/sandbox_file_stream_writer.cc +++ b/chromium/storage/browser/fileapi/sandbox_file_stream_writer.cc @@ -8,6 +8,7 @@ #include <limits> #include <tuple> +#include <utility> #include "base/sequenced_task_runner.h" #include "base/trace_event/trace_event.h" @@ -62,34 +63,34 @@ SandboxFileStreamWriter::SandboxFileStreamWriter( SandboxFileStreamWriter::~SandboxFileStreamWriter() = default; -int SandboxFileStreamWriter::Write( - net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) { +int SandboxFileStreamWriter::Write(net::IOBuffer* buf, + int buf_len, + net::CompletionOnceCallback callback) { + DCHECK(!write_callback_); has_pending_operation_ = true; + write_callback_ = std::move(callback); if (local_file_writer_) - return WriteInternal(buf, buf_len, callback); + return WriteInternal(buf, buf_len); - net::CompletionCallback write_task = base::Bind( + net::CompletionOnceCallback write_task = base::BindOnce( &SandboxFileStreamWriter::DidInitializeForWrite, - weak_factory_.GetWeakPtr(), base::RetainedRef(buf), buf_len, callback); + weak_factory_.GetWeakPtr(), base::RetainedRef(buf), buf_len); file_system_context_->operation_runner()->CreateSnapshotFile( - url_, base::Bind(&SandboxFileStreamWriter::DidCreateSnapshotFile, - weak_factory_.GetWeakPtr(), write_task)); + url_, base::BindOnce(&SandboxFileStreamWriter::DidCreateSnapshotFile, + weak_factory_.GetWeakPtr(), std::move(write_task))); return net::ERR_IO_PENDING; } -int SandboxFileStreamWriter::Cancel(const net::CompletionCallback& callback) { +int SandboxFileStreamWriter::Cancel(net::CompletionOnceCallback callback) { if (!has_pending_operation_) return net::ERR_UNEXPECTED; DCHECK(!callback.is_null()); - cancel_callback_ = callback; + cancel_callback_ = std::move(callback); return net::ERR_IO_PENDING; } -int SandboxFileStreamWriter::WriteInternal( - net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) { +int SandboxFileStreamWriter::WriteInternal(net::IOBuffer* buf, int buf_len) { // allowed_bytes_to_write could be negative if the file size is // greater than the current (possibly new) quota. DCHECK(total_bytes_written_ <= allowed_bytes_to_write_ || @@ -105,15 +106,15 @@ int SandboxFileStreamWriter::WriteInternal( DCHECK(local_file_writer_.get()); const int result = local_file_writer_->Write( buf, buf_len, - base::Bind(&SandboxFileStreamWriter::DidWrite, weak_factory_.GetWeakPtr(), - callback)); + base::BindOnce(&SandboxFileStreamWriter::DidWrite, + weak_factory_.GetWeakPtr())); if (result != net::ERR_IO_PENDING) has_pending_operation_ = false; return result; } void SandboxFileStreamWriter::DidCreateSnapshotFile( - const net::CompletionCallback& callback, + net::CompletionOnceCallback callback, base::File::Error file_error, const base::File::Info& file_info, const base::FilePath& platform_path, @@ -123,12 +124,12 @@ void SandboxFileStreamWriter::DidCreateSnapshotFile( if (CancelIfRequested()) return; if (file_error != base::File::FILE_OK) { - callback.Run(net::FileErrorToNetError(file_error)); + std::move(callback).Run(net::FileErrorToNetError(file_error)); return; } if (file_info.is_directory) { // We should not be writing to a directory. - callback.Run(net::ERR_ACCESS_DENIED); + std::move(callback).Run(net::ERR_ACCESS_DENIED); return; } file_size_ = file_info.size; @@ -151,7 +152,7 @@ void SandboxFileStreamWriter::DidCreateSnapshotFile( // If we don't have the quota manager or the requested filesystem type // does not support quota, we should be able to let it go. allowed_bytes_to_write_ = default_quota_; - callback.Run(net::OK); + std::move(callback).Run(net::OK); return; } @@ -162,11 +163,11 @@ void SandboxFileStreamWriter::DidCreateSnapshotFile( quota_manager_proxy->quota_manager()->GetUsageAndQuota( url_.origin(), FileSystemTypeToQuotaStorageType(url_.type()), base::BindOnce(&SandboxFileStreamWriter::DidGetUsageAndQuota, - weak_factory_.GetWeakPtr(), callback)); + weak_factory_.GetWeakPtr(), std::move(callback))); } void SandboxFileStreamWriter::DidGetUsageAndQuota( - const net::CompletionCallback& callback, + net::CompletionOnceCallback callback, blink::mojom::QuotaStatusCode status, int64_t usage, int64_t quota) { @@ -178,7 +179,7 @@ void SandboxFileStreamWriter::DidGetUsageAndQuota( // crbug.com/349708 TRACE_EVENT0("io", "SandboxFileStreamWriter::DidGetUsageAndQuota FAILED"); - callback.Run(net::ERR_FAILED); + std::move(callback).Run(net::ERR_FAILED); return; } @@ -186,37 +187,34 @@ void SandboxFileStreamWriter::DidGetUsageAndQuota( TRACE_EVENT0("io", "SandboxFileStreamWriter::DidGetUsageAndQuota OK"); allowed_bytes_to_write_ = quota - usage; - callback.Run(net::OK); + std::move(callback).Run(net::OK); } -void SandboxFileStreamWriter::DidInitializeForWrite( - net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback, - int init_status) { +void SandboxFileStreamWriter::DidInitializeForWrite(net::IOBuffer* buf, + int buf_len, + int init_status) { if (CancelIfRequested()) return; if (init_status != net::OK) { has_pending_operation_ = false; - callback.Run(init_status); + std::move(write_callback_).Run(init_status); return; } allowed_bytes_to_write_ = AdjustQuotaForOverlap( allowed_bytes_to_write_, initial_offset_, file_size_); - const int result = WriteInternal(buf, buf_len, callback); + const int result = WriteInternal(buf, buf_len); if (result != net::ERR_IO_PENDING) - callback.Run(result); + std::move(write_callback_).Run(result); } -void SandboxFileStreamWriter::DidWrite( - const net::CompletionCallback& callback, - int write_response) { +void SandboxFileStreamWriter::DidWrite(int write_response) { DCHECK(has_pending_operation_); has_pending_operation_ = false; if (write_response <= 0) { if (CancelIfRequested()) return; - callback.Run(write_response); + std::move(write_callback_).Run(write_response); return; } @@ -231,21 +229,19 @@ void SandboxFileStreamWriter::DidWrite( if (CancelIfRequested()) return; - callback.Run(write_response); + std::move(write_callback_).Run(write_response); } bool SandboxFileStreamWriter::CancelIfRequested() { if (cancel_callback_.is_null()) return false; - net::CompletionCallback pending_cancel = cancel_callback_; has_pending_operation_ = false; - cancel_callback_.Reset(); - pending_cancel.Run(net::OK); + std::move(cancel_callback_).Run(net::OK); return true; } -int SandboxFileStreamWriter::Flush(const net::CompletionCallback& callback) { +int SandboxFileStreamWriter::Flush(net::CompletionOnceCallback callback) { DCHECK(!has_pending_operation_); DCHECK(cancel_callback_.is_null()); @@ -253,7 +249,7 @@ int SandboxFileStreamWriter::Flush(const net::CompletionCallback& callback) { if (!local_file_writer_) return net::OK; - return local_file_writer_->Flush(callback); + return local_file_writer_->Flush(std::move(callback)); } } // namespace storage diff --git a/chromium/storage/browser/fileapi/sandbox_file_stream_writer.h b/chromium/storage/browser/fileapi/sandbox_file_stream_writer.h index 050a0292779..785571e6c9a 100644 --- a/chromium/storage/browser/fileapi/sandbox_file_stream_writer.h +++ b/chromium/storage/browser/fileapi/sandbox_file_stream_writer.h @@ -37,35 +37,32 @@ class STORAGE_EXPORT SandboxFileStreamWriter : public FileStreamWriter { // FileStreamWriter overrides. int Write(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback) override; - int Cancel(const net::CompletionCallback& callback) override; - int Flush(const net::CompletionCallback& callback) override; + net::CompletionOnceCallback callback) override; + int Cancel(net::CompletionOnceCallback callback) override; + int Flush(net::CompletionOnceCallback callback) override; // Used only by tests. void set_default_quota(int64_t quota) { default_quota_ = quota; } private: // Performs quota calculation and calls local_file_writer_->Write(). - int WriteInternal(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback); + int WriteInternal(net::IOBuffer* buf, int buf_len); // Callbacks that are chained for the first write. This eventually calls // WriteInternal. void DidCreateSnapshotFile( - const net::CompletionCallback& callback, + net::CompletionOnceCallback callback, base::File::Error file_error, const base::File::Info& file_info, const base::FilePath& platform_path, scoped_refptr<storage::ShareableFileReference> file_ref); - void DidGetUsageAndQuota(const net::CompletionCallback& callback, + void DidGetUsageAndQuota(net::CompletionOnceCallback callback, blink::mojom::QuotaStatusCode status, int64_t usage, int64_t quota); - void DidInitializeForWrite(net::IOBuffer* buf, int buf_len, - const net::CompletionCallback& callback, - int init_status); + void DidInitializeForWrite(net::IOBuffer* buf, int buf_len, int init_status); - void DidWrite(const net::CompletionCallback& callback, int write_response); + void DidWrite(int write_response); // Stops the in-flight operation, calls |cancel_callback_| and returns true // if there's a pending cancel request. @@ -75,7 +72,8 @@ class STORAGE_EXPORT SandboxFileStreamWriter : public FileStreamWriter { FileSystemURL url_; int64_t initial_offset_; std::unique_ptr<FileStreamWriter> local_file_writer_; - net::CompletionCallback cancel_callback_; + net::CompletionOnceCallback write_callback_; + net::CompletionOnceCallback cancel_callback_; UpdateObserverList observers_; diff --git a/chromium/storage/browser/fileapi/sandbox_file_system_backend.cc b/chromium/storage/browser/fileapi/sandbox_file_system_backend.cc index 9b38f2f7ceb..15b8a7317c7 100644 --- a/chromium/storage/browser/fileapi/sandbox_file_system_backend.cc +++ b/chromium/storage/browser/fileapi/sandbox_file_system_backend.cc @@ -53,12 +53,12 @@ void SandboxFileSystemBackend::Initialize(FileSystemContext* context) { // Set quota observers. delegate_->RegisterQuotaUpdateObserver(storage::kFileSystemTypeTemporary); - delegate_->AddFileAccessObserver( - storage::kFileSystemTypeTemporary, delegate_->quota_observer(), NULL); + delegate_->AddFileAccessObserver(storage::kFileSystemTypeTemporary, + delegate_->quota_observer(), nullptr); delegate_->RegisterQuotaUpdateObserver(storage::kFileSystemTypePersistent); - delegate_->AddFileAccessObserver( - storage::kFileSystemTypePersistent, delegate_->quota_observer(), NULL); + delegate_->AddFileAccessObserver(storage::kFileSystemTypePersistent, + delegate_->quota_observer(), nullptr); } void SandboxFileSystemBackend::ResolveURL(const FileSystemURL& url, @@ -87,7 +87,7 @@ AsyncFileUtil* SandboxFileSystemBackend::GetAsyncFileUtil( WatcherManager* SandboxFileSystemBackend::GetWatcherManager( FileSystemType type) { - return NULL; + return nullptr; } CopyOrMoveFileValidatorFactory* @@ -96,7 +96,7 @@ SandboxFileSystemBackend::GetCopyOrMoveFileValidatorFactory( base::File::Error* error_code) { DCHECK(error_code); *error_code = base::File::FILE_OK; - return NULL; + return nullptr; } FileSystemOperation* SandboxFileSystemBackend::CreateFileSystemOperation( @@ -110,7 +110,7 @@ FileSystemOperation* SandboxFileSystemBackend::CreateFileSystemOperation( std::unique_ptr<FileSystemOperationContext> operation_context = delegate_->CreateFileSystemOperationContext(url, context, error_code); if (!operation_context) - return NULL; + return nullptr; SpecialStoragePolicy* policy = delegate_->special_storage_policy(); if (policy && policy->IsStorageUnlimited(url.origin())) diff --git a/chromium/storage/browser/fileapi/sandbox_file_system_backend_delegate.cc b/chromium/storage/browser/fileapi/sandbox_file_system_backend_delegate.cc index 06fc50fdb10..94c63c390b4 100644 --- a/chromium/storage/browser/fileapi/sandbox_file_system_backend_delegate.cc +++ b/chromium/storage/browser/fileapi/sandbox_file_system_backend_delegate.cc @@ -90,13 +90,13 @@ std::set<std::string> GetKnownTypeStrings() { return known_type_strings; } -class ObfuscatedOriginEnumerator +class SandboxObfuscatedOriginEnumerator : public SandboxFileSystemBackendDelegate::OriginEnumerator { public: - explicit ObfuscatedOriginEnumerator(ObfuscatedFileUtil* file_util) { + explicit SandboxObfuscatedOriginEnumerator(ObfuscatedFileUtil* file_util) { enum_.reset(file_util->CreateOriginEnumerator()); } - ~ObfuscatedOriginEnumerator() override = default; + ~SandboxObfuscatedOriginEnumerator() override = default; GURL Next() override { return enum_->Next(); } @@ -109,12 +109,11 @@ class ObfuscatedOriginEnumerator std::unique_ptr<ObfuscatedFileUtil::AbstractOriginEnumerator> enum_; }; -void OpenFileSystemOnFileTaskRunner( - ObfuscatedFileUtil* file_util, - const GURL& origin_url, - FileSystemType type, - OpenFileSystemMode mode, - base::File::Error* error_ptr) { +void OpenSandboxFileSystemOnFileTaskRunner(ObfuscatedFileUtil* file_util, + const GURL& origin_url, + FileSystemType type, + OpenFileSystemMode mode, + base::File::Error* error_ptr) { DCHECK(error_ptr); const bool create = (mode == OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT); file_util->GetDirectoryForOriginAndType( @@ -233,7 +232,7 @@ SandboxFileSystemBackendDelegate::~SandboxFileSystemBackendDelegate() { SandboxFileSystemBackendDelegate::OriginEnumerator* SandboxFileSystemBackendDelegate::CreateOriginEnumerator() { - return new ObfuscatedOriginEnumerator(obfuscated_file_util()); + return new SandboxObfuscatedOriginEnumerator(obfuscated_file_util()); } base::FilePath @@ -276,8 +275,9 @@ void SandboxFileSystemBackendDelegate::OpenFileSystem( base::File::Error* error_ptr = new base::File::Error; file_task_runner_->PostTaskAndReply( FROM_HERE, - base::BindOnce(&OpenFileSystemOnFileTaskRunner, obfuscated_file_util(), - origin_url, type, mode, base::Unretained(error_ptr)), + base::BindOnce(&OpenSandboxFileSystemOnFileTaskRunner, + obfuscated_file_util(), origin_url, type, mode, + base::Unretained(error_ptr)), base::BindOnce(&DidOpenFileSystem, weak_factory_.GetWeakPtr(), std::move(quota_callback), base::BindOnce(std::move(callback), root_url, name), @@ -479,7 +479,7 @@ const UpdateObserverList* SandboxFileSystemBackendDelegate::GetUpdateObservers( std::map<FileSystemType, UpdateObserverList>::const_iterator iter = update_observers_.find(type); if (iter == update_observers_.end()) - return NULL; + return nullptr; return &iter->second; } @@ -488,7 +488,7 @@ const ChangeObserverList* SandboxFileSystemBackendDelegate::GetChangeObservers( std::map<FileSystemType, ChangeObserverList>::const_iterator iter = change_observers_.find(type); if (iter == change_observers_.end()) - return NULL; + return nullptr; return &iter->second; } @@ -497,7 +497,7 @@ const AccessObserverList* SandboxFileSystemBackendDelegate::GetAccessObservers( std::map<FileSystemType, AccessObserverList>::const_iterator iter = access_observers_.find(type); if (iter == access_observers_.end()) - return NULL; + return nullptr; return &iter->second; } @@ -704,12 +704,9 @@ ObfuscatedFileUtil* ObfuscatedFileUtil::CreateForTesting( storage::SpecialStoragePolicy* special_storage_policy, const base::FilePath& file_system_directory, leveldb::Env* env_override) { - return new ObfuscatedFileUtil(special_storage_policy, - file_system_directory, - env_override, - base::Bind(&GetTypeStringForURL), - GetKnownTypeStrings(), - NULL); + return new ObfuscatedFileUtil(special_storage_policy, file_system_directory, + env_override, base::Bind(&GetTypeStringForURL), + GetKnownTypeStrings(), nullptr); } } // namespace storage diff --git a/chromium/storage/browser/fileapi/sandbox_file_system_backend_delegate_unittest.cc b/chromium/storage/browser/fileapi/sandbox_file_system_backend_delegate_unittest.cc index cf49cd91524..c8dce44cd4f 100644 --- a/chromium/storage/browser/fileapi/sandbox_file_system_backend_delegate_unittest.cc +++ b/chromium/storage/browser/fileapi/sandbox_file_system_backend_delegate_unittest.cc @@ -42,7 +42,7 @@ class SandboxFileSystemBackendDelegateTest : public testing::Test { nullptr, base::ThreadTaskRunnerHandle::Get().get()); delegate_.reset(new storage::SandboxFileSystemBackendDelegate( quota_manager_proxy_.get(), base::ThreadTaskRunnerHandle::Get().get(), - data_dir_.GetPath(), NULL /* special_storage_policy */, + data_dir_.GetPath(), nullptr /* special_storage_policy */, CreateAllowFileAccessOptions(), nullptr /* env_override */)); } diff --git a/chromium/storage/browser/fileapi/sandbox_file_system_backend_unittest.cc b/chromium/storage/browser/fileapi/sandbox_file_system_backend_unittest.cc index 4f0017f5e1d..a5b3df85787 100644 --- a/chromium/storage/browser/fileapi/sandbox_file_system_backend_unittest.cc +++ b/chromium/storage/browser/fileapi/sandbox_file_system_backend_unittest.cc @@ -258,10 +258,9 @@ TEST_F(SandboxFileSystemBackendTest, GetRootPathGetWithoutCreate) { for (size_t i = 0; i < arraysize(kRootPathTestCases); ++i) { SCOPED_TRACE(testing::Message() << "RootPath (create=false) #" << i << " " << kRootPathTestCases[i].expected_path); - EXPECT_FALSE(GetRootPath(GURL(kRootPathTestCases[i].origin_url), - kRootPathTestCases[i].type, - storage::OPEN_FILE_SYSTEM_FAIL_IF_NONEXISTENT, - NULL)); + EXPECT_FALSE(GetRootPath( + GURL(kRootPathTestCases[i].origin_url), kRootPathTestCases[i].type, + storage::OPEN_FILE_SYSTEM_FAIL_IF_NONEXISTENT, nullptr)); } } @@ -272,10 +271,9 @@ TEST_F(SandboxFileSystemBackendTest, GetRootPathInIncognito) { for (size_t i = 0; i < arraysize(kRootPathTestCases); ++i) { SCOPED_TRACE(testing::Message() << "RootPath (incognito) #" << i << " " << kRootPathTestCases[i].expected_path); - EXPECT_FALSE(GetRootPath(GURL(kRootPathTestCases[i].origin_url), - kRootPathTestCases[i].type, - storage::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT, - NULL)); + EXPECT_FALSE(GetRootPath( + GURL(kRootPathTestCases[i].origin_url), kRootPathTestCases[i].type, + storage::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT, nullptr)); } } @@ -287,7 +285,7 @@ TEST_F(SandboxFileSystemBackendTest, GetRootPathFileURI) { EXPECT_FALSE(GetRootPath(GURL(kRootPathFileURITestCases[i].origin_url), kRootPathFileURITestCases[i].type, storage::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT, - NULL)); + nullptr)); } } diff --git a/chromium/storage/browser/fileapi/sandbox_origin_database.cc b/chromium/storage/browser/fileapi/sandbox_origin_database.cc index 19ffab2f1dd..1156c63bfc9 100644 --- a/chromium/storage/browser/fileapi/sandbox_origin_database.cc +++ b/chromium/storage/browser/fileapi/sandbox_origin_database.cc @@ -29,12 +29,14 @@ namespace { const base::FilePath::CharType kOriginDatabaseName[] = FILE_PATH_LITERAL("Origins"); const char kOriginKeyPrefix[] = "ORIGIN:"; -const char kLastPathKey[] = "LAST_PATH"; -const int64_t kMinimumReportIntervalHours = 1; -const char kInitStatusHistogramLabel[] = "FileSystem.OriginDatabaseInit"; -const char kDatabaseRepairHistogramLabel[] = "FileSystem.OriginDatabaseRepair"; - -enum InitStatus { +const char kSandboxOriginLastPathKey[] = "LAST_PATH"; +const int64_t kSandboxOriginMinimumReportIntervalHours = 1; +const char kSandboxOriginInitStatusHistogramLabel[] = + "FileSystem.OriginDatabaseInit"; +const char kSandboxOriginDatabaseRepairHistogramLabel[] = + "FileSystem.OriginDatabaseRepair"; + +enum class InitSandboxOriginStatus { INIT_STATUS_OK = 0, INIT_STATUS_CORRUPTION, INIT_STATUS_IO_ERROR, @@ -42,7 +44,7 @@ enum InitStatus { INIT_STATUS_MAX }; -enum RepairResult { +enum class SandboxOriginRepairResult { DB_REPAIR_SUCCEEDED = 0, DB_REPAIR_FAILED, DB_REPAIR_MAX @@ -54,7 +56,7 @@ std::string OriginToOriginKey(const std::string& origin) { } const char* LastPathKey() { - return kLastPathKey; + return kSandboxOriginLastPathKey; } } // namespace @@ -105,13 +107,16 @@ bool SandboxOriginDatabase::Init(InitOption init_option, LOG(WARNING) << "Attempting to repair SandboxOriginDatabase."; if (RepairDatabase(path)) { - UMA_HISTOGRAM_ENUMERATION(kDatabaseRepairHistogramLabel, - DB_REPAIR_SUCCEEDED, DB_REPAIR_MAX); + UMA_HISTOGRAM_ENUMERATION( + kSandboxOriginDatabaseRepairHistogramLabel, + SandboxOriginRepairResult::DB_REPAIR_SUCCEEDED, + SandboxOriginRepairResult::DB_REPAIR_MAX); LOG(WARNING) << "Repairing SandboxOriginDatabase completed."; return true; } - UMA_HISTOGRAM_ENUMERATION(kDatabaseRepairHistogramLabel, - DB_REPAIR_FAILED, DB_REPAIR_MAX); + UMA_HISTOGRAM_ENUMERATION(kSandboxOriginDatabaseRepairHistogramLabel, + SandboxOriginRepairResult::DB_REPAIR_FAILED, + SandboxOriginRepairResult::DB_REPAIR_MAX); FALLTHROUGH; case DELETE_ON_CORRUPTION: if (!base::DeleteFile(file_system_directory_, true)) @@ -193,23 +198,28 @@ void SandboxOriginDatabase::HandleError(const base::Location& from_here, void SandboxOriginDatabase::ReportInitStatus(const leveldb::Status& status) { base::Time now = base::Time::Now(); base::TimeDelta minimum_interval = - base::TimeDelta::FromHours(kMinimumReportIntervalHours); + base::TimeDelta::FromHours(kSandboxOriginMinimumReportIntervalHours); if (last_reported_time_ + minimum_interval >= now) return; last_reported_time_ = now; if (status.ok()) { - UMA_HISTOGRAM_ENUMERATION(kInitStatusHistogramLabel, - INIT_STATUS_OK, INIT_STATUS_MAX); + UMA_HISTOGRAM_ENUMERATION(kSandboxOriginInitStatusHistogramLabel, + InitSandboxOriginStatus::INIT_STATUS_OK, + InitSandboxOriginStatus::INIT_STATUS_MAX); } else if (status.IsCorruption()) { - UMA_HISTOGRAM_ENUMERATION(kInitStatusHistogramLabel, - INIT_STATUS_CORRUPTION, INIT_STATUS_MAX); + UMA_HISTOGRAM_ENUMERATION(kSandboxOriginInitStatusHistogramLabel, + InitSandboxOriginStatus::INIT_STATUS_CORRUPTION, + InitSandboxOriginStatus::INIT_STATUS_MAX); } else if (status.IsIOError()) { - UMA_HISTOGRAM_ENUMERATION(kInitStatusHistogramLabel, - INIT_STATUS_IO_ERROR, INIT_STATUS_MAX); + UMA_HISTOGRAM_ENUMERATION(kSandboxOriginInitStatusHistogramLabel, + InitSandboxOriginStatus::INIT_STATUS_IO_ERROR, + InitSandboxOriginStatus::INIT_STATUS_MAX); } else { - UMA_HISTOGRAM_ENUMERATION(kInitStatusHistogramLabel, - INIT_STATUS_UNKNOWN_ERROR, INIT_STATUS_MAX); + UMA_HISTOGRAM_ENUMERATION( + kSandboxOriginInitStatusHistogramLabel, + InitSandboxOriginStatus::INIT_STATUS_UNKNOWN_ERROR, + InitSandboxOriginStatus::INIT_STATUS_MAX); } } diff --git a/chromium/storage/browser/fileapi/sandbox_origin_database_unittest.cc b/chromium/storage/browser/fileapi/sandbox_origin_database_unittest.cc index e2675a7696d..d89ebb284c3 100644 --- a/chromium/storage/browser/fileapi/sandbox_origin_database_unittest.cc +++ b/chromium/storage/browser/fileapi/sandbox_origin_database_unittest.cc @@ -42,7 +42,7 @@ TEST(SandboxOriginDatabaseTest, BasicTest) { EXPECT_FALSE(base::PathExists(kFSDir)); EXPECT_TRUE(base::CreateDirectory(kFSDir)); - SandboxOriginDatabase database(kFSDir, NULL); + SandboxOriginDatabase database(kFSDir, nullptr); std::string origin("origin"); EXPECT_FALSE(database.HasOriginPath(origin)); @@ -72,7 +72,7 @@ TEST(SandboxOriginDatabaseTest, TwoPathTest) { EXPECT_FALSE(base::PathExists(kFSDir)); EXPECT_TRUE(base::CreateDirectory(kFSDir)); - SandboxOriginDatabase database(kFSDir, NULL); + SandboxOriginDatabase database(kFSDir, nullptr); std::string origin0("origin0"); std::string origin1("origin1"); @@ -100,7 +100,7 @@ TEST(SandboxOriginDatabaseTest, DropDatabaseTest) { EXPECT_FALSE(base::PathExists(kFSDir)); EXPECT_TRUE(base::CreateDirectory(kFSDir)); - SandboxOriginDatabase database(kFSDir, NULL); + SandboxOriginDatabase database(kFSDir, nullptr); std::string origin("origin"); EXPECT_FALSE(database.HasOriginPath(origin)); @@ -128,7 +128,7 @@ TEST(SandboxOriginDatabaseTest, DeleteOriginTest) { EXPECT_FALSE(base::PathExists(kFSDir)); EXPECT_TRUE(base::CreateDirectory(kFSDir)); - SandboxOriginDatabase database(kFSDir, NULL); + SandboxOriginDatabase database(kFSDir, nullptr); std::string origin("origin"); EXPECT_FALSE(database.HasOriginPath(origin)); @@ -157,7 +157,7 @@ TEST(SandboxOriginDatabaseTest, ListOriginsTest) { std::vector<SandboxOriginDatabase::OriginRecord> origins; - SandboxOriginDatabase database(kFSDir, NULL); + SandboxOriginDatabase database(kFSDir, nullptr); EXPECT_TRUE(database.ListAllOrigins(&origins)); EXPECT_TRUE(origins.empty()); origins.clear(); @@ -214,7 +214,7 @@ TEST(SandboxOriginDatabaseTest, DatabaseRecoveryTest) { }; std::unique_ptr<SandboxOriginDatabase> database( - new SandboxOriginDatabase(kFSDir, NULL)); + new SandboxOriginDatabase(kFSDir, nullptr)); for (size_t i = 0; i < arraysize(kOrigins); ++i) { base::FilePath path; EXPECT_FALSE(database->HasOriginPath(kOrigins[i])); @@ -243,7 +243,7 @@ TEST(SandboxOriginDatabaseTest, DatabaseRecoveryTest) { CorruptDatabase(kDBDir, leveldb::kLogFile, -1, 1); base::FilePath path; - database.reset(new SandboxOriginDatabase(kFSDir, NULL)); + database.reset(new SandboxOriginDatabase(kFSDir, nullptr)); std::vector<SandboxOriginDatabase::OriginRecord> origins_in_db; EXPECT_TRUE(database->ListAllOrigins(&origins_in_db)); @@ -284,7 +284,7 @@ TEST(SandboxOriginDatabaseTest, DatabaseRecoveryForMissingDBFileTest) { base::FilePath path; std::unique_ptr<SandboxOriginDatabase> database( - new SandboxOriginDatabase(kFSDir, NULL)); + new SandboxOriginDatabase(kFSDir, nullptr)); EXPECT_FALSE(database->HasOriginPath(kOrigin)); EXPECT_TRUE(database->GetPathForOrigin(kOrigin, &path)); EXPECT_FALSE(path.empty()); @@ -294,7 +294,7 @@ TEST(SandboxOriginDatabaseTest, DatabaseRecoveryForMissingDBFileTest) { DeleteDatabaseFile(kDBDir, kLevelDBFileTypes[i]); - database.reset(new SandboxOriginDatabase(kFSDir, NULL)); + database.reset(new SandboxOriginDatabase(kFSDir, nullptr)); std::vector<SandboxOriginDatabase::OriginRecord> origins_in_db; EXPECT_TRUE(database->ListAllOrigins(&origins_in_db)); diff --git a/chromium/storage/browser/fileapi/sandbox_prioritized_origin_database_unittest.cc b/chromium/storage/browser/fileapi/sandbox_prioritized_origin_database_unittest.cc index e21f418930e..5e1a106e30c 100644 --- a/chromium/storage/browser/fileapi/sandbox_prioritized_origin_database_unittest.cc +++ b/chromium/storage/browser/fileapi/sandbox_prioritized_origin_database_unittest.cc @@ -22,7 +22,7 @@ TEST(SandboxPrioritizedOriginDatabaseTest, BasicTest) { const std::string kOrigin1("origin1"); const std::string kOrigin2("origin2"); - SandboxPrioritizedOriginDatabase database(dir.GetPath(), NULL); + SandboxPrioritizedOriginDatabase database(dir.GetPath(), nullptr); // Set the kOrigin1 as a parimary origin. EXPECT_TRUE(database.InitializePrimaryOrigin(kOrigin1)); @@ -76,7 +76,7 @@ TEST(SandboxPrioritizedOriginDatabaseTest, SetPrimaryLaterTest) { const std::string kOrigin1("origin1"); const std::string kOrigin2("origin2"); - SandboxPrioritizedOriginDatabase database(dir.GetPath(), NULL); + SandboxPrioritizedOriginDatabase database(dir.GetPath(), nullptr); EXPECT_TRUE(database.GetPrimaryOrigin().empty()); @@ -105,7 +105,7 @@ TEST(SandboxPrioritizedOriginDatabaseTest, LostPrimaryOriginFileTest) { const std::string kOrigin1("origin1"); const std::string kData("foo"); - SandboxPrioritizedOriginDatabase database(dir.GetPath(), NULL); + SandboxPrioritizedOriginDatabase database(dir.GetPath(), nullptr); EXPECT_TRUE(database.GetPrimaryOrigin().empty()); @@ -149,7 +149,7 @@ TEST(SandboxPrioritizedOriginDatabaseTest, MigrationTest) { // Initialize the directory with two origins using the regular // SandboxOriginDatabase. { - SandboxOriginDatabase database_old(dir.GetPath(), NULL); + SandboxOriginDatabase database_old(dir.GetPath(), nullptr); base::FilePath old_db_path = database_old.GetDatabasePath(); EXPECT_FALSE(base::PathExists(old_db_path)); @@ -177,7 +177,7 @@ TEST(SandboxPrioritizedOriginDatabaseTest, MigrationTest) { } // Re-open the directory using sandboxPrioritizedOriginDatabase. - SandboxPrioritizedOriginDatabase database(dir.GetPath(), NULL); + SandboxPrioritizedOriginDatabase database(dir.GetPath(), nullptr); // Set the kOrigin1 as a parimary origin. // (Trying to initialize another origin should fail). diff --git a/chromium/storage/browser/fileapi/task_runner_bound_observer_list.h b/chromium/storage/browser/fileapi/task_runner_bound_observer_list.h index a244b6a42d2..4dad36c4fd9 100644 --- a/chromium/storage/browser/fileapi/task_runner_bound_observer_list.h +++ b/chromium/storage/browser/fileapi/task_runner_bound_observer_list.h @@ -39,7 +39,7 @@ class TaskRunnerBoundObserverList { virtual ~TaskRunnerBoundObserverList() {} // Returns a new observer list with given observer. - // It is valid to give NULL as |runner_to_notify|, and in that case + // It is valid to give nullptr as |runner_to_notify|, and in that case // notifications are dispatched on the current runner. // Note that this is a const method and does NOT change 'this' observer // list but returns a new list. diff --git a/chromium/storage/browser/fileapi/transient_file_util.cc b/chromium/storage/browser/fileapi/transient_file_util.cc index 892776cd2c9..fd0a24fd264 100644 --- a/chromium/storage/browser/fileapi/transient_file_util.cc +++ b/chromium/storage/browser/fileapi/transient_file_util.cc @@ -47,7 +47,7 @@ ScopedFile TransientFileUtil::CreateSnapshotFile( ScopedFile::DELETE_ON_SCOPE_OUT, context->task_runner()); scoped_file.AddScopeOutCallback( - base::BindOnce(&RevokeFileSystem, url.filesystem_id()), NULL); + base::BindOnce(&RevokeFileSystem, url.filesystem_id()), nullptr); return scoped_file; } diff --git a/chromium/storage/browser/fileapi/transient_file_util_unittest.cc b/chromium/storage/browser/fileapi/transient_file_util_unittest.cc index 922419dc42b..0567b32a19f 100644 --- a/chromium/storage/browser/fileapi/transient_file_util_unittest.cc +++ b/chromium/storage/browser/fileapi/transient_file_util_unittest.cc @@ -29,14 +29,14 @@ class TransientFileUtilTest : public testing::Test { void SetUp() override { file_system_context_ = CreateFileSystemContextForTesting( - NULL, base::FilePath(FILE_PATH_LITERAL("dummy"))); + nullptr, base::FilePath(FILE_PATH_LITERAL("dummy"))); transient_file_util_.reset(new storage::TransientFileUtil); ASSERT_TRUE(data_dir_.CreateUniqueTempDir()); } void TearDown() override { - file_system_context_ = NULL; + file_system_context_ = nullptr; base::RunLoop().RunUntilIdle(); } diff --git a/chromium/storage/browser/quota/OWNERS b/chromium/storage/browser/quota/OWNERS index 09c46c2b568..f62a608ec7a 100644 --- a/chromium/storage/browser/quota/OWNERS +++ b/chromium/storage/browser/quota/OWNERS @@ -1,3 +1,7 @@ +jsbell@chromium.org +kinuko@chromium.org +nhiroki@chromium.org +pwnall@chromium.org tzik@chromium.org # TEAM: storage-dev@chromium.org diff --git a/chromium/storage/browser/quota/client_usage_tracker.cc b/chromium/storage/browser/quota/client_usage_tracker.cc index 2db82893fd8..732fe4a045d 100644 --- a/chromium/storage/browser/quota/client_usage_tracker.cc +++ b/chromium/storage/browser/quota/client_usage_tracker.cc @@ -49,9 +49,10 @@ bool OriginSetContainsOrigin(const OriginSetByHost& origins, return itr != origins.end() && base::ContainsKey(itr->second, origin); } -void DidGetGlobalUsageForLimitedGlobalUsage(UsageCallback callback, - int64_t total_global_usage, - int64_t global_unlimited_usage) { +void DidGetGlobalClientUsageForLimitedGlobalClientUsage( + UsageCallback callback, + int64_t total_global_usage, + int64_t global_unlimited_usage) { std::move(callback).Run(total_global_usage - global_unlimited_usage); } @@ -85,8 +86,9 @@ ClientUsageTracker::~ClientUsageTracker() { void ClientUsageTracker::GetGlobalLimitedUsage(UsageCallback callback) { if (!global_usage_retrieved_) { - GetGlobalUsage(base::BindOnce(&DidGetGlobalUsageForLimitedGlobalUsage, - std::move(callback))); + GetGlobalUsage( + base::BindOnce(&DidGetGlobalClientUsageForLimitedGlobalClientUsage, + std::move(callback))); return; } @@ -157,7 +159,7 @@ void ClientUsageTracker::UpdateUsageCache(const GURL& origin, int64_t delta) { delta); // Notify the usage monitor that usage has changed. The storage monitor may - // be NULL during tests. + // be nullptr during tests. if (storage_monitor_) { StorageObserver::Filter filter(type_, origin); storage_monitor_->NotifyUsageChange(filter, delta); diff --git a/chromium/storage/browser/quota/quota_database.cc b/chromium/storage/browser/quota/quota_database.cc index dc8a3c3f4ee..9103809e27c 100644 --- a/chromium/storage/browser/quota/quota_database.cc +++ b/chromium/storage/browser/quota/quota_database.cc @@ -16,7 +16,7 @@ #include "base/macros.h" #include "base/metrics/histogram_macros.h" #include "base/stl_util.h" -#include "sql/connection.h" +#include "sql/database.h" #include "sql/meta_table.h" #include "sql/statement.h" #include "sql/transaction.h" @@ -29,8 +29,8 @@ namespace { // Definitions for database schema. -const int kCurrentVersion = 5; -const int kCompatibleVersion = 2; +const int kQuotaDatabaseCurrentSchemaVersion = 5; +const int kQuotaDatabaseCompatibleVersion = 2; const char kHostQuotaTable[] = "HostQuotaTable"; const char kOriginInfoTable[] = "OriginInfoTable"; @@ -38,31 +38,13 @@ const char kEvictionInfoTable[] = "EvictionInfoTable"; const char kIsOriginTableBootstrapped[] = "IsOriginTableBootstrapped"; bool VerifyValidQuotaConfig(const char* key) { - return (key != NULL && + return (key != nullptr && (!strcmp(key, QuotaDatabase::kDesiredAvailableSpaceKey) || !strcmp(key, QuotaDatabase::kTemporaryQuotaOverrideKey))); } const int kCommitIntervalMs = 30000; -enum OriginType { - // This enum is logged to UMA so only append to it - don't change - // the meaning of the existing values. - OTHER = 0, - NONE = 1, - GOOGLE_DURABLE = 2, - NON_GOOGLE_DURABLE = 3, - GOOGLE_UNLIMITED_EXTENSION = 4, - NON_GOOGLE_UNLIMITED_EXTENSION = 5, - IN_USE = 6, - - MAX_ORIGIN_TYPE -}; - -void HistogramOriginType(const OriginType& entry) { - UMA_HISTOGRAM_ENUMERATION("Quota.LRUOriginTypes", entry, MAX_ORIGIN_TYPE); -} - void LogDaysSinceLastAccess(base::Time this_time, const QuotaDatabase::OriginInfoTableEntry& entry) { base::TimeDelta time_since = this_time - std::max(entry.last_access_time, @@ -164,7 +146,7 @@ QuotaDatabase::~QuotaDatabase() { } } -void QuotaDatabase::CloseConnection() { +void QuotaDatabase::CloseDatabase() { meta_table_.reset(); db_.reset(); } @@ -450,37 +432,29 @@ bool QuotaDatabase::GetLRUOrigin( if (!LazyOpen(false)) return false; - const char* kSql = "SELECT origin FROM OriginInfoTable" - " WHERE type = ?" - " ORDER BY last_access_time ASC"; + static const char kSql[] = + "SELECT origin FROM OriginInfoTable" + " WHERE type = ?" + " ORDER BY last_access_time ASC"; sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt(0, static_cast<int>(type)); while (statement.Step()) { GURL url(statement.ColumnString(0)); - if (base::ContainsKey(exceptions, url)) { - HistogramOriginType(IN_USE); + if (base::ContainsKey(exceptions, url)) + continue; + + if (special_storage_policy && ( + special_storage_policy->IsStorageDurable(url) || + special_storage_policy->IsStorageUnlimited(url))) { continue; } - if (special_storage_policy) { - bool is_google = url.DomainIs("google.com"); - if (special_storage_policy->IsStorageDurable(url)) { - HistogramOriginType(is_google ? GOOGLE_DURABLE : NON_GOOGLE_DURABLE); - continue; - } - if (special_storage_policy->IsStorageUnlimited(url)) { - HistogramOriginType(is_google ? GOOGLE_UNLIMITED_EXTENSION - : NON_GOOGLE_UNLIMITED_EXTENSION); - continue; - } - } - HistogramOriginType(OTHER); + *origin = url; return true; } - HistogramOriginType(NONE); *origin = GURL(); return statement.Succeeded(); } @@ -556,7 +530,7 @@ bool QuotaDatabase::LazyOpen(bool create_if_needed) { return false; } - db_.reset(new sql::Connection); + db_.reset(new sql::Database); meta_table_.reset(new sql::MetaTable); db_->set_histogram_tag("Quota"); @@ -594,19 +568,21 @@ bool QuotaDatabase::EnsureDatabaseVersion() { static const size_t kIndexCount = arraysize(kIndexes); if (!sql::MetaTable::DoesTableExist(db_.get())) return CreateSchema(db_.get(), meta_table_.get(), - kCurrentVersion, kCompatibleVersion, - kTables, kTableCount, + kQuotaDatabaseCurrentSchemaVersion, + kQuotaDatabaseCompatibleVersion, kTables, kTableCount, kIndexes, kIndexCount); - if (!meta_table_->Init(db_.get(), kCurrentVersion, kCompatibleVersion)) + if (!meta_table_->Init(db_.get(), kQuotaDatabaseCurrentSchemaVersion, + kQuotaDatabaseCompatibleVersion)) return false; - if (meta_table_->GetCompatibleVersionNumber() > kCurrentVersion) { + if (meta_table_->GetCompatibleVersionNumber() > + kQuotaDatabaseCurrentSchemaVersion) { LOG(WARNING) << "Quota database is too new."; return false; } - if (meta_table_->GetVersionNumber() < kCurrentVersion) { + if (meta_table_->GetVersionNumber() < kQuotaDatabaseCurrentSchemaVersion) { if (!UpgradeSchema(meta_table_->GetVersionNumber())) return ResetSchema(); } @@ -622,12 +598,14 @@ bool QuotaDatabase::EnsureDatabaseVersion() { } // static -bool QuotaDatabase::CreateSchema( - sql::Connection* database, - sql::MetaTable* meta_table, - int schema_version, int compatible_version, - const TableSchema* tables, size_t tables_size, - const IndexSchema* indexes, size_t indexes_size) { +bool QuotaDatabase::CreateSchema(sql::Database* database, + sql::MetaTable* meta_table, + int schema_version, + int compatible_version, + const TableSchema* tables, + size_t tables_size, + const IndexSchema* indexes, + size_t indexes_size) { // TODO(kinuko): Factor out the common code to create databases. sql::Transaction transaction(database); if (!transaction.Begin()) @@ -674,7 +652,7 @@ bool QuotaDatabase::ResetSchema() { db_.reset(); meta_table_.reset(); - if (!sql::Connection::Delete(db_file_path_)) + if (!sql::Database::Delete(db_file_path_)) return false; // So we can't go recursive. diff --git a/chromium/storage/browser/quota/quota_database.h b/chromium/storage/browser/quota/quota_database.h index d4c6a59be19..529387f4b47 100644 --- a/chromium/storage/browser/quota/quota_database.h +++ b/chromium/storage/browser/quota/quota_database.h @@ -26,7 +26,7 @@ class QuotaDatabaseTest; } namespace sql { -class Connection; +class Database; class MetaTable; } @@ -61,7 +61,7 @@ class STORAGE_EXPORT QuotaDatabase { explicit QuotaDatabase(const base::FilePath& path); ~QuotaDatabase(); - void CloseConnection(); + void CloseDatabase(); // Returns whether the record could be found. bool GetHostQuota(const std::string& host, @@ -183,12 +183,14 @@ class STORAGE_EXPORT QuotaDatabase { blink::mojom::StorageType type, int64_t quota); - static bool CreateSchema( - sql::Connection* database, - sql::MetaTable* meta_table, - int schema_version, int compatible_version, - const TableSchema* tables, size_t tables_size, - const IndexSchema* indexes, size_t indexes_size); + static bool CreateSchema(sql::Database* database, + sql::MetaTable* meta_table, + int schema_version, + int compatible_version, + const TableSchema* tables, + size_t tables_size, + const IndexSchema* indexes, + size_t indexes_size); // |callback| may return false to stop reading data. bool DumpQuotaTable(const QuotaTableCallback& callback); @@ -196,7 +198,7 @@ class STORAGE_EXPORT QuotaDatabase { base::FilePath db_file_path_; - std::unique_ptr<sql::Connection> db_; + std::unique_ptr<sql::Database> db_; std::unique_ptr<sql::MetaTable> meta_table_; bool is_recreating_; bool is_disabled_; diff --git a/chromium/storage/browser/quota/quota_database_unittest.cc b/chromium/storage/browser/quota/quota_database_unittest.cc index 99c3a829934..ff4774df14d 100644 --- a/chromium/storage/browser/quota/quota_database_unittest.cc +++ b/chromium/storage/browser/quota/quota_database_unittest.cc @@ -15,7 +15,7 @@ #include "base/files/scoped_temp_dir.h" #include "base/macros.h" #include "base/message_loop/message_loop.h" -#include "sql/connection.h" +#include "sql/database.h" #include "sql/meta_table.h" #include "sql/statement.h" #include "sql/test/scoped_error_expecter.h" @@ -154,7 +154,7 @@ class QuotaDatabaseTest : public testing::Test { std::set<GURL> exceptions; GURL origin; - EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, NULL, &origin)); + EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, nullptr, &origin)); EXPECT_TRUE(origin.is_empty()); const GURL kOrigin1("http://a/"); @@ -174,7 +174,7 @@ class QuotaDatabaseTest : public testing::Test { EXPECT_TRUE(db.SetOriginLastAccessTime(kOrigin4, kPersistent, base::Time::FromInternalValue(40))); - EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, NULL, &origin)); + EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, nullptr, &origin)); EXPECT_EQ(kOrigin1.spec(), origin.spec()); // Test that unlimited origins are exluded from eviction, but @@ -192,15 +192,15 @@ class QuotaDatabaseTest : public testing::Test { EXPECT_EQ(kOrigin3.spec(), origin.spec()); exceptions.insert(kOrigin1); - EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, NULL, &origin)); + EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, nullptr, &origin)); EXPECT_EQ(kOrigin2.spec(), origin.spec()); exceptions.insert(kOrigin2); - EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, NULL, &origin)); + EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, nullptr, &origin)); EXPECT_EQ(kOrigin3.spec(), origin.spec()); exceptions.insert(kOrigin3); - EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, NULL, &origin)); + EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, nullptr, &origin)); EXPECT_TRUE(origin.is_empty()); EXPECT_TRUE( @@ -211,12 +211,12 @@ class QuotaDatabaseTest : public testing::Test { // Querying again to see if the deletion has worked. exceptions.clear(); - EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, NULL, &origin)); + EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, nullptr, &origin)); EXPECT_EQ(kOrigin2.spec(), origin.spec()); exceptions.insert(kOrigin1); exceptions.insert(kOrigin2); - EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, NULL, &origin)); + EXPECT_TRUE(db.GetLRUOrigin(kTemporary, exceptions, nullptr, &origin)); EXPECT_TRUE(origin.is_empty()); } @@ -465,8 +465,8 @@ class QuotaDatabaseTest : public testing::Test { private: template <typename Iterator> - void AssignQuotaTable(sql::Connection* db, Iterator itr, Iterator end) { - ASSERT_NE(db, (sql::Connection*)NULL); + void AssignQuotaTable(sql::Database* db, Iterator itr, Iterator end) { + ASSERT_NE(db, (sql::Database*)nullptr); for (; itr != end; ++itr) { const char* kSql = "INSERT INTO HostQuotaTable" @@ -484,8 +484,8 @@ class QuotaDatabaseTest : public testing::Test { } template <typename Iterator> - void AssignOriginInfoTable(sql::Connection* db, Iterator itr, Iterator end) { - ASSERT_NE(db, (sql::Connection*)NULL); + void AssignOriginInfoTable(sql::Database* db, Iterator itr, Iterator end) { + ASSERT_NE(db, (sql::Database*)nullptr); for (; itr != end; ++itr) { const char* kSql = "INSERT INTO OriginInfoTable" @@ -504,7 +504,7 @@ class QuotaDatabaseTest : public testing::Test { } } - bool OpenDatabase(sql::Connection* db, const base::FilePath& kDbFile) { + bool OpenDatabase(sql::Database* db, const base::FilePath& kDbFile) { if (kDbFile.empty()) { return db->OpenInMemory(); } @@ -521,7 +521,7 @@ class QuotaDatabaseTest : public testing::Test { const base::FilePath& kDbFile, const QuotaTableEntry* entries, size_t entries_size) { - std::unique_ptr<sql::Connection> db(new sql::Connection); + std::unique_ptr<sql::Database> db(new sql::Database); std::unique_ptr<sql::MetaTable> meta_table(new sql::MetaTable); // V2 schema definitions. diff --git a/chromium/storage/browser/quota/quota_macros.h b/chromium/storage/browser/quota/quota_macros.h new file mode 100644 index 00000000000..d21f63136fe --- /dev/null +++ b/chromium/storage/browser/quota/quota_macros.h @@ -0,0 +1,14 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef STORAGE_BROWSER_QUOTA_QUOTA_MACROS_H_ +#define STORAGE_BROWSER_QUOTA_QUOTA_MACROS_H_ + +#include "base/metrics/histogram_macros.h" + +#define UMA_HISTOGRAM_MBYTES(name, sample) \ + UMA_HISTOGRAM_CUSTOM_COUNTS((name), static_cast<int>((sample) / kMBytes), 1, \ + 10 * 1024 * 1024 /* 10TB */, 100) + +#endif // STORAGE_BROWSER_QUOTA_QUOTA_MACROS_H_ diff --git a/chromium/storage/browser/quota/quota_manager.cc b/chromium/storage/browser/quota/quota_manager.cc index d3315014be2..41a92cc4e2a 100644 --- a/chromium/storage/browser/quota/quota_manager.cc +++ b/chromium/storage/browser/quota/quota_manager.cc @@ -19,20 +19,20 @@ #include "base/command_line.h" #include "base/files/file_util.h" #include "base/macros.h" -#include "base/metrics/histogram_macros.h" #include "base/numerics/safe_conversions.h" #include "base/sequenced_task_runner.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" #include "base/sys_info.h" +#include "base/task/post_task.h" #include "base/task_runner_util.h" -#include "base/task_scheduler/post_task.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "base/trace_event/trace_event.h" #include "net/base/url_util.h" #include "storage/browser/quota/client_usage_tracker.h" +#include "storage/browser/quota/quota_macros.h" #include "storage/browser/quota/quota_manager_proxy.h" #include "storage/browser/quota/quota_temporary_storage_evictor.h" #include "storage/browser/quota/storage_monitor.h" @@ -48,10 +48,6 @@ const int64_t kMBytes = 1024 * 1024; const int kMinutesInMilliSeconds = 60 * 1000; const int64_t kReportHistogramInterval = 60 * 60 * 1000; // 1 hour -#define UMA_HISTOGRAM_MBYTES(name, sample) \ - UMA_HISTOGRAM_CUSTOM_COUNTS((name), static_cast<int>((sample) / kMBytes), 1, \ - 10 * 1024 * 1024 /* 10TB */, 100) - } // namespace const int64_t QuotaManager::kNoLimit = INT64_MAX; @@ -1142,7 +1138,7 @@ void QuotaManager::RemoveStorageObserver(StorageObserver* observer) { } QuotaManager::~QuotaManager() { - proxy_->manager_ = NULL; + proxy_->manager_ = nullptr; for (auto* client : clients_) client->OnQuotaManagerDestroyed(); if (database_) @@ -1232,11 +1228,11 @@ UsageTracker* QuotaManager::GetUsageTracker(StorageType type) const { case StorageType::kSyncable: return syncable_usage_tracker_.get(); case StorageType::kQuotaNotManaged: - return NULL; + return nullptr; case StorageType::kUnknown: NOTREACHED(); } - return NULL; + return nullptr; } void QuotaManager::GetCachedOrigins( diff --git a/chromium/storage/browser/quota/quota_manager_proxy.h b/chromium/storage/browser/quota/quota_manager_proxy.h index b3ab592f1c4..32b3292ab3e 100644 --- a/chromium/storage/browser/quota/quota_manager_proxy.h +++ b/chromium/storage/browser/quota/quota_manager_proxy.h @@ -59,7 +59,7 @@ class STORAGE_EXPORT QuotaManagerProxy UsageAndQuotaCallback callback); // This method may only be called on the IO thread. - // It may return NULL if the manager has already been deleted. + // It may return nullptr if the manager has already been deleted. QuotaManager* quota_manager() const; protected: diff --git a/chromium/storage/browser/quota/quota_manager_unittest.cc b/chromium/storage/browser/quota/quota_manager_unittest.cc index 54124896e20..174a262cc28 100644 --- a/chromium/storage/browser/quota/quota_manager_unittest.cc +++ b/chromium/storage/browser/quota/quota_manager_unittest.cc @@ -98,7 +98,7 @@ class QuotaManagerTest : public testing::Test { void TearDown() override { // Make sure the quota manager cleans up correctly. - quota_manager_ = NULL; + quota_manager_ = nullptr; scoped_task_environment_.RunUntilIdle(); } @@ -288,7 +288,7 @@ class QuotaManagerTest : public testing::Test { } void GetCachedOrigins(StorageType type, std::set<GURL>* origins) { - ASSERT_TRUE(origins != NULL); + ASSERT_TRUE(origins != nullptr); origins->clear(); quota_manager_->GetCachedOrigins(type, origins); } @@ -611,7 +611,7 @@ TEST_F(QuotaManagerTest, GetUsage_NoClient) { } TEST_F(QuotaManagerTest, GetUsage_EmptyClient) { - RegisterClient(CreateClient(NULL, 0, QuotaClient::kFileSystem)); + RegisterClient(CreateClient(nullptr, 0, QuotaClient::kFileSystem)); GetUsageAndQuotaForWebApps(GURL("http://foo.com/"), kTemp); scoped_task_environment_.RunUntilIdle(); EXPECT_EQ(QuotaStatusCode::kOk, status()); @@ -983,7 +983,7 @@ TEST_F(QuotaManagerTest, GetTemporaryUsageAndQuota_NukeManager) { DeleteOriginData(GURL("http://bar.com/"), kTemp, kAllClients); // Nuke before waiting for callbacks. - set_quota_manager(NULL); + set_quota_manager(nullptr); scoped_task_environment_.RunUntilIdle(); EXPECT_EQ(QuotaStatusCode::kErrorAbort, status()); } @@ -1155,7 +1155,7 @@ TEST_F(QuotaManagerTest, OriginInUse) { } TEST_F(QuotaManagerTest, GetAndSetPerststentHostQuota) { - RegisterClient(CreateClient(NULL, 0, QuotaClient::kFileSystem)); + RegisterClient(CreateClient(nullptr, 0, QuotaClient::kFileSystem)); GetPersistentHostQuota("foo.com"); scoped_task_environment_.RunUntilIdle(); @@ -1182,7 +1182,7 @@ TEST_F(QuotaManagerTest, GetAndSetPerststentHostQuota) { } TEST_F(QuotaManagerTest, GetAndSetPersistentUsageAndQuota) { - RegisterClient(CreateClient(NULL, 0, QuotaClient::kFileSystem)); + RegisterClient(CreateClient(nullptr, 0, QuotaClient::kFileSystem)); GetUsageAndQuotaForWebApps(GURL("http://foo.com/"), kPerm); scoped_task_environment_.RunUntilIdle(); @@ -1212,7 +1212,7 @@ TEST_F(QuotaManagerTest, GetAndSetPersistentUsageAndQuota) { } TEST_F(QuotaManagerTest, GetSyncableQuota) { - RegisterClient(CreateClient(NULL, 0, QuotaClient::kFileSystem)); + RegisterClient(CreateClient(nullptr, 0, QuotaClient::kFileSystem)); // Pre-condition check: available disk space (for testing) is less than // the default quota for syncable storage. @@ -1302,7 +1302,7 @@ TEST_F(QuotaManagerTest, GetPersistentUsageAndQuota_NukeManager) { RunAdditionalUsageAndQuotaTask(GURL("http://bar.com/"), kPerm); // Nuke before waiting for callbacks. - set_quota_manager(NULL); + set_quota_manager(nullptr); scoped_task_environment_.RunUntilIdle(); EXPECT_EQ(QuotaStatusCode::kErrorAbort, status()); } diff --git a/chromium/storage/browser/quota/quota_settings.cc b/chromium/storage/browser/quota/quota_settings.cc index 393dcd5b3f8..35a4b6b1d79 100644 --- a/chromium/storage/browser/quota/quota_settings.cc +++ b/chromium/storage/browser/quota/quota_settings.cc @@ -6,16 +6,12 @@ #include <algorithm> -#include "base/metrics/histogram_macros.h" #include "base/rand_util.h" #include "base/sys_info.h" -#include "base/task_scheduler/post_task.h" +#include "base/task/post_task.h" #include "base/threading/thread_restrictions.h" #include "build/build_config.h" - -#define UMA_HISTOGRAM_MBYTES(name, sample) \ - UMA_HISTOGRAM_CUSTOM_COUNTS((name), static_cast<int>((sample) / kMBytes), 1, \ - 10 * 1024 * 1024 /* 10TB */, 100) +#include "storage/browser/quota/quota_macros.h" namespace storage { @@ -137,7 +133,7 @@ void GetNominalDynamicSettings(const base::FilePath& partition_path, OptionalQuotaSettingsCallback callback) { base::PostTaskWithTraitsAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskPriority::BACKGROUND, + {base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&CalculateNominalDynamicSettings, partition_path, is_incognito), diff --git a/chromium/storage/browser/quota/quota_task.cc b/chromium/storage/browser/quota/quota_task.cc index 8e10a880503..b7266c4fdd3 100644 --- a/chromium/storage/browser/quota/quota_task.cc +++ b/chromium/storage/browser/quota/quota_task.cc @@ -43,7 +43,7 @@ void QuotaTask::CallCompleted() { void QuotaTask::Abort() { DCHECK(original_task_runner_->BelongsToCurrentThread()); - observer_ = NULL; + observer_ = nullptr; Aborted(); } diff --git a/chromium/storage/browser/quota/quota_temporary_storage_evictor.cc b/chromium/storage/browser/quota/quota_temporary_storage_evictor.cc index 181856631df..e9339282ea7 100644 --- a/chromium/storage/browser/quota/quota_temporary_storage_evictor.cc +++ b/chromium/storage/browser/quota/quota_temporary_storage_evictor.cc @@ -10,16 +10,11 @@ #include "base/auto_reset.h" #include "base/bind.h" -#include "base/metrics/histogram_macros.h" +#include "storage/browser/quota/quota_macros.h" #include "storage/browser/quota/quota_manager.h" #include "third_party/blink/public/mojom/quota/quota_types.mojom.h" #include "url/gurl.h" -#define UMA_HISTOGRAM_MBYTES(name, sample) \ - UMA_HISTOGRAM_CUSTOM_COUNTS( \ - (name), static_cast<int>((sample) / kMBytes), \ - 1, 10 * 1024 * 1024 /* 10TB */, 100) - #define UMA_HISTOGRAM_MINUTES(name, sample) \ UMA_HISTOGRAM_CUSTOM_TIMES( \ (name), (sample), \ diff --git a/chromium/storage/browser/quota/special_storage_policy.h b/chromium/storage/browser/quota/special_storage_policy.h index 526cd24a02f..25000d5f89b 100644 --- a/chromium/storage/browser/quota/special_storage_policy.h +++ b/chromium/storage/browser/quota/special_storage_policy.h @@ -85,7 +85,7 @@ class STORAGE_EXPORT SpecialStoragePolicy void NotifyRevoked(const GURL& origin, int change_flags); void NotifyCleared(); - base::ObserverList<Observer> observers_; + base::ObserverList<Observer>::Unchecked observers_; }; } // namespace storage diff --git a/chromium/storage/browser/quota/storage_monitor_unittest.cc b/chromium/storage/browser/quota/storage_monitor_unittest.cc index 0ffb6b1fc63..e633d221a88 100644 --- a/chromium/storage/browser/quota/storage_monitor_unittest.cc +++ b/chromium/storage/browser/quota/storage_monitor_unittest.cc @@ -118,7 +118,8 @@ class StorageMonitorTestBase : public testing::Test { const StorageObserver::Event* GetPendingEvent( const StorageObserverList& observer_list) { return observer_list.notification_timer_.IsRunning() - ? &observer_list.pending_event_ : NULL; + ? &observer_list.pending_event_ + : nullptr; } const StorageObserver::Event* GetPendingEvent( @@ -169,7 +170,7 @@ class StorageTestWithManagerBase : public StorageMonitorTestBase { void TearDown() override { // This ensures the quota manager is destroyed correctly. - quota_manager_ = NULL; + quota_manager_ = nullptr; scoped_task_environment_.RunUntilIdle(); } @@ -200,7 +201,7 @@ TEST_F(StorageObserverListTest, DispatchEventToSingleObserver) { observer_list.OnStorageChange(event); EXPECT_EQ(1, mock_observer.EventCount()); EXPECT_EQ(event, mock_observer.LastEvent()); - EXPECT_EQ(NULL, GetPendingEvent(observer_list)); + EXPECT_EQ(nullptr, GetPendingEvent(observer_list)); EXPECT_EQ(0, GetRequiredUpdatesCount(observer_list)); // Verify that the next event is pending. @@ -219,7 +220,7 @@ TEST_F(StorageObserverListTest, DispatchEventToSingleObserver) { observer_list.OnStorageChange(event); EXPECT_EQ(2, mock_observer.EventCount()); EXPECT_EQ(event, mock_observer.LastEvent()); - EXPECT_EQ(NULL, GetPendingEvent(observer_list)); + EXPECT_EQ(nullptr, GetPendingEvent(observer_list)); EXPECT_EQ(0, GetRequiredUpdatesCount(observer_list)); // Remove the observer. @@ -228,7 +229,7 @@ TEST_F(StorageObserverListTest, DispatchEventToSingleObserver) { observer_list.RemoveObserver(&mock_observer); observer_list.OnStorageChange(event); EXPECT_EQ(2, mock_observer.EventCount()); - EXPECT_EQ(NULL, GetPendingEvent(observer_list)); + EXPECT_EQ(nullptr, GetPendingEvent(observer_list)); } // Test dispatching events to multiple observers. @@ -258,7 +259,7 @@ TEST_F(StorageObserverListTest, DispatchEventToMultipleObservers) { EXPECT_EQ(1, mock_observer2.EventCount()); EXPECT_EQ(event, mock_observer1.LastEvent()); EXPECT_EQ(event, mock_observer2.LastEvent()); - EXPECT_EQ(NULL, GetPendingEvent(observer_list)); + EXPECT_EQ(nullptr, GetPendingEvent(observer_list)); EXPECT_EQ(0, GetRequiredUpdatesCount(observer_list)); // Fake the last notification time so that observer1 will receive the next @@ -281,7 +282,7 @@ TEST_F(StorageObserverListTest, DispatchEventToMultipleObservers) { EXPECT_EQ(2, mock_observer2.EventCount()); EXPECT_EQ(event, mock_observer1.LastEvent()); EXPECT_EQ(event, mock_observer2.LastEvent()); - EXPECT_EQ(NULL, GetPendingEvent(observer_list)); + EXPECT_EQ(nullptr, GetPendingEvent(observer_list)); EXPECT_EQ(0, GetRequiredUpdatesCount(observer_list)); } @@ -365,7 +366,7 @@ TEST_F(HostStorageObserversTest, InitializeOnObserver) { EXPECT_EQ(1, mock_observer2.EventCount()); EXPECT_EQ(expected_event, mock_observer2.LastEvent()); EXPECT_TRUE(host_observers.is_initialized()); - EXPECT_EQ(NULL, GetPendingEvent(host_observers)); + EXPECT_EQ(nullptr, GetPendingEvent(host_observers)); EXPECT_EQ(0, GetRequiredUpdatesCount(host_observers)); // Verify that both observers will receive events after a usage change. @@ -377,7 +378,7 @@ TEST_F(HostStorageObserversTest, InitializeOnObserver) { EXPECT_EQ(2, mock_observer2.EventCount()); EXPECT_EQ(expected_event, mock_observer1.LastEvent()); EXPECT_EQ(expected_event, mock_observer2.LastEvent()); - EXPECT_EQ(NULL, GetPendingEvent(host_observers)); + EXPECT_EQ(nullptr, GetPendingEvent(host_observers)); EXPECT_EQ(0, GetRequiredUpdatesCount(host_observers)); // Verify that the addition of a third observer only causes an event to be @@ -429,7 +430,7 @@ TEST_F(HostStorageObserversTest, RecoverFromBadUsageInit) { host_observers.NotifyUsageChange(params.filter, 9438); EXPECT_EQ(0, mock_observer.EventCount()); EXPECT_FALSE(host_observers.is_initialized()); - EXPECT_EQ(NULL, GetPendingEvent(host_observers)); + EXPECT_EQ(nullptr, GetPendingEvent(host_observers)); EXPECT_EQ(0, GetRequiredUpdatesCount(host_observers)); // Now ensure that quota manager returns a good status. @@ -456,7 +457,7 @@ TEST_F(HostStorageObserversTest, AsyncInitialization) { host_observers.NotifyUsageChange(params.filter, 7645); EXPECT_EQ(0, mock_observer.EventCount()); EXPECT_FALSE(host_observers.is_initialized()); - EXPECT_EQ(NULL, GetPendingEvent(host_observers)); + EXPECT_EQ(nullptr, GetPendingEvent(host_observers)); EXPECT_EQ(0, GetRequiredUpdatesCount(host_observers)); // Simulate notifying |host_observers| of a usage change before initialization @@ -467,7 +468,7 @@ TEST_F(HostStorageObserversTest, AsyncInitialization) { host_observers.NotifyUsageChange(params.filter, kDelta); EXPECT_EQ(0, mock_observer.EventCount()); EXPECT_FALSE(host_observers.is_initialized()); - EXPECT_EQ(NULL, GetPendingEvent(host_observers)); + EXPECT_EQ(nullptr, GetPendingEvent(host_observers)); EXPECT_EQ(0, GetRequiredUpdatesCount(host_observers)); // Simulate an asynchronous callback from QuotaManager. @@ -477,7 +478,7 @@ TEST_F(HostStorageObserversTest, AsyncInitialization) { EXPECT_EQ(1, mock_observer.EventCount()); EXPECT_EQ(expected_event, mock_observer.LastEvent()); EXPECT_TRUE(host_observers.is_initialized()); - EXPECT_EQ(NULL, GetPendingEvent(host_observers)); + EXPECT_EQ(nullptr, GetPendingEvent(host_observers)); EXPECT_EQ(0, GetRequiredUpdatesCount(host_observers)); } @@ -534,7 +535,7 @@ TEST_F(StorageTypeObserversTest, AddRemoveObservers) { class StorageMonitorTest : public StorageTestWithManagerBase { public: StorageMonitorTest() - : storage_monitor_(NULL), + : storage_monitor_(nullptr), params1_(StorageType::kTemporary, GURL(kDefaultOrigin), base::TimeDelta::FromHours(1), @@ -630,17 +631,15 @@ class StorageMonitorIntegrationTest : public testing::Test { false, data_dir_.GetPath(), base::ThreadTaskRunnerHandle::Get().get(), storage_policy_.get(), storage::GetQuotaSettingsFunc()); - client_ = new MockStorageClient(quota_manager_->proxy(), - NULL, - QuotaClient::kFileSystem, - 0); + client_ = new MockStorageClient(quota_manager_->proxy(), nullptr, + QuotaClient::kFileSystem, 0); quota_manager_->proxy()->RegisterClient(client_); } void TearDown() override { // This ensures the quota manager is destroyed correctly. - quota_manager_ = NULL; + quota_manager_ = nullptr; scoped_task_environment_.RunUntilIdle(); } diff --git a/chromium/storage/browser/quota/usage_tracker_unittest.cc b/chromium/storage/browser/quota/usage_tracker_unittest.cc index 3e641b8a055..48ea323f32a 100644 --- a/chromium/storage/browser/quota/usage_tracker_unittest.cc +++ b/chromium/storage/browser/quota/usage_tracker_unittest.cc @@ -140,7 +140,7 @@ class UsageTrackerTest : public testing::Test { usage_tracker_(GetUsageTrackerList(), StorageType::kTemporary, storage_policy_.get(), - NULL) {} + nullptr) {} ~UsageTrackerTest() override = default; |