 Chromium Code Reviews
 Chromium Code Reviews Issue 2545283002:
  A robust base::DeleteFile.
    
  
    Issue 2545283002:
  A robust base::DeleteFile. 
  | OLD | NEW | 
|---|---|
| 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> | 
| 20 | 21 | 
| 22 #include "base/base32.h" | |
| 21 #include "base/files/file_enumerator.h" | 23 #include "base/files/file_enumerator.h" | 
| 22 #include "base/files/file_path.h" | 24 #include "base/files/file_path.h" | 
| 23 #include "base/logging.h" | 25 #include "base/logging.h" | 
| 24 #include "base/macros.h" | 26 #include "base/macros.h" | 
| 25 #include "base/metrics/histogram.h" | 27 #include "base/metrics/histogram.h" | 
| 26 #include "base/process/process_handle.h" | 28 #include "base/process/process_handle.h" | 
| 27 #include "base/rand_util.h" | 29 #include "base/rand_util.h" | 
| 28 #include "base/strings/string_number_conversions.h" | 30 #include "base/strings/string_number_conversions.h" | 
| 29 #include "base/strings/string_util.h" | 31 #include "base/strings/string_util.h" | 
| 30 #include "base/strings/utf_string_conversions.h" | 32 #include "base/strings/utf_string_conversions.h" | 
| 31 #include "base/threading/thread_restrictions.h" | 33 #include "base/threading/thread_restrictions.h" | 
| 32 #include "base/time/time.h" | 34 #include "base/time/time.h" | 
| 33 #include "base/win/scoped_handle.h" | 35 #include "base/win/scoped_handle.h" | 
| 34 #include "base/win/windows_version.h" | 36 #include "base/win/windows_version.h" | 
| 35 | 37 | 
| 36 namespace base { | 38 namespace base { | 
| 37 | 39 | 
| 38 namespace { | 40 namespace { | 
| 39 | 41 | 
| 40 const DWORD kFileShareAll = | 42 const DWORD kFileShareAll = | 
| 41 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; | 43 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; | 
| 42 | 44 | 
| 43 // Deletes all files and directories in a path. | 45 // The workhorse of base::DeleteFile. This class implements a robust file and | 
| 
Will Harris
2016/12/07 19:47:43
how much of this comment should be exposed via the
 
grt (UTC plus 2)
2016/12/07 20:56:06
Updated!
 | |
| 44 // Returns false on the first failure it encounters. | 46 // directory deletion strategy to work with Windows' pecurlarity around file | 
| 
Sigurður Ásgeirsson
2016/12/07 16:29:18
nit: pecurlarity?
 
grt (UTC plus 2)
2016/12/07 20:56:06
what, you don't have that word in Icelandic? :-)
 | |
| 45 bool DeleteFileRecursive(const FilePath& path, | 47 // deletion -- on Windows, one does not simply delete a file. The Win32 | 
| 46 const FilePath::StringType& pattern, | 48 // DeleteFile function is deceptively named (though properly documented) as it | 
| 47 bool recursive) { | 49 // marks a file for deletion at some unspecified time in the future when all | 
| 48 FileEnumerator traversal(path, false, | 50 // handles are closed. This here workhorse accomplishes two goals: recursive | 
| 49 FileEnumerator::FILES | FileEnumerator::DIRECTORIES, | 51 // deletes can succeed in the face of other software operating therein (so long | 
| 50 pattern); | 52 // as they open files with SHARE_DELETE) and it's much more likely that callers | 
| 51 for (FilePath current = traversal.Next(); !current.empty(); | 53 // can delete a file or directory and then immediately create another with the | 
| 52 current = traversal.Next()) { | 54 // same name. This class implementes DeleteFile as follows: | 
| 53 // Try to clear the read-only bit if we find it. | 55 // - Open the item to be deleted. | 
| 
Sigurður Ásgeirsson
2016/12/07 16:29:19
This sounds like a single post-order traversal on
 
grt (UTC plus 2)
2016/12/07 20:56:06
From the caller's point of view, I'm not sure what
 | |
| 54 FileEnumerator::FileInfo info = traversal.GetInfo(); | 56 // - Rob the item of its read-only status, if applicable. | 
| 55 if ((info.find_data().dwFileAttributes & FILE_ATTRIBUTE_READONLY) && | 57 // - In the case of a directory that does not have a reparse point (i.e., a | 
| 56 (recursive || !info.IsDirectory())) { | 58 // plain old dirctory, not a mount point or a symlinks), recursively delete | 
| 
Sigurður Ásgeirsson
2016/12/07 16:29:18
nit: dirctory
 
grt (UTC plus 2)
2016/12/07 20:56:06
Done.
 | |
| 57 SetFileAttributes( | 59 // everything contained therein using the strategy described here. | 
| 58 current.value().c_str(), | 60 // - Paint the item with delete-on-close to make sure it is deletable. | 
| 59 info.find_data().dwFileAttributes & ~FILE_ATTRIBUTE_READONLY); | 61 // - Hide the item. | 
| 60 } | 62 // - Clear the delete-on-close bit so that it can... | 
| 61 | 63 // - Move the item up one directory (with a random name). | 
| 
Will Harris
2016/12/07 19:47:43
should the public header file describe that one of
 
grt (UTC plus 2)
2016/12/07 20:56:06
It's not a constraint. If the caller has write acc
 | |
| 62 if (info.IsDirectory()) { | 64 // - Paint the item with delete-on-close for good. | 
| 63 if (recursive && (!DeleteFileRecursive(current, pattern, true) || | 65 // | 
| 64 !RemoveDirectory(current.value().c_str()))) | 66 // Failure possibilities are: | 
| 65 return false; | 67 // - The item could not be opened. | 
| 66 } else if (!::DeleteFile(current.value().c_str())) { | 68 // - The item's attributes could not be read. | 
| 69 // - The item was read-only and this attribute could not be cleared. | |
| 70 // - The item could not be deleted for various legitimate reasons such as it | |
| 71 // being open without SHARE_DELETE access, or the current user not having | |
| 72 // permission to delete it. | |
| 73 // - The file was moved out to the temp directory, could not be deleted, and | |
| 74 // could not be moved back to its original location. This will DCHECK in a | |
| 75 // debug build, as it is highly undesirable and so far outside of expectation. | |
| 76 // | |
| 77 // There also exists a partial success case where the item could not be moved | |
| 78 // prior to deletion but was deleted in situ. This is essentially the Win32 | |
| 79 // DeleteFile behavior, also known as "better than nothing". | |
| 80 class TreeDeleter { | |
| 
Sigurður Ásgeirsson
2016/12/07 16:29:18
Maybe you'd want to expose this class for more nua
 
grt (UTC plus 2)
2016/12/07 20:56:06
I was mulling over metrics options. My inclination
 | |
| 81 public: | |
| 82 // Deletes a single item (a file, empty directory, mount point, symlink, etc). | |
| 83 // Returns false if the item could not be deleted. | |
| 84 static bool DeleteItem(const FilePath& path); | |
| 85 | |
| 86 // Recursively deletes |path| and its contents if |path| is a directory and | |
| 87 // does not have a reparse point. | |
| 88 static bool DeleteRecursive(const FilePath& path); | |
| 89 | |
| 90 private: | |
| 91 TreeDeleter(); | |
| 92 | |
| 93 // Sets |temp_dir_path_| to the path of a directory on the same volume as | |
| 94 // |path| (opened as |to_delete|) that will be used to temporarily hold files | |
| 95 // and directories as they are being deleted. | |
| 96 void ChooseTempDirIfNotChosen(const FilePath& path, | |
| 97 const win::ScopedHandle& to_delete); | |
| 98 | |
| 99 // Main entrypoint to delete |path|. |recurse|, when true, indicates that an | |
| 100 // instance created for recursion should recurse into directories. | |
| 101 bool Delete(const FilePath& path, bool recurse); | |
| 102 | |
| 103 // Deletes |to_delete|, using |basic_info| to adjust its attributes in the | |
| 104 // process. | |
| 105 bool DoDelete(const FilePath& path, | |
| 106 bool recurse, | |
| 107 const win::ScopedHandle& to_delete, | |
| 108 FILE_BASIC_INFO* basic_info); | |
| 109 | |
| 110 // Deletes as much of the contents of |path| as possible, returning |true| | |
| 111 // only if everything within was deleted. | |
| 112 bool DeleteContents(const FilePath& path); | |
| 113 | |
| 114 // Moves |to_delete| out into the temp directory of the operation. | |
| 115 // |to_delete| is expected to already have its delete-on-close attribute set. | |
| 116 // This function will clear it, move the file, and re-establish | |
| 117 // delete-on-close. Returns false if the delete-on-close attribute is not set | |
| 118 // on exit. | |
| 119 bool MoveToTemp(const FilePath& path, const win::ScopedHandle& to_delete); | |
| 120 | |
| 121 // Renames the item |to_delete| to |target|. | |
| 122 bool MoveTo(const win::ScopedHandle& to_delete, const FilePath& target); | |
| 123 | |
| 124 // Returns true if the serial number of the volume on which |path| resides | |
| 125 // can be obtained and equals |volume_serial_number|. | |
| 126 static bool VolumeSerialNumberIs(const FilePath& path, | |
| 127 ULONGLONG volume_serial_number); | |
| 128 | |
| 129 // The directory into which items are to be moved immediately prior to | |
| 130 // deletion. | |
| 131 FilePath temp_dir_path_; | |
| 132 | |
| 133 // The size, in bytes, of the FILE_RENAME_INFO block. | |
| 134 size_t rename_info_buffer_size_ = 0; | |
| 135 | |
| 136 // Holds a FILE_RENAME_INFO when the instance will be used to move files out | |
| 137 // of their current directory prior to deletion. | |
| 138 std::unique_ptr<uint8_t> rename_info_buffer_; | |
| 139 | |
| 140 DISALLOW_COPY_AND_ASSIGN(TreeDeleter); | |
| 141 }; | |
| 142 | |
| 143 // static | |
| 144 bool TreeDeleter::DeleteItem(const FilePath& path) { | |
| 145 return TreeDeleter().Delete(MakeAbsoluteFilePath(path), false /* !recurse */); | |
| 146 } | |
| 147 | |
| 148 // static | |
| 149 bool TreeDeleter::DeleteRecursive(const FilePath& path) { | |
| 150 return TreeDeleter().Delete(MakeAbsoluteFilePath(path), true /* recurse */); | |
| 151 } | |
| 152 | |
| 153 TreeDeleter::TreeDeleter() {} | |
| 154 | |
| 155 void TreeDeleter::ChooseTempDirIfNotChosen(const FilePath& path, | |
| 156 const win::ScopedHandle& to_delete) { | |
| 157 if (!temp_dir_path_.empty()) | |
| 158 return; | |
| 159 | |
| 160 // Use the dir of |path| if all else fails. | |
| 161 temp_dir_path_ = path.DirName(); | |
| 162 | |
| 163 // Get the volume serial number of the path to be deleted. | |
| 164 FILE_ID_INFO item_id_info = {}; | |
| 
grt (UTC plus 2)
2016/12/07 20:56:06
turns out this wasn't supported on Win7.
 | |
| 165 if (!::GetFileInformationByHandleEx(to_delete.Get(), FileIdInfo, | |
| 166 &item_id_info, sizeof(item_id_info))) { | |
| 167 PLOG(ERROR) << "Failed to get file ID info of " << path.value(); | |
| 168 return; | |
| 169 } | |
| 170 | |
| 171 FilePath temp_path; | |
| 172 | |
| 173 // Try %TEMP%. | |
| 174 if (GetTempDir(&temp_path) && | |
| 175 VolumeSerialNumberIs(temp_path, item_id_info.VolumeSerialNumber)) { | |
| 176 temp_dir_path_ = temp_path; | |
| 177 return; | |
| 178 } | |
| 179 | |
| 180 // Try X:\Temp and X:\Tmp. | |
| 181 wchar_t volume_path_name[MAX_PATH]; | |
| 182 if (::GetVolumePathName(path.NormalizePathSeparators().value().c_str(), | |
| 183 volume_path_name, arraysize(volume_path_name))) { | |
| 184 static constexpr const wchar_t* kTempNames[] = {L"Temp", L"Tmp"}; | |
| 185 for (const wchar_t* temp_name : kTempNames) { | |
| 186 temp_path = FilePath(volume_path_name).Append(temp_name); | |
| 187 if (VolumeSerialNumberIs(temp_path, item_id_info.VolumeSerialNumber)) { | |
| 188 temp_dir_path_ = temp_path; | |
| 
Sigurður Ásgeirsson
2016/12/07 16:29:18
Do you also need to test whether you can create or
 
grt (UTC plus 2)
2016/12/07 20:56:06
Hmm. Yeah, that makes sense. If X:\Temp can't be w
 | |
| 189 return; | |
| 190 } | |
| 191 } | |
| 192 } | |
| 193 | |
| 194 // Try the parent dir of |path|. | |
| 195 temp_path = path.DirName().DirName(); | |
| 196 if (VolumeSerialNumberIs(temp_path, item_id_info.VolumeSerialNumber)) | |
| 197 temp_dir_path_ = temp_path; | |
| 198 } | |
| 199 | |
| 200 bool TreeDeleter::Delete(const FilePath& path, bool recurse) { | |
| 201 // Open the item to be deleted with permission to hide and delete it with full | |
| 202 // sharing. Note that backup semantics are required to open a directory. | |
| 203 // Operate on a link or a mount point (implemented via reparse points) itself | |
| 204 // rather than on its target. | |
| 205 win::ScopedHandle to_delete(::CreateFile( | |
| 206 path.value().c_str(), | |
| 207 DELETE | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES, | |
| 208 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, | |
| 209 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, | |
| 210 nullptr)); | |
| 211 if (!to_delete.IsValid()) { | |
| 212 DWORD error = ::GetLastError(); | |
| 213 if (error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND) | |
| 214 return true; | |
| 215 // Try a straight-up delete as a fallback. | |
| 216 if (::DeleteFile(path.value().c_str())) | |
| 217 return true; | |
| 218 ::SetLastError(error); | |
| 219 PLOG(ERROR) << "Failed to open " << path.value() << " for deletion"; | |
| 220 return false; | |
| 221 } | |
| 222 | |
| 223 ChooseTempDirIfNotChosen(path, to_delete); | |
| 
Sigurður Ásgeirsson
2016/12/07 16:29:18
nit: EnsureTempDirChosen?
 
grt (UTC plus 2)
2016/12/07 20:56:06
Resolved the odd name otherwise.
 | |
| 224 | |
| 225 // Remove the item's read-only bit if it is set. This is required for | |
| 226 // deletion. | |
| 227 bool read_only_set = false; | |
| 228 FILE_BASIC_INFO basic_info = {}; | |
| 229 if (!::GetFileInformationByHandleEx(to_delete.Get(), FileBasicInfo, | |
| 230 &basic_info, sizeof(basic_info))) { | |
| 231 PLOG(ERROR) << "Failed to read attributes of " << path.value(); | |
| 232 return false; | |
| 233 } | |
| 234 if ((basic_info.FileAttributes & FILE_ATTRIBUTE_READONLY) != 0) { | |
| 235 basic_info.FileAttributes &= ~FILE_ATTRIBUTE_READONLY; | |
| 236 if (!::SetFileInformationByHandle(to_delete.Get(), FileBasicInfo, | |
| 237 &basic_info, sizeof(basic_info))) { | |
| 238 PLOG(ERROR) << "Failed to strip read-only attribute of " << path.value(); | |
| 67 return false; | 239 return false; | 
| 68 } | 240 } | 
| 69 } | 241 read_only_set = true; | 
| 242 } | |
| 243 | |
| 244 if (DoDelete(path, recurse, to_delete, &basic_info)) | |
| 245 return true; | |
| 246 | |
| 247 // Restore the item's read-only state on failure. | |
| 248 if (read_only_set) { | |
| 249 basic_info.FileAttributes |= FILE_ATTRIBUTE_READONLY; | |
| 250 if (!::SetFileInformationByHandle(to_delete.Get(), FileBasicInfo, | |
| 251 &basic_info, sizeof(basic_info))) { | |
| 252 PLOG(ERROR) << "Failed to restore read-only attribute of " | |
| 253 << path.value(); | |
| 254 } | |
| 255 } | |
| 256 return false; | |
| 257 } | |
| 258 | |
| 259 bool TreeDeleter::DoDelete(const FilePath& path, | |
| 260 bool recurse, | |
| 261 const win::ScopedHandle& to_delete, | |
| 262 FILE_BASIC_INFO* basic_info) { | |
| 263 // Recurse into this item if desired, this item is a directory, and this item | |
| 264 // does not have a reparse point (i.e., is not a mount point, a symlink, or | |
| 265 // some other directory-like thing implemented by a filesystem filter). | |
| 266 if (recurse && (basic_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 && | |
| 267 (basic_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0 && | |
| 268 !DeleteContents(path)) { | |
| 269 return false; | |
| 270 } | |
| 271 | |
| 272 // Check to see if it's possible to delete this item. A non-empty directory, | |
| 273 // for example, cannot be deleted. | |
| 274 FILE_DISPOSITION_INFO disposition = {TRUE}; // DeleteFile | |
| 275 if (!::SetFileInformationByHandle(to_delete.Get(), FileDispositionInfo, | |
| 276 &disposition, sizeof(disposition))) { | |
| 277 PLOG(ERROR) << "Unable to delete " << path.value(); | |
| 278 return false; | |
| 279 } | |
| 280 | |
| 281 // The item will now be deleted when all handles are closed. Hide it so that | |
| 282 // it appears to vanish right away and so that any other procs (e.g., | |
| 283 // explorer.exe) observing the temp directory have a greater liklihood of | |
| 
Sigurður Ásgeirsson
2016/12/07 16:29:18
nit: likelihood?
 
grt (UTC plus 2)
2016/12/07 20:56:06
Done.
(BTW: Damn, you're good. :-) )
 | |
| 284 // not reacting when a new file suddenly appears and disappears. | |
| 285 bool hidden_set = false; | |
| 286 if ((basic_info->FileAttributes & FILE_ATTRIBUTE_HIDDEN) == 0) { | |
| 287 basic_info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN; | |
| 288 if (!::SetFileInformationByHandle(to_delete.Get(), FileBasicInfo, | |
| 289 basic_info, sizeof(*basic_info))) { | |
| 290 PLOG(WARNING) << "Failed to hide " << path.value(); | |
| 291 } | |
| 292 hidden_set = true; | |
| 293 } | |
| 294 | |
| 295 if (MoveToTemp(path, to_delete)) | |
| 296 return true; | |
| 297 | |
| 298 // The item couldn't be deleted. Restore its visibility. | |
| 299 if (hidden_set) { | |
| 300 basic_info->FileAttributes &= ~FILE_ATTRIBUTE_HIDDEN; | |
| 301 if (!::SetFileInformationByHandle(to_delete.Get(), FileBasicInfo, | |
| 302 basic_info, sizeof(*basic_info))) { | |
| 303 PLOG(WARNING) << "Failed to unhide " << path.value(); | |
| 304 } | |
| 305 } | |
| 306 return false; | |
| 307 } | |
| 308 | |
| 309 bool TreeDeleter::DeleteContents(const FilePath& path) { | |
| 310 // Recurse through all subdirectories to clear them out. Ignore errors during | |
| 311 // this pass -- they will be reported if the directories themselves cannot be | |
| 312 // deleted below. | |
| 313 { | |
| 314 FileEnumerator enumer(path, false, FileEnumerator::DIRECTORIES); | |
| 315 for (FilePath item = enumer.Next(); !item.empty(); item = enumer.Next()) | |
| 316 Delete(item, true /* recurse */); | |
| 317 } | |
| 318 | |
| 319 // Now that the contents of all subdirectories have been cleared, repeatedly | |
| 320 // pass over the contents of this directory until there is nothing left that | |
| 321 // can be deleted. Bail out after five fruitless iterations. This is a | |
| 322 // mitigation for the failure mode where the item could not be moved out to | |
| 323 // the temp directory before deletion. | |
| 
Sigurður Ásgeirsson
2016/12/07 16:29:18
ah - oki - so failure to move to the temp dir is n
 
grt (UTC plus 2)
2016/12/07 20:56:06
Not fatal. I've improved things a bit so that the
 | |
| 324 bool items_failed; | |
| 325 int retries = 0; | |
| 326 do { | |
| 327 items_failed = false; | |
| 328 FileEnumerator enumer( | |
| 329 path, false, (FileEnumerator::DIRECTORIES | FileEnumerator::FILES)); | |
| 330 for (FilePath item = enumer.Next(); !item.empty(); item = enumer.Next()) { | |
| 331 if (Delete(item, false /* !recurse */)) | |
| 332 retries = 0; // Reset the retry count on any success. | |
| 333 else | |
| 334 items_failed = true; | |
| 335 } | |
| 336 } while (items_failed && ++retries < 5); | |
| 337 | |
| 338 // Report success if the last pass encountered no errors. | |
| 339 return !items_failed; | |
| 340 } | |
| 341 | |
| 342 bool TreeDeleter::MoveToTemp(const FilePath& path, | |
| 343 const win::ScopedHandle& to_delete) { | |
| 344 DCHECK(!temp_dir_path_.empty()); | |
| 345 | |
| 346 // Do the shuffle to move the item out to the temp directory so that a new | |
| 347 // item with the same name can be created immediately in this directory, or | |
| 348 // so that the containing directory can be deleted immediately. | |
| 349 | |
| 350 // Revoke deletion so that the item can be moved. | |
| 351 FILE_DISPOSITION_INFO disposition = {FALSE}; // DeleteFile | |
| 352 if (!::SetFileInformationByHandle(to_delete.Get(), FileDispositionInfo, | |
| 353 &disposition, sizeof(disposition))) { | |
| 354 PLOG(WARNING) << "Unable to revoke deletion of " << path.value() | |
| 355 << "; skipping move to temp"; | |
| 356 return true; | |
| 357 } | |
| 358 | |
| 359 // Move the file out to the temp directory. Failure to move is not a fatal | |
| 360 // failure, though it will lead to a race when deleting the containing | |
| 361 // directory. This is mitigated by retries in directory deletion. | |
| 362 bool file_moved = false; | |
| 363 int attempts = 0; | |
| 364 do { | |
| 365 char random[5]; | |
| 366 base::RandBytes(&random[0], sizeof(random)); | |
| 367 file_moved = MoveTo( | |
| 368 to_delete, | |
| 369 temp_dir_path_.AppendASCII( | |
| 370 base::Base32Encode(base::StringPiece(&random[0], sizeof(random))) | |
| 371 .append(".tmp"))); | |
| 372 } while (!file_moved && ++attempts < 5); | |
| 373 | |
| 374 // Mark the file to be deleted on close once again. | |
| 375 disposition.DeleteFile = TRUE; | |
| 376 if (!::SetFileInformationByHandle(to_delete.Get(), FileDispositionInfo, | |
| 377 &disposition, sizeof(disposition))) { | |
| 378 // This is highly unexpected since the file was to be deleted moments ago. | |
| 
Sigurður Ásgeirsson
2016/12/07 16:29:19
I could see this happen if there are things on the
 
grt (UTC plus 2)
2016/12/07 20:56:06
We're doing this on a handle that we opened with D
 
Sigurður Ásgeirsson
2016/12/08 14:29:26
Use the source, (young) Padawan <https://github.co
 | |
| 379 PLOG(ERROR) << "Failed to mark file to be deleted on close"; | |
| 380 | |
| 381 if (file_moved) { | |
| 382 // Try to move the file back to where it was. If this fails, we're in the | |
| 383 // town of cats and leaving the file in the wrong place. Regardless, make | |
| 384 // a final attempt to mark the file for deletion. | |
| 385 bool file_moved_back = MoveTo(to_delete, path); | |
| 386 LONG error = ::GetLastError(); | |
| 387 if (::SetFileInformationByHandle(to_delete.Get(), FileDispositionInfo, | |
| 388 &disposition, sizeof(disposition))) { | |
| 389 // Whew! The file will eventually be deleted in situ. | |
| 390 return true; | |
| 391 } | |
| 392 if (!file_moved_back) { | |
| 393 ::SetLastError(error); | |
| 394 PLOG(DFATAL) << "Failed to move item back to original location"; | |
| 395 } | |
| 396 } | |
| 397 return false; | |
| 398 } | |
| 399 | |
| 70 return true; | 400 return true; | 
| 71 } | 401 } | 
| 72 | 402 | 
| 403 bool TreeDeleter::MoveTo(const win::ScopedHandle& to_delete, | |
| 404 const FilePath& target) { | |
| 405 // Compute the proper size of the FILE_RENAME_INFO including the target path. | |
| 406 size_t path_bytes = (target.value().length() + 1) * sizeof(wchar_t); | |
| 407 size_t struct_size = offsetof(FILE_RENAME_INFO, FileName) + path_bytes; | |
| 408 | |
| 409 // Allocate a new buffer if needed. | |
| 410 if (rename_info_buffer_size_ < struct_size) { | |
| 411 rename_info_buffer_.reset(); | |
| 412 rename_info_buffer_.reset(new uint8_t[struct_size]); | |
| 413 rename_info_buffer_size_ = struct_size; | |
| 414 } | |
| 415 | |
| 416 // Formulate a FILE_RENAME_INFO struct in the buffer. | |
| 417 FILE_RENAME_INFO* file_rename_info = | |
| 418 reinterpret_cast<FILE_RENAME_INFO*>(rename_info_buffer_.get()); | |
| 419 file_rename_info->ReplaceIfExists = FALSE; | |
| 420 file_rename_info->RootDirectory = nullptr; | |
| 421 file_rename_info->FileNameLength = target.value().length(); | |
| 422 ::memcpy(&file_rename_info->FileName[0], target.value().c_str(), path_bytes); | |
| 423 | |
| 424 if (!::SetFileInformationByHandle(to_delete.Get(), FileRenameInfo, | |
| 425 file_rename_info, struct_size)) { | |
| 426 PLOG(ERROR) << "Failed to move item to " << target.value(); | |
| 427 return false; | |
| 428 } | |
| 429 return true; | |
| 430 } | |
| 431 | |
| 432 // static | |
| 433 bool TreeDeleter::VolumeSerialNumberIs(const FilePath& path, | |
| 434 ULONGLONG volume_serial_number) { | |
| 435 FILE_ID_INFO id_info = {}; | |
| 436 File file(path, (File::FLAG_OPEN | File::FLAG_SHARE_DELETE | | |
| 437 File::FLAG_BACKUP_SEMANTICS)); | |
| 438 if (!file.IsValid()) { | |
| 439 PLOG(ERROR) << "Unable to get volume serial number of " << path.value(); | |
| 440 return false; | |
| 441 } | |
| 442 return (::GetFileInformationByHandleEx(file.GetPlatformFile(), FileIdInfo, | |
| 443 &id_info, sizeof(id_info)) && | |
| 444 id_info.VolumeSerialNumber == volume_serial_number); | |
| 445 } | |
| 446 | |
| 73 } // namespace | 447 } // namespace | 
| 74 | 448 | 
| 75 FilePath MakeAbsoluteFilePath(const FilePath& input) { | 449 FilePath MakeAbsoluteFilePath(const FilePath& input) { | 
| 76 ThreadRestrictions::AssertIOAllowed(); | 450 ThreadRestrictions::AssertIOAllowed(); | 
| 77 wchar_t file_path[MAX_PATH]; | 451 wchar_t file_path[MAX_PATH]; | 
| 78 if (!_wfullpath(file_path, input.value().c_str(), MAX_PATH)) | 452 if (!_wfullpath(file_path, input.value().c_str(), MAX_PATH)) | 
| 79 return FilePath(); | 453 return FilePath(); | 
| 80 return FilePath(file_path); | 454 return FilePath(file_path); | 
| 81 } | 455 } | 
| 82 | 456 | 
| 83 bool DeleteFile(const FilePath& path, bool recursive) { | 457 bool DeleteFile(const FilePath& path, bool recursive) { | 
| 84 ThreadRestrictions::AssertIOAllowed(); | 458 ThreadRestrictions::AssertIOAllowed(); | 
| 85 | 459 | 
| 460 // Wildcards are not supported. | |
| 461 DCHECK_EQ(path.BaseName().value().find_first_of(L"*?"), | |
| 462 FilePath::StringType::npos); | |
| 463 | |
| 86 if (path.empty()) | 464 if (path.empty()) | 
| 87 return true; | 465 return true; | 
| 88 | 466 | 
| 89 if (path.value().length() >= MAX_PATH) | 467 if (path.value().length() >= MAX_PATH) | 
| 90 return false; | 468 return false; | 
| 91 | 469 | 
| 92 // Handle any path with wildcards. | 470 return recursive ? TreeDeleter::DeleteRecursive(path) | 
| 93 if (path.BaseName().value().find_first_of(L"*?") != | 471 : TreeDeleter::DeleteItem(path); | 
| 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 } | 472 } | 
| 117 | 473 | 
| 118 bool DeleteFileAfterReboot(const FilePath& path) { | 474 bool DeleteFileAfterReboot(const FilePath& path) { | 
| 119 ThreadRestrictions::AssertIOAllowed(); | 475 ThreadRestrictions::AssertIOAllowed(); | 
| 120 | 476 | 
| 121 if (path.value().length() >= MAX_PATH) | 477 if (path.value().length() >= MAX_PATH) | 
| 122 return false; | 478 return false; | 
| 123 | 479 | 
| 124 return MoveFileEx(path.value().c_str(), NULL, | 480 return MoveFileEx(path.value().c_str(), NULL, | 
| 125 MOVEFILE_DELAY_UNTIL_REBOOT | | 481 MOVEFILE_DELAY_UNTIL_REBOOT | | 
| (...skipping 697 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 823 // Like Move, this function is not transactional, so we just | 1179 // Like Move, this function is not transactional, so we just | 
| 824 // leave the copied bits behind if deleting from_path fails. | 1180 // leave the copied bits behind if deleting from_path fails. | 
| 825 // If to_path exists previously then we have already overwritten | 1181 // If to_path exists previously then we have already overwritten | 
| 826 // it by now, we don't get better off by deleting the new bits. | 1182 // it by now, we don't get better off by deleting the new bits. | 
| 827 } | 1183 } | 
| 828 return false; | 1184 return false; | 
| 829 } | 1185 } | 
| 830 | 1186 | 
| 831 } // namespace internal | 1187 } // namespace internal | 
| 832 } // namespace base | 1188 } // namespace base | 
| OLD | NEW |