Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / base / files / file.h
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 #if defined(OS_POSIX)
14 #include <sys/stat.h>
15 #endif
16
17 #include <string>
18
19 #include "base/base_export.h"
20 #include "base/basictypes.h"
21 #include "base/files/scoped_file.h"
22 #include "base/gtest_prod_util.h"
23 #include "base/move.h"
24 #include "base/time/time.h"
25
26 #if defined(OS_WIN)
27 #include "base/win/scoped_handle.h"
28 #endif
29
30 FORWARD_DECLARE_TEST(FileTest, MemoryCorruption);
31
32 namespace base {
33
34 class FilePath;
35
36 #if defined(OS_WIN)
37 typedef HANDLE PlatformFile;
38 #elif defined(OS_POSIX)
39 typedef int PlatformFile;
40
41 #if defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL)
42 typedef struct stat stat_wrapper_t;
43 #else
44 typedef struct stat64 stat_wrapper_t;
45 #endif
46 #endif  // defined(OS_POSIX)
47
48 // Thin wrapper around an OS-level file.
49 // Note that this class does not provide any support for asynchronous IO, other
50 // than the ability to create asynchronous handles on Windows.
51 //
52 // Note about const: this class does not attempt to determine if the underlying
53 // file system object is affected by a particular method in order to consider
54 // that method const or not. Only methods that deal with member variables in an
55 // obvious non-modifying way are marked as const. Any method that forward calls
56 // to the OS is not considered const, even if there is no apparent change to
57 // member variables.
58 class BASE_EXPORT File {
59   MOVE_ONLY_TYPE_FOR_CPP_03(File, RValue)
60
61  public:
62   // FLAG_(OPEN|CREATE).* are mutually exclusive. You should specify exactly one
63   // of the five (possibly combining with other flags) when opening or creating
64   // a file.
65   // FLAG_(WRITE|APPEND) are mutually exclusive. This is so that APPEND behavior
66   // will be consistent with O_APPEND on POSIX.
67   // FLAG_EXCLUSIVE_(READ|WRITE) only grant exclusive access to the file on
68   // creation on POSIX; for existing files, consider using Lock().
69   enum Flags {
70     FLAG_OPEN = 1 << 0,             // Opens a file, only if it exists.
71     FLAG_CREATE = 1 << 1,           // Creates a new file, only if it does not
72                                     // already exist.
73     FLAG_OPEN_ALWAYS = 1 << 2,      // May create a new file.
74     FLAG_CREATE_ALWAYS = 1 << 3,    // May overwrite an old file.
75     FLAG_OPEN_TRUNCATED = 1 << 4,   // Opens a file and truncates it, only if it
76                                     // exists.
77     FLAG_READ = 1 << 5,
78     FLAG_WRITE = 1 << 6,
79     FLAG_APPEND = 1 << 7,
80     FLAG_EXCLUSIVE_READ = 1 << 8,   // EXCLUSIVE is opposite of Windows SHARE.
81     FLAG_EXCLUSIVE_WRITE = 1 << 9,
82     FLAG_ASYNC = 1 << 10,
83     FLAG_TEMPORARY = 1 << 11,       // Used on Windows only.
84     FLAG_HIDDEN = 1 << 12,          // Used on Windows only.
85     FLAG_DELETE_ON_CLOSE = 1 << 13,
86     FLAG_WRITE_ATTRIBUTES = 1 << 14,  // Used on Windows only.
87     FLAG_SHARE_DELETE = 1 << 15,      // Used on Windows only.
88     FLAG_TERMINAL_DEVICE = 1 << 16,   // Serial port flags.
89     FLAG_BACKUP_SEMANTICS = 1 << 17,  // Used on Windows only.
90     FLAG_EXECUTE = 1 << 18,           // Used on Windows only.
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::PlatformFileInfo> implementation in
133   // chrome/common/common_param_traits.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 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.
149     bool is_symbolic_link;
150
151     // The last modified time of a file.
152     base::Time last_modified;
153
154     // The last accessed time of a file.
155     base::Time last_accessed;
156
157     // The creation time of a file.
158     base::Time creation_time;
159   };
160
161   File();
162
163   // Creates or opens the given file. This will fail with 'access denied' if the
164   // |name| contains path traversal ('..') components.
165   File(const FilePath& name, uint32 flags);
166
167   // Takes ownership of |platform_file|.
168   explicit File(PlatformFile platform_file);
169
170   // Creates an object with a specific error_details code.
171   explicit File(Error error_details);
172
173   // Move constructor for C++03 move emulation of this type.
174   File(RValue other);
175
176   ~File();
177
178   // Move operator= for C++03 move emulation of this type.
179   File& operator=(RValue other);
180
181   // Creates or opens the given file.
182   void Initialize(const FilePath& name, uint32 flags);
183
184   // Creates or opens the given file, allowing paths with traversal ('..')
185   // components. Use only with extreme care.
186   void InitializeUnsafe(const FilePath& name, uint32 flags);
187
188   bool IsValid() const;
189
190   // Returns true if a new file was created (or an old one truncated to zero
191   // length to simulate a new file, which can happen with
192   // FLAG_CREATE_ALWAYS), and false otherwise.
193   bool created() const { return created_; }
194
195   // Returns the OS result of opening this file. Note that the way to verify
196   // the success of the operation is to use IsValid(), not this method:
197   //   File file(name, flags);
198   //   if (!file.IsValid())
199   //     return;
200   Error error_details() const { return error_details_; }
201
202   PlatformFile GetPlatformFile() const;
203   PlatformFile TakePlatformFile();
204
205   // Destroying this object closes the file automatically.
206   void Close();
207
208   // Changes current position in the file to an |offset| relative to an origin
209   // defined by |whence|. Returns the resultant current position in the file
210   // (relative to the start) or -1 in case of error.
211   int64 Seek(Whence whence, int64 offset);
212
213   // Reads the given number of bytes (or until EOF is reached) starting with the
214   // given offset. Returns the number of bytes read, or -1 on error. Note that
215   // this function makes a best effort to read all data on all platforms, so it
216   // is not intended for stream oriented files but instead for cases when the
217   // normal expectation is that actually |size| bytes are read unless there is
218   // an error.
219   int Read(int64 offset, char* data, int size);
220
221   // Same as above but without seek.
222   int ReadAtCurrentPos(char* data, int size);
223
224   // Reads the given number of bytes (or until EOF is reached) starting with the
225   // given offset, but does not make any effort to read all data on all
226   // platforms. Returns the number of bytes read, or -1 on error.
227   int ReadNoBestEffort(int64 offset, char* data, int size);
228
229   // Same as above but without seek.
230   int ReadAtCurrentPosNoBestEffort(char* data, int size);
231
232   // Writes the given buffer into the file at the given offset, overwritting any
233   // data that was previously there. Returns the number of bytes written, or -1
234   // on error. Note that this function makes a best effort to write all data on
235   // all platforms.
236   // Ignores the offset and writes to the end of the file if the file was opened
237   // with FLAG_APPEND.
238   int Write(int64 offset, const char* data, int size);
239
240   // Save as above but without seek.
241   int WriteAtCurrentPos(const char* data, int size);
242
243   // Save as above but does not make any effort to write all data on all
244   // platforms. Returns the number of bytes written, or -1 on error.
245   int WriteAtCurrentPosNoBestEffort(const char* data, int size);
246
247   // Returns the current size of this file, or a negative number on failure.
248   int64 GetLength();
249
250   // Truncates the file to the given length. If |length| is greater than the
251   // current size of the file, the file is extended with zeros. If the file
252   // doesn't exist, |false| is returned.
253   bool SetLength(int64 length);
254
255   // Instructs the filesystem to flush the file to disk. (POSIX: fsync, Windows:
256   // FlushFileBuffers).
257   bool Flush();
258
259   // Updates the file times.
260   bool SetTimes(Time last_access_time, Time last_modified_time);
261
262   // Returns some basic information for the given file.
263   bool GetInfo(Info* info);
264
265   // Attempts to take an exclusive write lock on the file. Returns immediately
266   // (i.e. does not wait for another process to unlock the file). If the lock
267   // was obtained, the result will be FILE_OK. A lock only guarantees
268   // that other processes may not also take a lock on the same file with the
269   // same API - it may still be opened, renamed, unlinked, etc.
270   //
271   // Common semantics:
272   //  * Locks are held by processes, but not inherited by child processes.
273   //  * Locks are released by the OS on file close or process termination.
274   //  * Locks are reliable only on local filesystems.
275   //  * Duplicated file handles may also write to locked files.
276   // Windows-specific semantics:
277   //  * Locks are mandatory for read/write APIs, advisory for mapping APIs.
278   //  * Within a process, locking the same file (by the same or new handle)
279   //    will fail.
280   // POSIX-specific semantics:
281   //  * Locks are advisory only.
282   //  * Within a process, locking the same file (by the same or new handle)
283   //    will succeed.
284   //  * Closing any descriptor on a given file releases the lock.
285   Error Lock();
286
287   // Unlock a file previously locked.
288   Error Unlock();
289
290   bool async() const { return async_; }
291
292 #if defined(OS_WIN)
293   static Error OSErrorToFileError(DWORD last_error);
294 #elif defined(OS_POSIX)
295   static Error OSErrorToFileError(int saved_errno);
296 #endif
297
298   // Converts an error value to a human-readable form. Used for logging.
299   static std::string ErrorToString(Error error);
300
301  private:
302   FRIEND_TEST_ALL_PREFIXES(::FileTest, MemoryCorruption);
303
304 #if defined(OS_POSIX)
305   // Encloses a single ScopedFD, saving a cheap tamper resistent memory checksum
306   // alongside it. This checksum is validated at every access, allowing early
307   // detection of memory corruption.
308
309   // TODO(gavinp): This is in place temporarily to help us debug
310   // https://crbug.com/424562 , which can't be reproduced in valgrind. Remove
311   // this code after we have fixed this issue.
312   class MemoryCheckingScopedFD {
313    public:
314     MemoryCheckingScopedFD();
315     MemoryCheckingScopedFD(int fd);
316     ~MemoryCheckingScopedFD();
317
318     bool is_valid() const { Check(); return file_.is_valid(); }
319     int get() const { Check(); return file_.get(); }
320
321     void reset() { Check(); file_.reset(); UpdateChecksum(); }
322     void reset(int fd) { Check(); file_.reset(fd); UpdateChecksum(); }
323     int release() {
324       Check();
325       int fd = file_.release();
326       UpdateChecksum();
327       return fd;
328     }
329
330    private:
331     FRIEND_TEST_ALL_PREFIXES(::FileTest, MemoryCorruption);
332
333     // Computes the checksum for the current value of |file_|. Returns via an
334     // out parameter to guard against implicit conversions of unsigned integral
335     // types.
336     void ComputeMemoryChecksum(unsigned int* out_checksum) const;
337
338     // Confirms that the current |file_| and |file_memory_checksum_| agree,
339     // failing a CHECK if they do not.
340     void Check() const;
341
342     void UpdateChecksum();
343
344     ScopedFD file_;
345     unsigned int file_memory_checksum_;
346   };
347 #endif
348
349   void SetPlatformFile(PlatformFile file);
350
351 #if defined(OS_WIN)
352   win::ScopedHandle file_;
353 #elif defined(OS_POSIX)
354   MemoryCheckingScopedFD file_;
355 #endif
356
357   Error error_details_;
358   bool created_;
359   bool async_;
360 };
361
362 }  // namespace base
363
364 #endif  // BASE_FILES_FILE_H_