Supervised user import: Listen for profile creation/deletion
[chromium-blink-merge.git] / base / files / file_posix.cc
blob4c790571e8d6aeb732c6abfa038e51a7191edaa1
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 ThreadRestrictions::AssertIOAllowed();
35 return fstat(fd, sb);
37 #else
38 static int CallFstat(int fd, stat_wrapper_t *sb) {
39 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 CallFutimes(PlatformFile file, const struct timeval times[2]) {
56 #ifdef __USE_XOPEN2K8
57 // futimens should be available, but futimes might not be
58 // http://pubs.opengroup.org/onlinepubs/9699919799/
60 timespec ts_times[2];
61 ts_times[0].tv_sec = times[0].tv_sec;
62 ts_times[0].tv_nsec = times[0].tv_usec * 1000;
63 ts_times[1].tv_sec = times[1].tv_sec;
64 ts_times[1].tv_nsec = times[1].tv_usec * 1000;
66 return futimens(file, ts_times);
67 #else
68 return futimes(file, times);
69 #endif
72 static File::Error CallFctnlFlock(PlatformFile file, bool do_lock) {
73 struct flock lock;
74 lock.l_type = F_WRLCK;
75 lock.l_whence = SEEK_SET;
76 lock.l_start = 0;
77 lock.l_len = 0; // Lock entire file.
78 if (HANDLE_EINTR(fcntl(file, do_lock ? F_SETLK : F_UNLCK, &lock)) == -1)
79 return File::OSErrorToFileError(errno);
80 return File::FILE_OK;
82 #else // defined(OS_NACL)
84 static bool IsOpenAppend(PlatformFile file) {
85 // NaCl doesn't implement fcntl. Since NaCl's write conforms to the POSIX
86 // standard and always appends if the file is opened with O_APPEND, just
87 // return false here.
88 return false;
91 static int CallFtruncate(PlatformFile file, int64 length) {
92 NOTIMPLEMENTED(); // NaCl doesn't implement ftruncate.
93 return 0;
96 static int CallFutimes(PlatformFile file, const struct timeval times[2]) {
97 NOTIMPLEMENTED(); // NaCl doesn't implement futimes.
98 return 0;
101 static File::Error CallFctnlFlock(PlatformFile file, bool do_lock) {
102 NOTIMPLEMENTED(); // NaCl doesn't implement flock struct.
103 return File::FILE_ERROR_INVALID_OPERATION;
105 #endif // defined(OS_NACL)
107 } // namespace
109 void File::Info::FromStat(const stat_wrapper_t& stat_info) {
110 is_directory = S_ISDIR(stat_info.st_mode);
111 is_symbolic_link = S_ISLNK(stat_info.st_mode);
112 size = stat_info.st_size;
114 #if defined(OS_LINUX)
115 time_t last_modified_sec = stat_info.st_mtim.tv_sec;
116 int64 last_modified_nsec = stat_info.st_mtim.tv_nsec;
117 time_t last_accessed_sec = stat_info.st_atim.tv_sec;
118 int64 last_accessed_nsec = stat_info.st_atim.tv_nsec;
119 time_t creation_time_sec = stat_info.st_ctim.tv_sec;
120 int64 creation_time_nsec = stat_info.st_ctim.tv_nsec;
121 #elif defined(OS_ANDROID)
122 time_t last_modified_sec = stat_info.st_mtime;
123 int64 last_modified_nsec = stat_info.st_mtime_nsec;
124 time_t last_accessed_sec = stat_info.st_atime;
125 int64 last_accessed_nsec = stat_info.st_atime_nsec;
126 time_t creation_time_sec = stat_info.st_ctime;
127 int64 creation_time_nsec = stat_info.st_ctime_nsec;
128 #elif defined(OS_MACOSX) || defined(OS_IOS) || defined(OS_BSD)
129 time_t last_modified_sec = stat_info.st_mtimespec.tv_sec;
130 int64 last_modified_nsec = stat_info.st_mtimespec.tv_nsec;
131 time_t last_accessed_sec = stat_info.st_atimespec.tv_sec;
132 int64 last_accessed_nsec = stat_info.st_atimespec.tv_nsec;
133 time_t creation_time_sec = stat_info.st_ctimespec.tv_sec;
134 int64 creation_time_nsec = stat_info.st_ctimespec.tv_nsec;
135 #else
136 time_t last_modified_sec = stat_info.st_mtime;
137 int64 last_modified_nsec = 0;
138 time_t last_accessed_sec = stat_info.st_atime;
139 int64 last_accessed_nsec = 0;
140 time_t creation_time_sec = stat_info.st_ctime;
141 int64 creation_time_nsec = 0;
142 #endif
144 last_modified =
145 Time::FromTimeT(last_modified_sec) +
146 TimeDelta::FromMicroseconds(last_modified_nsec /
147 Time::kNanosecondsPerMicrosecond);
149 last_accessed =
150 Time::FromTimeT(last_accessed_sec) +
151 TimeDelta::FromMicroseconds(last_accessed_nsec /
152 Time::kNanosecondsPerMicrosecond);
154 creation_time =
155 Time::FromTimeT(creation_time_sec) +
156 TimeDelta::FromMicroseconds(creation_time_nsec /
157 Time::kNanosecondsPerMicrosecond);
160 bool File::IsValid() const {
161 return file_.is_valid();
164 PlatformFile File::GetPlatformFile() const {
165 return file_.get();
168 PlatformFile File::TakePlatformFile() {
169 return file_.release();
172 void File::Close() {
173 if (!IsValid())
174 return;
176 ThreadRestrictions::AssertIOAllowed();
177 file_.reset();
180 int64 File::Seek(Whence whence, int64 offset) {
181 ThreadRestrictions::AssertIOAllowed();
182 DCHECK(IsValid());
184 #if defined(OS_ANDROID)
185 COMPILE_ASSERT(sizeof(int64) == sizeof(off64_t), off64_t_64_bit);
186 return lseek64(file_.get(), static_cast<off64_t>(offset),
187 static_cast<int>(whence));
188 #else
189 COMPILE_ASSERT(sizeof(int64) == sizeof(off_t), off_t_64_bit);
190 return lseek(file_.get(), static_cast<off_t>(offset),
191 static_cast<int>(whence));
192 #endif
195 int File::Read(int64 offset, char* data, int size) {
196 ThreadRestrictions::AssertIOAllowed();
197 DCHECK(IsValid());
198 if (size < 0)
199 return -1;
201 int bytes_read = 0;
202 int rv;
203 do {
204 rv = HANDLE_EINTR(pread(file_.get(), data + bytes_read,
205 size - bytes_read, offset + bytes_read));
206 if (rv <= 0)
207 break;
209 bytes_read += rv;
210 } while (bytes_read < size);
212 return bytes_read ? bytes_read : rv;
215 int File::ReadAtCurrentPos(char* data, int size) {
216 ThreadRestrictions::AssertIOAllowed();
217 DCHECK(IsValid());
218 if (size < 0)
219 return -1;
221 int bytes_read = 0;
222 int rv;
223 do {
224 rv = HANDLE_EINTR(read(file_.get(), data + bytes_read, size - bytes_read));
225 if (rv <= 0)
226 break;
228 bytes_read += rv;
229 } while (bytes_read < size);
231 return bytes_read ? bytes_read : rv;
234 int File::ReadNoBestEffort(int64 offset, char* data, int size) {
235 ThreadRestrictions::AssertIOAllowed();
236 DCHECK(IsValid());
238 return HANDLE_EINTR(pread(file_.get(), data, size, offset));
241 int File::ReadAtCurrentPosNoBestEffort(char* data, int size) {
242 ThreadRestrictions::AssertIOAllowed();
243 DCHECK(IsValid());
244 if (size < 0)
245 return -1;
247 return HANDLE_EINTR(read(file_.get(), data, size));
250 int File::Write(int64 offset, const char* data, int size) {
251 ThreadRestrictions::AssertIOAllowed();
253 if (IsOpenAppend(file_.get()))
254 return WriteAtCurrentPos(data, size);
256 DCHECK(IsValid());
257 if (size < 0)
258 return -1;
260 int bytes_written = 0;
261 int rv;
262 do {
263 rv = HANDLE_EINTR(pwrite(file_.get(), data + bytes_written,
264 size - bytes_written, offset + bytes_written));
265 if (rv <= 0)
266 break;
268 bytes_written += rv;
269 } while (bytes_written < size);
271 return bytes_written ? bytes_written : rv;
274 int File::WriteAtCurrentPos(const char* data, int size) {
275 ThreadRestrictions::AssertIOAllowed();
276 DCHECK(IsValid());
277 if (size < 0)
278 return -1;
280 int bytes_written = 0;
281 int rv;
282 do {
283 rv = HANDLE_EINTR(write(file_.get(), data + bytes_written,
284 size - bytes_written));
285 if (rv <= 0)
286 break;
288 bytes_written += rv;
289 } while (bytes_written < size);
291 return bytes_written ? bytes_written : rv;
294 int File::WriteAtCurrentPosNoBestEffort(const char* data, int size) {
295 ThreadRestrictions::AssertIOAllowed();
296 DCHECK(IsValid());
297 if (size < 0)
298 return -1;
300 return HANDLE_EINTR(write(file_.get(), data, size));
303 int64 File::GetLength() {
304 DCHECK(IsValid());
306 stat_wrapper_t file_info;
307 if (CallFstat(file_.get(), &file_info))
308 return false;
310 return file_info.st_size;
313 bool File::SetLength(int64 length) {
314 ThreadRestrictions::AssertIOAllowed();
315 DCHECK(IsValid());
316 return !CallFtruncate(file_.get(), length);
319 bool File::SetTimes(Time last_access_time, Time last_modified_time) {
320 ThreadRestrictions::AssertIOAllowed();
321 DCHECK(IsValid());
323 timeval times[2];
324 times[0] = last_access_time.ToTimeVal();
325 times[1] = last_modified_time.ToTimeVal();
327 return !CallFutimes(file_.get(), times);
330 bool File::GetInfo(Info* info) {
331 DCHECK(IsValid());
333 stat_wrapper_t file_info;
334 if (CallFstat(file_.get(), &file_info))
335 return false;
337 info->FromStat(file_info);
338 return true;
341 File::Error File::Lock() {
342 return CallFctnlFlock(file_.get(), true);
345 File::Error File::Unlock() {
346 return CallFctnlFlock(file_.get(), false);
349 File File::Duplicate() {
350 if (!IsValid())
351 return File();
353 PlatformFile other_fd = dup(GetPlatformFile());
354 if (other_fd == -1)
355 return File(OSErrorToFileError(errno));
357 File other(other_fd);
358 if (async())
359 other.async_ = true;
360 return other.Pass();
363 // Static.
364 File::Error File::OSErrorToFileError(int saved_errno) {
365 switch (saved_errno) {
366 case EACCES:
367 case EISDIR:
368 case EROFS:
369 case EPERM:
370 return FILE_ERROR_ACCESS_DENIED;
371 case EBUSY:
372 #if !defined(OS_NACL) // ETXTBSY not defined by NaCl.
373 case ETXTBSY:
374 #endif
375 return FILE_ERROR_IN_USE;
376 case EEXIST:
377 return FILE_ERROR_EXISTS;
378 case EIO:
379 return FILE_ERROR_IO;
380 case ENOENT:
381 return FILE_ERROR_NOT_FOUND;
382 case EMFILE:
383 return FILE_ERROR_TOO_MANY_OPENED;
384 case ENOMEM:
385 return FILE_ERROR_NO_MEMORY;
386 case ENOSPC:
387 return FILE_ERROR_NO_SPACE;
388 case ENOTDIR:
389 return FILE_ERROR_NOT_A_DIRECTORY;
390 default:
391 #if !defined(OS_NACL) // NaCl build has no metrics code.
392 UMA_HISTOGRAM_SPARSE_SLOWLY("PlatformFile.UnknownErrors.Posix",
393 saved_errno);
394 #endif
395 return FILE_ERROR_FAILED;
399 File::MemoryCheckingScopedFD::MemoryCheckingScopedFD() {
400 UpdateChecksum();
403 File::MemoryCheckingScopedFD::MemoryCheckingScopedFD(int fd) : file_(fd) {
404 UpdateChecksum();
407 File::MemoryCheckingScopedFD::~MemoryCheckingScopedFD() {}
409 // static
410 void File::MemoryCheckingScopedFD::ComputeMemoryChecksum(
411 unsigned int* out_checksum) const {
412 // Use a single iteration of a linear congruentional generator (lcg) to
413 // provide a cheap checksum unlikely to be accidentally matched by a random
414 // memory corruption.
416 // By choosing constants that satisfy the Hull-Duebell Theorem on lcg cycle
417 // length, we insure that each distinct fd value maps to a distinct checksum,
418 // which maximises the utility of our checksum.
420 // This code uses "unsigned int" throughout for its defined modular semantics,
421 // which implicitly gives us a divisor that is a power of two.
423 const unsigned int kMultiplier = 13035 * 4 + 1;
424 COMPILE_ASSERT(((kMultiplier - 1) & 3) == 0, pred_must_be_multiple_of_four);
425 const unsigned int kIncrement = 1595649551;
426 COMPILE_ASSERT(kIncrement & 1, must_be_coprime_to_powers_of_two);
428 *out_checksum =
429 static_cast<unsigned int>(file_.get()) * kMultiplier + kIncrement;
432 void File::MemoryCheckingScopedFD::Check() const {
433 unsigned int computed_checksum;
434 ComputeMemoryChecksum(&computed_checksum);
435 CHECK_EQ(file_memory_checksum_, computed_checksum) << "corrupted fd memory";
438 void File::MemoryCheckingScopedFD::UpdateChecksum() {
439 ComputeMemoryChecksum(&file_memory_checksum_);
442 // NaCl doesn't implement system calls to open files directly.
443 #if !defined(OS_NACL)
444 // TODO(erikkay): does it make sense to support FLAG_EXCLUSIVE_* here?
445 void File::DoInitialize(const FilePath& name, uint32 flags) {
446 ThreadRestrictions::AssertIOAllowed();
447 DCHECK(!IsValid());
449 int open_flags = 0;
450 if (flags & FLAG_CREATE)
451 open_flags = O_CREAT | O_EXCL;
453 created_ = false;
455 if (flags & FLAG_CREATE_ALWAYS) {
456 DCHECK(!open_flags);
457 DCHECK(flags & FLAG_WRITE);
458 open_flags = O_CREAT | O_TRUNC;
461 if (flags & FLAG_OPEN_TRUNCATED) {
462 DCHECK(!open_flags);
463 DCHECK(flags & FLAG_WRITE);
464 open_flags = O_TRUNC;
467 if (!open_flags && !(flags & FLAG_OPEN) && !(flags & FLAG_OPEN_ALWAYS)) {
468 NOTREACHED();
469 errno = EOPNOTSUPP;
470 error_details_ = FILE_ERROR_FAILED;
471 return;
474 if (flags & FLAG_WRITE && flags & FLAG_READ) {
475 open_flags |= O_RDWR;
476 } else if (flags & FLAG_WRITE) {
477 open_flags |= O_WRONLY;
478 } else if (!(flags & FLAG_READ) &&
479 !(flags & FLAG_WRITE_ATTRIBUTES) &&
480 !(flags & FLAG_APPEND) &&
481 !(flags & FLAG_OPEN_ALWAYS)) {
482 NOTREACHED();
485 if (flags & FLAG_TERMINAL_DEVICE)
486 open_flags |= O_NOCTTY | O_NDELAY;
488 if (flags & FLAG_APPEND && flags & FLAG_READ)
489 open_flags |= O_APPEND | O_RDWR;
490 else if (flags & FLAG_APPEND)
491 open_flags |= O_APPEND | O_WRONLY;
493 COMPILE_ASSERT(O_RDONLY == 0, O_RDONLY_must_equal_zero);
495 int mode = S_IRUSR | S_IWUSR;
496 #if defined(OS_CHROMEOS)
497 mode |= S_IRGRP | S_IROTH;
498 #endif
500 int descriptor = HANDLE_EINTR(open(name.value().c_str(), open_flags, mode));
502 if (flags & FLAG_OPEN_ALWAYS) {
503 if (descriptor < 0) {
504 open_flags |= O_CREAT;
505 if (flags & FLAG_EXCLUSIVE_READ || flags & FLAG_EXCLUSIVE_WRITE)
506 open_flags |= O_EXCL; // together with O_CREAT implies O_NOFOLLOW
508 descriptor = HANDLE_EINTR(open(name.value().c_str(), open_flags, mode));
509 if (descriptor >= 0)
510 created_ = true;
514 if (descriptor < 0) {
515 error_details_ = File::OSErrorToFileError(errno);
516 return;
519 if (flags & (FLAG_CREATE_ALWAYS | FLAG_CREATE))
520 created_ = true;
522 if (flags & FLAG_DELETE_ON_CLOSE)
523 unlink(name.value().c_str());
525 async_ = ((flags & FLAG_ASYNC) == FLAG_ASYNC);
526 error_details_ = FILE_OK;
527 file_.reset(descriptor);
529 #endif // !defined(OS_NACL)
531 bool File::DoFlush() {
532 ThreadRestrictions::AssertIOAllowed();
533 DCHECK(IsValid());
534 #if defined(OS_NACL)
535 NOTIMPLEMENTED(); // NaCl doesn't implement fsync.
536 return true;
537 #elif defined(OS_LINUX) || defined(OS_ANDROID)
538 return !HANDLE_EINTR(fdatasync(file_.get()));
539 #else
540 return !HANDLE_EINTR(fsync(file_.get()));
541 #endif
544 void File::SetPlatformFile(PlatformFile file) {
545 DCHECK(!file_.is_valid());
546 file_.reset(file);
549 } // namespace base