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