• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
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/base_export.h"
13 #include "base/containers/span.h"
14 #include "base/files/file_path.h"
15 #include "base/files/file_tracing.h"
16 #include "base/files/platform_file.h"
17 #include "base/time/time.h"
18 #include "base/trace_event/base_tracing_forward.h"
19 #include "build/build_config.h"
20 
21 struct stat;
22 
23 namespace base {
24 
25 using stat_wrapper_t = struct stat;
26 
27 // Thin wrapper around an OS-level file.
28 // Note that this class does not provide any support for asynchronous IO, other
29 // than the ability to create asynchronous handles on Windows.
30 //
31 // Note about const: this class does not attempt to determine if the underlying
32 // file system object is affected by a particular method in order to consider
33 // that method const or not. Only methods that deal with member variables in an
34 // obvious non-modifying way are marked as const. Any method that forward calls
35 // to the OS is not considered const, even if there is no apparent change to
36 // member variables.
37 //
38 // On POSIX, if the given file is a symbolic link, most of the methods apply to
39 // the file that the symbolic link resolves to.
40 class BASE_EXPORT File {
41  public:
42   // FLAG_(OPEN|CREATE).* are mutually exclusive. You should specify exactly one
43   // of the five (possibly combining with other flags) when opening or creating
44   // a file.
45   // FLAG_(WRITE|APPEND) are mutually exclusive. This is so that APPEND behavior
46   // will be consistent with O_APPEND on POSIX.
47   enum Flags : uint32_t {
48     FLAG_OPEN = 1 << 0,            // Opens a file, only if it exists.
49     FLAG_CREATE = 1 << 1,          // Creates a new file, only if it does not
50                                    // already exist.
51     FLAG_OPEN_ALWAYS = 1 << 2,     // May create a new file.
52     FLAG_CREATE_ALWAYS = 1 << 3,   // May overwrite an old file.
53     FLAG_OPEN_TRUNCATED = 1 << 4,  // Opens a file and truncates it, only if it
54                                    // exists.
55     FLAG_READ = 1 << 5,
56     FLAG_WRITE = 1 << 6,
57     FLAG_APPEND = 1 << 7,
58     FLAG_WIN_EXCLUSIVE_READ = 1 << 8,   // Windows only. Opposite of SHARE.
59     FLAG_WIN_EXCLUSIVE_WRITE = 1 << 9,  // Windows only. Opposite of SHARE.
60     FLAG_ASYNC = 1 << 10,
61     FLAG_WIN_TEMPORARY = 1 << 11,  // Windows only.
62     FLAG_WIN_HIDDEN = 1 << 12,     // Windows only.
63     FLAG_DELETE_ON_CLOSE = 1 << 13,
64     FLAG_WRITE_ATTRIBUTES = 1 << 14,  // File opened in a mode allowing writing
65                                       // attributes, such as with SetTimes().
66     FLAG_WIN_SHARE_DELETE = 1 << 15,  // Windows only.
67     FLAG_TERMINAL_DEVICE = 1 << 16,   // Serial port flags.
68     FLAG_WIN_BACKUP_SEMANTICS = 1 << 17,  // Windows only.
69     FLAG_WIN_EXECUTE = 1 << 18,           // Windows only.
70     FLAG_WIN_SEQUENTIAL_SCAN = 1 << 19,   // Windows only.
71     FLAG_CAN_DELETE_ON_CLOSE = 1 << 20,  // Requests permission to delete a file
72                                          // via DeleteOnClose() (Windows only).
73                                          // See DeleteOnClose() for details.
74     FLAG_WIN_NO_EXECUTE =
75         1 << 21,  // Windows only. Marks the file with a deny ACE that prevents
76                   // opening the file with EXECUTE access. Cannot be used with
77                   // FILE_WIN_EXECUTE flag. See also PreventExecuteMapping.
78   };
79 
80   // This enum has been recorded in multiple histograms using PlatformFileError
81   // enum. If the order of the fields needs to change, please ensure that those
82   // histograms are obsolete or have been moved to a different enum.
83   //
84   // FILE_ERROR_ACCESS_DENIED is returned when a call fails because of a
85   // filesystem restriction. FILE_ERROR_SECURITY is returned when a browser
86   // policy doesn't allow the operation to be executed.
87   enum Error {
88     FILE_OK = 0,
89     FILE_ERROR_FAILED = -1,
90     FILE_ERROR_IN_USE = -2,
91     FILE_ERROR_EXISTS = -3,
92     FILE_ERROR_NOT_FOUND = -4,
93     FILE_ERROR_ACCESS_DENIED = -5,
94     FILE_ERROR_TOO_MANY_OPENED = -6,
95     FILE_ERROR_NO_MEMORY = -7,
96     FILE_ERROR_NO_SPACE = -8,
97     FILE_ERROR_NOT_A_DIRECTORY = -9,
98     FILE_ERROR_INVALID_OPERATION = -10,
99     FILE_ERROR_SECURITY = -11,
100     FILE_ERROR_ABORT = -12,
101     FILE_ERROR_NOT_A_FILE = -13,
102     FILE_ERROR_NOT_EMPTY = -14,
103     FILE_ERROR_INVALID_URL = -15,
104     FILE_ERROR_IO = -16,
105     // Put new entries here and increment FILE_ERROR_MAX.
106     FILE_ERROR_MAX = -17
107   };
108 
109   // This explicit mapping matches both FILE_ on Windows and SEEK_ on Linux.
110   enum Whence {
111     FROM_BEGIN   = 0,
112     FROM_CURRENT = 1,
113     FROM_END     = 2
114   };
115 
116   // Used to hold information about a given file.
117   // If you add more fields to this structure (platform-specific fields are OK),
118   // make sure to update all functions that use it in file_util_{win|posix}.cc,
119   // too, and the ParamTraits<base::File::Info> implementation in
120   // ipc/ipc_message_utils.cc.
121   struct BASE_EXPORT Info {
122     Info();
123     ~Info();
124 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
125     // Fills this struct with values from |stat_info|.
126     void FromStat(const stat_wrapper_t& stat_info);
127 #endif
128 
129     // The size of the file in bytes.  Undefined when is_directory is true.
130     int64_t size = 0;
131 
132     // True if the file corresponds to a directory.
133     bool is_directory = false;
134 
135     // True if the file corresponds to a symbolic link.  For Windows currently
136     // not supported and thus always false.
137     bool is_symbolic_link = false;
138 
139     // The last modified time of a file.
140     Time last_modified;
141 
142     // The last accessed time of a file.
143     Time last_accessed;
144 
145     // The creation time of a file.
146     Time creation_time;
147   };
148 
149   File();
150 
151   // Creates or opens the given file. This will fail with 'access denied' if the
152   // |path| contains path traversal ('..') components.
153   File(const FilePath& path, uint32_t flags);
154 
155   // Takes ownership of |platform_file| and sets async to false.
156   explicit File(ScopedPlatformFile platform_file);
157   explicit File(PlatformFile platform_file);
158 
159   // 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(ScopedPlatformFile platform_file, bool async);
163   File(PlatformFile platform_file, bool async);
164 
165   // Creates an object with a specific error_details code.
166   explicit File(Error error_details);
167 
168   File(File&& other);
169 
170   File(const File&) = delete;
171   File& operator=(const File&) = delete;
172 
173   ~File();
174 
175   File& operator=(File&& other);
176 
177   // Creates or opens the given file.
178   void Initialize(const FilePath& path, uint32_t flags);
179 
180   // Returns |true| if the handle / fd wrapped by this object is valid.  This
181   // method doesn't interact with the file system and is thus safe to be called
182   // from threads that disallow blocking.
183   bool IsValid() const;
184 
185   // Returns true if a new file was created (or an old one truncated to zero
186   // length to simulate a new file, which can happen with
187   // FLAG_CREATE_ALWAYS), and false otherwise.
created()188   bool created() const { return created_; }
189 
190   // Returns the OS result of opening this file. Note that the way to verify
191   // the success of the operation is to use IsValid(), not this method:
192   //   File file(path, flags);
193   //   if (!file.IsValid())
194   //     return;
error_details()195   Error error_details() const { return error_details_; }
196 
197   PlatformFile GetPlatformFile() const;
198   PlatformFile TakePlatformFile();
199 
200   // Destroying this object closes the file automatically.
201   void Close();
202 
203   // Changes current position in the file to an |offset| relative to an origin
204   // defined by |whence|. Returns the resultant current position in the file
205   // (relative to the start) or -1 in case of error.
206   int64_t Seek(Whence whence, int64_t offset);
207 
208   // Simplified versions of Read() and friends (see below) that check the int
209   // return value and just return a boolean. They return true if and only if
210   // the function read in / wrote out exactly |data.size()| bytes of data.
211   bool ReadAndCheck(int64_t offset, span<uint8_t> data);
212   bool ReadAtCurrentPosAndCheck(span<uint8_t> data);
213   bool WriteAndCheck(int64_t offset, span<const uint8_t> data);
214   bool WriteAtCurrentPosAndCheck(span<const uint8_t> data);
215 
216   // Reads the given number of bytes (or until EOF is reached) starting with the
217   // given offset. Returns the number of bytes read, or -1 on error. Note that
218   // this function makes a best effort to read all data on all platforms, so it
219   // is not intended for stream oriented files but instead for cases when the
220   // normal expectation is that actually |size| bytes are read unless there is
221   // an error.
222   int Read(int64_t offset, char* data, int size);
223 
224   // Same as above but without seek.
225   int ReadAtCurrentPos(char* data, int size);
226 
227   // Reads the given number of bytes (or until EOF is reached) starting with the
228   // given offset, but does not make any effort to read all data on all
229   // platforms. Returns the number of bytes read, or -1 on error.
230   int ReadNoBestEffort(int64_t offset, char* data, int size);
231 
232   // Same as above but without seek.
233   int ReadAtCurrentPosNoBestEffort(char* data, int size);
234 
235   // Writes the given buffer into the file at the given offset, overwritting any
236   // data that was previously there. Returns the number of bytes written, or -1
237   // on error. Note that this function makes a best effort to write all data on
238   // all platforms. |data| can be nullptr when |size| is 0.
239   // Ignores the offset and writes to the end of the file if the file was opened
240   // with FLAG_APPEND.
241   int Write(int64_t offset, const char* data, int size);
242 
243   // Save as above but without seek.
244   int WriteAtCurrentPos(const char* data, int size);
245 
246   // Save as above but does not make any effort to write all data on all
247   // platforms. Returns the number of bytes written, or -1 on error.
248   int WriteAtCurrentPosNoBestEffort(const char* data, int size);
249 
250   // Returns the current size of this file, or a negative number on failure.
251   int64_t GetLength();
252 
253   // Truncates the file to the given length. If |length| is greater than the
254   // current size of the file, the file is extended with zeros. If the file
255   // doesn't exist, |false| is returned.
256   bool SetLength(int64_t length);
257 
258   // Instructs the filesystem to flush the file to disk. (POSIX: fsync, Windows:
259   // FlushFileBuffers).
260   // Calling Flush() does not guarantee file integrity and thus is not a valid
261   // substitute for file integrity checks and recovery codepaths for malformed
262   // files. It can also be *really* slow, so avoid blocking on Flush(),
263   // especially please don't block shutdown on Flush().
264   // Latency percentiles of Flush() across all platforms as of July 2016:
265   // 50 %     > 5 ms
266   // 10 %     > 58 ms
267   //  1 %     > 357 ms
268   //  0.1 %   > 1.8 seconds
269   //  0.01 %  > 7.6 seconds
270   bool Flush();
271 
272   // Updates the file times.
273   bool SetTimes(Time last_access_time, Time last_modified_time);
274 
275   // Returns some basic information for the given file.
276   bool GetInfo(Info* info);
277 
278 #if !BUILDFLAG( \
279     IS_FUCHSIA)  // Fuchsia's POSIX API does not support file locking.
280   enum class LockMode {
281     kShared,
282     kExclusive,
283   };
284 
285   // Attempts to take an exclusive write lock on the file. Returns immediately
286   // (i.e. does not wait for another process to unlock the file). If the lock
287   // was obtained, the result will be FILE_OK. A lock only guarantees
288   // that other processes may not also take a lock on the same file with the
289   // same API - it may still be opened, renamed, unlinked, etc.
290   //
291   // Common semantics:
292   //  * Locks are held by processes, but not inherited by child processes.
293   //  * Locks are released by the OS on file close or process termination.
294   //  * Locks are reliable only on local filesystems.
295   //  * Duplicated file handles may also write to locked files.
296   // Windows-specific semantics:
297   //  * Locks are mandatory for read/write APIs, advisory for mapping APIs.
298   //  * Within a process, locking the same file (by the same or new handle)
299   //    will fail.
300   // POSIX-specific semantics:
301   //  * Locks are advisory only.
302   //  * Within a process, locking the same file (by the same or new handle)
303   //    will succeed. The new lock replaces the old lock.
304   //  * Closing any descriptor on a given file releases the lock.
305   Error Lock(LockMode mode);
306 
307   // Unlock a file previously locked.
308   Error Unlock();
309 
310 #endif  // !BUILDFLAG(IS_FUCHSIA)
311 
312   // Returns a new object referencing this file for use within the current
313   // process. Handling of FLAG_DELETE_ON_CLOSE varies by OS. On POSIX, the File
314   // object that was created or initialized with this flag will have unlinked
315   // the underlying file when it was created or opened. On Windows, the
316   // underlying file is deleted when the last handle to it is closed.
317   File Duplicate() const;
318 
async()319   bool async() const { return async_; }
320 
321   // Serialise this object into a trace.
322   void WriteIntoTrace(perfetto::TracedValue context) const;
323 
324 #if BUILDFLAG(IS_WIN)
325   // Sets or clears the DeleteFile disposition on the file. Returns true if
326   // the disposition was set or cleared, as indicated by |delete_on_close|.
327   //
328   // Microsoft Windows deletes a file only when the DeleteFile disposition is
329   // set on a file when the last handle to the last underlying kernel File
330   // object is closed. This disposition is be set by:
331   // - Calling the Win32 DeleteFile function with the path to a file.
332   // - Opening/creating a file with FLAG_DELETE_ON_CLOSE and then closing all
333   //   handles to that File object.
334   // - Opening/creating a file with FLAG_CAN_DELETE_ON_CLOSE and subsequently
335   //   calling DeleteOnClose(true).
336   //
337   // In all cases, all pre-existing handles to the file must have been opened
338   // with FLAG_WIN_SHARE_DELETE. Once the disposition has been set by any of the
339   // above means, no new File objects can be created for the file.
340   //
341   // So:
342   // - Use FLAG_WIN_SHARE_DELETE when creating/opening a file to allow another
343   //   entity on the system to cause it to be deleted when it is closed. (Note:
344   //   another entity can delete the file the moment after it is closed, so not
345   //   using this permission doesn't provide any protections.)
346   // - Use FLAG_DELETE_ON_CLOSE for any file that is to be deleted after use.
347   //   The OS will ensure it is deleted even in the face of process termination.
348   //   Note that it's possible for deletion to be cancelled via another File
349   //   object referencing the same file using DeleteOnClose(false) to clear the
350   //   DeleteFile disposition after the original File is closed.
351   // - Use FLAG_CAN_DELETE_ON_CLOSE in conjunction with DeleteOnClose() to alter
352   //   the DeleteFile disposition on an open handle. This fine-grained control
353   //   allows for marking a file for deletion during processing so that it is
354   //   deleted in the event of untimely process termination, and then clearing
355   //   this state once the file is suitable for persistence.
356   bool DeleteOnClose(bool delete_on_close);
357 #endif
358 
359 #if BUILDFLAG(IS_WIN)
360   static Error OSErrorToFileError(DWORD last_error);
361 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
362   static Error OSErrorToFileError(int saved_errno);
363 #endif
364 
365   // Gets the last global error (errno or GetLastError()) and converts it to the
366   // closest base::File::Error equivalent via OSErrorToFileError(). The returned
367   // value is only trustworthy immediately after another base::File method
368   // fails. base::File never resets the global error to zero.
369   static Error GetLastFileError();
370 
371   // Converts an error value to a human-readable form. Used for logging.
372   static std::string ErrorToString(Error error);
373 
374 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
375   // Wrapper for stat().
376   static int Stat(const char* path, stat_wrapper_t* sb);
377   // Wrapper for fstat().
378   static int Fstat(int fd, stat_wrapper_t* sb);
379   // Wrapper for lstat().
380   static int Lstat(const char* path, stat_wrapper_t* sb);
381 #endif
382 
383   // This function can be used to augment `flags` with the correct flags
384   // required to create a File that can be safely passed to an untrusted
385   // process. It must be called if the File is intended to be transferred to an
386   // untrusted process, but can still be safely called even if the File is not
387   // intended to be transferred.
AddFlagsForPassingToUntrustedProcess(uint32_t flags)388   static constexpr uint32_t AddFlagsForPassingToUntrustedProcess(
389       uint32_t flags) {
390     if (flags & File::FLAG_WRITE || flags & File::FLAG_APPEND ||
391         flags & File::FLAG_WRITE_ATTRIBUTES) {
392       flags |= File::FLAG_WIN_NO_EXECUTE;
393     }
394     return flags;
395   }
396 
397  private:
398   friend class FileTracing::ScopedTrace;
399 
400   // Creates or opens the given file. Only called if |path| has no
401   // traversal ('..') components.
402   void DoInitialize(const FilePath& path, uint32_t flags);
403 
404   void SetPlatformFile(PlatformFile file);
405 
406   ScopedPlatformFile file_;
407 
408   // A path to use for tracing purposes. Set if file tracing is enabled during
409   // |Initialize()|.
410   FilePath tracing_path_;
411 
412   // Object tied to the lifetime of |this| that enables/disables tracing.
413   FileTracing::ScopedEnabler trace_enabler_;
414 
415   Error error_details_ = FILE_ERROR_FAILED;
416   bool created_ = false;
417   bool async_ = false;
418 };
419 
420 }  // namespace base
421 
422 #endif  // BASE_FILES_FILE_H_
423