• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4 
5 #ifndef BASE_FILES_FILE_H_
6 #define BASE_FILES_FILE_H_
7 
8 #include <stdint.h>
9 
10 #include <string>
11 
12 #include "base/files/file_path.h"
13 #include "base/files/platform_file.h"
14 #include "base/files/scoped_file.h"
15 #include "base/macros.h"
16 #include "util/build_config.h"
17 #include "util/ticks.h"
18 
19 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
20 #include <sys/stat.h>
21 #endif
22 
23 namespace base {
24 
25 #if defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL) || \
26     defined(OS_HAIKU) || defined(OS_ANDROID) && __ANDROID_API__ < 21
27 typedef struct stat stat_wrapper_t;
28 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
29 typedef struct stat64 stat_wrapper_t;
30 #endif
31 
32 // Thin wrapper around an OS-level file.
33 // Note that this class does not provide any support for asynchronous IO.
34 //
35 // Note about const: this class does not attempt to determine if the underlying
36 // file system object is affected by a particular method in order to consider
37 // that method const or not. Only methods that deal with member variables in an
38 // obvious non-modifying way are marked as const. Any method that forward calls
39 // to the OS is not considered const, even if there is no apparent change to
40 // member variables.
41 class File {
42  public:
43   // FLAG_(OPEN|CREATE).* are mutually exclusive. You should specify exactly one
44   // of the five (possibly combining with other flags) when opening or creating
45   // a file.
46   enum Flags {
47     FLAG_OPEN = 1 << 0,            // Opens a file, only if it exists.
48     FLAG_CREATE_ALWAYS = 1 << 3,   // May overwrite an old file.
49     FLAG_READ = 1 << 4,
50     FLAG_WRITE = 1 << 5,
51   };
52 
53   // This enum has been recorded in multiple histograms using PlatformFileError
54   // enum. If the order of the fields needs to change, please ensure that those
55   // histograms are obsolete or have been moved to a different enum.
56   //
57   // FILE_ERROR_ACCESS_DENIED is returned when a call fails because of a
58   // filesystem restriction. FILE_ERROR_SECURITY is returned when a browser
59   // policy doesn't allow the operation to be executed.
60   enum Error {
61     FILE_OK = 0,
62     FILE_ERROR_FAILED = -1,
63     FILE_ERROR_IN_USE = -2,
64     FILE_ERROR_EXISTS = -3,
65     FILE_ERROR_NOT_FOUND = -4,
66     FILE_ERROR_ACCESS_DENIED = -5,
67     FILE_ERROR_TOO_MANY_OPENED = -6,
68     FILE_ERROR_NO_MEMORY = -7,
69     FILE_ERROR_NO_SPACE = -8,
70     FILE_ERROR_NOT_A_DIRECTORY = -9,
71     FILE_ERROR_INVALID_OPERATION = -10,
72     FILE_ERROR_SECURITY = -11,
73     FILE_ERROR_ABORT = -12,
74     FILE_ERROR_NOT_A_FILE = -13,
75     FILE_ERROR_NOT_EMPTY = -14,
76     FILE_ERROR_INVALID_URL = -15,
77     FILE_ERROR_IO = -16,
78     // Put new entries here and increment FILE_ERROR_MAX.
79     FILE_ERROR_MAX = -17
80   };
81 
82   // This explicit mapping matches both FILE_ on Windows and SEEK_ on Linux.
83   enum Whence { FROM_BEGIN = 0, FROM_CURRENT = 1, FROM_END = 2 };
84 
85   // Used to hold information about a given file.
86   // If you add more fields to this structure (platform-specific fields are OK),
87   // make sure to update all functions that use it in file_util_{win|posix}.cc,
88   // too, and the ParamTraits<base::File::Info> implementation in
89   // ipc/ipc_message_utils.cc.
90   struct Info {
91     Info();
92     ~Info();
93 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
94     // Fills this struct with values from |stat_info|.
95     void FromStat(const stat_wrapper_t& stat_info);
96 #endif
97 
98     // The size of the file in bytes.  Undefined when is_directory is true.
99     int64_t size;
100 
101     // True if the file corresponds to a directory.
102     bool is_directory;
103 
104     // True if the file corresponds to a symbolic link.  For Windows currently
105     // not supported and thus always false.
106     bool is_symbolic_link;
107 
108     // The last modified time of a file.
109     Ticks last_modified;
110 
111     // The last accessed time of a file.
112     Ticks last_accessed;
113 
114     // The creation time of a file.
115     Ticks creation_time;
116   };
117 
118   File();
119 
120   // Creates or opens the given file. This will fail with 'access denied' if the
121   // |path| contains path traversal ('..') components.
122   File(const FilePath& path, uint32_t flags);
123 
124   // Takes ownership of |platform_file|.
125   explicit File(PlatformFile platform_file);
126 
127   // Creates an object with a specific error_details code.
128   explicit File(Error error_details);
129 
130   File(File&& other);
131 
132   ~File();
133 
134   File& operator=(File&& other);
135 
136   // Creates or opens the given file.
137   void Initialize(const FilePath& path, uint32_t flags);
138 
139   // Returns |true| if the handle / fd wrapped by this object is valid.  This
140   // method doesn't interact with the file system (and is safe to be called from
141   // ThreadRestrictions::SetIOAllowed(false) threads).
142   bool IsValid() const;
143 
144   // Returns true if a new file was created (or an old one truncated to zero
145   // length to simulate a new file, which can happen with
146   // FLAG_CREATE_ALWAYS), and false otherwise.
created()147   bool created() const { return created_; }
148 
149   // Returns the OS result of opening this file. Note that the way to verify
150   // the success of the operation is to use IsValid(), not this method:
151   //   File file(path, flags);
152   //   if (!file.IsValid())
153   //     return;
error_details()154   Error error_details() const { return error_details_; }
155 
156   PlatformFile GetPlatformFile() const;
157   PlatformFile TakePlatformFile();
158 
159   // Destroying this object closes the file automatically.
160   void Close();
161 
162   // Changes current position in the file to an |offset| relative to an origin
163   // defined by |whence|. Returns the resultant current position in the file
164   // (relative to the start) or -1 in case of error.
165   int64_t Seek(Whence whence, int64_t offset);
166 
167   // Reads the given number of bytes (or until EOF is reached) starting with the
168   // given offset. Returns the number of bytes read, or -1 on error. Note that
169   // this function makes a best effort to read all data on all platforms, so it
170   // is not intended for stream oriented files but instead for cases when the
171   // normal expectation is that actually |size| bytes are read unless there is
172   // an error.
173   int Read(int64_t offset, char* data, int size);
174 
175   // Same as above but without seek.
176   int ReadAtCurrentPos(char* data, int size);
177 
178   // Reads the given number of bytes (or until EOF is reached) starting with the
179   // given offset, but does not make any effort to read all data on all
180   // platforms. Returns the number of bytes read, or -1 on error.
181   int ReadNoBestEffort(int64_t offset, char* data, int size);
182 
183   // Same as above but without seek.
184   int ReadAtCurrentPosNoBestEffort(char* data, int size);
185 
186   // Writes the given buffer into the file at the given offset, overwritting any
187   // data that was previously there. Returns the number of bytes written, or -1
188   // on error. Note that this function makes a best effort to write all data on
189   // all platforms. |data| can be nullptr when |size| is 0.
190   int Write(int64_t offset, const char* data, int size);
191 
192   // Save as above but without seek.
193   int WriteAtCurrentPos(const char* data, int size);
194 
195   // Save as above but does not make any effort to write all data on all
196   // platforms. Returns the number of bytes written, or -1 on error.
197   int WriteAtCurrentPosNoBestEffort(const char* data, int size);
198 
199   // Returns the current size of this file, or a negative number on failure.
200   int64_t GetLength();
201 
202   // Truncates the file to the given length. If |length| is greater than the
203   // current size of the file, the file is extended with zeros. If the file
204   // doesn't exist, |false| is returned.
205   bool SetLength(int64_t length);
206 
207   // Instructs the filesystem to flush the file to disk. (POSIX: fsync, Windows:
208   // FlushFileBuffers).
209   // Calling Flush() does not guarantee file integrity and thus is not a valid
210   // substitute for file integrity checks and recovery codepaths for malformed
211   // files. It can also be *really* slow, so avoid blocking on Flush(),
212   // especially please don't block shutdown on Flush().
213   // Latency percentiles of Flush() across all platforms as of July 2016:
214   // 50 %     > 5 ms
215   // 10 %     > 58 ms
216   //  1 %     > 357 ms
217   //  0.1 %   > 1.8 seconds
218   //  0.01 %  > 7.6 seconds
219   bool Flush();
220 
221   // Returns some basic information for the given file.
222   bool GetInfo(Info* info);
223 
224 #if !defined(OS_FUCHSIA)  // Fuchsia's POSIX API does not support file locking.
225 
226   // Attempts to take an exclusive write lock on the file. Returns immediately
227   // (i.e. does not wait for another process to unlock the file). If the lock
228   // was obtained, the result will be FILE_OK. A lock only guarantees
229   // that other processes may not also take a lock on the same file with the
230   // same API - it may still be opened, renamed, unlinked, etc.
231   //
232   // Common semantics:
233   //  * Locks are held by processes, but not inherited by child processes.
234   //  * Locks are released by the OS on file close or process termination.
235   //  * Locks are reliable only on local filesystems.
236   //  * Duplicated file handles may also write to locked files.
237   // Windows-specific semantics:
238   //  * Locks are mandatory for read/write APIs, advisory for mapping APIs.
239   //  * Within a process, locking the same file (by the same or new handle)
240   //    will fail.
241   // POSIX-specific semantics:
242   //  * Locks are advisory only.
243   //  * Within a process, locking the same file (by the same or new handle)
244   //    will succeed.
245   //  * Closing any descriptor on a given file releases the lock.
246   Error Lock();
247 
248   // Unlock a file previously locked.
249   Error Unlock();
250 
251 #endif  // !defined(OS_FUCHSIA)
252 
253   // Returns a new object referencing this file for use within the current
254   // process.
255   File Duplicate() const;
256 
257 #if defined(OS_WIN)
258   static Error OSErrorToFileError(DWORD last_error);
259 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
260   static Error OSErrorToFileError(int saved_errno);
261 #endif
262 
263   // Gets the last global error (errno or GetLastError()) and converts it to the
264   // closest base::File::Error equivalent via OSErrorToFileError(). The returned
265   // value is only trustworthy immediately after another base::File method
266   // fails. base::File never resets the global error to zero.
267   static Error GetLastFileError();
268 
269   // Converts an error value to a human-readable form. Used for logging.
270   static std::string ErrorToString(Error error);
271 
272  private:
273   // Creates or opens the given file. Only called if |path| has no
274   // traversal ('..') components.
275   void DoInitialize(const FilePath& path, uint32_t flags);
276 
277   void SetPlatformFile(PlatformFile file);
278 
279   ScopedPlatformFile file_;
280 
281   Error error_details_;
282   bool created_;
283 
284   DISALLOW_COPY_AND_ASSIGN(File);
285 };
286 
287 }  // namespace base
288 
289 #endif  // BASE_FILES_FILE_H_
290