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
3 // found in the LICENSE file.
5 #include "base/files/file.h"
9 #include "base/files/file_path.h"
10 #include "base/logging.h"
11 #include "base/metrics/sparse_histogram.h"
12 #include "base/threading/thread_restrictions.h"
16 // Make sure our Whence mappings match the system headers.
17 COMPILE_ASSERT(File::FROM_BEGIN
== FILE_BEGIN
&&
18 File::FROM_CURRENT
== FILE_CURRENT
&&
19 File::FROM_END
== FILE_END
, whence_matches_system
);
21 bool File::IsValid() const {
22 return file_
.IsValid();
25 PlatformFile
File::GetPlatformFile() const {
29 PlatformFile
File::TakePlatformFile() {
34 if (file_
.IsValid()) {
35 ThreadRestrictions::AssertIOAllowed();
40 int64
File::Seek(Whence whence
, int64 offset
) {
41 ThreadRestrictions::AssertIOAllowed();
44 LARGE_INTEGER distance
, res
;
45 distance
.QuadPart
= offset
;
46 DWORD move_method
= static_cast<DWORD
>(whence
);
47 if (!SetFilePointerEx(file_
.Get(), distance
, &res
, move_method
))
52 int File::Read(int64 offset
, char* data
, int size
) {
53 ThreadRestrictions::AssertIOAllowed();
59 LARGE_INTEGER offset_li
;
60 offset_li
.QuadPart
= offset
;
62 OVERLAPPED overlapped
= {0};
63 overlapped
.Offset
= offset_li
.LowPart
;
64 overlapped
.OffsetHigh
= offset_li
.HighPart
;
67 if (::ReadFile(file_
.Get(), data
, size
, &bytes_read
, &overlapped
))
69 if (ERROR_HANDLE_EOF
== GetLastError())
75 int File::ReadAtCurrentPos(char* data
, int size
) {
76 ThreadRestrictions::AssertIOAllowed();
83 if (::ReadFile(file_
.Get(), data
, size
, &bytes_read
, NULL
))
85 if (ERROR_HANDLE_EOF
== GetLastError())
91 int File::ReadNoBestEffort(int64 offset
, char* data
, int size
) {
92 return Read(offset
, data
, size
);
95 int File::ReadAtCurrentPosNoBestEffort(char* data
, int size
) {
96 return ReadAtCurrentPos(data
, size
);
99 int File::Write(int64 offset
, const char* data
, int size
) {
100 ThreadRestrictions::AssertIOAllowed();
104 LARGE_INTEGER offset_li
;
105 offset_li
.QuadPart
= offset
;
107 OVERLAPPED overlapped
= {0};
108 overlapped
.Offset
= offset_li
.LowPart
;
109 overlapped
.OffsetHigh
= offset_li
.HighPart
;
112 if (::WriteFile(file_
.Get(), data
, size
, &bytes_written
, &overlapped
))
113 return bytes_written
;
118 int File::WriteAtCurrentPos(const char* data
, int size
) {
119 ThreadRestrictions::AssertIOAllowed();
126 if (::WriteFile(file_
.Get(), data
, size
, &bytes_written
, NULL
))
127 return bytes_written
;
132 int File::WriteAtCurrentPosNoBestEffort(const char* data
, int size
) {
133 return WriteAtCurrentPos(data
, size
);
136 int64
File::GetLength() {
137 ThreadRestrictions::AssertIOAllowed();
140 if (!::GetFileSizeEx(file_
.Get(), &size
))
143 return static_cast<int64
>(size
.QuadPart
);
146 bool File::SetLength(int64 length
) {
147 ThreadRestrictions::AssertIOAllowed();
150 // Get the current file pointer.
151 LARGE_INTEGER file_pointer
;
154 if (!::SetFilePointerEx(file_
.Get(), zero
, &file_pointer
, FILE_CURRENT
))
157 LARGE_INTEGER length_li
;
158 length_li
.QuadPart
= length
;
159 // If length > file size, SetFilePointerEx() should extend the file
160 // with zeroes on all Windows standard file systems (NTFS, FATxx).
161 if (!::SetFilePointerEx(file_
.Get(), length_li
, NULL
, FILE_BEGIN
))
164 // Set the new file length and move the file pointer to its old position.
165 // This is consistent with ftruncate()'s behavior, even when the file
166 // pointer points to a location beyond the end of the file.
167 // TODO(rvargas): Emulating ftruncate details seem suspicious and it is not
168 // promised by the interface (nor was promised by PlatformFile). See if this
169 // implementation detail can be removed.
170 return ((::SetEndOfFile(file_
.Get()) != FALSE
) &&
171 (::SetFilePointerEx(file_
.Get(), file_pointer
, NULL
, FILE_BEGIN
) !=
175 bool File::SetTimes(Time last_access_time
, Time last_modified_time
) {
176 ThreadRestrictions::AssertIOAllowed();
179 FILETIME last_access_filetime
= last_access_time
.ToFileTime();
180 FILETIME last_modified_filetime
= last_modified_time
.ToFileTime();
181 return (::SetFileTime(file_
.Get(), NULL
, &last_access_filetime
,
182 &last_modified_filetime
) != FALSE
);
185 bool File::GetInfo(Info
* info
) {
186 ThreadRestrictions::AssertIOAllowed();
189 BY_HANDLE_FILE_INFORMATION file_info
;
190 if (!GetFileInformationByHandle(file_
.Get(), &file_info
))
194 size
.HighPart
= file_info
.nFileSizeHigh
;
195 size
.LowPart
= file_info
.nFileSizeLow
;
196 info
->size
= size
.QuadPart
;
198 (file_info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
199 info
->is_symbolic_link
= false; // Windows doesn't have symbolic links.
200 info
->last_modified
= Time::FromFileTime(file_info
.ftLastWriteTime
);
201 info
->last_accessed
= Time::FromFileTime(file_info
.ftLastAccessTime
);
202 info
->creation_time
= Time::FromFileTime(file_info
.ftCreationTime
);
206 File::Error
File::Lock() {
208 BOOL result
= LockFile(file_
.Get(), 0, 0, MAXDWORD
, MAXDWORD
);
210 return OSErrorToFileError(GetLastError());
214 File::Error
File::Unlock() {
216 BOOL result
= UnlockFile(file_
.Get(), 0, 0, MAXDWORD
, MAXDWORD
);
218 return OSErrorToFileError(GetLastError());
222 File
File::Duplicate() {
226 HANDLE other_handle
= nullptr;
228 if (!::DuplicateHandle(GetCurrentProcess(), // hSourceProcessHandle
230 GetCurrentProcess(), // hTargetProcessHandle
232 0, // dwDesiredAccess ignored due to SAME_ACCESS
233 FALSE
, // !bInheritHandle
234 DUPLICATE_SAME_ACCESS
)) {
235 return File(OSErrorToFileError(GetLastError()));
238 File
other(other_handle
);
245 File::Error
File::OSErrorToFileError(DWORD last_error
) {
246 switch (last_error
) {
247 case ERROR_SHARING_VIOLATION
:
248 return FILE_ERROR_IN_USE
;
249 case ERROR_FILE_EXISTS
:
250 return FILE_ERROR_EXISTS
;
251 case ERROR_FILE_NOT_FOUND
:
252 case ERROR_PATH_NOT_FOUND
:
253 return FILE_ERROR_NOT_FOUND
;
254 case ERROR_ACCESS_DENIED
:
255 return FILE_ERROR_ACCESS_DENIED
;
256 case ERROR_TOO_MANY_OPEN_FILES
:
257 return FILE_ERROR_TOO_MANY_OPENED
;
258 case ERROR_OUTOFMEMORY
:
259 case ERROR_NOT_ENOUGH_MEMORY
:
260 return FILE_ERROR_NO_MEMORY
;
261 case ERROR_HANDLE_DISK_FULL
:
262 case ERROR_DISK_FULL
:
263 case ERROR_DISK_RESOURCES_EXHAUSTED
:
264 return FILE_ERROR_NO_SPACE
;
265 case ERROR_USER_MAPPED_FILE
:
266 return FILE_ERROR_INVALID_OPERATION
;
267 case ERROR_NOT_READY
:
268 case ERROR_SECTOR_NOT_FOUND
:
269 case ERROR_DEV_NOT_EXIST
:
270 case ERROR_IO_DEVICE
:
271 case ERROR_FILE_CORRUPT
:
272 case ERROR_DISK_CORRUPT
:
273 return FILE_ERROR_IO
;
275 UMA_HISTOGRAM_SPARSE_SLOWLY("PlatformFile.UnknownErrors.Windows",
277 return FILE_ERROR_FAILED
;
281 void File::DoInitialize(const FilePath
& name
, uint32 flags
) {
282 ThreadRestrictions::AssertIOAllowed();
285 DWORD disposition
= 0;
287 if (flags
& FLAG_OPEN
)
288 disposition
= OPEN_EXISTING
;
290 if (flags
& FLAG_CREATE
) {
291 DCHECK(!disposition
);
292 disposition
= CREATE_NEW
;
295 if (flags
& FLAG_OPEN_ALWAYS
) {
296 DCHECK(!disposition
);
297 disposition
= OPEN_ALWAYS
;
300 if (flags
& FLAG_CREATE_ALWAYS
) {
301 DCHECK(!disposition
);
302 DCHECK(flags
& FLAG_WRITE
);
303 disposition
= CREATE_ALWAYS
;
306 if (flags
& FLAG_OPEN_TRUNCATED
) {
307 DCHECK(!disposition
);
308 DCHECK(flags
& FLAG_WRITE
);
309 disposition
= TRUNCATE_EXISTING
;
318 if (flags
& FLAG_WRITE
)
319 access
= GENERIC_WRITE
;
320 if (flags
& FLAG_APPEND
) {
322 access
= FILE_APPEND_DATA
;
324 if (flags
& FLAG_READ
)
325 access
|= GENERIC_READ
;
326 if (flags
& FLAG_WRITE_ATTRIBUTES
)
327 access
|= FILE_WRITE_ATTRIBUTES
;
328 if (flags
& FLAG_EXECUTE
)
329 access
|= GENERIC_EXECUTE
;
331 DWORD sharing
= (flags
& FLAG_EXCLUSIVE_READ
) ? 0 : FILE_SHARE_READ
;
332 if (!(flags
& FLAG_EXCLUSIVE_WRITE
))
333 sharing
|= FILE_SHARE_WRITE
;
334 if (flags
& FLAG_SHARE_DELETE
)
335 sharing
|= FILE_SHARE_DELETE
;
337 DWORD create_flags
= 0;
338 if (flags
& FLAG_ASYNC
)
339 create_flags
|= FILE_FLAG_OVERLAPPED
;
340 if (flags
& FLAG_TEMPORARY
)
341 create_flags
|= FILE_ATTRIBUTE_TEMPORARY
;
342 if (flags
& FLAG_HIDDEN
)
343 create_flags
|= FILE_ATTRIBUTE_HIDDEN
;
344 if (flags
& FLAG_DELETE_ON_CLOSE
)
345 create_flags
|= FILE_FLAG_DELETE_ON_CLOSE
;
346 if (flags
& FLAG_BACKUP_SEMANTICS
)
347 create_flags
|= FILE_FLAG_BACKUP_SEMANTICS
;
349 file_
.Set(CreateFile(name
.value().c_str(), access
, sharing
, NULL
,
350 disposition
, create_flags
, NULL
));
352 if (file_
.IsValid()) {
353 error_details_
= FILE_OK
;
354 async_
= ((flags
& FLAG_ASYNC
) == FLAG_ASYNC
);
356 if (flags
& (FLAG_OPEN_ALWAYS
))
357 created_
= (ERROR_ALREADY_EXISTS
!= GetLastError());
358 else if (flags
& (FLAG_CREATE_ALWAYS
| FLAG_CREATE
))
361 error_details_
= OSErrorToFileError(GetLastError());
365 bool File::DoFlush() {
366 ThreadRestrictions::AssertIOAllowed();
368 return ::FlushFileBuffers(file_
.Get()) != FALSE
;
371 void File::SetPlatformFile(PlatformFile file
) {