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

Side by Side Diff: base/file_util_win.cc

Issue 5754002: Moving away from shell api to support long path names on windows for filesystem. (Closed) Base URL: svn://chrome-svn/chrome/trunk/src/
Patch Set: '' Created 10 years 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 | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2010 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2010 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/file_util.h" 5 #include "base/file_util.h"
6 6
7 #include <windows.h> 7 #include <windows.h>
8 #include <propvarutil.h> 8 #include <propvarutil.h>
9 #include <psapi.h> 9 #include <psapi.h>
10 #include <shellapi.h> 10 #include <shellapi.h>
(...skipping 15 matching lines...) Expand all
26 #include "base/win/scoped_comptr.h" 26 #include "base/win/scoped_comptr.h"
27 #include "base/win/windows_version.h" 27 #include "base/win/windows_version.h"
28 28
29 namespace file_util { 29 namespace file_util {
30 30
31 namespace { 31 namespace {
32 32
33 const DWORD kFileShareAll = 33 const DWORD kFileShareAll =
34 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; 34 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
35 35
36 bool RemoveReadOnlyAttribute(const FilePath& path) {
37 // This helper for DeleteFile which can fail for read-only files.
38 DWORD attributes = ::GetFileAttributes(path.value().c_str());
39 if (attributes == INVALID_FILE_ATTRIBUTES)
40 return false;
41 if (attributes & FILE_ATTRIBUTE_READONLY) {
42 ::SetFileAttributes(path.value().c_str(),
43 attributes &~ FILE_ATTRIBUTE_READONLY);
44 }
45 return true;
46 }
47
36 // Helper for NormalizeFilePath(), defined below. 48 // Helper for NormalizeFilePath(), defined below.
37 bool DevicePathToDriveLetterPath(const FilePath& device_path, 49 bool DevicePathToDriveLetterPath(const FilePath& device_path,
38 FilePath* drive_letter_path) { 50 FilePath* drive_letter_path) {
39 base::ThreadRestrictions::AssertIOAllowed(); 51 base::ThreadRestrictions::AssertIOAllowed();
40 52
41 // Get the mapping of drive letters to device paths. 53 // Get the mapping of drive letters to device paths.
42 const int kDriveMappingSize = 1024; 54 const int kDriveMappingSize = 1024;
43 wchar_t drive_mapping[kDriveMappingSize] = {'\0'}; 55 wchar_t drive_mapping[kDriveMappingSize] = {'\0'};
44 if (!::GetLogicalDriveStrings(kDriveMappingSize - 1, drive_mapping)) { 56 if (!::GetLogicalDriveStrings(kDriveMappingSize - 1, drive_mapping)) {
45 LOG(ERROR) << "Failed to get drive mapping."; 57 LOG(ERROR) << "Failed to get drive mapping.";
(...skipping 79 matching lines...) Expand 10 before | Expand all | Expand 10 after
125 } while (FindNextFile(find_handle, &find_file_data)); 137 } while (FindNextFile(find_handle, &find_file_data));
126 FindClose(find_handle); 138 FindClose(find_handle);
127 } 139 }
128 140
129 return file_count; 141 return file_count;
130 } 142 }
131 143
132 bool Delete(const FilePath& path, bool recursive) { 144 bool Delete(const FilePath& path, bool recursive) {
133 base::ThreadRestrictions::AssertIOAllowed(); 145 base::ThreadRestrictions::AssertIOAllowed();
134 146
135 if (path.value().length() >= MAX_PATH) 147 base::PlatformFileInfo file_info;
136 return false; 148 if (!GetFileInfo(path, &file_info))
149 return true;
137 150
138 if (!recursive) { 151 if (!file_info.is_directory) {
139 // If not recursing, then first check to see if |path| is a directory. 152 if (!RemoveReadOnlyAttribute(path))
140 // If it is, then remove it with RemoveDirectory. 153 return false;
141 base::PlatformFileInfo file_info; 154 return (DeleteFile(path.value().c_str()) != 0);
142 if (GetFileInfo(path, &file_info) && file_info.is_directory)
143 return RemoveDirectory(path.value().c_str()) != 0;
144
145 // Otherwise, it's a file, wildcard or non-existant. Try DeleteFile first
146 // because it should be faster. If DeleteFile fails, then we fall through
147 // to SHFileOperation, which will do the right thing.
148 if (DeleteFile(path.value().c_str()) != 0)
149 return true;
150 } 155 }
151 156
152 // SHFILEOPSTRUCT wants the path to be terminated with two NULLs, 157 if (!recursive)
153 // so we have to use wcscpy because wcscpy_s writes non-NULLs 158 return RemoveDirectory(path.value().c_str()) != 0;
154 // into the rest of the buffer.
155 wchar_t double_terminated_path[MAX_PATH + 1] = {0};
156 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
157 wcscpy(double_terminated_path, path.value().c_str());
158 159
159 SHFILEOPSTRUCT file_operation = {0}; 160 // Matches posix version of iterating directories.
160 file_operation.wFunc = FO_DELETE; 161 bool success = true;
161 file_operation.pFrom = double_terminated_path; 162 std::stack<FilePath::StringType> directories;
162 file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION; 163 directories.push(path.value());
163 if (!recursive) 164 FileEnumerator traversal(path, true, static_cast<FileEnumerator::FILE_TYPE>(
164 file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY; 165 FileEnumerator::FILES | FileEnumerator::DIRECTORIES));
165 int err = SHFileOperation(&file_operation);
166 166
167 // Since we're passing flags to the operation telling it to be silent, 167 for (FilePath current = traversal.Next(); success && !current.empty();
168 // it's possible for the operation to be aborted/cancelled without err 168 current = traversal.Next()) {
169 // being set (although MSDN doesn't give any scenarios for how this can 169 FileEnumerator::FindInfo info;
170 // happen). See MSDN for SHFileOperation and SHFILEOPTSTRUCT. 170 traversal.GetFindInfo(&info);
171 if (file_operation.fAnyOperationsAborted) 171 if (traversal.IsDirectory(info)) {
172 return false; 172 directories.push(current.value());
173 173 } else {
174 // Some versions of Windows return ERROR_FILE_NOT_FOUND (0x2) when deleting 174 if (!RemoveReadOnlyAttribute(current))
175 // an empty directory and some return 0x402 when they should be returning 175 return false;
176 // ERROR_FILE_NOT_FOUND. MSDN says Vista and up won't return 0x402. 176 success = (DeleteFile(current.value().c_str()) != 0);
177 return (err == 0 || err == ERROR_FILE_NOT_FOUND || err == 0x402); 177 }
178 }
179 while (success && !directories.empty()) {
180 FilePath dir = FilePath(directories.top());
181 directories.pop();
182 success = (RemoveDirectory(dir.value().c_str()) != 0);
183 }
184 return success;
178 } 185 }
179 186
180 bool DeleteAfterReboot(const FilePath& path) { 187 bool DeleteAfterReboot(const FilePath& path) {
181 base::ThreadRestrictions::AssertIOAllowed(); 188 base::ThreadRestrictions::AssertIOAllowed();
182 189
183 if (path.value().length() >= MAX_PATH) 190 if (path.value().length() >= MAX_PATH)
184 return false; 191 return false;
185 192
186 return MoveFileEx(path.value().c_str(), NULL, 193 return MoveFileEx(path.value().c_str(), NULL,
187 MOVEFILE_DELAY_UNTIL_REBOOT | 194 MOVEFILE_DELAY_UNTIL_REBOOT |
188 MOVEFILE_REPLACE_EXISTING) != FALSE; 195 MOVEFILE_REPLACE_EXISTING) != FALSE;
189 } 196 }
190 197
191 bool Move(const FilePath& from_path, const FilePath& to_path) { 198 bool Move(const FilePath& from_path, const FilePath& to_path) {
192 base::ThreadRestrictions::AssertIOAllowed(); 199 base::ThreadRestrictions::AssertIOAllowed();
193 200
194 // NOTE: I suspect we could support longer paths, but that would involve
195 // analyzing all our usage of files.
196 if (from_path.value().length() >= MAX_PATH ||
197 to_path.value().length() >= MAX_PATH) {
198 return false;
199 }
200 if (MoveFileEx(from_path.value().c_str(), to_path.value().c_str(), 201 if (MoveFileEx(from_path.value().c_str(), to_path.value().c_str(),
201 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0) 202 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0)
202 return true; 203 return true;
203 if (DirectoryExists(from_path)) { 204 if (DirectoryExists(from_path)) {
204 // MoveFileEx fails if moving directory across volumes. We will simulate 205 // MoveFileEx fails if moving directory across volumes. We will simulate
205 // the move by using Copy and Delete. Ideally we could check whether 206 // the move by using Copy and Delete. Ideally we could check whether
206 // from_path and to_path are indeed in different volumes. 207 // from_path and to_path are indeed in different volumes.
207 return CopyAndDeleteDirectory(from_path, to_path); 208 return CopyAndDeleteDirectory(from_path, to_path);
208 } 209 }
209 return false; 210 return false;
(...skipping 16 matching lines...) Expand all
226 // When writing to a network share, we may not be able to change the ACLs. 227 // When writing to a network share, we may not be able to change the ACLs.
227 // Ignore ACL errors then (REPLACEFILE_IGNORE_MERGE_ERRORS). 228 // Ignore ACL errors then (REPLACEFILE_IGNORE_MERGE_ERRORS).
228 return ::ReplaceFile(to_path.value().c_str(), 229 return ::ReplaceFile(to_path.value().c_str(),
229 from_path.value().c_str(), NULL, 230 from_path.value().c_str(), NULL,
230 REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL) ? true : false; 231 REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL) ? true : false;
231 } 232 }
232 233
233 bool CopyFile(const FilePath& from_path, const FilePath& to_path) { 234 bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
234 base::ThreadRestrictions::AssertIOAllowed(); 235 base::ThreadRestrictions::AssertIOAllowed();
235 236
236 // NOTE: I suspect we could support longer paths, but that would involve
237 // analyzing all our usage of files.
238 if (from_path.value().length() >= MAX_PATH ||
239 to_path.value().length() >= MAX_PATH) {
240 return false;
241 }
242 return (::CopyFile(from_path.value().c_str(), to_path.value().c_str(), 237 return (::CopyFile(from_path.value().c_str(), to_path.value().c_str(),
243 false) != 0); 238 false) != 0);
244 } 239 }
245 240
246 bool ShellCopy(const FilePath& from_path, const FilePath& to_path,
247 bool recursive) {
248 base::ThreadRestrictions::AssertIOAllowed();
249
250 // NOTE: I suspect we could support longer paths, but that would involve
251 // analyzing all our usage of files.
252 if (from_path.value().length() >= MAX_PATH ||
253 to_path.value().length() >= MAX_PATH) {
254 return false;
255 }
256
257 // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
258 // so we have to use wcscpy because wcscpy_s writes non-NULLs
259 // into the rest of the buffer.
260 wchar_t double_terminated_path_from[MAX_PATH + 1] = {0};
261 wchar_t double_terminated_path_to[MAX_PATH + 1] = {0};
262 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
263 wcscpy(double_terminated_path_from, from_path.value().c_str());
264 #pragma warning(suppress:4996) // don't complain about wcscpy deprecation
265 wcscpy(double_terminated_path_to, to_path.value().c_str());
266
267 SHFILEOPSTRUCT file_operation = {0};
268 file_operation.wFunc = FO_COPY;
269 file_operation.pFrom = double_terminated_path_from;
270 file_operation.pTo = double_terminated_path_to;
271 file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION |
272 FOF_NOCONFIRMMKDIR;
273 if (!recursive)
274 file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY;
275
276 return (SHFileOperation(&file_operation) == 0);
277 }
278
279 bool CopyDirectory(const FilePath& from_path, const FilePath& to_path, 241 bool CopyDirectory(const FilePath& from_path, const FilePath& to_path,
280 bool recursive) { 242 bool recursive) {
281 base::ThreadRestrictions::AssertIOAllowed(); 243 base::ThreadRestrictions::AssertIOAllowed();
244 FilePath real_to_path = to_path;
245 if (PathExists(real_to_path)) {
246 if (!AbsolutePath(&real_to_path))
kinuko 2010/12/22 23:20:49 Shouldn't we call the startWith checks before call
Kavita Kanetkar 2010/12/23 03:14:28 Done.
247 return false;
248 } else {
249 real_to_path = real_to_path.DirName();
250 if (!AbsolutePath(&real_to_path))
251 return false;
252 }
253 FilePath real_from_path = from_path;
254 if (!AbsolutePath(&real_from_path))
255 return false;
256 if (real_to_path.value().size() >= real_from_path.value().size() &&
257 real_to_path.value().compare(0, real_from_path.value().size(),
258 real_from_path.value()) == 0)
259 return false;
282 260
283 if (recursive) 261 if (!PathExists(from_path)) {
284 return ShellCopy(from_path, to_path, true); 262 LOG(ERROR) << "CopyDirectory() couldn't get info on source directory: "
285 263 << from_path.value();
286 // The following code assumes that from path is a directory. 264 return false;
287 DCHECK(DirectoryExists(from_path));
288
289 // Instead of creating a new directory, we copy the old one to include the
290 // security information of the folder as part of the copy.
291 if (!PathExists(to_path)) {
292 // Except that Vista fails to do that, and instead do a recursive copy if
293 // the target directory doesn't exist.
294 if (base::win::GetVersion() >= base::win::VERSION_VISTA)
295 CreateDirectory(to_path);
296 else
297 ShellCopy(from_path, to_path, false);
298 } 265 }
299 266
300 FilePath directory = from_path.Append(L"*.*"); 267 FilePath from_path_base = from_path;
301 return ShellCopy(directory, to_path, false); 268 if (recursive && DirectoryExists(to_path)) {
269 // If the destination already exists and is a directory, then the
270 // top level of source needs to be copied.
271 from_path_base = from_path.DirName();
272 }
273
274 // This matches previous shell implementation that assumed that
275 // non-recursive calls will always have a directory for from_path.
276 DCHECK(recursive || DirectoryExists(from_path));
277
278 bool success = true;
279 FileEnumerator::FILE_TYPE traverse_type =
280 static_cast<FileEnumerator::FILE_TYPE>(FileEnumerator::FILES);
kinuko 2010/12/22 23:20:49 (repeating michael's question) is this static_cast
281 if (recursive)
282 traverse_type = static_cast<FileEnumerator::FILE_TYPE>(
283 traverse_type | FileEnumerator::DIRECTORIES);
284 FileEnumerator traversal(from_path, recursive, traverse_type);
285 FilePath current = from_path;
286 while (success && !current.empty()) {
287 // current is the source path, including from_path, so paste
288 // the suffix after from_path onto to_path to create the target_path.
289 FilePath::StringType relative_path_suffix(
kinuko 2010/12/22 23:20:49 I think michael meant suffix -> relative_path rath
Kavita Kanetkar 2010/12/23 03:14:28 I liked suffix var name better. But changed since
290 &current.value().c_str()[from_path_base.value().size()]);
291
292 // Strip the leading '\' (if any).
293 if (!relative_path_suffix.empty()) {
294 DCHECK_EQ('\\', relative_path_suffix[0]);
295 relative_path_suffix.erase(0, 1);
296 }
297 const FilePath target_path = to_path.Append(relative_path_suffix);
298
299 FileEnumerator::FindInfo info;
300 traversal.GetFindInfo(&info);
301 if (traversal.IsDirectory(info)) {
kinuko 2010/12/22 23:20:49 FileEnumerator::IsDirectory(info) would be better?
Kavita Kanetkar 2010/12/23 03:14:28 I needed to replace this with DirectoryExists() ne
302 if (::CreateDirectory(target_path.value().c_str(), NULL) == 0) {
303 if (!DirectoryExists(target_path)) {
304 LOG(ERROR) << "CopyDirectory() couldn't create directory: "
305 << target_path.value();
306 success = false;
307 }
308 }
309 } else {
310 if (!CopyFile(current, target_path)) {
311 LOG(ERROR) << "CopyDirectory() couldn't create file: "
312 << target_path.value();
313 success = false;
314 }
315 }
316 current = traversal.Next();
317 }
318 return success;
302 } 319 }
303 320
304 bool CopyAndDeleteDirectory(const FilePath& from_path, 321 bool CopyAndDeleteDirectory(const FilePath& from_path,
305 const FilePath& to_path) { 322 const FilePath& to_path) {
306 base::ThreadRestrictions::AssertIOAllowed(); 323 base::ThreadRestrictions::AssertIOAllowed();
307 if (CopyDirectory(from_path, to_path, true)) { 324 if (CopyDirectory(from_path, to_path, true)) {
308 if (Delete(from_path, true)) { 325 if (Delete(from_path, true)) {
309 return true; 326 return true;
310 } 327 }
311 // Like Move, this function is not transactional, so we just 328 // Like Move, this function is not transactional, so we just
312 // leave the copied bits behind if deleting from_path fails. 329 // leave the copied bits behind if deleting from_path fails.
313 // If to_path exists previously then we have already overwritten 330 // If to_path exists previously then we have already overwritten
314 // it by now, we don't get better off by deleting the new bits. 331 // it by now, we don't get better off by deleting the new bits.
315 } 332 }
316 return false; 333 return false;
317 } 334 }
318 335
319
320 bool PathExists(const FilePath& path) { 336 bool PathExists(const FilePath& path) {
321 base::ThreadRestrictions::AssertIOAllowed(); 337 base::ThreadRestrictions::AssertIOAllowed();
322 return (GetFileAttributes(path.value().c_str()) != INVALID_FILE_ATTRIBUTES); 338 return (GetFileAttributes(path.value().c_str()) != INVALID_FILE_ATTRIBUTES);
323 } 339 }
324 340
325 bool PathIsWritable(const FilePath& path) { 341 bool PathIsWritable(const FilePath& path) {
326 base::ThreadRestrictions::AssertIOAllowed(); 342 base::ThreadRestrictions::AssertIOAllowed();
327 HANDLE dir = 343 HANDLE dir =
328 CreateFile(path.value().c_str(), FILE_ADD_FILE, kFileShareAll, 344 CreateFile(path.value().c_str(), FILE_ADD_FILE, kFileShareAll,
329 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); 345 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
(...skipping 803 matching lines...) Expand 10 before | Expand all | Expand 10 after
1133 uint8 unused = *(touch + offset); 1149 uint8 unused = *(touch + offset);
1134 offset += step_size; 1150 offset += step_size;
1135 } 1151 }
1136 FreeLibrary(dll_module); 1152 FreeLibrary(dll_module);
1137 } 1153 }
1138 1154
1139 return true; 1155 return true;
1140 } 1156 }
1141 1157
1142 } // namespace file_util 1158 } // namespace file_util
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698