-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy patheventhandler_win.cc
1501 lines (1344 loc) · 46.1 KB
/
eventhandler_win.cc
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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "platform/globals.h"
#if defined(DART_HOST_OS_WINDOWS)
#include "bin/eventhandler.h"
#include "bin/eventhandler_win.h"
#include <fcntl.h> // NOLINT
#include <io.h> // NOLINT
#include <mswsock.h> // NOLINT
#include <winsock2.h> // NOLINT
#include <ws2tcpip.h> // NOLINT
#include <utility>
#include "bin/builtin.h"
#include "bin/dartutils.h"
#include "bin/lockers.h"
#include "bin/process.h"
#include "bin/socket.h"
#include "bin/thread.h"
#include "bin/utils.h"
#include "platform/syslog.h"
#include "platform/utils.h"
namespace dart {
namespace bin {
// kBufferSize must be >= kMaxUDPPackageLength so that a complete UDP packet
// can fit in the buffer.
static constexpr int kBufferSize = 64 * 1024;
static constexpr int kStdOverlappedBufferSize = 16 * 1024;
static constexpr int kMaxUDPPackageLength = 64 * 1024;
// For AcceptEx there needs to be buffer storage for address
// information for two addresses (local and remote address). The
// AcceptEx documentation says: "This value must be at least 16
// bytes more than the maximum address length for the transport
// protocol in use."
static constexpr int kAcceptExAddressAdditionalBytes = 16;
static constexpr int kAcceptExAddressStorageSize =
sizeof(SOCKADDR_STORAGE) + kAcceptExAddressAdditionalBytes;
static constexpr intptr_t kOutEventMask = 1 << kOutEvent;
static constexpr intptr_t kInEventMask = 1 << kInEvent;
static bool DispatchEventIfEnabled(Handle* handle, intptr_t event_mask) {
if ((handle->Mask() & event_mask) != 0) {
DartUtils::PostInt32(handle->NextNotifyDartPort(event_mask), event_mask);
return true;
}
return false;
}
static bool DispatchOutEventIfEnabled(Handle* handle) {
return DispatchEventIfEnabled(handle, kOutEventMask);
}
static bool DispatchInEventIfEnabled(Handle* handle) {
return DispatchEventIfEnabled(handle, kInEventMask);
}
OverlappedBuffer::OverlappedBuffer(Handle* handle,
int buffer_size,
Operation operation)
: buflen_(buffer_size), operation_(operation), handle_(handle) {
memset(GetBufferStart(), 0, GetBufferSize());
if (operation == kRecvFrom) {
// Reserve part of the buffer for the length of source sockaddr
// and source sockaddr.
const int kAdditionalSize =
sizeof(struct sockaddr_storage) + sizeof(socklen_t);
ASSERT(buflen_ > kAdditionalSize);
buflen_ -= kAdditionalSize;
from_len_addr_ =
reinterpret_cast<socklen_t*>(GetBufferStart() + GetBufferSize());
*from_len_addr_ = sizeof(struct sockaddr_storage);
from_ = reinterpret_cast<struct sockaddr*>(from_len_addr_ + 1);
} else {
from_len_addr_ = nullptr;
from_ = nullptr;
}
index_ = 0;
data_length_ = 0;
if (operation_ == kAccept) {
client_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
}
// Retain handle for the duration of the operation.
handle->Retain();
}
OverlappedBuffer::~OverlappedBuffer() {
// If handle was not detached from the buffer release the reference
// we were holding to it.
if (handle_ != nullptr) {
handle_->Release();
}
if (client_ != INVALID_SOCKET) {
closesocket(client_);
}
}
std::unique_ptr<OverlappedBuffer> OverlappedBuffer::AllocateBuffer(
Handle* handle,
int buffer_size,
Operation operation) {
OverlappedBuffer* buffer =
new (buffer_size) OverlappedBuffer(handle, buffer_size, operation);
return std::unique_ptr<OverlappedBuffer>{buffer};
}
std::unique_ptr<OverlappedBuffer> OverlappedBuffer::AllocateAcceptBuffer(
Handle* handle) {
return AllocateBuffer(handle, 2 * kAcceptExAddressStorageSize, kAccept);
}
std::unique_ptr<OverlappedBuffer> OverlappedBuffer::AllocateReadBuffer(
Handle* handle,
int buffer_size) {
return AllocateBuffer(handle, buffer_size, kRead);
}
std::unique_ptr<OverlappedBuffer> OverlappedBuffer::AllocateRecvFromBuffer(
Handle* handle,
int buffer_size) {
// For calling recvfrom additional buffer space is needed for the source
// address information.
buffer_size += sizeof(socklen_t) + sizeof(struct sockaddr_storage);
return AllocateBuffer(handle, buffer_size, kRecvFrom);
}
std::unique_ptr<OverlappedBuffer> OverlappedBuffer::AllocateWriteBuffer(
Handle* handle,
int buffer_size) {
return AllocateBuffer(handle, buffer_size, kWrite);
}
std::unique_ptr<OverlappedBuffer> OverlappedBuffer::AllocateSendToBuffer(
Handle* handle,
int buffer_size) {
return AllocateBuffer(handle, buffer_size, kSendTo);
}
std::unique_ptr<OverlappedBuffer> OverlappedBuffer::AllocateDisconnectBuffer(
Handle* handle) {
return AllocateBuffer(handle, 0, kDisconnect);
}
std::unique_ptr<OverlappedBuffer> OverlappedBuffer::AllocateConnectBuffer(
Handle* handle) {
return AllocateBuffer(handle, 0, kConnect);
}
OverlappedBuffer* OverlappedBuffer::GetFromOverlapped(OVERLAPPED* overlapped) {
OverlappedBuffer* buffer =
CONTAINING_RECORD(overlapped, OverlappedBuffer, overlapped_);
return buffer;
}
int OverlappedBuffer::Read(void* buffer, int num_bytes) {
if (num_bytes > GetRemainingLength()) {
num_bytes = GetRemainingLength();
}
memmove(buffer, GetBufferStart() + index_, num_bytes);
index_ += num_bytes;
return num_bytes;
}
int OverlappedBuffer::Write(const void* buffer, int num_bytes) {
ASSERT(num_bytes == buflen_);
memmove(GetBufferStart(), buffer, num_bytes);
data_length_ = num_bytes;
return num_bytes;
}
int OverlappedBuffer::GetRemainingLength() {
ASSERT(operation_ == kRead || operation_ == kRecvFrom);
return data_length_ - index_;
}
Handle::Handle(intptr_t handle,
Type type,
Handle::SupportsOverlappedIO supports_overlapped_io /* = kYes */)
: ReferenceCounted(),
DescriptorInfoBase(handle),
monitor_(),
type_(type),
handle_(reinterpret_cast<HANDLE>(handle)),
data_ready_() {
if (supports_overlapped_io == SupportsOverlappedIO::kYes) {
EventHandler::delegate()->AssociateWithCompletionPort(this);
} else {
flags_ |= 1 << kDoesNotSupportOverlappedIO;
}
}
Handle::~Handle() {}
void Handle::Close() {
MonitorLocker ml(&monitor_);
CloseLocked(&ml);
}
void Handle::CloseLocked(MonitorLocker* ml) {
if (!supports_overlapped_io()) {
// If the handle uses synchronous I/O (e.g. stdin), cancel any pending
// operation before closing the handle, so the read thread is not blocked.
BOOL result = CancelIoEx(handle_, nullptr);
ASSERT(result || (GetLastError() == ERROR_NOT_FOUND));
}
if (!IsClosing()) {
// Close the socket and set the closing state. This close method can be
// called again if this socket has pending IO operations in flight.
MarkClosing();
// Perform handle type specific closing.
DoCloseLocked(ml);
}
ASSERT(IsHandleClosed());
}
void Handle::DoCloseLocked(MonitorLocker* ml) {
if (!IsHandleClosed()) {
CloseHandle(handle_);
handle_ = INVALID_HANDLE_VALUE;
}
}
bool Handle::HasPendingRead() {
return pending_read_ != nullptr;
}
bool Handle::HasPendingWrite() {
return pending_write_ != nullptr;
}
void Handle::WaitForReadThreadStarted() {
MonitorLocker ml(&monitor_);
while (read_thread_starting_) {
ml.Wait();
}
}
void Handle::WaitForReadThreadFinished() {
HANDLE to_join = nullptr;
{
MonitorLocker ml(&monitor_);
if (read_thread_ != INVALID_HANDLE_VALUE) {
while (!read_thread_finished_) {
ml.Wait();
}
read_thread_finished_ = false;
to_join = read_thread_;
read_thread_ = INVALID_HANDLE_VALUE;
}
}
if (to_join != nullptr) {
// Join the read thread.
DWORD res = WaitForSingleObject(to_join, INFINITE);
CloseHandle(to_join);
ASSERT(res == WAIT_OBJECT_0);
}
}
void Handle::ReadComplete(std::unique_ptr<OverlappedBuffer> buffer) {
WaitForReadThreadStarted();
{
MonitorLocker ml(&monitor_);
// Currently only one outstanding read at the time.
ASSERT(pending_read_ == buffer.get());
ASSERT(data_ready_ == nullptr);
if (!IsClosing()) {
data_ready_ = std::move(buffer);
}
pending_read_ = nullptr;
}
WaitForReadThreadFinished();
}
void Handle::WriteComplete(std::unique_ptr<OverlappedBuffer> buffer) {
MonitorLocker ml(&monitor_);
// Currently only one outstanding write at the time.
ASSERT(pending_write_ == buffer.get());
pending_write_ = nullptr;
}
// Helper method which returns a real HANDLE for the current thread.
static HANDLE GetCurrentThreadHandle() {
HANDLE thread_handle = INVALID_HANDLE_VALUE;
if (!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
GetCurrentProcess(), &thread_handle,
/*dwDesiredAccess=*/0, FALSE, DUPLICATE_SAME_ACCESS)) {
FATAL("Failed to obtain thread handle");
}
return thread_handle;
}
void Handle::NotifyReadThreadStarted() {
MonitorLocker ml(&monitor_);
ASSERT(read_thread_starting_);
ASSERT(read_thread_ == INVALID_HANDLE_VALUE);
read_thread_ = GetCurrentThreadHandle();
read_thread_starting_ = false;
ml.Notify();
}
void Handle::NotifyReadThreadFinished() {
MonitorLocker ml(&monitor_);
ASSERT(!read_thread_finished_);
ASSERT(read_thread_ != INVALID_HANDLE_VALUE);
read_thread_finished_ = true;
ml.Notify();
}
void Handle::ReadSyncCompleteAsync() {
NotifyReadThreadStarted();
ASSERT(HasPendingRead());
ASSERT(pending_read_->GetBufferSize() >= kStdOverlappedBufferSize);
DWORD buffer_size = pending_read_->GetBufferSize();
if (GetFileType(handle_) == FILE_TYPE_CHAR) {
buffer_size = kStdOverlappedBufferSize;
}
char* buffer_start = pending_read_->GetBufferStart();
DWORD bytes_read = 0;
BOOL ok = ReadFile(handle_, buffer_start, buffer_size, &bytes_read, nullptr);
if (!ok) {
bytes_read = 0;
}
OVERLAPPED* overlapped = pending_read_->GetCleanOverlapped();
ok = PostQueuedCompletionStatus(EventHandler::delegate()->completion_port(),
bytes_read, reinterpret_cast<ULONG_PTR>(this),
overlapped);
if (!ok) {
FATAL("PostQueuedCompletionStatus failed");
}
NotifyReadThreadFinished();
}
bool Handle::IssueReadLocked(MonitorLocker* ml) {
ASSERT(type_ != kListenSocket);
ASSERT(!HasPendingRead());
auto buffer = OverlappedBuffer::AllocateReadBuffer(this, kBufferSize);
// Must initialize pending_read_ before issuing async operation, because
// completion will race with this code.
pending_read_ = buffer.get();
if (supports_overlapped_io()) {
BOOL ok =
ReadFile(handle_, buffer->GetBufferStart(), buffer->GetBufferSize(),
nullptr, buffer->GetCleanOverlapped());
if (ok || (GetLastError() == ERROR_IO_PENDING)) {
// Completing asynchronously.
buffer.release(); // HandleIOCompletion will take ownership.
return true;
}
pending_read_ = nullptr;
HandleIssueError();
return false;
} else {
// Completing asynchronously through thread.
Retain();
buffer.release(); // HandleIOCompletion will take ownership.
read_thread_starting_ = true;
Thread::Start(
"dart:io ReadFile",
[](uword args) {
auto handle = reinterpret_cast<Handle*>(args);
handle->ReadSyncCompleteAsync();
handle->Release();
},
reinterpret_cast<uword>(this));
return true;
}
}
bool Handle::IssueRecvFromLocked(MonitorLocker* ml) {
return false;
}
bool Handle::IssueWriteLocked(MonitorLocker* ml,
std::unique_ptr<OverlappedBuffer> buffer) {
ASSERT(type_ != kListenSocket);
ASSERT(!HasPendingWrite());
ASSERT(buffer->operation() == OverlappedBuffer::kWrite);
// Must initialize pending_write_ before issuing asynchronous operation,
// because completion will race with this code.
pending_write_ = buffer.get();
BOOL ok =
WriteFile(handle_, buffer->GetBufferStart(), buffer->GetBufferSize(),
nullptr, buffer->GetCleanOverlapped());
if (ok || (GetLastError() == ERROR_IO_PENDING)) {
// Completing asynchronously.
buffer.release(); // HandleIOCompletion will take ownership.
return true;
}
pending_write_ = nullptr;
HandleIssueError();
return false;
}
bool Handle::IssueSendToLocked(MonitorLocker* ml,
std::unique_ptr<OverlappedBuffer> buffer,
struct sockaddr* sa,
socklen_t sa_len) {
return false;
}
static void HandleClosed(Handle* handle) {
if (!handle->IsClosing()) {
handle->NotifyAllDartPorts(1 << kCloseEvent);
}
}
static void HandleError(Handle* handle) {
handle->set_last_error(WSAGetLastError());
handle->MarkError();
if (!handle->IsClosing()) {
handle->NotifyAllDartPorts(1 << kErrorEvent);
}
}
void Handle::HandleIssueError() {
DWORD error = GetLastError();
if (error == ERROR_BROKEN_PIPE) {
HandleClosed(this);
} else {
HandleError(this);
}
SetLastError(error);
}
bool FileHandle::IsClosed() {
return IsClosing() && !HasPendingRead() && !HasPendingWrite();
}
void DirectoryWatchHandle::Start() {
MonitorLocker ml(&monitor_);
IssueReadLocked(&ml);
}
bool DirectoryWatchHandle::IsClosed() {
return IsClosing() && !HasPendingRead();
}
bool DirectoryWatchHandle::IssueReadLocked(MonitorLocker* ml) {
// It may have been started before, as we start the directory-handler when
// we create it.
if (HasPendingRead() || (data_ready_ != nullptr)) {
return true;
}
auto buffer = OverlappedBuffer::AllocateReadBuffer(this, kBufferSize);
// Set up pending_read_ before ReadDirectoryChangesW because it might be
// needed in ReadComplete invoked on event loop thread right away if data is
// also ready right away.
pending_read_ = buffer.get();
BOOL ok = ReadDirectoryChangesW(
handle_, buffer->GetBufferStart(), buffer->GetBufferSize(), recursive_,
events_, nullptr, buffer->GetCleanOverlapped(), nullptr);
if (ok || (GetLastError() == ERROR_IO_PENDING)) {
// Completing asynchronously.
buffer.release(); // HandleIOCompletion will take ownership.
return true;
}
pending_read_ = nullptr;
return false;
}
void DirectoryWatchHandle::Stop() {
MonitorLocker ml(&monitor_);
// Stop the outstanding read, so we can close the handle.
if (HasPendingRead()) {
CancelIoEx(handle(), pending_read_->GetCleanOverlapped());
// Don't dispose of the buffer, as it will still complete (with length 0).
}
DoCloseLocked(&ml);
}
void SocketHandle::HandleIssueError() {
int error = WSAGetLastError();
if (error == WSAECONNRESET) {
HandleClosed(this);
} else {
HandleError(this);
}
WSASetLastError(error);
}
bool ListenSocket::IssueAcceptLocked(MonitorLocker* ml) {
auto buffer = OverlappedBuffer::AllocateAcceptBuffer(this);
DWORD received;
BOOL ok;
ok = EventHandler::delegate()->accept_ex()(
socket(), buffer->client(), buffer->GetBufferStart(),
0, // For now don't receive data with accept.
kAcceptExAddressStorageSize, kAcceptExAddressStorageSize, &received,
buffer->GetCleanOverlapped());
if (ok || WSAGetLastError() == WSA_IO_PENDING) {
pending_accept_count_++;
buffer.release(); // HandleIOCompletion will take ownership.
return true;
}
HandleError(this);
return false;
}
bool ListenSocket::StartAccept() {
MonitorLocker ml(&monitor_);
// Always keep 5 outstanding accepts going, to enhance performance.
for (intptr_t i = 0; i < kMinIssuedAccepts; i++) {
if (!IssueAcceptLocked(&ml)) {
return false;
}
}
return true;
}
void ListenSocket::AcceptComplete(std::unique_ptr<OverlappedBuffer> buffer) {
MonitorLocker ml(&monitor_);
if (!IsClosing()) {
// Update the accepted socket to support the full range of API calls.
SOCKET s = socket();
int rc = setsockopt(buffer->client(), SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
reinterpret_cast<char*>(&s), sizeof(s));
if (rc == NO_ERROR) {
SOCKET client = buffer->client();
buffer->DetachClient();
// getpeername() returns incorrect results when used with a socket that
// was accepted using overlapped I/O. AcceptEx includes the remote
// address in its result so retrieve it using GetAcceptExSockaddrs and
// save it.
LPSOCKADDR local_addr;
int local_addr_length;
LPSOCKADDR remote_addr;
int remote_addr_length;
EventHandler::delegate()->get_accept_ex_sockaddrs()(
buffer->GetBufferStart(), 0, kAcceptExAddressStorageSize,
kAcceptExAddressStorageSize, &local_addr, &local_addr_length,
&remote_addr, &remote_addr_length);
RawAddr* raw_remote_addr = new RawAddr;
memmove(raw_remote_addr, remote_addr, remote_addr_length);
// Insert the accepted socket into the list.
ClientSocket* client_socket =
new ClientSocket(client, std::unique_ptr<RawAddr>(raw_remote_addr));
client_socket->mark_connected();
if (accepted_head_ == nullptr) {
accepted_head_ = client_socket;
accepted_tail_ = client_socket;
} else {
ASSERT(accepted_tail_ != nullptr);
accepted_tail_->set_next(client_socket);
accepted_tail_ = client_socket;
}
accepted_count_++;
}
}
pending_accept_count_--;
DispatchCompletedAcceptsLocked(&ml);
}
void ListenSocket::DispatchCompletedAcceptsLocked(MonitorLocker* ml) {
if (IsClosing()) {
return;
}
for (int i = 0; i < accepted_count(); i++) {
if (!DispatchInEventIfEnabled(this)) {
break;
}
}
}
static void NotifyDestroyedIfClosed(Handle* handle) {
if (handle->IsClosed()) {
handle->NotifyAllDartPorts(1 << kDestroyedEvent);
handle->RemoveAllPorts();
}
}
void ListenSocket::DoCloseLocked(MonitorLocker* ml) {
closesocket(socket());
handle_ = INVALID_HANDLE_VALUE;
// Get rid of connections already accepted.
ClientSocket* next_client = accepted_head_;
while (next_client != nullptr) {
ClientSocket* client = next_client;
next_client = client->next();
client->set_next(nullptr);
client->Close();
NotifyDestroyedIfClosed(client);
client->Release();
}
accepted_head_ = accepted_tail_ = nullptr;
accepted_count_ = 0;
}
ClientSocket* ListenSocket::Accept() {
MonitorLocker ml(&monitor_);
ClientSocket* result = nullptr;
if (accepted_head_ != nullptr) {
result = accepted_head_;
accepted_head_ = accepted_head_->next();
if (accepted_head_ == nullptr) {
accepted_tail_ = nullptr;
}
result->set_next(nullptr);
accepted_count_--;
}
// We have less than 5 pending accepts and are not closing try to queue
// another accept.
if (!IsClosing() && (pending_accept_count_ < kMinIssuedAccepts)) {
IssueAcceptLocked(&ml);
}
return result;
}
bool ListenSocket::IsClosed() {
return IsClosing() && !HasPendingAccept();
}
intptr_t Handle::Available() {
MonitorLocker ml(&monitor_);
if (data_ready_ == nullptr) {
return 0;
}
return data_ready_->GetRemainingLength();
}
bool Handle::DataReady() {
return data_ready_ != nullptr;
}
intptr_t Handle::Read(void* buffer, intptr_t num_bytes) {
MonitorLocker ml(&monitor_);
if (data_ready_ == nullptr) {
return 0;
}
num_bytes =
data_ready_->Read(buffer, Utils::Minimum<intptr_t>(num_bytes, INT_MAX));
if (data_ready_->IsEmpty()) {
data_ready_ = nullptr;
if (!IsClosing() && !IsClosedRead()) {
IssueReadLocked(&ml);
}
}
return num_bytes;
}
intptr_t Handle::RecvFrom(void* buffer,
intptr_t num_bytes,
struct sockaddr* sa,
socklen_t sa_len) {
MonitorLocker ml(&monitor_);
if (data_ready_ == nullptr) {
return 0;
}
num_bytes =
data_ready_->Read(buffer, Utils::Minimum<intptr_t>(num_bytes, INT_MAX));
if (data_ready_->from()->sa_family == AF_INET) {
ASSERT(sa_len >= sizeof(struct sockaddr_in));
memmove(sa, data_ready_->from(), sizeof(struct sockaddr_in));
} else {
ASSERT(data_ready_->from()->sa_family == AF_INET6);
ASSERT(sa_len >= sizeof(struct sockaddr_in6));
memmove(sa, data_ready_->from(), sizeof(struct sockaddr_in6));
}
// Always dispose of the buffer, as UDP messages must be read in their
// entirety to match how recvfrom works in a socket.
data_ready_ = nullptr;
if (!IsClosing() && !IsClosedRead()) {
IssueRecvFromLocked(&ml);
}
return num_bytes;
}
intptr_t Handle::Write(const void* data, intptr_t num_bytes) {
MonitorLocker ml(&monitor_);
if (HasPendingWrite() || IsClosed()) {
return 0;
}
if (num_bytes > kBufferSize) {
num_bytes = kBufferSize;
}
ASSERT(supports_overlapped_io());
int truncated_bytes = Utils::Minimum<intptr_t>(num_bytes, INT_MAX);
auto buffer = OverlappedBuffer::AllocateWriteBuffer(this, truncated_bytes);
buffer->Write(data, truncated_bytes);
if (!IssueWriteLocked(&ml, std::move(buffer))) {
return -1;
}
return truncated_bytes;
}
intptr_t Handle::SendTo(const void* data,
intptr_t num_bytes,
struct sockaddr* sa,
socklen_t sa_len) {
MonitorLocker ml(&monitor_);
if (HasPendingWrite() || IsClosed()) {
return 0;
}
if (num_bytes > kBufferSize) {
ASSERT(kBufferSize >= kMaxUDPPackageLength);
// The provided buffer is larger than the maximum UDP datagram size so
// return an error immediately. If the buffer were larger and the data were
// actually passed to `WSASendTo()` then the operation would fail with
// ERROR_INVALID_USER_BUFFER anyway.
SetLastError(ERROR_INVALID_USER_BUFFER);
return -1;
}
auto buffer = OverlappedBuffer::AllocateSendToBuffer(this, num_bytes);
buffer->Write(data, num_bytes);
if (!IssueSendToLocked(&ml, std::move(buffer), sa, sa_len)) {
return -1;
}
return num_bytes;
}
Mutex* StdHandle::stdin_mutex_ = new Mutex();
StdHandle* StdHandle::stdin_ = nullptr;
StdHandle* StdHandle::Stdin(HANDLE handle) {
MutexLocker ml(stdin_mutex_);
if (stdin_ == nullptr) {
stdin_ = new StdHandle(handle);
}
return stdin_;
}
void StdHandle::RunWriteLoop() {
MonitorLocker ml(&monitor_);
write_thread_running_ = true;
thread_handle_ = GetCurrentThreadHandle();
// Notify we have started.
ml.Notify();
while (write_thread_running_) {
ml.Wait(Monitor::kNoTimeout);
if (HasPendingWrite()) {
// We woke up and had a pending write. Execute it.
WriteSyncCompleteAsync();
}
}
write_thread_exists_ = false;
ml.Notify();
}
void StdHandle::WriteSyncCompleteAsync() {
ASSERT(HasPendingWrite());
DWORD bytes_written = -1;
BOOL ok = WriteFile(handle_, pending_write_->GetBufferStart(),
pending_write_->GetBufferSize(), &bytes_written, nullptr);
if (!ok) {
bytes_written = 0;
}
thread_wrote_ += bytes_written;
OVERLAPPED* overlapped = pending_write_->GetCleanOverlapped();
ok = PostQueuedCompletionStatus(
EventHandler::delegate()->completion_port(), bytes_written,
reinterpret_cast<ULONG_PTR>(this), overlapped);
if (!ok) {
FATAL("PostQueuedCompletionStatus failed");
}
}
intptr_t StdHandle::Write(const void* buffer, intptr_t num_bytes) {
MonitorLocker ml(&monitor_);
if (HasPendingWrite()) {
return 0;
}
if (num_bytes > kBufferSize) {
num_bytes = kBufferSize;
}
// In the case of stdout and stderr, OverlappedIO is not supported.
// Here we'll instead use a thread, to make it async.
// This code is actually never exposed to the user, as stdout and stderr is
// not available as a RawSocket, but only wrapped in a Socket.
// Note that we return '0', unless a thread have already completed a write.
if (thread_wrote_ > 0) {
if (num_bytes > thread_wrote_) {
num_bytes = thread_wrote_;
}
thread_wrote_ -= num_bytes;
return num_bytes;
}
if (!write_thread_exists_) {
write_thread_exists_ = true;
// The write thread gets a reference to the Handle, which it places in
// the events it puts on the IO completion port.
Retain();
Thread::Start(
"dart:io WriteFile",
[](uword args) {
auto handle = reinterpret_cast<StdHandle*>(args);
handle->RunWriteLoop();
handle->Release();
},
reinterpret_cast<uword>(this));
while (!write_thread_running_) {
// Wait until we the thread is running.
ml.Wait(Monitor::kNoTimeout);
}
}
// Only queue up to INT_MAX bytes.
int truncated_bytes = Utils::Minimum<intptr_t>(num_bytes, INT_MAX);
// Create buffer and notify thread about the new handle.
pending_write_ =
OverlappedBuffer::AllocateWriteBuffer(this, truncated_bytes).release();
pending_write_->Write(buffer, truncated_bytes);
ml.Notify();
return 0;
}
void StdHandle::DoCloseLocked(MonitorLocker* ml) {
if (write_thread_exists_) {
write_thread_running_ = false;
ml->Notify();
while (write_thread_exists_) {
ml->Wait(Monitor::kNoTimeout);
}
// Join the thread.
DWORD res = WaitForSingleObject(thread_handle_, INFINITE);
CloseHandle(thread_handle_);
ASSERT(res == WAIT_OBJECT_0);
}
Handle::DoCloseLocked(ml);
MutexLocker stdin_mutex_locker(stdin_mutex_);
stdin_->Release();
StdHandle::stdin_ = nullptr;
}
#if defined(DEBUG)
intptr_t ClientSocket::disconnecting_ = 0;
#endif
void ClientSocket::Shutdown(int how) {
int rc = shutdown(socket(), how);
if (how == SD_RECEIVE) {
MarkClosedRead();
}
if (how == SD_SEND) {
MarkClosedWrite();
}
if (how == SD_BOTH) {
MarkClosedRead();
MarkClosedWrite();
}
}
void ClientSocket::DoCloseLocked(MonitorLocker* ml) {
// Always do a shutdown before initiating a disconnect.
shutdown(socket(), SD_BOTH);
IssueDisconnectLocked(ml);
handle_ = INVALID_HANDLE_VALUE;
}
bool ClientSocket::IssueReadLocked(MonitorLocker* ml) {
ASSERT(!HasPendingRead());
// TODO(sgjesse): Use a MTU value here. Only the loopback adapter can
// handle 64k datagrams.
auto buffer = OverlappedBuffer::AllocateReadBuffer(this, 65536);
DWORD flags;
flags = 0;
pending_read_ = buffer.get();
int rc = WSARecv(socket(), buffer->GetWASBUF(), 1, nullptr, &flags,
buffer->GetCleanOverlapped(), nullptr);
if ((rc == NO_ERROR) || (WSAGetLastError() == WSA_IO_PENDING)) {
buffer.release(); // HandleIOCompletion will take ownership.
return true;
}
pending_read_ = nullptr;
HandleIssueError();
return false;
}
bool ClientSocket::IssueWriteLocked(MonitorLocker* ml,
std::unique_ptr<OverlappedBuffer> buffer) {
ASSERT(!HasPendingWrite());
ASSERT(buffer->operation() == OverlappedBuffer::kWrite);
pending_write_ = buffer.get();
int rc = WSASend(socket(), pending_write_->GetWASBUF(), 1, nullptr, 0,
pending_write_->GetCleanOverlapped(), nullptr);
if ((rc == NO_ERROR) || (WSAGetLastError() == WSA_IO_PENDING)) {
buffer.release(); // HandleIOCompletion will take ownership.
return true;
}
pending_write_ = nullptr;
HandleIssueError();
return false;
}
void ClientSocket::IssueDisconnectLocked(MonitorLocker* ml) {
auto buffer = OverlappedBuffer::AllocateDisconnectBuffer(this);
BOOL ok = EventHandler::delegate()->disconnect_ex()(
socket(), buffer->GetCleanOverlapped(), TF_REUSE_SOCKET, 0);
// DisconnectEx works like other OverlappedIO APIs, where we can get either an
// immediate success or delayed operation by WSA_IO_PENDING being set.
if (ok || (WSAGetLastError() != WSA_IO_PENDING)) {
DisconnectComplete();
} else {
// Completing asynchronously.
buffer.release(); // HandleIOCompletion will take ownership.
}
// When the Dart side receives this event, it may decide to close its Dart
// ports. When all ports are closed, the VM will shut down. The EventHandler
// will then shut down. If the EventHandler shuts down before this
// asynchronous disconnect finishes, this ClientSocket will be leaked.
// TODO(dart:io): Retain a list of client sockets that are in the process of
// disconnecting. Disconnect them forcefully, and clean up their resources
// when the EventHandler shuts down.
NotifyAllDartPorts(1 << kDestroyedEvent);
RemoveAllPorts();
#if defined(DEBUG)
disconnecting_++;
#endif
}
void ClientSocket::DisconnectComplete() {
closesocket(socket());
data_ready_ = nullptr;
mark_closed();
#if defined(DEBUG)
disconnecting_--;
#endif
}
void ClientSocket::ConnectComplete() {
// Update socket to support full socket API, after ConnectEx completed.
setsockopt(socket(), SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, nullptr, 0);
// If the port is set, we already listen for this socket in Dart.
// Handle the cases here.
if (!IsClosedRead() && ((Mask() & kInEventMask) != 0)) {
MonitorLocker ml(&monitor_);
IssueReadLocked(&ml);
}
if (!IsClosedWrite()) {
DispatchOutEventIfEnabled(this);
}
}
bool ClientSocket::IsClosed() {
return connected_ && closed_ && !HasPendingRead() && !HasPendingWrite();
}
bool ClientSocket::PopulateRemoteAddr(RawAddr& addr) {
if (!remote_addr_) {
return false;
}
addr = *remote_addr_;
return true;
}
bool DatagramSocket::IssueSendToLocked(MonitorLocker* ml,
std::unique_ptr<OverlappedBuffer> buffer,
struct sockaddr* sa,
socklen_t sa_len) {
ASSERT(!HasPendingWrite());
ASSERT(buffer->operation() == OverlappedBuffer::kSendTo);
pending_write_ = buffer.get();
int rc = WSASendTo(socket(), pending_write_->GetWASBUF(), 1, nullptr, 0, sa,
sa_len, pending_write_->GetCleanOverlapped(), nullptr);
if ((rc == NO_ERROR) || (WSAGetLastError() == WSA_IO_PENDING)) {
buffer.release(); // HandleIOCompletion will take ownership.
return true;
}
pending_write_ = nullptr;
HandleIssueError();
return false;
}
bool DatagramSocket::IssueRecvFromLocked(MonitorLocker* ml) {
ASSERT(!HasPendingRead());
auto buffer =
OverlappedBuffer::AllocateRecvFromBuffer(this, kMaxUDPPackageLength);
pending_read_ = buffer.get();
DWORD flags = 0;