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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609
|
//===-- ConnectionFileDescriptor.cpp ----------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#if defined(__APPLE__)
// Enable this special support for Apple builds where we can have unlimited
// select bounds. We tried switching to poll() and kqueue and we were panicing
// the kernel, so we have to stick with select for now.
#define _DARWIN_UNLIMITED_SELECT
#endif
#include "lldb/Core/ConnectionFileDescriptor.h"
#include "lldb/Host/Config.h"
#include "lldb/Host/SocketAddress.h"
// C Includes
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#ifndef LLDB_DISABLE_POSIX
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <termios.h>
#include <unistd.h>
#endif
#ifdef _WIN32
#include "lldb/Host/windows/windows.h"
#include <winsock2.h>
#include <WS2tcpip.h>
#endif
// C++ Includes
// Other libraries and framework includes
#include "llvm/Support/ErrorHandling.h"
#if defined(__APPLE__)
#include "llvm/ADT/SmallVector.h"
#endif
// Project includes
#include "lldb/lldb-private-log.h"
#include "lldb/Interpreter/Args.h"
#include "lldb/Core/Communication.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/RegularExpression.h"
#include "lldb/Core/Timer.h"
using namespace lldb;
using namespace lldb_private;
static bool
DecodeHostAndPort (const char *host_and_port,
std::string &host_str,
std::string &port_str,
int32_t& port,
Error *error_ptr)
{
static RegularExpression g_regex ("([^:]+):([0-9]+)");
RegularExpression::Match regex_match(2);
if (g_regex.Execute (host_and_port, ®ex_match))
{
if (regex_match.GetMatchAtIndex (host_and_port, 1, host_str) &&
regex_match.GetMatchAtIndex (host_and_port, 2, port_str))
{
port = Args::StringToSInt32 (port_str.c_str(), INT32_MIN);
if (port != INT32_MIN)
{
if (error_ptr)
error_ptr->Clear();
return true;
}
}
}
host_str.clear();
port_str.clear();
port = INT32_MIN;
if (error_ptr)
error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", host_and_port);
return false;
}
ConnectionFileDescriptor::ConnectionFileDescriptor () :
Connection(),
m_fd_send (-1),
m_fd_recv (-1),
m_fd_send_type (eFDTypeFile),
m_fd_recv_type (eFDTypeFile),
m_udp_send_sockaddr (new SocketAddress()),
m_should_close_fd (false),
m_socket_timeout_usec(0),
m_pipe_read(-1),
m_pipe_write(-1),
m_mutex (Mutex::eMutexTypeRecursive),
m_shutting_down (false)
{
Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION | LIBLLDB_LOG_OBJECT));
if (log)
log->Printf ("%p ConnectionFileDescriptor::ConnectionFileDescriptor ()", this);
}
ConnectionFileDescriptor::ConnectionFileDescriptor (int fd, bool owns_fd) :
Connection(),
m_fd_send (fd),
m_fd_recv (fd),
m_fd_send_type (eFDTypeFile),
m_fd_recv_type (eFDTypeFile),
m_udp_send_sockaddr (new SocketAddress()),
m_should_close_fd (owns_fd),
m_socket_timeout_usec(0),
m_pipe_read(-1),
m_pipe_write(-1),
m_mutex (Mutex::eMutexTypeRecursive),
m_shutting_down (false)
{
Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION | LIBLLDB_LOG_OBJECT));
if (log)
log->Printf ("%p ConnectionFileDescriptor::ConnectionFileDescriptor (fd = %i, owns_fd = %i)", this, fd, owns_fd);
OpenCommandPipe ();
}
ConnectionFileDescriptor::~ConnectionFileDescriptor ()
{
Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION | LIBLLDB_LOG_OBJECT));
if (log)
log->Printf ("%p ConnectionFileDescriptor::~ConnectionFileDescriptor ()", this);
Disconnect (NULL);
CloseCommandPipe ();
}
void
ConnectionFileDescriptor::OpenCommandPipe ()
{
CloseCommandPipe();
Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
// Make the command file descriptor here:
int filedes[2];
#ifndef LLDB_DISABLE_POSIX
int result = pipe (filedes);
#else
int result = -1;
#endif
if (result != 0)
{
if (log)
log->Printf ("%p ConnectionFileDescriptor::OpenCommandPipe () - could not make pipe: %s",
this,
strerror(errno));
}
else
{
m_pipe_read = filedes[0];
m_pipe_write = filedes[1];
if (log)
log->Printf ("%p ConnectionFileDescriptor::OpenCommandPipe() - success readfd=%d writefd=%d",
this,
m_pipe_read,
m_pipe_write);
}
}
void
ConnectionFileDescriptor::CloseCommandPipe ()
{
Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
if (log)
log->Printf ("%p ConnectionFileDescriptor::CloseCommandPipe()",
this);
if (m_pipe_read != -1)
{
#ifdef _MSC_VER
llvm_unreachable("pipe close unsupported in MSVC");
#else
close (m_pipe_read);
#endif
m_pipe_read = -1;
}
if (m_pipe_write != -1)
{
#ifdef _MSC_VER
llvm_unreachable("pipe close unsupported in MSVC");
#else
close (m_pipe_write);
#endif
m_pipe_write = -1;
}
}
bool
ConnectionFileDescriptor::IsConnected () const
{
return m_fd_send >= 0 || m_fd_recv >= 0;
}
ConnectionStatus
ConnectionFileDescriptor::Connect (const char *s, Error *error_ptr)
{
Mutex::Locker locker (m_mutex);
Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
if (log)
log->Printf ("%p ConnectionFileDescriptor::Connect (url = '%s')", this, s);
OpenCommandPipe();
if (s && s[0])
{
char *end = NULL;
if (strstr(s, "listen://"))
{
// listen://HOST:PORT
unsigned long listen_port = ::strtoul(s + strlen("listen://"), &end, 0);
return SocketListen (listen_port, error_ptr);
}
else if (strstr(s, "unix-accept://"))
{
// unix://SOCKNAME
return NamedSocketAccept (s + strlen("unix-accept://"), error_ptr);
}
else if (strstr(s, "connect://"))
{
return ConnectTCP (s + strlen("connect://"), error_ptr);
}
else if (strstr(s, "tcp-connect://"))
{
return ConnectTCP (s + strlen("tcp-connect://"), error_ptr);
}
else if (strstr(s, "udp://"))
{
return ConnectUDP (s + strlen("udp://"), error_ptr);
}
else if (strstr(s, "fd://"))
{
// Just passing a native file descriptor within this current process
// that is already opened (possibly from a service or other source).
s += strlen ("fd://");
bool success = false;
m_fd_send = m_fd_recv = Args::StringToSInt32 (s, -1, 0, &success);
if (success)
{
// We have what looks to be a valid file descriptor, but we
// should make sure it is. We currently are doing this by trying to
// get the flags from the file descriptor and making sure it
// isn't a bad fd.
errno = 0;
#ifndef LLDB_DISABLE_POSIX
int flags = ::fcntl (m_fd_send, F_GETFL, 0);
#else
int flags = -1;
#endif
if (flags == -1 || errno == EBADF)
{
if (error_ptr)
error_ptr->SetErrorStringWithFormat ("stale file descriptor: %s", s);
m_fd_send = m_fd_recv = -1;
return eConnectionStatusError;
}
else
{
// Try and get a socket option from this file descriptor to
// see if this is a socket and set m_is_socket accordingly.
int resuse;
bool is_socket = GetSocketOption (m_fd_send, SOL_SOCKET, SO_REUSEADDR, resuse) == 0;
if (is_socket)
m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
// Don't take ownership of a file descriptor that gets passed
// to us since someone else opened the file descriptor and
// handed it to us.
// TODO: Since are using a URL to open connection we should
// eventually parse options using the web standard where we
// have "fd://123?opt1=value;opt2=value" and we can have an
// option be "owns=1" or "owns=0" or something like this to
// allow us to specify this. For now, we assume we must
// assume we don't own it.
m_should_close_fd = false;
return eConnectionStatusSuccess;
}
}
if (error_ptr)
error_ptr->SetErrorStringWithFormat ("invalid file descriptor: \"fd://%s\"", s);
m_fd_send = m_fd_recv = -1;
return eConnectionStatusError;
}
else if (strstr(s, "file://"))
{
// file:///PATH
const char *path = s + strlen("file://");
#ifndef LLDB_DISABLE_POSIX
do
{
m_fd_send = m_fd_recv = ::open (path, O_RDWR);
} while (m_fd_send == -1 && errno == EINTR);
if (m_fd_send == -1)
{
if (error_ptr)
error_ptr->SetErrorToErrno();
return eConnectionStatusError;
}
if (::isatty(m_fd_send))
{
// Set up serial terminal emulation
struct termios options;
::tcgetattr (m_fd_send, &options);
// Set port speed to maximum
::cfsetospeed (&options, B115200);
::cfsetispeed (&options, B115200);
// Raw input, disable echo and signals
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
// Make sure only one character is needed to return from a read
options.c_cc[VMIN] = 1;
options.c_cc[VTIME] = 0;
::tcsetattr (m_fd_send, TCSANOW, &options);
}
int flags = ::fcntl (m_fd_send, F_GETFL, 0);
if (flags >= 0)
{
if ((flags & O_NONBLOCK) == 0)
{
flags |= O_NONBLOCK;
::fcntl (m_fd_send, F_SETFL, flags);
}
}
m_should_close_fd = true;
return eConnectionStatusSuccess;
#else
return eConnectionStatusError;
#endif
}
if (error_ptr)
error_ptr->SetErrorStringWithFormat ("unsupported connection URL: '%s'", s);
return eConnectionStatusError;
}
if (error_ptr)
error_ptr->SetErrorString("invalid connect arguments");
return eConnectionStatusError;
}
ConnectionStatus
ConnectionFileDescriptor::Disconnect (Error *error_ptr)
{
Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
if (log)
log->Printf ("%p ConnectionFileDescriptor::Disconnect ()", this);
ConnectionStatus status = eConnectionStatusSuccess;
if (m_fd_send < 0 && m_fd_recv < 0)
{
if (log)
log->Printf ("%p ConnectionFileDescriptor::Disconnect(): Nothing to disconnect", this);
return eConnectionStatusSuccess;
}
// Try to get the ConnectionFileDescriptor's mutex. If we fail, that is quite likely
// because somebody is doing a blocking read on our file descriptor. If that's the case,
// then send the "q" char to the command file channel so the read will wake up and the connection
// will then know to shut down.
m_shutting_down = true;
Mutex::Locker locker;
bool got_lock= locker.TryLock (m_mutex);
if (!got_lock)
{
if (m_pipe_write != -1 )
{
int result;
result = write (m_pipe_write, "q", 1);
if (log)
log->Printf ("%p ConnectionFileDescriptor::Disconnect(): Couldn't get the lock, sent 'q' to %d, result = %d.", this, m_pipe_write, result);
}
else if (log)
log->Printf ("%p ConnectionFileDescriptor::Disconnect(): Couldn't get the lock, but no command pipe is available.", this);
locker.Lock (m_mutex);
}
if (m_should_close_fd == true)
{
if (m_fd_send == m_fd_recv)
{
status = Close (m_fd_send, m_fd_send_type, error_ptr);
}
else
{
// File descriptors are the different, close both if needed
if (m_fd_send >= 0)
status = Close (m_fd_send, m_fd_send_type, error_ptr);
if (m_fd_recv >= 0)
{
ConnectionStatus recv_status = Close (m_fd_recv, m_fd_recv_type, error_ptr);
if (status == eConnectionStatusSuccess)
status = recv_status;
}
}
}
// Now set all our descriptors to invalid values.
m_fd_send = m_fd_recv = -1;
if (status != eConnectionStatusSuccess)
{
return status;
}
m_shutting_down = false;
return eConnectionStatusSuccess;
}
size_t
ConnectionFileDescriptor::Read (void *dst,
size_t dst_len,
uint32_t timeout_usec,
ConnectionStatus &status,
Error *error_ptr)
{
Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
if (log)
log->Printf ("%p ConnectionFileDescriptor::Read () ::read (fd = %i, dst = %p, dst_len = %" PRIu64 ")...",
this, m_fd_recv, dst, (uint64_t)dst_len);
Mutex::Locker locker;
bool got_lock = locker.TryLock (m_mutex);
if (!got_lock)
{
if (log)
log->Printf ("%p ConnectionFileDescriptor::Read () failed to get the connection lock.",
this);
if (error_ptr)
error_ptr->SetErrorString ("failed to get the connection lock for read.");
status = eConnectionStatusTimedOut;
return 0;
}
else if (m_shutting_down)
return eConnectionStatusError;
ssize_t bytes_read = 0;
status = BytesAvailable (timeout_usec, error_ptr);
if (status == eConnectionStatusSuccess)
{
do
{
#ifndef LLDB_DISABLE_POSIX
bytes_read = ::read (m_fd_recv, dst, dst_len);
#else
switch (m_fd_send_type) {
case eFDTypeSocket:
case eFDTypeSocketUDP:
bytes_read = ::recv (m_fd_recv, (char*)dst, dst_len, 0);
break;
default:
bytes_read = -1;
break;
}
#endif
} while (bytes_read < 0 && errno == EINTR);
}
if (status != eConnectionStatusSuccess)
return 0;
Error error;
if (bytes_read == 0)
{
error.Clear(); // End-of-file. Do not automatically close; pass along for the end-of-file handlers.
status = eConnectionStatusEndOfFile;
}
else if (bytes_read < 0)
{
error.SetErrorToErrno();
}
else
{
error.Clear();
}
if (log)
log->Printf ("%p ConnectionFileDescriptor::Read () ::read (fd = %i, dst = %p, dst_len = %" PRIu64 ") => %" PRIi64 ", error = %s",
this,
m_fd_recv,
dst,
(uint64_t)dst_len,
(int64_t)bytes_read,
error.AsCString());
if (error_ptr)
*error_ptr = error;
if (error.Fail())
{
uint32_t error_value = error.GetError();
switch (error_value)
{
case EAGAIN: // The file was marked for non-blocking I/O, and no data were ready to be read.
if (m_fd_recv_type == eFDTypeSocket || m_fd_recv_type == eFDTypeSocketUDP)
status = eConnectionStatusTimedOut;
else
status = eConnectionStatusSuccess;
return 0;
case EFAULT: // Buf points outside the allocated address space.
case EINTR: // A read from a slow device was interrupted before any data arrived by the delivery of a signal.
case EINVAL: // The pointer associated with fildes was negative.
case EIO: // An I/O error occurred while reading from the file system.
// The process group is orphaned.
// The file is a regular file, nbyte is greater than 0,
// the starting position is before the end-of-file, and
// the starting position is greater than or equal to the
// offset maximum established for the open file
// descriptor associated with fildes.
case EISDIR: // An attempt is made to read a directory.
case ENOBUFS: // An attempt to allocate a memory buffer fails.
case ENOMEM: // Insufficient memory is available.
status = eConnectionStatusError;
break; // Break to close....
case ENOENT: // no such file or directory
case EBADF: // fildes is not a valid file or socket descriptor open for reading.
case ENXIO: // An action is requested of a device that does not exist..
// A requested action cannot be performed by the device.
case ECONNRESET:// The connection is closed by the peer during a read attempt on a socket.
case ENOTCONN: // A read is attempted on an unconnected socket.
status = eConnectionStatusLostConnection;
break; // Break to close....
case ETIMEDOUT: // A transmission timeout occurs during a read attempt on a socket.
status = eConnectionStatusTimedOut;
return 0;
default:
if (log)
log->Printf("%p ConnectionFileDescriptor::Read (), unexpected error: %s", this, strerror(error_value));
status = eConnectionStatusError;
break; // Break to close....
}
return 0;
}
return bytes_read;
}
size_t
ConnectionFileDescriptor::Write (const void *src, size_t src_len, ConnectionStatus &status, Error *error_ptr)
{
Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
if (log)
log->Printf ("%p ConnectionFileDescriptor::Write (src = %p, src_len = %" PRIu64 ")", this, src, (uint64_t)src_len);
if (!IsConnected ())
{
if (error_ptr)
error_ptr->SetErrorString("not connected");
status = eConnectionStatusNoConnection;
return 0;
}
Error error;
ssize_t bytes_sent = 0;
switch (m_fd_send_type)
{
#ifndef LLDB_DISABLE_POSIX
case eFDTypeFile: // Other FD requireing read/write
do
{
bytes_sent = ::write (m_fd_send, src, src_len);
} while (bytes_sent < 0 && errno == EINTR);
break;
#endif
case eFDTypeSocket: // Socket requiring send/recv
do
{
bytes_sent = ::send (m_fd_send, (char*)src, src_len, 0);
} while (bytes_sent < 0 && errno == EINTR);
break;
case eFDTypeSocketUDP: // Unconnected UDP socket requiring sendto/recvfrom
assert (m_udp_send_sockaddr->GetFamily() != 0);
do
{
bytes_sent = ::sendto (m_fd_send,
(char*)src,
src_len,
0,
*m_udp_send_sockaddr,
m_udp_send_sockaddr->GetLength());
} while (bytes_sent < 0 && errno == EINTR);
break;
}
if (bytes_sent < 0)
error.SetErrorToErrno ();
else
error.Clear ();
if (log)
{
switch (m_fd_send_type)
{
case eFDTypeFile: // Other FD requireing read/write
log->Printf ("%p ConnectionFileDescriptor::Write() ::write (fd = %i, src = %p, src_len = %" PRIu64 ") => %" PRIi64 " (error = %s)",
this,
m_fd_send,
src,
(uint64_t)src_len,
(int64_t)bytes_sent,
error.AsCString());
break;
case eFDTypeSocket: // Socket requiring send/recv
log->Printf ("%p ConnectionFileDescriptor::Write() ::send (socket = %i, src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
this,
m_fd_send,
src,
(uint64_t)src_len,
(int64_t)bytes_sent,
error.AsCString());
break;
case eFDTypeSocketUDP: // Unconnected UDP socket requiring sendto/recvfrom
log->Printf ("%p ConnectionFileDescriptor::Write() ::sendto (socket = %i, src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
this,
m_fd_send,
src,
(uint64_t)src_len,
(int64_t)bytes_sent,
error.AsCString());
break;
}
}
if (error_ptr)
*error_ptr = error;
if (error.Fail())
{
switch (error.GetError())
{
case EAGAIN:
case EINTR:
status = eConnectionStatusSuccess;
return 0;
case ECONNRESET:// The connection is closed by the peer during a read attempt on a socket.
case ENOTCONN: // A read is attempted on an unconnected socket.
status = eConnectionStatusLostConnection;
break; // Break to close....
default:
status = eConnectionStatusError;
break; // Break to close....
}
return 0;
}
status = eConnectionStatusSuccess;
return bytes_sent;
}
#if defined(__APPLE__)
// This ConnectionFileDescriptor::BytesAvailable() uses select().
//
// PROS:
// - select is consistent across most unix platforms
// - this Apple specific version allows for unlimited fds in the fd_sets by
// setting the _DARWIN_UNLIMITED_SELECT define prior to including the
// required header files.
// CONS:
// - Darwin only
ConnectionStatus
ConnectionFileDescriptor::BytesAvailable (uint32_t timeout_usec, Error *error_ptr)
{
// Don't need to take the mutex here separately since we are only called from Read. If we
// ever get used more generally we will need to lock here as well.
Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
if (log)
log->Printf("%p ConnectionFileDescriptor::BytesAvailable (timeout_usec = %u)", this, timeout_usec);
struct timeval *tv_ptr;
struct timeval tv;
if (timeout_usec == UINT32_MAX)
{
// Infinite wait...
tv_ptr = NULL;
}
else
{
TimeValue time_value;
time_value.OffsetWithMicroSeconds (timeout_usec);
tv.tv_sec = time_value.seconds();
tv.tv_usec = time_value.microseconds();
tv_ptr = &tv;
}
// Make a copy of the file descriptors to make sure we don't
// have another thread change these values out from under us
// and cause problems in the loop below where like in FS_SET()
const int data_fd = m_fd_recv;
const int pipe_fd = m_pipe_read;
if (data_fd >= 0)
{
const bool have_pipe_fd = pipe_fd >= 0;
while (data_fd == m_fd_recv)
{
const int nfds = std::max<int>(data_fd, pipe_fd) + 1;
llvm::SmallVector<fd_set, 1> read_fds;
read_fds.resize((nfds/FD_SETSIZE) + 1);
for (size_t i=0; i<read_fds.size(); ++i)
FD_ZERO (&read_fds[i]);
// FD_SET doesn't bounds check, it just happily walks off the end
// but we have taken care of making the extra storage with our
// SmallVector of fd_set objects
FD_SET (data_fd, read_fds.data());
if (have_pipe_fd)
FD_SET (pipe_fd, read_fds.data());
Error error;
if (log)
{
if (have_pipe_fd)
log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p)...",
this, nfds, data_fd, pipe_fd, tv_ptr);
else
log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p)...",
this, nfds, data_fd, tv_ptr);
}
const int num_set_fds = ::select (nfds, read_fds.data(), NULL, NULL, tv_ptr);
if (num_set_fds < 0)
error.SetErrorToErrno();
else
error.Clear();
if (log)
{
if (have_pipe_fd)
log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p) => %d, error = %s",
this, nfds, data_fd, pipe_fd, tv_ptr, num_set_fds, error.AsCString());
else
log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p) => %d, error = %s",
this, nfds, data_fd, tv_ptr, num_set_fds, error.AsCString());
}
if (error_ptr)
*error_ptr = error;
if (error.Fail())
{
switch (error.GetError())
{
case EBADF: // One of the descriptor sets specified an invalid descriptor.
return eConnectionStatusLostConnection;
case EINVAL: // The specified time limit is invalid. One of its components is negative or too large.
default: // Other unknown error
return eConnectionStatusError;
case EAGAIN: // The kernel was (perhaps temporarily) unable to
// allocate the requested number of file descriptors,
// or we have non-blocking IO
case EINTR: // A signal was delivered before the time limit
// expired and before any of the selected events
// occurred.
break; // Lets keep reading to until we timeout
}
}
else if (num_set_fds == 0)
{
return eConnectionStatusTimedOut;
}
else if (num_set_fds > 0)
{
// FD_ISSET is happy to deal with a something larger than
// a single fd_set.
if (FD_ISSET(data_fd, read_fds.data()))
return eConnectionStatusSuccess;
if (have_pipe_fd && FD_ISSET(pipe_fd, read_fds.data()))
{
// We got a command to exit. Read the data from that pipe:
char buffer[16];
ssize_t bytes_read;
do
{
bytes_read = ::read (pipe_fd, buffer, sizeof(buffer));
} while (bytes_read < 0 && errno == EINTR);
assert (bytes_read == 1 && buffer[0] == 'q');
if (log)
log->Printf("%p ConnectionFileDescriptor::BytesAvailable() got data: %*s from the command channel.",
this, (int) bytes_read, buffer);
return eConnectionStatusEndOfFile;
}
}
}
}
if (error_ptr)
error_ptr->SetErrorString("not connected");
return eConnectionStatusLostConnection;
}
#else
// This ConnectionFileDescriptor::BytesAvailable() uses select().
//
// PROS:
// - select is consistent across most unix platforms
// CONS:
// - only supports file descriptors up to FD_SETSIZE. This implementation
// will assert if it runs into that hard limit to let users know that
// another ConnectionFileDescriptor::BytesAvailable() should be used
// or a new version of ConnectionFileDescriptor::BytesAvailable() should
// be written for the system that is running into the limitations. MacOSX
// uses kqueues, and there is a poll() based implementation below.
ConnectionStatus
ConnectionFileDescriptor::BytesAvailable (uint32_t timeout_usec, Error *error_ptr)
{
// Don't need to take the mutex here separately since we are only called from Read. If we
// ever get used more generally we will need to lock here as well.
Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
if (log)
log->Printf("%p ConnectionFileDescriptor::BytesAvailable (timeout_usec = %u)", this, timeout_usec);
struct timeval *tv_ptr;
struct timeval tv;
if (timeout_usec == UINT32_MAX)
{
// Infinite wait...
tv_ptr = NULL;
}
else
{
TimeValue time_value;
time_value.OffsetWithMicroSeconds (timeout_usec);
tv.tv_sec = time_value.seconds();
tv.tv_usec = time_value.microseconds();
tv_ptr = &tv;
}
// Make a copy of the file descriptors to make sure we don't
// have another thread change these values out from under us
// and cause problems in the loop below where like in FS_SET()
const int data_fd = m_fd_recv;
const int pipe_fd = m_pipe_read;
if (data_fd >= 0)
{
// If this assert fires off on MacOSX, we will need to switch to using
// libdispatch to read from file descriptors because poll() is causing
// kernel panics and if we exceed FD_SETSIZE we will have no choice...
#ifndef _MSC_VER
assert (data_fd < FD_SETSIZE);
#endif
const bool have_pipe_fd = pipe_fd >= 0;
if (have_pipe_fd)
{
assert (pipe_fd < FD_SETSIZE);
}
while (data_fd == m_fd_recv)
{
fd_set read_fds;
FD_ZERO (&read_fds);
FD_SET (data_fd, &read_fds);
if (have_pipe_fd)
FD_SET (pipe_fd, &read_fds);
const int nfds = std::max<int>(data_fd, pipe_fd) + 1;
Error error;
if (log)
{
if (have_pipe_fd)
log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p)...",
this, nfds, data_fd, pipe_fd, tv_ptr);
else
log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p)...",
this, nfds, data_fd, tv_ptr);
}
const int num_set_fds = ::select (nfds, &read_fds, NULL, NULL, tv_ptr);
if (num_set_fds < 0)
error.SetErrorToErrno();
else
error.Clear();
if (log)
{
if (have_pipe_fd)
log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i, %i}, NULL, NULL, timeout=%p) => %d, error = %s",
this, nfds, data_fd, pipe_fd, tv_ptr, num_set_fds, error.AsCString());
else
log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds=%i, fds={%i}, NULL, NULL, timeout=%p) => %d, error = %s",
this, nfds, data_fd, tv_ptr, num_set_fds, error.AsCString());
}
if (error_ptr)
*error_ptr = error;
if (error.Fail())
{
switch (error.GetError())
{
case EBADF: // One of the descriptor sets specified an invalid descriptor.
return eConnectionStatusLostConnection;
case EINVAL: // The specified time limit is invalid. One of its components is negative or too large.
default: // Other unknown error
return eConnectionStatusError;
case EAGAIN: // The kernel was (perhaps temporarily) unable to
// allocate the requested number of file descriptors,
// or we have non-blocking IO
case EINTR: // A signal was delivered before the time limit
// expired and before any of the selected events
// occurred.
break; // Lets keep reading to until we timeout
}
}
else if (num_set_fds == 0)
{
return eConnectionStatusTimedOut;
}
else if (num_set_fds > 0)
{
if (FD_ISSET(data_fd, &read_fds))
return eConnectionStatusSuccess;
if (have_pipe_fd && FD_ISSET(pipe_fd, &read_fds))
{
// We got a command to exit. Read the data from that pipe:
char buffer[16];
ssize_t bytes_read;
do
{
bytes_read = ::read (pipe_fd, buffer, sizeof(buffer));
} while (bytes_read < 0 && errno == EINTR);
assert (bytes_read == 1 && buffer[0] == 'q');
if (log)
log->Printf("%p ConnectionFileDescriptor::BytesAvailable() got data: %*s from the command channel.",
this, (int) bytes_read, buffer);
return eConnectionStatusEndOfFile;
}
}
}
}
if (error_ptr)
error_ptr->SetErrorString("not connected");
return eConnectionStatusLostConnection;
}
#endif
#if 0
#include <poll.h>
// This ConnectionFileDescriptor::BytesAvailable() uses poll(). poll() should NOT
// be used on MacOSX as it has all sorts of restrictions on the types of file descriptors
// that it doesn't support.
//
// There may be some systems that properly support poll() that could use this
// implementation. I will let each system opt into this on their own.
//
// PROS:
// - no restrictions on the fd value that is used
// CONS:
// - varies wildly from platform to platform in its implementation restrictions
ConnectionStatus
ConnectionFileDescriptor::BytesAvailable (uint32_t timeout_usec, Error *error_ptr)
{
// Don't need to take the mutex here separately since we are only called from Read. If we
// ever get used more generally we will need to lock here as well.
Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
if (log)
log->Printf("%p ConnectionFileDescriptor::BytesAvailable (timeout_usec = %u)", this, timeout_usec);
int timeout_msec = 0;
if (timeout_usec == UINT32_MAX)
{
// Infinite wait...
timeout_msec = -1;
}
else if (timeout_usec == 0)
{
// Return immediately, don't wait
timeout_msec = 0;
}
else
{
// Convert usec to msec
timeout_msec = (timeout_usec + 999) / 1000;
}
// Make a copy of the file descriptors to make sure we don't
// have another thread change these values out from under us
// and cause problems in the loop below where like in FS_SET()
const int data_fd = m_fd_recv;
const int pipe_fd = m_pipe_read;
// Make sure the file descriptor can be used with select as it
// must be in range
if (data_fd >= 0)
{
const bool have_pipe_fd = pipe_fd >= 0;
struct pollfd fds[2] =
{
{ data_fd, POLLIN, 0 },
{ pipe_fd, POLLIN, 0 }
};
const int nfds = have_pipe_fd ? 2 : 1;
Error error;
while (data_fd == m_fd_recv)
{
const int num_set_fds = ::poll (fds, nfds, timeout_msec);
if (num_set_fds < 0)
error.SetErrorToErrno();
else
error.Clear();
if (error_ptr)
*error_ptr = error;
if (log)
{
if (have_pipe_fd)
log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::poll (fds={{%i,POLLIN},{%i,POLLIN}}, nfds=%i, timeout_ms=%i) => %d, error = %s\n",
this,
data_fd,
pipe_fd,
nfds,
timeout_msec,
num_set_fds,
error.AsCString());
else
log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::poll (fds={{%i,POLLIN}}, nfds=%i, timeout_ms=%i) => %d, error = %s\n",
this,
data_fd,
nfds,
timeout_msec,
num_set_fds,
error.AsCString());
}
if (error.Fail())
{
switch (error.GetError())
{
case EBADF: // One of the descriptor sets specified an invalid descriptor.
return eConnectionStatusLostConnection;
case EINVAL: // The specified time limit is invalid. One of its components is negative or too large.
default: // Other unknown error
return eConnectionStatusError;
case EAGAIN: // The kernel was (perhaps temporarily) unable to
// allocate the requested number of file descriptors,
// or we have non-blocking IO
case EINTR: // A signal was delivered before the time limit
// expired and before any of the selected events
// occurred.
break; // Lets keep reading to until we timeout
}
}
else if (num_set_fds == 0)
{
return eConnectionStatusTimedOut;
}
else if (num_set_fds > 0)
{
if (fds[0].revents & POLLIN)
return eConnectionStatusSuccess;
if (fds[1].revents & POLLIN)
{
// We got a command to exit. Read the data from that pipe:
char buffer[16];
ssize_t bytes_read;
do
{
bytes_read = ::read (pipe_fd, buffer, sizeof(buffer));
} while (bytes_read < 0 && errno == EINTR);
assert (bytes_read == 1 && buffer[0] == 'q');
if (log)
log->Printf("%p ConnectionFileDescriptor::BytesAvailable() got data: %*s from the command channel.",
this, (int) bytes_read, buffer);
return eConnectionStatusEndOfFile;
}
}
}
}
if (error_ptr)
error_ptr->SetErrorString("not connected");
return eConnectionStatusLostConnection;
}
#endif
ConnectionStatus
ConnectionFileDescriptor::Close (int& fd, FDType type, Error *error_ptr)
{
if (error_ptr)
error_ptr->Clear();
bool success = true;
// Avoid taking a lock if we can
if (fd >= 0)
{
Mutex::Locker locker (m_mutex);
// Check the FD after the lock is taken to ensure only one thread
// can get into the close scope below
if (fd >= 0)
{
Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
if (log)
log->Printf ("%p ConnectionFileDescriptor::Close (fd = %i)", this,fd);
#if _WIN32
if (type != eFDTypeFile)
success = closesocket(fd) == 0;
else
#endif
success = ::close (fd) == 0;
// A reference to a FD was passed in, set it to an invalid value
fd = -1;
if (!success && error_ptr)
{
// Only set the error if we have been asked to since something else
// might have caused us to try and shut down the connection and may
// have already set the error.
error_ptr->SetErrorToErrno();
}
}
}
if (success)
return eConnectionStatusSuccess;
else
return eConnectionStatusError;
}
ConnectionStatus
ConnectionFileDescriptor::NamedSocketAccept (const char *socket_name, Error *error_ptr)
{
#ifndef LLDB_DISABLE_POSIX
ConnectionStatus result = eConnectionStatusError;
struct sockaddr_un saddr_un;
m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
int listen_socket = ::socket (AF_UNIX, SOCK_STREAM, 0);
if (listen_socket == -1)
{
if (error_ptr)
error_ptr->SetErrorToErrno();
return eConnectionStatusError;
}
saddr_un.sun_family = AF_UNIX;
::strncpy(saddr_un.sun_path, socket_name, sizeof(saddr_un.sun_path) - 1);
saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0';
#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
saddr_un.sun_len = SUN_LEN (&saddr_un);
#endif
if (::bind (listen_socket, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) == 0)
{
if (::listen (listen_socket, 5) == 0)
{
m_fd_send = m_fd_recv = ::accept (listen_socket, NULL, 0);
if (m_fd_send > 0)
{
m_should_close_fd = true;
if (error_ptr)
error_ptr->Clear();
result = eConnectionStatusSuccess;
}
}
}
if (result != eConnectionStatusSuccess)
{
if (error_ptr)
error_ptr->SetErrorToErrno();
}
// We are done with the listen port
Close (listen_socket, eFDTypeSocket, NULL);
return result;
#else
return eConnectionStatusError;
#endif
}
ConnectionStatus
ConnectionFileDescriptor::NamedSocketConnect (const char *socket_name, Error *error_ptr)
{
#ifndef LLDB_DISABLE_POSIX
Disconnect (NULL);
m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
// Open the socket that was passed in as an option
struct sockaddr_un saddr_un;
m_fd_send = m_fd_recv = ::socket (AF_UNIX, SOCK_STREAM, 0);
if (m_fd_send == -1)
{
if (error_ptr)
error_ptr->SetErrorToErrno();
return eConnectionStatusError;
}
saddr_un.sun_family = AF_UNIX;
::strncpy(saddr_un.sun_path, socket_name, sizeof(saddr_un.sun_path) - 1);
saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0';
#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
saddr_un.sun_len = SUN_LEN (&saddr_un);
#endif
if (::connect (m_fd_send, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) < 0)
{
if (error_ptr)
error_ptr->SetErrorToErrno();
Disconnect (NULL);
return eConnectionStatusError;
}
if (error_ptr)
error_ptr->Clear();
return eConnectionStatusSuccess;
#else
return eConnectionStatusError;
#endif
}
ConnectionStatus
ConnectionFileDescriptor::SocketListen (uint16_t listen_port_num, Error *error_ptr)
{
Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
if (log)
log->Printf ("%p ConnectionFileDescriptor::SocketListen (port = %i)", this, listen_port_num);
Disconnect (NULL);
m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
int listen_port = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listen_port == -1)
{
if (error_ptr)
error_ptr->SetErrorToErrno();
return eConnectionStatusError;
}
// enable local address reuse
SetSocketOption (listen_port, SOL_SOCKET, SO_REUSEADDR, 1);
SocketAddress localhost;
if (localhost.SetToLocalhost (AF_INET, listen_port_num))
{
int err = ::bind (listen_port, localhost, localhost.GetLength());
if (err == -1)
{
if (error_ptr)
error_ptr->SetErrorToErrno();
Close (listen_port, eFDTypeSocket, NULL);
return eConnectionStatusError;
}
err = ::listen (listen_port, 1);
if (err == -1)
{
if (error_ptr)
error_ptr->SetErrorToErrno();
Close (listen_port, eFDTypeSocket, NULL);
return eConnectionStatusError;
}
m_fd_send = m_fd_recv = ::accept (listen_port, NULL, 0);
if (m_fd_send == -1)
{
if (error_ptr)
error_ptr->SetErrorToErrno();
Close (listen_port, eFDTypeSocket, NULL);
return eConnectionStatusError;
}
}
// We are done with the listen port
Close (listen_port, eFDTypeSocket, NULL);
m_should_close_fd = true;
// Keep our TCP packets coming without any delays.
SetSocketOption (m_fd_send, IPPROTO_TCP, TCP_NODELAY, 1);
if (error_ptr)
error_ptr->Clear();
return eConnectionStatusSuccess;
}
ConnectionStatus
ConnectionFileDescriptor::ConnectTCP (const char *host_and_port, Error *error_ptr)
{
Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
if (log)
log->Printf ("%p ConnectionFileDescriptor::ConnectTCP (host/port = %s)", this, host_and_port);
Disconnect (NULL);
m_fd_send_type = m_fd_recv_type = eFDTypeSocket;
std::string host_str;
std::string port_str;
int32_t port = INT32_MIN;
if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, error_ptr))
return eConnectionStatusError;
// Create the socket
m_fd_send = m_fd_recv = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (m_fd_send == -1)
{
if (error_ptr)
error_ptr->SetErrorToErrno();
return eConnectionStatusError;
}
m_should_close_fd = true;
// Enable local address reuse
SetSocketOption (m_fd_send, SOL_SOCKET, SO_REUSEADDR, 1);
struct sockaddr_in sa;
::memset (&sa, 0, sizeof (sa));
sa.sin_family = AF_INET;
sa.sin_port = htons (port);
int inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);
if (inet_pton_result <= 0)
{
struct hostent *host_entry = gethostbyname (host_str.c_str());
if (host_entry)
host_str = ::inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);
inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);
if (inet_pton_result <= 0)
{
if (error_ptr)
{
if (inet_pton_result == -1)
error_ptr->SetErrorToErrno();
else
error_ptr->SetErrorStringWithFormat("invalid host string: '%s'", host_str.c_str());
}
Disconnect (NULL);
return eConnectionStatusError;
}
}
if (-1 == ::connect (m_fd_send, (const struct sockaddr *)&sa, sizeof(sa)))
{
if (error_ptr)
error_ptr->SetErrorToErrno();
Disconnect (NULL);
return eConnectionStatusError;
}
// Keep our TCP packets coming without any delays.
SetSocketOption (m_fd_send, IPPROTO_TCP, TCP_NODELAY, 1);
if (error_ptr)
error_ptr->Clear();
return eConnectionStatusSuccess;
}
ConnectionStatus
ConnectionFileDescriptor::ConnectUDP (const char *host_and_port, Error *error_ptr)
{
Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
if (log)
log->Printf ("%p ConnectionFileDescriptor::ConnectUDP (host/port = %s)", this, host_and_port);
Disconnect (NULL);
m_fd_send_type = m_fd_recv_type = eFDTypeSocketUDP;
std::string host_str;
std::string port_str;
int32_t port = INT32_MIN;
if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, error_ptr))
return eConnectionStatusError;
// Setup the receiving end of the UDP connection on this localhost
// on port zero. After we bind to port zero we can read the port.
m_fd_recv = ::socket (AF_INET, SOCK_DGRAM, 0);
if (m_fd_recv == -1)
{
// Socket creation failed...
if (error_ptr)
error_ptr->SetErrorToErrno();
}
else
{
// Socket was created, now lets bind to the requested port
SocketAddress addr;
addr.SetToLocalhost (AF_INET, 0);
if (::bind (m_fd_recv, addr, addr.GetLength()) == -1)
{
// Bind failed...
if (error_ptr)
error_ptr->SetErrorToErrno();
Disconnect (NULL);
}
}
if (m_fd_recv == -1)
return eConnectionStatusError;
// At this point we have setup the recieve port, now we need to
// setup the UDP send socket
struct addrinfo hints;
struct addrinfo *service_info_list = NULL;
::memset (&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
int err = ::getaddrinfo (host_str.c_str(), port_str.c_str(), &hints, &service_info_list);
if (err != 0)
{
if (error_ptr)
error_ptr->SetErrorStringWithFormat("getaddrinfo(%s, %s, &hints, &info) returned error %i (%s)",
host_str.c_str(),
port_str.c_str(),
err,
gai_strerror(err));
Disconnect (NULL);
return eConnectionStatusError;
}
for (struct addrinfo *service_info_ptr = service_info_list;
service_info_ptr != NULL;
service_info_ptr = service_info_ptr->ai_next)
{
m_fd_send = ::socket (service_info_ptr->ai_family,
service_info_ptr->ai_socktype,
service_info_ptr->ai_protocol);
if (m_fd_send != -1)
{
*m_udp_send_sockaddr = service_info_ptr;
break;
}
else
continue;
}
:: freeaddrinfo (service_info_list);
if (m_fd_send == -1)
{
Disconnect (NULL);
return eConnectionStatusError;
}
if (error_ptr)
error_ptr->Clear();
m_should_close_fd = true;
return eConnectionStatusSuccess;
}
#if defined(_WIN32)
typedef const char * set_socket_option_arg_type;
typedef char * get_socket_option_arg_type;
#else // #if defined(_WIN32)
typedef const void * set_socket_option_arg_type;
typedef void * get_socket_option_arg_type;
#endif // #if defined(_WIN32)
int
ConnectionFileDescriptor::GetSocketOption(int fd, int level, int option_name, int &option_value)
{
get_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
socklen_t option_value_size = sizeof(int);
return ::getsockopt(fd, level, option_name, option_value_p, &option_value_size);
}
int
ConnectionFileDescriptor::SetSocketOption(int fd, int level, int option_name, int option_value)
{
set_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
return ::setsockopt(fd, level, option_name, option_value_p, sizeof(option_value));
}
bool
ConnectionFileDescriptor::SetSocketReceiveTimeout (uint32_t timeout_usec)
{
switch (m_fd_recv_type)
{
case eFDTypeFile: // Other FD requireing read/write
break;
case eFDTypeSocket: // Socket requiring send/recv
case eFDTypeSocketUDP: // Unconnected UDP socket requiring sendto/recvfrom
{
// Check in case timeout for m_fd has already been set to this value
if (timeout_usec == m_socket_timeout_usec)
return true;
//printf ("ConnectionFileDescriptor::SetSocketReceiveTimeout (timeout_usec = %u)\n", timeout_usec);
struct timeval timeout;
if (timeout_usec == UINT32_MAX)
{
timeout.tv_sec = 0;
timeout.tv_usec = 0;
}
else if (timeout_usec == 0)
{
// Sending in zero does an infinite timeout, so set this as low
// as we can go to get an effective zero timeout...
timeout.tv_sec = 0;
timeout.tv_usec = 1;
}
else
{
timeout.tv_sec = timeout_usec / TimeValue::MicroSecPerSec;
timeout.tv_usec = timeout_usec % TimeValue::MicroSecPerSec;
}
if (::setsockopt (m_fd_recv, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<get_socket_option_arg_type>(&timeout), sizeof(timeout)) == 0)
{
m_socket_timeout_usec = timeout_usec;
return true;
}
}
}
return false;
}
in_port_t
ConnectionFileDescriptor::GetSocketPort (int fd)
{
// We bound to port zero, so we need to figure out which port we actually bound to
SocketAddress sock_addr;
socklen_t sock_addr_len = sock_addr.GetMaxLength ();
if (::getsockname (fd, sock_addr, &sock_addr_len) == 0)
return sock_addr.GetPort ();
return 0;
}
// If the read file descriptor is a socket, then return
// the port number that is being used by the socket.
in_port_t
ConnectionFileDescriptor::GetReadPort () const
{
return ConnectionFileDescriptor::GetSocketPort (m_fd_recv);
}
// If the write file descriptor is a socket, then return
// the port number that is being used by the socket.
in_port_t
ConnectionFileDescriptor::GetWritePort () const
{
return ConnectionFileDescriptor::GetSocketPort (m_fd_send);
}
|