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 #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"
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
);
32 #if defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL)
33 static int CallFstat(int fd
, stat_wrapper_t
*sb
) {
34 ThreadRestrictions::AssertIOAllowed();
38 static int CallFstat(int fd
, stat_wrapper_t
*sb
) {
39 ThreadRestrictions::AssertIOAllowed();
40 return fstat64(fd
, sb
);
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.
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]) {
57 // futimens should be available, but futimes might not be
58 // http://pubs.opengroup.org/onlinepubs/9699919799/
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
);
68 return futimes(file
, times
);
72 static File::Error
CallFctnlFlock(PlatformFile file
, bool do_lock
) {
74 lock
.l_type
= F_WRLCK
;
75 lock
.l_whence
= SEEK_SET
;
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
);
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
91 static int CallFtruncate(PlatformFile file
, int64 length
) {
92 NOTIMPLEMENTED(); // NaCl doesn't implement ftruncate.
96 static int CallFutimes(PlatformFile file
, const struct timeval times
[2]) {
97 NOTIMPLEMENTED(); // NaCl doesn't implement futimes.
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)
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
;
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;
145 Time::FromTimeT(last_modified_sec
) +
146 TimeDelta::FromMicroseconds(last_modified_nsec
/
147 Time::kNanosecondsPerMicrosecond
);
150 Time::FromTimeT(last_accessed_sec
) +
151 TimeDelta::FromMicroseconds(last_accessed_nsec
/
152 Time::kNanosecondsPerMicrosecond
);
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 {
168 PlatformFile
File::TakePlatformFile() {
169 return file_
.release();
176 ThreadRestrictions::AssertIOAllowed();
180 int64
File::Seek(Whence whence
, int64 offset
) {
181 ThreadRestrictions::AssertIOAllowed();
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
));
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
));
195 int File::Read(int64 offset
, char* data
, int size
) {
196 ThreadRestrictions::AssertIOAllowed();
204 rv
= HANDLE_EINTR(pread(file_
.get(), data
+ bytes_read
,
205 size
- bytes_read
, offset
+ bytes_read
));
210 } while (bytes_read
< size
);
212 return bytes_read
? bytes_read
: rv
;
215 int File::ReadAtCurrentPos(char* data
, int size
) {
216 ThreadRestrictions::AssertIOAllowed();
224 rv
= HANDLE_EINTR(read(file_
.get(), data
+ bytes_read
, size
- bytes_read
));
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();
238 return HANDLE_EINTR(pread(file_
.get(), data
, size
, offset
));
241 int File::ReadAtCurrentPosNoBestEffort(char* data
, int size
) {
242 ThreadRestrictions::AssertIOAllowed();
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
);
260 int bytes_written
= 0;
263 rv
= HANDLE_EINTR(pwrite(file_
.get(), data
+ bytes_written
,
264 size
- bytes_written
, offset
+ bytes_written
));
269 } while (bytes_written
< size
);
271 return bytes_written
? bytes_written
: rv
;
274 int File::WriteAtCurrentPos(const char* data
, int size
) {
275 ThreadRestrictions::AssertIOAllowed();
280 int bytes_written
= 0;
283 rv
= HANDLE_EINTR(write(file_
.get(), data
+ bytes_written
,
284 size
- bytes_written
));
289 } while (bytes_written
< size
);
291 return bytes_written
? bytes_written
: rv
;
294 int File::WriteAtCurrentPosNoBestEffort(const char* data
, int size
) {
295 ThreadRestrictions::AssertIOAllowed();
300 return HANDLE_EINTR(write(file_
.get(), data
, size
));
303 int64
File::GetLength() {
306 stat_wrapper_t file_info
;
307 if (CallFstat(file_
.get(), &file_info
))
310 return file_info
.st_size
;
313 bool File::SetLength(int64 length
) {
314 ThreadRestrictions::AssertIOAllowed();
316 return !CallFtruncate(file_
.get(), length
);
319 bool File::SetTimes(Time last_access_time
, Time last_modified_time
) {
320 ThreadRestrictions::AssertIOAllowed();
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
) {
333 stat_wrapper_t file_info
;
334 if (CallFstat(file_
.get(), &file_info
))
337 info
->FromStat(file_info
);
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() {
353 PlatformFile other_fd
= dup(GetPlatformFile());
355 return File(OSErrorToFileError(errno
));
357 File
other(other_fd
);
364 File::Error
File::OSErrorToFileError(int saved_errno
) {
365 switch (saved_errno
) {
370 return FILE_ERROR_ACCESS_DENIED
;
372 #if !defined(OS_NACL) // ETXTBSY not defined by NaCl.
375 return FILE_ERROR_IN_USE
;
377 return FILE_ERROR_EXISTS
;
379 return FILE_ERROR_IO
;
381 return FILE_ERROR_NOT_FOUND
;
383 return FILE_ERROR_TOO_MANY_OPENED
;
385 return FILE_ERROR_NO_MEMORY
;
387 return FILE_ERROR_NO_SPACE
;
389 return FILE_ERROR_NOT_A_DIRECTORY
;
391 #if !defined(OS_NACL) // NaCl build has no metrics code.
392 UMA_HISTOGRAM_SPARSE_SLOWLY("PlatformFile.UnknownErrors.Posix",
395 return FILE_ERROR_FAILED
;
399 File::MemoryCheckingScopedFD::MemoryCheckingScopedFD() {
403 File::MemoryCheckingScopedFD::MemoryCheckingScopedFD(int fd
) : file_(fd
) {
407 File::MemoryCheckingScopedFD::~MemoryCheckingScopedFD() {}
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
);
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();
450 if (flags
& FLAG_CREATE
)
451 open_flags
= O_CREAT
| O_EXCL
;
455 if (flags
& FLAG_CREATE_ALWAYS
) {
457 DCHECK(flags
& FLAG_WRITE
);
458 open_flags
= O_CREAT
| O_TRUNC
;
461 if (flags
& FLAG_OPEN_TRUNCATED
) {
463 DCHECK(flags
& FLAG_WRITE
);
464 open_flags
= O_TRUNC
;
467 if (!open_flags
&& !(flags
& FLAG_OPEN
) && !(flags
& FLAG_OPEN_ALWAYS
)) {
470 error_details_
= FILE_ERROR_FAILED
;
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
)) {
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
;
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
));
514 if (descriptor
< 0) {
515 error_details_
= File::OSErrorToFileError(errno
);
519 if (flags
& (FLAG_CREATE_ALWAYS
| FLAG_CREATE
))
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();
535 NOTIMPLEMENTED(); // NaCl doesn't implement fsync.
537 #elif defined(OS_LINUX) || defined(OS_ANDROID)
538 return !HANDLE_EINTR(fdatasync(file_
.get()));
540 return !HANDLE_EINTR(fsync(file_
.get()));
544 void File::SetPlatformFile(PlatformFile file
) {
545 DCHECK(!file_
.is_valid());