Docserver: Skip to version 3-45-2. There was a test instance already uploaded
[chromium-blink-merge.git] / base / files / file_posix.cc
blob43684b5dabfe3df9b2a6907cd5dfbecb8e3582c3
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 <errno.h>
8 #include <fcntl.h>
9 #include <sys/stat.h>
10 #include <unistd.h>
12 #include "base/files/file_path.h"
13 #include "base/logging.h"
14 #include "base/metrics/sparse_histogram.h"
15 #include "base/posix/eintr_wrapper.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/threading/thread_restrictions.h"
19 #if defined(OS_ANDROID)
20 #include "base/os_compat_android.h"
21 #endif
23 namespace base {
25 // Make sure our Whence mappings match the system headers.
26 COMPILE_ASSERT(File::FROM_BEGIN == SEEK_SET &&
27 File::FROM_CURRENT == SEEK_CUR &&
28 File::FROM_END == SEEK_END, whence_matches_system);
30 namespace {
32 #if defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL)
33 static int CallFstat(int fd, stat_wrapper_t *sb) {
34 base::ThreadRestrictions::AssertIOAllowed();
35 return fstat(fd, sb);
37 #else
38 static int CallFstat(int fd, stat_wrapper_t *sb) {
39 base::ThreadRestrictions::AssertIOAllowed();
40 return fstat64(fd, sb);
42 #endif
44 // NaCl doesn't provide the following system calls, so either simulate them or
45 // wrap them in order to minimize the number of #ifdef's in this file.
46 #if !defined(OS_NACL)
47 static bool IsOpenAppend(PlatformFile file) {
48 return (fcntl(file, F_GETFL) & O_APPEND) != 0;
51 static int CallFtruncate(PlatformFile file, int64 length) {
52 return HANDLE_EINTR(ftruncate(file, length));
55 static int CallFsync(PlatformFile file) {
56 return HANDLE_EINTR(fsync(file));
59 static int CallFutimes(PlatformFile file, const struct timeval times[2]) {
60 #ifdef __USE_XOPEN2K8
61 // futimens should be available, but futimes might not be
62 // http://pubs.opengroup.org/onlinepubs/9699919799/
64 timespec ts_times[2];
65 ts_times[0].tv_sec = times[0].tv_sec;
66 ts_times[0].tv_nsec = times[0].tv_usec * 1000;
67 ts_times[1].tv_sec = times[1].tv_sec;
68 ts_times[1].tv_nsec = times[1].tv_usec * 1000;
70 return futimens(file, ts_times);
71 #else
72 return futimes(file, times);
73 #endif
76 static File::Error CallFctnlFlock(PlatformFile file, bool do_lock) {
77 struct flock lock;
78 lock.l_type = F_WRLCK;
79 lock.l_whence = SEEK_SET;
80 lock.l_start = 0;
81 lock.l_len = 0; // Lock entire file.
82 if (HANDLE_EINTR(fcntl(file, do_lock ? F_SETLK : F_UNLCK, &lock)) == -1)
83 return File::OSErrorToFileError(errno);
84 return File::FILE_OK;
86 #else // defined(OS_NACL)
88 static bool IsOpenAppend(PlatformFile file) {
89 // NaCl doesn't implement fcntl. Since NaCl's write conforms to the POSIX
90 // standard and always appends if the file is opened with O_APPEND, just
91 // return false here.
92 return false;
95 static int CallFtruncate(PlatformFile file, int64 length) {
96 NOTIMPLEMENTED(); // NaCl doesn't implement ftruncate.
97 return 0;
100 static int CallFsync(PlatformFile file) {
101 NOTIMPLEMENTED(); // NaCl doesn't implement fsync.
102 return 0;
105 static int CallFutimes(PlatformFile file, const struct timeval times[2]) {
106 NOTIMPLEMENTED(); // NaCl doesn't implement futimes.
107 return 0;
110 static File::Error CallFctnlFlock(PlatformFile file, bool do_lock) {
111 NOTIMPLEMENTED(); // NaCl doesn't implement flock struct.
112 return File::FILE_ERROR_INVALID_OPERATION;
114 #endif // defined(OS_NACL)
116 } // namespace
118 void File::Info::FromStat(const stat_wrapper_t& stat_info) {
119 is_directory = S_ISDIR(stat_info.st_mode);
120 is_symbolic_link = S_ISLNK(stat_info.st_mode);
121 size = stat_info.st_size;
123 #if defined(OS_LINUX)
124 time_t last_modified_sec = stat_info.st_mtim.tv_sec;
125 int64 last_modified_nsec = stat_info.st_mtim.tv_nsec;
126 time_t last_accessed_sec = stat_info.st_atim.tv_sec;
127 int64 last_accessed_nsec = stat_info.st_atim.tv_nsec;
128 time_t creation_time_sec = stat_info.st_ctim.tv_sec;
129 int64 creation_time_nsec = stat_info.st_ctim.tv_nsec;
130 #elif defined(OS_ANDROID)
131 time_t last_modified_sec = stat_info.st_mtime;
132 int64 last_modified_nsec = stat_info.st_mtime_nsec;
133 time_t last_accessed_sec = stat_info.st_atime;
134 int64 last_accessed_nsec = stat_info.st_atime_nsec;
135 time_t creation_time_sec = stat_info.st_ctime;
136 int64 creation_time_nsec = stat_info.st_ctime_nsec;
137 #elif defined(OS_MACOSX) || defined(OS_IOS) || defined(OS_BSD)
138 time_t last_modified_sec = stat_info.st_mtimespec.tv_sec;
139 int64 last_modified_nsec = stat_info.st_mtimespec.tv_nsec;
140 time_t last_accessed_sec = stat_info.st_atimespec.tv_sec;
141 int64 last_accessed_nsec = stat_info.st_atimespec.tv_nsec;
142 time_t creation_time_sec = stat_info.st_ctimespec.tv_sec;
143 int64 creation_time_nsec = stat_info.st_ctimespec.tv_nsec;
144 #else
145 time_t last_modified_sec = stat_info.st_mtime;
146 int64 last_modified_nsec = 0;
147 time_t last_accessed_sec = stat_info.st_atime;
148 int64 last_accessed_nsec = 0;
149 time_t creation_time_sec = stat_info.st_ctime;
150 int64 creation_time_nsec = 0;
151 #endif
153 last_modified =
154 Time::FromTimeT(last_modified_sec) +
155 TimeDelta::FromMicroseconds(last_modified_nsec /
156 Time::kNanosecondsPerMicrosecond);
158 last_accessed =
159 Time::FromTimeT(last_accessed_sec) +
160 TimeDelta::FromMicroseconds(last_accessed_nsec /
161 Time::kNanosecondsPerMicrosecond);
163 creation_time =
164 Time::FromTimeT(creation_time_sec) +
165 TimeDelta::FromMicroseconds(creation_time_nsec /
166 Time::kNanosecondsPerMicrosecond);
169 // NaCl doesn't implement system calls to open files directly.
170 #if !defined(OS_NACL)
171 // TODO(erikkay): does it make sense to support FLAG_EXCLUSIVE_* here?
172 void File::InitializeUnsafe(const FilePath& name, uint32 flags) {
173 base::ThreadRestrictions::AssertIOAllowed();
174 DCHECK(!IsValid());
176 int open_flags = 0;
177 if (flags & FLAG_CREATE)
178 open_flags = O_CREAT | O_EXCL;
180 created_ = false;
182 if (flags & FLAG_CREATE_ALWAYS) {
183 DCHECK(!open_flags);
184 DCHECK(flags & FLAG_WRITE);
185 open_flags = O_CREAT | O_TRUNC;
188 if (flags & FLAG_OPEN_TRUNCATED) {
189 DCHECK(!open_flags);
190 DCHECK(flags & FLAG_WRITE);
191 open_flags = O_TRUNC;
194 if (!open_flags && !(flags & FLAG_OPEN) && !(flags & FLAG_OPEN_ALWAYS)) {
195 NOTREACHED();
196 errno = EOPNOTSUPP;
197 error_details_ = FILE_ERROR_FAILED;
198 return;
201 if (flags & FLAG_WRITE && flags & FLAG_READ) {
202 open_flags |= O_RDWR;
203 } else if (flags & FLAG_WRITE) {
204 open_flags |= O_WRONLY;
205 } else if (!(flags & FLAG_READ) &&
206 !(flags & FLAG_WRITE_ATTRIBUTES) &&
207 !(flags & FLAG_APPEND) &&
208 !(flags & FLAG_OPEN_ALWAYS)) {
209 NOTREACHED();
212 if (flags & FLAG_TERMINAL_DEVICE)
213 open_flags |= O_NOCTTY | O_NDELAY;
215 if (flags & FLAG_APPEND && flags & FLAG_READ)
216 open_flags |= O_APPEND | O_RDWR;
217 else if (flags & FLAG_APPEND)
218 open_flags |= O_APPEND | O_WRONLY;
220 COMPILE_ASSERT(O_RDONLY == 0, O_RDONLY_must_equal_zero);
222 int mode = S_IRUSR | S_IWUSR;
223 #if defined(OS_CHROMEOS)
224 mode |= S_IRGRP | S_IROTH;
225 #endif
227 int descriptor = HANDLE_EINTR(open(name.value().c_str(), open_flags, mode));
229 if (flags & FLAG_OPEN_ALWAYS) {
230 if (descriptor < 0) {
231 open_flags |= O_CREAT;
232 if (flags & FLAG_EXCLUSIVE_READ || flags & FLAG_EXCLUSIVE_WRITE)
233 open_flags |= O_EXCL; // together with O_CREAT implies O_NOFOLLOW
235 descriptor = HANDLE_EINTR(open(name.value().c_str(), open_flags, mode));
236 if (descriptor >= 0)
237 created_ = true;
241 if (descriptor < 0) {
242 error_details_ = File::OSErrorToFileError(errno);
243 return;
246 if (flags & (FLAG_CREATE_ALWAYS | FLAG_CREATE))
247 created_ = true;
249 if (flags & FLAG_DELETE_ON_CLOSE)
250 unlink(name.value().c_str());
252 async_ = ((flags & FLAG_ASYNC) == FLAG_ASYNC);
253 error_details_ = FILE_OK;
254 file_.reset(descriptor);
256 #endif // !defined(OS_NACL)
258 bool File::IsValid() const {
259 return file_.is_valid();
262 PlatformFile File::GetPlatformFile() const {
263 return file_.get();
266 PlatformFile File::TakePlatformFile() {
267 return file_.release();
270 void File::Close() {
271 if (!IsValid())
272 return;
274 base::ThreadRestrictions::AssertIOAllowed();
275 file_.reset();
278 int64 File::Seek(Whence whence, int64 offset) {
279 base::ThreadRestrictions::AssertIOAllowed();
280 DCHECK(IsValid());
282 #if defined(OS_ANDROID)
283 COMPILE_ASSERT(sizeof(int64) == sizeof(off64_t), off64_t_64_bit);
284 return lseek64(file_.get(), static_cast<off64_t>(offset),
285 static_cast<int>(whence));
286 #else
287 COMPILE_ASSERT(sizeof(int64) == sizeof(off_t), off_t_64_bit);
288 return lseek(file_.get(), static_cast<off_t>(offset),
289 static_cast<int>(whence));
290 #endif
293 int File::Read(int64 offset, char* data, int size) {
294 base::ThreadRestrictions::AssertIOAllowed();
295 DCHECK(IsValid());
296 if (size < 0)
297 return -1;
299 int bytes_read = 0;
300 int rv;
301 do {
302 rv = HANDLE_EINTR(pread(file_.get(), data + bytes_read,
303 size - bytes_read, offset + bytes_read));
304 if (rv <= 0)
305 break;
307 bytes_read += rv;
308 } while (bytes_read < size);
310 return bytes_read ? bytes_read : rv;
313 int File::ReadAtCurrentPos(char* data, int size) {
314 base::ThreadRestrictions::AssertIOAllowed();
315 DCHECK(IsValid());
316 if (size < 0)
317 return -1;
319 int bytes_read = 0;
320 int rv;
321 do {
322 rv = HANDLE_EINTR(read(file_.get(), data + bytes_read, size - bytes_read));
323 if (rv <= 0)
324 break;
326 bytes_read += rv;
327 } while (bytes_read < size);
329 return bytes_read ? bytes_read : rv;
332 int File::ReadNoBestEffort(int64 offset, char* data, int size) {
333 base::ThreadRestrictions::AssertIOAllowed();
334 DCHECK(IsValid());
336 return HANDLE_EINTR(pread(file_.get(), data, size, offset));
339 int File::ReadAtCurrentPosNoBestEffort(char* data, int size) {
340 base::ThreadRestrictions::AssertIOAllowed();
341 DCHECK(IsValid());
342 if (size < 0)
343 return -1;
345 return HANDLE_EINTR(read(file_.get(), data, size));
348 int File::Write(int64 offset, const char* data, int size) {
349 base::ThreadRestrictions::AssertIOAllowed();
351 if (IsOpenAppend(file_.get()))
352 return WriteAtCurrentPos(data, size);
354 DCHECK(IsValid());
355 if (size < 0)
356 return -1;
358 int bytes_written = 0;
359 int rv;
360 do {
361 rv = HANDLE_EINTR(pwrite(file_.get(), data + bytes_written,
362 size - bytes_written, offset + bytes_written));
363 if (rv <= 0)
364 break;
366 bytes_written += rv;
367 } while (bytes_written < size);
369 return bytes_written ? bytes_written : rv;
372 int File::WriteAtCurrentPos(const char* data, int size) {
373 base::ThreadRestrictions::AssertIOAllowed();
374 DCHECK(IsValid());
375 if (size < 0)
376 return -1;
378 int bytes_written = 0;
379 int rv;
380 do {
381 rv = HANDLE_EINTR(write(file_.get(), data + bytes_written,
382 size - bytes_written));
383 if (rv <= 0)
384 break;
386 bytes_written += rv;
387 } while (bytes_written < size);
389 return bytes_written ? bytes_written : rv;
392 int File::WriteAtCurrentPosNoBestEffort(const char* data, int size) {
393 base::ThreadRestrictions::AssertIOAllowed();
394 DCHECK(IsValid());
395 if (size < 0)
396 return -1;
398 return HANDLE_EINTR(write(file_.get(), data, size));
401 int64 File::GetLength() {
402 DCHECK(IsValid());
404 stat_wrapper_t file_info;
405 if (CallFstat(file_.get(), &file_info))
406 return false;
408 return file_info.st_size;
411 bool File::SetLength(int64 length) {
412 base::ThreadRestrictions::AssertIOAllowed();
413 DCHECK(IsValid());
414 return !CallFtruncate(file_.get(), length);
417 bool File::Flush() {
418 base::ThreadRestrictions::AssertIOAllowed();
419 DCHECK(IsValid());
420 return !CallFsync(file_.get());
423 bool File::SetTimes(Time last_access_time, Time last_modified_time) {
424 base::ThreadRestrictions::AssertIOAllowed();
425 DCHECK(IsValid());
427 timeval times[2];
428 times[0] = last_access_time.ToTimeVal();
429 times[1] = last_modified_time.ToTimeVal();
431 return !CallFutimes(file_.get(), times);
434 bool File::GetInfo(Info* info) {
435 DCHECK(IsValid());
437 stat_wrapper_t file_info;
438 if (CallFstat(file_.get(), &file_info))
439 return false;
441 info->FromStat(file_info);
442 return true;
445 File::Error File::Lock() {
446 return CallFctnlFlock(file_.get(), true);
449 File::Error File::Unlock() {
450 return CallFctnlFlock(file_.get(), false);
453 // Static.
454 File::Error File::OSErrorToFileError(int saved_errno) {
455 switch (saved_errno) {
456 case EACCES:
457 case EISDIR:
458 case EROFS:
459 case EPERM:
460 return FILE_ERROR_ACCESS_DENIED;
461 #if !defined(OS_NACL) // ETXTBSY not defined by NaCl.
462 case ETXTBSY:
463 return FILE_ERROR_IN_USE;
464 #endif
465 case EEXIST:
466 return FILE_ERROR_EXISTS;
467 case ENOENT:
468 return FILE_ERROR_NOT_FOUND;
469 case EMFILE:
470 return FILE_ERROR_TOO_MANY_OPENED;
471 case ENOMEM:
472 return FILE_ERROR_NO_MEMORY;
473 case ENOSPC:
474 return FILE_ERROR_NO_SPACE;
475 case ENOTDIR:
476 return FILE_ERROR_NOT_A_DIRECTORY;
477 default:
478 #if !defined(OS_NACL) // NaCl build has no metrics code.
479 UMA_HISTOGRAM_SPARSE_SLOWLY("PlatformFile.UnknownErrors.Posix",
480 saved_errno);
481 #endif
482 return FILE_ERROR_FAILED;
486 void File::SetPlatformFile(PlatformFile file) {
487 DCHECK(!file_.is_valid());
488 file_.reset(file);
491 } // namespace base