-
Notifications
You must be signed in to change notification settings - Fork 0
/
sysdeps_win32.cpp
3174 lines (2749 loc) · 113 KB
/
sysdeps_win32.cpp
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) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define TRACE_TAG SYSDEPS
#include "sysdeps.h"
#include <lmcons.h>
#include <windows.h>
#include <winsock2.h> /* winsock.h *must* be included before windows.h. */
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <memory>
#include <mutex>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
#include <cutils/sockets.h>
#include <android-base/errors.h>
#include <android-base/file.h>
#include <android-base/logging.h>
#include <android-base/macros.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#include <android-base/utf8.h>
#include "adb.h"
#include "adb_utils.h"
#include "sysdeps/uio.h"
/* forward declarations */
typedef const struct FHClassRec_* FHClass;
typedef struct FHRec_* FH;
typedef struct FHClassRec_ {
void (*_fh_init)(FH);
int (*_fh_close)(FH);
int64_t (*_fh_lseek)(FH, int64_t, int);
int (*_fh_read)(FH, void*, int);
int (*_fh_write)(FH, const void*, int);
int (*_fh_writev)(FH, const adb_iovec*, int);
intptr_t (*_fh_get_os_handle)(FH);
} FHClassRec;
static void _fh_file_init(FH);
static int _fh_file_close(FH);
static int64_t _fh_file_lseek(FH, int64_t, int);
static int _fh_file_read(FH, void*, int);
static int _fh_file_write(FH, const void*, int);
static int _fh_file_writev(FH, const adb_iovec*, int);
static intptr_t _fh_file_get_os_handle(FH f);
static const FHClassRec _fh_file_class = {
_fh_file_init, _fh_file_close, _fh_file_lseek, _fh_file_read,
_fh_file_write, _fh_file_writev, _fh_file_get_os_handle,
};
static void _fh_socket_init(FH);
static int _fh_socket_close(FH);
static int64_t _fh_socket_lseek(FH, int64_t, int);
static int _fh_socket_read(FH, void*, int);
static int _fh_socket_write(FH, const void*, int);
static int _fh_socket_writev(FH, const adb_iovec*, int);
static intptr_t _fh_socket_get_os_handle(FH f);
static const FHClassRec _fh_socket_class = {
_fh_socket_init, _fh_socket_close, _fh_socket_lseek, _fh_socket_read,
_fh_socket_write, _fh_socket_writev, _fh_socket_get_os_handle,
};
#if defined(assert)
#undef assert
#endif
void handle_deleter::operator()(HANDLE h) {
// CreateFile() is documented to return INVALID_HANDLE_FILE on error,
// implying that NULL is a valid handle, but this is probably impossible.
// Other APIs like CreateEvent() are documented to return NULL on error,
// implying that INVALID_HANDLE_VALUE is a valid handle, but this is also
// probably impossible. Thus, consider both NULL and INVALID_HANDLE_VALUE
// as invalid handles. std::unique_ptr won't call a deleter with NULL, so we
// only need to check for INVALID_HANDLE_VALUE.
if (h != INVALID_HANDLE_VALUE) {
if (!CloseHandle(h)) {
D("CloseHandle(%p) failed: %s", h,
android::base::SystemErrorCodeToString(GetLastError()).c_str());
}
}
}
/**************************************************************************/
/**************************************************************************/
/***** *****/
/***** common file descriptor handling *****/
/***** *****/
/**************************************************************************/
/**************************************************************************/
typedef struct FHRec_
{
FHClass clazz;
int used;
int eof;
union {
HANDLE handle;
SOCKET socket;
} u;
char name[32];
} FHRec;
#define fh_handle u.handle
#define fh_socket u.socket
#define WIN32_FH_BASE 2048
#define WIN32_MAX_FHS 2048
static std::mutex& _win32_lock = *new std::mutex();
static FHRec _win32_fhs[ WIN32_MAX_FHS ];
static int _win32_fh_next; // where to start search for free FHRec
static FH _fh_from_int(borrowed_fd bfd, const char* func) {
FH f;
int fd = bfd.get();
fd -= WIN32_FH_BASE;
if (fd < 0 || fd >= WIN32_MAX_FHS) {
D("_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE, func);
errno = EBADF;
return nullptr;
}
f = &_win32_fhs[fd];
if (f->used == 0) {
D("_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE, func);
errno = EBADF;
return nullptr;
}
return f;
}
static int _fh_to_int(FH f) {
if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
return (int)(f - _win32_fhs) + WIN32_FH_BASE;
return -1;
}
static FH _fh_alloc(FHClass clazz) {
FH f = nullptr;
std::lock_guard<std::mutex> lock(_win32_lock);
for (int i = _win32_fh_next; i < WIN32_MAX_FHS; ++i) {
if (_win32_fhs[i].clazz == nullptr) {
f = &_win32_fhs[i];
_win32_fh_next = i + 1;
f->clazz = clazz;
f->used = 1;
f->eof = 0;
f->name[0] = '\0';
clazz->_fh_init(f);
return f;
}
}
D("_fh_alloc: no more free file descriptors");
errno = EMFILE; // Too many open files
return nullptr;
}
static int _fh_close(FH f) {
// Use lock so that closing only happens once and so that _fh_alloc can't
// allocate a FH that we're in the middle of closing.
std::lock_guard<std::mutex> lock(_win32_lock);
int offset = f - _win32_fhs;
if (_win32_fh_next > offset) {
_win32_fh_next = offset;
}
if (f->used) {
f->clazz->_fh_close( f );
f->name[0] = '\0';
f->eof = 0;
f->used = 0;
f->clazz = nullptr;
}
return 0;
}
// Deleter for unique_fh.
class fh_deleter {
public:
void operator()(struct FHRec_* fh) {
// We're called from a destructor and destructors should not overwrite
// errno because callers may do:
// errno = EBLAH;
// return -1; // calls destructor, which should not overwrite errno
const int saved_errno = errno;
_fh_close(fh);
errno = saved_errno;
}
};
// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
/**************************************************************************/
/**************************************************************************/
/***** *****/
/***** file-based descriptor handling *****/
/***** *****/
/**************************************************************************/
/**************************************************************************/
static void _fh_file_init(FH f) {
f->fh_handle = INVALID_HANDLE_VALUE;
}
static int _fh_file_close(FH f) {
CloseHandle(f->fh_handle);
f->fh_handle = INVALID_HANDLE_VALUE;
return 0;
}
static int _fh_file_read(FH f, void* buf, int len) {
DWORD read_bytes;
if (!ReadFile(f->fh_handle, buf, (DWORD)len, &read_bytes, nullptr)) {
D("adb_read: could not read %d bytes from %s", len, f->name);
errno = EIO;
return -1;
} else if (read_bytes < (DWORD)len) {
f->eof = 1;
}
return read_bytes;
}
static int _fh_file_write(FH f, const void* buf, int len) {
DWORD wrote_bytes;
if (!WriteFile(f->fh_handle, buf, (DWORD)len, &wrote_bytes, nullptr)) {
D("adb_file_write: could not write %d bytes from %s", len, f->name);
errno = EIO;
return -1;
} else if (wrote_bytes < (DWORD)len) {
f->eof = 1;
}
return wrote_bytes;
}
static int _fh_file_writev(FH f, const adb_iovec* iov, int iovcnt) {
if (iovcnt <= 0) {
errno = EINVAL;
return -1;
}
DWORD wrote_bytes = 0;
for (int i = 0; i < iovcnt; ++i) {
ssize_t rc = _fh_file_write(f, iov[i].iov_base, iov[i].iov_len);
if (rc == -1) {
return wrote_bytes > 0 ? wrote_bytes : -1;
} else if (rc == 0) {
return wrote_bytes;
}
wrote_bytes += rc;
if (static_cast<size_t>(rc) < iov[i].iov_len) {
return wrote_bytes;
}
}
return wrote_bytes;
}
static int64_t _fh_file_lseek(FH f, int64_t pos, int origin) {
DWORD method;
switch (origin) {
case SEEK_SET:
method = FILE_BEGIN;
break;
case SEEK_CUR:
method = FILE_CURRENT;
break;
case SEEK_END:
method = FILE_END;
break;
default:
errno = EINVAL;
return -1;
}
LARGE_INTEGER li = {.QuadPart = pos};
if (!SetFilePointerEx(f->fh_handle, li, &li, method)) {
errno = EIO;
return -1;
}
f->eof = 0;
return li.QuadPart;
}
static intptr_t _fh_file_get_os_handle(FH f) {
return reinterpret_cast<intptr_t>(f->u.handle);
}
/**************************************************************************/
/**************************************************************************/
/***** *****/
/***** file-based descriptor handling *****/
/***** *****/
/**************************************************************************/
/**************************************************************************/
int adb_open(const char* path, int options) {
FH f;
DWORD desiredAccess = 0;
DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
// CreateFileW is inherently O_CLOEXEC by default.
options &= ~O_CLOEXEC;
switch (options) {
case O_RDONLY:
desiredAccess = GENERIC_READ;
break;
case O_WRONLY:
desiredAccess = GENERIC_WRITE;
break;
case O_RDWR:
desiredAccess = GENERIC_READ | GENERIC_WRITE;
break;
default:
D("adb_open: invalid options (0x%0x)", options);
errno = EINVAL;
return -1;
}
f = _fh_alloc(&_fh_file_class);
if (!f) {
return -1;
}
std::wstring path_wide;
if (!android::base::UTF8ToWide(path, &path_wide)) {
return -1;
}
f->fh_handle =
CreateFileW(path_wide.c_str(), desiredAccess, shareMode, nullptr, OPEN_EXISTING, 0, nullptr);
if (f->fh_handle == INVALID_HANDLE_VALUE) {
const DWORD err = GetLastError();
_fh_close(f);
D("adb_open: could not open '%s': ", path);
switch (err) {
case ERROR_FILE_NOT_FOUND:
D("file not found");
errno = ENOENT;
return -1;
case ERROR_PATH_NOT_FOUND:
D("path not found");
errno = ENOTDIR;
return -1;
default:
D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
errno = ENOENT;
return -1;
}
}
snprintf(f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path);
D("adb_open: '%s' => fd %d", path, _fh_to_int(f));
return _fh_to_int(f);
}
/* ignore mode on Win32 */
int adb_creat(const char* path, int mode) {
FH f;
f = _fh_alloc(&_fh_file_class);
if (!f) {
return -1;
}
std::wstring path_wide;
if (!android::base::UTF8ToWide(path, &path_wide)) {
return -1;
}
f->fh_handle = CreateFileW(path_wide.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (f->fh_handle == INVALID_HANDLE_VALUE) {
const DWORD err = GetLastError();
_fh_close(f);
D("adb_creat: could not open '%s': ", path);
switch (err) {
case ERROR_FILE_NOT_FOUND:
D("file not found");
errno = ENOENT;
return -1;
case ERROR_PATH_NOT_FOUND:
D("path not found");
errno = ENOTDIR;
return -1;
default:
D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
errno = ENOENT;
return -1;
}
}
snprintf(f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path);
D("adb_creat: '%s' => fd %d", path, _fh_to_int(f));
return _fh_to_int(f);
}
int adb_read(borrowed_fd fd, void* buf, int len) {
FH f = _fh_from_int(fd, __func__);
if (f == nullptr) {
errno = EBADF;
return -1;
}
return f->clazz->_fh_read(f, buf, len);
}
int adb_pread(borrowed_fd fd, void* buf, int len, off64_t offset) {
OVERLAPPED overlapped = {};
overlapped.Offset = static_cast<DWORD>(offset);
overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32);
DWORD bytes_read;
if (!::ReadFile(adb_get_os_handle(fd), buf, static_cast<DWORD>(len), &bytes_read,
&overlapped)) {
D("adb_pread: could not read %d bytes from FD %d", len, fd.get());
switch (::GetLastError()) {
case ERROR_IO_PENDING:
errno = EAGAIN;
return -1;
default:
errno = EINVAL;
return -1;
}
}
return static_cast<int>(bytes_read);
}
int adb_write(borrowed_fd fd, const void* buf, int len) {
FH f = _fh_from_int(fd, __func__);
if (f == nullptr) {
errno = EBADF;
return -1;
}
return f->clazz->_fh_write(f, buf, len);
}
ssize_t adb_writev(borrowed_fd fd, const adb_iovec* iov, int iovcnt) {
FH f = _fh_from_int(fd, __func__);
if (f == nullptr) {
errno = EBADF;
return -1;
}
return f->clazz->_fh_writev(f, iov, iovcnt);
}
int adb_pwrite(borrowed_fd fd, const void* buf, int len, off64_t offset) {
OVERLAPPED params = {};
params.Offset = static_cast<DWORD>(offset);
params.OffsetHigh = static_cast<DWORD>(offset >> 32);
DWORD bytes_written = 0;
if (!::WriteFile(adb_get_os_handle(fd), buf, len, &bytes_written, ¶ms)) {
D("adb_pwrite: could not write %d bytes to FD %d", len, fd.get());
switch (::GetLastError()) {
case ERROR_IO_PENDING:
errno = EAGAIN;
return -1;
default:
errno = EINVAL;
return -1;
}
}
return static_cast<int>(bytes_written);
}
int64_t adb_lseek(borrowed_fd fd, int64_t pos, int where) {
FH f = _fh_from_int(fd, __func__);
if (!f) {
errno = EBADF;
return -1;
}
return f->clazz->_fh_lseek(f, pos, where);
}
int adb_close(int fd) {
FH f = _fh_from_int(fd, __func__);
if (!f) {
errno = EBADF;
return -1;
}
D("adb_close: %s", f->name);
_fh_close(f);
return 0;
}
HANDLE adb_get_os_handle(borrowed_fd fd) {
FH f = _fh_from_int(fd, __func__);
if (!f) {
errno = EBADF;
return nullptr;
}
D("adb_get_os_handle: %s", f->name);
const intptr_t intptr_handle = f->clazz->_fh_get_os_handle(f);
const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
return handle;
}
/**************************************************************************/
/**************************************************************************/
/***** *****/
/***** socket-based file descriptors *****/
/***** *****/
/**************************************************************************/
/**************************************************************************/
#undef setsockopt
static void _socket_set_errno( const DWORD err ) {
// Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
// lot of POSIX and socket error codes, some of the resulting error codes
// are mapped to strings by adb_strerror().
switch ( err ) {
case 0: errno = 0; break;
// Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
// case WSAEINTR: errno = EINTR; break;
case WSAEFAULT: errno = EFAULT; break;
case WSAEINVAL: errno = EINVAL; break;
case WSAEMFILE: errno = EMFILE; break;
// Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
// non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
// callers check specifically for EAGAIN.
case WSAEWOULDBLOCK: errno = EAGAIN; break;
case WSAENOTSOCK: errno = ENOTSOCK; break;
case WSAENOPROTOOPT: errno = ENOPROTOOPT; break;
case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break;
case WSAENETDOWN: errno = ENETDOWN; break;
case WSAENETRESET: errno = ENETRESET; break;
// Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems
// to use EPIPE for these situations and there are some callers that look
// for EPIPE.
case WSAECONNABORTED: errno = EPIPE; break;
case WSAECONNRESET: errno = ECONNRESET; break;
case WSAENOBUFS: errno = ENOBUFS; break;
case WSAENOTCONN: errno = ENOTCONN; break;
// Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or
// SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future
// considerations: Reportedly send() can return zero on timeout, and POSIX
// code may expect EAGAIN instead of ETIMEDOUT on timeout.
// case WSAETIMEDOUT: errno = ETIMEDOUT; break;
case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
default:
errno = EINVAL;
D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
err, errno );
}
}
extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
// WSAPoll doesn't handle invalid/non-socket handles, so we need to handle them ourselves.
int skipped = 0;
std::vector<WSAPOLLFD> sockets;
std::vector<adb_pollfd*> original;
for (size_t i = 0; i < nfds; ++i) {
FH fh = _fh_from_int(fds[i].fd, __func__);
if (!fh || !fh->used || fh->clazz != &_fh_socket_class) {
D("adb_poll received bad FD %d", fds[i].fd);
fds[i].revents = POLLNVAL;
++skipped;
} else {
WSAPOLLFD wsapollfd = {
.fd = fh->u.socket,
.events = static_cast<short>(fds[i].events)
};
sockets.push_back(wsapollfd);
original.push_back(&fds[i]);
}
}
if (sockets.empty()) {
return skipped;
}
// If we have any invalid FDs in our FD set, make sure to return immediately.
if (skipped > 0) {
timeout = 0;
}
int result = WSAPoll(sockets.data(), sockets.size(), timeout);
if (result == SOCKET_ERROR) {
_socket_set_errno(WSAGetLastError());
return -1;
}
// Map the results back onto the original set.
for (size_t i = 0; i < sockets.size(); ++i) {
original[i]->revents = sockets[i].revents;
}
// WSAPoll appears to return the number of unique FDs with available events, instead of how many
// of the pollfd elements have a non-zero revents field, which is what it and poll are specified
// to do. Ignore its result and calculate the proper return value.
result = 0;
for (size_t i = 0; i < nfds; ++i) {
if (fds[i].revents != 0) {
++result;
}
}
return result;
}
static void _fh_socket_init(FH f) {
f->fh_socket = INVALID_SOCKET;
}
static int _fh_socket_close(FH f) {
if (f->fh_socket != INVALID_SOCKET) {
if (closesocket(f->fh_socket) == SOCKET_ERROR) {
// Don't set errno here, since adb_close will ignore it.
const DWORD err = WSAGetLastError();
D("closesocket failed: %s", android::base::SystemErrorCodeToString(err).c_str());
}
f->fh_socket = INVALID_SOCKET;
}
return 0;
}
static int64_t _fh_socket_lseek(FH f, int64_t pos, int origin) {
errno = EPIPE;
return -1;
}
static int _fh_socket_read(FH f, void* buf, int len) {
int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
if (result == SOCKET_ERROR) {
const DWORD err = WSAGetLastError();
// WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
// that to reduce spam and confusion.
if (err != WSAEWOULDBLOCK) {
D("recv fd %d failed: %s", _fh_to_int(f),
android::base::SystemErrorCodeToString(err).c_str());
}
_socket_set_errno(err);
result = -1;
}
return result;
}
static int _fh_socket_write(FH f, const void* buf, int len) {
int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
if (result == SOCKET_ERROR) {
const DWORD err = WSAGetLastError();
// WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
// that to reduce spam and confusion.
if (err != WSAEWOULDBLOCK) {
D("send fd %d failed: %s", _fh_to_int(f),
android::base::SystemErrorCodeToString(err).c_str());
}
_socket_set_errno(err);
result = -1;
} else {
// According to https://code.google.com/p/chromium/issues/detail?id=27870
// Winsock Layered Service Providers may cause this.
CHECK_LE(result, len) << "Tried to write " << len << " bytes to " << f->name << ", but "
<< result << " bytes reportedly written";
}
return result;
}
// Make sure that adb_iovec is compatible with WSABUF.
static_assert(sizeof(adb_iovec) == sizeof(WSABUF), "");
static_assert(SIZEOF_MEMBER(adb_iovec, iov_len) == SIZEOF_MEMBER(WSABUF, len), "");
static_assert(offsetof(adb_iovec, iov_len) == offsetof(WSABUF, len), "");
static_assert(SIZEOF_MEMBER(adb_iovec, iov_base) == SIZEOF_MEMBER(WSABUF, buf), "");
static_assert(offsetof(adb_iovec, iov_base) == offsetof(WSABUF, buf), "");
static int _fh_socket_writev(FH f, const adb_iovec* iov, int iovcnt) {
if (iovcnt <= 0) {
errno = EINVAL;
return -1;
}
WSABUF* wsabuf = reinterpret_cast<WSABUF*>(const_cast<adb_iovec*>(iov));
DWORD bytes_written = 0;
int result = WSASend(f->fh_socket, wsabuf, iovcnt, &bytes_written, 0, nullptr, nullptr);
if (result == SOCKET_ERROR) {
const DWORD err = WSAGetLastError();
// WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
// that to reduce spam and confusion.
if (err != WSAEWOULDBLOCK) {
D("send fd %d failed: %s", _fh_to_int(f),
android::base::SystemErrorCodeToString(err).c_str());
}
_socket_set_errno(err);
return -1;
}
CHECK_GE(static_cast<DWORD>(std::numeric_limits<int>::max()), bytes_written);
return static_cast<int>(bytes_written);
}
static intptr_t _fh_socket_get_os_handle(FH f) {
return f->u.socket;
}
/**************************************************************************/
/**************************************************************************/
/***** *****/
/***** replacement for libs/cutils/socket_xxxx.c *****/
/***** *****/
/**************************************************************************/
/**************************************************************************/
static void _init_winsock() {
static std::once_flag once;
std::call_once(once, []() {
WSADATA wsaData;
int rc = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (rc != 0) {
LOG(FATAL) << "could not initialize Winsock: "
<< android::base::SystemErrorCodeToString(rc);
}
// Note that we do not call atexit() to register WSACleanup to be called
// at normal process termination because:
// 1) When exit() is called, there are still threads actively using
// Winsock because we don't cleanly shutdown all threads, so it
// doesn't make sense to call WSACleanup() and may cause problems
// with those threads.
// 2) A deadlock can occur when exit() holds a C Runtime lock, then it
// calls WSACleanup() which tries to unload a DLL, which tries to
// grab the LoaderLock. This conflicts with the device_poll_thread
// which holds the LoaderLock because AdbWinApi.dll calls
// setupapi.dll which tries to load wintrust.dll which tries to load
// crypt32.dll which calls atexit() which tries to acquire the C
// Runtime lock that the other thread holds.
});
}
// Map a socket type to an explicit socket protocol instead of using the socket
// protocol of 0. Explicit socket protocols are used by most apps and we should
// do the same to reduce the chance of exercising uncommon code-paths that might
// have problems or that might load different Winsock service providers that
// have problems.
static int GetSocketProtocolFromSocketType(int type) {
switch (type) {
case SOCK_STREAM:
return IPPROTO_TCP;
case SOCK_DGRAM:
return IPPROTO_UDP;
default:
LOG(FATAL) << "Unknown socket type: " << type;
return 0;
}
}
int adb_socket(int domain, int type, int protocol) {
SOCKET s;
unique_fh f(_fh_alloc(&_fh_socket_class));
if (!f) {
return -1;
}
s = socket(domain, type, GetSocketProtocolFromSocketType(type));
if (s == INVALID_SOCKET) {
const DWORD err = WSAGetLastError();
const auto error = android::base::StringPrintf(
"cannot create socket: %s", android::base::SystemErrorCodeToString(err).c_str());
D("%s", error.c_str());
_socket_set_errno(err);
return -1;
}
f->fh_socket = s;
const int fd = _fh_to_int(f.get());
f.release();
return fd;
}
int adb_bind(borrowed_fd fd, const sockaddr* addr, socklen_t addrlen) {
FH fh = _fh_from_int(fd, __func__);
if (!fh || fh->clazz != &_fh_socket_class) {
D("adb_bind: invalid fd %d", fd.get());
errno = EBADF;
return -1;
}
if (bind(fh->fh_socket, addr, addrlen) == SOCKET_ERROR) {
const DWORD err = WSAGetLastError();
LOG(ERROR) << "adb_bind: bind on fd " << fd.get()
<< " failed: " + android::base::SystemErrorCodeToString(err);
_socket_set_errno(err);
return -1;
}
return 0;
}
static void to_WSAMSG(const struct adb_msghdr* msg, WSAMSG* wmsg) {
WSABUF* msgbuf = reinterpret_cast<WSABUF*>(msg->msg_iov);
memset(wmsg, 0, sizeof(decltype(*wmsg)));
wmsg->name = (struct sockaddr*)msg->msg_name;
char ipaddr[1024];
switch (wmsg->name->sa_family) {
case AF_INET: {
auto* sin = reinterpret_cast<struct sockaddr_in*>(wmsg->name);
inet_ntop(sin->sin_family, &sin->sin_addr, ipaddr, 1024);
break;
}
case AF_INET6: {
auto* sin = reinterpret_cast<struct sockaddr_in6*>(wmsg->name);
inet_ntop(sin->sin6_family, &sin->sin6_addr, ipaddr, 1024);
break;
}
default:
// Address may be unset when receiving messages, which is fine.
break;
}
wmsg->namelen = msg->msg_namelen;
wmsg->lpBuffers = msgbuf;
wmsg->dwBufferCount = msg->msg_iovlen;
wmsg->Control.len = msg->msg_controllen;
wmsg->Control.buf = (char*)msg->msg_control;
wmsg->dwFlags = msg->msg_flags;
}
ssize_t adb_sendmsg(borrowed_fd fd, const struct adb_msghdr* msg, int flags) {
FH fh = _fh_from_int(fd, __func__);
if (!fh || fh->clazz != &_fh_socket_class) {
D("adb_sendmsg: invalid fd %d", fd.get());
errno = EBADF;
return -1;
}
WSAMSG wmsg;
to_WSAMSG(msg, &wmsg);
DWORD num_bytes = 0;
// TODO: WSASendMsg doesn't work when setting the source address to INADDR_ANY. Posix sendmsg()
// works though. Need to figure out what to do when we get a wildcard address.
auto ret = WSASendMsg(fh->fh_socket, &wmsg, 0, &num_bytes, NULL, NULL);
if (ret == SOCKET_ERROR) {
const DWORD err = WSAGetLastError();
LOG(ERROR) << "WSASendMsg() failed " << android::base::SystemErrorCodeToString(err);
_socket_set_errno(err);
return -1;
}
return num_bytes;
}
// WSARecvMsg() function pointer must be obtained at runtime.
static LPFN_WSARECVMSG GetWSARecvMsgFunc(borrowed_fd fd) {
FH fh = _fh_from_int(fd, __func__);
if (!fh || fh->clazz != &_fh_socket_class) {
D("%s(%d) failed: invalid fd", __func__, fd.get());
errno = EBADF;
return nullptr;
}
LPFN_WSARECVMSG func = nullptr;
GUID guid = WSAID_WSARECVMSG;
DWORD bytes_returned = 0;
if (WSAIoctl(fh->fh_socket, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid), &func,
sizeof(func), &bytes_returned, nullptr, nullptr) != 0) {
const DWORD err = WSAGetLastError();
D("%s(%d) failed: %s", __func__, fd.get(),
android::base::SystemErrorCodeToString(err).c_str());
_socket_set_errno(err);
return nullptr;
}
return func;
}
ssize_t adb_recvmsg(borrowed_fd fd, struct adb_msghdr* msg, int flags) {
FH fh = _fh_from_int(fd, __func__);
if (!fh || fh->clazz != &_fh_socket_class) {
D("adb_recvmsg: invalid fd %d", fd.get());
errno = EBADF;
return -1;
}
auto WSARecvMsgFunc = GetWSARecvMsgFunc(fd);
if (!WSARecvMsgFunc) {
errno = ENOSYS;
return -1;
}
WSAMSG wmsg;
to_WSAMSG(msg, &wmsg);
DWORD num_bytes = 0;
CHECK_EQ(wmsg.dwBufferCount, 1U);
char* orig = wmsg.lpBuffers[0].buf;
auto orig_len = wmsg.lpBuffers[0].len;
auto bytes_remaining = orig_len;
auto orig_flags = wmsg.dwFlags;
while (bytes_remaining > 0) {
const auto ret = WSARecvMsgFunc(fh->fh_socket, &wmsg, &num_bytes, NULL, NULL);
if (ret == SOCKET_ERROR) {
const DWORD err = WSAGetLastError();
LOG(ERROR) << "WSARecvMsg() failed " << android::base::SystemErrorCodeToString(err);
_socket_set_errno(err);
return -1;
}
bytes_remaining -= num_bytes;
if (bytes_remaining > 0) {
wmsg.lpBuffers[0].buf = orig + (orig_len - bytes_remaining);
wmsg.lpBuffers[0].len = bytes_remaining;
// WSARecvMsg will change dwFlags, which will make subsequent calls to WSARecvMsg fail
// with invalid operation error.
wmsg.dwFlags = orig_flags;
}
}
wmsg.lpBuffers[0].buf = orig;
wmsg.lpBuffers[0].len = orig_len;
return orig_len;
}
adb_cmsghdr* adb_CMSG_FIRSTHDR(adb_msghdr* msgh) {
WSAMSG wmsg;
to_WSAMSG(msgh, &wmsg);
return WSA_CMSG_FIRSTHDR(&wmsg);
}
adb_cmsghdr* adb_CMSG_NXTHDR(adb_msghdr* msgh, adb_cmsghdr* cmsg) {
WSAMSG wmsg;
to_WSAMSG(msgh, &wmsg);
return WSA_CMSG_NXTHDR(&wmsg, cmsg);
}
unsigned char* adb_CMSG_DATA(adb_cmsghdr* cmsg) {
return WSA_CMSG_DATA(cmsg);
}
int network_loopback_client(int port, int type, std::string* error) {
struct sockaddr_in addr;