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

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 76 matching lines...) Expand 10 before | Expand all | Expand 10 after
122 // File was created after or on comparison time 134 // File was created after or on comparison time
123 if ((result == 1) || (result == 0)) 135 if ((result == 1) || (result == 0))
124 ++file_count; 136 ++file_count;
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) {
Erik does not do reviews 2010/12/23 17:57:27 it seems like this Delete change is worthwhile on
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 (!real_to_path.StartsWithExtendedPathOrUNCPrefix() &&
247 !AbsolutePath(&real_to_path))
248 return false;
249 } else {
250 real_to_path = real_to_path.DirName();
251 if (!real_to_path.StartsWithExtendedPathOrUNCPrefix() &&
252 !AbsolutePath(&real_to_path))
253 return false;
254 }
255 FilePath real_from_path = from_path;
256 if (!real_from_path.StartsWithExtendedPathOrUNCPrefix() &&
257 !AbsolutePath(&real_from_path))
258 return false;
259 if (real_to_path.value().size() >= real_from_path.value().size() &&
260 real_to_path.value().compare(0, real_from_path.value().size(),
261 real_from_path.value()) == 0)
262 return false;
282 263
283 if (recursive) 264 if (!PathExists(from_path)) {
284 return ShellCopy(from_path, to_path, true); 265 LOG(ERROR) << "CopyDirectory() couldn't get info on source directory: "
285 266 << from_path.value();
286 // The following code assumes that from path is a directory. 267 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 } 268 }
299 269
300 FilePath directory = from_path.Append(L"*.*"); 270 FilePath from_path_base = from_path;
301 return ShellCopy(directory, to_path, false); 271 if (recursive && DirectoryExists(to_path)) {
272 // If the destination already exists and is a directory, then the
273 // top level of source needs to be copied.
274 from_path_base = from_path.DirName();
275 }
276
277 // This matches previous shell implementation that assumed that
278 // non-recursive calls will always have a directory for from_path.
279 DCHECK(recursive || DirectoryExists(from_path));
280
281 bool success = true;
282 FileEnumerator::FILE_TYPE traverse_type =
283 static_cast<FileEnumerator::FILE_TYPE>(FileEnumerator::FILES);
284 if (recursive)
285 traverse_type = static_cast<FileEnumerator::FILE_TYPE>(
286 traverse_type | FileEnumerator::DIRECTORIES);
287 FileEnumerator traversal(from_path, recursive, traverse_type);
288 FilePath current = from_path;
289 while (success && !current.empty()) {
290 // current is the source path, including from_path, so paste
291 // the relative_path after from_path onto to_path to create
292 // the target_path.
293 FilePath::StringType relative_path(
294 &current.value().c_str()[from_path_base.value().size()]);
295
296 // Strip the leading '\' (if any).
297 if (!relative_path.empty()) {
298 DCHECK_EQ('\\', relative_path[0]);
299 relative_path.erase(0, 1);
300 }
301 const FilePath target_path = to_path.Append(relative_path);
302
303 if (DirectoryExists(current)) {
304 if (::CreateDirectory(target_path.value().c_str(), NULL) == 0) {
305 if (!DirectoryExists(target_path)) {
306 LOG(ERROR) << "CopyDirectory() couldn't create directory: "
307 << target_path.value();
308 success = false;
309 }
310 }
311 } else {
312 if (!CopyFile(current, target_path)) {
313 LOG(ERROR) << "CopyDirectory() couldn't create file: "
314 << target_path.value();
315 success = false;
316 }
317 }
318 current = traversal.Next();
319 }
320 return success;
302 } 321 }
303 322
304 bool CopyAndDeleteDirectory(const FilePath& from_path, 323 bool CopyAndDeleteDirectory(const FilePath& from_path,
305 const FilePath& to_path) { 324 const FilePath& to_path) {
306 base::ThreadRestrictions::AssertIOAllowed(); 325 base::ThreadRestrictions::AssertIOAllowed();
307 if (CopyDirectory(from_path, to_path, true)) { 326 if (CopyDirectory(from_path, to_path, true)) {
308 if (Delete(from_path, true)) { 327 if (Delete(from_path, true)) {
309 return true; 328 return true;
310 } 329 }
311 // Like Move, this function is not transactional, so we just 330 // Like Move, this function is not transactional, so we just
312 // leave the copied bits behind if deleting from_path fails. 331 // leave the copied bits behind if deleting from_path fails.
313 // If to_path exists previously then we have already overwritten 332 // 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. 333 // it by now, we don't get better off by deleting the new bits.
315 } 334 }
316 return false; 335 return false;
317 } 336 }
318 337
319
320 bool PathExists(const FilePath& path) { 338 bool PathExists(const FilePath& path) {
321 base::ThreadRestrictions::AssertIOAllowed(); 339 base::ThreadRestrictions::AssertIOAllowed();
322 return (GetFileAttributes(path.value().c_str()) != INVALID_FILE_ATTRIBUTES); 340 return (GetFileAttributes(path.value().c_str()) != INVALID_FILE_ATTRIBUTES);
323 } 341 }
324 342
325 bool PathIsWritable(const FilePath& path) { 343 bool PathIsWritable(const FilePath& path) {
326 base::ThreadRestrictions::AssertIOAllowed(); 344 base::ThreadRestrictions::AssertIOAllowed();
327 HANDLE dir = 345 HANDLE dir =
328 CreateFile(path.value().c_str(), FILE_ADD_FILE, kFileShareAll, 346 CreateFile(path.value().c_str(), FILE_ADD_FILE, kFileShareAll,
329 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); 347 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); 1151 uint8 unused = *(touch + offset);
1134 offset += step_size; 1152 offset += step_size;
1135 } 1153 }
1136 FreeLibrary(dll_module); 1154 FreeLibrary(dll_module);
1137 } 1155 }
1138 1156
1139 return true; 1157 return true;
1140 } 1158 }
1141 1159
1142 } // namespace file_util 1160 } // namespace file_util
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698