| OLD | NEW |
| 1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. | 1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
| 4 | 4 |
| 5 #include "base/files/important_file_writer.h" | 5 #include "base/files/important_file_writer.h" |
| 6 | 6 |
| 7 #include <stdio.h> | 7 #include <stdio.h> |
| 8 | 8 |
| 9 #include <string> | 9 #include <string> |
| 10 | 10 |
| 11 #include "base/bind.h" | 11 #include "base/bind.h" |
| 12 #include "base/critical_closure.h" | 12 #include "base/critical_closure.h" |
| 13 #include "base/debug/alias.h" | 13 #include "base/debug/alias.h" |
| 14 #include "base/files/file.h" | 14 #include "base/files/file.h" |
| 15 #include "base/files/file_path.h" | 15 #include "base/files/file_path.h" |
| 16 #include "base/files/file_util.h" | 16 #include "base/files/file_util.h" |
| 17 #include "base/logging.h" | 17 #include "base/logging.h" |
| 18 #include "base/metrics/histogram.h" | 18 #include "base/metrics/histogram.h" |
| 19 #include "base/numerics/safe_conversions.h" |
| 19 #include "base/strings/string_number_conversions.h" | 20 #include "base/strings/string_number_conversions.h" |
| 20 #include "base/strings/string_util.h" | 21 #include "base/strings/string_util.h" |
| 21 #include "base/task_runner.h" | 22 #include "base/task_runner.h" |
| 22 #include "base/task_runner_util.h" | 23 #include "base/task_runner_util.h" |
| 23 #include "base/threading/thread.h" | 24 #include "base/threading/thread.h" |
| 24 #include "base/time/time.h" | 25 #include "base/time/time.h" |
| 25 | 26 |
| 26 namespace base { | 27 namespace base { |
| 27 | 28 |
| 28 namespace { | 29 namespace { |
| (...skipping 11 matching lines...) Expand all Loading... |
| 40 FAILED_WRITING, | 41 FAILED_WRITING, |
| 41 FAILED_RENAMING, | 42 FAILED_RENAMING, |
| 42 FAILED_FLUSHING, | 43 FAILED_FLUSHING, |
| 43 TEMP_FILE_FAILURE_MAX | 44 TEMP_FILE_FAILURE_MAX |
| 44 }; | 45 }; |
| 45 | 46 |
| 46 void LogFailure(const FilePath& path, TempFileFailure failure_code, | 47 void LogFailure(const FilePath& path, TempFileFailure failure_code, |
| 47 const std::string& message) { | 48 const std::string& message) { |
| 48 UMA_HISTOGRAM_ENUMERATION("ImportantFile.TempFileFailures", failure_code, | 49 UMA_HISTOGRAM_ENUMERATION("ImportantFile.TempFileFailures", failure_code, |
| 49 TEMP_FILE_FAILURE_MAX); | 50 TEMP_FILE_FAILURE_MAX); |
| 50 DPLOG(WARNING) << "temp file failure: " << path.value().c_str() | 51 DPLOG(WARNING) << "temp file failure: " << path.value() << " : " << message; |
| 51 << " : " << message; | |
| 52 } | 52 } |
| 53 | 53 |
| 54 // Helper function to call WriteFileAtomically() with a scoped_ptr<std::string>. | 54 // Helper function to call WriteFileAtomically() with a scoped_ptr<std::string>. |
| 55 bool WriteScopedStringToFileAtomically(const FilePath& path, | 55 bool WriteScopedStringToFileAtomically(const FilePath& path, |
| 56 scoped_ptr<std::string> data) { | 56 scoped_ptr<std::string> data) { |
| 57 return ImportantFileWriter::WriteFileAtomically(path, *data); | 57 return ImportantFileWriter::WriteFileAtomically(path, *data); |
| 58 } | 58 } |
| 59 | 59 |
| 60 } // namespace | 60 } // namespace |
| 61 | 61 |
| 62 // static | 62 // static |
| 63 bool ImportantFileWriter::WriteFileAtomically(const FilePath& path, | 63 bool ImportantFileWriter::WriteFileAtomically(const FilePath& path, |
| 64 const std::string& data) { | 64 const std::string& data) { |
| 65 #if defined(OS_CHROMEOS) | 65 #if defined(OS_CHROMEOS) |
| 66 // On Chrome OS, chrome gets killed when it cannot finish shutdown quickly, | 66 // On Chrome OS, chrome gets killed when it cannot finish shutdown quickly, |
| 67 // and this function seems to be one of the slowest shutdown steps. | 67 // and this function seems to be one of the slowest shutdown steps. |
| 68 // Include some info to the report for investigation. crbug.com/418627 | 68 // Include some info to the report for investigation. crbug.com/418627 |
| 69 // TODO(hashimoto): Remove this. | 69 // TODO(hashimoto): Remove this. |
| 70 struct { | 70 struct { |
| 71 size_t data_size; | 71 size_t data_size; |
| 72 char path[128]; | 72 char path[128]; |
| 73 } file_info; | 73 } file_info; |
| 74 file_info.data_size = data.size(); | 74 file_info.data_size = data.size(); |
| 75 base::strlcpy(file_info.path, path.value().c_str(), | 75 strlcpy(file_info.path, path.value().c_str(), arraysize(file_info.path)); |
| 76 arraysize(file_info.path)); | 76 debug::Alias(&file_info); |
| 77 base::debug::Alias(&file_info); | |
| 78 #endif | 77 #endif |
| 78 |
| 79 // Write the data to a temp file then rename to avoid data loss if we crash | 79 // Write the data to a temp file then rename to avoid data loss if we crash |
| 80 // while writing the file. Ensure that the temp file is on the same volume | 80 // while writing the file. Ensure that the temp file is on the same volume |
| 81 // as target file, so it can be moved in one step, and that the temp file | 81 // as target file, so it can be moved in one step, and that the temp file |
| 82 // is securely created. | 82 // is securely created. |
| 83 FilePath tmp_file_path; | 83 FilePath tmp_file_path; |
| 84 if (!base::CreateTemporaryFileInDir(path.DirName(), &tmp_file_path)) { | 84 if (!CreateTemporaryFileInDir(path.DirName(), &tmp_file_path)) { |
| 85 LogFailure(path, FAILED_CREATING, "could not create temporary file"); | 85 LogFailure(path, FAILED_CREATING, "could not create temporary file"); |
| 86 return false; | 86 return false; |
| 87 } | 87 } |
| 88 | 88 |
| 89 File tmp_file(tmp_file_path, File::FLAG_OPEN | File::FLAG_WRITE); | 89 File tmp_file(tmp_file_path, File::FLAG_OPEN | File::FLAG_WRITE); |
| 90 if (!tmp_file.IsValid()) { | 90 if (!tmp_file.IsValid()) { |
| 91 LogFailure(path, FAILED_OPENING, "could not open temporary file"); | 91 LogFailure(path, FAILED_OPENING, "could not open temporary file"); |
| 92 return false; | 92 return false; |
| 93 } | 93 } |
| 94 | 94 |
| 95 // If this happens in the wild something really bad is going on. | 95 // If this fails in the wild, something really bad is going on. |
| 96 CHECK_LE(data.length(), static_cast<size_t>(kint32max)); | 96 const int data_length = checked_cast<int32_t>(data.length()); |
| 97 int bytes_written = tmp_file.Write(0, data.data(), | 97 int bytes_written = tmp_file.Write(0, data.data(), data_length); |
| 98 static_cast<int>(data.length())); | |
| 99 bool flush_success = tmp_file.Flush(); | 98 bool flush_success = tmp_file.Flush(); |
| 100 tmp_file.Close(); | 99 tmp_file.Close(); |
| 101 | 100 |
| 102 if (bytes_written < static_cast<int>(data.length())) { | 101 if (bytes_written < data_length) { |
| 103 LogFailure(path, FAILED_WRITING, "error writing, bytes_written=" + | 102 LogFailure(path, FAILED_WRITING, "error writing, bytes_written=" + |
| 104 IntToString(bytes_written)); | 103 IntToString(bytes_written)); |
| 105 base::DeleteFile(tmp_file_path, false); | 104 DeleteFile(tmp_file_path, false); |
| 106 return false; | 105 return false; |
| 107 } | 106 } |
| 108 | 107 |
| 109 if (!flush_success) { | 108 if (!flush_success) { |
| 110 LogFailure(path, FAILED_FLUSHING, "error flushing"); | 109 LogFailure(path, FAILED_FLUSHING, "error flushing"); |
| 111 base::DeleteFile(tmp_file_path, false); | 110 DeleteFile(tmp_file_path, false); |
| 112 return false; | 111 return false; |
| 113 } | 112 } |
| 114 | 113 |
| 115 if (!base::ReplaceFile(tmp_file_path, path, NULL)) { | 114 if (!ReplaceFile(tmp_file_path, path, nullptr)) { |
| 116 LogFailure(path, FAILED_RENAMING, "could not rename temporary file"); | 115 LogFailure(path, FAILED_RENAMING, "could not rename temporary file"); |
| 117 base::DeleteFile(tmp_file_path, false); | 116 DeleteFile(tmp_file_path, false); |
| 118 return false; | 117 return false; |
| 119 } | 118 } |
| 120 | 119 |
| 121 return true; | 120 return true; |
| 122 } | 121 } |
| 123 | 122 |
| 124 ImportantFileWriter::ImportantFileWriter( | 123 ImportantFileWriter::ImportantFileWriter( |
| 125 const FilePath& path, | 124 const FilePath& path, |
| 126 const scoped_refptr<base::SequencedTaskRunner>& task_runner) | 125 const scoped_refptr<SequencedTaskRunner>& task_runner) |
| 126 : ImportantFileWriter( |
| 127 path, |
| 128 task_runner, |
| 129 TimeDelta::FromMilliseconds(kDefaultCommitIntervalMs)) { |
| 130 } |
| 131 |
| 132 ImportantFileWriter::ImportantFileWriter( |
| 133 const FilePath& path, |
| 134 const scoped_refptr<SequencedTaskRunner>& task_runner, |
| 135 TimeDelta interval) |
| 127 : path_(path), | 136 : path_(path), |
| 128 task_runner_(task_runner), | 137 task_runner_(task_runner), |
| 129 serializer_(NULL), | 138 serializer_(nullptr), |
| 130 commit_interval_(TimeDelta::FromMilliseconds(kDefaultCommitIntervalMs)), | 139 commit_interval_(interval), |
| 131 weak_factory_(this) { | 140 weak_factory_(this) { |
| 132 DCHECK(CalledOnValidThread()); | 141 DCHECK(CalledOnValidThread()); |
| 133 DCHECK(task_runner_); | 142 DCHECK(task_runner_); |
| 134 } | 143 } |
| 135 | 144 |
| 136 ImportantFileWriter::~ImportantFileWriter() { | 145 ImportantFileWriter::~ImportantFileWriter() { |
| 137 // We're usually a member variable of some other object, which also tends | 146 // We're usually a member variable of some other object, which also tends |
| 138 // to be our serializer. It may not be safe to call back to the parent object | 147 // to be our serializer. It may not be safe to call back to the parent object |
| 139 // being destructed. | 148 // being destructed. |
| 140 DCHECK(!HasPendingWrite()); | 149 DCHECK(!HasPendingWrite()); |
| 141 } | 150 } |
| 142 | 151 |
| 143 bool ImportantFileWriter::HasPendingWrite() const { | 152 bool ImportantFileWriter::HasPendingWrite() const { |
| 144 DCHECK(CalledOnValidThread()); | 153 DCHECK(CalledOnValidThread()); |
| 145 return timer_.IsRunning(); | 154 return timer_.IsRunning(); |
| 146 } | 155 } |
| 147 | 156 |
| 148 void ImportantFileWriter::WriteNow(scoped_ptr<std::string> data) { | 157 void ImportantFileWriter::WriteNow(scoped_ptr<std::string> data) { |
| 149 DCHECK(CalledOnValidThread()); | 158 DCHECK(CalledOnValidThread()); |
| 150 if (data->length() > static_cast<size_t>(kint32max)) { | 159 if (!IsValueInRangeForNumericType<int32_t>(data->length())) { |
| 151 NOTREACHED(); | 160 NOTREACHED(); |
| 152 return; | 161 return; |
| 153 } | 162 } |
| 154 | 163 |
| 155 if (HasPendingWrite()) | 164 if (HasPendingWrite()) |
| 156 timer_.Stop(); | 165 timer_.Stop(); |
| 157 | 166 |
| 158 auto task = Bind(&WriteScopedStringToFileAtomically, path_, Passed(&data)); | 167 auto task = Bind(&WriteScopedStringToFileAtomically, path_, Passed(&data)); |
| 159 if (!PostWriteTask(task)) { | 168 if (!PostWriteTask(task)) { |
| 160 // Posting the task to background message loop is not expected | 169 // Posting the task to background message loop is not expected |
| (...skipping 17 matching lines...) Expand all Loading... |
| 178 } | 187 } |
| 179 } | 188 } |
| 180 | 189 |
| 181 void ImportantFileWriter::DoScheduledWrite() { | 190 void ImportantFileWriter::DoScheduledWrite() { |
| 182 DCHECK(serializer_); | 191 DCHECK(serializer_); |
| 183 scoped_ptr<std::string> data(new std::string); | 192 scoped_ptr<std::string> data(new std::string); |
| 184 if (serializer_->SerializeData(data.get())) { | 193 if (serializer_->SerializeData(data.get())) { |
| 185 WriteNow(data.Pass()); | 194 WriteNow(data.Pass()); |
| 186 } else { | 195 } else { |
| 187 DLOG(WARNING) << "failed to serialize data to be saved in " | 196 DLOG(WARNING) << "failed to serialize data to be saved in " |
| 188 << path_.value().c_str(); | 197 << path_.value(); |
| 189 } | 198 } |
| 190 serializer_ = NULL; | 199 serializer_ = nullptr; |
| 191 } | 200 } |
| 192 | 201 |
| 193 void ImportantFileWriter::RegisterOnNextSuccessfulWriteCallback( | 202 void ImportantFileWriter::RegisterOnNextSuccessfulWriteCallback( |
| 194 const base::Closure& on_next_successful_write) { | 203 const Closure& on_next_successful_write) { |
| 195 DCHECK(on_next_successful_write_.is_null()); | 204 DCHECK(on_next_successful_write_.is_null()); |
| 196 on_next_successful_write_ = on_next_successful_write; | 205 on_next_successful_write_ = on_next_successful_write; |
| 197 } | 206 } |
| 198 | 207 |
| 199 bool ImportantFileWriter::PostWriteTask(const Callback<bool()>& task) { | 208 bool ImportantFileWriter::PostWriteTask(const Callback<bool()>& task) { |
| 200 // TODO(gab): This code could always use PostTaskAndReplyWithResult and let | 209 // TODO(gab): This code could always use PostTaskAndReplyWithResult and let |
| 201 // ForwardSuccessfulWrite() no-op if |on_next_successful_write_| is null, but | 210 // ForwardSuccessfulWrite() no-op if |on_next_successful_write_| is null, but |
| 202 // PostTaskAndReply causes memory leaks in tests (crbug.com/371974) and | 211 // PostTaskAndReply causes memory leaks in tests (crbug.com/371974) and |
| 203 // suppressing all of those is unrealistic hence we avoid most of them by | 212 // suppressing all of those is unrealistic hence we avoid most of them by |
| 204 // using PostTask() in the typical scenario below. | 213 // using PostTask() in the typical scenario below. |
| 205 if (!on_next_successful_write_.is_null()) { | 214 if (!on_next_successful_write_.is_null()) { |
| 206 return base::PostTaskAndReplyWithResult( | 215 return PostTaskAndReplyWithResult( |
| 207 task_runner_.get(), | 216 task_runner_.get(), |
| 208 FROM_HERE, | 217 FROM_HERE, |
| 209 MakeCriticalClosure(task), | 218 MakeCriticalClosure(task), |
| 210 Bind(&ImportantFileWriter::ForwardSuccessfulWrite, | 219 Bind(&ImportantFileWriter::ForwardSuccessfulWrite, |
| 211 weak_factory_.GetWeakPtr())); | 220 weak_factory_.GetWeakPtr())); |
| 212 } | 221 } |
| 213 return task_runner_->PostTask( | 222 return task_runner_->PostTask( |
| 214 FROM_HERE, | 223 FROM_HERE, |
| 215 MakeCriticalClosure(base::Bind(IgnoreResult(task)))); | 224 MakeCriticalClosure(Bind(IgnoreResult(task)))); |
| 216 } | 225 } |
| 217 | 226 |
| 218 void ImportantFileWriter::ForwardSuccessfulWrite(bool result) { | 227 void ImportantFileWriter::ForwardSuccessfulWrite(bool result) { |
| 219 DCHECK(CalledOnValidThread()); | 228 DCHECK(CalledOnValidThread()); |
| 220 if (result && !on_next_successful_write_.is_null()) { | 229 if (result && !on_next_successful_write_.is_null()) { |
| 221 on_next_successful_write_.Run(); | 230 on_next_successful_write_.Run(); |
| 222 on_next_successful_write_.Reset(); | 231 on_next_successful_write_.Reset(); |
| 223 } | 232 } |
| 224 } | 233 } |
| 225 | 234 |
| 226 } // namespace base | 235 } // namespace base |
| OLD | NEW |