Samuel Huang | 06f1ae9 | 2018-03-13 18:19:34 +0000 | [diff] [blame] | 1 | // Copyright 2017 The Chromium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include "components/zucchini/mapped_file.h" |
| 6 | |
| 7 | #include <utility> |
| 8 | |
| 9 | #include "base/files/file_util.h" |
Samuel Huang | 06f1ae9 | 2018-03-13 18:19:34 +0000 | [diff] [blame] | 10 | #include "build/build_config.h" |
| 11 | |
| 12 | namespace zucchini { |
| 13 | |
Samuel Huang | f35146e | 2018-06-21 15:50:22 +0000 | [diff] [blame] | 14 | MappedFileReader::MappedFileReader(base::File file) { |
Samuel Huang | 06f1ae9 | 2018-03-13 18:19:34 +0000 | [diff] [blame] | 15 | if (!file.IsValid()) { |
| 16 | error_ = "Invalid file."; |
| 17 | return; // |buffer_| will be uninitialized, and therefore invalid. |
| 18 | } |
| 19 | if (!buffer_.Initialize(std::move(file))) { |
| 20 | error_ = "Can't map file to memory."; |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | MappedFileWriter::MappedFileWriter(const base::FilePath& file_path, |
Samuel Huang | f35146e | 2018-06-21 15:50:22 +0000 | [diff] [blame] | 25 | base::File file, |
Samuel Huang | 06f1ae9 | 2018-03-13 18:19:34 +0000 | [diff] [blame] | 26 | size_t length) |
| 27 | : file_path_(file_path), delete_behavior_(kManualDeleteOnClose) { |
| 28 | if (!file.IsValid()) { |
| 29 | error_ = "Invalid file."; |
| 30 | return; // |buffer_| will be uninitialized, and therefore invalid. |
| 31 | } |
| 32 | |
| 33 | #if defined(OS_WIN) |
| 34 | file_handle_ = file.Duplicate(); |
| 35 | // Tell the OS to delete the file when all handles are closed. |
| 36 | if (file_handle_.DeleteOnClose(true)) { |
| 37 | delete_behavior_ = kAutoDeleteOnClose; |
| 38 | } else { |
| 39 | error_ = "Failed to mark file for delete-on-close."; |
| 40 | } |
| 41 | #endif // defined(OS_WIN) |
| 42 | |
| 43 | bool is_ok = buffer_.Initialize(std::move(file), {0, length}, |
| 44 | base::MemoryMappedFile::READ_WRITE_EXTEND); |
| 45 | if (!is_ok) { |
| 46 | error_ = "Can't map file to memory."; |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | MappedFileWriter::~MappedFileWriter() { |
| 51 | if (!HasError() && delete_behavior_ == kManualDeleteOnClose && |
Kelvin Zhang | 539c01b | 2021-08-19 10:52:34 -0700 | [diff] [blame] | 52 | !file_path_.empty() && !base::DeleteFile(file_path_, false)) { |
Samuel Huang | 06f1ae9 | 2018-03-13 18:19:34 +0000 | [diff] [blame] | 53 | error_ = "Failed to delete file."; |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | bool MappedFileWriter::Keep() { |
| 58 | #if defined(OS_WIN) |
| 59 | if (delete_behavior_ == kAutoDeleteOnClose && |
| 60 | !file_handle_.DeleteOnClose(false)) { |
| 61 | error_ = "Failed to prevent deletion of file."; |
| 62 | return false; |
| 63 | } |
| 64 | #endif // defined(OS_WIN) |
| 65 | delete_behavior_ = kKeep; |
| 66 | return true; |
| 67 | } |
| 68 | |
| 69 | } // namespace zucchini |