Upgrade GDB from 7.4.1 to 7.6.1 on the vendor branch
[dragonfly.git] / contrib / gdb-7 / gdb / remote.c
CommitLineData
5796c8dc
SS
1/* Remote target communications for serial-line targets in custom GDB protocol
2
ef5ccd6c 3 Copyright (C) 1988-2013 Free Software Foundation, Inc.
5796c8dc
SS
4
5 This file is part of GDB.
6
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.
11
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.
16
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/>. */
19
20/* See the GDB User Guide for details of the GDB remote protocol. */
21
22#include "defs.h"
23#include "gdb_string.h"
24#include <ctype.h>
25#include <fcntl.h>
26#include "inferior.h"
27#include "bfd.h"
28#include "symfile.h"
29#include "exceptions.h"
30#include "target.h"
31/*#include "terminal.h" */
32#include "gdbcmd.h"
33#include "objfiles.h"
34#include "gdb-stabs.h"
35#include "gdbthread.h"
36#include "remote.h"
ef5ccd6c 37#include "remote-notif.h"
5796c8dc
SS
38#include "regcache.h"
39#include "value.h"
40#include "gdb_assert.h"
41#include "observer.h"
42#include "solib.h"
43#include "cli/cli-decode.h"
44#include "cli/cli-setshow.h"
45#include "target-descriptions.h"
ef5ccd6c 46#include "gdb_bfd.h"
5796c8dc
SS
47
48#include <ctype.h>
49#include <sys/time.h>
50
51#include "event-loop.h"
52#include "event-top.h"
53#include "inf-loop.h"
54
55#include <signal.h>
56#include "serial.h"
57
58#include "gdbcore.h" /* for exec_bfd */
59
60#include "remote-fileio.h"
61#include "gdb/fileio.h"
62#include "gdb_stat.h"
cf7f2e2d 63#include "xml-support.h"
5796c8dc
SS
64
65#include "memory-map.h"
66
cf7f2e2d
JM
67#include "tracepoint.h"
68#include "ax.h"
69#include "ax-gdb.h"
ef5ccd6c
JM
70#include "agent.h"
71#include "btrace.h"
cf7f2e2d 72
c50c785c 73/* Temp hacks for tracepoint encoding migration. */
cf7f2e2d
JM
74static char *target_buf;
75static long target_buf_size;
cf7f2e2d 76
5796c8dc
SS
77/* The size to align memory write packets, when practical. The protocol
78 does not guarantee any alignment, and gdb will generate short
79 writes and unaligned writes, but even as a best-effort attempt this
80 can improve bulk transfers. For instance, if a write is misaligned
81 relative to the target's data bus, the stub may need to make an extra
82 round trip fetching data from the target. This doesn't make a
83 huge difference, but it's easy to do, so we try to be helpful.
84
85 The alignment chosen is arbitrary; usually data bus width is
86 important here, not the possibly larger cache line size. */
87enum { REMOTE_ALIGN_WRITES = 16 };
88
89/* Prototypes for local functions. */
90static void cleanup_sigint_signal_handler (void *dummy);
91static void initialize_sigint_signal_handler (void);
92static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
93static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
ef5ccd6c 94 int forever, int *is_notif);
5796c8dc
SS
95
96static void handle_remote_sigint (int);
97static void handle_remote_sigint_twice (int);
98static void async_remote_interrupt (gdb_client_data);
99void async_remote_interrupt_twice (gdb_client_data);
100
101static void remote_files_info (struct target_ops *ignore);
102
103static void remote_prepare_to_store (struct regcache *regcache);
104
105static void remote_open (char *name, int from_tty);
106
107static void extended_remote_open (char *name, int from_tty);
108
109static void remote_open_1 (char *, int, struct target_ops *, int extended_p);
110
111static void remote_close (int quitting);
112
113static void remote_mourn (struct target_ops *ops);
114
115static void extended_remote_restart (void);
116
117static void extended_remote_mourn (struct target_ops *);
118
119static void remote_mourn_1 (struct target_ops *);
120
121static void remote_send (char **buf, long *sizeof_buf_p);
122
123static int readchar (int timeout);
124
ef5ccd6c
JM
125static void remote_serial_write (const char *str, int len);
126
5796c8dc
SS
127static void remote_kill (struct target_ops *ops);
128
129static int tohex (int nib);
130
131static int remote_can_async_p (void);
132
133static int remote_is_async_p (void);
134
135static void remote_async (void (*callback) (enum inferior_event_type event_type,
136 void *context), void *context);
137
5796c8dc
SS
138static void remote_detach (struct target_ops *ops, char *args, int from_tty);
139
140static void remote_interrupt (int signo);
141
142static void remote_interrupt_twice (int signo);
143
144static void interrupt_query (void);
145
146static void set_general_thread (struct ptid ptid);
147static void set_continue_thread (struct ptid ptid);
148
149static void get_offsets (void);
150
151static void skip_frame (void);
152
153static long read_frame (char **buf_p, long *sizeof_buf);
154
155static int hexnumlen (ULONGEST num);
156
157static void init_remote_ops (void);
158
159static void init_extended_remote_ops (void);
160
161static void remote_stop (ptid_t);
162
163static int ishex (int ch, int *val);
164
165static int stubhex (int ch);
166
167static int hexnumstr (char *, ULONGEST);
168
169static int hexnumnstr (char *, ULONGEST, int);
170
171static CORE_ADDR remote_address_masked (CORE_ADDR);
172
173static void print_packet (char *);
174
5796c8dc
SS
175static void compare_sections_command (char *, int);
176
177static void packet_command (char *, int);
178
179static int stub_unpack_int (char *buff, int fieldlength);
180
181static ptid_t remote_current_thread (ptid_t oldptid);
182
183static void remote_find_new_threads (void);
184
185static void record_currthread (ptid_t currthread);
186
187static int fromhex (int a);
188
5796c8dc
SS
189static int putpkt_binary (char *buf, int cnt);
190
191static void check_binary_download (CORE_ADDR addr);
192
193struct packet_config;
194
195static void show_packet_config_cmd (struct packet_config *config);
196
197static void update_packet_config (struct packet_config *config);
198
199static void set_remote_protocol_packet_cmd (char *args, int from_tty,
200 struct cmd_list_element *c);
201
202static void show_remote_protocol_packet_cmd (struct ui_file *file,
203 int from_tty,
204 struct cmd_list_element *c,
205 const char *value);
206
207static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
208static ptid_t read_ptid (char *buf, char **obuf);
209
cf7f2e2d
JM
210static void remote_set_permissions (void);
211
212struct remote_state;
213static int remote_get_trace_status (struct trace_status *ts);
214
215static int remote_upload_tracepoints (struct uploaded_tp **utpp);
216
217static int remote_upload_trace_state_variables (struct uploaded_tsv **utsvp);
218
5796c8dc
SS
219static void remote_query_supported (void);
220
221static void remote_check_symbols (struct objfile *objfile);
222
223void _initialize_remote (void);
224
225struct stop_reply;
5796c8dc 226static void stop_reply_xfree (struct stop_reply *);
ef5ccd6c 227static void remote_parse_stop_reply (char *, struct stop_reply *);
5796c8dc 228static void push_stop_reply (struct stop_reply *);
ef5ccd6c 229static void discard_pending_stop_replies (struct inferior *);
5796c8dc
SS
230static int peek_stop_reply (ptid_t ptid);
231
232static void remote_async_inferior_event_handler (gdb_client_data);
5796c8dc
SS
233
234static void remote_terminal_ours (void);
235
236static int remote_read_description_p (struct target_ops *target);
237
cf7f2e2d
JM
238static void remote_console_output (char *msg);
239
ef5ccd6c 240static int remote_supports_cond_breakpoints (void);
5796c8dc 241
ef5ccd6c 242static int remote_can_run_breakpoint_commands (void);
5796c8dc
SS
243
244/* For "remote". */
245
246static struct cmd_list_element *remote_cmdlist;
247
248/* For "set remote" and "show remote". */
249
250static struct cmd_list_element *remote_set_cmdlist;
251static struct cmd_list_element *remote_show_cmdlist;
252
253/* Description of the remote protocol state for the currently
254 connected target. This is per-target state, and independent of the
255 selected architecture. */
256
257struct remote_state
258{
259 /* A buffer to use for incoming packets, and its current size. The
260 buffer is grown dynamically for larger incoming packets.
261 Outgoing packets may also be constructed in this buffer.
262 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
263 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
264 packets. */
265 char *buf;
266 long buf_size;
267
a45ae5f8
JM
268 /* True if we're going through initial connection setup (finding out
269 about the remote side's threads, relocating symbols, etc.). */
270 int starting_up;
271
5796c8dc
SS
272 /* If we negotiated packet size explicitly (and thus can bypass
273 heuristics for the largest packet size that will not overflow
274 a buffer in the stub), this will be set to that packet size.
275 Otherwise zero, meaning to use the guessed size. */
276 long explicit_packet_size;
277
278 /* remote_wait is normally called when the target is running and
279 waits for a stop reply packet. But sometimes we need to call it
280 when the target is already stopped. We can send a "?" packet
281 and have remote_wait read the response. Or, if we already have
282 the response, we can stash it in BUF and tell remote_wait to
283 skip calling getpkt. This flag is set when BUF contains a
284 stop reply packet and the target is not waiting. */
285 int cached_wait_status;
286
287 /* True, if in no ack mode. That is, neither GDB nor the stub will
288 expect acks from each other. The connection is assumed to be
289 reliable. */
290 int noack_mode;
291
292 /* True if we're connected in extended remote mode. */
293 int extended;
294
295 /* True if the stub reported support for multi-process
296 extensions. */
297 int multi_process_aware;
298
299 /* True if we resumed the target and we're waiting for the target to
300 stop. In the mean time, we can't start another command/query.
301 The remote server wouldn't be ready to process it, so we'd
302 timeout waiting for a reply that would never come and eventually
303 we'd close the connection. This can happen in asynchronous mode
304 because we allow GDB commands while the target is running. */
305 int waiting_for_stop_reply;
306
307 /* True if the stub reports support for non-stop mode. */
308 int non_stop_aware;
309
310 /* True if the stub reports support for vCont;t. */
311 int support_vCont_t;
312
313 /* True if the stub reports support for conditional tracepoints. */
314 int cond_tracepoints;
cf7f2e2d 315
ef5ccd6c
JM
316 /* True if the stub reports support for target-side breakpoint
317 conditions. */
318 int cond_breakpoints;
319
320 /* True if the stub reports support for target-side breakpoint
321 commands. */
322 int breakpoint_commands;
323
cf7f2e2d
JM
324 /* True if the stub reports support for fast tracepoints. */
325 int fast_tracepoints;
326
327 /* True if the stub reports support for static tracepoints. */
328 int static_tracepoints;
329
a45ae5f8
JM
330 /* True if the stub reports support for installing tracepoint while
331 tracing. */
332 int install_in_trace;
333
cf7f2e2d
JM
334 /* True if the stub can continue running a trace while GDB is
335 disconnected. */
336 int disconnected_tracing;
337
a45ae5f8
JM
338 /* True if the stub reports support for enabling and disabling
339 tracepoints while a trace experiment is running. */
340 int enable_disable_tracepoints;
341
342 /* True if the stub can collect strings using tracenz bytecode. */
343 int string_tracing;
344
cf7f2e2d
JM
345 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
346 responded to that. */
347 int ctrlc_pending_p;
5796c8dc
SS
348};
349
cf7f2e2d
JM
350/* Private data that we'll store in (struct thread_info)->private. */
351struct private_thread_info
352{
353 char *extra;
354 int core;
355};
356
357static void
358free_private_thread_info (struct private_thread_info *info)
359{
360 xfree (info->extra);
361 xfree (info);
362}
363
5796c8dc
SS
364/* Returns true if the multi-process extensions are in effect. */
365static int
366remote_multi_process_p (struct remote_state *rs)
367{
ef5ccd6c 368 return rs->multi_process_aware;
5796c8dc
SS
369}
370
371/* This data could be associated with a target, but we do not always
372 have access to the current target when we need it, so for now it is
373 static. This will be fine for as long as only one target is in use
374 at a time. */
375static struct remote_state remote_state;
376
377static struct remote_state *
378get_remote_state_raw (void)
379{
380 return &remote_state;
381}
382
383/* Description of the remote protocol for a given architecture. */
384
385struct packet_reg
386{
387 long offset; /* Offset into G packet. */
388 long regnum; /* GDB's internal register number. */
389 LONGEST pnum; /* Remote protocol register number. */
390 int in_g_packet; /* Always part of G packet. */
ef5ccd6c 391 /* long size in bytes; == register_size (target_gdbarch (), regnum);
5796c8dc 392 at present. */
ef5ccd6c 393 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
5796c8dc
SS
394 at present. */
395};
396
397struct remote_arch_state
398{
399 /* Description of the remote protocol registers. */
400 long sizeof_g_packet;
401
402 /* Description of the remote protocol registers indexed by REGNUM
403 (making an array gdbarch_num_regs in size). */
404 struct packet_reg *regs;
405
406 /* This is the size (in chars) of the first response to the ``g''
407 packet. It is used as a heuristic when determining the maximum
408 size of memory-read and memory-write packets. A target will
409 typically only reserve a buffer large enough to hold the ``g''
410 packet. The size does not include packet overhead (headers and
411 trailers). */
412 long actual_register_packet_size;
413
414 /* This is the maximum size (in chars) of a non read/write packet.
415 It is also used as a cap on the size of read/write packets. */
416 long remote_packet_size;
417};
418
cf7f2e2d
JM
419long sizeof_pkt = 2000;
420
421/* Utility: generate error from an incoming stub packet. */
422static void
423trace_error (char *buf)
424{
425 if (*buf++ != 'E')
426 return; /* not an error msg */
427 switch (*buf)
428 {
429 case '1': /* malformed packet error */
430 if (*++buf == '0') /* general case: */
431 error (_("remote.c: error in outgoing packet."));
432 else
433 error (_("remote.c: error in outgoing packet at field #%ld."),
434 strtol (buf, NULL, 16));
cf7f2e2d
JM
435 default:
436 error (_("Target returns error code '%s'."), buf);
437 }
438}
439
440/* Utility: wait for reply from stub, while accepting "O" packets. */
441static char *
442remote_get_noisy_reply (char **buf_p,
443 long *sizeof_buf)
444{
445 do /* Loop on reply from remote stub. */
446 {
447 char *buf;
448
c50c785c 449 QUIT; /* Allow user to bail out with ^C. */
cf7f2e2d
JM
450 getpkt (buf_p, sizeof_buf, 0);
451 buf = *buf_p;
452 if (buf[0] == 'E')
453 trace_error (buf);
454 else if (strncmp (buf, "qRelocInsn:", strlen ("qRelocInsn:")) == 0)
455 {
456 ULONGEST ul;
457 CORE_ADDR from, to, org_to;
458 char *p, *pp;
459 int adjusted_size = 0;
460 volatile struct gdb_exception ex;
461
462 p = buf + strlen ("qRelocInsn:");
463 pp = unpack_varlen_hex (p, &ul);
464 if (*pp != ';')
465 error (_("invalid qRelocInsn packet: %s"), buf);
466 from = ul;
467
468 p = pp + 1;
c50c785c 469 unpack_varlen_hex (p, &ul);
cf7f2e2d
JM
470 to = ul;
471
472 org_to = to;
473
474 TRY_CATCH (ex, RETURN_MASK_ALL)
475 {
ef5ccd6c 476 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
cf7f2e2d
JM
477 }
478 if (ex.reason >= 0)
479 {
480 adjusted_size = to - org_to;
481
ef5ccd6c 482 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
cf7f2e2d
JM
483 putpkt (buf);
484 }
485 else if (ex.reason < 0 && ex.error == MEMORY_ERROR)
486 {
487 /* Propagate memory errors silently back to the target.
488 The stub may have limited the range of addresses we
489 can write to, for example. */
490 putpkt ("E01");
491 }
492 else
493 {
494 /* Something unexpectedly bad happened. Be verbose so
495 we can tell what, and propagate the error back to the
496 stub, so it doesn't get stuck waiting for a
497 response. */
498 exception_fprintf (gdb_stderr, ex,
499 _("warning: relocating instruction: "));
500 putpkt ("E01");
501 }
502 }
503 else if (buf[0] == 'O' && buf[1] != 'K')
504 remote_console_output (buf + 1); /* 'O' message from stub */
505 else
c50c785c 506 return buf; /* Here's the actual reply. */
cf7f2e2d
JM
507 }
508 while (1);
509}
5796c8dc
SS
510
511/* Handle for retreving the remote protocol data from gdbarch. */
512static struct gdbarch_data *remote_gdbarch_data_handle;
513
514static struct remote_arch_state *
515get_remote_arch_state (void)
516{
ef5ccd6c 517 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
5796c8dc
SS
518}
519
520/* Fetch the global remote target state. */
521
522static struct remote_state *
523get_remote_state (void)
524{
525 /* Make sure that the remote architecture state has been
526 initialized, because doing so might reallocate rs->buf. Any
527 function which calls getpkt also needs to be mindful of changes
528 to rs->buf, but this call limits the number of places which run
529 into trouble. */
530 get_remote_arch_state ();
531
532 return get_remote_state_raw ();
533}
534
535static int
536compare_pnums (const void *lhs_, const void *rhs_)
537{
538 const struct packet_reg * const *lhs = lhs_;
539 const struct packet_reg * const *rhs = rhs_;
540
541 if ((*lhs)->pnum < (*rhs)->pnum)
542 return -1;
543 else if ((*lhs)->pnum == (*rhs)->pnum)
544 return 0;
545 else
546 return 1;
547}
548
a45ae5f8
JM
549static int
550map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
5796c8dc
SS
551{
552 int regnum, num_remote_regs, offset;
5796c8dc
SS
553 struct packet_reg **remote_regs;
554
5796c8dc
SS
555 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
556 {
a45ae5f8 557 struct packet_reg *r = &regs[regnum];
5796c8dc
SS
558
559 if (register_size (gdbarch, regnum) == 0)
560 /* Do not try to fetch zero-sized (placeholder) registers. */
561 r->pnum = -1;
562 else
563 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
564
565 r->regnum = regnum;
566 }
567
568 /* Define the g/G packet format as the contents of each register
569 with a remote protocol number, in order of ascending protocol
570 number. */
571
572 remote_regs = alloca (gdbarch_num_regs (gdbarch)
a45ae5f8 573 * sizeof (struct packet_reg *));
5796c8dc
SS
574 for (num_remote_regs = 0, regnum = 0;
575 regnum < gdbarch_num_regs (gdbarch);
576 regnum++)
a45ae5f8
JM
577 if (regs[regnum].pnum != -1)
578 remote_regs[num_remote_regs++] = &regs[regnum];
5796c8dc
SS
579
580 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
581 compare_pnums);
582
583 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
584 {
585 remote_regs[regnum]->in_g_packet = 1;
586 remote_regs[regnum]->offset = offset;
587 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
588 }
589
a45ae5f8
JM
590 return offset;
591}
592
593/* Given the architecture described by GDBARCH, return the remote
594 protocol register's number and the register's offset in the g/G
595 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
596 If the target does not have a mapping for REGNUM, return false,
597 otherwise, return true. */
598
599int
600remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
601 int *pnum, int *poffset)
602{
603 int sizeof_g_packet;
604 struct packet_reg *regs;
605 struct cleanup *old_chain;
606
607 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
608
609 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
610 old_chain = make_cleanup (xfree, regs);
611
612 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
613
614 *pnum = regs[regnum].pnum;
615 *poffset = regs[regnum].offset;
616
617 do_cleanups (old_chain);
618
619 return *pnum != -1;
620}
621
622static void *
623init_remote_state (struct gdbarch *gdbarch)
624{
625 struct remote_state *rs = get_remote_state_raw ();
626 struct remote_arch_state *rsa;
627
628 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
629
630 /* Use the architecture to build a regnum<->pnum table, which will be
631 1:1 unless a feature set specifies otherwise. */
632 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
633 gdbarch_num_regs (gdbarch),
634 struct packet_reg);
635
5796c8dc
SS
636 /* Record the maximum possible size of the g packet - it may turn out
637 to be smaller. */
a45ae5f8 638 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
5796c8dc 639
c50c785c 640 /* Default maximum number of characters in a packet body. Many
5796c8dc
SS
641 remote stubs have a hardwired buffer size of 400 bytes
642 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
643 as the maximum packet-size to ensure that the packet and an extra
644 NUL character can always fit in the buffer. This stops GDB
645 trashing stubs that try to squeeze an extra NUL into what is
646 already a full buffer (As of 1999-12-04 that was most stubs). */
647 rsa->remote_packet_size = 400 - 1;
648
649 /* This one is filled in when a ``g'' packet is received. */
650 rsa->actual_register_packet_size = 0;
651
652 /* Should rsa->sizeof_g_packet needs more space than the
c50c785c
JM
653 default, adjust the size accordingly. Remember that each byte is
654 encoded as two characters. 32 is the overhead for the packet
655 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
5796c8dc
SS
656 (``$NN:G...#NN'') is a better guess, the below has been padded a
657 little. */
658 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
659 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
660
661 /* Make sure that the packet buffer is plenty big enough for
662 this architecture. */
663 if (rs->buf_size < rsa->remote_packet_size)
664 {
665 rs->buf_size = 2 * rsa->remote_packet_size;
666 rs->buf = xrealloc (rs->buf, rs->buf_size);
667 }
668
669 return rsa;
670}
671
672/* Return the current allowed size of a remote packet. This is
673 inferred from the current architecture, and should be used to
674 limit the length of outgoing packets. */
675static long
676get_remote_packet_size (void)
677{
678 struct remote_state *rs = get_remote_state ();
679 struct remote_arch_state *rsa = get_remote_arch_state ();
680
681 if (rs->explicit_packet_size)
682 return rs->explicit_packet_size;
683
684 return rsa->remote_packet_size;
685}
686
687static struct packet_reg *
688packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
689{
ef5ccd6c 690 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
5796c8dc
SS
691 return NULL;
692 else
693 {
694 struct packet_reg *r = &rsa->regs[regnum];
cf7f2e2d 695
5796c8dc
SS
696 gdb_assert (r->regnum == regnum);
697 return r;
698 }
699}
700
701static struct packet_reg *
702packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
703{
704 int i;
cf7f2e2d 705
ef5ccd6c 706 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
5796c8dc
SS
707 {
708 struct packet_reg *r = &rsa->regs[i];
cf7f2e2d 709
5796c8dc
SS
710 if (r->pnum == pnum)
711 return r;
712 }
713 return NULL;
714}
715
716/* FIXME: graces/2002-08-08: These variables should eventually be
717 bound to an instance of the target object (as in gdbarch-tdep()),
718 when such a thing exists. */
719
720/* This is set to the data address of the access causing the target
721 to stop for a watchpoint. */
722static CORE_ADDR remote_watch_data_address;
723
724/* This is non-zero if target stopped for a watchpoint. */
725static int remote_stopped_by_watchpoint_p;
726
727static struct target_ops remote_ops;
728
729static struct target_ops extended_remote_ops;
730
5796c8dc
SS
731/* FIXME: cagney/1999-09-23: Even though getpkt was called with
732 ``forever'' still use the normal timeout mechanism. This is
733 currently used by the ASYNC code to guarentee that target reads
734 during the initial connect always time-out. Once getpkt has been
735 modified to return a timeout indication and, in turn
736 remote_wait()/wait_for_inferior() have gained a timeout parameter
737 this can go away. */
738static int wait_forever_enabled_p = 1;
739
cf7f2e2d
JM
740/* Allow the user to specify what sequence to send to the remote
741 when he requests a program interruption: Although ^C is usually
742 what remote systems expect (this is the default, here), it is
743 sometimes preferable to send a break. On other systems such
744 as the Linux kernel, a break followed by g, which is Magic SysRq g
745 is required in order to interrupt the execution. */
746const char interrupt_sequence_control_c[] = "Ctrl-C";
747const char interrupt_sequence_break[] = "BREAK";
748const char interrupt_sequence_break_g[] = "BREAK-g";
ef5ccd6c 749static const char *const interrupt_sequence_modes[] =
cf7f2e2d
JM
750 {
751 interrupt_sequence_control_c,
752 interrupt_sequence_break,
753 interrupt_sequence_break_g,
754 NULL
755 };
756static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
757
758static void
759show_interrupt_sequence (struct ui_file *file, int from_tty,
760 struct cmd_list_element *c,
761 const char *value)
762{
763 if (interrupt_sequence_mode == interrupt_sequence_control_c)
764 fprintf_filtered (file,
765 _("Send the ASCII ETX character (Ctrl-c) "
766 "to the remote target to interrupt the "
767 "execution of the program.\n"));
768 else if (interrupt_sequence_mode == interrupt_sequence_break)
769 fprintf_filtered (file,
770 _("send a break signal to the remote target "
771 "to interrupt the execution of the program.\n"));
772 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
773 fprintf_filtered (file,
774 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
775 "the remote target to interrupt the execution "
776 "of Linux kernel.\n"));
777 else
778 internal_error (__FILE__, __LINE__,
779 _("Invalid value for interrupt_sequence_mode: %s."),
780 interrupt_sequence_mode);
781}
5796c8dc 782
cf7f2e2d
JM
783/* This boolean variable specifies whether interrupt_sequence is sent
784 to the remote target when gdb connects to it.
785 This is mostly needed when you debug the Linux kernel: The Linux kernel
786 expects BREAK g which is Magic SysRq g for connecting gdb. */
787static int interrupt_on_connect = 0;
5796c8dc 788
cf7f2e2d
JM
789/* This variable is used to implement the "set/show remotebreak" commands.
790 Since these commands are now deprecated in favor of "set/show remote
791 interrupt-sequence", it no longer has any effect on the code. */
5796c8dc
SS
792static int remote_break;
793
cf7f2e2d
JM
794static void
795set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
796{
797 if (remote_break)
798 interrupt_sequence_mode = interrupt_sequence_break;
799 else
800 interrupt_sequence_mode = interrupt_sequence_control_c;
801}
802
803static void
804show_remotebreak (struct ui_file *file, int from_tty,
805 struct cmd_list_element *c,
806 const char *value)
807{
808}
809
5796c8dc
SS
810/* Descriptor for I/O to remote machine. Initialize it to NULL so that
811 remote_open knows that we don't have a file open when the program
812 starts. */
813static struct serial *remote_desc = NULL;
814
815/* This variable sets the number of bits in an address that are to be
816 sent in a memory ("M" or "m") packet. Normally, after stripping
c50c785c 817 leading zeros, the entire address would be sent. This variable
5796c8dc
SS
818 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
819 initial implementation of remote.c restricted the address sent in
820 memory packets to ``host::sizeof long'' bytes - (typically 32
821 bits). Consequently, for 64 bit targets, the upper 32 bits of an
822 address was never sent. Since fixing this bug may cause a break in
823 some remote targets this variable is principly provided to
824 facilitate backward compatibility. */
825
ef5ccd6c 826static unsigned int remote_address_size;
5796c8dc
SS
827
828/* Temporary to track who currently owns the terminal. See
829 remote_terminal_* for more details. */
830
831static int remote_async_terminal_ours_p;
832
833/* The executable file to use for "run" on the remote side. */
834
835static char *remote_exec_file = "";
836
837\f
838/* User configurable variables for the number of characters in a
839 memory read/write packet. MIN (rsa->remote_packet_size,
840 rsa->sizeof_g_packet) is the default. Some targets need smaller
841 values (fifo overruns, et.al.) and some users need larger values
842 (speed up transfers). The variables ``preferred_*'' (the user
843 request), ``current_*'' (what was actually set) and ``forced_*''
844 (Positive - a soft limit, negative - a hard limit). */
845
846struct memory_packet_config
847{
848 char *name;
849 long size;
850 int fixed_p;
851};
852
853/* Compute the current size of a read/write packet. Since this makes
854 use of ``actual_register_packet_size'' the computation is dynamic. */
855
856static long
857get_memory_packet_size (struct memory_packet_config *config)
858{
859 struct remote_state *rs = get_remote_state ();
860 struct remote_arch_state *rsa = get_remote_arch_state ();
861
862 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
863 law?) that some hosts don't cope very well with large alloca()
864 calls. Eventually the alloca() code will be replaced by calls to
865 xmalloc() and make_cleanups() allowing this restriction to either
866 be lifted or removed. */
867#ifndef MAX_REMOTE_PACKET_SIZE
868#define MAX_REMOTE_PACKET_SIZE 16384
869#endif
870 /* NOTE: 20 ensures we can write at least one byte. */
871#ifndef MIN_REMOTE_PACKET_SIZE
872#define MIN_REMOTE_PACKET_SIZE 20
873#endif
874 long what_they_get;
875 if (config->fixed_p)
876 {
877 if (config->size <= 0)
878 what_they_get = MAX_REMOTE_PACKET_SIZE;
879 else
880 what_they_get = config->size;
881 }
882 else
883 {
884 what_they_get = get_remote_packet_size ();
885 /* Limit the packet to the size specified by the user. */
886 if (config->size > 0
887 && what_they_get > config->size)
888 what_they_get = config->size;
889
890 /* Limit it to the size of the targets ``g'' response unless we have
891 permission from the stub to use a larger packet size. */
892 if (rs->explicit_packet_size == 0
893 && rsa->actual_register_packet_size > 0
894 && what_they_get > rsa->actual_register_packet_size)
895 what_they_get = rsa->actual_register_packet_size;
896 }
897 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
898 what_they_get = MAX_REMOTE_PACKET_SIZE;
899 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
900 what_they_get = MIN_REMOTE_PACKET_SIZE;
901
902 /* Make sure there is room in the global buffer for this packet
903 (including its trailing NUL byte). */
904 if (rs->buf_size < what_they_get + 1)
905 {
906 rs->buf_size = 2 * what_they_get;
907 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
908 }
909
910 return what_they_get;
911}
912
c50c785c 913/* Update the size of a read/write packet. If they user wants
5796c8dc
SS
914 something really big then do a sanity check. */
915
916static void
917set_memory_packet_size (char *args, struct memory_packet_config *config)
918{
919 int fixed_p = config->fixed_p;
920 long size = config->size;
cf7f2e2d 921
5796c8dc
SS
922 if (args == NULL)
923 error (_("Argument required (integer, `fixed' or `limited')."));
924 else if (strcmp (args, "hard") == 0
925 || strcmp (args, "fixed") == 0)
926 fixed_p = 1;
927 else if (strcmp (args, "soft") == 0
928 || strcmp (args, "limit") == 0)
929 fixed_p = 0;
930 else
931 {
932 char *end;
cf7f2e2d 933
5796c8dc
SS
934 size = strtoul (args, &end, 0);
935 if (args == end)
936 error (_("Invalid %s (bad syntax)."), config->name);
937#if 0
938 /* Instead of explicitly capping the size of a packet to
939 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
940 instead allowed to set the size to something arbitrarily
941 large. */
942 if (size > MAX_REMOTE_PACKET_SIZE)
943 error (_("Invalid %s (too large)."), config->name);
944#endif
945 }
946 /* Extra checks? */
947 if (fixed_p && !config->fixed_p)
948 {
949 if (! query (_("The target may not be able to correctly handle a %s\n"
950 "of %ld bytes. Change the packet size? "),
951 config->name, size))
952 error (_("Packet size not changed."));
953 }
954 /* Update the config. */
955 config->fixed_p = fixed_p;
956 config->size = size;
957}
958
959static void
960show_memory_packet_size (struct memory_packet_config *config)
961{
962 printf_filtered (_("The %s is %ld. "), config->name, config->size);
963 if (config->fixed_p)
964 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
965 get_memory_packet_size (config));
966 else
967 printf_filtered (_("Packets are limited to %ld bytes.\n"),
968 get_memory_packet_size (config));
969}
970
971static struct memory_packet_config memory_write_packet_config =
972{
973 "memory-write-packet-size",
974};
975
976static void
977set_memory_write_packet_size (char *args, int from_tty)
978{
979 set_memory_packet_size (args, &memory_write_packet_config);
980}
981
982static void
983show_memory_write_packet_size (char *args, int from_tty)
984{
985 show_memory_packet_size (&memory_write_packet_config);
986}
987
988static long
989get_memory_write_packet_size (void)
990{
991 return get_memory_packet_size (&memory_write_packet_config);
992}
993
994static struct memory_packet_config memory_read_packet_config =
995{
996 "memory-read-packet-size",
997};
998
999static void
1000set_memory_read_packet_size (char *args, int from_tty)
1001{
1002 set_memory_packet_size (args, &memory_read_packet_config);
1003}
1004
1005static void
1006show_memory_read_packet_size (char *args, int from_tty)
1007{
1008 show_memory_packet_size (&memory_read_packet_config);
1009}
1010
1011static long
1012get_memory_read_packet_size (void)
1013{
1014 long size = get_memory_packet_size (&memory_read_packet_config);
cf7f2e2d 1015
5796c8dc
SS
1016 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1017 extra buffer size argument before the memory read size can be
1018 increased beyond this. */
1019 if (size > get_remote_packet_size ())
1020 size = get_remote_packet_size ();
1021 return size;
1022}
1023
1024\f
1025/* Generic configuration support for packets the stub optionally
c50c785c 1026 supports. Allows the user to specify the use of the packet as well
5796c8dc
SS
1027 as allowing GDB to auto-detect support in the remote stub. */
1028
1029enum packet_support
1030 {
1031 PACKET_SUPPORT_UNKNOWN = 0,
1032 PACKET_ENABLE,
1033 PACKET_DISABLE
1034 };
1035
1036struct packet_config
1037 {
1038 const char *name;
1039 const char *title;
1040 enum auto_boolean detect;
1041 enum packet_support support;
1042 };
1043
1044/* Analyze a packet's return value and update the packet config
1045 accordingly. */
1046
1047enum packet_result
1048{
1049 PACKET_ERROR,
1050 PACKET_OK,
1051 PACKET_UNKNOWN
1052};
1053
1054static void
1055update_packet_config (struct packet_config *config)
1056{
1057 switch (config->detect)
1058 {
1059 case AUTO_BOOLEAN_TRUE:
1060 config->support = PACKET_ENABLE;
1061 break;
1062 case AUTO_BOOLEAN_FALSE:
1063 config->support = PACKET_DISABLE;
1064 break;
1065 case AUTO_BOOLEAN_AUTO:
1066 config->support = PACKET_SUPPORT_UNKNOWN;
1067 break;
1068 }
1069}
1070
1071static void
1072show_packet_config_cmd (struct packet_config *config)
1073{
1074 char *support = "internal-error";
cf7f2e2d 1075
5796c8dc
SS
1076 switch (config->support)
1077 {
1078 case PACKET_ENABLE:
1079 support = "enabled";
1080 break;
1081 case PACKET_DISABLE:
1082 support = "disabled";
1083 break;
1084 case PACKET_SUPPORT_UNKNOWN:
1085 support = "unknown";
1086 break;
1087 }
1088 switch (config->detect)
1089 {
1090 case AUTO_BOOLEAN_AUTO:
c50c785c
JM
1091 printf_filtered (_("Support for the `%s' packet "
1092 "is auto-detected, currently %s.\n"),
5796c8dc
SS
1093 config->name, support);
1094 break;
1095 case AUTO_BOOLEAN_TRUE:
1096 case AUTO_BOOLEAN_FALSE:
1097 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1098 config->name, support);
1099 break;
1100 }
1101}
1102
1103static void
1104add_packet_config_cmd (struct packet_config *config, const char *name,
1105 const char *title, int legacy)
1106{
1107 char *set_doc;
1108 char *show_doc;
1109 char *cmd_name;
1110
1111 config->name = name;
1112 config->title = title;
1113 config->detect = AUTO_BOOLEAN_AUTO;
1114 config->support = PACKET_SUPPORT_UNKNOWN;
1115 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1116 name, title);
c50c785c
JM
1117 show_doc = xstrprintf ("Show current use of remote "
1118 "protocol `%s' (%s) packet",
5796c8dc
SS
1119 name, title);
1120 /* set/show TITLE-packet {auto,on,off} */
1121 cmd_name = xstrprintf ("%s-packet", title);
1122 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
c50c785c
JM
1123 &config->detect, set_doc,
1124 show_doc, NULL, /* help_doc */
5796c8dc
SS
1125 set_remote_protocol_packet_cmd,
1126 show_remote_protocol_packet_cmd,
1127 &remote_set_cmdlist, &remote_show_cmdlist);
1128 /* The command code copies the documentation strings. */
1129 xfree (set_doc);
1130 xfree (show_doc);
1131 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1132 if (legacy)
1133 {
1134 char *legacy_name;
cf7f2e2d 1135
5796c8dc
SS
1136 legacy_name = xstrprintf ("%s-packet", name);
1137 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1138 &remote_set_cmdlist);
1139 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1140 &remote_show_cmdlist);
1141 }
1142}
1143
1144static enum packet_result
1145packet_check_result (const char *buf)
1146{
1147 if (buf[0] != '\0')
1148 {
1149 /* The stub recognized the packet request. Check that the
1150 operation succeeded. */
1151 if (buf[0] == 'E'
1152 && isxdigit (buf[1]) && isxdigit (buf[2])
1153 && buf[3] == '\0')
1154 /* "Enn" - definitly an error. */
1155 return PACKET_ERROR;
1156
1157 /* Always treat "E." as an error. This will be used for
1158 more verbose error messages, such as E.memtypes. */
1159 if (buf[0] == 'E' && buf[1] == '.')
1160 return PACKET_ERROR;
1161
1162 /* The packet may or may not be OK. Just assume it is. */
1163 return PACKET_OK;
1164 }
1165 else
1166 /* The stub does not support the packet. */
1167 return PACKET_UNKNOWN;
1168}
1169
1170static enum packet_result
1171packet_ok (const char *buf, struct packet_config *config)
1172{
1173 enum packet_result result;
1174
1175 result = packet_check_result (buf);
1176 switch (result)
1177 {
1178 case PACKET_OK:
1179 case PACKET_ERROR:
1180 /* The stub recognized the packet request. */
1181 switch (config->support)
1182 {
1183 case PACKET_SUPPORT_UNKNOWN:
1184 if (remote_debug)
1185 fprintf_unfiltered (gdb_stdlog,
1186 "Packet %s (%s) is supported\n",
1187 config->name, config->title);
1188 config->support = PACKET_ENABLE;
1189 break;
1190 case PACKET_DISABLE:
1191 internal_error (__FILE__, __LINE__,
1192 _("packet_ok: attempt to use a disabled packet"));
1193 break;
1194 case PACKET_ENABLE:
1195 break;
1196 }
1197 break;
1198 case PACKET_UNKNOWN:
1199 /* The stub does not support the packet. */
1200 switch (config->support)
1201 {
1202 case PACKET_ENABLE:
1203 if (config->detect == AUTO_BOOLEAN_AUTO)
1204 /* If the stub previously indicated that the packet was
1205 supported then there is a protocol error.. */
1206 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1207 config->name, config->title);
1208 else
1209 /* The user set it wrong. */
1210 error (_("Enabled packet %s (%s) not recognized by stub"),
1211 config->name, config->title);
1212 break;
1213 case PACKET_SUPPORT_UNKNOWN:
1214 if (remote_debug)
1215 fprintf_unfiltered (gdb_stdlog,
1216 "Packet %s (%s) is NOT supported\n",
1217 config->name, config->title);
1218 config->support = PACKET_DISABLE;
1219 break;
1220 case PACKET_DISABLE:
1221 break;
1222 }
1223 break;
1224 }
1225
1226 return result;
1227}
1228
1229enum {
1230 PACKET_vCont = 0,
1231 PACKET_X,
1232 PACKET_qSymbol,
1233 PACKET_P,
1234 PACKET_p,
1235 PACKET_Z0,
1236 PACKET_Z1,
1237 PACKET_Z2,
1238 PACKET_Z3,
1239 PACKET_Z4,
1240 PACKET_vFile_open,
1241 PACKET_vFile_pread,
1242 PACKET_vFile_pwrite,
1243 PACKET_vFile_close,
1244 PACKET_vFile_unlink,
ef5ccd6c 1245 PACKET_vFile_readlink,
5796c8dc
SS
1246 PACKET_qXfer_auxv,
1247 PACKET_qXfer_features,
1248 PACKET_qXfer_libraries,
a45ae5f8 1249 PACKET_qXfer_libraries_svr4,
5796c8dc
SS
1250 PACKET_qXfer_memory_map,
1251 PACKET_qXfer_spu_read,
1252 PACKET_qXfer_spu_write,
1253 PACKET_qXfer_osdata,
cf7f2e2d
JM
1254 PACKET_qXfer_threads,
1255 PACKET_qXfer_statictrace_read,
c50c785c 1256 PACKET_qXfer_traceframe_info,
ef5ccd6c 1257 PACKET_qXfer_uib,
cf7f2e2d 1258 PACKET_qGetTIBAddr,
5796c8dc
SS
1259 PACKET_qGetTLSAddr,
1260 PACKET_qSupported,
1261 PACKET_QPassSignals,
ef5ccd6c 1262 PACKET_QProgramSignals,
5796c8dc
SS
1263 PACKET_qSearch_memory,
1264 PACKET_vAttach,
1265 PACKET_vRun,
1266 PACKET_QStartNoAckMode,
1267 PACKET_vKill,
1268 PACKET_qXfer_siginfo_read,
1269 PACKET_qXfer_siginfo_write,
1270 PACKET_qAttached,
1271 PACKET_ConditionalTracepoints,
ef5ccd6c
JM
1272 PACKET_ConditionalBreakpoints,
1273 PACKET_BreakpointCommands,
cf7f2e2d
JM
1274 PACKET_FastTracepoints,
1275 PACKET_StaticTracepoints,
a45ae5f8 1276 PACKET_InstallInTrace,
5796c8dc
SS
1277 PACKET_bc,
1278 PACKET_bs,
cf7f2e2d
JM
1279 PACKET_TracepointSource,
1280 PACKET_QAllow,
a45ae5f8
JM
1281 PACKET_qXfer_fdpic,
1282 PACKET_QDisableRandomization,
ef5ccd6c
JM
1283 PACKET_QAgent,
1284 PACKET_QTBuffer_size,
1285 PACKET_Qbtrace_off,
1286 PACKET_Qbtrace_bts,
1287 PACKET_qXfer_btrace,
5796c8dc
SS
1288 PACKET_MAX
1289};
1290
1291static struct packet_config remote_protocol_packets[PACKET_MAX];
1292
1293static void
1294set_remote_protocol_packet_cmd (char *args, int from_tty,
1295 struct cmd_list_element *c)
1296{
1297 struct packet_config *packet;
1298
1299 for (packet = remote_protocol_packets;
1300 packet < &remote_protocol_packets[PACKET_MAX];
1301 packet++)
1302 {
1303 if (&packet->detect == c->var)
1304 {
1305 update_packet_config (packet);
1306 return;
1307 }
1308 }
c50c785c 1309 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
5796c8dc
SS
1310 c->name);
1311}
1312
1313static void
1314show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1315 struct cmd_list_element *c,
1316 const char *value)
1317{
1318 struct packet_config *packet;
1319
1320 for (packet = remote_protocol_packets;
1321 packet < &remote_protocol_packets[PACKET_MAX];
1322 packet++)
1323 {
1324 if (&packet->detect == c->var)
1325 {
1326 show_packet_config_cmd (packet);
1327 return;
1328 }
1329 }
c50c785c 1330 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
5796c8dc
SS
1331 c->name);
1332}
1333
1334/* Should we try one of the 'Z' requests? */
1335
1336enum Z_packet_type
1337{
1338 Z_PACKET_SOFTWARE_BP,
1339 Z_PACKET_HARDWARE_BP,
1340 Z_PACKET_WRITE_WP,
1341 Z_PACKET_READ_WP,
1342 Z_PACKET_ACCESS_WP,
1343 NR_Z_PACKET_TYPES
1344};
1345
1346/* For compatibility with older distributions. Provide a ``set remote
1347 Z-packet ...'' command that updates all the Z packet types. */
1348
1349static enum auto_boolean remote_Z_packet_detect;
1350
1351static void
1352set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1353 struct cmd_list_element *c)
1354{
1355 int i;
cf7f2e2d 1356
5796c8dc
SS
1357 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1358 {
1359 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1360 update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
1361 }
1362}
1363
1364static void
1365show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1366 struct cmd_list_element *c,
1367 const char *value)
1368{
1369 int i;
cf7f2e2d 1370
5796c8dc
SS
1371 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1372 {
1373 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1374 }
1375}
1376
1377/* Should we try the 'ThreadInfo' query packet?
1378
1379 This variable (NOT available to the user: auto-detect only!)
1380 determines whether GDB will use the new, simpler "ThreadInfo"
1381 query or the older, more complex syntax for thread queries.
1382 This is an auto-detect variable (set to true at each connect,
1383 and set to false when the target fails to recognize it). */
1384
1385static int use_threadinfo_query;
1386static int use_threadextra_query;
1387
1388/* Tokens for use by the asynchronous signal handlers for SIGINT. */
1389static struct async_signal_handler *sigint_remote_twice_token;
1390static struct async_signal_handler *sigint_remote_token;
1391
1392\f
1393/* Asynchronous signal handle registered as event loop source for
1394 when we have pending events ready to be passed to the core. */
1395
1396static struct async_event_handler *remote_async_inferior_event_token;
1397
5796c8dc
SS
1398\f
1399
1400static ptid_t magic_null_ptid;
1401static ptid_t not_sent_ptid;
1402static ptid_t any_thread_ptid;
1403
1404/* These are the threads which we last sent to the remote system. The
1405 TID member will be -1 for all or -2 for not sent yet. */
1406
1407static ptid_t general_thread;
1408static ptid_t continue_thread;
1409
ef5ccd6c 1410/* This is the traceframe which we last selected on the remote system.
c50c785c
JM
1411 It will be -1 if no traceframe is selected. */
1412static int remote_traceframe_number = -1;
1413
5796c8dc
SS
1414/* Find out if the stub attached to PID (and hence GDB should offer to
1415 detach instead of killing it when bailing out). */
1416
1417static int
1418remote_query_attached (int pid)
1419{
1420 struct remote_state *rs = get_remote_state ();
ef5ccd6c 1421 size_t size = get_remote_packet_size ();
5796c8dc
SS
1422
1423 if (remote_protocol_packets[PACKET_qAttached].support == PACKET_DISABLE)
1424 return 0;
1425
1426 if (remote_multi_process_p (rs))
ef5ccd6c 1427 xsnprintf (rs->buf, size, "qAttached:%x", pid);
5796c8dc 1428 else
ef5ccd6c 1429 xsnprintf (rs->buf, size, "qAttached");
5796c8dc
SS
1430
1431 putpkt (rs->buf);
1432 getpkt (&rs->buf, &rs->buf_size, 0);
1433
1434 switch (packet_ok (rs->buf,
1435 &remote_protocol_packets[PACKET_qAttached]))
1436 {
1437 case PACKET_OK:
1438 if (strcmp (rs->buf, "1") == 0)
1439 return 1;
1440 break;
1441 case PACKET_ERROR:
1442 warning (_("Remote failure reply: %s"), rs->buf);
1443 break;
1444 case PACKET_UNKNOWN:
1445 break;
1446 }
1447
1448 return 0;
1449}
1450
ef5ccd6c
JM
1451/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1452 has been invented by GDB, instead of reported by the target. Since
1453 we can be connected to a remote system before before knowing about
1454 any inferior, mark the target with execution when we find the first
1455 inferior. If ATTACHED is 1, then we had just attached to this
1456 inferior. If it is 0, then we just created this inferior. If it
1457 is -1, then try querying the remote stub to find out if it had
1458 attached to the inferior or not. */
5796c8dc
SS
1459
1460static struct inferior *
ef5ccd6c 1461remote_add_inferior (int fake_pid_p, int pid, int attached)
5796c8dc
SS
1462{
1463 struct inferior *inf;
1464
1465 /* Check whether this process we're learning about is to be
1466 considered attached, or if is to be considered to have been
1467 spawned by the stub. */
1468 if (attached == -1)
1469 attached = remote_query_attached (pid);
1470
ef5ccd6c 1471 if (gdbarch_has_global_solist (target_gdbarch ()))
cf7f2e2d
JM
1472 {
1473 /* If the target shares code across all inferiors, then every
1474 attach adds a new inferior. */
1475 inf = add_inferior (pid);
1476
1477 /* ... and every inferior is bound to the same program space.
1478 However, each inferior may still have its own address
1479 space. */
1480 inf->aspace = maybe_new_address_space ();
1481 inf->pspace = current_program_space;
1482 }
1483 else
1484 {
1485 /* In the traditional debugging scenario, there's a 1-1 match
1486 between program/address spaces. We simply bind the inferior
1487 to the program space's address space. */
1488 inf = current_inferior ();
1489 inferior_appeared (inf, pid);
1490 }
5796c8dc
SS
1491
1492 inf->attach_flag = attached;
ef5ccd6c 1493 inf->fake_pid_p = fake_pid_p;
5796c8dc
SS
1494
1495 return inf;
1496}
1497
1498/* Add thread PTID to GDB's thread list. Tag it as executing/running
1499 according to RUNNING. */
1500
1501static void
1502remote_add_thread (ptid_t ptid, int running)
1503{
1504 add_thread (ptid);
1505
1506 set_executing (ptid, running);
1507 set_running (ptid, running);
1508}
1509
1510/* Come here when we learn about a thread id from the remote target.
1511 It may be the first time we hear about such thread, so take the
1512 opportunity to add it to GDB's thread list. In case this is the
1513 first time we're noticing its corresponding inferior, add it to
1514 GDB's inferior list as well. */
1515
1516static void
1517remote_notice_new_inferior (ptid_t currthread, int running)
1518{
1519 /* If this is a new thread, add it to GDB's thread list.
1520 If we leave it up to WFI to do this, bad things will happen. */
1521
1522 if (in_thread_list (currthread) && is_exited (currthread))
1523 {
1524 /* We're seeing an event on a thread id we knew had exited.
1525 This has to be a new thread reusing the old id. Add it. */
1526 remote_add_thread (currthread, running);
1527 return;
1528 }
1529
1530 if (!in_thread_list (currthread))
1531 {
1532 struct inferior *inf = NULL;
1533 int pid = ptid_get_pid (currthread);
1534
1535 if (ptid_is_pid (inferior_ptid)
1536 && pid == ptid_get_pid (inferior_ptid))
1537 {
1538 /* inferior_ptid has no thread member yet. This can happen
1539 with the vAttach -> remote_wait,"TAAthread:" path if the
1540 stub doesn't support qC. This is the first stop reported
1541 after an attach, so this is the main thread. Update the
1542 ptid in the thread list. */
1543 if (in_thread_list (pid_to_ptid (pid)))
1544 thread_change_ptid (inferior_ptid, currthread);
1545 else
1546 {
1547 remote_add_thread (currthread, running);
1548 inferior_ptid = currthread;
1549 }
cf7f2e2d 1550 return;
5796c8dc
SS
1551 }
1552
1553 if (ptid_equal (magic_null_ptid, inferior_ptid))
1554 {
1555 /* inferior_ptid is not set yet. This can happen with the
1556 vRun -> remote_wait,"TAAthread:" path if the stub
1557 doesn't support qC. This is the first stop reported
1558 after an attach, so this is the main thread. Update the
1559 ptid in the thread list. */
cf7f2e2d 1560 thread_change_ptid (inferior_ptid, currthread);
5796c8dc
SS
1561 return;
1562 }
1563
1564 /* When connecting to a target remote, or to a target
1565 extended-remote which already was debugging an inferior, we
1566 may not know about it yet. Add it before adding its child
1567 thread, so notifications are emitted in a sensible order. */
1568 if (!in_inferior_list (ptid_get_pid (currthread)))
ef5ccd6c
JM
1569 {
1570 struct remote_state *rs = get_remote_state ();
1571 int fake_pid_p = !remote_multi_process_p (rs);
1572
1573 inf = remote_add_inferior (fake_pid_p,
1574 ptid_get_pid (currthread), -1);
1575 }
5796c8dc
SS
1576
1577 /* This is really a new thread. Add it. */
1578 remote_add_thread (currthread, running);
1579
1580 /* If we found a new inferior, let the common code do whatever
1581 it needs to with it (e.g., read shared libraries, insert
1582 breakpoints). */
1583 if (inf != NULL)
1584 notice_new_inferior (currthread, running, 0);
1585 }
1586}
1587
cf7f2e2d
JM
1588/* Return the private thread data, creating it if necessary. */
1589
ef5ccd6c 1590static struct private_thread_info *
cf7f2e2d
JM
1591demand_private_info (ptid_t ptid)
1592{
1593 struct thread_info *info = find_thread_ptid (ptid);
1594
1595 gdb_assert (info);
1596
1597 if (!info->private)
1598 {
1599 info->private = xmalloc (sizeof (*(info->private)));
1600 info->private_dtor = free_private_thread_info;
1601 info->private->core = -1;
1602 info->private->extra = 0;
1603 }
1604
1605 return info->private;
1606}
1607
5796c8dc
SS
1608/* Call this function as a result of
1609 1) A halt indication (T packet) containing a thread id
1610 2) A direct query of currthread
c50c785c 1611 3) Successful execution of set thread */
5796c8dc
SS
1612
1613static void
1614record_currthread (ptid_t currthread)
1615{
1616 general_thread = currthread;
5796c8dc
SS
1617}
1618
1619static char *last_pass_packet;
1620
1621/* If 'QPassSignals' is supported, tell the remote stub what signals
1622 it can simply pass through to the inferior without reporting. */
1623
1624static void
a45ae5f8 1625remote_pass_signals (int numsigs, unsigned char *pass_signals)
5796c8dc
SS
1626{
1627 if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1628 {
1629 char *pass_packet, *p;
5796c8dc
SS
1630 int count = 0, i;
1631
1632 gdb_assert (numsigs < 256);
1633 for (i = 0; i < numsigs; i++)
1634 {
a45ae5f8 1635 if (pass_signals[i])
5796c8dc
SS
1636 count++;
1637 }
1638 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1639 strcpy (pass_packet, "QPassSignals:");
1640 p = pass_packet + strlen (pass_packet);
1641 for (i = 0; i < numsigs; i++)
1642 {
a45ae5f8 1643 if (pass_signals[i])
5796c8dc
SS
1644 {
1645 if (i >= 16)
1646 *p++ = tohex (i >> 4);
1647 *p++ = tohex (i & 15);
1648 if (count)
1649 *p++ = ';';
1650 else
1651 break;
1652 count--;
1653 }
1654 }
1655 *p = 0;
1656 if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
1657 {
1658 struct remote_state *rs = get_remote_state ();
1659 char *buf = rs->buf;
1660
1661 putpkt (pass_packet);
1662 getpkt (&rs->buf, &rs->buf_size, 0);
1663 packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1664 if (last_pass_packet)
1665 xfree (last_pass_packet);
1666 last_pass_packet = pass_packet;
1667 }
1668 else
1669 xfree (pass_packet);
1670 }
1671}
1672
ef5ccd6c
JM
1673/* The last QProgramSignals packet sent to the target. We bypass
1674 sending a new program signals list down to the target if the new
1675 packet is exactly the same as the last we sent. IOW, we only let
1676 the target know about program signals list changes. */
1677
1678static char *last_program_signals_packet;
1679
1680/* If 'QProgramSignals' is supported, tell the remote stub what
1681 signals it should pass through to the inferior when detaching. */
1682
1683static void
1684remote_program_signals (int numsigs, unsigned char *signals)
1685{
1686 if (remote_protocol_packets[PACKET_QProgramSignals].support != PACKET_DISABLE)
1687 {
1688 char *packet, *p;
1689 int count = 0, i;
1690
1691 gdb_assert (numsigs < 256);
1692 for (i = 0; i < numsigs; i++)
1693 {
1694 if (signals[i])
1695 count++;
1696 }
1697 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1698 strcpy (packet, "QProgramSignals:");
1699 p = packet + strlen (packet);
1700 for (i = 0; i < numsigs; i++)
1701 {
1702 if (signal_pass_state (i))
1703 {
1704 if (i >= 16)
1705 *p++ = tohex (i >> 4);
1706 *p++ = tohex (i & 15);
1707 if (count)
1708 *p++ = ';';
1709 else
1710 break;
1711 count--;
1712 }
1713 }
1714 *p = 0;
1715 if (!last_program_signals_packet
1716 || strcmp (last_program_signals_packet, packet) != 0)
1717 {
1718 struct remote_state *rs = get_remote_state ();
1719 char *buf = rs->buf;
1720
1721 putpkt (packet);
1722 getpkt (&rs->buf, &rs->buf_size, 0);
1723 packet_ok (buf, &remote_protocol_packets[PACKET_QProgramSignals]);
1724 xfree (last_program_signals_packet);
1725 last_program_signals_packet = packet;
1726 }
1727 else
1728 xfree (packet);
1729 }
1730}
1731
5796c8dc
SS
1732/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1733 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1734 thread. If GEN is set, set the general thread, if not, then set
1735 the step/continue thread. */
1736static void
1737set_thread (struct ptid ptid, int gen)
1738{
1739 struct remote_state *rs = get_remote_state ();
1740 ptid_t state = gen ? general_thread : continue_thread;
1741 char *buf = rs->buf;
1742 char *endbuf = rs->buf + get_remote_packet_size ();
1743
1744 if (ptid_equal (state, ptid))
1745 return;
1746
1747 *buf++ = 'H';
1748 *buf++ = gen ? 'g' : 'c';
1749 if (ptid_equal (ptid, magic_null_ptid))
1750 xsnprintf (buf, endbuf - buf, "0");
1751 else if (ptid_equal (ptid, any_thread_ptid))
1752 xsnprintf (buf, endbuf - buf, "0");
1753 else if (ptid_equal (ptid, minus_one_ptid))
1754 xsnprintf (buf, endbuf - buf, "-1");
1755 else
1756 write_ptid (buf, endbuf, ptid);
1757 putpkt (rs->buf);
1758 getpkt (&rs->buf, &rs->buf_size, 0);
1759 if (gen)
1760 general_thread = ptid;
1761 else
1762 continue_thread = ptid;
1763}
1764
1765static void
1766set_general_thread (struct ptid ptid)
1767{
1768 set_thread (ptid, 1);
1769}
1770
1771static void
1772set_continue_thread (struct ptid ptid)
1773{
1774 set_thread (ptid, 0);
1775}
1776
1777/* Change the remote current process. Which thread within the process
1778 ends up selected isn't important, as long as it is the same process
1779 as what INFERIOR_PTID points to.
1780
1781 This comes from that fact that there is no explicit notion of
1782 "selected process" in the protocol. The selected process for
1783 general operations is the process the selected general thread
1784 belongs to. */
1785
1786static void
1787set_general_process (void)
1788{
1789 struct remote_state *rs = get_remote_state ();
1790
1791 /* If the remote can't handle multiple processes, don't bother. */
ef5ccd6c 1792 if (!rs->extended || !remote_multi_process_p (rs))
5796c8dc
SS
1793 return;
1794
1795 /* We only need to change the remote current thread if it's pointing
1796 at some other process. */
1797 if (ptid_get_pid (general_thread) != ptid_get_pid (inferior_ptid))
1798 set_general_thread (inferior_ptid);
1799}
1800
1801\f
1802/* Return nonzero if the thread PTID is still alive on the remote
1803 system. */
1804
1805static int
1806remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1807{
1808 struct remote_state *rs = get_remote_state ();
1809 char *p, *endp;
1810
1811 if (ptid_equal (ptid, magic_null_ptid))
1812 /* The main thread is always alive. */
1813 return 1;
1814
1815 if (ptid_get_pid (ptid) != 0 && ptid_get_tid (ptid) == 0)
1816 /* The main thread is always alive. This can happen after a
1817 vAttach, if the remote side doesn't support
1818 multi-threading. */
1819 return 1;
1820
1821 p = rs->buf;
1822 endp = rs->buf + get_remote_packet_size ();
1823
1824 *p++ = 'T';
1825 write_ptid (p, endp, ptid);
1826
1827 putpkt (rs->buf);
1828 getpkt (&rs->buf, &rs->buf_size, 0);
1829 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1830}
1831
1832/* About these extended threadlist and threadinfo packets. They are
1833 variable length packets but, the fields within them are often fixed
1834 length. They are redundent enough to send over UDP as is the
1835 remote protocol in general. There is a matching unit test module
1836 in libstub. */
1837
1838#define OPAQUETHREADBYTES 8
1839
1840/* a 64 bit opaque identifier */
1841typedef unsigned char threadref[OPAQUETHREADBYTES];
1842
1843/* WARNING: This threadref data structure comes from the remote O.S.,
c50c785c 1844 libstub protocol encoding, and remote.c. It is not particularly
5796c8dc
SS
1845 changable. */
1846
1847/* Right now, the internal structure is int. We want it to be bigger.
c50c785c 1848 Plan to fix this. */
5796c8dc
SS
1849
1850typedef int gdb_threadref; /* Internal GDB thread reference. */
1851
1852/* gdb_ext_thread_info is an internal GDB data structure which is
1853 equivalent to the reply of the remote threadinfo packet. */
1854
1855struct gdb_ext_thread_info
1856 {
1857 threadref threadid; /* External form of thread reference. */
1858 int active; /* Has state interesting to GDB?
1859 regs, stack. */
1860 char display[256]; /* Brief state display, name,
1861 blocked/suspended. */
1862 char shortname[32]; /* To be used to name threads. */
1863 char more_display[256]; /* Long info, statistics, queue depth,
1864 whatever. */
1865 };
1866
1867/* The volume of remote transfers can be limited by submitting
1868 a mask containing bits specifying the desired information.
1869 Use a union of these values as the 'selection' parameter to
c50c785c 1870 get_thread_info. FIXME: Make these TAG names more thread specific. */
5796c8dc
SS
1871
1872#define TAG_THREADID 1
1873#define TAG_EXISTS 2
1874#define TAG_DISPLAY 4
1875#define TAG_THREADNAME 8
1876#define TAG_MOREDISPLAY 16
1877
1878#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1879
1880char *unpack_varlen_hex (char *buff, ULONGEST *result);
1881
1882static char *unpack_nibble (char *buf, int *val);
1883
1884static char *pack_nibble (char *buf, int nibble);
1885
1886static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
1887
1888static char *unpack_byte (char *buf, int *value);
1889
1890static char *pack_int (char *buf, int value);
1891
1892static char *unpack_int (char *buf, int *value);
1893
1894static char *unpack_string (char *src, char *dest, int length);
1895
1896static char *pack_threadid (char *pkt, threadref *id);
1897
1898static char *unpack_threadid (char *inbuf, threadref *id);
1899
1900void int_to_threadref (threadref *id, int value);
1901
1902static int threadref_to_int (threadref *ref);
1903
1904static void copy_threadref (threadref *dest, threadref *src);
1905
1906static int threadmatch (threadref *dest, threadref *src);
1907
1908static char *pack_threadinfo_request (char *pkt, int mode,
1909 threadref *id);
1910
1911static int remote_unpack_thread_info_response (char *pkt,
1912 threadref *expectedref,
1913 struct gdb_ext_thread_info
1914 *info);
1915
1916
1917static int remote_get_threadinfo (threadref *threadid,
1918 int fieldset, /*TAG mask */
1919 struct gdb_ext_thread_info *info);
1920
1921static char *pack_threadlist_request (char *pkt, int startflag,
1922 int threadcount,
1923 threadref *nextthread);
1924
1925static int parse_threadlist_response (char *pkt,
1926 int result_limit,
1927 threadref *original_echo,
1928 threadref *resultlist,
1929 int *doneflag);
1930
1931static int remote_get_threadlist (int startflag,
1932 threadref *nextthread,
1933 int result_limit,
1934 int *done,
1935 int *result_count,
1936 threadref *threadlist);
1937
1938typedef int (*rmt_thread_action) (threadref *ref, void *context);
1939
1940static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1941 void *context, int looplimit);
1942
1943static int remote_newthread_step (threadref *ref, void *context);
1944
1945
1946/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
1947 buffer we're allowed to write to. Returns
1948 BUF+CHARACTERS_WRITTEN. */
1949
1950static char *
1951write_ptid (char *buf, const char *endbuf, ptid_t ptid)
1952{
1953 int pid, tid;
1954 struct remote_state *rs = get_remote_state ();
1955
1956 if (remote_multi_process_p (rs))
1957 {
1958 pid = ptid_get_pid (ptid);
1959 if (pid < 0)
1960 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
1961 else
1962 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
1963 }
1964 tid = ptid_get_tid (ptid);
1965 if (tid < 0)
1966 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
1967 else
1968 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
1969
1970 return buf;
1971}
1972
1973/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
1974 passed the last parsed char. Returns null_ptid on error. */
1975
1976static ptid_t
1977read_ptid (char *buf, char **obuf)
1978{
1979 char *p = buf;
1980 char *pp;
1981 ULONGEST pid = 0, tid = 0;
1982
1983 if (*p == 'p')
1984 {
1985 /* Multi-process ptid. */
1986 pp = unpack_varlen_hex (p + 1, &pid);
1987 if (*pp != '.')
c50c785c 1988 error (_("invalid remote ptid: %s"), p);
5796c8dc
SS
1989
1990 p = pp;
1991 pp = unpack_varlen_hex (p + 1, &tid);
1992 if (obuf)
1993 *obuf = pp;
1994 return ptid_build (pid, 0, tid);
1995 }
1996
1997 /* No multi-process. Just a tid. */
1998 pp = unpack_varlen_hex (p, &tid);
1999
2000 /* Since the stub is not sending a process id, then default to
2001 what's in inferior_ptid, unless it's null at this point. If so,
2002 then since there's no way to know the pid of the reported
2003 threads, use the magic number. */
2004 if (ptid_equal (inferior_ptid, null_ptid))
2005 pid = ptid_get_pid (magic_null_ptid);
2006 else
2007 pid = ptid_get_pid (inferior_ptid);
2008
2009 if (obuf)
2010 *obuf = pp;
2011 return ptid_build (pid, 0, tid);
2012}
2013
2014/* Encode 64 bits in 16 chars of hex. */
2015
2016static const char hexchars[] = "0123456789abcdef";
2017
2018static int
2019ishex (int ch, int *val)
2020{
2021 if ((ch >= 'a') && (ch <= 'f'))
2022 {
2023 *val = ch - 'a' + 10;
2024 return 1;
2025 }
2026 if ((ch >= 'A') && (ch <= 'F'))
2027 {
2028 *val = ch - 'A' + 10;
2029 return 1;
2030 }
2031 if ((ch >= '0') && (ch <= '9'))
2032 {
2033 *val = ch - '0';
2034 return 1;
2035 }
2036 return 0;
2037}
2038
2039static int
2040stubhex (int ch)
2041{
2042 if (ch >= 'a' && ch <= 'f')
2043 return ch - 'a' + 10;
2044 if (ch >= '0' && ch <= '9')
2045 return ch - '0';
2046 if (ch >= 'A' && ch <= 'F')
2047 return ch - 'A' + 10;
2048 return -1;
2049}
2050
2051static int
2052stub_unpack_int (char *buff, int fieldlength)
2053{
2054 int nibble;
2055 int retval = 0;
2056
2057 while (fieldlength)
2058 {
2059 nibble = stubhex (*buff++);
2060 retval |= nibble;
2061 fieldlength--;
2062 if (fieldlength)
2063 retval = retval << 4;
2064 }
2065 return retval;
2066}
2067
2068char *
2069unpack_varlen_hex (char *buff, /* packet to parse */
2070 ULONGEST *result)
2071{
2072 int nibble;
2073 ULONGEST retval = 0;
2074
2075 while (ishex (*buff, &nibble))
2076 {
2077 buff++;
2078 retval = retval << 4;
2079 retval |= nibble & 0x0f;
2080 }
2081 *result = retval;
2082 return buff;
2083}
2084
2085static char *
2086unpack_nibble (char *buf, int *val)
2087{
2088 *val = fromhex (*buf++);
2089 return buf;
2090}
2091
2092static char *
2093pack_nibble (char *buf, int nibble)
2094{
2095 *buf++ = hexchars[(nibble & 0x0f)];
2096 return buf;
2097}
2098
2099static char *
2100pack_hex_byte (char *pkt, int byte)
2101{
2102 *pkt++ = hexchars[(byte >> 4) & 0xf];
2103 *pkt++ = hexchars[(byte & 0xf)];
2104 return pkt;
2105}
2106
2107static char *
2108unpack_byte (char *buf, int *value)
2109{
2110 *value = stub_unpack_int (buf, 2);
2111 return buf + 2;
2112}
2113
2114static char *
2115pack_int (char *buf, int value)
2116{
2117 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2118 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2119 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2120 buf = pack_hex_byte (buf, (value & 0xff));
2121 return buf;
2122}
2123
2124static char *
2125unpack_int (char *buf, int *value)
2126{
2127 *value = stub_unpack_int (buf, 8);
2128 return buf + 8;
2129}
2130
2131#if 0 /* Currently unused, uncomment when needed. */
2132static char *pack_string (char *pkt, char *string);
2133
2134static char *
2135pack_string (char *pkt, char *string)
2136{
2137 char ch;
2138 int len;
2139
2140 len = strlen (string);
2141 if (len > 200)
2142 len = 200; /* Bigger than most GDB packets, junk??? */
2143 pkt = pack_hex_byte (pkt, len);
2144 while (len-- > 0)
2145 {
2146 ch = *string++;
2147 if ((ch == '\0') || (ch == '#'))
2148 ch = '*'; /* Protect encapsulation. */
2149 *pkt++ = ch;
2150 }
2151 return pkt;
2152}
2153#endif /* 0 (unused) */
2154
2155static char *
2156unpack_string (char *src, char *dest, int length)
2157{
2158 while (length--)
2159 *dest++ = *src++;
2160 *dest = '\0';
2161 return src;
2162}
2163
2164static char *
2165pack_threadid (char *pkt, threadref *id)
2166{
2167 char *limit;
2168 unsigned char *altid;
2169
2170 altid = (unsigned char *) id;
2171 limit = pkt + BUF_THREAD_ID_SIZE;
2172 while (pkt < limit)
2173 pkt = pack_hex_byte (pkt, *altid++);
2174 return pkt;
2175}
2176
2177
2178static char *
2179unpack_threadid (char *inbuf, threadref *id)
2180{
2181 char *altref;
2182 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2183 int x, y;
2184
2185 altref = (char *) id;
2186
2187 while (inbuf < limit)
2188 {
2189 x = stubhex (*inbuf++);
2190 y = stubhex (*inbuf++);
2191 *altref++ = (x << 4) | y;
2192 }
2193 return inbuf;
2194}
2195
2196/* Externally, threadrefs are 64 bits but internally, they are still
c50c785c 2197 ints. This is due to a mismatch of specifications. We would like
5796c8dc
SS
2198 to use 64bit thread references internally. This is an adapter
2199 function. */
2200
2201void
2202int_to_threadref (threadref *id, int value)
2203{
2204 unsigned char *scan;
2205
2206 scan = (unsigned char *) id;
2207 {
2208 int i = 4;
2209 while (i--)
2210 *scan++ = 0;
2211 }
2212 *scan++ = (value >> 24) & 0xff;
2213 *scan++ = (value >> 16) & 0xff;
2214 *scan++ = (value >> 8) & 0xff;
2215 *scan++ = (value & 0xff);
2216}
2217
2218static int
2219threadref_to_int (threadref *ref)
2220{
2221 int i, value = 0;
2222 unsigned char *scan;
2223
2224 scan = *ref;
2225 scan += 4;
2226 i = 4;
2227 while (i-- > 0)
2228 value = (value << 8) | ((*scan++) & 0xff);
2229 return value;
2230}
2231
2232static void
2233copy_threadref (threadref *dest, threadref *src)
2234{
2235 int i;
2236 unsigned char *csrc, *cdest;
2237
2238 csrc = (unsigned char *) src;
2239 cdest = (unsigned char *) dest;
2240 i = 8;
2241 while (i--)
2242 *cdest++ = *csrc++;
2243}
2244
2245static int
2246threadmatch (threadref *dest, threadref *src)
2247{
2248 /* Things are broken right now, so just assume we got a match. */
2249#if 0
2250 unsigned char *srcp, *destp;
2251 int i, result;
2252 srcp = (char *) src;
2253 destp = (char *) dest;
2254
2255 result = 1;
2256 while (i-- > 0)
2257 result &= (*srcp++ == *destp++) ? 1 : 0;
2258 return result;
2259#endif
2260 return 1;
2261}
2262
2263/*
2264 threadid:1, # always request threadid
2265 context_exists:2,
2266 display:4,
2267 unique_name:8,
2268 more_display:16
2269 */
2270
2271/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2272
2273static char *
2274pack_threadinfo_request (char *pkt, int mode, threadref *id)
2275{
2276 *pkt++ = 'q'; /* Info Query */
2277 *pkt++ = 'P'; /* process or thread info */
2278 pkt = pack_int (pkt, mode); /* mode */
2279 pkt = pack_threadid (pkt, id); /* threadid */
2280 *pkt = '\0'; /* terminate */
2281 return pkt;
2282}
2283
2284/* These values tag the fields in a thread info response packet. */
2285/* Tagging the fields allows us to request specific fields and to
2286 add more fields as time goes by. */
2287
2288#define TAG_THREADID 1 /* Echo the thread identifier. */
2289#define TAG_EXISTS 2 /* Is this process defined enough to
2290 fetch registers and its stack? */
2291#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2292#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2293#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2294 the process. */
2295
2296static int
2297remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2298 struct gdb_ext_thread_info *info)
2299{
2300 struct remote_state *rs = get_remote_state ();
2301 int mask, length;
2302 int tag;
2303 threadref ref;
2304 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2305 int retval = 1;
2306
2307 /* info->threadid = 0; FIXME: implement zero_threadref. */
2308 info->active = 0;
2309 info->display[0] = '\0';
2310 info->shortname[0] = '\0';
2311 info->more_display[0] = '\0';
2312
2313 /* Assume the characters indicating the packet type have been
2314 stripped. */
2315 pkt = unpack_int (pkt, &mask); /* arg mask */
2316 pkt = unpack_threadid (pkt, &ref);
2317
2318 if (mask == 0)
2319 warning (_("Incomplete response to threadinfo request."));
2320 if (!threadmatch (&ref, expectedref))
2321 { /* This is an answer to a different request. */
2322 warning (_("ERROR RMT Thread info mismatch."));
2323 return 0;
2324 }
2325 copy_threadref (&info->threadid, &ref);
2326
2327 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2328
2329 /* Packets are terminated with nulls. */
2330 while ((pkt < limit) && mask && *pkt)
2331 {
2332 pkt = unpack_int (pkt, &tag); /* tag */
2333 pkt = unpack_byte (pkt, &length); /* length */
2334 if (!(tag & mask)) /* Tags out of synch with mask. */
2335 {
2336 warning (_("ERROR RMT: threadinfo tag mismatch."));
2337 retval = 0;
2338 break;
2339 }
2340 if (tag == TAG_THREADID)
2341 {
2342 if (length != 16)
2343 {
2344 warning (_("ERROR RMT: length of threadid is not 16."));
2345 retval = 0;
2346 break;
2347 }
2348 pkt = unpack_threadid (pkt, &ref);
2349 mask = mask & ~TAG_THREADID;
2350 continue;
2351 }
2352 if (tag == TAG_EXISTS)
2353 {
2354 info->active = stub_unpack_int (pkt, length);
2355 pkt += length;
2356 mask = mask & ~(TAG_EXISTS);
2357 if (length > 8)
2358 {
2359 warning (_("ERROR RMT: 'exists' length too long."));
2360 retval = 0;
2361 break;
2362 }
2363 continue;
2364 }
2365 if (tag == TAG_THREADNAME)
2366 {
2367 pkt = unpack_string (pkt, &info->shortname[0], length);
2368 mask = mask & ~TAG_THREADNAME;
2369 continue;
2370 }
2371 if (tag == TAG_DISPLAY)
2372 {
2373 pkt = unpack_string (pkt, &info->display[0], length);
2374 mask = mask & ~TAG_DISPLAY;
2375 continue;
2376 }
2377 if (tag == TAG_MOREDISPLAY)
2378 {
2379 pkt = unpack_string (pkt, &info->more_display[0], length);
2380 mask = mask & ~TAG_MOREDISPLAY;
2381 continue;
2382 }
2383 warning (_("ERROR RMT: unknown thread info tag."));
2384 break; /* Not a tag we know about. */
2385 }
2386 return retval;
2387}
2388
2389static int
2390remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2391 struct gdb_ext_thread_info *info)
2392{
2393 struct remote_state *rs = get_remote_state ();
2394 int result;
2395
2396 pack_threadinfo_request (rs->buf, fieldset, threadid);
2397 putpkt (rs->buf);
2398 getpkt (&rs->buf, &rs->buf_size, 0);
2399
2400 if (rs->buf[0] == '\0')
2401 return 0;
2402
2403 result = remote_unpack_thread_info_response (rs->buf + 2,
2404 threadid, info);
2405 return result;
2406}
2407
2408/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2409
2410static char *
2411pack_threadlist_request (char *pkt, int startflag, int threadcount,
2412 threadref *nextthread)
2413{
2414 *pkt++ = 'q'; /* info query packet */
2415 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2416 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2417 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2418 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2419 *pkt = '\0';
2420 return pkt;
2421}
2422
2423/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2424
2425static int
2426parse_threadlist_response (char *pkt, int result_limit,
2427 threadref *original_echo, threadref *resultlist,
2428 int *doneflag)
2429{
2430 struct remote_state *rs = get_remote_state ();
2431 char *limit;
2432 int count, resultcount, done;
2433
2434 resultcount = 0;
2435 /* Assume the 'q' and 'M chars have been stripped. */
2436 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2437 /* done parse past here */
2438 pkt = unpack_byte (pkt, &count); /* count field */
2439 pkt = unpack_nibble (pkt, &done);
2440 /* The first threadid is the argument threadid. */
2441 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2442 while ((count-- > 0) && (pkt < limit))
2443 {
2444 pkt = unpack_threadid (pkt, resultlist++);
2445 if (resultcount++ >= result_limit)
2446 break;
2447 }
2448 if (doneflag)
2449 *doneflag = done;
2450 return resultcount;
2451}
2452
2453static int
2454remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2455 int *done, int *result_count, threadref *threadlist)
2456{
2457 struct remote_state *rs = get_remote_state ();
2458 static threadref echo_nextthread;
2459 int result = 1;
2460
2461 /* Trancate result limit to be smaller than the packet size. */
c50c785c
JM
2462 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2463 >= get_remote_packet_size ())
5796c8dc
SS
2464 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2465
2466 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2467 putpkt (rs->buf);
2468 getpkt (&rs->buf, &rs->buf_size, 0);
2469
2470 if (*rs->buf == '\0')
c50c785c 2471 return 0;
5796c8dc
SS
2472 else
2473 *result_count =
2474 parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
2475 threadlist, done);
2476
2477 if (!threadmatch (&echo_nextthread, nextthread))
2478 {
2479 /* FIXME: This is a good reason to drop the packet. */
2480 /* Possably, there is a duplicate response. */
2481 /* Possabilities :
2482 retransmit immediatly - race conditions
2483 retransmit after timeout - yes
2484 exit
2485 wait for packet, then exit
2486 */
2487 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2488 return 0; /* I choose simply exiting. */
2489 }
2490 if (*result_count <= 0)
2491 {
2492 if (*done != 1)
2493 {
2494 warning (_("RMT ERROR : failed to get remote thread list."));
2495 result = 0;
2496 }
2497 return result; /* break; */
2498 }
2499 if (*result_count > result_limit)
2500 {
2501 *result_count = 0;
2502 warning (_("RMT ERROR: threadlist response longer than requested."));
2503 return 0;
2504 }
2505 return result;
2506}
2507
2508/* This is the interface between remote and threads, remotes upper
2509 interface. */
2510
2511/* remote_find_new_threads retrieves the thread list and for each
2512 thread in the list, looks up the thread in GDB's internal list,
2513 adding the thread if it does not already exist. This involves
2514 getting partial thread lists from the remote target so, polling the
2515 quit_flag is required. */
2516
2517
2518/* About this many threadisds fit in a packet. */
2519
2520#define MAXTHREADLISTRESULTS 32
2521
2522static int
2523remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2524 int looplimit)
2525{
2526 int done, i, result_count;
2527 int startflag = 1;
2528 int result = 1;
2529 int loopcount = 0;
2530 static threadref nextthread;
2531 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
2532
2533 done = 0;
2534 while (!done)
2535 {
2536 if (loopcount++ > looplimit)
2537 {
2538 result = 0;
2539 warning (_("Remote fetch threadlist -infinite loop-."));
2540 break;
2541 }
2542 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
2543 &done, &result_count, resultthreadlist))
2544 {
2545 result = 0;
2546 break;
2547 }
2548 /* Clear for later iterations. */
2549 startflag = 0;
2550 /* Setup to resume next batch of thread references, set nextthread. */
2551 if (result_count >= 1)
2552 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
2553 i = 0;
2554 while (result_count--)
2555 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
2556 break;
2557 }
2558 return result;
2559}
2560
2561static int
2562remote_newthread_step (threadref *ref, void *context)
2563{
2564 int pid = ptid_get_pid (inferior_ptid);
2565 ptid_t ptid = ptid_build (pid, 0, threadref_to_int (ref));
2566
2567 if (!in_thread_list (ptid))
2568 add_thread (ptid);
2569 return 1; /* continue iterator */
2570}
2571
2572#define CRAZY_MAX_THREADS 1000
2573
2574static ptid_t
2575remote_current_thread (ptid_t oldpid)
2576{
2577 struct remote_state *rs = get_remote_state ();
2578
2579 putpkt ("qC");
2580 getpkt (&rs->buf, &rs->buf_size, 0);
2581 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2582 return read_ptid (&rs->buf[2], NULL);
2583 else
2584 return oldpid;
2585}
2586
2587/* Find new threads for info threads command.
2588 * Original version, using John Metzler's thread protocol.
2589 */
2590
2591static void
2592remote_find_new_threads (void)
2593{
2594 remote_threadlist_iterator (remote_newthread_step, 0,
2595 CRAZY_MAX_THREADS);
2596}
2597
cf7f2e2d
JM
2598#if defined(HAVE_LIBEXPAT)
2599
2600typedef struct thread_item
2601{
2602 ptid_t ptid;
2603 char *extra;
2604 int core;
2605} thread_item_t;
2606DEF_VEC_O(thread_item_t);
2607
2608struct threads_parsing_context
2609{
2610 VEC (thread_item_t) *items;
2611};
2612
2613static void
2614start_thread (struct gdb_xml_parser *parser,
2615 const struct gdb_xml_element *element,
2616 void *user_data, VEC(gdb_xml_value_s) *attributes)
2617{
2618 struct threads_parsing_context *data = user_data;
2619
2620 struct thread_item item;
2621 char *id;
c50c785c 2622 struct gdb_xml_value *attr;
cf7f2e2d 2623
c50c785c 2624 id = xml_find_attribute (attributes, "id")->value;
cf7f2e2d
JM
2625 item.ptid = read_ptid (id, NULL);
2626
c50c785c
JM
2627 attr = xml_find_attribute (attributes, "core");
2628 if (attr != NULL)
2629 item.core = *(ULONGEST *) attr->value;
cf7f2e2d
JM
2630 else
2631 item.core = -1;
2632
2633 item.extra = 0;
2634
2635 VEC_safe_push (thread_item_t, data->items, &item);
2636}
2637
2638static void
2639end_thread (struct gdb_xml_parser *parser,
2640 const struct gdb_xml_element *element,
2641 void *user_data, const char *body_text)
2642{
2643 struct threads_parsing_context *data = user_data;
2644
2645 if (body_text && *body_text)
2646 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2647}
2648
2649const struct gdb_xml_attribute thread_attributes[] = {
2650 { "id", GDB_XML_AF_NONE, NULL, NULL },
2651 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2652 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2653};
2654
2655const struct gdb_xml_element thread_children[] = {
2656 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2657};
2658
2659const struct gdb_xml_element threads_children[] = {
2660 { "thread", thread_attributes, thread_children,
2661 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2662 start_thread, end_thread },
2663 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2664};
2665
2666const struct gdb_xml_element threads_elements[] = {
2667 { "threads", NULL, threads_children,
2668 GDB_XML_EF_NONE, NULL, NULL },
2669 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2670};
2671
2672/* Discard the contents of the constructed thread info context. */
2673
2674static void
2675clear_threads_parsing_context (void *p)
2676{
2677 struct threads_parsing_context *context = p;
2678 int i;
2679 struct thread_item *item;
2680
2681 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2682 xfree (item->extra);
2683
2684 VEC_free (thread_item_t, context->items);
2685}
2686
2687#endif
2688
5796c8dc
SS
2689/*
2690 * Find all threads for info threads command.
2691 * Uses new thread protocol contributed by Cisco.
2692 * Falls back and attempts to use the older method (above)
2693 * if the target doesn't respond to the new method.
2694 */
2695
2696static void
2697remote_threads_info (struct target_ops *ops)
2698{
2699 struct remote_state *rs = get_remote_state ();
2700 char *bufp;
2701 ptid_t new_thread;
2702
2703 if (remote_desc == 0) /* paranoia */
2704 error (_("Command can only be used when connected to the remote target."));
2705
cf7f2e2d
JM
2706#if defined(HAVE_LIBEXPAT)
2707 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2708 {
2709 char *xml = target_read_stralloc (&current_target,
2710 TARGET_OBJECT_THREADS, NULL);
2711
2712 struct cleanup *back_to = make_cleanup (xfree, xml);
c50c785c 2713
cf7f2e2d
JM
2714 if (xml && *xml)
2715 {
cf7f2e2d 2716 struct threads_parsing_context context;
cf7f2e2d 2717
c50c785c
JM
2718 context.items = NULL;
2719 make_cleanup (clear_threads_parsing_context, &context);
cf7f2e2d 2720
c50c785c
JM
2721 if (gdb_xml_parse_quick (_("threads"), "threads.dtd",
2722 threads_elements, xml, &context) == 0)
cf7f2e2d
JM
2723 {
2724 int i;
2725 struct thread_item *item;
2726
c50c785c
JM
2727 for (i = 0;
2728 VEC_iterate (thread_item_t, context.items, i, item);
2729 ++i)
cf7f2e2d
JM
2730 {
2731 if (!ptid_equal (item->ptid, null_ptid))
2732 {
2733 struct private_thread_info *info;
2734 /* In non-stop mode, we assume new found threads
2735 are running until proven otherwise with a
2736 stop reply. In all-stop, we can only get
2737 here if all threads are stopped. */
2738 int running = non_stop ? 1 : 0;
2739
2740 remote_notice_new_inferior (item->ptid, running);
2741
2742 info = demand_private_info (item->ptid);
2743 info->core = item->core;
2744 info->extra = item->extra;
2745 item->extra = NULL;
2746 }
2747 }
2748 }
cf7f2e2d
JM
2749 }
2750
2751 do_cleanups (back_to);
2752 return;
2753 }
2754#endif
2755
5796c8dc
SS
2756 if (use_threadinfo_query)
2757 {
2758 putpkt ("qfThreadInfo");
2759 getpkt (&rs->buf, &rs->buf_size, 0);
2760 bufp = rs->buf;
2761 if (bufp[0] != '\0') /* q packet recognized */
2762 {
ef5ccd6c
JM
2763 struct cleanup *old_chain;
2764 char *saved_reply;
2765
2766 /* remote_notice_new_inferior (in the loop below) may make
2767 new RSP calls, which clobber rs->buf. Work with a
2768 copy. */
2769 bufp = saved_reply = xstrdup (rs->buf);
2770 old_chain = make_cleanup (free_current_contents, &saved_reply);
2771
5796c8dc
SS
2772 while (*bufp++ == 'm') /* reply contains one or more TID */
2773 {
2774 do
2775 {
2776 new_thread = read_ptid (bufp, &bufp);
2777 if (!ptid_equal (new_thread, null_ptid))
2778 {
2779 /* In non-stop mode, we assume new found threads
2780 are running until proven otherwise with a
2781 stop reply. In all-stop, we can only get
2782 here if all threads are stopped. */
2783 int running = non_stop ? 1 : 0;
2784
2785 remote_notice_new_inferior (new_thread, running);
2786 }
2787 }
2788 while (*bufp++ == ','); /* comma-separated list */
ef5ccd6c 2789 free_current_contents (&saved_reply);
5796c8dc
SS
2790 putpkt ("qsThreadInfo");
2791 getpkt (&rs->buf, &rs->buf_size, 0);
ef5ccd6c 2792 bufp = saved_reply = xstrdup (rs->buf);
5796c8dc 2793 }
ef5ccd6c 2794 do_cleanups (old_chain);
5796c8dc
SS
2795 return; /* done */
2796 }
2797 }
2798
2799 /* Only qfThreadInfo is supported in non-stop mode. */
2800 if (non_stop)
2801 return;
2802
2803 /* Else fall back to old method based on jmetzler protocol. */
2804 use_threadinfo_query = 0;
2805 remote_find_new_threads ();
2806 return;
2807}
2808
2809/*
2810 * Collect a descriptive string about the given thread.
2811 * The target may say anything it wants to about the thread
2812 * (typically info about its blocked / runnable state, name, etc.).
2813 * This string will appear in the info threads display.
2814 *
2815 * Optional: targets are not required to implement this function.
2816 */
2817
2818static char *
2819remote_threads_extra_info (struct thread_info *tp)
2820{
2821 struct remote_state *rs = get_remote_state ();
2822 int result;
2823 int set;
2824 threadref id;
2825 struct gdb_ext_thread_info threadinfo;
2826 static char display_buf[100]; /* arbitrary... */
2827 int n = 0; /* position in display_buf */
2828
2829 if (remote_desc == 0) /* paranoia */
2830 internal_error (__FILE__, __LINE__,
2831 _("remote_threads_extra_info"));
2832
2833 if (ptid_equal (tp->ptid, magic_null_ptid)
2834 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_tid (tp->ptid) == 0))
2835 /* This is the main thread which was added by GDB. The remote
2836 server doesn't know about it. */
2837 return NULL;
2838
cf7f2e2d
JM
2839 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2840 {
2841 struct thread_info *info = find_thread_ptid (tp->ptid);
2842
2843 if (info && info->private)
2844 return info->private->extra;
2845 else
2846 return NULL;
2847 }
2848
5796c8dc
SS
2849 if (use_threadextra_query)
2850 {
2851 char *b = rs->buf;
2852 char *endb = rs->buf + get_remote_packet_size ();
2853
2854 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2855 b += strlen (b);
2856 write_ptid (b, endb, tp->ptid);
2857
2858 putpkt (rs->buf);
2859 getpkt (&rs->buf, &rs->buf_size, 0);
2860 if (rs->buf[0] != 0)
2861 {
2862 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2863 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2864 display_buf [result] = '\0';
2865 return display_buf;
2866 }
2867 }
2868
2869 /* If the above query fails, fall back to the old method. */
2870 use_threadextra_query = 0;
2871 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2872 | TAG_MOREDISPLAY | TAG_DISPLAY;
2873 int_to_threadref (&id, ptid_get_tid (tp->ptid));
2874 if (remote_get_threadinfo (&id, set, &threadinfo))
2875 if (threadinfo.active)
2876 {
2877 if (*threadinfo.shortname)
2878 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2879 " Name: %s,", threadinfo.shortname);
2880 if (*threadinfo.display)
2881 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2882 " State: %s,", threadinfo.display);
2883 if (*threadinfo.more_display)
2884 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2885 " Priority: %s", threadinfo.more_display);
2886
2887 if (n > 0)
2888 {
2889 /* For purely cosmetic reasons, clear up trailing commas. */
2890 if (',' == display_buf[n-1])
2891 display_buf[n-1] = ' ';
2892 return display_buf;
2893 }
2894 }
2895 return NULL;
2896}
2897\f
2898
cf7f2e2d
JM
2899static int
2900remote_static_tracepoint_marker_at (CORE_ADDR addr,
2901 struct static_tracepoint_marker *marker)
2902{
2903 struct remote_state *rs = get_remote_state ();
2904 char *p = rs->buf;
2905
ef5ccd6c 2906 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
cf7f2e2d
JM
2907 p += strlen (p);
2908 p += hexnumstr (p, addr);
2909 putpkt (rs->buf);
2910 getpkt (&rs->buf, &rs->buf_size, 0);
2911 p = rs->buf;
2912
2913 if (*p == 'E')
2914 error (_("Remote failure reply: %s"), p);
2915
2916 if (*p++ == 'm')
2917 {
2918 parse_static_tracepoint_marker_definition (p, &p, marker);
2919 return 1;
2920 }
2921
2922 return 0;
2923}
2924
cf7f2e2d
JM
2925static VEC(static_tracepoint_marker_p) *
2926remote_static_tracepoint_markers_by_strid (const char *strid)
2927{
2928 struct remote_state *rs = get_remote_state ();
2929 VEC(static_tracepoint_marker_p) *markers = NULL;
2930 struct static_tracepoint_marker *marker = NULL;
2931 struct cleanup *old_chain;
2932 char *p;
2933
2934 /* Ask for a first packet of static tracepoint marker
2935 definition. */
2936 putpkt ("qTfSTM");
2937 getpkt (&rs->buf, &rs->buf_size, 0);
2938 p = rs->buf;
2939 if (*p == 'E')
2940 error (_("Remote failure reply: %s"), p);
2941
2942 old_chain = make_cleanup (free_current_marker, &marker);
2943
2944 while (*p++ == 'm')
2945 {
2946 if (marker == NULL)
2947 marker = XCNEW (struct static_tracepoint_marker);
2948
2949 do
2950 {
2951 parse_static_tracepoint_marker_definition (p, &p, marker);
2952
2953 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
2954 {
2955 VEC_safe_push (static_tracepoint_marker_p,
2956 markers, marker);
2957 marker = NULL;
2958 }
2959 else
2960 {
2961 release_static_tracepoint_marker (marker);
2962 memset (marker, 0, sizeof (*marker));
2963 }
2964 }
2965 while (*p++ == ','); /* comma-separated list */
2966 /* Ask for another packet of static tracepoint definition. */
2967 putpkt ("qTsSTM");
2968 getpkt (&rs->buf, &rs->buf_size, 0);
2969 p = rs->buf;
2970 }
2971
2972 do_cleanups (old_chain);
2973 return markers;
2974}
2975
2976\f
2977/* Implement the to_get_ada_task_ptid function for the remote targets. */
2978
2979static ptid_t
2980remote_get_ada_task_ptid (long lwp, long thread)
2981{
2982 return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
2983}
2984\f
2985
5796c8dc
SS
2986/* Restart the remote side; this is an extended protocol operation. */
2987
2988static void
2989extended_remote_restart (void)
2990{
2991 struct remote_state *rs = get_remote_state ();
2992
2993 /* Send the restart command; for reasons I don't understand the
2994 remote side really expects a number after the "R". */
2995 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
2996 putpkt (rs->buf);
2997
2998 remote_fileio_reset ();
2999}
3000\f
3001/* Clean up connection to a remote debugger. */
3002
3003static void
3004remote_close (int quitting)
3005{
3006 if (remote_desc == NULL)
3007 return; /* already closed */
3008
3009 /* Make sure we leave stdin registered in the event loop, and we
3010 don't leave the async SIGINT signal handler installed. */
3011 remote_terminal_ours ();
3012
3013 serial_close (remote_desc);
3014 remote_desc = NULL;
3015
3016 /* We don't have a connection to the remote stub anymore. Get rid
c50c785c
JM
3017 of all the inferiors and their threads we were controlling.
3018 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3019 will be unable to find the thread corresponding to (pid, 0, 0). */
cf7f2e2d 3020 inferior_ptid = null_ptid;
c50c785c 3021 discard_all_inferiors ();
5796c8dc 3022
ef5ccd6c
JM
3023 /* Stop replies may from inferiors which are still unknown to GDB.
3024 We are closing the remote target, so we should discard
3025 everything, including the stop replies from GDB-unknown
3026 inferiors. */
3027 discard_pending_stop_replies (NULL);
5796c8dc
SS
3028
3029 if (remote_async_inferior_event_token)
3030 delete_async_event_handler (&remote_async_inferior_event_token);
ef5ccd6c
JM
3031
3032 remote_notif_unregister_async_event_handler ();
5796c8dc
SS
3033}
3034
3035/* Query the remote side for the text, data and bss offsets. */
3036
3037static void
3038get_offsets (void)
3039{
3040 struct remote_state *rs = get_remote_state ();
3041 char *buf;
3042 char *ptr;
3043 int lose, num_segments = 0, do_sections, do_segments;
3044 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3045 struct section_offsets *offs;
3046 struct symfile_segment_data *data;
3047
3048 if (symfile_objfile == NULL)
3049 return;
3050
3051 putpkt ("qOffsets");
3052 getpkt (&rs->buf, &rs->buf_size, 0);
3053 buf = rs->buf;
3054
3055 if (buf[0] == '\000')
3056 return; /* Return silently. Stub doesn't support
3057 this command. */
3058 if (buf[0] == 'E')
3059 {
3060 warning (_("Remote failure reply: %s"), buf);
3061 return;
3062 }
3063
3064 /* Pick up each field in turn. This used to be done with scanf, but
3065 scanf will make trouble if CORE_ADDR size doesn't match
3066 conversion directives correctly. The following code will work
3067 with any size of CORE_ADDR. */
3068 text_addr = data_addr = bss_addr = 0;
3069 ptr = buf;
3070 lose = 0;
3071
3072 if (strncmp (ptr, "Text=", 5) == 0)
3073 {
3074 ptr += 5;
3075 /* Don't use strtol, could lose on big values. */
3076 while (*ptr && *ptr != ';')
3077 text_addr = (text_addr << 4) + fromhex (*ptr++);
3078
3079 if (strncmp (ptr, ";Data=", 6) == 0)
3080 {
3081 ptr += 6;
3082 while (*ptr && *ptr != ';')
3083 data_addr = (data_addr << 4) + fromhex (*ptr++);
3084 }
3085 else
3086 lose = 1;
3087
3088 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
3089 {
3090 ptr += 5;
3091 while (*ptr && *ptr != ';')
3092 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3093
3094 if (bss_addr != data_addr)
3095 warning (_("Target reported unsupported offsets: %s"), buf);
3096 }
3097 else
3098 lose = 1;
3099 }
3100 else if (strncmp (ptr, "TextSeg=", 8) == 0)
3101 {
3102 ptr += 8;
3103 /* Don't use strtol, could lose on big values. */
3104 while (*ptr && *ptr != ';')
3105 text_addr = (text_addr << 4) + fromhex (*ptr++);
3106 num_segments = 1;
3107
3108 if (strncmp (ptr, ";DataSeg=", 9) == 0)
3109 {
3110 ptr += 9;
3111 while (*ptr && *ptr != ';')
3112 data_addr = (data_addr << 4) + fromhex (*ptr++);
3113 num_segments++;
3114 }
3115 }
3116 else
3117 lose = 1;
3118
3119 if (lose)
3120 error (_("Malformed response to offset query, %s"), buf);
3121 else if (*ptr != '\0')
3122 warning (_("Target reported unsupported offsets: %s"), buf);
3123
3124 offs = ((struct section_offsets *)
3125 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3126 memcpy (offs, symfile_objfile->section_offsets,
3127 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3128
3129 data = get_symfile_segment_data (symfile_objfile->obfd);
3130 do_segments = (data != NULL);
3131 do_sections = num_segments == 0;
3132
3133 if (num_segments > 0)
3134 {
3135 segments[0] = text_addr;
3136 segments[1] = data_addr;
3137 }
3138 /* If we have two segments, we can still try to relocate everything
3139 by assuming that the .text and .data offsets apply to the whole
3140 text and data segments. Convert the offsets given in the packet
3141 to base addresses for symfile_map_offsets_to_segments. */
3142 else if (data && data->num_segments == 2)
3143 {
3144 segments[0] = data->segment_bases[0] + text_addr;
3145 segments[1] = data->segment_bases[1] + data_addr;
3146 num_segments = 2;
3147 }
3148 /* If the object file has only one segment, assume that it is text
3149 rather than data; main programs with no writable data are rare,
3150 but programs with no code are useless. Of course the code might
3151 have ended up in the data segment... to detect that we would need
3152 the permissions here. */
3153 else if (data && data->num_segments == 1)
3154 {
3155 segments[0] = data->segment_bases[0] + text_addr;
3156 num_segments = 1;
3157 }
3158 /* There's no way to relocate by segment. */
3159 else
3160 do_segments = 0;
3161
3162 if (do_segments)
3163 {
3164 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3165 offs, num_segments, segments);
3166
3167 if (ret == 0 && !do_sections)
c50c785c
JM
3168 error (_("Can not handle qOffsets TextSeg "
3169 "response with this symbol file"));
5796c8dc
SS
3170
3171 if (ret > 0)
3172 do_sections = 0;
3173 }
3174
3175 if (data)
3176 free_symfile_segment_data (data);
3177
3178 if (do_sections)
3179 {
3180 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3181
c50c785c
JM
3182 /* This is a temporary kludge to force data and bss to use the
3183 same offsets because that's what nlmconv does now. The real
3184 solution requires changes to the stub and remote.c that I
3185 don't have time to do right now. */
5796c8dc
SS
3186
3187 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3188 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3189 }
3190
3191 objfile_relocate (symfile_objfile, offs);
3192}
3193
3194/* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3195 threads we know are stopped already. This is used during the
3196 initial remote connection in non-stop mode --- threads that are
3197 reported as already being stopped are left stopped. */
3198
3199static int
3200set_stop_requested_callback (struct thread_info *thread, void *data)
3201{
3202 /* If we have a stop reply for this thread, it must be stopped. */
3203 if (peek_stop_reply (thread->ptid))
3204 set_stop_requested (thread->ptid, 1);
3205
3206 return 0;
3207}
3208
cf7f2e2d
JM
3209/* Send interrupt_sequence to remote target. */
3210static void
c50c785c 3211send_interrupt_sequence (void)
cf7f2e2d
JM
3212{
3213 if (interrupt_sequence_mode == interrupt_sequence_control_c)
ef5ccd6c 3214 remote_serial_write ("\x03", 1);
cf7f2e2d
JM
3215 else if (interrupt_sequence_mode == interrupt_sequence_break)
3216 serial_send_break (remote_desc);
3217 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3218 {
3219 serial_send_break (remote_desc);
ef5ccd6c 3220 remote_serial_write ("g", 1);
cf7f2e2d
JM
3221 }
3222 else
3223 internal_error (__FILE__, __LINE__,
3224 _("Invalid value for interrupt_sequence_mode: %s."),
3225 interrupt_sequence_mode);
3226}
3227
ef5ccd6c
JM
3228
3229/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3230 and extract the PTID. Returns NULL_PTID if not found. */
3231
3232static ptid_t
3233stop_reply_extract_thread (char *stop_reply)
3234{
3235 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3236 {
3237 char *p;
3238
3239 /* Txx r:val ; r:val (...) */
3240 p = &stop_reply[3];
3241
3242 /* Look for "register" named "thread". */
3243 while (*p != '\0')
3244 {
3245 char *p1;
3246
3247 p1 = strchr (p, ':');
3248 if (p1 == NULL)
3249 return null_ptid;
3250
3251 if (strncmp (p, "thread", p1 - p) == 0)
3252 return read_ptid (++p1, &p);
3253
3254 p1 = strchr (p, ';');
3255 if (p1 == NULL)
3256 return null_ptid;
3257 p1++;
3258
3259 p = p1;
3260 }
3261 }
3262
3263 return null_ptid;
3264}
3265
3266/* Query the remote target for which is the current thread/process,
3267 add it to our tables, and update INFERIOR_PTID. The caller is
3268 responsible for setting the state such that the remote end is ready
3269 to return the current thread.
3270
3271 This function is called after handling the '?' or 'vRun' packets,
3272 whose response is a stop reply from which we can also try
3273 extracting the thread. If the target doesn't support the explicit
3274 qC query, we infer the current thread from that stop reply, passed
3275 in in WAIT_STATUS, which may be NULL. */
3276
3277static void
3278add_current_inferior_and_thread (char *wait_status)
3279{
3280 struct remote_state *rs = get_remote_state ();
3281 int fake_pid_p = 0;
3282 ptid_t ptid = null_ptid;
3283
3284 inferior_ptid = null_ptid;
3285
3286 /* Now, if we have thread information, update inferior_ptid. First
3287 if we have a stop reply handy, maybe it's a T stop reply with a
3288 "thread" register we can extract the current thread from. If
3289 not, ask the remote which is the current thread, with qC. The
3290 former method avoids a roundtrip. Note we don't use
3291 remote_parse_stop_reply as that makes use of the target
3292 architecture, which we haven't yet fully determined at this
3293 point. */
3294 if (wait_status != NULL)
3295 ptid = stop_reply_extract_thread (wait_status);
3296 if (ptid_equal (ptid, null_ptid))
3297 ptid = remote_current_thread (inferior_ptid);
3298
3299 if (!ptid_equal (ptid, null_ptid))
3300 {
3301 if (!remote_multi_process_p (rs))
3302 fake_pid_p = 1;
3303
3304 inferior_ptid = ptid;
3305 }
3306 else
3307 {
3308 /* Without this, some commands which require an active target
3309 (such as kill) won't work. This variable serves (at least)
3310 double duty as both the pid of the target process (if it has
3311 such), and as a flag indicating that a target is active. */
3312 inferior_ptid = magic_null_ptid;
3313 fake_pid_p = 1;
3314 }
3315
3316 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1);
3317
3318 /* Add the main thread. */
3319 add_thread_silent (inferior_ptid);
3320}
3321
5796c8dc 3322static void
a45ae5f8 3323remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
5796c8dc 3324{
5796c8dc
SS
3325 struct remote_state *rs = get_remote_state ();
3326 struct packet_config *noack_config;
3327 char *wait_status = NULL;
3328
3329 immediate_quit++; /* Allow user to interrupt it. */
ef5ccd6c 3330 QUIT;
5796c8dc 3331
cf7f2e2d
JM
3332 if (interrupt_on_connect)
3333 send_interrupt_sequence ();
3334
c50c785c
JM
3335 /* Ack any packet which the remote side has already sent. */
3336 serial_write (remote_desc, "+", 1);
3337
a45ae5f8
JM
3338 /* Signal other parts that we're going through the initial setup,
3339 and so things may not be stable yet. */
3340 rs->starting_up = 1;
3341
5796c8dc
SS
3342 /* The first packet we send to the target is the optional "supported
3343 packets" request. If the target can answer this, it will tell us
3344 which later probes to skip. */
3345 remote_query_supported ();
3346
cf7f2e2d
JM
3347 /* If the stub wants to get a QAllow, compose one and send it. */
3348 if (remote_protocol_packets[PACKET_QAllow].support != PACKET_DISABLE)
3349 remote_set_permissions ();
3350
5796c8dc
SS
3351 /* Next, we possibly activate noack mode.
3352
3353 If the QStartNoAckMode packet configuration is set to AUTO,
3354 enable noack mode if the stub reported a wish for it with
3355 qSupported.
3356
3357 If set to TRUE, then enable noack mode even if the stub didn't
3358 report it in qSupported. If the stub doesn't reply OK, the
3359 session ends with an error.
3360
3361 If FALSE, then don't activate noack mode, regardless of what the
3362 stub claimed should be the default with qSupported. */
3363
3364 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3365
3366 if (noack_config->detect == AUTO_BOOLEAN_TRUE
3367 || (noack_config->detect == AUTO_BOOLEAN_AUTO
3368 && noack_config->support == PACKET_ENABLE))
3369 {
3370 putpkt ("QStartNoAckMode");
3371 getpkt (&rs->buf, &rs->buf_size, 0);
3372 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3373 rs->noack_mode = 1;
3374 }
3375
a45ae5f8 3376 if (extended_p)
5796c8dc
SS
3377 {
3378 /* Tell the remote that we are using the extended protocol. */
3379 putpkt ("!");
3380 getpkt (&rs->buf, &rs->buf_size, 0);
3381 }
3382
ef5ccd6c
JM
3383 /* Let the target know which signals it is allowed to pass down to
3384 the program. */
3385 update_signals_program_target ();
3386
5796c8dc
SS
3387 /* Next, if the target can specify a description, read it. We do
3388 this before anything involving memory or registers. */
3389 target_find_description ();
3390
cf7f2e2d
JM
3391 /* Next, now that we know something about the target, update the
3392 address spaces in the program spaces. */
3393 update_address_spaces ();
3394
5796c8dc
SS
3395 /* On OSs where the list of libraries is global to all
3396 processes, we fetch them early. */
ef5ccd6c 3397 if (gdbarch_has_global_solist (target_gdbarch ()))
a45ae5f8 3398 solib_add (NULL, from_tty, target, auto_solib_add);
5796c8dc
SS
3399
3400 if (non_stop)
3401 {
3402 if (!rs->non_stop_aware)
c50c785c
JM
3403 error (_("Non-stop mode requested, but remote "
3404 "does not support non-stop"));
5796c8dc
SS
3405
3406 putpkt ("QNonStop:1");
3407 getpkt (&rs->buf, &rs->buf_size, 0);
3408
3409 if (strcmp (rs->buf, "OK") != 0)
c50c785c 3410 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
5796c8dc
SS
3411
3412 /* Find about threads and processes the stub is already
3413 controlling. We default to adding them in the running state.
3414 The '?' query below will then tell us about which threads are
3415 stopped. */
a45ae5f8 3416 remote_threads_info (target);
5796c8dc
SS
3417 }
3418 else if (rs->non_stop_aware)
3419 {
3420 /* Don't assume that the stub can operate in all-stop mode.
ef5ccd6c 3421 Request it explicitly. */
5796c8dc
SS
3422 putpkt ("QNonStop:0");
3423 getpkt (&rs->buf, &rs->buf_size, 0);
3424
3425 if (strcmp (rs->buf, "OK") != 0)
c50c785c 3426 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
5796c8dc
SS
3427 }
3428
3429 /* Check whether the target is running now. */
3430 putpkt ("?");
3431 getpkt (&rs->buf, &rs->buf_size, 0);
3432
3433 if (!non_stop)
3434 {
ef5ccd6c
JM
3435 ptid_t ptid;
3436 int fake_pid_p = 0;
3437 struct inferior *inf;
3438
5796c8dc
SS
3439 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3440 {
a45ae5f8 3441 if (!extended_p)
5796c8dc
SS
3442 error (_("The target is not running (try extended-remote?)"));
3443
3444 /* We're connected, but not running. Drop out before we
3445 call start_remote. */
a45ae5f8 3446 rs->starting_up = 0;
5796c8dc
SS
3447 return;
3448 }
3449 else
3450 {
3451 /* Save the reply for later. */
3452 wait_status = alloca (strlen (rs->buf) + 1);
3453 strcpy (wait_status, rs->buf);
3454 }
3455
3456 /* Let the stub know that we want it to return the thread. */
3457 set_continue_thread (minus_one_ptid);
3458
ef5ccd6c 3459 add_current_inferior_and_thread (wait_status);
5796c8dc 3460
a45ae5f8
JM
3461 /* init_wait_for_inferior should be called before get_offsets in order
3462 to manage `inserted' flag in bp loc in a correct state.
3463 breakpoint_init_inferior, called from init_wait_for_inferior, set
3464 `inserted' flag to 0, while before breakpoint_re_set, called from
3465 start_remote, set `inserted' flag to 1. In the initialization of
3466 inferior, breakpoint_init_inferior should be called first, and then
3467 breakpoint_re_set can be called. If this order is broken, state of
3468 `inserted' flag is wrong, and cause some problems on breakpoint
3469 manipulation. */
3470 init_wait_for_inferior ();
3471
5796c8dc
SS
3472 get_offsets (); /* Get text, data & bss offsets. */
3473
3474 /* If we could not find a description using qXfer, and we know
3475 how to do it some other way, try again. This is not
3476 supported for non-stop; it could be, but it is tricky if
3477 there are no stopped threads when we connect. */
a45ae5f8 3478 if (remote_read_description_p (target)
ef5ccd6c 3479 && gdbarch_target_desc (target_gdbarch ()) == NULL)
5796c8dc
SS
3480 {
3481 target_clear_description ();
3482 target_find_description ();
3483 }
3484
3485 /* Use the previously fetched status. */
3486 gdb_assert (wait_status != NULL);
3487 strcpy (rs->buf, wait_status);
3488 rs->cached_wait_status = 1;
3489
3490 immediate_quit--;
a45ae5f8 3491 start_remote (from_tty); /* Initialize gdb process mechanisms. */
5796c8dc
SS
3492 }
3493 else
3494 {
3495 /* Clear WFI global state. Do this before finding about new
3496 threads and inferiors, and setting the current inferior.
3497 Otherwise we would clear the proceed status of the current
3498 inferior when we want its stop_soon state to be preserved
3499 (see notice_new_inferior). */
3500 init_wait_for_inferior ();
3501
3502 /* In non-stop, we will either get an "OK", meaning that there
3503 are no stopped threads at this time; or, a regular stop
3504 reply. In the latter case, there may be more than one thread
3505 stopped --- we pull them all out using the vStopped
3506 mechanism. */
3507 if (strcmp (rs->buf, "OK") != 0)
3508 {
ef5ccd6c 3509 struct notif_client *notif = &notif_client_stop;
5796c8dc 3510
ef5ccd6c
JM
3511 /* remote_notif_get_pending_replies acks this one, and gets
3512 the rest out. */
3513 notif_client_stop.pending_event
3514 = remote_notif_parse (notif, rs->buf);
3515 remote_notif_get_pending_events (notif);
5796c8dc
SS
3516
3517 /* Make sure that threads that were stopped remain
3518 stopped. */
3519 iterate_over_threads (set_stop_requested_callback, NULL);
3520 }
3521
3522 if (target_can_async_p ())
3523 target_async (inferior_event_handler, 0);
3524
3525 if (thread_count () == 0)
3526 {
a45ae5f8 3527 if (!extended_p)
5796c8dc
SS
3528 error (_("The target is not running (try extended-remote?)"));
3529
3530 /* We're connected, but not running. Drop out before we
3531 call start_remote. */
a45ae5f8 3532 rs->starting_up = 0;
5796c8dc
SS
3533 return;
3534 }
3535
3536 /* Let the stub know that we want it to return the thread. */
3537
3538 /* Force the stub to choose a thread. */
3539 set_general_thread (null_ptid);
3540
3541 /* Query it. */
3542 inferior_ptid = remote_current_thread (minus_one_ptid);
3543 if (ptid_equal (inferior_ptid, minus_one_ptid))
3544 error (_("remote didn't report the current thread in non-stop mode"));
3545
3546 get_offsets (); /* Get text, data & bss offsets. */
3547
3548 /* In non-stop mode, any cached wait status will be stored in
3549 the stop reply queue. */
3550 gdb_assert (wait_status == NULL);
cf7f2e2d 3551
a45ae5f8
JM
3552 /* Report all signals during attach/startup. */
3553 remote_pass_signals (0, NULL);
5796c8dc
SS
3554 }
3555
3556 /* If we connected to a live target, do some additional setup. */
3557 if (target_has_execution)
3558 {
3559 if (exec_bfd) /* No use without an exec file. */
3560 remote_check_symbols (symfile_objfile);
3561 }
3562
cf7f2e2d
JM
3563 /* Possibly the target has been engaged in a trace run started
3564 previously; find out where things are at. */
3565 if (remote_get_trace_status (current_trace_status ()) != -1)
3566 {
3567 struct uploaded_tp *uploaded_tps = NULL;
3568 struct uploaded_tsv *uploaded_tsvs = NULL;
5796c8dc 3569
cf7f2e2d
JM
3570 if (current_trace_status ()->running)
3571 printf_filtered (_("Trace is already running on the target.\n"));
3572
3573 /* Get trace state variables first, they may be checked when
3574 parsing uploaded commands. */
3575
3576 remote_upload_trace_state_variables (&uploaded_tsvs);
3577
3578 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3579
3580 remote_upload_tracepoints (&uploaded_tps);
3581
3582 merge_uploaded_tracepoints (&uploaded_tps);
3583 }
3584
a45ae5f8
JM
3585 /* The thread and inferior lists are now synchronized with the
3586 target, our symbols have been relocated, and we're merged the
3587 target's tracepoints with ours. We're done with basic start
3588 up. */
3589 rs->starting_up = 0;
3590
cf7f2e2d 3591 /* If breakpoints are global, insert them now. */
ef5ccd6c 3592 if (gdbarch_has_global_breakpoints (target_gdbarch ())
cf7f2e2d
JM
3593 && breakpoints_always_inserted_mode ())
3594 insert_breakpoints ();
3595}
3596
3597/* Open a connection to a remote debugger.
5796c8dc
SS
3598 NAME is the filename used for communication. */
3599
3600static void
3601remote_open (char *name, int from_tty)
3602{
3603 remote_open_1 (name, from_tty, &remote_ops, 0);
3604}
3605
3606/* Open a connection to a remote debugger using the extended
3607 remote gdb protocol. NAME is the filename used for communication. */
3608
3609static void
3610extended_remote_open (char *name, int from_tty)
3611{
3612 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3613}
3614
3615/* Generic code for opening a connection to a remote target. */
3616
3617static void
3618init_all_packet_configs (void)
3619{
3620 int i;
cf7f2e2d 3621
5796c8dc
SS
3622 for (i = 0; i < PACKET_MAX; i++)
3623 update_packet_config (&remote_protocol_packets[i]);
3624}
3625
3626/* Symbol look-up. */
3627
3628static void
3629remote_check_symbols (struct objfile *objfile)
3630{
3631 struct remote_state *rs = get_remote_state ();
3632 char *msg, *reply, *tmp;
3633 struct minimal_symbol *sym;
3634 int end;
3635
c50c785c
JM
3636 /* The remote side has no concept of inferiors that aren't running
3637 yet, it only knows about running processes. If we're connected
3638 but our current inferior is not running, we should not invite the
3639 remote target to request symbol lookups related to its
3640 (unrelated) current process. */
3641 if (!target_has_execution)
3642 return;
3643
5796c8dc
SS
3644 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
3645 return;
3646
c50c785c
JM
3647 /* Make sure the remote is pointing at the right process. Note
3648 there's no way to select "no process". */
5796c8dc
SS
3649 set_general_process ();
3650
3651 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3652 because we need both at the same time. */
3653 msg = alloca (get_remote_packet_size ());
3654
3655 /* Invite target to request symbol lookups. */
3656
3657 putpkt ("qSymbol::");
3658 getpkt (&rs->buf, &rs->buf_size, 0);
3659 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
3660 reply = rs->buf;
3661
3662 while (strncmp (reply, "qSymbol:", 8) == 0)
3663 {
3664 tmp = &reply[8];
3665 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
3666 msg[end] = '\0';
3667 sym = lookup_minimal_symbol (msg, NULL, NULL);
3668 if (sym == NULL)
3669 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
3670 else
3671 {
ef5ccd6c 3672 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5796c8dc
SS
3673 CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
3674
3675 /* If this is a function address, return the start of code
3676 instead of any data function descriptor. */
ef5ccd6c 3677 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
5796c8dc
SS
3678 sym_addr,
3679 &current_target);
3680
3681 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
3682 phex_nz (sym_addr, addr_size), &reply[8]);
3683 }
3684
3685 putpkt (msg);
3686 getpkt (&rs->buf, &rs->buf_size, 0);
3687 reply = rs->buf;
3688 }
3689}
3690
3691static struct serial *
3692remote_serial_open (char *name)
3693{
3694 static int udp_warning = 0;
3695
3696 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3697 of in ser-tcp.c, because it is the remote protocol assuming that the
3698 serial connection is reliable and not the serial connection promising
3699 to be. */
3700 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
3701 {
c50c785c
JM
3702 warning (_("The remote protocol may be unreliable over UDP.\n"
3703 "Some events may be lost, rendering further debugging "
3704 "impossible."));
5796c8dc
SS
3705 udp_warning = 1;
3706 }
3707
3708 return serial_open (name);
3709}
3710
cf7f2e2d
JM
3711/* Inform the target of our permission settings. The permission flags
3712 work without this, but if the target knows the settings, it can do
3713 a couple things. First, it can add its own check, to catch cases
3714 that somehow manage to get by the permissions checks in target
3715 methods. Second, if the target is wired to disallow particular
3716 settings (for instance, a system in the field that is not set up to
3717 be able to stop at a breakpoint), it can object to any unavailable
3718 permissions. */
3719
3720void
3721remote_set_permissions (void)
3722{
3723 struct remote_state *rs = get_remote_state ();
3724
ef5ccd6c
JM
3725 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3726 "WriteReg:%x;WriteMem:%x;"
3727 "InsertBreak:%x;InsertTrace:%x;"
3728 "InsertFastTrace:%x;Stop:%x",
3729 may_write_registers, may_write_memory,
3730 may_insert_breakpoints, may_insert_tracepoints,
3731 may_insert_fast_tracepoints, may_stop);
cf7f2e2d
JM
3732 putpkt (rs->buf);
3733 getpkt (&rs->buf, &rs->buf_size, 0);
3734
3735 /* If the target didn't like the packet, warn the user. Do not try
3736 to undo the user's settings, that would just be maddening. */
3737 if (strcmp (rs->buf, "OK") != 0)
c50c785c 3738 warning (_("Remote refused setting permissions with: %s"), rs->buf);
cf7f2e2d
JM
3739}
3740
5796c8dc
SS
3741/* This type describes each known response to the qSupported
3742 packet. */
3743struct protocol_feature
3744{
3745 /* The name of this protocol feature. */
3746 const char *name;
3747
3748 /* The default for this protocol feature. */
3749 enum packet_support default_support;
3750
3751 /* The function to call when this feature is reported, or after
3752 qSupported processing if the feature is not supported.
3753 The first argument points to this structure. The second
3754 argument indicates whether the packet requested support be
3755 enabled, disabled, or probed (or the default, if this function
3756 is being called at the end of processing and this feature was
3757 not reported). The third argument may be NULL; if not NULL, it
3758 is a NUL-terminated string taken from the packet following
3759 this feature's name and an equals sign. */
3760 void (*func) (const struct protocol_feature *, enum packet_support,
3761 const char *);
3762
3763 /* The corresponding packet for this feature. Only used if
3764 FUNC is remote_supported_packet. */
3765 int packet;
3766};
3767
3768static void
3769remote_supported_packet (const struct protocol_feature *feature,
3770 enum packet_support support,
3771 const char *argument)
3772{
3773 if (argument)
3774 {
3775 warning (_("Remote qSupported response supplied an unexpected value for"
3776 " \"%s\"."), feature->name);
3777 return;
3778 }
3779
3780 if (remote_protocol_packets[feature->packet].support
3781 == PACKET_SUPPORT_UNKNOWN)
3782 remote_protocol_packets[feature->packet].support = support;
3783}
3784
3785static void
3786remote_packet_size (const struct protocol_feature *feature,
3787 enum packet_support support, const char *value)
3788{