Supervised user import: Listen for profile creation/deletion
[chromium-blink-merge.git] / base / files / file_win.cc
blob200ea296644a06238e21642313e831a1845a6596
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"
7 #include <io.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"
14 namespace base {
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 {
26 return file_.Get();
29 PlatformFile File::TakePlatformFile() {
30 return file_.Take();
33 void File::Close() {
34 if (file_.IsValid()) {
35 ThreadRestrictions::AssertIOAllowed();
36 file_.Close();
40 int64 File::Seek(Whence whence, int64 offset) {
41 ThreadRestrictions::AssertIOAllowed();
42 DCHECK(IsValid());
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))
48 return -1;
49 return res.QuadPart;
52 int File::Read(int64 offset, char* data, int size) {
53 ThreadRestrictions::AssertIOAllowed();
54 DCHECK(IsValid());
55 DCHECK(!async_);
56 if (size < 0)
57 return -1;
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;
66 DWORD bytes_read;
67 if (::ReadFile(file_.Get(), data, size, &bytes_read, &overlapped))
68 return bytes_read;
69 if (ERROR_HANDLE_EOF == GetLastError())
70 return 0;
72 return -1;
75 int File::ReadAtCurrentPos(char* data, int size) {
76 ThreadRestrictions::AssertIOAllowed();
77 DCHECK(IsValid());
78 DCHECK(!async_);
79 if (size < 0)
80 return -1;
82 DWORD bytes_read;
83 if (::ReadFile(file_.Get(), data, size, &bytes_read, NULL))
84 return bytes_read;
85 if (ERROR_HANDLE_EOF == GetLastError())
86 return 0;
88 return -1;
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();
101 DCHECK(IsValid());
102 DCHECK(!async_);
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;
111 DWORD bytes_written;
112 if (::WriteFile(file_.Get(), data, size, &bytes_written, &overlapped))
113 return bytes_written;
115 return -1;
118 int File::WriteAtCurrentPos(const char* data, int size) {
119 ThreadRestrictions::AssertIOAllowed();
120 DCHECK(IsValid());
121 DCHECK(!async_);
122 if (size < 0)
123 return -1;
125 DWORD bytes_written;
126 if (::WriteFile(file_.Get(), data, size, &bytes_written, NULL))
127 return bytes_written;
129 return -1;
132 int File::WriteAtCurrentPosNoBestEffort(const char* data, int size) {
133 return WriteAtCurrentPos(data, size);
136 int64 File::GetLength() {
137 ThreadRestrictions::AssertIOAllowed();
138 DCHECK(IsValid());
139 LARGE_INTEGER size;
140 if (!::GetFileSizeEx(file_.Get(), &size))
141 return -1;
143 return static_cast<int64>(size.QuadPart);
146 bool File::SetLength(int64 length) {
147 ThreadRestrictions::AssertIOAllowed();
148 DCHECK(IsValid());
150 // Get the current file pointer.
151 LARGE_INTEGER file_pointer;
152 LARGE_INTEGER zero;
153 zero.QuadPart = 0;
154 if (!::SetFilePointerEx(file_.Get(), zero, &file_pointer, FILE_CURRENT))
155 return false;
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))
162 return false;
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) !=
172 FALSE));
175 bool File::SetTimes(Time last_access_time, Time last_modified_time) {
176 ThreadRestrictions::AssertIOAllowed();
177 DCHECK(IsValid());
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();
187 DCHECK(IsValid());
189 BY_HANDLE_FILE_INFORMATION file_info;
190 if (!GetFileInformationByHandle(file_.Get(), &file_info))
191 return false;
193 LARGE_INTEGER size;
194 size.HighPart = file_info.nFileSizeHigh;
195 size.LowPart = file_info.nFileSizeLow;
196 info->size = size.QuadPart;
197 info->is_directory =
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);
203 return true;
206 File::Error File::Lock() {
207 DCHECK(IsValid());
208 BOOL result = LockFile(file_.Get(), 0, 0, MAXDWORD, MAXDWORD);
209 if (!result)
210 return OSErrorToFileError(GetLastError());
211 return FILE_OK;
214 File::Error File::Unlock() {
215 DCHECK(IsValid());
216 BOOL result = UnlockFile(file_.Get(), 0, 0, MAXDWORD, MAXDWORD);
217 if (!result)
218 return OSErrorToFileError(GetLastError());
219 return FILE_OK;
222 File File::Duplicate() {
223 if (!IsValid())
224 return File();
226 HANDLE other_handle = nullptr;
228 if (!::DuplicateHandle(GetCurrentProcess(), // hSourceProcessHandle
229 GetPlatformFile(),
230 GetCurrentProcess(), // hTargetProcessHandle
231 &other_handle,
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);
239 if (async())
240 other.async_ = true;
241 return other.Pass();
244 // Static.
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;
274 default:
275 UMA_HISTOGRAM_SPARSE_SLOWLY("PlatformFile.UnknownErrors.Windows",
276 last_error);
277 return FILE_ERROR_FAILED;
281 void File::DoInitialize(const FilePath& name, uint32 flags) {
282 ThreadRestrictions::AssertIOAllowed();
283 DCHECK(!IsValid());
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;
312 if (!disposition) {
313 NOTREACHED();
314 return;
317 DWORD access = 0;
318 if (flags & FLAG_WRITE)
319 access = GENERIC_WRITE;
320 if (flags & FLAG_APPEND) {
321 DCHECK(!access);
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))
359 created_ = true;
360 } else {
361 error_details_ = OSErrorToFileError(GetLastError());
365 bool File::DoFlush() {
366 ThreadRestrictions::AssertIOAllowed();
367 DCHECK(IsValid());
368 return ::FlushFileBuffers(file_.Get()) != FALSE;
371 void File::SetPlatformFile(PlatformFile file) {
372 file_.Set(file);
375 } // namespace base