file.h 17 KB

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