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"
12 #include "base/files/file_path.h"
13 #include "base/logging.h"
14 #include "base/metrics/sparse_histogram.h"
15 // TODO(rvargas): remove this (needed for kInvalidPlatformFileValue).
16 #include "base/platform_file.h"
17 #include "base/posix/eintr_wrapper.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/threading/thread_restrictions.h"
21 #if defined(OS_ANDROID)
22 #include "base/os_compat_android.h"
27 // Make sure our Whence mappings match the system headers.
28 COMPILE_ASSERT(File::FROM_BEGIN == SEEK_SET &&
29 File::FROM_CURRENT == SEEK_CUR &&
30 File::FROM_END == SEEK_END, whence_matches_system);
34 #if defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL)
35 typedef struct stat stat_wrapper_t;
36 static int CallFstat(int fd, stat_wrapper_t *sb) {
37 base::ThreadRestrictions::AssertIOAllowed();
41 typedef struct stat64 stat_wrapper_t;
42 static int CallFstat(int fd, stat_wrapper_t *sb) {
43 base::ThreadRestrictions::AssertIOAllowed();
44 return fstat64(fd, sb);
48 // NaCl doesn't provide the following system calls, so either simulate them or
49 // wrap them in order to minimize the number of #ifdef's in this file.
51 static bool IsOpenAppend(PlatformFile file) {
52 return (fcntl(file, F_GETFL) & O_APPEND) != 0;
55 static int CallFtruncate(PlatformFile file, int64 length) {
56 return HANDLE_EINTR(ftruncate(file, length));
59 static int CallFsync(PlatformFile file) {
60 return HANDLE_EINTR(fsync(file));
63 static int CallFutimes(PlatformFile file, const struct timeval times[2]) {
65 // futimens should be available, but futimes might not be
66 // http://pubs.opengroup.org/onlinepubs/9699919799/
69 ts_times[0].tv_sec = times[0].tv_sec;
70 ts_times[0].tv_nsec = times[0].tv_usec * 1000;
71 ts_times[1].tv_sec = times[1].tv_sec;
72 ts_times[1].tv_nsec = times[1].tv_usec * 1000;
74 return futimens(file, ts_times);
76 return futimes(file, times);
80 static File::Error CallFctnlFlock(PlatformFile file, bool do_lock) {
82 lock.l_type = F_WRLCK;
83 lock.l_whence = SEEK_SET;
85 lock.l_len = 0; // Lock entire file.
86 if (HANDLE_EINTR(fcntl(file, do_lock ? F_SETLK : F_UNLCK, &lock)) == -1)
87 return File::OSErrorToFileError(errno);
90 #else // defined(OS_NACL)
92 static bool IsOpenAppend(PlatformFile file) {
93 // NaCl doesn't implement fcntl. Since NaCl's write conforms to the POSIX
94 // standard and always appends if the file is opened with O_APPEND, just
99 static int CallFtruncate(PlatformFile file, int64 length) {
100 NOTIMPLEMENTED(); // NaCl doesn't implement ftruncate.
104 static int CallFsync(PlatformFile file) {
105 NOTIMPLEMENTED(); // NaCl doesn't implement fsync.
109 static int CallFutimes(PlatformFile file, const struct timeval times[2]) {
110 NOTIMPLEMENTED(); // NaCl doesn't implement futimes.
114 static File::Error CallFctnlFlock(PlatformFile file, bool do_lock) {
115 NOTIMPLEMENTED(); // NaCl doesn't implement flock struct.
116 return File::FILE_ERROR_INVALID_OPERATION;
118 #endif // defined(OS_NACL)
122 // NaCl doesn't implement system calls to open files directly.
123 #if !defined(OS_NACL)
124 // TODO(erikkay): does it make sense to support FLAG_EXCLUSIVE_* here?
125 void File::InitializeUnsafe(const FilePath& name, uint32 flags) {
126 base::ThreadRestrictions::AssertIOAllowed();
128 DCHECK(!(flags & FLAG_ASYNC));
131 if (flags & FLAG_CREATE)
132 open_flags = O_CREAT | O_EXCL;
136 if (flags & FLAG_CREATE_ALWAYS) {
138 open_flags = O_CREAT | O_TRUNC;
141 if (flags & FLAG_OPEN_TRUNCATED) {
143 DCHECK(flags & FLAG_WRITE);
144 open_flags = O_TRUNC;
147 if (!open_flags && !(flags & FLAG_OPEN) && !(flags & FLAG_OPEN_ALWAYS)) {
150 error_details_ = FILE_ERROR_FAILED;
154 if (flags & FLAG_WRITE && flags & FLAG_READ) {
155 open_flags |= O_RDWR;
156 } else if (flags & FLAG_WRITE) {
157 open_flags |= O_WRONLY;
158 } else if (!(flags & FLAG_READ) &&
159 !(flags & FLAG_WRITE_ATTRIBUTES) &&
160 !(flags & FLAG_APPEND) &&
161 !(flags & FLAG_OPEN_ALWAYS)) {
165 if (flags & FLAG_TERMINAL_DEVICE)
166 open_flags |= O_NOCTTY | O_NDELAY;
168 if (flags & FLAG_APPEND && flags & FLAG_READ)
169 open_flags |= O_APPEND | O_RDWR;
170 else if (flags & FLAG_APPEND)
171 open_flags |= O_APPEND | O_WRONLY;
173 COMPILE_ASSERT(O_RDONLY == 0, O_RDONLY_must_equal_zero);
175 int mode = S_IRUSR | S_IWUSR;
176 #if defined(OS_CHROMEOS)
177 mode |= S_IRGRP | S_IROTH;
180 int descriptor = HANDLE_EINTR(open(name.value().c_str(), open_flags, mode));
182 if (flags & FLAG_OPEN_ALWAYS) {
183 if (descriptor < 0) {
184 open_flags |= O_CREAT;
185 if (flags & FLAG_EXCLUSIVE_READ || flags & FLAG_EXCLUSIVE_WRITE)
186 open_flags |= O_EXCL; // together with O_CREAT implies O_NOFOLLOW
188 descriptor = HANDLE_EINTR(open(name.value().c_str(), open_flags, mode));
194 if (descriptor >= 0 && (flags & (FLAG_CREATE_ALWAYS | FLAG_CREATE)))
197 if ((descriptor >= 0) && (flags & FLAG_DELETE_ON_CLOSE))
198 unlink(name.value().c_str());
201 error_details_ = FILE_OK;
203 error_details_ = File::OSErrorToFileError(errno);
207 #endif // !defined(OS_NACL)
209 bool File::IsValid() const {
213 PlatformFile File::TakePlatformFile() {
214 PlatformFile file = file_;
215 file_ = kInvalidPlatformFileValue;
220 base::ThreadRestrictions::AssertIOAllowed();
224 if (!IGNORE_EINTR(close(file_)))
225 file_ = kInvalidPlatformFileValue;
228 int64 File::Seek(Whence whence, int64 offset) {
229 base::ThreadRestrictions::AssertIOAllowed();
231 if (file_ < 0 || offset < 0)
234 return lseek(file_, static_cast<off_t>(offset), static_cast<int>(whence));
237 int File::Read(int64 offset, char* data, int size) {
238 base::ThreadRestrictions::AssertIOAllowed();
246 rv = HANDLE_EINTR(pread(file_, data + bytes_read,
247 size - bytes_read, offset + bytes_read));
252 } while (bytes_read < size);
254 return bytes_read ? bytes_read : rv;
257 int File::ReadAtCurrentPos(char* data, int size) {
258 base::ThreadRestrictions::AssertIOAllowed();
266 rv = HANDLE_EINTR(read(file_, data, size));
271 } while (bytes_read < size);
273 return bytes_read ? bytes_read : rv;
276 int File::ReadNoBestEffort(int64 offset, char* data, int size) {
277 base::ThreadRestrictions::AssertIOAllowed();
280 return HANDLE_EINTR(pread(file_, data, size, offset));
283 int File::ReadAtCurrentPosNoBestEffort(char* data, int size) {
284 base::ThreadRestrictions::AssertIOAllowed();
289 return HANDLE_EINTR(read(file_, data, size));
292 int File::Write(int64 offset, const char* data, int size) {
293 base::ThreadRestrictions::AssertIOAllowed();
295 if (IsOpenAppend(file_))
296 return WriteAtCurrentPos(data, size);
302 int bytes_written = 0;
305 rv = HANDLE_EINTR(pwrite(file_, data + bytes_written,
306 size - bytes_written, offset + bytes_written));
311 } while (bytes_written < size);
313 return bytes_written ? bytes_written : rv;
316 int File::WriteAtCurrentPos(const char* data, int size) {
317 base::ThreadRestrictions::AssertIOAllowed();
322 int bytes_written = 0;
325 rv = HANDLE_EINTR(write(file_, data, size));
330 } while (bytes_written < size);
332 return bytes_written ? bytes_written : rv;
335 int File::WriteAtCurrentPosNoBestEffort(const char* data, int size) {
336 base::ThreadRestrictions::AssertIOAllowed();
341 return HANDLE_EINTR(write(file_, data, size));
344 int64 File::GetLength() {
347 stat_wrapper_t file_info;
348 if (CallFstat(file_, &file_info))
351 return file_info.st_size;
354 bool File::SetLength(int64 length) {
355 base::ThreadRestrictions::AssertIOAllowed();
357 return !CallFtruncate(file_, length);
361 base::ThreadRestrictions::AssertIOAllowed();
363 return !CallFsync(file_);
366 bool File::SetTimes(Time last_access_time, Time last_modified_time) {
367 base::ThreadRestrictions::AssertIOAllowed();
371 times[0] = last_access_time.ToTimeVal();
372 times[1] = last_modified_time.ToTimeVal();
374 return !CallFutimes(file_, times);
377 bool File::GetInfo(Info* info) {
380 stat_wrapper_t file_info;
381 if (CallFstat(file_, &file_info))
384 info->is_directory = S_ISDIR(file_info.st_mode);
385 info->is_symbolic_link = S_ISLNK(file_info.st_mode);
386 info->size = file_info.st_size;
388 #if defined(OS_LINUX)
389 const time_t last_modified_sec = file_info.st_mtim.tv_sec;
390 const int64 last_modified_nsec = file_info.st_mtim.tv_nsec;
391 const time_t last_accessed_sec = file_info.st_atim.tv_sec;
392 const int64 last_accessed_nsec = file_info.st_atim.tv_nsec;
393 const time_t creation_time_sec = file_info.st_ctim.tv_sec;
394 const int64 creation_time_nsec = file_info.st_ctim.tv_nsec;
395 #elif defined(OS_ANDROID)
396 const time_t last_modified_sec = file_info.st_mtime;
397 const int64 last_modified_nsec = file_info.st_mtime_nsec;
398 const time_t last_accessed_sec = file_info.st_atime;
399 const int64 last_accessed_nsec = file_info.st_atime_nsec;
400 const time_t creation_time_sec = file_info.st_ctime;
401 const int64 creation_time_nsec = file_info.st_ctime_nsec;
402 #elif defined(OS_MACOSX) || defined(OS_IOS) || defined(OS_BSD)
403 const time_t last_modified_sec = file_info.st_mtimespec.tv_sec;
404 const int64 last_modified_nsec = file_info.st_mtimespec.tv_nsec;
405 const time_t last_accessed_sec = file_info.st_atimespec.tv_sec;
406 const int64 last_accessed_nsec = file_info.st_atimespec.tv_nsec;
407 const time_t creation_time_sec = file_info.st_ctimespec.tv_sec;
408 const int64 creation_time_nsec = file_info.st_ctimespec.tv_nsec;
410 // TODO(gavinp): Investigate a good high resolution option for OS_NACL.
411 const time_t last_modified_sec = file_info.st_mtime;
412 const int64 last_modified_nsec = 0;
413 const time_t last_accessed_sec = file_info.st_atime;
414 const int64 last_accessed_nsec = 0;
415 const time_t creation_time_sec = file_info.st_ctime;
416 const int64 creation_time_nsec = 0;
419 info->last_modified =
420 base::Time::FromTimeT(last_modified_sec) +
421 base::TimeDelta::FromMicroseconds(last_modified_nsec /
422 base::Time::kNanosecondsPerMicrosecond);
423 info->last_accessed =
424 base::Time::FromTimeT(last_accessed_sec) +
425 base::TimeDelta::FromMicroseconds(last_accessed_nsec /
426 base::Time::kNanosecondsPerMicrosecond);
427 info->creation_time =
428 base::Time::FromTimeT(creation_time_sec) +
429 base::TimeDelta::FromMicroseconds(creation_time_nsec /
430 base::Time::kNanosecondsPerMicrosecond);
434 File::Error File::Lock() {
435 return CallFctnlFlock(file_, true);
438 File::Error File::Unlock() {
439 return CallFctnlFlock(file_, false);
443 File::Error File::OSErrorToFileError(int saved_errno) {
444 switch (saved_errno) {
449 return FILE_ERROR_ACCESS_DENIED;
450 #if !defined(OS_NACL) // ETXTBSY not defined by NaCl.
452 return FILE_ERROR_IN_USE;
455 return FILE_ERROR_EXISTS;
457 return FILE_ERROR_NOT_FOUND;
459 return FILE_ERROR_TOO_MANY_OPENED;
461 return FILE_ERROR_NO_MEMORY;
463 return FILE_ERROR_NO_SPACE;
465 return FILE_ERROR_NOT_A_DIRECTORY;
467 #if !defined(OS_NACL) // NaCl build has no metrics code.
468 UMA_HISTOGRAM_SPARSE_SLOWLY("PlatformFile.UnknownErrors.Posix",
471 return FILE_ERROR_FAILED;
475 void File::SetPlatformFile(PlatformFile file) {
476 DCHECK_EQ(file_, kInvalidPlatformFileValue);