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