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 22namespace 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 || defined(OS_SERENITY) 27typedef struct stat stat_wrapper_t; 28#elif defined(OS_POSIX) || defined(OS_FUCHSIA) 29typedef 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. 41class File { 42 public: 43 // FLAG_(OPEN|CREATE).* are mutually exclusive. You should specify exactly one 44 // of the three (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 = 1 << 1, // Creates a new file, only if it does not 49 // already exist. 50 FLAG_CREATE_ALWAYS = 1 << 3, // May overwrite an old file. 51 FLAG_READ = 1 << 4, 52 FLAG_WRITE = 1 << 5, 53 }; 54 55 // This enum has been recorded in multiple histograms using PlatformFileError 56 // enum. If the order of the fields needs to change, please ensure that those 57 // histograms are obsolete or have been moved to a different enum. 58 // 59 // FILE_ERROR_ACCESS_DENIED is returned when a call fails because of a 60 // filesystem restriction. FILE_ERROR_SECURITY is returned when a browser 61 // policy doesn't allow the operation to be executed. 62 enum Error { 63 FILE_OK = 0, 64 FILE_ERROR_FAILED = -1, 65 FILE_ERROR_IN_USE = -2, 66 FILE_ERROR_EXISTS = -3, 67 FILE_ERROR_NOT_FOUND = -4, 68 FILE_ERROR_ACCESS_DENIED = -5, 69 FILE_ERROR_TOO_MANY_OPENED = -6, 70 FILE_ERROR_NO_MEMORY = -7, 71 FILE_ERROR_NO_SPACE = -8, 72 FILE_ERROR_NOT_A_DIRECTORY = -9, 73 FILE_ERROR_INVALID_OPERATION = -10, 74 FILE_ERROR_SECURITY = -11, 75 FILE_ERROR_ABORT = -12, 76 FILE_ERROR_NOT_A_FILE = -13, 77 FILE_ERROR_NOT_EMPTY = -14, 78 FILE_ERROR_INVALID_URL = -15, 79 FILE_ERROR_IO = -16, 80 // Put new entries here and increment FILE_ERROR_MAX. 81 FILE_ERROR_MAX = -17 82 }; 83 84 // This explicit mapping matches both FILE_ on Windows and SEEK_ on Linux. 85 enum Whence { FROM_BEGIN = 0, FROM_CURRENT = 1, FROM_END = 2 }; 86 87 // Used to hold information about a given file. 88 // If you add more fields to this structure (platform-specific fields are OK), 89 // make sure to update all functions that use it in file_util_{win|posix}.cc, 90 // too, and the ParamTraits<base::File::Info> implementation in 91 // ipc/ipc_message_utils.cc. 92 struct Info { 93 Info(); 94 ~Info(); 95#if defined(OS_POSIX) || defined(OS_FUCHSIA) 96 // Fills this struct with values from |stat_info|. 97 void FromStat(const stat_wrapper_t& stat_info); 98#endif 99 100 // The size of the file in bytes. Undefined when is_directory is true. 101 int64_t size = 0; 102 103 // True if the file corresponds to a directory. 104 bool is_directory = false; 105 106 // True if the file corresponds to a symbolic link. For Windows currently 107 // not supported and thus always false. 108 bool is_symbolic_link = false; 109 110 // The last modified time of a file. 111 Ticks last_modified; 112 113 // The last accessed time of a file. 114 Ticks last_accessed; 115 116 // The creation time of a file. 117 Ticks creation_time; 118 }; 119 120 File(); 121 122 // Creates or opens the given file. This will fail with 'access denied' if the 123 // |path| contains path traversal ('..') components. 124 File(const FilePath& path, uint32_t flags); 125 126 // Takes ownership of |platform_file|. 127 explicit File(ScopedPlatformFile platform_file); 128 explicit File(PlatformFile platform_file); 129 130 // Creates an object with a specific error_details code. 131 explicit File(Error error_details); 132 133 File(File&& other); 134 135 ~File(); 136 137 File& operator=(File&& other); 138 139 // Creates or opens the given file. 140 void Initialize(const FilePath& path, uint32_t flags); 141 142 // Returns |true| if the handle / fd wrapped by this object is valid. This 143 // method doesn't interact with the file system (and is safe to be called from 144 // ThreadRestrictions::SetIOAllowed(false) threads). 145 bool IsValid() const; 146 147 // Returns the OS result of opening this file. Note that the way to verify 148 // the success of the operation is to use IsValid(), not this method: 149 // File file(path, flags); 150 // if (!file.IsValid()) 151 // return; 152 Error error_details() const { return error_details_; } 153 154 PlatformFile GetPlatformFile() const; 155 PlatformFile TakePlatformFile(); 156 157 // Destroying this object closes the file automatically. 158 void Close(); 159 160 // Changes current position in the file to an |offset| relative to an origin 161 // defined by |whence|. Returns the resultant current position in the file 162 // (relative to the start) or -1 in case of error. 163 int64_t Seek(Whence whence, int64_t offset); 164 165 // Reads the given number of bytes (or until EOF is reached) starting with the 166 // given offset. Returns the number of bytes read, or -1 on error. Note that 167 // this function makes a best effort to read all data on all platforms, so it 168 // is not intended for stream oriented files but instead for cases when the 169 // normal expectation is that actually |size| bytes are read unless there is 170 // an error. 171 int Read(int64_t offset, char* data, int size); 172 173 // Same as above but without seek. 174 int ReadAtCurrentPos(char* data, int size); 175 176 // Reads the given number of bytes (or until EOF is reached) starting with the 177 // given offset, but does not make any effort to read all data on all 178 // platforms. Returns the number of bytes read, or -1 on error. 179 int ReadNoBestEffort(int64_t offset, char* data, int size); 180 181 // Same as above but without seek. 182 int ReadAtCurrentPosNoBestEffort(char* data, int size); 183 184 // Writes the given buffer into the file at the given offset, overwriting any 185 // data that was previously there. Returns the number of bytes written, or -1 186 // on error. Note that this function makes a best effort to write all data on 187 // all platforms. |data| can be nullptr when |size| is 0. 188 int Write(int64_t offset, const char* data, int size); 189 190 // Save as above but without seek. 191 int WriteAtCurrentPos(const char* data, int size); 192 193 // Save as above but does not make any effort to write all data on all 194 // platforms. Returns the number of bytes written, or -1 on error. 195 int WriteAtCurrentPosNoBestEffort(const char* data, int size); 196 197 // Returns the current size of this file, or a negative number on failure. 198 int64_t GetLength(); 199 200 // Truncates the file to the given length. If |length| is greater than the 201 // current size of the file, the file is extended with zeros. If the file 202 // doesn't exist, |false| is returned. 203 bool SetLength(int64_t length); 204 205 // Instructs the filesystem to flush the file to disk. (POSIX: fsync, Windows: 206 // FlushFileBuffers). 207 // Calling Flush() does not guarantee file integrity and thus is not a valid 208 // substitute for file integrity checks and recovery codepaths for malformed 209 // files. It can also be *really* slow, so avoid blocking on Flush(), 210 // especially please don't block shutdown on Flush(). 211 // Latency percentiles of Flush() across all platforms as of July 2016: 212 // 50 % > 5 ms 213 // 10 % > 58 ms 214 // 1 % > 357 ms 215 // 0.1 % > 1.8 seconds 216 // 0.01 % > 7.6 seconds 217 bool Flush(); 218 219 // Returns some basic information for the given file. 220 bool GetInfo(Info* info); 221 222#if !defined(OS_FUCHSIA) // Fuchsia's POSIX API does not support file locking. 223 224 // Attempts to take an exclusive write lock on the file. Returns immediately 225 // (i.e. does not wait for another process to unlock the file). If the lock 226 // was obtained, the result will be FILE_OK. A lock only guarantees 227 // that other processes may not also take a lock on the same file with the 228 // same API - it may still be opened, renamed, unlinked, etc. 229 // 230 // Common semantics: 231 // * Locks are held by processes, but not inherited by child processes. 232 // * Locks are released by the OS on file close or process termination. 233 // * Locks are reliable only on local filesystems. 234 // * Duplicated file handles may also write to locked files. 235 // Windows-specific semantics: 236 // * Locks are mandatory for read/write APIs, advisory for mapping APIs. 237 // * Within a process, locking the same file (by the same or new handle) 238 // will fail. 239 // POSIX-specific semantics: 240 // * Locks are advisory only. 241 // * Within a process, locking the same file (by the same or new handle) 242 // will succeed. 243 // * Closing any descriptor on a given file releases the lock. 244 Error Lock(); 245 246 // Unlock a file previously locked. 247 Error Unlock(); 248 249#endif // !defined(OS_FUCHSIA) 250 251 // Returns a new object referencing this file for use within the current 252 // process. 253 File Duplicate() const; 254 255#if defined(OS_WIN) 256 static Error OSErrorToFileError(DWORD last_error); 257#elif defined(OS_POSIX) || defined(OS_FUCHSIA) 258 static Error OSErrorToFileError(int saved_errno); 259#endif 260 261 // Gets the last global error (errno or GetLastError()) and converts it to the 262 // closest base::File::Error equivalent via OSErrorToFileError(). The returned 263 // value is only trustworthy immediately after another base::File method 264 // fails. base::File never resets the global error to zero. 265 static Error GetLastFileError(); 266 267 // Converts an error value to a human-readable form. Used for logging. 268 static std::string ErrorToString(Error error); 269 270 private: 271 // Creates or opens the given file. Only called if |path| has no 272 // traversal ('..') components. 273 void DoInitialize(const FilePath& path, uint32_t flags); 274 275 void SetPlatformFile(PlatformFile file); 276 277 ScopedPlatformFile file_; 278 279 Error error_details_ = FILE_ERROR_FAILED; 280 281 File(const File&) = delete; 282 File& operator=(const File&) = delete; 283}; 284 285} // namespace base 286 287#endif // BASE_FILES_FILE_H_ 288