blob: 6b5d83d57323af0dfe9f7bd9b84b115dc62e3a54 [file] [log] [blame]
[email protected]9ad009a2013-11-28 01:31:311// 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.
4
[email protected]f62ac7d2013-12-04 00:46:325#ifndef BASE_FILES_FILE_H_
6#define BASE_FILES_FILE_H_
[email protected]9ad009a2013-11-28 01:31:317
avi543540e2015-12-24 05:15:328#include <stdint.h>
[email protected]f745d722014-04-05 02:39:189
[email protected]b73427e2014-05-30 10:07:3010#include <string>
11
[email protected]9ad009a2013-11-28 01:31:3112#include "base/base_export.h"
dbeam492dc31b2015-05-11 07:53:4713#include "base/files/file_path.h"
14#include "base/files/file_tracing.h"
[email protected]49ec0312014-03-18 02:39:0315#include "base/files/scoped_file.h"
[email protected]f62ac7d2013-12-04 00:46:3216#include "base/move.h"
[email protected]9ad009a2013-11-28 01:31:3117#include "base/time/time.h"
avi543540e2015-12-24 05:15:3218#include "build/build_config.h"
[email protected]9ad009a2013-11-28 01:31:3119
[email protected]f62ac7d2013-12-04 00:46:3220#if defined(OS_WIN)
avi543540e2015-12-24 05:15:3221#include <windows.h>
[email protected]f62ac7d2013-12-04 00:46:3222#include "base/win/scoped_handle.h"
23#endif
24
avi543540e2015-12-24 05:15:3225#if defined(OS_POSIX)
26#include <sys/stat.h>
27#endif
28
[email protected]9ad009a2013-11-28 01:31:3129namespace base {
30
[email protected]9ad009a2013-11-28 01:31:3131#if defined(OS_WIN)
rockot5d4213ff2016-05-25 19:07:1032using PlatformFile = HANDLE;
[email protected]9ad009a2013-11-28 01:31:3133
rockot5d4213ff2016-05-25 19:07:1034const PlatformFile kInvalidPlatformFile = INVALID_HANDLE_VALUE;
35#elif defined(OS_POSIX)
36using PlatformFile = int;
37
38const PlatformFile kInvalidPlatformFile = -1;
[email protected]f745d722014-04-05 02:39:1839#if defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL)
40typedef struct stat stat_wrapper_t;
41#else
42typedef struct stat64 stat_wrapper_t;
43#endif
44#endif // defined(OS_POSIX)
[email protected]f62ac7d2013-12-04 00:46:3245
46// Thin wrapper around an OS-level file.
47// Note that this class does not provide any support for asynchronous IO, other
48// than the ability to create asynchronous handles on Windows.
[email protected]9ad009a2013-11-28 01:31:3149//
[email protected]f62ac7d2013-12-04 00:46:3250// Note about const: this class does not attempt to determine if the underlying
51// file system object is affected by a particular method in order to consider
52// that method const or not. Only methods that deal with member variables in an
53// obvious non-modifying way are marked as const. Any method that forward calls
54// to the OS is not considered const, even if there is no apparent change to
55// member variables.
56class BASE_EXPORT File {
dchenge1b0277c2015-12-01 12:09:5257 MOVE_ONLY_TYPE_FOR_CPP_03(File)
[email protected]9ad009a2013-11-28 01:31:3158
[email protected]9ad009a2013-11-28 01:31:3159 public:
[email protected]f62ac7d2013-12-04 00:46:3260 // FLAG_(OPEN|CREATE).* are mutually exclusive. You should specify exactly one
61 // of the five (possibly combining with other flags) when opening or creating
62 // a file.
63 // FLAG_(WRITE|APPEND) are mutually exclusive. This is so that APPEND behavior
64 // will be consistent with O_APPEND on POSIX.
65 // FLAG_EXCLUSIVE_(READ|WRITE) only grant exclusive access to the file on
66 // creation on POSIX; for existing files, consider using Lock().
67 enum Flags {
68 FLAG_OPEN = 1 << 0, // Opens a file, only if it exists.
69 FLAG_CREATE = 1 << 1, // Creates a new file, only if it does not
70 // already exist.
71 FLAG_OPEN_ALWAYS = 1 << 2, // May create a new file.
72 FLAG_CREATE_ALWAYS = 1 << 3, // May overwrite an old file.
73 FLAG_OPEN_TRUNCATED = 1 << 4, // Opens a file and truncates it, only if it
74 // exists.
75 FLAG_READ = 1 << 5,
76 FLAG_WRITE = 1 << 6,
77 FLAG_APPEND = 1 << 7,
78 FLAG_EXCLUSIVE_READ = 1 << 8, // EXCLUSIVE is opposite of Windows SHARE.
79 FLAG_EXCLUSIVE_WRITE = 1 << 9,
80 FLAG_ASYNC = 1 << 10,
81 FLAG_TEMPORARY = 1 << 11, // Used on Windows only.
82 FLAG_HIDDEN = 1 << 12, // Used on Windows only.
83 FLAG_DELETE_ON_CLOSE = 1 << 13,
84 FLAG_WRITE_ATTRIBUTES = 1 << 14, // Used on Windows only.
85 FLAG_SHARE_DELETE = 1 << 15, // Used on Windows only.
86 FLAG_TERMINAL_DEVICE = 1 << 16, // Serial port flags.
87 FLAG_BACKUP_SEMANTICS = 1 << 17, // Used on Windows only.
88 FLAG_EXECUTE = 1 << 18, // Used on Windows only.
fdoray2c32fab2015-10-30 18:44:3989 FLAG_SEQUENTIAL_SCAN = 1 << 19, // Used on Windows only.
[email protected]f62ac7d2013-12-04 00:46:3290 };
[email protected]9ad009a2013-11-28 01:31:3191
[email protected]f62ac7d2013-12-04 00:46:3292 // This enum has been recorded in multiple histograms. If the order of the
93 // fields needs to change, please ensure that those histograms are obsolete or
94 // have been moved to a different enum.
95 //
96 // FILE_ERROR_ACCESS_DENIED is returned when a call fails because of a
97 // filesystem restriction. FILE_ERROR_SECURITY is returned when a browser
98 // policy doesn't allow the operation to be executed.
99 enum Error {
100 FILE_OK = 0,
101 FILE_ERROR_FAILED = -1,
102 FILE_ERROR_IN_USE = -2,
103 FILE_ERROR_EXISTS = -3,
104 FILE_ERROR_NOT_FOUND = -4,
105 FILE_ERROR_ACCESS_DENIED = -5,
106 FILE_ERROR_TOO_MANY_OPENED = -6,
107 FILE_ERROR_NO_MEMORY = -7,
108 FILE_ERROR_NO_SPACE = -8,
109 FILE_ERROR_NOT_A_DIRECTORY = -9,
110 FILE_ERROR_INVALID_OPERATION = -10,
111 FILE_ERROR_SECURITY = -11,
112 FILE_ERROR_ABORT = -12,
113 FILE_ERROR_NOT_A_FILE = -13,
114 FILE_ERROR_NOT_EMPTY = -14,
115 FILE_ERROR_INVALID_URL = -15,
116 FILE_ERROR_IO = -16,
117 // Put new entries here and increment FILE_ERROR_MAX.
118 FILE_ERROR_MAX = -17
119 };
120
121 // This explicit mapping matches both FILE_ on Windows and SEEK_ on Linux.
122 enum Whence {
123 FROM_BEGIN = 0,
124 FROM_CURRENT = 1,
125 FROM_END = 2
126 };
127
128 // Used to hold information about a given file.
129 // If you add more fields to this structure (platform-specific fields are OK),
tnagel718a46e2015-03-17 22:39:43130 // make sure to update all functions that use it in file_util_{win|posix}.cc,
131 // too, and the ParamTraits<base::File::Info> implementation in
132 // ipc/ipc_message_utils.cc.
[email protected]f62ac7d2013-12-04 00:46:32133 struct BASE_EXPORT Info {
134 Info();
135 ~Info();
[email protected]f745d722014-04-05 02:39:18136#if defined(OS_POSIX)
137 // Fills this struct with values from |stat_info|.
138 void FromStat(const stat_wrapper_t& stat_info);
139#endif
[email protected]f62ac7d2013-12-04 00:46:32140
141 // The size of the file in bytes. Undefined when is_directory is true.
avi543540e2015-12-24 05:15:32142 int64_t size;
[email protected]f62ac7d2013-12-04 00:46:32143
144 // True if the file corresponds to a directory.
145 bool is_directory;
146
tnagel718a46e2015-03-17 22:39:43147 // True if the file corresponds to a symbolic link. For Windows currently
148 // not supported and thus always false.
[email protected]f62ac7d2013-12-04 00:46:32149 bool is_symbolic_link;
150
151 // The last modified time of a file.
dbeam38d002a22015-04-23 21:42:34152 Time last_modified;
[email protected]f62ac7d2013-12-04 00:46:32153
154 // The last accessed time of a file.
dbeam38d002a22015-04-23 21:42:34155 Time last_accessed;
[email protected]f62ac7d2013-12-04 00:46:32156
157 // The creation time of a file.
dbeam38d002a22015-04-23 21:42:34158 Time creation_time;
[email protected]f62ac7d2013-12-04 00:46:32159 };
160
161 File();
162
163 // Creates or opens the given file. This will fail with 'access denied' if the
dbeam492dc31b2015-05-11 07:53:47164 // |path| contains path traversal ('..') components.
avi543540e2015-12-24 05:15:32165 File(const FilePath& path, uint32_t flags);
[email protected]f62ac7d2013-12-04 00:46:32166
167 // Takes ownership of |platform_file|.
168 explicit File(PlatformFile platform_file);
169
[email protected]f4bc9f12014-03-26 09:59:31170 // Creates an object with a specific error_details code.
171 explicit File(Error error_details);
172
dchenge1b0277c2015-12-01 12:09:52173 File(File&& other);
[email protected]f62ac7d2013-12-04 00:46:32174
175 ~File();
176
reillygaa435e72015-06-16 00:48:48177 // Takes ownership of |platform_file|.
178 static File CreateForAsyncHandle(PlatformFile platform_file);
179
dchenge1b0277c2015-12-01 12:09:52180 File& operator=(File&& other);
[email protected]f62ac7d2013-12-04 00:46:32181
[email protected]58ba3ea2014-01-03 22:14:15182 // Creates or opens the given file.
avi543540e2015-12-24 05:15:32183 void Initialize(const FilePath& path, uint32_t flags);
[email protected]58ba3ea2014-01-03 22:14:15184
lukasza7b718e82015-10-21 21:27:13185 // Returns |true| if the handle / fd wrapped by this object is valid. This
186 // method doesn't interact with the file system (and is safe to be called from
187 // ThreadRestrictions::SetIOAllowed(false) threads).
[email protected]f62ac7d2013-12-04 00:46:32188 bool IsValid() const;
189
190 // Returns true if a new file was created (or an old one truncated to zero
191 // length to simulate a new file, which can happen with
192 // FLAG_CREATE_ALWAYS), and false otherwise.
193 bool created() const { return created_; }
194
[email protected]48abb282014-02-21 17:25:53195 // Returns the OS result of opening this file. Note that the way to verify
196 // the success of the operation is to use IsValid(), not this method:
dbeam492dc31b2015-05-11 07:53:47197 // File file(path, flags);
[email protected]48abb282014-02-21 17:25:53198 // if (!file.IsValid())
199 // return;
[email protected]ee8808c2014-01-08 22:30:21200 Error error_details() const { return error_details_; }
[email protected]f62ac7d2013-12-04 00:46:32201
[email protected]49ec0312014-03-18 02:39:03202 PlatformFile GetPlatformFile() const;
[email protected]f62ac7d2013-12-04 00:46:32203 PlatformFile TakePlatformFile();
204
205 // Destroying this object closes the file automatically.
206 void Close();
207
208 // Changes current position in the file to an |offset| relative to an origin
209 // defined by |whence|. Returns the resultant current position in the file
210 // (relative to the start) or -1 in case of error.
avi543540e2015-12-24 05:15:32211 int64_t Seek(Whence whence, int64_t offset);
[email protected]f62ac7d2013-12-04 00:46:32212
213 // Reads the given number of bytes (or until EOF is reached) starting with the
214 // given offset. Returns the number of bytes read, or -1 on error. Note that
215 // this function makes a best effort to read all data on all platforms, so it
216 // is not intended for stream oriented files but instead for cases when the
217 // normal expectation is that actually |size| bytes are read unless there is
218 // an error.
avi543540e2015-12-24 05:15:32219 int Read(int64_t offset, char* data, int size);
[email protected]f62ac7d2013-12-04 00:46:32220
221 // Same as above but without seek.
222 int ReadAtCurrentPos(char* data, int size);
223
224 // Reads the given number of bytes (or until EOF is reached) starting with the
225 // given offset, but does not make any effort to read all data on all
226 // platforms. Returns the number of bytes read, or -1 on error.
avi543540e2015-12-24 05:15:32227 int ReadNoBestEffort(int64_t offset, char* data, int size);
[email protected]f62ac7d2013-12-04 00:46:32228
229 // Same as above but without seek.
230 int ReadAtCurrentPosNoBestEffort(char* data, int size);
231
232 // Writes the given buffer into the file at the given offset, overwritting any
233 // data that was previously there. Returns the number of bytes written, or -1
234 // on error. Note that this function makes a best effort to write all data on
235 // all platforms.
236 // Ignores the offset and writes to the end of the file if the file was opened
237 // with FLAG_APPEND.
avi543540e2015-12-24 05:15:32238 int Write(int64_t offset, const char* data, int size);
[email protected]f62ac7d2013-12-04 00:46:32239
240 // Save as above but without seek.
241 int WriteAtCurrentPos(const char* data, int size);
242
243 // Save as above but does not make any effort to write all data on all
244 // platforms. Returns the number of bytes written, or -1 on error.
245 int WriteAtCurrentPosNoBestEffort(const char* data, int size);
246
[email protected]58ba3ea2014-01-03 22:14:15247 // Returns the current size of this file, or a negative number on failure.
avi543540e2015-12-24 05:15:32248 int64_t GetLength();
[email protected]58ba3ea2014-01-03 22:14:15249
[email protected]f62ac7d2013-12-04 00:46:32250 // Truncates the file to the given length. If |length| is greater than the
251 // current size of the file, the file is extended with zeros. If the file
252 // doesn't exist, |false| is returned.
avi543540e2015-12-24 05:15:32253 bool SetLength(int64_t length);
[email protected]f62ac7d2013-12-04 00:46:32254
tnagel0e460192014-10-20 09:37:00255 // Instructs the filesystem to flush the file to disk. (POSIX: fsync, Windows:
256 // FlushFileBuffers).
[email protected]f62ac7d2013-12-04 00:46:32257 bool Flush();
258
259 // Updates the file times.
260 bool SetTimes(Time last_access_time, Time last_modified_time);
261
262 // Returns some basic information for the given file.
263 bool GetInfo(Info* info);
264
265 // Attempts to take an exclusive write lock on the file. Returns immediately
266 // (i.e. does not wait for another process to unlock the file). If the lock
267 // was obtained, the result will be FILE_OK. A lock only guarantees
268 // that other processes may not also take a lock on the same file with the
269 // same API - it may still be opened, renamed, unlinked, etc.
270 //
271 // Common semantics:
272 // * Locks are held by processes, but not inherited by child processes.
273 // * Locks are released by the OS on file close or process termination.
274 // * Locks are reliable only on local filesystems.
275 // * Duplicated file handles may also write to locked files.
276 // Windows-specific semantics:
277 // * Locks are mandatory for read/write APIs, advisory for mapping APIs.
278 // * Within a process, locking the same file (by the same or new handle)
279 // will fail.
280 // POSIX-specific semantics:
281 // * Locks are advisory only.
282 // * Within a process, locking the same file (by the same or new handle)
283 // will succeed.
284 // * Closing any descriptor on a given file releases the lock.
285 Error Lock();
286
287 // Unlock a file previously locked.
288 Error Unlock();
289
grtbad56032015-03-19 17:54:40290 // Returns a new object referencing this file for use within the current
291 // process. Handling of FLAG_DELETE_ON_CLOSE varies by OS. On POSIX, the File
292 // object that was created or initialized with this flag will have unlinked
293 // the underlying file when it was created or opened. On Windows, the
294 // underlying file is deleted when the last handle to it is closed.
295 File Duplicate();
296
[email protected]a08305912014-03-21 00:41:15297 bool async() const { return async_; }
298
[email protected]f62ac7d2013-12-04 00:46:32299#if defined(OS_WIN)
300 static Error OSErrorToFileError(DWORD last_error);
301#elif defined(OS_POSIX)
302 static Error OSErrorToFileError(int saved_errno);
303#endif
[email protected]9ad009a2013-11-28 01:31:31304
[email protected]b73427e2014-05-30 10:07:30305 // Converts an error value to a human-readable form. Used for logging.
306 static std::string ErrorToString(Error error);
307
[email protected]9ad009a2013-11-28 01:31:31308 private:
dbeam492dc31b2015-05-11 07:53:47309 friend class FileTracing::ScopedTrace;
310
dbeamfd5b1082015-07-02 03:33:08311 // Creates or opens the given file. Only called if |path| has no
dbeam492dc31b2015-05-11 07:53:47312 // traversal ('..') components.
avi543540e2015-12-24 05:15:32313 void DoInitialize(const FilePath& path, uint32_t flags);
dbeam492cd472015-04-24 01:27:53314
tnagel0ac31482015-04-03 10:11:46315 // TODO(tnagel): Reintegrate into Flush() once histogram isn't needed anymore,
316 // cf. issue 473337.
317 bool DoFlush();
318
[email protected]f62ac7d2013-12-04 00:46:32319 void SetPlatformFile(PlatformFile file);
320
321#if defined(OS_WIN)
322 win::ScopedHandle file_;
323#elif defined(OS_POSIX)
gavinpac9c196f2015-09-28 22:58:12324 ScopedFD file_;
[email protected]f62ac7d2013-12-04 00:46:32325#endif
326
dbeamfd5b1082015-07-02 03:33:08327 // A path to use for tracing purposes. Set if file tracing is enabled during
328 // |Initialize()|.
329 FilePath tracing_path_;
dbeam492dc31b2015-05-11 07:53:47330
331 // Object tied to the lifetime of |this| that enables/disables tracing.
332 FileTracing::ScopedEnabler trace_enabler_;
333
[email protected]ee8808c2014-01-08 22:30:21334 Error error_details_;
[email protected]f62ac7d2013-12-04 00:46:32335 bool created_;
336 bool async_;
[email protected]9ad009a2013-11-28 01:31:31337};
338
339} // namespace base
340
[email protected]f62ac7d2013-12-04 00:46:32341#endif // BASE_FILES_FILE_H_
gavinpac9c196f2015-09-28 22:58:12342