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 base::ThreadRestrictions::AssertIOAllowed();
38 static int CallFstat(int fd
, stat_wrapper_t
*sb
) {
39 base::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 CallFsync(PlatformFile file
) {
56 return HANDLE_EINTR(fsync(file
));
59 static int CallFutimes(PlatformFile file
, const struct timeval times
[2]) {
61 // futimens should be available, but futimes might not be
62 // http://pubs.opengroup.org/onlinepubs/9699919799/
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
);
72 return futimes(file
, times
);
76 static File::Error
CallFctnlFlock(PlatformFile file
, bool do_lock
) {
78 lock
.l_type
= F_WRLCK
;
79 lock
.l_whence
= SEEK_SET
;
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
);
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
95 static int CallFtruncate(PlatformFile file
, int64 length
) {
96 NOTIMPLEMENTED(); // NaCl doesn't implement ftruncate.
100 static int CallFsync(PlatformFile file
) {
101 NOTIMPLEMENTED(); // NaCl doesn't implement fsync.
105 static int CallFutimes(PlatformFile file
, const struct timeval times
[2]) {
106 NOTIMPLEMENTED(); // NaCl doesn't implement futimes.
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)
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
;
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;
154 Time::FromTimeT(last_modified_sec
) +
155 TimeDelta::FromMicroseconds(last_modified_nsec
/
156 Time::kNanosecondsPerMicrosecond
);
159 Time::FromTimeT(last_accessed_sec
) +
160 TimeDelta::FromMicroseconds(last_accessed_nsec
/
161 Time::kNanosecondsPerMicrosecond
);
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();
177 if (flags
& FLAG_CREATE
)
178 open_flags
= O_CREAT
| O_EXCL
;
182 if (flags
& FLAG_CREATE_ALWAYS
) {
184 DCHECK(flags
& FLAG_WRITE
);
185 open_flags
= O_CREAT
| O_TRUNC
;
188 if (flags
& FLAG_OPEN_TRUNCATED
) {
190 DCHECK(flags
& FLAG_WRITE
);
191 open_flags
= O_TRUNC
;
194 if (!open_flags
&& !(flags
& FLAG_OPEN
) && !(flags
& FLAG_OPEN_ALWAYS
)) {
197 error_details_
= FILE_ERROR_FAILED
;
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
)) {
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
;
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
));
241 if (descriptor
< 0) {
242 error_details_
= File::OSErrorToFileError(errno
);
246 if (flags
& (FLAG_CREATE_ALWAYS
| FLAG_CREATE
))
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 {
266 PlatformFile
File::TakePlatformFile() {
267 return file_
.release();
274 base::ThreadRestrictions::AssertIOAllowed();
278 int64
File::Seek(Whence whence
, int64 offset
) {
279 base::ThreadRestrictions::AssertIOAllowed();
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
));
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
));
293 int File::Read(int64 offset
, char* data
, int size
) {
294 base::ThreadRestrictions::AssertIOAllowed();
302 rv
= HANDLE_EINTR(pread(file_
.get(), data
+ bytes_read
,
303 size
- bytes_read
, offset
+ bytes_read
));
308 } while (bytes_read
< size
);
310 return bytes_read
? bytes_read
: rv
;
313 int File::ReadAtCurrentPos(char* data
, int size
) {
314 base::ThreadRestrictions::AssertIOAllowed();
322 rv
= HANDLE_EINTR(read(file_
.get(), data
+ bytes_read
, size
- bytes_read
));
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();
336 return HANDLE_EINTR(pread(file_
.get(), data
, size
, offset
));
339 int File::ReadAtCurrentPosNoBestEffort(char* data
, int size
) {
340 base::ThreadRestrictions::AssertIOAllowed();
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
);
358 int bytes_written
= 0;
361 rv
= HANDLE_EINTR(pwrite(file_
.get(), data
+ bytes_written
,
362 size
- bytes_written
, offset
+ bytes_written
));
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();
378 int bytes_written
= 0;
381 rv
= HANDLE_EINTR(write(file_
.get(), data
+ bytes_written
,
382 size
- bytes_written
));
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();
398 return HANDLE_EINTR(write(file_
.get(), data
, size
));
401 int64
File::GetLength() {
404 stat_wrapper_t file_info
;
405 if (CallFstat(file_
.get(), &file_info
))
408 return file_info
.st_size
;
411 bool File::SetLength(int64 length
) {
412 base::ThreadRestrictions::AssertIOAllowed();
414 return !CallFtruncate(file_
.get(), length
);
418 base::ThreadRestrictions::AssertIOAllowed();
420 return !CallFsync(file_
.get());
423 bool File::SetTimes(Time last_access_time
, Time last_modified_time
) {
424 base::ThreadRestrictions::AssertIOAllowed();
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
) {
437 stat_wrapper_t file_info
;
438 if (CallFstat(file_
.get(), &file_info
))
441 info
->FromStat(file_info
);
445 File::Error
File::Lock() {
446 return CallFctnlFlock(file_
.get(), true);
449 File::Error
File::Unlock() {
450 return CallFctnlFlock(file_
.get(), false);
454 File::Error
File::OSErrorToFileError(int saved_errno
) {
455 switch (saved_errno
) {
460 return FILE_ERROR_ACCESS_DENIED
;
461 #if !defined(OS_NACL) // ETXTBSY not defined by NaCl.
463 return FILE_ERROR_IN_USE
;
466 return FILE_ERROR_EXISTS
;
468 return FILE_ERROR_NOT_FOUND
;
470 return FILE_ERROR_TOO_MANY_OPENED
;
472 return FILE_ERROR_NO_MEMORY
;
474 return FILE_ERROR_NO_SPACE
;
476 return FILE_ERROR_NOT_A_DIRECTORY
;
478 #if !defined(OS_NACL) // NaCl build has no metrics code.
479 UMA_HISTOGRAM_SPARSE_SLOWLY("PlatformFile.UnknownErrors.Posix",
482 return FILE_ERROR_FAILED
;
486 void File::SetPlatformFile(PlatformFile file
) {
487 DCHECK(!file_
.is_valid());