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 "build/build_config.h"
      9 #if defined(OS_WIN)
     10 #include <windows.h>
     11 #endif
     12 
     13 #include <string>
     14 
     15 #include "base/base_export.h"
     16 #include "base/basictypes.h"
     17 #include "base/files/file_path.h"
     18 #include "base/move.h"
     19 #include "base/time/time.h"
     20 
     21 #if defined(OS_WIN)
     22 #include "base/win/scoped_handle.h"
     23 #endif
     24 
     25 namespace base {
     26 
     27 #if defined(OS_WIN)
     28 typedef HANDLE PlatformFile;
     29 #elif defined(OS_POSIX)
     30 typedef int PlatformFile;
     31 #endif
     32 
     33 
     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.
     37 //
     38 // 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.
     44 class BASE_EXPORT File {
     45   MOVE_ONLY_TYPE_FOR_CPP_03(File, RValue)
     46 
     47  public:
     48   // FLAG_(OPEN|CREATE).* are mutually exclusive. You should specify exactly one
     49   // of the five (possibly combining with other flags) when opening or creating
     50   // a file.
     51   // FLAG_(WRITE|APPEND) are mutually exclusive. This is so that APPEND behavior
     52   // will be consistent with O_APPEND on POSIX.
     53   // FLAG_EXCLUSIVE_(READ|WRITE) only grant exclusive access to the file on
     54   // creation on POSIX; for existing files, consider using Lock().
     55   enum Flags {
     56     FLAG_OPEN = 1 << 0,             // Opens a file, only if it exists.
     57     FLAG_CREATE = 1 << 1,           // Creates a new file, only if it does not
     58                                     // already exist.
     59     FLAG_OPEN_ALWAYS = 1 << 2,      // May create a new file.
     60     FLAG_CREATE_ALWAYS = 1 << 3,    // May overwrite an old file.
     61     FLAG_OPEN_TRUNCATED = 1 << 4,   // Opens a file and truncates it, only if it
     62                                     // exists.
     63     FLAG_READ = 1 << 5,
     64     FLAG_WRITE = 1 << 6,
     65     FLAG_APPEND = 1 << 7,
     66     FLAG_EXCLUSIVE_READ = 1 << 8,   // EXCLUSIVE is opposite of Windows SHARE.
     67     FLAG_EXCLUSIVE_WRITE = 1 << 9,
     68     FLAG_ASYNC = 1 << 10,
     69     FLAG_TEMPORARY = 1 << 11,       // Used on Windows only.
     70     FLAG_HIDDEN = 1 << 12,          // Used on Windows only.
     71     FLAG_DELETE_ON_CLOSE = 1 << 13,
     72     FLAG_WRITE_ATTRIBUTES = 1 << 14,  // Used on Windows only.
     73     FLAG_SHARE_DELETE = 1 << 15,      // Used on Windows only.
     74     FLAG_TERMINAL_DEVICE = 1 << 16,   // Serial port flags.
     75     FLAG_BACKUP_SEMANTICS = 1 << 17,  // Used on Windows only.
     76     FLAG_EXECUTE = 1 << 18,           // Used on Windows only.
     77   };
     78 
     79   // This enum has been recorded in multiple histograms. If the order of the
     80   // fields needs to change, please ensure that those histograms are obsolete or
     81   // have been moved to a different enum.
     82   //
     83   // FILE_ERROR_ACCESS_DENIED is returned when a call fails because of a
     84   // filesystem restriction. FILE_ERROR_SECURITY is returned when a browser
     85   // policy doesn't allow the operation to be executed.
     86   enum Error {
     87     FILE_OK = 0,
     88     FILE_ERROR_FAILED = -1,
     89     FILE_ERROR_IN_USE = -2,
     90     FILE_ERROR_EXISTS = -3,
     91     FILE_ERROR_NOT_FOUND = -4,
     92     FILE_ERROR_ACCESS_DENIED = -5,
     93     FILE_ERROR_TOO_MANY_OPENED = -6,
     94     FILE_ERROR_NO_MEMORY = -7,
     95     FILE_ERROR_NO_SPACE = -8,
     96     FILE_ERROR_NOT_A_DIRECTORY = -9,
     97     FILE_ERROR_INVALID_OPERATION = -10,
     98     FILE_ERROR_SECURITY = -11,
     99     FILE_ERROR_ABORT = -12,
    100     FILE_ERROR_NOT_A_FILE = -13,
    101     FILE_ERROR_NOT_EMPTY = -14,
    102     FILE_ERROR_INVALID_URL = -15,
    103     FILE_ERROR_IO = -16,
    104     // Put new entries here and increment FILE_ERROR_MAX.
    105     FILE_ERROR_MAX = -17
    106   };
    107 
    108   // This explicit mapping matches both FILE_ on Windows and SEEK_ on Linux.
    109   enum Whence {
    110     FROM_BEGIN   = 0,
    111     FROM_CURRENT = 1,
    112     FROM_END     = 2
    113   };
    114 
    115   // Used to hold information about a given file.
    116   // If you add more fields to this structure (platform-specific fields are OK),
    117   // make sure to update all functions that use it in file_util_{win|posix}.cc
    118   // too, and the ParamTraits<base::PlatformFileInfo> implementation in
    119   // chrome/common/common_param_traits.cc.
    120   struct BASE_EXPORT Info {
    121     Info();
    122     ~Info();
    123 
    124     // The size of the file in bytes.  Undefined when is_directory is true.
    125     int64 size;
    126 
    127     // True if the file corresponds to a directory.
    128     bool is_directory;
    129 
    130     // True if the file corresponds to a symbolic link.
    131     bool is_symbolic_link;
    132 
    133     // The last modified time of a file.
    134     base::Time last_modified;
    135 
    136     // The last accessed time of a file.
    137     base::Time last_accessed;
    138 
    139     // The creation time of a file.
    140     base::Time creation_time;
    141   };
    142 
    143   File();
    144 
    145   // Creates or opens the given file. This will fail with 'access denied' if the
    146   // |name| contains path traversal ('..') components.
    147   File(const FilePath& name, uint32 flags);
    148 
    149   // Takes ownership of |platform_file|.
    150   explicit File(PlatformFile platform_file);
    151 
    152   // Move constructor for C++03 move emulation of this type.
    153   File(RValue other);
    154 
    155   ~File();
    156 
    157   // Move operator= for C++03 move emulation of this type.
    158   File& operator=(RValue other);
    159 
    160   // Creates or opens the given file, allowing paths with traversal ('..')
    161   // components. Use only with extreme care.
    162   void CreateBaseFileUnsafe(const FilePath& name, uint32 flags);
    163 
    164   bool IsValid() const;
    165 
    166   // Returns true if a new file was created (or an old one truncated to zero
    167   // length to simulate a new file, which can happen with
    168   // FLAG_CREATE_ALWAYS), and false otherwise.
    169   bool created() const { return created_; }
    170 
    171   // Returns the OS result of opening this file.
    172   Error error() const { return error_; }
    173 
    174   PlatformFile GetPlatformFile() const { return file_; }
    175   PlatformFile TakePlatformFile();
    176 
    177   // Destroying this object closes the file automatically.
    178   void Close();
    179 
    180   // Changes current position in the file to an |offset| relative to an origin
    181   // defined by |whence|. Returns the resultant current position in the file
    182   // (relative to the start) or -1 in case of error.
    183   int64 Seek(Whence whence, int64 offset);
    184 
    185   // Reads the given number of bytes (or until EOF is reached) starting with the
    186   // given offset. Returns the number of bytes read, or -1 on error. Note that
    187   // this function makes a best effort to read all data on all platforms, so it
    188   // is not intended for stream oriented files but instead for cases when the
    189   // normal expectation is that actually |size| bytes are read unless there is
    190   // an error.
    191   int Read(int64 offset, char* data, int size);
    192 
    193   // Same as above but without seek.
    194   int ReadAtCurrentPos(char* data, int size);
    195 
    196   // Reads the given number of bytes (or until EOF is reached) starting with the
    197   // given offset, but does not make any effort to read all data on all
    198   // platforms. Returns the number of bytes read, or -1 on error.
    199   int ReadNoBestEffort(int64 offset, char* data, int size);
    200 
    201   // Same as above but without seek.
    202   int ReadAtCurrentPosNoBestEffort(char* data, int size);
    203 
    204   // Writes the given buffer into the file at the given offset, overwritting any
    205   // data that was previously there. Returns the number of bytes written, or -1
    206   // on error. Note that this function makes a best effort to write all data on
    207   // all platforms.
    208   // Ignores the offset and writes to the end of the file if the file was opened
    209   // with FLAG_APPEND.
    210   int Write(int64 offset, const char* data, int size);
    211 
    212   // Save as above but without seek.
    213   int WriteAtCurrentPos(const char* data, int size);
    214 
    215   // Save as above but does not make any effort to write all data on all
    216   // platforms. Returns the number of bytes written, or -1 on error.
    217   int WriteAtCurrentPosNoBestEffort(const char* data, int size);
    218 
    219   // Truncates the file to the given length. If |length| is greater than the
    220   // current size of the file, the file is extended with zeros. If the file
    221   // doesn't exist, |false| is returned.
    222   bool Truncate(int64 length);
    223 
    224   // Flushes the buffers.
    225   bool Flush();
    226 
    227   // Updates the file times.
    228   bool SetTimes(Time last_access_time, Time last_modified_time);
    229 
    230   // Returns some basic information for the given file.
    231   bool GetInfo(Info* info);
    232 
    233   // Attempts to take an exclusive write lock on the file. Returns immediately
    234   // (i.e. does not wait for another process to unlock the file). If the lock
    235   // was obtained, the result will be FILE_OK. A lock only guarantees
    236   // that other processes may not also take a lock on the same file with the
    237   // same API - it may still be opened, renamed, unlinked, etc.
    238   //
    239   // Common semantics:
    240   //  * Locks are held by processes, but not inherited by child processes.
    241   //  * Locks are released by the OS on file close or process termination.
    242   //  * Locks are reliable only on local filesystems.
    243   //  * Duplicated file handles may also write to locked files.
    244   // Windows-specific semantics:
    245   //  * Locks are mandatory for read/write APIs, advisory for mapping APIs.
    246   //  * Within a process, locking the same file (by the same or new handle)
    247   //    will fail.
    248   // POSIX-specific semantics:
    249   //  * Locks are advisory only.
    250   //  * Within a process, locking the same file (by the same or new handle)
    251   //    will succeed.
    252   //  * Closing any descriptor on a given file releases the lock.
    253   Error Lock();
    254 
    255   // Unlock a file previously locked.
    256   Error Unlock();
    257 
    258 #if defined(OS_WIN)
    259   static Error OSErrorToFileError(DWORD last_error);
    260 #elif defined(OS_POSIX)
    261   static Error OSErrorToFileError(int saved_errno);
    262 #endif
    263 
    264  private:
    265   void SetPlatformFile(PlatformFile file);
    266 
    267 #if defined(OS_WIN)
    268   win::ScopedHandle file_;
    269 #elif defined(OS_POSIX)
    270   PlatformFile file_;
    271 #endif
    272 
    273   Error error_;
    274   bool created_;
    275   bool async_;
    276 };
    277 
    278 }  // namespace base
    279 
    280 #endif  // BASE_FILES_FILE_H_
    281