• 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 "util/build_config.h"
16 #include "util/ticks.h"
17 
18 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
19 #include <sys/stat.h>
20 #endif
21 
22 namespace base {
23 
24 #if defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL) || \
25     defined(OS_HAIKU) || defined(OS_MSYS) || defined(OS_ZOS) ||  \
26     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 = 0;
100 
101     // True if the file corresponds to a directory.
102     bool is_directory = false;
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 = false;
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 the OS result of opening this file. Note that the way to verify
145   // the success of the operation is to use IsValid(), not this method:
146   //   File file(path, flags);
147   //   if (!file.IsValid())
148   //     return;
error_details()149   Error error_details() const { return error_details_; }
150 
151   PlatformFile GetPlatformFile() const;
152   PlatformFile TakePlatformFile();
153 
154   // Destroying this object closes the file automatically.
155   void Close();
156 
157   // Changes current position in the file to an |offset| relative to an origin
158   // defined by |whence|. Returns the resultant current position in the file
159   // (relative to the start) or -1 in case of error.
160   int64_t Seek(Whence whence, int64_t offset);
161 
162   // Reads the given number of bytes (or until EOF is reached) starting with the
163   // given offset. Returns the number of bytes read, or -1 on error. Note that
164   // this function makes a best effort to read all data on all platforms, so it
165   // is not intended for stream oriented files but instead for cases when the
166   // normal expectation is that actually |size| bytes are read unless there is
167   // an error.
168   int Read(int64_t offset, char* data, int size);
169 
170   // Same as above but without seek.
171   int ReadAtCurrentPos(char* data, int size);
172 
173   // Reads the given number of bytes (or until EOF is reached) starting with the
174   // given offset, but does not make any effort to read all data on all
175   // platforms. Returns the number of bytes read, or -1 on error.
176   int ReadNoBestEffort(int64_t offset, char* data, int size);
177 
178   // Same as above but without seek.
179   int ReadAtCurrentPosNoBestEffort(char* data, int size);
180 
181   // Writes the given buffer into the file at the given offset, overwriting any
182   // data that was previously there. Returns the number of bytes written, or -1
183   // on error. Note that this function makes a best effort to write all data on
184   // all platforms. |data| can be nullptr when |size| is 0.
185   int Write(int64_t offset, const char* data, int size);
186 
187   // Save as above but without seek.
188   int WriteAtCurrentPos(const char* data, int size);
189 
190   // Save as above but does not make any effort to write all data on all
191   // platforms. Returns the number of bytes written, or -1 on error.
192   int WriteAtCurrentPosNoBestEffort(const char* data, int size);
193 
194   // Returns the current size of this file, or a negative number on failure.
195   int64_t GetLength();
196 
197   // Truncates the file to the given length. If |length| is greater than the
198   // current size of the file, the file is extended with zeros. If the file
199   // doesn't exist, |false| is returned.
200   bool SetLength(int64_t length);
201 
202   // Instructs the filesystem to flush the file to disk. (POSIX: fsync, Windows:
203   // FlushFileBuffers).
204   // Calling Flush() does not guarantee file integrity and thus is not a valid
205   // substitute for file integrity checks and recovery codepaths for malformed
206   // files. It can also be *really* slow, so avoid blocking on Flush(),
207   // especially please don't block shutdown on Flush().
208   // Latency percentiles of Flush() across all platforms as of July 2016:
209   // 50 %     > 5 ms
210   // 10 %     > 58 ms
211   //  1 %     > 357 ms
212   //  0.1 %   > 1.8 seconds
213   //  0.01 %  > 7.6 seconds
214   bool Flush();
215 
216   // Returns some basic information for the given file.
217   bool GetInfo(Info* info);
218 
219 #if !defined(OS_FUCHSIA)  // Fuchsia's POSIX API does not support file locking.
220 
221   // Attempts to take an exclusive write lock on the file. Returns immediately
222   // (i.e. does not wait for another process to unlock the file). If the lock
223   // was obtained, the result will be FILE_OK. A lock only guarantees
224   // that other processes may not also take a lock on the same file with the
225   // same API - it may still be opened, renamed, unlinked, etc.
226   //
227   // Common semantics:
228   //  * Locks are held by processes, but not inherited by child processes.
229   //  * Locks are released by the OS on file close or process termination.
230   //  * Locks are reliable only on local filesystems.
231   //  * Duplicated file handles may also write to locked files.
232   // Windows-specific semantics:
233   //  * Locks are mandatory for read/write APIs, advisory for mapping APIs.
234   //  * Within a process, locking the same file (by the same or new handle)
235   //    will fail.
236   // POSIX-specific semantics:
237   //  * Locks are advisory only.
238   //  * Within a process, locking the same file (by the same or new handle)
239   //    will succeed.
240   //  * Closing any descriptor on a given file releases the lock.
241   Error Lock();
242 
243   // Unlock a file previously locked.
244   Error Unlock();
245 
246 #endif  // !defined(OS_FUCHSIA)
247 
248   // Returns a new object referencing this file for use within the current
249   // process.
250   File Duplicate() const;
251 
252 #if defined(OS_WIN)
253   static Error OSErrorToFileError(DWORD last_error);
254 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
255   static Error OSErrorToFileError(int saved_errno);
256 #endif
257 
258   // Gets the last global error (errno or GetLastError()) and converts it to the
259   // closest base::File::Error equivalent via OSErrorToFileError(). The returned
260   // value is only trustworthy immediately after another base::File method
261   // fails. base::File never resets the global error to zero.
262   static Error GetLastFileError();
263 
264   // Converts an error value to a human-readable form. Used for logging.
265   static std::string ErrorToString(Error error);
266 
267  private:
268   // Creates or opens the given file. Only called if |path| has no
269   // traversal ('..') components.
270   void DoInitialize(const FilePath& path, uint32_t flags);
271 
272   void SetPlatformFile(PlatformFile file);
273 
274   ScopedPlatformFile file_;
275 
276   Error error_details_ = FILE_ERROR_FAILED;
277 
278   File(const File&) = delete;
279   File& operator=(const File&) = delete;
280 };
281 
282 }  // namespace base
283 
284 #endif  // BASE_FILES_FILE_H_
285