Fix: strip --strip-debug breaks relocations
[binutils-gdb.git] / gdb / ser-tcp.c
blobcfd1343eced7dac24b68b9c00eb203fb33463e57
1 /* Serial interface for raw TCP connections on Un*x like systems.
3 Copyright (C) 1992-2023 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 #include "defs.h"
21 #include "serial.h"
22 #include "ser-base.h"
23 #include "ser-tcp.h"
24 #include "gdbcmd.h"
25 #include "cli/cli-decode.h"
26 #include "cli/cli-setshow.h"
27 #include "gdbsupport/filestuff.h"
28 #include "gdbsupport/netstuff.h"
30 #include <sys/types.h>
32 #ifdef HAVE_SYS_FILIO_H
33 #include <sys/filio.h>
34 #endif
35 #ifdef HAVE_SYS_IOCTL_H
36 #include <sys/ioctl.h>
37 #endif
39 #include "gdbsupport/gdb_sys_time.h"
41 #ifdef USE_WIN32API
42 #include <ws2tcpip.h>
43 #ifndef ETIMEDOUT
44 #define ETIMEDOUT WSAETIMEDOUT
45 #endif
46 /* Gnulib defines close too, but gnulib's replacement
47 doesn't call closesocket unless we import the
48 socketlib module. */
49 #undef close
50 #define close(fd) closesocket (fd)
51 #define ioctl ioctlsocket
52 #else
53 #include <netinet/in.h>
54 #include <arpa/inet.h>
55 #include <netdb.h>
56 #include <sys/socket.h>
57 #include <netinet/tcp.h>
58 #endif
60 #include <signal.h>
61 #include "gdbsupport/gdb_select.h"
62 #include <algorithm>
64 #ifndef HAVE_SOCKLEN_T
65 typedef int socklen_t;
66 #endif
68 /* For "set tcp" and "show tcp". */
70 static struct cmd_list_element *tcp_set_cmdlist;
71 static struct cmd_list_element *tcp_show_cmdlist;
73 /* Whether to auto-retry refused connections. */
75 static bool tcp_auto_retry = true;
77 /* Timeout period for connections, in seconds. */
79 static unsigned int tcp_retry_limit = 15;
81 /* How many times per second to poll deprecated_ui_loop_hook. */
83 #define POLL_INTERVAL 5
85 /* Helper function to wait a while. If SOCK is not -1, wait on its
86 file descriptor. Otherwise just wait on a timeout, updating
87 *POLLS. Returns -1 on timeout or interrupt and set OUT_ERROR,
88 otherwise the value of select. */
90 static int
91 wait_for_connect (int sock, unsigned int *polls, ULONGEST *out_error)
93 struct timeval t;
94 int n;
96 /* While we wait for the connect to complete,
97 poll the UI so it can update or the user can
98 interrupt. */
99 if (deprecated_ui_loop_hook && deprecated_ui_loop_hook (0))
101 *out_error = EINTR;
102 return -1;
105 /* Check for timeout. */
106 if (*polls > tcp_retry_limit * POLL_INTERVAL)
108 *out_error = ETIMEDOUT;
109 return -1;
112 /* Back off to polling once per second after the first POLL_INTERVAL
113 polls. */
114 if (*polls < POLL_INTERVAL)
116 t.tv_sec = 0;
117 t.tv_usec = 1000000 / POLL_INTERVAL;
119 else
121 t.tv_sec = 1;
122 t.tv_usec = 0;
125 if (sock >= 0)
127 fd_set rset, wset, eset;
129 FD_ZERO (&rset);
130 FD_SET (sock, &rset);
131 wset = rset;
132 eset = rset;
134 /* POSIX systems return connection success or failure by signalling
135 wset. Windows systems return success in wset and failure in
136 eset.
138 We must call select here, rather than gdb_select, because
139 the serial structure has not yet been initialized - the
140 MinGW select wrapper will not know that this FD refers
141 to a socket. */
142 n = select (sock + 1, &rset, &wset, &eset, &t);
144 else
145 /* Use gdb_select here, since we have no file descriptors, and on
146 Windows, plain select doesn't work in that case. */
147 n = interruptible_select (0, NULL, NULL, NULL, &t);
149 /* If we didn't time out, only count it as one poll. */
150 if (n > 0 || *polls < POLL_INTERVAL)
151 (*polls)++;
152 else
153 (*polls) += POLL_INTERVAL;
155 return n;
158 /* A helper to get the error number for either Windows or POSIX. */
159 static ULONGEST
160 get_error ()
162 #ifdef USE_WIN32API
163 return WSAGetLastError ();
164 #else
165 return errno;
166 #endif
169 /* Try to connect to the host represented by AINFO. If the connection
170 succeeds, return its socket. Otherwise, return -1 and set OUT_ERROR
171 accordingly. POLLS is used when 'connect' returns EINPROGRESS, and
172 we need to invoke 'wait_for_connect' to obtain the status. */
174 static int
175 try_connect (const struct addrinfo *ainfo, unsigned int *polls,
176 ULONGEST *out_error)
178 int sock = gdb_socket_cloexec (ainfo->ai_family, ainfo->ai_socktype,
179 ainfo->ai_protocol);
181 if (sock < 0)
183 *out_error = get_error ();
184 return -1;
187 /* Set socket nonblocking. */
188 #ifdef USE_WIN32API
189 u_long ioarg = 1;
190 #else
191 int ioarg = 1;
192 #endif
194 ioctl (sock, FIONBIO, &ioarg);
196 /* Use Non-blocking connect. connect() will return 0 if connected
197 already. */
198 if (connect (sock, ainfo->ai_addr, ainfo->ai_addrlen) < 0)
200 ULONGEST err = get_error ();
202 /* If we've got a "connection refused" error, just return
203 -1. The caller will know what to do. */
204 if (
205 #ifdef USE_WIN32API
206 err == WSAECONNREFUSED
207 #else
208 err == ECONNREFUSED
209 #endif
212 close (sock);
213 *out_error = err;
214 return -1;
217 if (
218 /* Any other error (except EINPROGRESS) will be "swallowed"
219 here. We return without specifying a return value, and
220 set errno if the caller wants to inspect what
221 happened. */
222 #ifdef USE_WIN32API
223 /* Under Windows, calling "connect" with a non-blocking socket
224 results in WSAEWOULDBLOCK, not WSAEINPROGRESS. */
225 err != WSAEWOULDBLOCK
226 #else
227 err != EINPROGRESS
228 #endif
231 close (sock);
232 *out_error = err;
233 return -1;
236 /* Looks like we need to wait for the connect. */
237 int n;
240 n = wait_for_connect (sock, polls, out_error);
241 while (n == 0);
243 if (n < 0)
245 /* A negative value here means that we either timed out or
246 got interrupted by the user. Just return. */
247 close (sock);
248 /* OUT_ERROR was set by wait_for_connect, above. */
249 return -1;
253 /* Got something. Is it an error? */
254 int err;
255 socklen_t len = sizeof (err);
257 /* On Windows, the fourth parameter to getsockopt is a "char *";
258 on UNIX systems it is generally "void *". The cast to "char *"
259 is OK everywhere, since in C++ any data pointer type can be
260 implicitly converted to "void *". */
261 int ret = getsockopt (sock, SOL_SOCKET, SO_ERROR, (char *) &err, &len);
263 if (ret < 0)
265 *out_error = get_error ();
266 close (sock);
267 return -1;
269 else if (ret == 0 && err != 0)
271 *out_error = err;
272 close (sock);
273 return -1;
276 /* The connection succeeded. Return the socket. */
277 return sock;
280 /* Open a tcp socket. */
282 void
283 net_open (struct serial *scb, const char *name)
285 struct addrinfo hint;
286 struct addrinfo *ainfo;
288 memset (&hint, 0, sizeof (hint));
289 /* Assume no prefix will be passed, therefore we should use
290 AF_UNSPEC. */
291 hint.ai_family = AF_UNSPEC;
292 hint.ai_socktype = SOCK_STREAM;
293 hint.ai_protocol = IPPROTO_TCP;
295 parsed_connection_spec parsed = parse_connection_spec (name, &hint);
297 if (parsed.port_str.empty ())
298 error (_("Missing port on hostname '%s'"), name);
300 int r = getaddrinfo (parsed.host_str.c_str (),
301 parsed.port_str.c_str (),
302 &hint, &ainfo);
304 if (r != 0)
305 error (_("%s: cannot resolve name: %s\n"), name, gai_strerror (r));
307 scoped_free_addrinfo free_ainfo (ainfo);
309 /* Flag to indicate whether we've got a connection refused. It will
310 be true if any of the connections tried was refused. */
311 bool got_connrefused;
312 /* If a connection succeeds, SUCCESS_AINFO will point to the
313 'struct addrinfo' that succeed. */
314 struct addrinfo *success_ainfo = NULL;
315 unsigned int polls = 0;
316 ULONGEST last_error = 0;
318 /* Assume the worst. */
319 scb->fd = -1;
323 got_connrefused = false;
325 for (addrinfo *iter = ainfo; iter != NULL; iter = iter->ai_next)
327 /* Iterate over the list of possible addresses to connect
328 to. For each, we'll try to connect and see if it
329 succeeds. */
330 int sock = try_connect (iter, &polls, &last_error);
332 if (sock >= 0)
334 /* We've gotten a successful connection. Save its
335 'struct addrinfo', the socket, and break. */
336 success_ainfo = iter;
337 scb->fd = sock;
338 break;
340 else if (
341 #ifdef USE_WIN32API
342 last_error == WSAECONNREFUSED
343 #else
344 last_error == ECONNREFUSED
345 #endif
347 got_connrefused = true;
350 /* Just retry if:
352 - tcp_auto_retry is true, and
353 - We haven't gotten a connection yet, and
354 - Any of our connection attempts returned with ECONNREFUSED, and
355 - wait_for_connect signals that we can keep going. */
356 while (tcp_auto_retry
357 && success_ainfo == NULL
358 && got_connrefused
359 && wait_for_connect (-1, &polls, &last_error) >= 0);
361 if (success_ainfo == NULL)
363 net_close (scb);
364 #ifdef USE_WIN32API
365 throw_winerror_with_name (_("could not connect"), last_error);
366 #else
367 perror_with_name (_("could not connect"), last_error);
368 #endif
371 /* Turn off nonblocking. */
372 #ifdef USE_WIN32API
373 u_long ioarg = 0;
374 #else
375 int ioarg = 0;
376 #endif
378 ioctl (scb->fd, FIONBIO, &ioarg);
380 if (success_ainfo->ai_protocol == IPPROTO_TCP)
382 /* Disable Nagle algorithm. Needed in some cases. */
383 int tmp = 1;
385 setsockopt (scb->fd, IPPROTO_TCP, TCP_NODELAY,
386 (char *) &tmp, sizeof (tmp));
389 #ifdef SIGPIPE
390 /* If we don't do this, then GDB simply exits
391 when the remote side dies. */
392 signal (SIGPIPE, SIG_IGN);
393 #endif
396 void
397 net_close (struct serial *scb)
399 if (scb->fd == -1)
400 return;
402 close (scb->fd);
403 scb->fd = -1;
407 net_read_prim (struct serial *scb, size_t count)
409 /* Need to cast to silence -Wpointer-sign on MinGW, as Winsock's
410 'recv' takes 'char *' as second argument, while 'scb->buf' is
411 'unsigned char *'. */
412 int result = recv (scb->fd, (char *) scb->buf, count, 0);
413 if (result == -1 && errno != EINTR)
414 perror_with_name ("error while reading");
415 return result;
419 net_write_prim (struct serial *scb, const void *buf, size_t count)
421 /* On Windows, the second parameter to send is a "const char *"; on
422 UNIX systems it is generally "const void *". The cast to "const
423 char *" is OK everywhere, since in C++ any data pointer type can
424 be implicitly converted to "const void *". */
425 int result = send (scb->fd, (const char *) buf, count, 0);
426 if (result == -1 && errno != EINTR)
427 perror_with_name ("error while writing");
428 return result;
431 void
432 ser_tcp_send_break (struct serial *scb)
434 /* Send telnet IAC and BREAK characters. */
435 serial_write (scb, "\377\363", 2);
438 #ifndef USE_WIN32API
440 /* The TCP ops. */
442 static const struct serial_ops tcp_ops =
444 "tcp",
445 net_open,
446 net_close,
447 NULL,
448 ser_base_readchar,
449 ser_base_write,
450 ser_base_flush_output,
451 ser_base_flush_input,
452 ser_tcp_send_break,
453 ser_base_raw,
454 ser_base_get_tty_state,
455 ser_base_copy_tty_state,
456 ser_base_set_tty_state,
457 ser_base_print_tty_state,
458 ser_base_setbaudrate,
459 ser_base_setstopbits,
460 ser_base_setparity,
461 ser_base_drain_output,
462 ser_base_async,
463 net_read_prim,
464 net_write_prim
467 #endif /* USE_WIN32API */
469 void _initialize_ser_tcp ();
470 void
471 _initialize_ser_tcp ()
473 #ifdef USE_WIN32API
474 /* Do nothing; the TCP serial operations will be initialized in
475 ser-mingw.c. */
476 #else
477 serial_add_interface (&tcp_ops);
478 #endif /* USE_WIN32API */
480 add_setshow_prefix_cmd ("tcp", class_maintenance,
481 _("\
482 TCP protocol specific variables.\n\
483 Configure variables specific to remote TCP connections."),
484 _("\
485 TCP protocol specific variables.\n\
486 Configure variables specific to remote TCP connections."),
487 &tcp_set_cmdlist, &tcp_show_cmdlist,
488 &setlist, &showlist);
490 add_setshow_boolean_cmd ("auto-retry", class_obscure,
491 &tcp_auto_retry, _("\
492 Set auto-retry on socket connect."), _("\
493 Show auto-retry on socket connect."),
494 NULL, NULL, NULL,
495 &tcp_set_cmdlist, &tcp_show_cmdlist);
497 add_setshow_uinteger_cmd ("connect-timeout", class_obscure,
498 &tcp_retry_limit, _("\
499 Set timeout limit in seconds for socket connection."), _("\
500 Show timeout limit in seconds for socket connection."), _("\
501 If set to \"unlimited\", GDB will keep attempting to establish a\n\
502 connection forever, unless interrupted with Ctrl-c.\n\
503 The default is 15 seconds."),
504 NULL, NULL,
505 &tcp_set_cmdlist, &tcp_show_cmdlist);