blob: ca99b131d78f650cc5d8a47aff2238ce23317cfa [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"
Brett Wilsonc7d73a992017-07-14 01:56:1315#include "base/files/platform_file.h"
[email protected]49ec0312014-03-18 02:39:0316#include "base/files/scoped_file.h"
dcheng1a2fd6cd2016-06-07 21:39:1217#include "base/macros.h"
[email protected]9ad009a2013-11-28 01:31:3118#include "base/time/time.h"
avi543540e2015-12-24 05:15:3219#include "build/build_config.h"
[email protected]9ad009a2013-11-28 01:31:3120
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3921#if defined(OS_POSIX) || defined(OS_FUCHSIA)
avi543540e2015-12-24 05:15:3222#include <sys/stat.h>
23#endif
24
[email protected]9ad009a2013-11-28 01:31:3125namespace base {
26
bsheedy2a59f252018-01-03 21:30:0527#if defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL) || \
28 defined(OS_ANDROID) && __ANDROID_API__ < 21
[email protected]f745d722014-04-05 02:39:1829typedef struct stat stat_wrapper_t;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3930#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]f745d722014-04-05 02:39:1831typedef struct stat64 stat_wrapper_t;
32#endif
[email protected]f62ac7d2013-12-04 00:46:3233
34// Thin wrapper around an OS-level file.
35// Note that this class does not provide any support for asynchronous IO, other
36// than the ability to create asynchronous handles on Windows.
[email protected]9ad009a2013-11-28 01:31:3137//
[email protected]f62ac7d2013-12-04 00:46:3238// Note about const: this class does not attempt to determine if the underlying
39// file system object is affected by a particular method in order to consider
40// that method const or not. Only methods that deal with member variables in an
41// obvious non-modifying way are marked as const. Any method that forward calls
42// to the OS is not considered const, even if there is no apparent change to
43// member variables.
44class BASE_EXPORT File {
[email protected]9ad009a2013-11-28 01:31:3145 public:
[email protected]f62ac7d2013-12-04 00:46:3246 // FLAG_(OPEN|CREATE).* are mutually exclusive. You should specify exactly one
47 // of the five (possibly combining with other flags) when opening or creating
48 // a file.
49 // FLAG_(WRITE|APPEND) are mutually exclusive. This is so that APPEND behavior
50 // will be consistent with O_APPEND on POSIX.
51 // FLAG_EXCLUSIVE_(READ|WRITE) only grant exclusive access to the file on
52 // creation on POSIX; for existing files, consider using Lock().
53 enum Flags {
grt37dd9232017-01-13 21:52:4554 FLAG_OPEN = 1 << 0, // Opens a file, only if it exists.
55 FLAG_CREATE = 1 << 1, // Creates a new file, only if it does not
56 // already exist.
57 FLAG_OPEN_ALWAYS = 1 << 2, // May create a new file.
58 FLAG_CREATE_ALWAYS = 1 << 3, // May overwrite an old file.
59 FLAG_OPEN_TRUNCATED = 1 << 4, // Opens a file and truncates it, only if it
60 // exists.
[email protected]f62ac7d2013-12-04 00:46:3261 FLAG_READ = 1 << 5,
62 FLAG_WRITE = 1 << 6,
63 FLAG_APPEND = 1 << 7,
grt37dd9232017-01-13 21:52:4564 FLAG_EXCLUSIVE_READ = 1 << 8, // EXCLUSIVE is opposite of Windows SHARE.
[email protected]f62ac7d2013-12-04 00:46:3265 FLAG_EXCLUSIVE_WRITE = 1 << 9,
66 FLAG_ASYNC = 1 << 10,
grt37dd9232017-01-13 21:52:4567 FLAG_TEMPORARY = 1 << 11, // Used on Windows only.
68 FLAG_HIDDEN = 1 << 12, // Used on Windows only.
[email protected]f62ac7d2013-12-04 00:46:3269 FLAG_DELETE_ON_CLOSE = 1 << 13,
grt37dd9232017-01-13 21:52:4570 FLAG_WRITE_ATTRIBUTES = 1 << 14, // Used on Windows only.
71 FLAG_SHARE_DELETE = 1 << 15, // Used on Windows only.
72 FLAG_TERMINAL_DEVICE = 1 << 16, // Serial port flags.
73 FLAG_BACKUP_SEMANTICS = 1 << 17, // Used on Windows only.
74 FLAG_EXECUTE = 1 << 18, // Used on Windows only.
75 FLAG_SEQUENTIAL_SCAN = 1 << 19, // Used on Windows only.
76 FLAG_CAN_DELETE_ON_CLOSE = 1 << 20, // Requests permission to delete a file
77 // via DeleteOnClose() (Windows only).
78 // See DeleteOnClose() for details.
[email protected]f62ac7d2013-12-04 00:46:3279 };
[email protected]9ad009a2013-11-28 01:31:3180
Jérôme Lebel46c04be2018-03-21 18:29:3981 // This enum has been recorded in multiple histograms using PlatformFileError
82 // enum. If the order of the fields needs to change, please ensure that those
83 // histograms are obsolete or have been moved to a different enum.
[email protected]f62ac7d2013-12-04 00:46:3284 //
85 // FILE_ERROR_ACCESS_DENIED is returned when a call fails because of a
86 // filesystem restriction. FILE_ERROR_SECURITY is returned when a browser
87 // policy doesn't allow the operation to be executed.
88 enum Error {
89 FILE_OK = 0,
90 FILE_ERROR_FAILED = -1,
91 FILE_ERROR_IN_USE = -2,
92 FILE_ERROR_EXISTS = -3,
93 FILE_ERROR_NOT_FOUND = -4,
94 FILE_ERROR_ACCESS_DENIED = -5,
95 FILE_ERROR_TOO_MANY_OPENED = -6,
96 FILE_ERROR_NO_MEMORY = -7,
97 FILE_ERROR_NO_SPACE = -8,
98 FILE_ERROR_NOT_A_DIRECTORY = -9,
99 FILE_ERROR_INVALID_OPERATION = -10,
100 FILE_ERROR_SECURITY = -11,
101 FILE_ERROR_ABORT = -12,
102 FILE_ERROR_NOT_A_FILE = -13,
103 FILE_ERROR_NOT_EMPTY = -14,
104 FILE_ERROR_INVALID_URL = -15,
105 FILE_ERROR_IO = -16,
106 // Put new entries here and increment FILE_ERROR_MAX.
107 FILE_ERROR_MAX = -17
108 };
109
110 // This explicit mapping matches both FILE_ on Windows and SEEK_ on Linux.
111 enum Whence {
112 FROM_BEGIN = 0,
113 FROM_CURRENT = 1,
114 FROM_END = 2
115 };
116
117 // Used to hold information about a given file.
118 // If you add more fields to this structure (platform-specific fields are OK),
tnagel718a46e2015-03-17 22:39:43119 // make sure to update all functions that use it in file_util_{win|posix}.cc,
120 // too, and the ParamTraits<base::File::Info> implementation in
121 // ipc/ipc_message_utils.cc.
[email protected]f62ac7d2013-12-04 00:46:32122 struct BASE_EXPORT Info {
123 Info();
124 ~Info();
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39125#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]f745d722014-04-05 02:39:18126 // Fills this struct with values from |stat_info|.
127 void FromStat(const stat_wrapper_t& stat_info);
128#endif
[email protected]f62ac7d2013-12-04 00:46:32129
130 // The size of the file in bytes. Undefined when is_directory is true.
avi543540e2015-12-24 05:15:32131 int64_t size;
[email protected]f62ac7d2013-12-04 00:46:32132
133 // True if the file corresponds to a directory.
134 bool is_directory;
135
tnagel718a46e2015-03-17 22:39:43136 // True if the file corresponds to a symbolic link. For Windows currently
137 // not supported and thus always false.
[email protected]f62ac7d2013-12-04 00:46:32138 bool is_symbolic_link;
139
140 // The last modified time of a file.
dbeam38d002a22015-04-23 21:42:34141 Time last_modified;
[email protected]f62ac7d2013-12-04 00:46:32142
143 // The last accessed time of a file.
dbeam38d002a22015-04-23 21:42:34144 Time last_accessed;
[email protected]f62ac7d2013-12-04 00:46:32145
146 // The creation time of a file.
dbeam38d002a22015-04-23 21:42:34147 Time creation_time;
[email protected]f62ac7d2013-12-04 00:46:32148 };
149
150 File();
151
152 // Creates or opens the given file. This will fail with 'access denied' if the
dbeam492dc31b2015-05-11 07:53:47153 // |path| contains path traversal ('..') components.
avi543540e2015-12-24 05:15:32154 File(const FilePath& path, uint32_t flags);
[email protected]f62ac7d2013-12-04 00:46:32155
Robbie McElrathd7980792018-06-20 00:24:46156 // Takes ownership of |platform_file| and sets async to false.
[email protected]f62ac7d2013-12-04 00:46:32157 explicit File(PlatformFile platform_file);
158
Robbie McElrathd7980792018-06-20 00:24:46159 // Takes ownership of |platform_file| and sets async to the given value.
160 // This constructor exists because on Windows you can't check if platform_file
161 // is async or not.
162 File(PlatformFile platform_file, bool async);
163
[email protected]f4bc9f12014-03-26 09:59:31164 // Creates an object with a specific error_details code.
165 explicit File(Error error_details);
166
dchenge1b0277c2015-12-01 12:09:52167 File(File&& other);
[email protected]f62ac7d2013-12-04 00:46:32168
169 ~File();
170
dchenge1b0277c2015-12-01 12:09:52171 File& operator=(File&& other);
[email protected]f62ac7d2013-12-04 00:46:32172
[email protected]58ba3ea2014-01-03 22:14:15173 // Creates or opens the given file.
avi543540e2015-12-24 05:15:32174 void Initialize(const FilePath& path, uint32_t flags);
[email protected]58ba3ea2014-01-03 22:14:15175
lukasza7b718e82015-10-21 21:27:13176 // Returns |true| if the handle / fd wrapped by this object is valid. This
177 // method doesn't interact with the file system (and is safe to be called from
178 // ThreadRestrictions::SetIOAllowed(false) threads).
[email protected]f62ac7d2013-12-04 00:46:32179 bool IsValid() const;
180
181 // Returns true if a new file was created (or an old one truncated to zero
182 // length to simulate a new file, which can happen with
183 // FLAG_CREATE_ALWAYS), and false otherwise.
184 bool created() const { return created_; }
185
[email protected]48abb282014-02-21 17:25:53186 // Returns the OS result of opening this file. Note that the way to verify
187 // the success of the operation is to use IsValid(), not this method:
dbeam492dc31b2015-05-11 07:53:47188 // File file(path, flags);
[email protected]48abb282014-02-21 17:25:53189 // if (!file.IsValid())
190 // return;
[email protected]ee8808c2014-01-08 22:30:21191 Error error_details() const { return error_details_; }
[email protected]f62ac7d2013-12-04 00:46:32192
[email protected]49ec0312014-03-18 02:39:03193 PlatformFile GetPlatformFile() const;
[email protected]f62ac7d2013-12-04 00:46:32194 PlatformFile TakePlatformFile();
195
196 // Destroying this object closes the file automatically.
197 void Close();
198
199 // Changes current position in the file to an |offset| relative to an origin
200 // defined by |whence|. Returns the resultant current position in the file
201 // (relative to the start) or -1 in case of error.
avi543540e2015-12-24 05:15:32202 int64_t Seek(Whence whence, int64_t offset);
[email protected]f62ac7d2013-12-04 00:46:32203
204 // Reads the given number of bytes (or until EOF is reached) starting with the
205 // given offset. Returns the number of bytes read, or -1 on error. Note that
206 // this function makes a best effort to read all data on all platforms, so it
207 // is not intended for stream oriented files but instead for cases when the
208 // normal expectation is that actually |size| bytes are read unless there is
209 // an error.
avi543540e2015-12-24 05:15:32210 int Read(int64_t offset, char* data, int size);
[email protected]f62ac7d2013-12-04 00:46:32211
212 // Same as above but without seek.
213 int ReadAtCurrentPos(char* data, int size);
214
215 // Reads the given number of bytes (or until EOF is reached) starting with the
216 // given offset, but does not make any effort to read all data on all
217 // platforms. Returns the number of bytes read, or -1 on error.
avi543540e2015-12-24 05:15:32218 int ReadNoBestEffort(int64_t offset, char* data, int size);
[email protected]f62ac7d2013-12-04 00:46:32219
220 // Same as above but without seek.
221 int ReadAtCurrentPosNoBestEffort(char* data, int size);
222
223 // Writes the given buffer into the file at the given offset, overwritting any
224 // data that was previously there. Returns the number of bytes written, or -1
225 // on error. Note that this function makes a best effort to write all data on
Sergey Ulanov3c6541d2017-08-31 23:59:52226 // all platforms. |data| can be nullptr when |size| is 0.
[email protected]f62ac7d2013-12-04 00:46:32227 // Ignores the offset and writes to the end of the file if the file was opened
228 // with FLAG_APPEND.
avi543540e2015-12-24 05:15:32229 int Write(int64_t offset, const char* data, int size);
[email protected]f62ac7d2013-12-04 00:46:32230
231 // Save as above but without seek.
232 int WriteAtCurrentPos(const char* data, int size);
233
234 // Save as above but does not make any effort to write all data on all
235 // platforms. Returns the number of bytes written, or -1 on error.
236 int WriteAtCurrentPosNoBestEffort(const char* data, int size);
237
[email protected]58ba3ea2014-01-03 22:14:15238 // Returns the current size of this file, or a negative number on failure.
avi543540e2015-12-24 05:15:32239 int64_t GetLength();
[email protected]58ba3ea2014-01-03 22:14:15240
[email protected]f62ac7d2013-12-04 00:46:32241 // Truncates the file to the given length. If |length| is greater than the
242 // current size of the file, the file is extended with zeros. If the file
243 // doesn't exist, |false| is returned.
avi543540e2015-12-24 05:15:32244 bool SetLength(int64_t length);
[email protected]f62ac7d2013-12-04 00:46:32245
tnagel0e460192014-10-20 09:37:00246 // Instructs the filesystem to flush the file to disk. (POSIX: fsync, Windows:
247 // FlushFileBuffers).
tnagel301e81e2016-07-22 23:55:18248 // Calling Flush() does not guarantee file integrity and thus is not a valid
249 // substitute for file integrity checks and recovery codepaths for malformed
250 // files. It can also be *really* slow, so avoid blocking on Flush(),
251 // especially please don't block shutdown on Flush().
252 // Latency percentiles of Flush() across all platforms as of July 2016:
253 // 50 % > 5 ms
254 // 10 % > 58 ms
255 // 1 % > 357 ms
256 // 0.1 % > 1.8 seconds
257 // 0.01 % > 7.6 seconds
[email protected]f62ac7d2013-12-04 00:46:32258 bool Flush();
259
260 // Updates the file times.
261 bool SetTimes(Time last_access_time, Time last_modified_time);
262
263 // Returns some basic information for the given file.
264 bool GetInfo(Info* info);
265
Kevin Marshall2804dbe22017-07-14 02:58:07266#if !defined(OS_FUCHSIA) // Fuchsia's POSIX API does not support file locking.
267
[email protected]f62ac7d2013-12-04 00:46:32268 // Attempts to take an exclusive write lock on the file. Returns immediately
269 // (i.e. does not wait for another process to unlock the file). If the lock
270 // was obtained, the result will be FILE_OK. A lock only guarantees
271 // that other processes may not also take a lock on the same file with the
272 // same API - it may still be opened, renamed, unlinked, etc.
273 //
274 // Common semantics:
275 // * Locks are held by processes, but not inherited by child processes.
276 // * Locks are released by the OS on file close or process termination.
277 // * Locks are reliable only on local filesystems.
278 // * Duplicated file handles may also write to locked files.
279 // Windows-specific semantics:
280 // * Locks are mandatory for read/write APIs, advisory for mapping APIs.
281 // * Within a process, locking the same file (by the same or new handle)
282 // will fail.
283 // POSIX-specific semantics:
284 // * Locks are advisory only.
285 // * Within a process, locking the same file (by the same or new handle)
286 // will succeed.
287 // * Closing any descriptor on a given file releases the lock.
288 Error Lock();
289
290 // Unlock a file previously locked.
291 Error Unlock();
292
Kevin Marshall2804dbe22017-07-14 02:58:07293#endif // !defined(OS_FUCHSIA)
294
grtbad56032015-03-19 17:54:40295 // Returns a new object referencing this file for use within the current
296 // process. Handling of FLAG_DELETE_ON_CLOSE varies by OS. On POSIX, the File
297 // object that was created or initialized with this flag will have unlinked
298 // the underlying file when it was created or opened. On Windows, the
299 // underlying file is deleted when the last handle to it is closed.
kulshin00e2bd62016-07-20 20:57:35300 File Duplicate() const;
grtbad56032015-03-19 17:54:40301
[email protected]a08305912014-03-21 00:41:15302 bool async() const { return async_; }
303
[email protected]f62ac7d2013-12-04 00:46:32304#if defined(OS_WIN)
grt37dd9232017-01-13 21:52:45305 // Sets or clears the DeleteFile disposition on the handle. Returns true if
306 // the disposition was set or cleared, as indicated by |delete_on_close|.
307 //
308 // Microsoft Windows deletes a file only when the last handle to the
309 // underlying kernel object is closed when the DeleteFile disposition has been
310 // set by any handle holder. This disposition is be set by:
311 // - Calling the Win32 DeleteFile function with the path to a file.
312 // - Opening/creating a file with FLAG_DELETE_ON_CLOSE.
313 // - Opening/creating a file with FLAG_CAN_DELETE_ON_CLOSE and subsequently
314 // calling DeleteOnClose(true).
315 //
316 // In all cases, all pre-existing handles to the file must have been opened
317 // with FLAG_SHARE_DELETE.
318 //
319 // So:
320 // - Use FLAG_SHARE_DELETE when creating/opening a file to allow another
321 // entity on the system to cause it to be deleted when it is closed. (Note:
322 // another entity can delete the file the moment after it is closed, so not
323 // using this permission doesn't provide any protections.)
324 // - Use FLAG_DELETE_ON_CLOSE for any file that is to be deleted after use.
325 // The OS will ensure it is deleted even in the face of process termination.
326 // - Use FLAG_CAN_DELETE_ON_CLOSE in conjunction with DeleteOnClose() to alter
327 // the DeleteFile disposition on an open handle. This fine-grained control
328 // allows for marking a file for deletion during processing so that it is
329 // deleted in the event of untimely process termination, and then clearing
330 // this state once the file is suitable for persistence.
331 bool DeleteOnClose(bool delete_on_close);
332#endif
333
334#if defined(OS_WIN)
[email protected]f62ac7d2013-12-04 00:46:32335 static Error OSErrorToFileError(DWORD last_error);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39336#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]f62ac7d2013-12-04 00:46:32337 static Error OSErrorToFileError(int saved_errno);
338#endif
[email protected]9ad009a2013-11-28 01:31:31339
Chris Mumford5ba7cac12017-12-04 21:23:00340 // Gets the last global error (errno or GetLastError()) and converts it to the
341 // closest base::File::Error equivalent via OSErrorToFileError(). The returned
342 // value is only trustworthy immediately after another base::File method
343 // fails. base::File never resets the global error to zero.
344 static Error GetLastFileError();
345
[email protected]b73427e2014-05-30 10:07:30346 // Converts an error value to a human-readable form. Used for logging.
347 static std::string ErrorToString(Error error);
348
[email protected]9ad009a2013-11-28 01:31:31349 private:
dbeam492dc31b2015-05-11 07:53:47350 friend class FileTracing::ScopedTrace;
351
dbeamfd5b1082015-07-02 03:33:08352 // Creates or opens the given file. Only called if |path| has no
dbeam492dc31b2015-05-11 07:53:47353 // traversal ('..') components.
avi543540e2015-12-24 05:15:32354 void DoInitialize(const FilePath& path, uint32_t flags);
dbeam492cd472015-04-24 01:27:53355
[email protected]f62ac7d2013-12-04 00:46:32356 void SetPlatformFile(PlatformFile file);
357
Brett Wilsonc7d73a992017-07-14 01:56:13358 ScopedPlatformFile file_;
[email protected]f62ac7d2013-12-04 00:46:32359
dbeamfd5b1082015-07-02 03:33:08360 // A path to use for tracing purposes. Set if file tracing is enabled during
361 // |Initialize()|.
362 FilePath tracing_path_;
dbeam492dc31b2015-05-11 07:53:47363
364 // Object tied to the lifetime of |this| that enables/disables tracing.
365 FileTracing::ScopedEnabler trace_enabler_;
366
[email protected]ee8808c2014-01-08 22:30:21367 Error error_details_;
[email protected]f62ac7d2013-12-04 00:46:32368 bool created_;
369 bool async_;
dcheng1a2fd6cd2016-06-07 21:39:12370
371 DISALLOW_COPY_AND_ASSIGN(File);
[email protected]9ad009a2013-11-28 01:31:31372};
373
374} // namespace base
375
[email protected]f62ac7d2013-12-04 00:46:32376#endif // BASE_FILES_FILE_H_
gavinpac9c196f2015-09-28 22:58:12377