Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(115)

Side by Side Diff: net/base/file_stream_posix.cc

Issue 10701050: net: Implement canceling of all async operations in FileStream. (Closed) Base URL: https://src.chromium.org/chrome/trunk/src/
Patch Set: Created 8 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 // For 64-bit file access (off_t = off64_t, lseek64, etc). 5 // For 64-bit file access (off_t = off64_t, lseek64, etc).
6 #define _FILE_OFFSET_BITS 64 6 #define _FILE_OFFSET_BITS 64
7 7
8 #include "net/base/file_stream.h" 8 #include "net/base/file_stream_posix.h"
9 9
10 #include <sys/types.h> 10 #include <sys/types.h>
11 #include <sys/stat.h> 11 #include <sys/stat.h>
12 #include <fcntl.h> 12 #include <fcntl.h>
13 #include <unistd.h> 13 #include <unistd.h>
14 #include <errno.h> 14 #include <errno.h>
15 15
16 #include "base/basictypes.h" 16 #include "base/basictypes.h"
17 #include "base/bind.h" 17 #include "base/bind.h"
18 #include "base/bind_helpers.h" 18 #include "base/bind_helpers.h"
19 #include "base/callback.h" 19 #include "base/callback.h"
20 #include "base/eintr_wrapper.h" 20 #include "base/eintr_wrapper.h"
21 #include "base/file_path.h" 21 #include "base/file_path.h"
22 #include "base/logging.h" 22 #include "base/logging.h"
23 #include "base/memory/ref_counted.h"
23 #include "base/message_loop.h" 24 #include "base/message_loop.h"
24 #include "base/metrics/histogram.h" 25 #include "base/metrics/histogram.h"
25 #include "base/string_util.h" 26 #include "base/string_util.h"
27 #include "base/task_runner_util.h"
26 #include "base/threading/thread_restrictions.h" 28 #include "base/threading/thread_restrictions.h"
27 #include "base/threading/worker_pool.h" 29 #include "base/threading/worker_pool.h"
28 #include "base/synchronization/waitable_event.h"
29 #include "net/base/file_stream_metrics.h"
30 #include "net/base/file_stream_net_log_parameters.h" 30 #include "net/base/file_stream_net_log_parameters.h"
31 #include "net/base/io_buffer.h" 31 #include "net/base/io_buffer.h"
32 #include "net/base/net_errors.h" 32 #include "net/base/net_errors.h"
33 33
34 #if defined(OS_ANDROID) 34 #if defined(OS_ANDROID)
35 // Android's bionic libc only supports the LFS transitional API. 35 // Android's bionic libc only supports the LFS transitional API.
36 #define off_t off64_t 36 #define off_t off64_t
37 #define lseek lseek64 37 #define lseek lseek64
38 #define stat stat64 38 #define stat stat64
39 #define fstat fstat64 39 #define fstat fstat64
40 #endif 40 #endif
41 41
42 namespace net { 42 namespace net {
43 43
44 // We cast back and forth, so make sure it's the size we're expecting. 44 // We cast back and forth, so make sure it's the size we're expecting.
45 COMPILE_ASSERT(sizeof(int64) == sizeof(off_t), off_t_64_bit); 45 COMPILE_ASSERT(sizeof(int64) == sizeof(off_t), off_t_64_bit);
46 46
47 // Make sure our Whence mappings match the system headers. 47 // Make sure our Whence mappings match the system headers.
48 COMPILE_ASSERT(FROM_BEGIN == SEEK_SET && 48 COMPILE_ASSERT(FROM_BEGIN == SEEK_SET &&
49 FROM_CURRENT == SEEK_CUR && 49 FROM_CURRENT == SEEK_CUR &&
50 FROM_END == SEEK_END, whence_matches_system); 50 FROM_END == SEEK_END, whence_matches_system);
51 51
52 namespace { 52 FileStream::Context::Context(const BoundNetLog& bound_net_log)
53 53 : file_(base::kInvalidPlatformFileValue),
54 int RecordAndMapError(int error, 54 record_uma_(false),
55 FileErrorSource source, 55 async_in_progress_(false),
56 bool record_uma, 56 orphaned_(false),
57 const net::BoundNetLog& bound_net_log) { 57 bound_net_log_(bound_net_log) {
58 net::Error net_error = MapSystemError(error); 58 }
59 59
60 bound_net_log.AddEvent( 60 FileStream::Context::Context(base::PlatformFile file,
61 net::NetLog::TYPE_FILE_STREAM_ERROR, 61 const BoundNetLog& bound_net_log,
62 base::Bind(&NetLogFileStreamErrorCallback, 62 int /* open_flags */)
63 source, error, net_error)); 63 : file_(file),
64 64 record_uma_(false),
65 RecordFileError(error, source, record_uma); 65 async_in_progress_(false),
66 66 orphaned_(false),
67 return net_error; 67 bound_net_log_(bound_net_log) {
68 } 68 }
69 69
70 // Opens a file with some network logging. 70 FileStream::Context::~Context() {
71 // The opened file and the result code are written to |file| and |result|. 71 }
72 void OpenFile(const FilePath& path, 72
73 int open_flags, 73 void FileStream::Context::Orphan() {
willchan no longer on Chromium 2012/09/05 00:15:48 I would change this to DCHECK(async_in_progress);
74 bool record_uma, 74 orphaned_ = true;
75 base::PlatformFile* file, 75 if (!async_in_progress_)
76 int* result, 76 CloseAsync(CompletionCallback());
77 const net::BoundNetLog& bound_net_log) { 77 }
78 std::string file_name = path.AsUTF8Unsafe(); 78
79 bound_net_log.BeginEvent( 79 void FileStream::Context::OpenAsync(const FilePath& path,
80 net::NetLog::TYPE_FILE_STREAM_OPEN, 80 int open_flags,
81 NetLog::StringCallback("file_name", &file_name)); 81 const CompletionCallback& callback) {
82 82 DCHECK(!async_in_progress_);
83 *result = OK; 83
84 *file = base::CreatePlatformFile(path, open_flags, NULL, NULL); 84 BeginOpenEvent(path);
85 if (*file == base::kInvalidPlatformFileValue) { 85
86 bound_net_log.EndEvent(net::NetLog::TYPE_FILE_STREAM_OPEN); 86 const bool posted = base::PostTaskAndReplyWithResult(
87 *result = RecordAndMapError(errno, FILE_ERROR_SOURCE_OPEN, record_uma, 87 base::WorkerPool::GetTaskRunner(true /* task_is_slow */),
88 bound_net_log); 88 FROM_HERE,
89 } 89 base::Bind(&Context::OpenFileImpl,
90 } 90 base::Unretained(this), path, open_flags),
91 91 base::Bind(&Context::OnOpenCompleted,
92 // Opens a file using OpenFile() and then signals the completion. 92 base::Unretained(this), callback));
93 void OpenFileAndSignal(const FilePath& path, 93 DCHECK(posted);
94 int open_flags, 94
95 bool record_uma, 95 async_in_progress_ = true;
96 base::PlatformFile* file, 96 }
97 int* result, 97
98 base::WaitableEvent* on_io_complete, 98 int FileStream::Context::OpenSync(const FilePath& path, int open_flags) {
99 const net::BoundNetLog& bound_net_log) { 99 BeginOpenEvent(path);
100 OpenFile(path, open_flags, record_uma, file, result, bound_net_log); 100 int result = OpenFileImpl(path, open_flags);
101 on_io_complete->Signal(); 101 CheckForOpenError(&result);
102 } 102 return result;
103 103 }
104 // Closes a file with some network logging. 104
105 void CloseFile(base::PlatformFile file, 105 void FileStream::Context::CloseAsync(const CompletionCallback& callback) {
106 const net::BoundNetLog& bound_net_log) { 106 DCHECK(!async_in_progress_);
107 bound_net_log.AddEvent(net::NetLog::TYPE_FILE_STREAM_CLOSE); 107
108 if (file == base::kInvalidPlatformFileValue) 108 bound_net_log_.AddEvent(net::NetLog::TYPE_FILE_STREAM_CLOSE);
109 return; 109
110 110 if (file_ == base::kInvalidPlatformFileValue) {
111 if (!base::ClosePlatformFile(file)) 111 MessageLoop::current()->PostTask(
112 NOTREACHED(); 112 FROM_HERE,
113 bound_net_log.EndEvent(net::NetLog::TYPE_FILE_STREAM_OPEN); 113 base::Bind(&Context::OnCloseCompleted,
114 } 114 base::Unretained(this), callback));
115 115 } else {
116 // Closes a file with CloseFile() and signals the completion. 116 const bool posted = base::WorkerPool::PostTaskAndReply(
117 void CloseFileAndSignal(base::PlatformFile* file, 117 FROM_HERE,
118 base::WaitableEvent* on_io_complete, 118 base::Bind(&Context::CloseFileImpl,
119 const net::BoundNetLog& bound_net_log) { 119 base::Unretained(this)),
120 CloseFile(*file, bound_net_log); 120 base::Bind(&Context::OnCloseCompleted,
121 *file = base::kInvalidPlatformFileValue; 121 base::Unretained(this), callback),
122 on_io_complete->Signal(); 122 true /* task_is_slow */);
123 } 123 DCHECK(posted);
124 124
125 // Adjusts the position from where the data is read. 125 async_in_progress_ = true;
126 void SeekFile(base::PlatformFile file, 126 }
127 Whence whence, 127 }
128 int64 offset, 128
129 int64* result, 129 void FileStream::Context::CloseSync() {
130 bool record_uma, 130 DCHECK(!async_in_progress_);
131 const net::BoundNetLog& bound_net_log) { 131 bound_net_log_.AddEvent(net::NetLog::TYPE_FILE_STREAM_CLOSE);
132 off_t res = lseek(file, static_cast<off_t>(offset), 132 if (file_ != base::kInvalidPlatformFileValue) {
133 static_cast<int>(whence)); 133 CloseFileImpl();
134 if (res == static_cast<off_t>(-1)) { 134 bound_net_log_.EndEvent(net::NetLog::TYPE_FILE_STREAM_OPEN);
135 *result = RecordAndMapError(errno, 135 }
136 FILE_ERROR_SOURCE_SEEK, 136 }
137 record_uma, 137
138 bound_net_log); 138 void FileStream::Context::SeekAsync(Whence whence,
139 return; 139 int64 offset,
140 } 140 const Int64CompletionCallback& callback) {
141 *result = res; 141 DCHECK(!async_in_progress_);
142 } 142
143 143 const bool posted = base::PostTaskAndReplyWithResult(
144 // Seeks a file by calling SeekSync() and signals the completion. 144 base::WorkerPool::GetTaskRunner(true /* task is slow */),
145 void SeekFileAndSignal(base::PlatformFile file, 145 FROM_HERE,
146 Whence whence, 146 base::Bind(&Context::SeekFileImpl,
147 int64 offset, 147 base::Unretained(this), whence, offset),
148 int64* result, 148 base::Bind(&Context::OnIOCompleted<int64>,
149 bool record_uma, 149 base::Unretained(this), callback, FILE_ERROR_SOURCE_SEEK));
150 base::WaitableEvent* on_io_complete, 150 DCHECK(posted);
151 const net::BoundNetLog& bound_net_log) { 151
152 SeekFile(file, whence, offset, result, record_uma, bound_net_log); 152 async_in_progress_ = true;
153 on_io_complete->Signal(); 153 }
154 } 154
155 155 int64 FileStream::Context::SeekSync(Whence whence, int64 offset) {
156 // ReadFile() is a simple wrapper around read() that handles EINTR signals and 156 off_t result = SeekFileImpl(whence, offset);
157 // calls MapSystemError() to map errno to net error codes. 157 CheckForIOError(&result, FILE_ERROR_SOURCE_SEEK);
158 void ReadFile(base::PlatformFile file, 158 return result;
159 char* buf, 159 }
160 int buf_len, 160
161 bool record_uma, 161 int64 FileStream::Context::GetFileSize() const {
162 int* result, 162 struct stat info;
163 const net::BoundNetLog& bound_net_log) { 163 if (fstat(file_, &info) != 0)
164 base::ThreadRestrictions::AssertIOAllowed(); 164 return RecordAndMapError(errno, FILE_ERROR_SOURCE_GET_SIZE);
165 // read(..., 0) returns 0 to indicate end-of-file. 165
166 166 return static_cast<int64>(info.st_size);
167 // Loop in the case of getting interrupted by a signal. 167 }
168 ssize_t res = HANDLE_EINTR(read(file, buf, static_cast<size_t>(buf_len))); 168
169 if (res == -1) { 169 int FileStream::Context::ReadAsync(IOBuffer* in_buf,
170 res = RecordAndMapError(errno, FILE_ERROR_SOURCE_READ, 170 int buf_len,
171 record_uma, bound_net_log); 171 const CompletionCallback& callback) {
172 } 172 DCHECK(!async_in_progress_);
173 *result = res; 173
174 } 174 scoped_refptr<IOBuffer> buf = in_buf;
175 175 const bool posted = base::PostTaskAndReplyWithResult(
176 // Reads a file using ReadFile() and signals the completion. 176 base::WorkerPool::GetTaskRunner(true /* task is slow */),
177 void ReadFileAndSignal(base::PlatformFile file, 177 FROM_HERE,
178 scoped_refptr<IOBuffer> buf, 178 base::Bind(&Context::ReadFileImpl,
179 int buf_len, 179 base::Unretained(this), buf, buf_len),
180 bool record_uma, 180 base::Bind(&Context::OnIOCompleted<int>,
181 int* result, 181 base::Unretained(this), callback, FILE_ERROR_SOURCE_READ));
182 base::WaitableEvent* on_io_complete, 182 DCHECK(posted);
183 const net::BoundNetLog& bound_net_log) { 183
184 ReadFile(file, buf->data(), buf_len, record_uma, result, bound_net_log); 184 async_in_progress_ = true;
185 on_io_complete->Signal(); 185 return ERR_IO_PENDING;
186 } 186 }
187 187
188 // WriteFile() is a simple wrapper around write() that handles EINTR signals and 188 int FileStream::Context::ReadSync(char* in_buf, int buf_len) {
189 // calls MapSystemError() to map errno to net error codes. It tries to write to 189 scoped_refptr<IOBuffer> buf = new WrappedIOBuffer(in_buf);
190 // completion. 190 int result = ReadFileImpl(buf, buf_len);
191 void WriteFile(base::PlatformFile file, 191 CheckForIOError(&result, FILE_ERROR_SOURCE_READ);
192 const char* buf, 192 return result;
193 int buf_len, 193 }
194 bool record_uma, 194
195 int* result, 195 int FileStream::Context::WriteAsync(IOBuffer* in_buf,
196 const net::BoundNetLog& bound_net_log) { 196 int buf_len,
197 base::ThreadRestrictions::AssertIOAllowed(); 197 const CompletionCallback& callback) {
198 198 DCHECK(!async_in_progress_);
199 ssize_t res = HANDLE_EINTR(write(file, buf, buf_len)); 199
200 if (res == -1) { 200 scoped_refptr<IOBuffer> buf = in_buf;
201 res = RecordAndMapError(errno, FILE_ERROR_SOURCE_WRITE, record_uma, 201 const bool posted = base::PostTaskAndReplyWithResult(
202 bound_net_log); 202 base::WorkerPool::GetTaskRunner(true /* task is slow */),
203 } 203 FROM_HERE,
204 *result = res; 204 base::Bind(&Context::WriteFileImpl,
205 } 205 base::Unretained(this), buf, buf_len),
206 206 base::Bind(&Context::OnIOCompleted<int>,
207 // Writes a file using WriteFile() and signals the completion. 207 base::Unretained(this), callback, FILE_ERROR_SOURCE_WRITE));
208 void WriteFileAndSignal(base::PlatformFile file, 208 DCHECK(posted);
209 scoped_refptr<IOBuffer> buf, 209
210 int buf_len, 210 async_in_progress_ = true;
211 bool record_uma, 211 return ERR_IO_PENDING;
212 int* result, 212 }
213 base::WaitableEvent* on_io_complete, 213
214 const net::BoundNetLog& bound_net_log) { 214 int FileStream::Context::WriteSync(const char* in_buf, int buf_len) {
215 WriteFile(file, buf->data(), buf_len, record_uma, result, bound_net_log); 215 scoped_refptr<IOBuffer> buf = new WrappedIOBuffer(in_buf);
216 on_io_complete->Signal(); 216 int result = WriteFileImpl(buf, buf_len);
217 } 217 CheckForIOError(&result, FILE_ERROR_SOURCE_WRITE);
218 218 return result;
219 // FlushFile() is a simple wrapper around fsync() that handles EINTR signals and 219 }
220 // calls MapSystemError() to map errno to net error codes. It tries to flush to 220
221 // completion. 221 int FileStream::Context::Flush() {
222 int FlushFile(base::PlatformFile file, 222 ssize_t res = HANDLE_EINTR(fsync(file_));
223 bool record_uma, 223 if (res == -1)
224 const net::BoundNetLog& bound_net_log) { 224 res = RecordAndMapError(errno, FILE_ERROR_SOURCE_FLUSH);
225 base::ThreadRestrictions::AssertIOAllowed();
226 ssize_t res = HANDLE_EINTR(fsync(file));
227 if (res == -1) {
228 res = RecordAndMapError(errno, FILE_ERROR_SOURCE_FLUSH, record_uma,
229 bound_net_log);
230 }
231 return res; 225 return res;
232 } 226 }
233 227
234 // Called when Read(), Write() or Seek() is completed. 228 int FileStream::Context::Truncate(int64 bytes) {
235 // |result| contains the result or a network error code.
236 template <typename R>
237 void OnIOComplete(const base::WeakPtr<FileStreamPosix>& stream,
238 const base::Callback<void(R)>& callback,
239 R* result) {
240 if (!stream.get())
241 return;
242
243 // Reset this before Run() as Run() may issue a new async operation.
244 stream->ResetOnIOComplete();
245 callback.Run(*result);
246 }
247
248 } // namespace
249
250 // FileStreamPosix ------------------------------------------------------------
251
252 FileStreamPosix::FileStreamPosix(net::NetLog* net_log)
253 : file_(base::kInvalidPlatformFileValue),
254 open_flags_(0),
255 auto_closed_(true),
256 record_uma_(false),
257 bound_net_log_(net::BoundNetLog::Make(net_log,
258 net::NetLog::SOURCE_FILESTREAM)),
259 weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
260 bound_net_log_.BeginEvent(net::NetLog::TYPE_FILE_STREAM_ALIVE);
261 }
262
263 FileStreamPosix::FileStreamPosix(
264 base::PlatformFile file, int flags, net::NetLog* net_log)
265 : file_(file),
266 open_flags_(flags),
267 auto_closed_(false),
268 record_uma_(false),
269 bound_net_log_(net::BoundNetLog::Make(net_log,
270 net::NetLog::SOURCE_FILESTREAM)),
271 weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
272 bound_net_log_.BeginEvent(net::NetLog::TYPE_FILE_STREAM_ALIVE);
273 }
274
275 FileStreamPosix::~FileStreamPosix() {
276 if (open_flags_ & base::PLATFORM_FILE_ASYNC) {
277 // Block until the last open/close/read/write operation is complete.
278 // TODO(satorux): Ideally we should not block. crbug.com/115067
279 WaitForIOCompletion();
280 }
281
282 if (auto_closed_) {
283 if (open_flags_ & base::PLATFORM_FILE_ASYNC) {
284 // Close the file in the background.
285 if (IsOpen()) {
286 const bool posted = base::WorkerPool::PostTask(
287 FROM_HERE,
288 base::Bind(&CloseFile, file_, bound_net_log_),
289 true /* task_is_slow */);
290 DCHECK(posted);
291 }
292 } else {
293 CloseSync();
294 }
295 }
296
297 bound_net_log_.EndEvent(net::NetLog::TYPE_FILE_STREAM_ALIVE);
298 }
299
300 void FileStreamPosix::Close(const CompletionCallback& callback) {
301 DCHECK(open_flags_ & base::PLATFORM_FILE_ASYNC);
302
303 DCHECK(!weak_ptr_factory_.HasWeakPtrs());
304 DCHECK(!on_io_complete_.get());
305 on_io_complete_.reset(new base::WaitableEvent(
306 false /* manual_reset */, false /* initially_signaled */));
307
308 // Passing &file_ to a thread pool looks unsafe but it's safe here as the
309 // destructor ensures that the close operation is complete with
310 // WaitForIOCompletion(). See also the destructor.
311 const bool posted = base::WorkerPool::PostTaskAndReply(
312 FROM_HERE,
313 base::Bind(&CloseFileAndSignal, &file_, on_io_complete_.get(),
314 bound_net_log_),
315 base::Bind(&FileStreamPosix::OnClosed,
316 weak_ptr_factory_.GetWeakPtr(),
317 callback),
318 true /* task_is_slow */);
319
320 DCHECK(posted);
321 }
322
323 void FileStreamPosix::CloseSync() {
324 // TODO(satorux): Replace the following async stuff with a
325 // DCHECK(open_flags & ASYNC) once once all async clients are migrated to
326 // use Close(). crbug.com/114783
327
328 // Abort any existing asynchronous operations.
329 weak_ptr_factory_.InvalidateWeakPtrs();
330 // Block until the last open/read/write operation is complete.
331 // TODO(satorux): Ideally we should not block. crbug.com/115067
332 WaitForIOCompletion();
333
334 CloseFile(file_, bound_net_log_);
335 file_ = base::kInvalidPlatformFileValue;
336 }
337
338 int FileStreamPosix::Open(const FilePath& path, int open_flags,
339 const CompletionCallback& callback) {
340 if (IsOpen()) {
341 DLOG(FATAL) << "File is already open!";
342 return ERR_UNEXPECTED;
343 }
344
345 open_flags_ = open_flags;
346 DCHECK(open_flags_ & base::PLATFORM_FILE_ASYNC);
347
348 DCHECK(!weak_ptr_factory_.HasWeakPtrs());
349 DCHECK(!on_io_complete_.get());
350 on_io_complete_.reset(new base::WaitableEvent(
351 false /* manual_reset */, false /* initially_signaled */));
352
353 // Passing &file_ to a thread pool looks unsafe but it's safe here as the
354 // destructor ensures that the open operation is complete with
355 // WaitForIOCompletion(). See also the destructor.
356 int* result = new int(OK);
357 const bool posted = base::WorkerPool::PostTaskAndReply(
358 FROM_HERE,
359 base::Bind(&OpenFileAndSignal,
360 path, open_flags, record_uma_, &file_, result,
361 on_io_complete_.get(), bound_net_log_),
362 base::Bind(&OnIOComplete<int>, weak_ptr_factory_.GetWeakPtr(),
363 callback, base::Owned(result)),
364 true /* task_is_slow */);
365 DCHECK(posted);
366 return ERR_IO_PENDING;
367 }
368
369 int FileStreamPosix::OpenSync(const FilePath& path, int open_flags) {
370 if (IsOpen()) {
371 DLOG(FATAL) << "File is already open!";
372 return ERR_UNEXPECTED;
373 }
374
375 open_flags_ = open_flags;
376 // TODO(satorux): Put a DCHECK once once all async clients are migrated
377 // to use Open(). crbug.com/114783
378 //
379 // DCHECK(!(open_flags_ & base::PLATFORM_FILE_ASYNC));
380
381 int result = OK;
382 OpenFile(path, open_flags_, record_uma_, &file_, &result, bound_net_log_);
383 return result;
384 }
385
386 bool FileStreamPosix::IsOpen() const {
387 return file_ != base::kInvalidPlatformFileValue;
388 }
389
390 int FileStreamPosix::Seek(Whence whence, int64 offset,
391 const Int64CompletionCallback& callback) {
392 if (!IsOpen())
393 return ERR_UNEXPECTED;
394
395 // Make sure we're async and we have no other in-flight async operations.
396 DCHECK(open_flags_ & base::PLATFORM_FILE_ASYNC);
397 DCHECK(!weak_ptr_factory_.HasWeakPtrs());
398 DCHECK(!on_io_complete_.get());
399
400 on_io_complete_.reset(new base::WaitableEvent(
401 false /* manual_reset */, false /* initially_signaled */));
402
403 int64* result = new int64(-1);
404 const bool posted = base::WorkerPool::PostTaskAndReply(
405 FROM_HERE,
406 base::Bind(&SeekFileAndSignal, file_, whence, offset, result,
407 record_uma_, on_io_complete_.get(), bound_net_log_),
408 base::Bind(&OnIOComplete<int64>,
409 weak_ptr_factory_.GetWeakPtr(),
410 callback, base::Owned(result)),
411 true /* task is slow */);
412 DCHECK(posted);
413 return ERR_IO_PENDING;
414 }
415
416 int64 FileStreamPosix::SeekSync(Whence whence, int64 offset) {
417 base::ThreadRestrictions::AssertIOAllowed();
418
419 if (!IsOpen())
420 return ERR_UNEXPECTED;
421
422 // If we're in async, make sure we don't have a request in flight.
423 DCHECK(!(open_flags_ & base::PLATFORM_FILE_ASYNC) ||
424 !on_io_complete_.get());
425
426 off_t result = -1;
427 SeekFile(file_, whence, offset, &result, record_uma_, bound_net_log_);
428 return result;
429 }
430
431 int64 FileStreamPosix::Available() {
432 base::ThreadRestrictions::AssertIOAllowed();
433
434 if (!IsOpen())
435 return ERR_UNEXPECTED;
436
437 int64 cur_pos = SeekSync(FROM_CURRENT, 0);
438 if (cur_pos < 0)
439 return cur_pos;
440
441 struct stat info;
442 if (fstat(file_, &info) != 0) {
443 return RecordAndMapError(errno,
444 FILE_ERROR_SOURCE_GET_SIZE,
445 record_uma_,
446 bound_net_log_);
447 }
448
449 int64 size = static_cast<int64>(info.st_size);
450 DCHECK_GT(size, cur_pos);
451
452 return size - cur_pos;
453 }
454
455 int FileStreamPosix::Read(
456 IOBuffer* in_buf, int buf_len, const CompletionCallback& callback) {
457 if (!IsOpen())
458 return ERR_UNEXPECTED;
459
460 // read(..., 0) will return 0, which indicates end-of-file.
461 DCHECK_GT(buf_len, 0);
462 DCHECK(open_flags_ & base::PLATFORM_FILE_READ);
463 DCHECK(open_flags_ & base::PLATFORM_FILE_ASYNC);
464
465 // Make sure we don't have a request in flight.
466 DCHECK(!weak_ptr_factory_.HasWeakPtrs());
467 DCHECK(!on_io_complete_.get());
468
469 on_io_complete_.reset(new base::WaitableEvent(
470 false /* manual_reset */, false /* initially_signaled */));
471
472 int* result = new int(OK);
473 scoped_refptr<IOBuffer> buf = in_buf;
474 const bool posted = base::WorkerPool::PostTaskAndReply(
475 FROM_HERE,
476 base::Bind(&ReadFileAndSignal, file_, buf, buf_len,
477 record_uma_, result, on_io_complete_.get(), bound_net_log_),
478 base::Bind(&OnIOComplete<int>,
479 weak_ptr_factory_.GetWeakPtr(),
480 callback, base::Owned(result)),
481 true /* task is slow */);
482 DCHECK(posted);
483 return ERR_IO_PENDING;
484 }
485
486 int FileStreamPosix::ReadSync(char* buf, int buf_len) {
487 if (!IsOpen())
488 return ERR_UNEXPECTED;
489
490 DCHECK(!(open_flags_ & base::PLATFORM_FILE_ASYNC));
491 // read(..., 0) will return 0, which indicates end-of-file.
492 DCHECK_GT(buf_len, 0);
493 DCHECK(open_flags_ & base::PLATFORM_FILE_READ);
494
495 int result = OK;
496 ReadFile(file_, buf, buf_len, record_uma_, &result, bound_net_log_);
497 return result;
498 }
499
500 int FileStreamPosix::ReadUntilComplete(char *buf, int buf_len) {
501 int to_read = buf_len;
502 int bytes_total = 0;
503
504 do {
505 int bytes_read = ReadSync(buf, to_read);
506 if (bytes_read <= 0) {
507 if (bytes_total == 0)
508 return bytes_read;
509
510 return bytes_total;
511 }
512
513 bytes_total += bytes_read;
514 buf += bytes_read;
515 to_read -= bytes_read;
516 } while (bytes_total < buf_len);
517
518 return bytes_total;
519 }
520
521 int FileStreamPosix::Write(
522 IOBuffer* in_buf, int buf_len, const CompletionCallback& callback) {
523 if (!IsOpen())
524 return ERR_UNEXPECTED;
525
526 DCHECK(open_flags_ & base::PLATFORM_FILE_ASYNC);
527 DCHECK(open_flags_ & base::PLATFORM_FILE_WRITE);
528 // write(..., 0) will return 0, which indicates end-of-file.
529 DCHECK_GT(buf_len, 0);
530
531 // Make sure we don't have a request in flight.
532 DCHECK(!weak_ptr_factory_.HasWeakPtrs());
533 DCHECK(!on_io_complete_.get());
534 on_io_complete_.reset(new base::WaitableEvent(
535 false /* manual_reset */, false /* initially_signaled */));
536
537 int* result = new int(OK);
538 scoped_refptr<IOBuffer> buf = in_buf;
539 const bool posted = base::WorkerPool::PostTaskAndReply(
540 FROM_HERE,
541 base::Bind(&WriteFileAndSignal, file_, buf, buf_len,
542 record_uma_, result, on_io_complete_.get(), bound_net_log_),
543 base::Bind(&OnIOComplete<int>,
544 weak_ptr_factory_.GetWeakPtr(),
545 callback, base::Owned(result)),
546 true /* task is slow */);
547 DCHECK(posted);
548 return ERR_IO_PENDING;
549 }
550
551 int FileStreamPosix::WriteSync(
552 const char* buf, int buf_len) {
553 if (!IsOpen())
554 return ERR_UNEXPECTED;
555
556 DCHECK(!(open_flags_ & base::PLATFORM_FILE_ASYNC));
557 DCHECK(open_flags_ & base::PLATFORM_FILE_WRITE);
558 // write(..., 0) will return 0, which indicates end-of-file.
559 DCHECK_GT(buf_len, 0);
560
561 int result = OK;
562 WriteFile(file_, buf, buf_len, record_uma_, &result, bound_net_log_);
563 return result;
564 }
565
566 int64 FileStreamPosix::Truncate(int64 bytes) {
567 base::ThreadRestrictions::AssertIOAllowed();
568
569 if (!IsOpen())
570 return ERR_UNEXPECTED;
571
572 // We'd better be open for writing.
573 DCHECK(open_flags_ & base::PLATFORM_FILE_WRITE);
574
575 // Seek to the position to truncate from.
576 int64 seek_position = SeekSync(FROM_BEGIN, bytes);
577 if (seek_position != bytes)
578 return ERR_UNEXPECTED;
579
580 // And truncate the file.
581 int result = ftruncate(file_, bytes); 229 int result = ftruncate(file_, bytes);
582 if (result == 0) 230 if (result == 0)
583 return seek_position; 231 return bytes;
584 232
585 return RecordAndMapError(errno, 233 return RecordAndMapError(errno, FILE_ERROR_SOURCE_SET_EOF);
586 FILE_ERROR_SOURCE_SET_EOF, 234 }
587 record_uma_, 235
588 bound_net_log_); 236 int FileStream::Context::RecordAndMapError(int error,
589 } 237 FileErrorSource source) const {
590 238 // The following check is against incorrect use or bug. File descriptor
591 int FileStreamPosix::Flush() { 239 // shouldn't ever be closed outside of FileStream while it still tries to do
592 if (!IsOpen()) 240 // something with it.
593 return ERR_UNEXPECTED; 241 DCHECK(error != EBADF);
594 242 net::Error net_error = MapSystemError(error);
595 return FlushFile(file_, record_uma_, bound_net_log_); 243
596 } 244 if (!orphaned_) {
597 245 bound_net_log_.AddEvent(net::NetLog::TYPE_FILE_STREAM_ERROR,
598 void FileStreamPosix::EnableErrorStatistics() { 246 base::Bind(&NetLogFileStreamErrorCallback,
599 record_uma_ = true; 247 source, error, net_error));
600 } 248 }
601 249 RecordFileError(error, source, record_uma_);
602 void FileStreamPosix::SetBoundNetLogSource( 250 return net_error;
603 const net::BoundNetLog& owner_bound_net_log) { 251 }
604 if ((owner_bound_net_log.source().id == net::NetLog::Source::kInvalidId) && 252
605 (bound_net_log_.source().id == net::NetLog::Source::kInvalidId)) { 253 void FileStream::Context::BeginOpenEvent(const FilePath& path) {
606 // Both |BoundNetLog|s are invalid. 254 std::string file_name = path.AsUTF8Unsafe();
607 return; 255 bound_net_log_.BeginEvent(net::NetLog::TYPE_FILE_STREAM_OPEN,
608 } 256 NetLog::StringCallback("file_name", &file_name));
609 257 }
610 // Should never connect to itself. 258
611 DCHECK_NE(bound_net_log_.source().id, owner_bound_net_log.source().id); 259 int FileStream::Context::OpenFileImpl(const FilePath& path, int open_flags) {
612 260 file_ = base::CreatePlatformFile(path, open_flags, NULL, NULL);
613 bound_net_log_.AddEvent( 261 if (file_ == base::kInvalidPlatformFileValue)
614 net::NetLog::TYPE_FILE_STREAM_BOUND_TO_OWNER, 262 return errno;
615 owner_bound_net_log.source().ToEventParametersCallback()); 263
616 264 return OK;
617 owner_bound_net_log.AddEvent( 265 }
618 net::NetLog::TYPE_FILE_STREAM_SOURCE, 266
619 bound_net_log_.source().ToEventParametersCallback()); 267 void FileStream::Context::CheckForOpenError(int* result) {
620 } 268 if (file_ == base::kInvalidPlatformFileValue) {
621 269 bound_net_log_.EndEvent(net::NetLog::TYPE_FILE_STREAM_OPEN);
622 base::PlatformFile FileStreamPosix::GetPlatformFileForTesting() { 270 *result = RecordAndMapError(*result, FILE_ERROR_SOURCE_OPEN);
623 return file_; 271 }
624 } 272 }
625 273
626 void FileStreamPosix::ResetOnIOComplete() { 274 void FileStream::Context::OnOpenCompleted(const CompletionCallback& callback,
627 on_io_complete_.reset(); 275 int result) {
628 weak_ptr_factory_.InvalidateWeakPtrs(); 276 CheckForOpenError(&result);
629 } 277 OnAsyncCompleted(callback, result);
630 278 }
631 void FileStreamPosix::OnClosed(const CompletionCallback& callback) { 279
280 void FileStream::Context::CloseFileImpl() {
281 if (!base::ClosePlatformFile(file_))
282 NOTREACHED();
632 file_ = base::kInvalidPlatformFileValue; 283 file_ = base::kInvalidPlatformFileValue;
633 284 }
634 // Reset this before Run() as Run() may issue a new async operation. 285
635 ResetOnIOComplete(); 286 void FileStream::Context::OnCloseCompleted(const CompletionCallback& callback) {
636 callback.Run(OK); 287 if (!orphaned_) {
637 } 288 bound_net_log_.EndEvent(net::NetLog::TYPE_FILE_STREAM_OPEN);
638 289 // Reset this before Run() as Run() may issue a new async operation.
639 void FileStreamPosix::WaitForIOCompletion() { 290 async_in_progress_ = false;
640 // http://crbug.com/115067 291 callback.Run(OK);
641 base::ThreadRestrictions::ScopedAllowWait allow_wait; 292 } else {
642 if (on_io_complete_.get()) { 293 delete this;
643 on_io_complete_->Wait(); 294 }
644 on_io_complete_.reset(); 295 }
645 } 296
297 int64 FileStream::Context::SeekFileImpl(Whence whence, int64 offset) {
298 base::ThreadRestrictions::AssertIOAllowed();
299
300 off_t res = lseek(file_, static_cast<off_t>(offset),
301 static_cast<int>(whence));
302 if (res == static_cast<off_t>(-1))
303 return errno;
304
305 return res;
306 }
307
308 int FileStream::Context::ReadFileImpl(scoped_refptr<IOBuffer> buf,
309 int buf_len) {
310 base::ThreadRestrictions::AssertIOAllowed();
311
312 // Loop in the case of getting interrupted by a signal.
313 ssize_t res = HANDLE_EINTR(read(file_, buf->data(),
314 static_cast<size_t>(buf_len)));
315 if (res == -1)
316 return errno;
317
318 return res;
319 }
320
321 int FileStream::Context::WriteFileImpl(scoped_refptr<IOBuffer> buf,
322 int buf_len) {
323 base::ThreadRestrictions::AssertIOAllowed();
324
325 ssize_t res = HANDLE_EINTR(write(file_, buf->data(), buf_len));
326 if (res == -1)
327 return errno;
328
329 return res;
330 }
331
332 template <typename R>
333 void FileStream::Context::CheckForIOError(R* result, FileErrorSource source) {
334 if (*result < 0)
335 *result = RecordAndMapError(static_cast<int>(*result), source);
336 }
337
338 template <typename R>
339 void FileStream::Context::OnIOCompleted(const base::Callback<void(R)>& callback,
340 FileErrorSource source,
341 R result) {
342 CheckForIOError(&result, source);
343 OnAsyncCompleted(callback, result);
344 }
345
346 template <typename R>
347 void FileStream::Context::OnAsyncCompleted(
348 const base::Callback<void(R)>& callback,
349 R result) {
350 // Reset this before Run() as Run() may issue a new async operation. Also it
351 // should be reset before CloseAsync() because it shouldn't run if any async
352 // operation is in progress.
353 async_in_progress_ = false;
354 if (orphaned_)
355 CloseAsync(CompletionCallback());
356 else
357 callback.Run(result);
646 } 358 }
647 359
648 } // namespace net 360 } // namespace net
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698