1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/file_stream.h"
#include <windows.h>
#include "base/file_path.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/worker_pool.h"
#include "net/base/file_stream_metrics.h"
#include "net/base/file_stream_net_log_parameters.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
namespace net {
// Ensure that we can just use our Whence values directly.
COMPILE_ASSERT(FROM_BEGIN == FILE_BEGIN, bad_whence_begin);
COMPILE_ASSERT(FROM_CURRENT == FILE_CURRENT, bad_whence_current);
COMPILE_ASSERT(FROM_END == FILE_END, bad_whence_end);
static void SetOffset(OVERLAPPED* overlapped, const LARGE_INTEGER& offset) {
overlapped->Offset = offset.LowPart;
overlapped->OffsetHigh = offset.HighPart;
}
static void IncrementOffset(OVERLAPPED* overlapped, DWORD count) {
LARGE_INTEGER offset;
offset.LowPart = overlapped->Offset;
offset.HighPart = overlapped->OffsetHigh;
offset.QuadPart += static_cast<LONGLONG>(count);
SetOffset(overlapped, offset);
}
namespace {
int RecordAndMapError(int error,
FileErrorSource source,
bool record_uma,
const net::BoundNetLog& bound_net_log) {
net::Error net_error = MapSystemError(error);
bound_net_log.AddEvent(
net::NetLog::TYPE_FILE_STREAM_ERROR,
make_scoped_refptr(
new FileStreamErrorParameters(GetFileErrorSourceName(source),
error,
net_error)));
RecordFileError(error, source, record_uma);
return net_error;
}
// Opens a file with some network logging.
// The opened file and the result code are written to |file| and |result|.
void OpenFile(const FilePath& path,
int open_flags,
bool record_uma,
const net::BoundNetLog& bound_net_log,
base::PlatformFile* file,
int* result) {
bound_net_log.BeginEvent(
net::NetLog::TYPE_FILE_STREAM_OPEN,
make_scoped_refptr(
new net::NetLogStringParameter("file_name",
path.AsUTF8Unsafe())));
*file = base::CreatePlatformFile(path, open_flags, NULL, NULL);
if (*file == base::kInvalidPlatformFileValue) {
DWORD error = GetLastError();
LOG(WARNING) << "Failed to open file: " << error;
*result = RecordAndMapError(error,
FILE_ERROR_SOURCE_OPEN,
record_uma,
bound_net_log);
bound_net_log.EndEvent(net::NetLog::TYPE_FILE_STREAM_OPEN, NULL);
return;
}
}
// Closes a file with some network logging.
void CloseFile(base::PlatformFile file,
const net::BoundNetLog& bound_net_log) {
bound_net_log.AddEvent(net::NetLog::TYPE_FILE_STREAM_CLOSE, NULL);
if (file == base::kInvalidPlatformFileValue)
return;
CancelIo(file);
if (!base::ClosePlatformFile(file))
NOTREACHED();
bound_net_log.EndEvent(net::NetLog::TYPE_FILE_STREAM_OPEN, NULL);
}
} // namespace
// FileStreamWin::AsyncContext ----------------------------------------------
class FileStreamWin::AsyncContext : public MessageLoopForIO::IOHandler {
public:
explicit AsyncContext(const net::BoundNetLog& bound_net_log)
: context_(), is_closing_(false),
record_uma_(false), bound_net_log_(bound_net_log),
error_source_(FILE_ERROR_SOURCE_COUNT) {
context_.handler = this;
}
~AsyncContext();
void IOCompletionIsPending(const CompletionCallback& callback,
IOBuffer* buf);
OVERLAPPED* overlapped() { return &context_.overlapped; }
const CompletionCallback& callback() const { return callback_; }
void set_error_source(FileErrorSource source) { error_source_ = source; }
void EnableErrorStatistics() {
record_uma_ = true;
}
private:
virtual void OnIOCompleted(MessageLoopForIO::IOContext* context,
DWORD bytes_read, DWORD error) OVERRIDE;
MessageLoopForIO::IOContext context_;
CompletionCallback callback_;
scoped_refptr<IOBuffer> in_flight_buf_;
bool is_closing_;
bool record_uma_;
const net::BoundNetLog bound_net_log_;
FileErrorSource error_source_;
};
FileStreamWin::AsyncContext::~AsyncContext() {
is_closing_ = true;
bool waited = false;
base::TimeTicks start = base::TimeTicks::Now();
while (!callback_.is_null()) {
waited = true;
MessageLoopForIO::current()->WaitForIOCompletion(INFINITE, this);
}
if (waited) {
// We want to see if we block the message loop for too long.
UMA_HISTOGRAM_TIMES("AsyncIO.FileStreamClose",
base::TimeTicks::Now() - start);
}
}
void FileStreamWin::AsyncContext::IOCompletionIsPending(
const CompletionCallback& callback,
IOBuffer* buf) {
DCHECK(callback_.is_null());
callback_ = callback;
in_flight_buf_ = buf; // Hold until the async operation ends.
}
void FileStreamWin::AsyncContext::OnIOCompleted(
MessageLoopForIO::IOContext* context, DWORD bytes_read, DWORD error) {
DCHECK_EQ(&context_, context);
DCHECK(!callback_.is_null());
if (is_closing_) {
callback_.Reset();
in_flight_buf_ = NULL;
return;
}
int result = static_cast<int>(bytes_read);
if (error && error != ERROR_HANDLE_EOF) {
result = RecordAndMapError(error, error_source_, record_uma_,
bound_net_log_);
}
if (bytes_read)
IncrementOffset(&context->overlapped, bytes_read);
CompletionCallback temp_callback = callback_;
callback_.Reset();
scoped_refptr<IOBuffer> temp_buf = in_flight_buf_;
in_flight_buf_ = NULL;
temp_callback.Run(result);
}
// FileStream ------------------------------------------------------------
FileStreamWin::FileStreamWin(net::NetLog* net_log)
: file_(base::kInvalidPlatformFileValue),
open_flags_(0),
auto_closed_(true),
record_uma_(false),
bound_net_log_(net::BoundNetLog::Make(net_log,
net::NetLog::SOURCE_FILESTREAM)),
weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
bound_net_log_.BeginEvent(net::NetLog::TYPE_FILE_STREAM_ALIVE, NULL);
}
FileStreamWin::FileStreamWin(
base::PlatformFile file, int flags, net::NetLog* net_log)
: file_(file),
open_flags_(flags),
auto_closed_(false),
record_uma_(false),
bound_net_log_(net::BoundNetLog::Make(net_log,
net::NetLog::SOURCE_FILESTREAM)),
weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
bound_net_log_.BeginEvent(net::NetLog::TYPE_FILE_STREAM_ALIVE, NULL);
// If the file handle is opened with base::PLATFORM_FILE_ASYNC, we need to
// make sure we will perform asynchronous File IO to it.
if (flags & base::PLATFORM_FILE_ASYNC) {
async_context_.reset(new AsyncContext(bound_net_log_));
MessageLoopForIO::current()->RegisterIOHandler(file_,
async_context_.get());
}
}
FileStreamWin::~FileStreamWin() {
if (auto_closed_) {
if (async_context_.get()) {
// Block until the last read/write operation is complete, if needed.
// This is needed to close the file safely.
// TODO(satorux): Remove the blocking logic. crrev.com/115067
async_context_.reset();
// Close the file in the background.
const bool posted = base::WorkerPool::PostTask(
FROM_HERE,
base::Bind(&CloseFile, file_, bound_net_log_),
true /* task_is_slow */);
DCHECK(posted);
} else {
CloseSync();
}
}
bound_net_log_.EndEvent(net::NetLog::TYPE_FILE_STREAM_ALIVE, NULL);
}
void FileStreamWin::Close(const CompletionCallback& callback) {
DCHECK(callback_.is_null());
callback_ = callback;
// Make sure we don't have a request in flight. Unlike CloseSync(), don't
// abort existing asynchronous operations, as it'd block.
DCHECK(async_context_.get());
DCHECK(async_context_->callback().is_null());
const bool posted = base::WorkerPool::PostTaskAndReply(
FROM_HERE,
base::Bind(&CloseFile, file_, bound_net_log_),
base::Bind(&FileStreamWin::OnClosed, weak_ptr_factory_.GetWeakPtr()),
true /* task_is_slow */);
DCHECK(posted);
}
void FileStreamWin::CloseSync() {
// The logic here is similar to CloseFile() but async_context_.reset() is
// caled in this function.
bound_net_log_.AddEvent(net::NetLog::TYPE_FILE_STREAM_CLOSE, NULL);
if (file_ != base::kInvalidPlatformFileValue)
CancelIo(file_);
// TODO(satorux): Remove this once all async clients are migrated to use
// Close(). crbug.com/114783
async_context_.reset();
if (file_ != base::kInvalidPlatformFileValue) {
if (!base::ClosePlatformFile(file_))
NOTREACHED();
file_ = base::kInvalidPlatformFileValue;
bound_net_log_.EndEvent(net::NetLog::TYPE_FILE_STREAM_OPEN, NULL);
}
}
int FileStreamWin::Open(const FilePath& path, int open_flags,
const CompletionCallback& callback) {
if (IsOpen()) {
DLOG(FATAL) << "File is already open!";
return ERR_UNEXPECTED;
}
DCHECK(callback_.is_null());
callback_ = callback;
open_flags_ = open_flags;
DCHECK(open_flags_ & base::PLATFORM_FILE_ASYNC);
base::PlatformFile* file =
new base::PlatformFile(base::kInvalidPlatformFileValue);
int* result = new int(OK);
const bool posted = base::WorkerPool::PostTaskAndReply(
FROM_HERE,
base::Bind(&OpenFile, path, open_flags, record_uma_, bound_net_log_,
file, result),
base::Bind(&FileStreamWin::OnOpened,
weak_ptr_factory_.GetWeakPtr(),
base::Owned(file),
base::Owned(result)),
true /* task_is_slow */);
DCHECK(posted);
return ERR_IO_PENDING;
}
int FileStreamWin::OpenSync(const FilePath& path, int open_flags) {
if (IsOpen()) {
DLOG(FATAL) << "File is already open!";
return ERR_UNEXPECTED;
}
open_flags_ = open_flags;
int result = OK;
OpenFile(path, open_flags_, record_uma_, bound_net_log_, &file_, &result);
if (result != OK)
return result;
// TODO(satorux): Remove this once all async clients are migrated to use
// Open(). crbug.com/114783
if (open_flags_ & base::PLATFORM_FILE_ASYNC) {
async_context_.reset(new AsyncContext(bound_net_log_));
if (record_uma_)
async_context_->EnableErrorStatistics();
MessageLoopForIO::current()->RegisterIOHandler(file_,
async_context_.get());
}
return OK;
}
bool FileStreamWin::IsOpen() const {
return file_ != base::kInvalidPlatformFileValue;
}
int64 FileStreamWin::Seek(Whence whence, int64 offset) {
if (!IsOpen())
return ERR_UNEXPECTED;
DCHECK(!async_context_.get() || async_context_->callback().is_null());
LARGE_INTEGER distance, result;
distance.QuadPart = offset;
DWORD move_method = static_cast<DWORD>(whence);
if (!SetFilePointerEx(file_, distance, &result, move_method)) {
DWORD error = GetLastError();
LOG(WARNING) << "SetFilePointerEx failed: " << error;
return RecordAndMapError(error,
FILE_ERROR_SOURCE_SEEK,
record_uma_,
bound_net_log_);
}
if (async_context_.get()) {
async_context_->set_error_source(FILE_ERROR_SOURCE_SEEK);
SetOffset(async_context_->overlapped(), result);
}
return result.QuadPart;
}
int64 FileStreamWin::Available() {
base::ThreadRestrictions::AssertIOAllowed();
if (!IsOpen())
return ERR_UNEXPECTED;
int64 cur_pos = Seek(FROM_CURRENT, 0);
if (cur_pos < 0)
return cur_pos;
LARGE_INTEGER file_size;
if (!GetFileSizeEx(file_, &file_size)) {
DWORD error = GetLastError();
LOG(WARNING) << "GetFileSizeEx failed: " << error;
return RecordAndMapError(error,
FILE_ERROR_SOURCE_GET_SIZE,
record_uma_,
bound_net_log_);
}
return file_size.QuadPart - cur_pos;
}
int FileStreamWin::Read(
IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
DCHECK(async_context_.get());
if (!IsOpen())
return ERR_UNEXPECTED;
DCHECK(open_flags_ & base::PLATFORM_FILE_READ);
OVERLAPPED* overlapped = NULL;
DCHECK(!callback.is_null());
DCHECK(async_context_->callback().is_null());
overlapped = async_context_->overlapped();
async_context_->set_error_source(FILE_ERROR_SOURCE_READ);
int rv = 0;
DWORD bytes_read;
if (!ReadFile(file_, buf->data(), buf_len, &bytes_read, overlapped)) {
DWORD error = GetLastError();
if (error == ERROR_IO_PENDING) {
async_context_->IOCompletionIsPending(callback, buf);
rv = ERR_IO_PENDING;
} else if (error == ERROR_HANDLE_EOF) {
rv = 0; // Report EOF by returning 0 bytes read.
} else {
LOG(WARNING) << "ReadFile failed: " << error;
rv = RecordAndMapError(error,
FILE_ERROR_SOURCE_READ,
record_uma_,
bound_net_log_);
}
} else if (overlapped) {
async_context_->IOCompletionIsPending(callback, buf);
rv = ERR_IO_PENDING;
} else {
rv = static_cast<int>(bytes_read);
}
return rv;
}
int FileStreamWin::ReadSync(char* buf, int buf_len) {
DCHECK(!async_context_.get());
base::ThreadRestrictions::AssertIOAllowed();
if (!IsOpen())
return ERR_UNEXPECTED;
DCHECK(open_flags_ & base::PLATFORM_FILE_READ);
int rv = 0;
DWORD bytes_read;
if (!ReadFile(file_, buf, buf_len, &bytes_read, NULL)) {
DWORD error = GetLastError();
if (error == ERROR_HANDLE_EOF) {
rv = 0; // Report EOF by returning 0 bytes read.
} else {
LOG(WARNING) << "ReadFile failed: " << error;
rv = RecordAndMapError(error,
FILE_ERROR_SOURCE_READ,
record_uma_,
bound_net_log_);
}
} else {
rv = static_cast<int>(bytes_read);
}
return rv;
}
int FileStreamWin::ReadUntilComplete(char *buf, int buf_len) {
int to_read = buf_len;
int bytes_total = 0;
do {
int bytes_read = ReadSync(buf, to_read);
if (bytes_read <= 0) {
if (bytes_total == 0)
return bytes_read;
return bytes_total;
}
bytes_total += bytes_read;
buf += bytes_read;
to_read -= bytes_read;
} while (bytes_total < buf_len);
return bytes_total;
}
int FileStreamWin::Write(
IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
DCHECK(async_context_.get());
if (!IsOpen())
return ERR_UNEXPECTED;
DCHECK(open_flags_ & base::PLATFORM_FILE_WRITE);
OVERLAPPED* overlapped = NULL;
DCHECK(!callback.is_null());
DCHECK(async_context_->callback().is_null());
overlapped = async_context_->overlapped();
async_context_->set_error_source(FILE_ERROR_SOURCE_WRITE);
int rv = 0;
DWORD bytes_written = 0;
if (!WriteFile(file_, buf->data(), buf_len, &bytes_written, overlapped)) {
DWORD error = GetLastError();
if (error == ERROR_IO_PENDING) {
async_context_->IOCompletionIsPending(callback, buf);
rv = ERR_IO_PENDING;
} else {
LOG(WARNING) << "WriteFile failed: " << error;
rv = RecordAndMapError(error,
FILE_ERROR_SOURCE_WRITE,
record_uma_,
bound_net_log_);
}
} else if (overlapped) {
async_context_->IOCompletionIsPending(callback, buf);
rv = ERR_IO_PENDING;
} else {
rv = static_cast<int>(bytes_written);
}
return rv;
}
int FileStreamWin::WriteSync(
const char* buf, int buf_len) {
DCHECK(!async_context_.get());
base::ThreadRestrictions::AssertIOAllowed();
if (!IsOpen())
return ERR_UNEXPECTED;
DCHECK(open_flags_ & base::PLATFORM_FILE_WRITE);
int rv = 0;
DWORD bytes_written = 0;
if (!WriteFile(file_, buf, buf_len, &bytes_written, NULL)) {
DWORD error = GetLastError();
LOG(WARNING) << "WriteFile failed: " << error;
rv = RecordAndMapError(error,
FILE_ERROR_SOURCE_WRITE,
record_uma_,
bound_net_log_);
} else {
rv = static_cast<int>(bytes_written);
}
return rv;
}
int FileStreamWin::Flush() {
base::ThreadRestrictions::AssertIOAllowed();
if (!IsOpen())
return ERR_UNEXPECTED;
DCHECK(open_flags_ & base::PLATFORM_FILE_WRITE);
if (FlushFileBuffers(file_)) {
return OK;
}
return RecordAndMapError(GetLastError(),
FILE_ERROR_SOURCE_FLUSH,
record_uma_,
bound_net_log_);
}
int64 FileStreamWin::Truncate(int64 bytes) {
base::ThreadRestrictions::AssertIOAllowed();
if (!IsOpen())
return ERR_UNEXPECTED;
// We'd better be open for writing.
DCHECK(open_flags_ & base::PLATFORM_FILE_WRITE);
// Seek to the position to truncate from.
int64 seek_position = Seek(FROM_BEGIN, bytes);
if (seek_position != bytes)
return ERR_UNEXPECTED;
// And truncate the file.
BOOL result = SetEndOfFile(file_);
if (!result) {
DWORD error = GetLastError();
LOG(WARNING) << "SetEndOfFile failed: " << error;
return RecordAndMapError(error,
FILE_ERROR_SOURCE_SET_EOF,
record_uma_,
bound_net_log_);
}
// Success.
return seek_position;
}
void FileStreamWin::EnableErrorStatistics() {
record_uma_ = true;
if (async_context_.get())
async_context_->EnableErrorStatistics();
}
void FileStreamWin::SetBoundNetLogSource(
const net::BoundNetLog& owner_bound_net_log) {
if ((owner_bound_net_log.source().id == net::NetLog::Source::kInvalidId) &&
(bound_net_log_.source().id == net::NetLog::Source::kInvalidId)) {
// Both |BoundNetLog|s are invalid.
return;
}
// Should never connect to itself.
DCHECK_NE(bound_net_log_.source().id, owner_bound_net_log.source().id);
bound_net_log_.AddEvent(
net::NetLog::TYPE_FILE_STREAM_BOUND_TO_OWNER,
make_scoped_refptr(
new net::NetLogSourceParameter("source_dependency",
owner_bound_net_log.source())));
owner_bound_net_log.AddEvent(
net::NetLog::TYPE_FILE_STREAM_SOURCE,
make_scoped_refptr(
new net::NetLogSourceParameter("source_dependency",
bound_net_log_.source())));
}
base::PlatformFile FileStreamWin::GetPlatformFileForTesting() {
return file_;
}
void FileStreamWin::OnClosed() {
file_ = base::kInvalidPlatformFileValue;
CompletionCallback temp = callback_;
callback_.Reset();
temp.Run(OK);
}
void FileStreamWin::OnOpened(base::PlatformFile* file, int* result) {
file_ = *file;
if (*result == OK) {
async_context_.reset(new AsyncContext(bound_net_log_));
if (record_uma_)
async_context_->EnableErrorStatistics();
MessageLoopForIO::current()->RegisterIOHandler(file_,
async_context_.get());
}
CompletionCallback temp = callback_;
callback_.Reset();
temp.Run(*result);
}
} // namespace net
|