Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(208)

Side by Side Diff: base/files/file_util_win.cc

Issue 2545283002: A robust base::DeleteFile.
Patch Set: test fixes Created 3 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « base/files/file_util_unittest.cc ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2012 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/file_util.h" 5 #include "base/files/file_util.h"
6 6
7 #include <windows.h> 7 #include <windows.h>
8 #include <io.h> 8 #include <io.h>
9 #include <psapi.h> 9 #include <psapi.h>
10 #include <shellapi.h> 10 #include <shellapi.h>
11 #include <shlobj.h> 11 #include <shlobj.h>
12 #include <stddef.h> 12 #include <stddef.h>
13 #include <stdint.h> 13 #include <stdint.h>
14 #include <string.h>
14 #include <time.h> 15 #include <time.h>
15 #include <winsock2.h> 16 #include <winsock2.h>
16 17
17 #include <algorithm> 18 #include <algorithm>
18 #include <limits> 19 #include <limits>
19 #include <string> 20 #include <string>
21 #include <utility>
20 22
23 #include "base/base32.h"
21 #include "base/files/file_enumerator.h" 24 #include "base/files/file_enumerator.h"
22 #include "base/files/file_path.h" 25 #include "base/files/file_path.h"
23 #include "base/logging.h" 26 #include "base/logging.h"
24 #include "base/macros.h" 27 #include "base/macros.h"
25 #include "base/metrics/histogram.h" 28 #include "base/metrics/histogram.h"
26 #include "base/process/process_handle.h" 29 #include "base/process/process_handle.h"
27 #include "base/rand_util.h" 30 #include "base/rand_util.h"
28 #include "base/strings/string_number_conversions.h" 31 #include "base/strings/string_number_conversions.h"
29 #include "base/strings/string_util.h" 32 #include "base/strings/string_util.h"
30 #include "base/strings/utf_string_conversions.h" 33 #include "base/strings/utf_string_conversions.h"
31 #include "base/threading/thread_restrictions.h" 34 #include "base/threading/thread_restrictions.h"
32 #include "base/time/time.h" 35 #include "base/time/time.h"
33 #include "base/win/scoped_handle.h" 36 #include "base/win/scoped_handle.h"
34 #include "base/win/windows_version.h" 37 #include "base/win/windows_version.h"
35 38
36 namespace base { 39 namespace base {
37 40
38 namespace { 41 namespace {
39 42
40 const DWORD kFileShareAll = 43 const DWORD kFileShareAll =
41 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; 44 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
42 45
43 // Deletes all files and directories in a path. 46 // The workhorse of base::DeleteFile. This class implements a robust file and
44 // Returns false on the first failure it encounters. 47 // directory deletion strategy to work with Windows' peculiarity around file
45 bool DeleteFileRecursive(const FilePath& path, 48 // deletion -- on Windows, one does not simply delete a file. The Win32
46 const FilePath::StringType& pattern, 49 // DeleteFile function is deceptively named (though properly documented) as it
47 bool recursive) { 50 // marks a file for deletion at some unspecified time in the future when all
48 FileEnumerator traversal(path, false, 51 // handles are closed. This here workhorse accomplishes two goals: recursive
49 FileEnumerator::FILES | FileEnumerator::DIRECTORIES, 52 // deletes can succeed in the face of other software operating therein (so long
50 pattern); 53 // as they open files with SHARE_DELETE) and it's much more likely that callers
51 for (FilePath current = traversal.Next(); !current.empty(); 54 // can delete a file or directory and then immediately create another with the
52 current = traversal.Next()) { 55 // same name. This class implementes DeleteFile as follows:
53 // Try to clear the read-only bit if we find it. 56 // - Open the item to be deleted.
54 FileEnumerator::FileInfo info = traversal.GetInfo(); 57 // - Rob the item of its read-only status, if applicable.
55 if ((info.find_data().dwFileAttributes & FILE_ATTRIBUTE_READONLY) && 58 // - In the case of a directory that does not have a reparse point (i.e., a
56 (recursive || !info.IsDirectory())) { 59 // plain old directory, not a mount point or a symlinks), recursively delete
57 SetFileAttributes( 60 // everything contained therein using the strategy described here.
58 current.value().c_str(), 61 // - Paint the item with delete-on-close to make sure it is deletable.
59 info.find_data().dwFileAttributes & ~FILE_ATTRIBUTE_READONLY); 62 // - Hide the item.
60 } 63 // - Clear the delete-on-close bit so that it can...
61 64 // - Move the item to a temporary directory (with a random name).
62 if (info.IsDirectory()) { 65 // - Paint the item with delete-on-close for good.
63 if (recursive && (!DeleteFileRecursive(current, pattern, true) || 66 //
64 !RemoveDirectory(current.value().c_str()))) 67 // Failure possibilities are:
65 return false; 68 // - The item could not be opened.
66 } else if (!::DeleteFile(current.value().c_str())) { 69 // - The item's attributes could not be read.
70 // - The item was read-only and this attribute could not be cleared.
71 // - The item could not be deleted for various legitimate reasons such as it
72 // being open without SHARE_DELETE access, or the current user not having
73 // permission to delete it.
74 // - The file was moved out to the temp directory, could not be deleted, and
75 // could not be moved back to its original location. This will DCHECK in a
76 // debug build, as it is highly undesirable and so far outside of expectation.
77 //
78 // There also exists a partial success case where the item could not be moved
79 // prior to deletion but was deleted in situ. This is essentially the Win32
80 // DeleteFile behavior, also known as "better than nothing".
81 class TreeDeleter {
82 public:
83 // Deletes |path| (a file or a directory). If |recursive| is true and |path|
84 // names a directory that does not have a reparse point (i.e., is not a mount
85 // point or a symlink), then recursively deletes the contents of |path| prior
86 // to deleting |path|. Returns false if |path| was not entirely deleted.
87 static bool RobustDelete(const FilePath& path,
88 bool recursive,
89 DeleteFileMetrics* metrics);
90
91 private:
92 TreeDeleter();
93
94 // Returns a random 8.3 ASCII filename.
95 static std::string GenerateRandomFileName();
96
97 // Returns true if the serial number of the volume on which |path| resides
98 // can be obtained, equals |volume_serial_number|, and a file can be created
99 // in the directory.
100 static bool IsSuitableTemporaryDirectory(const FilePath& path,
101 DWORD volume_serial_number);
102
103 // Deletes |path| (recursively, if |recursive|) with up to 4 retries.
104 bool BeginDelete(const FilePath& path, bool recursive);
105
106 // Sets |temp_dir_path_| to the path of a directory on the same volume as
107 // |path| (opened as |to_delete|) that will be used to temporarily hold files
108 // and directories as they are being deleted.
109 void ChooseTempDir(const FilePath& path, const win::ScopedHandle& to_delete);
110
111 // Main entrypoint to delete |path|. |level| indicates the current level of
112 // recursion. |recurse|, when true, indicates that the operation should
113 // recurse into directories.
114 bool Delete(const FilePath& path, int level, bool recurse);
115
116 // Main entrypoint to the open-and-delete-on-close strategy.
117 bool DeleteOnClose(const FilePath& path, int level, bool recurse);
118
119 // Deletes |path| (a file or an empty directory) using the traditional Win32
120 // APIs.
121 bool DeleteFallback(const FilePath& path);
122
123 // Deletes |to_delete|, using |basic_info| to adjust its attributes in the
124 // process.
125 bool DoDelete(const FilePath& path,
126 int level,
127 bool recurse,
128 const win::ScopedHandle& to_delete,
129 FILE_BASIC_INFO* basic_info);
130
131 // Deletes as much of the contents of |path| as possible, returning |true|
132 // only if everything within was deleted.
133 bool DeleteContents(const FilePath& path, int level);
134
135 // Moves |to_delete| out into the temp directory of the operation.
136 // |to_delete| is expected to already have its delete-on-close attribute set.
137 // This function will clear it, move the file, and re-establish
138 // delete-on-close. Returns false if the delete-on-close attribute is not set
139 // on exit.
140 bool MoveToTemp(const FilePath& path, const win::ScopedHandle& to_delete);
141
142 // Renames the item |to_delete| to |target|.
143 bool MoveTo(const win::ScopedHandle& to_delete, const FilePath& target);
144
145 // Metrics relating to the operation.
146 DeleteFileMetrics metrics_ = DeleteFileMetrics();
147
148 // The directory into which items are to be moved immediately prior to
149 // deletion.
150 FilePath temp_dir_path_;
151
152 // The size, in bytes, of the FILE_RENAME_INFO block.
153 size_t rename_info_buffer_size_ = 0;
154
155 // Holds a FILE_RENAME_INFO when the instance will be used to move files out
156 // of their current directory prior to deletion.
157 std::unique_ptr<uint8_t> rename_info_buffer_;
158
159 DISALLOW_COPY_AND_ASSIGN(TreeDeleter);
160 };
161
162 // static
163 bool TreeDeleter::RobustDelete(const FilePath& path,
164 bool recursive,
165 DeleteFileMetrics* metrics) {
166 TreeDeleter deleter;
167 bool result = deleter.BeginDelete(MakeAbsoluteFilePath(path), recursive);
168 if (metrics)
169 *metrics = deleter.metrics_;
170 return result;
171 }
172
173 TreeDeleter::TreeDeleter() {}
174
175 // static
176 std::string TreeDeleter::GenerateRandomFileName() {
177 char random[5];
178 RandBytes(&random[0], sizeof(random));
179 return Base32Encode(StringPiece(&random[0], sizeof(random))).append(".tmp");
180 }
181
182 // static
183 bool TreeDeleter::IsSuitableTemporaryDirectory(const FilePath& path,
184 DWORD volume_serial_number) {
185 BY_HANDLE_FILE_INFORMATION info = {};
186 File file(path, (File::FLAG_OPEN | File::FLAG_SHARE_DELETE |
187 File::FLAG_BACKUP_SEMANTICS));
188 if (!file.IsValid()) {
189 PLOG(ERROR) << "Unable to get volume serial number of " << path.value();
190 return false;
191 }
192 if (!::GetFileInformationByHandle(file.GetPlatformFile(), &info) ||
193 info.dwVolumeSerialNumber != volume_serial_number) {
194 return false;
195 }
196 file.Close();
197
198 // Check that a file can be created in the directory.
199 file.Initialize(path.AppendASCII(GenerateRandomFileName()),
200 (File::FLAG_CREATE | File::FLAG_WRITE | File::FLAG_TEMPORARY |
201 File::FLAG_HIDDEN | File::FLAG_DELETE_ON_CLOSE |
202 File::FLAG_SHARE_DELETE));
203 return file.IsValid();
204 }
205
206 bool TreeDeleter::BeginDelete(const FilePath& path, bool recursive) {
207 // Repeatedly attempt to delete |path| until there is nothing left that can be
208 // deleted. Bail out after five fruitless iterations (four retries).
209 int retries_without_progress = 0;
210 while (true) {
211 int total_deleted_before = metrics_.delete_on_close_success_count +
212 metrics_.delete_file_success_count;
213 if (Delete(path, 0, recursive))
214 return true; // Yay!
215 if (metrics_.delete_on_close_success_count +
216 metrics_.delete_file_success_count >
217 total_deleted_before) {
218 // Progress is being made; reset the retry count.
219 retries_without_progress = 0;
220 } else if (++retries_without_progress == 5) {
221 // Give up after making no progress five consecutive times.
222 break;
223 }
224 ++metrics_.total_retry_count;
225 }
226
227 return false;
228 }
229
230 void TreeDeleter::ChooseTempDir(const FilePath& path,
231 const win::ScopedHandle& to_delete) {
232 DCHECK(temp_dir_path_.empty());
233
234 // Get the volume serial number of the path to be deleted.
235 BY_HANDLE_FILE_INFORMATION item_info = {};
236 if (::GetFileInformationByHandle(to_delete.Get(), &item_info)) {
237 FilePath temp_path;
238
239 // Try %TEMP%.
240 if (GetTempDir(&temp_path) &&
241 IsSuitableTemporaryDirectory(temp_path,
242 item_info.dwVolumeSerialNumber)) {
243 temp_dir_path_ = temp_path;
244 metrics_.temporary_directory_location = DeleteFileMetrics::TEMP;
245 return;
246 }
247
248 // Try X:\Temp and X:\Tmp.
249 wchar_t volume_path_name[MAX_PATH];
250 if (::GetVolumePathName(path.NormalizePathSeparators().value().c_str(),
251 volume_path_name, arraysize(volume_path_name))) {
252 static constexpr const wchar_t* kTempNames[] = {L"Temp", L"Tmp"};
253 for (const wchar_t* temp_name : kTempNames) {
254 temp_path = FilePath(volume_path_name).Append(temp_name);
255 if (IsSuitableTemporaryDirectory(temp_path,
256 item_info.dwVolumeSerialNumber)) {
257 temp_dir_path_ = temp_path;
258 metrics_.temporary_directory_location =
259 DeleteFileMetrics::VOLUME_TEMP;
260 return;
261 }
262 }
263 }
264
265 // Try the parent dir of |path|.
266 temp_path = path.DirName().DirName();
267 if (IsSuitableTemporaryDirectory(temp_path,
268 item_info.dwVolumeSerialNumber)) {
269 temp_dir_path_ = temp_path;
270 metrics_.temporary_directory_location = DeleteFileMetrics::PARENT;
271 return;
272 }
273
274 // Try the dir of |path|.
275 temp_path = path.DirName();
276 if (IsSuitableTemporaryDirectory(temp_path,
277 item_info.dwVolumeSerialNumber)) {
278 temp_dir_path_ = temp_path;
279 metrics_.temporary_directory_location = DeleteFileMetrics::ITEM;
280 return;
281 }
282 }
283
284 PLOG(ERROR) << "Failed to get file info of " << path.value();
285 DCHECK(temp_dir_path_.empty());
286 metrics_.temporary_directory_location = DeleteFileMetrics::NONE;
287 }
288
289 bool TreeDeleter::Delete(const FilePath& path, int level, bool recurse) {
290 if (DeleteOnClose(path, level, recurse)) {
291 ++metrics_.delete_on_close_success_count;
292 return true;
293 }
294 if (DeleteFallback(path)) {
295 ++metrics_.delete_file_success_count;
296 return true;
297 }
298 ++metrics_.fail_count;
299 return false;
300 }
301
302 bool TreeDeleter::DeleteOnClose(const FilePath& path, int level, bool recurse) {
303 // Open the item to be deleted with permission to hide and delete it with full
304 // sharing. Note that backup semantics are required to open a directory.
305 // Operate on a link or a mount point (implemented via reparse points) itself
306 // rather than on its target.
307 win::ScopedHandle to_delete(::CreateFile(
308 path.value().c_str(),
309 DELETE | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES,
310 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
311 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
312 nullptr));
313 if (!to_delete.IsValid()) {
314 DWORD error = ::GetLastError();
315 if (error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND)
316 return true;
317 PLOG(ERROR) << "Failed to open " << path.value() << " for deletion";
318 return false;
319 }
320
321 if (metrics_.temporary_directory_location == DeleteFileMetrics::UNDECIDED)
322 ChooseTempDir(path, to_delete);
323
324 // Remove the item's read-only bit if it is set. This is required for
325 // deletion.
326 bool read_only_set = false;
327 FILE_BASIC_INFO basic_info = {};
328 if (!::GetFileInformationByHandleEx(to_delete.Get(), FileBasicInfo,
329 &basic_info, sizeof(basic_info))) {
330 PLOG(ERROR) << "Failed to read attributes of " << path.value();
331 return false;
332 }
333 if ((basic_info.FileAttributes & FILE_ATTRIBUTE_READONLY) != 0) {
334 basic_info.FileAttributes &= ~FILE_ATTRIBUTE_READONLY;
335 if (!::SetFileInformationByHandle(to_delete.Get(), FileBasicInfo,
336 &basic_info, sizeof(basic_info))) {
337 PLOG(ERROR) << "Failed to strip read-only attribute of " << path.value();
67 return false; 338 return false;
68 } 339 }
69 } 340 read_only_set = true;
341 }
342
343 if (DoDelete(path, level, recurse, to_delete, &basic_info))
344 return true;
345
346 // Restore the item's read-only state on failure.
347 if (read_only_set) {
348 basic_info.FileAttributes |= FILE_ATTRIBUTE_READONLY;
349 if (!::SetFileInformationByHandle(to_delete.Get(), FileBasicInfo,
350 &basic_info, sizeof(basic_info))) {
351 PLOG(ERROR) << "Failed to restore read-only attribute of "
352 << path.value();
353 }
354 }
355 return false;
356 }
357
358 bool TreeDeleter::DeleteFallback(const FilePath& path) {
359 // Try a straight-up delete as a fallback. Don't bother figuring out if |path|
360 // names a file or an empty directory; just try both.
361 return ::DeleteFile(path.value().c_str()) ||
362 ::RemoveDirectory(path.value().c_str());
363 }
364
365 bool TreeDeleter::DoDelete(const FilePath& path,
366 int level,
367 bool recurse,
368 const win::ScopedHandle& to_delete,
369 FILE_BASIC_INFO* basic_info) {
370 // Recurse into this item if desired, this item is a directory, and this item
371 // does not have a reparse point (i.e., is not a mount point, a symlink, or
372 // some other directory-like thing implemented by a filesystem filter).
373 if (recurse && (basic_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 &&
374 (basic_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0 &&
375 !DeleteContents(path, level + 1)) {
376 return false;
377 }
378
379 // Check to see if it's possible to delete this item. A non-empty directory,
380 // for example, cannot be deleted.
381 FILE_DISPOSITION_INFO disposition = {TRUE}; // DeleteFile
382 if (!::SetFileInformationByHandle(to_delete.Get(), FileDispositionInfo,
383 &disposition, sizeof(disposition))) {
384 PLOG(ERROR) << "Unable to delete " << path.value();
385 return false;
386 }
387
388 // The item will now be deleted when all handles are closed. Hide it so that
389 // it appears to vanish right away and so that any other procs (e.g.,
390 // explorer.exe) observing the temp directory have a greater likelihood of
391 // not reacting when a new file suddenly appears and disappears.
392 bool hidden_set = false;
393 if ((basic_info->FileAttributes & FILE_ATTRIBUTE_HIDDEN) == 0) {
394 basic_info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
395 if (!::SetFileInformationByHandle(to_delete.Get(), FileBasicInfo,
396 basic_info, sizeof(*basic_info))) {
397 PLOG(WARNING) << "Failed to hide " << path.value();
398 }
399 hidden_set = true;
400 }
401
402 if (temp_dir_path_.empty() || MoveToTemp(path, to_delete))
403 return true;
404
405 // The item couldn't be deleted. Restore its visibility.
406 if (hidden_set) {
407 basic_info->FileAttributes &= ~FILE_ATTRIBUTE_HIDDEN;
408 if (!::SetFileInformationByHandle(to_delete.Get(), FileBasicInfo,
409 basic_info, sizeof(*basic_info))) {
410 PLOG(WARNING) << "Failed to unhide " << path.value();
411 }
412 }
413 return false;
414 }
415
416 bool TreeDeleter::DeleteContents(const FilePath& path, int level) {
417 metrics_.max_depth = std::max(metrics_.max_depth, level);
418
419 // Recursively (and greedily) delete everything in |path|.
420 bool items_failed = false;
421 FileEnumerator enumer(path, false,
422 (FileEnumerator::DIRECTORIES | FileEnumerator::FILES));
423 for (FilePath item = enumer.Next(); !item.empty(); item = enumer.Next()) {
424 if (!Delete(item, level, true /* recurse */))
425 items_failed = true;
426 }
427
428 // Report success in the absence of failures.
429 return !items_failed;
430 }
431
432 bool TreeDeleter::MoveToTemp(const FilePath& path,
433 const win::ScopedHandle& to_delete) {
434 DCHECK(!temp_dir_path_.empty());
435 // Do the shuffle to move the item out to the temp directory so that a new
436 // item with the same name can be created immediately in this directory, or
437 // so that the containing directory can be deleted immediately.
438
439 // Revoke deletion so that the item can be moved.
440 FILE_DISPOSITION_INFO disposition = {FALSE}; // DeleteFile
441 if (!::SetFileInformationByHandle(to_delete.Get(), FileDispositionInfo,
442 &disposition, sizeof(disposition))) {
443 PLOG(WARNING) << "Unable to revoke deletion of " << path.value()
444 << "; skipping move to temp";
445 return true;
446 }
447
448 // Move the file out to the temp directory. Failure to move is not a fatal
449 // failure, though it will lead to a race when deleting the containing
450 // directory. This is mitigated by retries in directory deletion.
451 bool file_moved = false;
452 int attempts = 0;
453 do {
454 file_moved =
455 MoveTo(to_delete, temp_dir_path_.AppendASCII(GenerateRandomFileName()));
456 } while (!file_moved && ++attempts < 5);
457
458 // Mark the file to be deleted on close once again.
459 disposition.DeleteFile = TRUE;
460 if (!::SetFileInformationByHandle(to_delete.Get(), FileDispositionInfo,
461 &disposition, sizeof(disposition))) {
462 // This is unexpected since the file was to be deleted moments ago, but is
463 // possible (e.g., another process has mapped it into memory).
464 PLOG(ERROR) << "Failed to mark file to be deleted on close";
465
466 if (file_moved) {
467 // Try to move the file back to where it was. If this fails, we're in the
468 // town of cats and leaving the file in the wrong place. Regardless, make
469 // a final attempt to mark the file for deletion.
470 bool file_moved_back = MoveTo(to_delete, path);
471 LONG error = ::GetLastError();
472 if (::SetFileInformationByHandle(to_delete.Get(), FileDispositionInfo,
473 &disposition, sizeof(disposition))) {
474 // Whew! The file will eventually be deleted in situ.
475 if (!file_moved_back)
476 ++metrics_.move_to_temp_count;
477 return true;
478 }
479 if (!file_moved_back) {
480 ::SetLastError(error);
481 PLOG(DFATAL) << "Failed to move item back to original location";
482 }
483 }
484 return false;
485 }
486
487 ++metrics_.move_to_temp_count;
488
70 return true; 489 return true;
71 } 490 }
491
492 bool TreeDeleter::MoveTo(const win::ScopedHandle& to_delete,
493 const FilePath& target) {
494 // Compute the proper size of the FILE_RENAME_INFO including the target path.
495 size_t path_bytes = (target.value().length() + 1) * sizeof(wchar_t);
496 size_t struct_size = offsetof(FILE_RENAME_INFO, FileName) + path_bytes;
497
498 // Allocate a new buffer if needed.
499 if (rename_info_buffer_size_ < struct_size) {
500 rename_info_buffer_.reset();
501 rename_info_buffer_.reset(new uint8_t[struct_size]);
502 rename_info_buffer_size_ = struct_size;
503 }
504
505 // Formulate a FILE_RENAME_INFO struct in the buffer.
506 FILE_RENAME_INFO* file_rename_info =
507 reinterpret_cast<FILE_RENAME_INFO*>(rename_info_buffer_.get());
508 file_rename_info->ReplaceIfExists = FALSE;
509 file_rename_info->RootDirectory = nullptr;
510 file_rename_info->FileNameLength = target.value().length();
511 ::memcpy(&file_rename_info->FileName[0], target.value().c_str(), path_bytes);
512
513 if (!::SetFileInformationByHandle(to_delete.Get(), FileRenameInfo,
514 file_rename_info, struct_size)) {
515 PLOG(ERROR) << "Failed to move item to " << target.value();
516 return false;
517 }
518 return true;
519 }
72 520
73 } // namespace 521 } // namespace
74 522
75 FilePath MakeAbsoluteFilePath(const FilePath& input) { 523 FilePath MakeAbsoluteFilePath(const FilePath& input) {
76 ThreadRestrictions::AssertIOAllowed(); 524 ThreadRestrictions::AssertIOAllowed();
77 wchar_t file_path[MAX_PATH]; 525 wchar_t file_path[MAX_PATH];
78 if (!_wfullpath(file_path, input.value().c_str(), MAX_PATH)) 526 if (!_wfullpath(file_path, input.value().c_str(), MAX_PATH))
79 return FilePath(); 527 return FilePath();
80 return FilePath(file_path); 528 return FilePath(file_path);
81 } 529 }
82 530
83 bool DeleteFile(const FilePath& path, bool recursive) { 531 bool DeleteFile(const FilePath& path, bool recursive) {
532 return DeleteFileWithMetrics(path, recursive, nullptr);
533 }
534
535 bool DeleteFileWithMetrics(const FilePath& path,
536 bool recursive,
537 DeleteFileMetrics* metrics) {
84 ThreadRestrictions::AssertIOAllowed(); 538 ThreadRestrictions::AssertIOAllowed();
85 539
540 // Wildcards are not supported.
541 DCHECK_EQ(path.BaseName().value().find_first_of(L"*?"),
542 FilePath::StringType::npos);
543
86 if (path.empty()) 544 if (path.empty())
87 return true; 545 return true;
88 546
89 if (path.value().length() >= MAX_PATH) 547 if (path.value().length() >= MAX_PATH)
90 return false; 548 return false;
91 549
92 // Handle any path with wildcards. 550 return TreeDeleter::RobustDelete(path, recursive, metrics);
93 if (path.BaseName().value().find_first_of(L"*?") !=
94 FilePath::StringType::npos) {
95 return DeleteFileRecursive(path.DirName(), path.BaseName().value(),
96 recursive);
97 }
98 DWORD attr = GetFileAttributes(path.value().c_str());
99 // We're done if we can't find the path.
100 if (attr == INVALID_FILE_ATTRIBUTES)
101 return true;
102 // We may need to clear the read-only bit.
103 if ((attr & FILE_ATTRIBUTE_READONLY) &&
104 !SetFileAttributes(path.value().c_str(),
105 attr & ~FILE_ATTRIBUTE_READONLY)) {
106 return false;
107 }
108 // Directories are handled differently if they're recursive.
109 if (!(attr & FILE_ATTRIBUTE_DIRECTORY))
110 return !!::DeleteFile(path.value().c_str());
111 // Handle a simple, single file delete.
112 if (!recursive || DeleteFileRecursive(path, L"*", true))
113 return !!RemoveDirectory(path.value().c_str());
114
115 return false;
116 } 551 }
117 552
118 bool DeleteFileAfterReboot(const FilePath& path) { 553 bool DeleteFileAfterReboot(const FilePath& path) {
119 ThreadRestrictions::AssertIOAllowed(); 554 ThreadRestrictions::AssertIOAllowed();
120 555
121 if (path.value().length() >= MAX_PATH) 556 if (path.value().length() >= MAX_PATH)
122 return false; 557 return false;
123 558
124 return MoveFileEx(path.value().c_str(), NULL, 559 return MoveFileEx(path.value().c_str(), NULL,
125 MOVEFILE_DELAY_UNTIL_REBOOT | 560 MOVEFILE_DELAY_UNTIL_REBOOT |
(...skipping 694 matching lines...) Expand 10 before | Expand all | Expand 10 after
820 // Like Move, this function is not transactional, so we just 1255 // Like Move, this function is not transactional, so we just
821 // leave the copied bits behind if deleting from_path fails. 1256 // leave the copied bits behind if deleting from_path fails.
822 // If to_path exists previously then we have already overwritten 1257 // If to_path exists previously then we have already overwritten
823 // it by now, we don't get better off by deleting the new bits. 1258 // it by now, we don't get better off by deleting the new bits.
824 } 1259 }
825 return false; 1260 return false;
826 } 1261 }
827 1262
828 } // namespace internal 1263 } // namespace internal
829 } // namespace base 1264 } // namespace base
OLDNEW
« no previous file with comments | « base/files/file_util_unittest.cc ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698