* source.c (open): Strip DOS drive letter if present before
[binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
4 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
5 2010 Free Software Foundation, Inc.
6
7 This file is part of GDB.
8
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21
22 /* See the GDB User Guide for details of the GDB remote protocol. */
23
24 #include "defs.h"
25 #include "gdb_string.h"
26 #include <ctype.h>
27 #include <fcntl.h>
28 #include "inferior.h"
29 #include "bfd.h"
30 #include "symfile.h"
31 #include "exceptions.h"
32 #include "target.h"
33 /*#include "terminal.h" */
34 #include "gdbcmd.h"
35 #include "objfiles.h"
36 #include "gdb-stabs.h"
37 #include "gdbthread.h"
38 #include "remote.h"
39 #include "regcache.h"
40 #include "value.h"
41 #include "gdb_assert.h"
42 #include "observer.h"
43 #include "solib.h"
44 #include "cli/cli-decode.h"
45 #include "cli/cli-setshow.h"
46 #include "target-descriptions.h"
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"
63 #include "xml-support.h"
64
65 #include "memory-map.h"
66
67 #include "tracepoint.h"
68 #include "ax.h"
69 #include "ax-gdb.h"
70
71 /* temp hacks for tracepoint encoding migration */
72 static char *target_buf;
73 static long target_buf_size;
74 /*static*/ void
75 encode_actions (struct breakpoint *t, struct bp_location *tloc,
76 char ***tdp_actions, char ***stepping_actions);
77
78 /* The size to align memory write packets, when practical. The protocol
79 does not guarantee any alignment, and gdb will generate short
80 writes and unaligned writes, but even as a best-effort attempt this
81 can improve bulk transfers. For instance, if a write is misaligned
82 relative to the target's data bus, the stub may need to make an extra
83 round trip fetching data from the target. This doesn't make a
84 huge difference, but it's easy to do, so we try to be helpful.
85
86 The alignment chosen is arbitrary; usually data bus width is
87 important here, not the possibly larger cache line size. */
88 enum { REMOTE_ALIGN_WRITES = 16 };
89
90 /* Prototypes for local functions. */
91 static void cleanup_sigint_signal_handler (void *dummy);
92 static void initialize_sigint_signal_handler (void);
93 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
94 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
95 int forever);
96
97 static void handle_remote_sigint (int);
98 static void handle_remote_sigint_twice (int);
99 static void async_remote_interrupt (gdb_client_data);
100 void async_remote_interrupt_twice (gdb_client_data);
101
102 static void remote_files_info (struct target_ops *ignore);
103
104 static void remote_prepare_to_store (struct regcache *regcache);
105
106 static void remote_open (char *name, int from_tty);
107
108 static void extended_remote_open (char *name, int from_tty);
109
110 static void remote_open_1 (char *, int, struct target_ops *, int extended_p);
111
112 static void remote_close (int quitting);
113
114 static void remote_mourn (struct target_ops *ops);
115
116 static void extended_remote_restart (void);
117
118 static void extended_remote_mourn (struct target_ops *);
119
120 static void remote_mourn_1 (struct target_ops *);
121
122 static void remote_send (char **buf, long *sizeof_buf_p);
123
124 static int readchar (int timeout);
125
126 static void remote_kill (struct target_ops *ops);
127
128 static int tohex (int nib);
129
130 static int remote_can_async_p (void);
131
132 static int remote_is_async_p (void);
133
134 static void remote_async (void (*callback) (enum inferior_event_type event_type,
135 void *context), void *context);
136
137 static int remote_async_mask (int new_mask);
138
139 static void remote_detach (struct target_ops *ops, char *args, int from_tty);
140
141 static void remote_interrupt (int signo);
142
143 static void remote_interrupt_twice (int signo);
144
145 static void interrupt_query (void);
146
147 static void set_general_thread (struct ptid ptid);
148 static void set_continue_thread (struct ptid ptid);
149
150 static void get_offsets (void);
151
152 static void skip_frame (void);
153
154 static long read_frame (char **buf_p, long *sizeof_buf);
155
156 static int hexnumlen (ULONGEST num);
157
158 static void init_remote_ops (void);
159
160 static void init_extended_remote_ops (void);
161
162 static void remote_stop (ptid_t);
163
164 static int ishex (int ch, int *val);
165
166 static int stubhex (int ch);
167
168 static int hexnumstr (char *, ULONGEST);
169
170 static int hexnumnstr (char *, ULONGEST, int);
171
172 static CORE_ADDR remote_address_masked (CORE_ADDR);
173
174 static void print_packet (char *);
175
176 static void compare_sections_command (char *, int);
177
178 static void packet_command (char *, int);
179
180 static int stub_unpack_int (char *buff, int fieldlength);
181
182 static ptid_t remote_current_thread (ptid_t oldptid);
183
184 static void remote_find_new_threads (void);
185
186 static void record_currthread (ptid_t currthread);
187
188 static int fromhex (int a);
189
190 extern int hex2bin (const char *hex, gdb_byte *bin, int count);
191
192 extern int bin2hex (const gdb_byte *bin, char *hex, int count);
193
194 static int putpkt_binary (char *buf, int cnt);
195
196 static void check_binary_download (CORE_ADDR addr);
197
198 struct packet_config;
199
200 static void show_packet_config_cmd (struct packet_config *config);
201
202 static void update_packet_config (struct packet_config *config);
203
204 static void set_remote_protocol_packet_cmd (char *args, int from_tty,
205 struct cmd_list_element *c);
206
207 static void show_remote_protocol_packet_cmd (struct ui_file *file,
208 int from_tty,
209 struct cmd_list_element *c,
210 const char *value);
211
212 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
213 static ptid_t read_ptid (char *buf, char **obuf);
214
215 struct remote_state;
216 static int remote_get_trace_status (struct trace_status *ts);
217
218 static int remote_upload_tracepoints (struct uploaded_tp **utpp);
219
220 static int remote_upload_trace_state_variables (struct uploaded_tsv **utsvp);
221
222 static void remote_query_supported (void);
223
224 static void remote_check_symbols (struct objfile *objfile);
225
226 void _initialize_remote (void);
227
228 struct stop_reply;
229 static struct stop_reply *stop_reply_xmalloc (void);
230 static void stop_reply_xfree (struct stop_reply *);
231 static void do_stop_reply_xfree (void *arg);
232 static void remote_parse_stop_reply (char *buf, struct stop_reply *);
233 static void push_stop_reply (struct stop_reply *);
234 static void remote_get_pending_stop_replies (void);
235 static void discard_pending_stop_replies (int pid);
236 static int peek_stop_reply (ptid_t ptid);
237
238 static void remote_async_inferior_event_handler (gdb_client_data);
239 static void remote_async_get_pending_events_handler (gdb_client_data);
240
241 static void remote_terminal_ours (void);
242
243 static int remote_read_description_p (struct target_ops *target);
244
245 /* The non-stop remote protocol provisions for one pending stop reply.
246 This is where we keep it until it is acknowledged. */
247
248 static struct stop_reply *pending_stop_reply = NULL;
249
250 /* For "remote". */
251
252 static struct cmd_list_element *remote_cmdlist;
253
254 /* For "set remote" and "show remote". */
255
256 static struct cmd_list_element *remote_set_cmdlist;
257 static struct cmd_list_element *remote_show_cmdlist;
258
259 /* Description of the remote protocol state for the currently
260 connected target. This is per-target state, and independent of the
261 selected architecture. */
262
263 struct remote_state
264 {
265 /* A buffer to use for incoming packets, and its current size. The
266 buffer is grown dynamically for larger incoming packets.
267 Outgoing packets may also be constructed in this buffer.
268 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
269 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
270 packets. */
271 char *buf;
272 long buf_size;
273
274 /* If we negotiated packet size explicitly (and thus can bypass
275 heuristics for the largest packet size that will not overflow
276 a buffer in the stub), this will be set to that packet size.
277 Otherwise zero, meaning to use the guessed size. */
278 long explicit_packet_size;
279
280 /* remote_wait is normally called when the target is running and
281 waits for a stop reply packet. But sometimes we need to call it
282 when the target is already stopped. We can send a "?" packet
283 and have remote_wait read the response. Or, if we already have
284 the response, we can stash it in BUF and tell remote_wait to
285 skip calling getpkt. This flag is set when BUF contains a
286 stop reply packet and the target is not waiting. */
287 int cached_wait_status;
288
289 /* True, if in no ack mode. That is, neither GDB nor the stub will
290 expect acks from each other. The connection is assumed to be
291 reliable. */
292 int noack_mode;
293
294 /* True if we're connected in extended remote mode. */
295 int extended;
296
297 /* True if the stub reported support for multi-process
298 extensions. */
299 int multi_process_aware;
300
301 /* True if we resumed the target and we're waiting for the target to
302 stop. In the mean time, we can't start another command/query.
303 The remote server wouldn't be ready to process it, so we'd
304 timeout waiting for a reply that would never come and eventually
305 we'd close the connection. This can happen in asynchronous mode
306 because we allow GDB commands while the target is running. */
307 int waiting_for_stop_reply;
308
309 /* True if the stub reports support for non-stop mode. */
310 int non_stop_aware;
311
312 /* True if the stub reports support for vCont;t. */
313 int support_vCont_t;
314
315 /* True if the stub reports support for conditional tracepoints. */
316 int cond_tracepoints;
317
318 /* True if the stub reports support for fast tracepoints. */
319 int fast_tracepoints;
320
321 /* True if the stub can continue running a trace while GDB is
322 disconnected. */
323 int disconnected_tracing;
324
325 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
326 responded to that. */
327 int ctrlc_pending_p;
328 };
329
330 /* Private data that we'll store in (struct thread_info)->private. */
331 struct private_thread_info
332 {
333 char *extra;
334 int core;
335 };
336
337 static void
338 free_private_thread_info (struct private_thread_info *info)
339 {
340 xfree (info->extra);
341 xfree (info);
342 }
343
344 /* Returns true if the multi-process extensions are in effect. */
345 static int
346 remote_multi_process_p (struct remote_state *rs)
347 {
348 return rs->extended && rs->multi_process_aware;
349 }
350
351 /* This data could be associated with a target, but we do not always
352 have access to the current target when we need it, so for now it is
353 static. This will be fine for as long as only one target is in use
354 at a time. */
355 static struct remote_state remote_state;
356
357 static struct remote_state *
358 get_remote_state_raw (void)
359 {
360 return &remote_state;
361 }
362
363 /* Description of the remote protocol for a given architecture. */
364
365 struct packet_reg
366 {
367 long offset; /* Offset into G packet. */
368 long regnum; /* GDB's internal register number. */
369 LONGEST pnum; /* Remote protocol register number. */
370 int in_g_packet; /* Always part of G packet. */
371 /* long size in bytes; == register_size (target_gdbarch, regnum);
372 at present. */
373 /* char *name; == gdbarch_register_name (target_gdbarch, regnum);
374 at present. */
375 };
376
377 struct remote_arch_state
378 {
379 /* Description of the remote protocol registers. */
380 long sizeof_g_packet;
381
382 /* Description of the remote protocol registers indexed by REGNUM
383 (making an array gdbarch_num_regs in size). */
384 struct packet_reg *regs;
385
386 /* This is the size (in chars) of the first response to the ``g''
387 packet. It is used as a heuristic when determining the maximum
388 size of memory-read and memory-write packets. A target will
389 typically only reserve a buffer large enough to hold the ``g''
390 packet. The size does not include packet overhead (headers and
391 trailers). */
392 long actual_register_packet_size;
393
394 /* This is the maximum size (in chars) of a non read/write packet.
395 It is also used as a cap on the size of read/write packets. */
396 long remote_packet_size;
397 };
398
399 long sizeof_pkt = 2000;
400
401 /* Utility: generate error from an incoming stub packet. */
402 static void
403 trace_error (char *buf)
404 {
405 if (*buf++ != 'E')
406 return; /* not an error msg */
407 switch (*buf)
408 {
409 case '1': /* malformed packet error */
410 if (*++buf == '0') /* general case: */
411 error (_("remote.c: error in outgoing packet."));
412 else
413 error (_("remote.c: error in outgoing packet at field #%ld."),
414 strtol (buf, NULL, 16));
415 case '2':
416 error (_("trace API error 0x%s."), ++buf);
417 default:
418 error (_("Target returns error code '%s'."), buf);
419 }
420 }
421
422 /* Utility: wait for reply from stub, while accepting "O" packets. */
423 static char *
424 remote_get_noisy_reply (char **buf_p,
425 long *sizeof_buf)
426 {
427 do /* Loop on reply from remote stub. */
428 {
429 char *buf;
430 QUIT; /* allow user to bail out with ^C */
431 getpkt (buf_p, sizeof_buf, 0);
432 buf = *buf_p;
433 if (buf[0] == 'E')
434 trace_error (buf);
435 else if (buf[0] == 'O' && buf[1] != 'K')
436 remote_console_output (buf + 1); /* 'O' message from stub */
437 else
438 return buf; /* here's the actual reply */
439 }
440 while (1);
441 }
442
443 /* Handle for retreving the remote protocol data from gdbarch. */
444 static struct gdbarch_data *remote_gdbarch_data_handle;
445
446 static struct remote_arch_state *
447 get_remote_arch_state (void)
448 {
449 return gdbarch_data (target_gdbarch, remote_gdbarch_data_handle);
450 }
451
452 /* Fetch the global remote target state. */
453
454 static struct remote_state *
455 get_remote_state (void)
456 {
457 /* Make sure that the remote architecture state has been
458 initialized, because doing so might reallocate rs->buf. Any
459 function which calls getpkt also needs to be mindful of changes
460 to rs->buf, but this call limits the number of places which run
461 into trouble. */
462 get_remote_arch_state ();
463
464 return get_remote_state_raw ();
465 }
466
467 static int
468 compare_pnums (const void *lhs_, const void *rhs_)
469 {
470 const struct packet_reg * const *lhs = lhs_;
471 const struct packet_reg * const *rhs = rhs_;
472
473 if ((*lhs)->pnum < (*rhs)->pnum)
474 return -1;
475 else if ((*lhs)->pnum == (*rhs)->pnum)
476 return 0;
477 else
478 return 1;
479 }
480
481 static void *
482 init_remote_state (struct gdbarch *gdbarch)
483 {
484 int regnum, num_remote_regs, offset;
485 struct remote_state *rs = get_remote_state_raw ();
486 struct remote_arch_state *rsa;
487 struct packet_reg **remote_regs;
488
489 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
490
491 /* Use the architecture to build a regnum<->pnum table, which will be
492 1:1 unless a feature set specifies otherwise. */
493 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
494 gdbarch_num_regs (gdbarch),
495 struct packet_reg);
496 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
497 {
498 struct packet_reg *r = &rsa->regs[regnum];
499
500 if (register_size (gdbarch, regnum) == 0)
501 /* Do not try to fetch zero-sized (placeholder) registers. */
502 r->pnum = -1;
503 else
504 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
505
506 r->regnum = regnum;
507 }
508
509 /* Define the g/G packet format as the contents of each register
510 with a remote protocol number, in order of ascending protocol
511 number. */
512
513 remote_regs = alloca (gdbarch_num_regs (gdbarch)
514 * sizeof (struct packet_reg *));
515 for (num_remote_regs = 0, regnum = 0;
516 regnum < gdbarch_num_regs (gdbarch);
517 regnum++)
518 if (rsa->regs[regnum].pnum != -1)
519 remote_regs[num_remote_regs++] = &rsa->regs[regnum];
520
521 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
522 compare_pnums);
523
524 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
525 {
526 remote_regs[regnum]->in_g_packet = 1;
527 remote_regs[regnum]->offset = offset;
528 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
529 }
530
531 /* Record the maximum possible size of the g packet - it may turn out
532 to be smaller. */
533 rsa->sizeof_g_packet = offset;
534
535 /* Default maximum number of characters in a packet body. Many
536 remote stubs have a hardwired buffer size of 400 bytes
537 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
538 as the maximum packet-size to ensure that the packet and an extra
539 NUL character can always fit in the buffer. This stops GDB
540 trashing stubs that try to squeeze an extra NUL into what is
541 already a full buffer (As of 1999-12-04 that was most stubs). */
542 rsa->remote_packet_size = 400 - 1;
543
544 /* This one is filled in when a ``g'' packet is received. */
545 rsa->actual_register_packet_size = 0;
546
547 /* Should rsa->sizeof_g_packet needs more space than the
548 default, adjust the size accordingly. Remember that each byte is
549 encoded as two characters. 32 is the overhead for the packet
550 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
551 (``$NN:G...#NN'') is a better guess, the below has been padded a
552 little. */
553 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
554 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
555
556 /* Make sure that the packet buffer is plenty big enough for
557 this architecture. */
558 if (rs->buf_size < rsa->remote_packet_size)
559 {
560 rs->buf_size = 2 * rsa->remote_packet_size;
561 rs->buf = xrealloc (rs->buf, rs->buf_size);
562 }
563
564 return rsa;
565 }
566
567 /* Return the current allowed size of a remote packet. This is
568 inferred from the current architecture, and should be used to
569 limit the length of outgoing packets. */
570 static long
571 get_remote_packet_size (void)
572 {
573 struct remote_state *rs = get_remote_state ();
574 struct remote_arch_state *rsa = get_remote_arch_state ();
575
576 if (rs->explicit_packet_size)
577 return rs->explicit_packet_size;
578
579 return rsa->remote_packet_size;
580 }
581
582 static struct packet_reg *
583 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
584 {
585 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch))
586 return NULL;
587 else
588 {
589 struct packet_reg *r = &rsa->regs[regnum];
590 gdb_assert (r->regnum == regnum);
591 return r;
592 }
593 }
594
595 static struct packet_reg *
596 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
597 {
598 int i;
599 for (i = 0; i < gdbarch_num_regs (target_gdbarch); i++)
600 {
601 struct packet_reg *r = &rsa->regs[i];
602 if (r->pnum == pnum)
603 return r;
604 }
605 return NULL;
606 }
607
608 /* FIXME: graces/2002-08-08: These variables should eventually be
609 bound to an instance of the target object (as in gdbarch-tdep()),
610 when such a thing exists. */
611
612 /* This is set to the data address of the access causing the target
613 to stop for a watchpoint. */
614 static CORE_ADDR remote_watch_data_address;
615
616 /* This is non-zero if target stopped for a watchpoint. */
617 static int remote_stopped_by_watchpoint_p;
618
619 static struct target_ops remote_ops;
620
621 static struct target_ops extended_remote_ops;
622
623 static int remote_async_mask_value = 1;
624
625 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
626 ``forever'' still use the normal timeout mechanism. This is
627 currently used by the ASYNC code to guarentee that target reads
628 during the initial connect always time-out. Once getpkt has been
629 modified to return a timeout indication and, in turn
630 remote_wait()/wait_for_inferior() have gained a timeout parameter
631 this can go away. */
632 static int wait_forever_enabled_p = 1;
633
634 /* Allow the user to specify what sequence to send to the remote
635 when he requests a program interruption: Although ^C is usually
636 what remote systems expect (this is the default, here), it is
637 sometimes preferable to send a break. On other systems such
638 as the Linux kernel, a break followed by g, which is Magic SysRq g
639 is required in order to interrupt the execution. */
640 const char interrupt_sequence_control_c[] = "Ctrl-C";
641 const char interrupt_sequence_break[] = "BREAK";
642 const char interrupt_sequence_break_g[] = "BREAK-g";
643 static const char *interrupt_sequence_modes[] =
644 {
645 interrupt_sequence_control_c,
646 interrupt_sequence_break,
647 interrupt_sequence_break_g,
648 NULL
649 };
650 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
651
652 static void
653 show_interrupt_sequence (struct ui_file *file, int from_tty,
654 struct cmd_list_element *c,
655 const char *value)
656 {
657 if (interrupt_sequence_mode == interrupt_sequence_control_c)
658 fprintf_filtered (file,
659 _("Send the ASCII ETX character (Ctrl-c) "
660 "to the remote target to interrupt the "
661 "execution of the program.\n"));
662 else if (interrupt_sequence_mode == interrupt_sequence_break)
663 fprintf_filtered (file,
664 _("send a break signal to the remote target "
665 "to interrupt the execution of the program.\n"));
666 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
667 fprintf_filtered (file,
668 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
669 "the remote target to interrupt the execution "
670 "of Linux kernel.\n"));
671 else
672 internal_error (__FILE__, __LINE__,
673 _("Invalid value for interrupt_sequence_mode: %s."),
674 interrupt_sequence_mode);
675 }
676
677 /* This boolean variable specifies whether interrupt_sequence is sent
678 to the remote target when gdb connects to it.
679 This is mostly needed when you debug the Linux kernel: The Linux kernel
680 expects BREAK g which is Magic SysRq g for connecting gdb. */
681 static int interrupt_on_connect = 0;
682
683 /* This variable is used to implement the "set/show remotebreak" commands.
684 Since these commands are now deprecated in favor of "set/show remote
685 interrupt-sequence", it no longer has any effect on the code. */
686 static int remote_break;
687
688 static void
689 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
690 {
691 if (remote_break)
692 interrupt_sequence_mode = interrupt_sequence_break;
693 else
694 interrupt_sequence_mode = interrupt_sequence_control_c;
695 }
696
697 static void
698 show_remotebreak (struct ui_file *file, int from_tty,
699 struct cmd_list_element *c,
700 const char *value)
701 {
702 }
703
704 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
705 remote_open knows that we don't have a file open when the program
706 starts. */
707 static struct serial *remote_desc = NULL;
708
709 /* This variable sets the number of bits in an address that are to be
710 sent in a memory ("M" or "m") packet. Normally, after stripping
711 leading zeros, the entire address would be sent. This variable
712 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
713 initial implementation of remote.c restricted the address sent in
714 memory packets to ``host::sizeof long'' bytes - (typically 32
715 bits). Consequently, for 64 bit targets, the upper 32 bits of an
716 address was never sent. Since fixing this bug may cause a break in
717 some remote targets this variable is principly provided to
718 facilitate backward compatibility. */
719
720 static int remote_address_size;
721
722 /* Temporary to track who currently owns the terminal. See
723 remote_terminal_* for more details. */
724
725 static int remote_async_terminal_ours_p;
726
727 /* The executable file to use for "run" on the remote side. */
728
729 static char *remote_exec_file = "";
730
731 \f
732 /* User configurable variables for the number of characters in a
733 memory read/write packet. MIN (rsa->remote_packet_size,
734 rsa->sizeof_g_packet) is the default. Some targets need smaller
735 values (fifo overruns, et.al.) and some users need larger values
736 (speed up transfers). The variables ``preferred_*'' (the user
737 request), ``current_*'' (what was actually set) and ``forced_*''
738 (Positive - a soft limit, negative - a hard limit). */
739
740 struct memory_packet_config
741 {
742 char *name;
743 long size;
744 int fixed_p;
745 };
746
747 /* Compute the current size of a read/write packet. Since this makes
748 use of ``actual_register_packet_size'' the computation is dynamic. */
749
750 static long
751 get_memory_packet_size (struct memory_packet_config *config)
752 {
753 struct remote_state *rs = get_remote_state ();
754 struct remote_arch_state *rsa = get_remote_arch_state ();
755
756 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
757 law?) that some hosts don't cope very well with large alloca()
758 calls. Eventually the alloca() code will be replaced by calls to
759 xmalloc() and make_cleanups() allowing this restriction to either
760 be lifted or removed. */
761 #ifndef MAX_REMOTE_PACKET_SIZE
762 #define MAX_REMOTE_PACKET_SIZE 16384
763 #endif
764 /* NOTE: 20 ensures we can write at least one byte. */
765 #ifndef MIN_REMOTE_PACKET_SIZE
766 #define MIN_REMOTE_PACKET_SIZE 20
767 #endif
768 long what_they_get;
769 if (config->fixed_p)
770 {
771 if (config->size <= 0)
772 what_they_get = MAX_REMOTE_PACKET_SIZE;
773 else
774 what_they_get = config->size;
775 }
776 else
777 {
778 what_they_get = get_remote_packet_size ();
779 /* Limit the packet to the size specified by the user. */
780 if (config->size > 0
781 && what_they_get > config->size)
782 what_they_get = config->size;
783
784 /* Limit it to the size of the targets ``g'' response unless we have
785 permission from the stub to use a larger packet size. */
786 if (rs->explicit_packet_size == 0
787 && rsa->actual_register_packet_size > 0
788 && what_they_get > rsa->actual_register_packet_size)
789 what_they_get = rsa->actual_register_packet_size;
790 }
791 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
792 what_they_get = MAX_REMOTE_PACKET_SIZE;
793 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
794 what_they_get = MIN_REMOTE_PACKET_SIZE;
795
796 /* Make sure there is room in the global buffer for this packet
797 (including its trailing NUL byte). */
798 if (rs->buf_size < what_they_get + 1)
799 {
800 rs->buf_size = 2 * what_they_get;
801 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
802 }
803
804 return what_they_get;
805 }
806
807 /* Update the size of a read/write packet. If they user wants
808 something really big then do a sanity check. */
809
810 static void
811 set_memory_packet_size (char *args, struct memory_packet_config *config)
812 {
813 int fixed_p = config->fixed_p;
814 long size = config->size;
815 if (args == NULL)
816 error (_("Argument required (integer, `fixed' or `limited')."));
817 else if (strcmp (args, "hard") == 0
818 || strcmp (args, "fixed") == 0)
819 fixed_p = 1;
820 else if (strcmp (args, "soft") == 0
821 || strcmp (args, "limit") == 0)
822 fixed_p = 0;
823 else
824 {
825 char *end;
826 size = strtoul (args, &end, 0);
827 if (args == end)
828 error (_("Invalid %s (bad syntax)."), config->name);
829 #if 0
830 /* Instead of explicitly capping the size of a packet to
831 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
832 instead allowed to set the size to something arbitrarily
833 large. */
834 if (size > MAX_REMOTE_PACKET_SIZE)
835 error (_("Invalid %s (too large)."), config->name);
836 #endif
837 }
838 /* Extra checks? */
839 if (fixed_p && !config->fixed_p)
840 {
841 if (! query (_("The target may not be able to correctly handle a %s\n"
842 "of %ld bytes. Change the packet size? "),
843 config->name, size))
844 error (_("Packet size not changed."));
845 }
846 /* Update the config. */
847 config->fixed_p = fixed_p;
848 config->size = size;
849 }
850
851 static void
852 show_memory_packet_size (struct memory_packet_config *config)
853 {
854 printf_filtered (_("The %s is %ld. "), config->name, config->size);
855 if (config->fixed_p)
856 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
857 get_memory_packet_size (config));
858 else
859 printf_filtered (_("Packets are limited to %ld bytes.\n"),
860 get_memory_packet_size (config));
861 }
862
863 static struct memory_packet_config memory_write_packet_config =
864 {
865 "memory-write-packet-size",
866 };
867
868 static void
869 set_memory_write_packet_size (char *args, int from_tty)
870 {
871 set_memory_packet_size (args, &memory_write_packet_config);
872 }
873
874 static void
875 show_memory_write_packet_size (char *args, int from_tty)
876 {
877 show_memory_packet_size (&memory_write_packet_config);
878 }
879
880 static long
881 get_memory_write_packet_size (void)
882 {
883 return get_memory_packet_size (&memory_write_packet_config);
884 }
885
886 static struct memory_packet_config memory_read_packet_config =
887 {
888 "memory-read-packet-size",
889 };
890
891 static void
892 set_memory_read_packet_size (char *args, int from_tty)
893 {
894 set_memory_packet_size (args, &memory_read_packet_config);
895 }
896
897 static void
898 show_memory_read_packet_size (char *args, int from_tty)
899 {
900 show_memory_packet_size (&memory_read_packet_config);
901 }
902
903 static long
904 get_memory_read_packet_size (void)
905 {
906 long size = get_memory_packet_size (&memory_read_packet_config);
907 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
908 extra buffer size argument before the memory read size can be
909 increased beyond this. */
910 if (size > get_remote_packet_size ())
911 size = get_remote_packet_size ();
912 return size;
913 }
914
915 \f
916 /* Generic configuration support for packets the stub optionally
917 supports. Allows the user to specify the use of the packet as well
918 as allowing GDB to auto-detect support in the remote stub. */
919
920 enum packet_support
921 {
922 PACKET_SUPPORT_UNKNOWN = 0,
923 PACKET_ENABLE,
924 PACKET_DISABLE
925 };
926
927 struct packet_config
928 {
929 const char *name;
930 const char *title;
931 enum auto_boolean detect;
932 enum packet_support support;
933 };
934
935 /* Analyze a packet's return value and update the packet config
936 accordingly. */
937
938 enum packet_result
939 {
940 PACKET_ERROR,
941 PACKET_OK,
942 PACKET_UNKNOWN
943 };
944
945 static void
946 update_packet_config (struct packet_config *config)
947 {
948 switch (config->detect)
949 {
950 case AUTO_BOOLEAN_TRUE:
951 config->support = PACKET_ENABLE;
952 break;
953 case AUTO_BOOLEAN_FALSE:
954 config->support = PACKET_DISABLE;
955 break;
956 case AUTO_BOOLEAN_AUTO:
957 config->support = PACKET_SUPPORT_UNKNOWN;
958 break;
959 }
960 }
961
962 static void
963 show_packet_config_cmd (struct packet_config *config)
964 {
965 char *support = "internal-error";
966 switch (config->support)
967 {
968 case PACKET_ENABLE:
969 support = "enabled";
970 break;
971 case PACKET_DISABLE:
972 support = "disabled";
973 break;
974 case PACKET_SUPPORT_UNKNOWN:
975 support = "unknown";
976 break;
977 }
978 switch (config->detect)
979 {
980 case AUTO_BOOLEAN_AUTO:
981 printf_filtered (_("Support for the `%s' packet is auto-detected, currently %s.\n"),
982 config->name, support);
983 break;
984 case AUTO_BOOLEAN_TRUE:
985 case AUTO_BOOLEAN_FALSE:
986 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
987 config->name, support);
988 break;
989 }
990 }
991
992 static void
993 add_packet_config_cmd (struct packet_config *config, const char *name,
994 const char *title, int legacy)
995 {
996 char *set_doc;
997 char *show_doc;
998 char *cmd_name;
999
1000 config->name = name;
1001 config->title = title;
1002 config->detect = AUTO_BOOLEAN_AUTO;
1003 config->support = PACKET_SUPPORT_UNKNOWN;
1004 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1005 name, title);
1006 show_doc = xstrprintf ("Show current use of remote protocol `%s' (%s) packet",
1007 name, title);
1008 /* set/show TITLE-packet {auto,on,off} */
1009 cmd_name = xstrprintf ("%s-packet", title);
1010 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1011 &config->detect, set_doc, show_doc, NULL, /* help_doc */
1012 set_remote_protocol_packet_cmd,
1013 show_remote_protocol_packet_cmd,
1014 &remote_set_cmdlist, &remote_show_cmdlist);
1015 /* The command code copies the documentation strings. */
1016 xfree (set_doc);
1017 xfree (show_doc);
1018 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1019 if (legacy)
1020 {
1021 char *legacy_name;
1022 legacy_name = xstrprintf ("%s-packet", name);
1023 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1024 &remote_set_cmdlist);
1025 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1026 &remote_show_cmdlist);
1027 }
1028 }
1029
1030 static enum packet_result
1031 packet_check_result (const char *buf)
1032 {
1033 if (buf[0] != '\0')
1034 {
1035 /* The stub recognized the packet request. Check that the
1036 operation succeeded. */
1037 if (buf[0] == 'E'
1038 && isxdigit (buf[1]) && isxdigit (buf[2])
1039 && buf[3] == '\0')
1040 /* "Enn" - definitly an error. */
1041 return PACKET_ERROR;
1042
1043 /* Always treat "E." as an error. This will be used for
1044 more verbose error messages, such as E.memtypes. */
1045 if (buf[0] == 'E' && buf[1] == '.')
1046 return PACKET_ERROR;
1047
1048 /* The packet may or may not be OK. Just assume it is. */
1049 return PACKET_OK;
1050 }
1051 else
1052 /* The stub does not support the packet. */
1053 return PACKET_UNKNOWN;
1054 }
1055
1056 static enum packet_result
1057 packet_ok (const char *buf, struct packet_config *config)
1058 {
1059 enum packet_result result;
1060
1061 result = packet_check_result (buf);
1062 switch (result)
1063 {
1064 case PACKET_OK:
1065 case PACKET_ERROR:
1066 /* The stub recognized the packet request. */
1067 switch (config->support)
1068 {
1069 case PACKET_SUPPORT_UNKNOWN:
1070 if (remote_debug)
1071 fprintf_unfiltered (gdb_stdlog,
1072 "Packet %s (%s) is supported\n",
1073 config->name, config->title);
1074 config->support = PACKET_ENABLE;
1075 break;
1076 case PACKET_DISABLE:
1077 internal_error (__FILE__, __LINE__,
1078 _("packet_ok: attempt to use a disabled packet"));
1079 break;
1080 case PACKET_ENABLE:
1081 break;
1082 }
1083 break;
1084 case PACKET_UNKNOWN:
1085 /* The stub does not support the packet. */
1086 switch (config->support)
1087 {
1088 case PACKET_ENABLE:
1089 if (config->detect == AUTO_BOOLEAN_AUTO)
1090 /* If the stub previously indicated that the packet was
1091 supported then there is a protocol error.. */
1092 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1093 config->name, config->title);
1094 else
1095 /* The user set it wrong. */
1096 error (_("Enabled packet %s (%s) not recognized by stub"),
1097 config->name, config->title);
1098 break;
1099 case PACKET_SUPPORT_UNKNOWN:
1100 if (remote_debug)
1101 fprintf_unfiltered (gdb_stdlog,
1102 "Packet %s (%s) is NOT supported\n",
1103 config->name, config->title);
1104 config->support = PACKET_DISABLE;
1105 break;
1106 case PACKET_DISABLE:
1107 break;
1108 }
1109 break;
1110 }
1111
1112 return result;
1113 }
1114
1115 enum {
1116 PACKET_vCont = 0,
1117 PACKET_X,
1118 PACKET_qSymbol,
1119 PACKET_P,
1120 PACKET_p,
1121 PACKET_Z0,
1122 PACKET_Z1,
1123 PACKET_Z2,
1124 PACKET_Z3,
1125 PACKET_Z4,
1126 PACKET_vFile_open,
1127 PACKET_vFile_pread,
1128 PACKET_vFile_pwrite,
1129 PACKET_vFile_close,
1130 PACKET_vFile_unlink,
1131 PACKET_qXfer_auxv,
1132 PACKET_qXfer_features,
1133 PACKET_qXfer_libraries,
1134 PACKET_qXfer_memory_map,
1135 PACKET_qXfer_spu_read,
1136 PACKET_qXfer_spu_write,
1137 PACKET_qXfer_osdata,
1138 PACKET_qXfer_threads,
1139 PACKET_qGetTLSAddr,
1140 PACKET_qSupported,
1141 PACKET_QPassSignals,
1142 PACKET_qSearch_memory,
1143 PACKET_vAttach,
1144 PACKET_vRun,
1145 PACKET_QStartNoAckMode,
1146 PACKET_vKill,
1147 PACKET_qXfer_siginfo_read,
1148 PACKET_qXfer_siginfo_write,
1149 PACKET_qAttached,
1150 PACKET_ConditionalTracepoints,
1151 PACKET_FastTracepoints,
1152 PACKET_bc,
1153 PACKET_bs,
1154 PACKET_TracepointSource,
1155 PACKET_MAX
1156 };
1157
1158 static struct packet_config remote_protocol_packets[PACKET_MAX];
1159
1160 static void
1161 set_remote_protocol_packet_cmd (char *args, int from_tty,
1162 struct cmd_list_element *c)
1163 {
1164 struct packet_config *packet;
1165
1166 for (packet = remote_protocol_packets;
1167 packet < &remote_protocol_packets[PACKET_MAX];
1168 packet++)
1169 {
1170 if (&packet->detect == c->var)
1171 {
1172 update_packet_config (packet);
1173 return;
1174 }
1175 }
1176 internal_error (__FILE__, __LINE__, "Could not find config for %s",
1177 c->name);
1178 }
1179
1180 static void
1181 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1182 struct cmd_list_element *c,
1183 const char *value)
1184 {
1185 struct packet_config *packet;
1186
1187 for (packet = remote_protocol_packets;
1188 packet < &remote_protocol_packets[PACKET_MAX];
1189 packet++)
1190 {
1191 if (&packet->detect == c->var)
1192 {
1193 show_packet_config_cmd (packet);
1194 return;
1195 }
1196 }
1197 internal_error (__FILE__, __LINE__, "Could not find config for %s",
1198 c->name);
1199 }
1200
1201 /* Should we try one of the 'Z' requests? */
1202
1203 enum Z_packet_type
1204 {
1205 Z_PACKET_SOFTWARE_BP,
1206 Z_PACKET_HARDWARE_BP,
1207 Z_PACKET_WRITE_WP,
1208 Z_PACKET_READ_WP,
1209 Z_PACKET_ACCESS_WP,
1210 NR_Z_PACKET_TYPES
1211 };
1212
1213 /* For compatibility with older distributions. Provide a ``set remote
1214 Z-packet ...'' command that updates all the Z packet types. */
1215
1216 static enum auto_boolean remote_Z_packet_detect;
1217
1218 static void
1219 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1220 struct cmd_list_element *c)
1221 {
1222 int i;
1223 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1224 {
1225 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1226 update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
1227 }
1228 }
1229
1230 static void
1231 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1232 struct cmd_list_element *c,
1233 const char *value)
1234 {
1235 int i;
1236 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1237 {
1238 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1239 }
1240 }
1241
1242 /* Should we try the 'ThreadInfo' query packet?
1243
1244 This variable (NOT available to the user: auto-detect only!)
1245 determines whether GDB will use the new, simpler "ThreadInfo"
1246 query or the older, more complex syntax for thread queries.
1247 This is an auto-detect variable (set to true at each connect,
1248 and set to false when the target fails to recognize it). */
1249
1250 static int use_threadinfo_query;
1251 static int use_threadextra_query;
1252
1253 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1254 static struct async_signal_handler *sigint_remote_twice_token;
1255 static struct async_signal_handler *sigint_remote_token;
1256
1257 \f
1258 /* Asynchronous signal handle registered as event loop source for
1259 when we have pending events ready to be passed to the core. */
1260
1261 static struct async_event_handler *remote_async_inferior_event_token;
1262
1263 /* Asynchronous signal handle registered as event loop source for when
1264 the remote sent us a %Stop notification. The registered callback
1265 will do a vStopped sequence to pull the rest of the events out of
1266 the remote side into our event queue. */
1267
1268 static struct async_event_handler *remote_async_get_pending_events_token;
1269 \f
1270
1271 static ptid_t magic_null_ptid;
1272 static ptid_t not_sent_ptid;
1273 static ptid_t any_thread_ptid;
1274
1275 /* These are the threads which we last sent to the remote system. The
1276 TID member will be -1 for all or -2 for not sent yet. */
1277
1278 static ptid_t general_thread;
1279 static ptid_t continue_thread;
1280
1281 /* Find out if the stub attached to PID (and hence GDB should offer to
1282 detach instead of killing it when bailing out). */
1283
1284 static int
1285 remote_query_attached (int pid)
1286 {
1287 struct remote_state *rs = get_remote_state ();
1288
1289 if (remote_protocol_packets[PACKET_qAttached].support == PACKET_DISABLE)
1290 return 0;
1291
1292 if (remote_multi_process_p (rs))
1293 sprintf (rs->buf, "qAttached:%x", pid);
1294 else
1295 sprintf (rs->buf, "qAttached");
1296
1297 putpkt (rs->buf);
1298 getpkt (&rs->buf, &rs->buf_size, 0);
1299
1300 switch (packet_ok (rs->buf,
1301 &remote_protocol_packets[PACKET_qAttached]))
1302 {
1303 case PACKET_OK:
1304 if (strcmp (rs->buf, "1") == 0)
1305 return 1;
1306 break;
1307 case PACKET_ERROR:
1308 warning (_("Remote failure reply: %s"), rs->buf);
1309 break;
1310 case PACKET_UNKNOWN:
1311 break;
1312 }
1313
1314 return 0;
1315 }
1316
1317 /* Add PID to GDB's inferior table. Since we can be connected to a
1318 remote system before before knowing about any inferior, mark the
1319 target with execution when we find the first inferior. If ATTACHED
1320 is 1, then we had just attached to this inferior. If it is 0, then
1321 we just created this inferior. If it is -1, then try querying the
1322 remote stub to find out if it had attached to the inferior or
1323 not. */
1324
1325 static struct inferior *
1326 remote_add_inferior (int pid, int attached)
1327 {
1328 struct inferior *inf;
1329
1330 /* Check whether this process we're learning about is to be
1331 considered attached, or if is to be considered to have been
1332 spawned by the stub. */
1333 if (attached == -1)
1334 attached = remote_query_attached (pid);
1335
1336 if (gdbarch_has_global_solist (target_gdbarch))
1337 {
1338 /* If the target shares code across all inferiors, then every
1339 attach adds a new inferior. */
1340 inf = add_inferior (pid);
1341
1342 /* ... and every inferior is bound to the same program space.
1343 However, each inferior may still have its own address
1344 space. */
1345 inf->aspace = maybe_new_address_space ();
1346 inf->pspace = current_program_space;
1347 }
1348 else
1349 {
1350 /* In the traditional debugging scenario, there's a 1-1 match
1351 between program/address spaces. We simply bind the inferior
1352 to the program space's address space. */
1353 inf = current_inferior ();
1354 inferior_appeared (inf, pid);
1355 }
1356
1357 inf->attach_flag = attached;
1358
1359 return inf;
1360 }
1361
1362 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1363 according to RUNNING. */
1364
1365 static void
1366 remote_add_thread (ptid_t ptid, int running)
1367 {
1368 add_thread (ptid);
1369
1370 set_executing (ptid, running);
1371 set_running (ptid, running);
1372 }
1373
1374 /* Come here when we learn about a thread id from the remote target.
1375 It may be the first time we hear about such thread, so take the
1376 opportunity to add it to GDB's thread list. In case this is the
1377 first time we're noticing its corresponding inferior, add it to
1378 GDB's inferior list as well. */
1379
1380 static void
1381 remote_notice_new_inferior (ptid_t currthread, int running)
1382 {
1383 /* If this is a new thread, add it to GDB's thread list.
1384 If we leave it up to WFI to do this, bad things will happen. */
1385
1386 if (in_thread_list (currthread) && is_exited (currthread))
1387 {
1388 /* We're seeing an event on a thread id we knew had exited.
1389 This has to be a new thread reusing the old id. Add it. */
1390 remote_add_thread (currthread, running);
1391 return;
1392 }
1393
1394 if (!in_thread_list (currthread))
1395 {
1396 struct inferior *inf = NULL;
1397 int pid = ptid_get_pid (currthread);
1398
1399 if (ptid_is_pid (inferior_ptid)
1400 && pid == ptid_get_pid (inferior_ptid))
1401 {
1402 /* inferior_ptid has no thread member yet. This can happen
1403 with the vAttach -> remote_wait,"TAAthread:" path if the
1404 stub doesn't support qC. This is the first stop reported
1405 after an attach, so this is the main thread. Update the
1406 ptid in the thread list. */
1407 if (in_thread_list (pid_to_ptid (pid)))
1408 thread_change_ptid (inferior_ptid, currthread);
1409 else
1410 {
1411 remote_add_thread (currthread, running);
1412 inferior_ptid = currthread;
1413 }
1414 return;
1415 }
1416
1417 if (ptid_equal (magic_null_ptid, inferior_ptid))
1418 {
1419 /* inferior_ptid is not set yet. This can happen with the
1420 vRun -> remote_wait,"TAAthread:" path if the stub
1421 doesn't support qC. This is the first stop reported
1422 after an attach, so this is the main thread. Update the
1423 ptid in the thread list. */
1424 thread_change_ptid (inferior_ptid, currthread);
1425 return;
1426 }
1427
1428 /* When connecting to a target remote, or to a target
1429 extended-remote which already was debugging an inferior, we
1430 may not know about it yet. Add it before adding its child
1431 thread, so notifications are emitted in a sensible order. */
1432 if (!in_inferior_list (ptid_get_pid (currthread)))
1433 inf = remote_add_inferior (ptid_get_pid (currthread), -1);
1434
1435 /* This is really a new thread. Add it. */
1436 remote_add_thread (currthread, running);
1437
1438 /* If we found a new inferior, let the common code do whatever
1439 it needs to with it (e.g., read shared libraries, insert
1440 breakpoints). */
1441 if (inf != NULL)
1442 notice_new_inferior (currthread, running, 0);
1443 }
1444 }
1445
1446 /* Return the private thread data, creating it if necessary. */
1447
1448 struct private_thread_info *
1449 demand_private_info (ptid_t ptid)
1450 {
1451 struct thread_info *info = find_thread_ptid (ptid);
1452
1453 gdb_assert (info);
1454
1455 if (!info->private)
1456 {
1457 info->private = xmalloc (sizeof (*(info->private)));
1458 info->private_dtor = free_private_thread_info;
1459 info->private->core = -1;
1460 info->private->extra = 0;
1461 }
1462
1463 return info->private;
1464 }
1465
1466 /* Call this function as a result of
1467 1) A halt indication (T packet) containing a thread id
1468 2) A direct query of currthread
1469 3) Successful execution of set thread
1470 */
1471
1472 static void
1473 record_currthread (ptid_t currthread)
1474 {
1475 general_thread = currthread;
1476 }
1477
1478 static char *last_pass_packet;
1479
1480 /* If 'QPassSignals' is supported, tell the remote stub what signals
1481 it can simply pass through to the inferior without reporting. */
1482
1483 static void
1484 remote_pass_signals (void)
1485 {
1486 if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1487 {
1488 char *pass_packet, *p;
1489 int numsigs = (int) TARGET_SIGNAL_LAST;
1490 int count = 0, i;
1491
1492 gdb_assert (numsigs < 256);
1493 for (i = 0; i < numsigs; i++)
1494 {
1495 if (signal_stop_state (i) == 0
1496 && signal_print_state (i) == 0
1497 && signal_pass_state (i) == 1)
1498 count++;
1499 }
1500 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1501 strcpy (pass_packet, "QPassSignals:");
1502 p = pass_packet + strlen (pass_packet);
1503 for (i = 0; i < numsigs; i++)
1504 {
1505 if (signal_stop_state (i) == 0
1506 && signal_print_state (i) == 0
1507 && signal_pass_state (i) == 1)
1508 {
1509 if (i >= 16)
1510 *p++ = tohex (i >> 4);
1511 *p++ = tohex (i & 15);
1512 if (count)
1513 *p++ = ';';
1514 else
1515 break;
1516 count--;
1517 }
1518 }
1519 *p = 0;
1520 if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
1521 {
1522 struct remote_state *rs = get_remote_state ();
1523 char *buf = rs->buf;
1524
1525 putpkt (pass_packet);
1526 getpkt (&rs->buf, &rs->buf_size, 0);
1527 packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1528 if (last_pass_packet)
1529 xfree (last_pass_packet);
1530 last_pass_packet = pass_packet;
1531 }
1532 else
1533 xfree (pass_packet);
1534 }
1535 }
1536
1537 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1538 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1539 thread. If GEN is set, set the general thread, if not, then set
1540 the step/continue thread. */
1541 static void
1542 set_thread (struct ptid ptid, int gen)
1543 {
1544 struct remote_state *rs = get_remote_state ();
1545 ptid_t state = gen ? general_thread : continue_thread;
1546 char *buf = rs->buf;
1547 char *endbuf = rs->buf + get_remote_packet_size ();
1548
1549 if (ptid_equal (state, ptid))
1550 return;
1551
1552 *buf++ = 'H';
1553 *buf++ = gen ? 'g' : 'c';
1554 if (ptid_equal (ptid, magic_null_ptid))
1555 xsnprintf (buf, endbuf - buf, "0");
1556 else if (ptid_equal (ptid, any_thread_ptid))
1557 xsnprintf (buf, endbuf - buf, "0");
1558 else if (ptid_equal (ptid, minus_one_ptid))
1559 xsnprintf (buf, endbuf - buf, "-1");
1560 else
1561 write_ptid (buf, endbuf, ptid);
1562 putpkt (rs->buf);
1563 getpkt (&rs->buf, &rs->buf_size, 0);
1564 if (gen)
1565 general_thread = ptid;
1566 else
1567 continue_thread = ptid;
1568 }
1569
1570 static void
1571 set_general_thread (struct ptid ptid)
1572 {
1573 set_thread (ptid, 1);
1574 }
1575
1576 static void
1577 set_continue_thread (struct ptid ptid)
1578 {
1579 set_thread (ptid, 0);
1580 }
1581
1582 /* Change the remote current process. Which thread within the process
1583 ends up selected isn't important, as long as it is the same process
1584 as what INFERIOR_PTID points to.
1585
1586 This comes from that fact that there is no explicit notion of
1587 "selected process" in the protocol. The selected process for
1588 general operations is the process the selected general thread
1589 belongs to. */
1590
1591 static void
1592 set_general_process (void)
1593 {
1594 struct remote_state *rs = get_remote_state ();
1595
1596 /* If the remote can't handle multiple processes, don't bother. */
1597 if (!remote_multi_process_p (rs))
1598 return;
1599
1600 /* We only need to change the remote current thread if it's pointing
1601 at some other process. */
1602 if (ptid_get_pid (general_thread) != ptid_get_pid (inferior_ptid))
1603 set_general_thread (inferior_ptid);
1604 }
1605
1606 \f
1607 /* Return nonzero if the thread PTID is still alive on the remote
1608 system. */
1609
1610 static int
1611 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1612 {
1613 struct remote_state *rs = get_remote_state ();
1614 char *p, *endp;
1615
1616 if (ptid_equal (ptid, magic_null_ptid))
1617 /* The main thread is always alive. */
1618 return 1;
1619
1620 if (ptid_get_pid (ptid) != 0 && ptid_get_tid (ptid) == 0)
1621 /* The main thread is always alive. This can happen after a
1622 vAttach, if the remote side doesn't support
1623 multi-threading. */
1624 return 1;
1625
1626 p = rs->buf;
1627 endp = rs->buf + get_remote_packet_size ();
1628
1629 *p++ = 'T';
1630 write_ptid (p, endp, ptid);
1631
1632 putpkt (rs->buf);
1633 getpkt (&rs->buf, &rs->buf_size, 0);
1634 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1635 }
1636
1637 /* About these extended threadlist and threadinfo packets. They are
1638 variable length packets but, the fields within them are often fixed
1639 length. They are redundent enough to send over UDP as is the
1640 remote protocol in general. There is a matching unit test module
1641 in libstub. */
1642
1643 #define OPAQUETHREADBYTES 8
1644
1645 /* a 64 bit opaque identifier */
1646 typedef unsigned char threadref[OPAQUETHREADBYTES];
1647
1648 /* WARNING: This threadref data structure comes from the remote O.S.,
1649 libstub protocol encoding, and remote.c. it is not particularly
1650 changable. */
1651
1652 /* Right now, the internal structure is int. We want it to be bigger.
1653 Plan to fix this.
1654 */
1655
1656 typedef int gdb_threadref; /* Internal GDB thread reference. */
1657
1658 /* gdb_ext_thread_info is an internal GDB data structure which is
1659 equivalent to the reply of the remote threadinfo packet. */
1660
1661 struct gdb_ext_thread_info
1662 {
1663 threadref threadid; /* External form of thread reference. */
1664 int active; /* Has state interesting to GDB?
1665 regs, stack. */
1666 char display[256]; /* Brief state display, name,
1667 blocked/suspended. */
1668 char shortname[32]; /* To be used to name threads. */
1669 char more_display[256]; /* Long info, statistics, queue depth,
1670 whatever. */
1671 };
1672
1673 /* The volume of remote transfers can be limited by submitting
1674 a mask containing bits specifying the desired information.
1675 Use a union of these values as the 'selection' parameter to
1676 get_thread_info. FIXME: Make these TAG names more thread specific.
1677 */
1678
1679 #define TAG_THREADID 1
1680 #define TAG_EXISTS 2
1681 #define TAG_DISPLAY 4
1682 #define TAG_THREADNAME 8
1683 #define TAG_MOREDISPLAY 16
1684
1685 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1686
1687 char *unpack_varlen_hex (char *buff, ULONGEST *result);
1688
1689 static char *unpack_nibble (char *buf, int *val);
1690
1691 static char *pack_nibble (char *buf, int nibble);
1692
1693 static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
1694
1695 static char *unpack_byte (char *buf, int *value);
1696
1697 static char *pack_int (char *buf, int value);
1698
1699 static char *unpack_int (char *buf, int *value);
1700
1701 static char *unpack_string (char *src, char *dest, int length);
1702
1703 static char *pack_threadid (char *pkt, threadref *id);
1704
1705 static char *unpack_threadid (char *inbuf, threadref *id);
1706
1707 void int_to_threadref (threadref *id, int value);
1708
1709 static int threadref_to_int (threadref *ref);
1710
1711 static void copy_threadref (threadref *dest, threadref *src);
1712
1713 static int threadmatch (threadref *dest, threadref *src);
1714
1715 static char *pack_threadinfo_request (char *pkt, int mode,
1716 threadref *id);
1717
1718 static int remote_unpack_thread_info_response (char *pkt,
1719 threadref *expectedref,
1720 struct gdb_ext_thread_info
1721 *info);
1722
1723
1724 static int remote_get_threadinfo (threadref *threadid,
1725 int fieldset, /*TAG mask */
1726 struct gdb_ext_thread_info *info);
1727
1728 static char *pack_threadlist_request (char *pkt, int startflag,
1729 int threadcount,
1730 threadref *nextthread);
1731
1732 static int parse_threadlist_response (char *pkt,
1733 int result_limit,
1734 threadref *original_echo,
1735 threadref *resultlist,
1736 int *doneflag);
1737
1738 static int remote_get_threadlist (int startflag,
1739 threadref *nextthread,
1740 int result_limit,
1741 int *done,
1742 int *result_count,
1743 threadref *threadlist);
1744
1745 typedef int (*rmt_thread_action) (threadref *ref, void *context);
1746
1747 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1748 void *context, int looplimit);
1749
1750 static int remote_newthread_step (threadref *ref, void *context);
1751
1752
1753 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
1754 buffer we're allowed to write to. Returns
1755 BUF+CHARACTERS_WRITTEN. */
1756
1757 static char *
1758 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
1759 {
1760 int pid, tid;
1761 struct remote_state *rs = get_remote_state ();
1762
1763 if (remote_multi_process_p (rs))
1764 {
1765 pid = ptid_get_pid (ptid);
1766 if (pid < 0)
1767 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
1768 else
1769 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
1770 }
1771 tid = ptid_get_tid (ptid);
1772 if (tid < 0)
1773 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
1774 else
1775 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
1776
1777 return buf;
1778 }
1779
1780 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
1781 passed the last parsed char. Returns null_ptid on error. */
1782
1783 static ptid_t
1784 read_ptid (char *buf, char **obuf)
1785 {
1786 char *p = buf;
1787 char *pp;
1788 ULONGEST pid = 0, tid = 0;
1789
1790 if (*p == 'p')
1791 {
1792 /* Multi-process ptid. */
1793 pp = unpack_varlen_hex (p + 1, &pid);
1794 if (*pp != '.')
1795 error (_("invalid remote ptid: %s\n"), p);
1796
1797 p = pp;
1798 pp = unpack_varlen_hex (p + 1, &tid);
1799 if (obuf)
1800 *obuf = pp;
1801 return ptid_build (pid, 0, tid);
1802 }
1803
1804 /* No multi-process. Just a tid. */
1805 pp = unpack_varlen_hex (p, &tid);
1806
1807 /* Since the stub is not sending a process id, then default to
1808 what's in inferior_ptid, unless it's null at this point. If so,
1809 then since there's no way to know the pid of the reported
1810 threads, use the magic number. */
1811 if (ptid_equal (inferior_ptid, null_ptid))
1812 pid = ptid_get_pid (magic_null_ptid);
1813 else
1814 pid = ptid_get_pid (inferior_ptid);
1815
1816 if (obuf)
1817 *obuf = pp;
1818 return ptid_build (pid, 0, tid);
1819 }
1820
1821 /* Encode 64 bits in 16 chars of hex. */
1822
1823 static const char hexchars[] = "0123456789abcdef";
1824
1825 static int
1826 ishex (int ch, int *val)
1827 {
1828 if ((ch >= 'a') && (ch <= 'f'))
1829 {
1830 *val = ch - 'a' + 10;
1831 return 1;
1832 }
1833 if ((ch >= 'A') && (ch <= 'F'))
1834 {
1835 *val = ch - 'A' + 10;
1836 return 1;
1837 }
1838 if ((ch >= '0') && (ch <= '9'))
1839 {
1840 *val = ch - '0';
1841 return 1;
1842 }
1843 return 0;
1844 }
1845
1846 static int
1847 stubhex (int ch)
1848 {
1849 if (ch >= 'a' && ch <= 'f')
1850 return ch - 'a' + 10;
1851 if (ch >= '0' && ch <= '9')
1852 return ch - '0';
1853 if (ch >= 'A' && ch <= 'F')
1854 return ch - 'A' + 10;
1855 return -1;
1856 }
1857
1858 static int
1859 stub_unpack_int (char *buff, int fieldlength)
1860 {
1861 int nibble;
1862 int retval = 0;
1863
1864 while (fieldlength)
1865 {
1866 nibble = stubhex (*buff++);
1867 retval |= nibble;
1868 fieldlength--;
1869 if (fieldlength)
1870 retval = retval << 4;
1871 }
1872 return retval;
1873 }
1874
1875 char *
1876 unpack_varlen_hex (char *buff, /* packet to parse */
1877 ULONGEST *result)
1878 {
1879 int nibble;
1880 ULONGEST retval = 0;
1881
1882 while (ishex (*buff, &nibble))
1883 {
1884 buff++;
1885 retval = retval << 4;
1886 retval |= nibble & 0x0f;
1887 }
1888 *result = retval;
1889 return buff;
1890 }
1891
1892 static char *
1893 unpack_nibble (char *buf, int *val)
1894 {
1895 *val = fromhex (*buf++);
1896 return buf;
1897 }
1898
1899 static char *
1900 pack_nibble (char *buf, int nibble)
1901 {
1902 *buf++ = hexchars[(nibble & 0x0f)];
1903 return buf;
1904 }
1905
1906 static char *
1907 pack_hex_byte (char *pkt, int byte)
1908 {
1909 *pkt++ = hexchars[(byte >> 4) & 0xf];
1910 *pkt++ = hexchars[(byte & 0xf)];
1911 return pkt;
1912 }
1913
1914 static char *
1915 unpack_byte (char *buf, int *value)
1916 {
1917 *value = stub_unpack_int (buf, 2);
1918 return buf + 2;
1919 }
1920
1921 static char *
1922 pack_int (char *buf, int value)
1923 {
1924 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
1925 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
1926 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
1927 buf = pack_hex_byte (buf, (value & 0xff));
1928 return buf;
1929 }
1930
1931 static char *
1932 unpack_int (char *buf, int *value)
1933 {
1934 *value = stub_unpack_int (buf, 8);
1935 return buf + 8;
1936 }
1937
1938 #if 0 /* Currently unused, uncomment when needed. */
1939 static char *pack_string (char *pkt, char *string);
1940
1941 static char *
1942 pack_string (char *pkt, char *string)
1943 {
1944 char ch;
1945 int len;
1946
1947 len = strlen (string);
1948 if (len > 200)
1949 len = 200; /* Bigger than most GDB packets, junk??? */
1950 pkt = pack_hex_byte (pkt, len);
1951 while (len-- > 0)
1952 {
1953 ch = *string++;
1954 if ((ch == '\0') || (ch == '#'))
1955 ch = '*'; /* Protect encapsulation. */
1956 *pkt++ = ch;
1957 }
1958 return pkt;
1959 }
1960 #endif /* 0 (unused) */
1961
1962 static char *
1963 unpack_string (char *src, char *dest, int length)
1964 {
1965 while (length--)
1966 *dest++ = *src++;
1967 *dest = '\0';
1968 return src;
1969 }
1970
1971 static char *
1972 pack_threadid (char *pkt, threadref *id)
1973 {
1974 char *limit;
1975 unsigned char *altid;
1976
1977 altid = (unsigned char *) id;
1978 limit = pkt + BUF_THREAD_ID_SIZE;
1979 while (pkt < limit)
1980 pkt = pack_hex_byte (pkt, *altid++);
1981 return pkt;
1982 }
1983
1984
1985 static char *
1986 unpack_threadid (char *inbuf, threadref *id)
1987 {
1988 char *altref;
1989 char *limit = inbuf + BUF_THREAD_ID_SIZE;
1990 int x, y;
1991
1992 altref = (char *) id;
1993
1994 while (inbuf < limit)
1995 {
1996 x = stubhex (*inbuf++);
1997 y = stubhex (*inbuf++);
1998 *altref++ = (x << 4) | y;
1999 }
2000 return inbuf;
2001 }
2002
2003 /* Externally, threadrefs are 64 bits but internally, they are still
2004 ints. This is due to a mismatch of specifications. We would like
2005 to use 64bit thread references internally. This is an adapter
2006 function. */
2007
2008 void
2009 int_to_threadref (threadref *id, int value)
2010 {
2011 unsigned char *scan;
2012
2013 scan = (unsigned char *) id;
2014 {
2015 int i = 4;
2016 while (i--)
2017 *scan++ = 0;
2018 }
2019 *scan++ = (value >> 24) & 0xff;
2020 *scan++ = (value >> 16) & 0xff;
2021 *scan++ = (value >> 8) & 0xff;
2022 *scan++ = (value & 0xff);
2023 }
2024
2025 static int
2026 threadref_to_int (threadref *ref)
2027 {
2028 int i, value = 0;
2029 unsigned char *scan;
2030
2031 scan = *ref;
2032 scan += 4;
2033 i = 4;
2034 while (i-- > 0)
2035 value = (value << 8) | ((*scan++) & 0xff);
2036 return value;
2037 }
2038
2039 static void
2040 copy_threadref (threadref *dest, threadref *src)
2041 {
2042 int i;
2043 unsigned char *csrc, *cdest;
2044
2045 csrc = (unsigned char *) src;
2046 cdest = (unsigned char *) dest;
2047 i = 8;
2048 while (i--)
2049 *cdest++ = *csrc++;
2050 }
2051
2052 static int
2053 threadmatch (threadref *dest, threadref *src)
2054 {
2055 /* Things are broken right now, so just assume we got a match. */
2056 #if 0
2057 unsigned char *srcp, *destp;
2058 int i, result;
2059 srcp = (char *) src;
2060 destp = (char *) dest;
2061
2062 result = 1;
2063 while (i-- > 0)
2064 result &= (*srcp++ == *destp++) ? 1 : 0;
2065 return result;
2066 #endif
2067 return 1;
2068 }
2069
2070 /*
2071 threadid:1, # always request threadid
2072 context_exists:2,
2073 display:4,
2074 unique_name:8,
2075 more_display:16
2076 */
2077
2078 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2079
2080 static char *
2081 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2082 {
2083 *pkt++ = 'q'; /* Info Query */
2084 *pkt++ = 'P'; /* process or thread info */
2085 pkt = pack_int (pkt, mode); /* mode */
2086 pkt = pack_threadid (pkt, id); /* threadid */
2087 *pkt = '\0'; /* terminate */
2088 return pkt;
2089 }
2090
2091 /* These values tag the fields in a thread info response packet. */
2092 /* Tagging the fields allows us to request specific fields and to
2093 add more fields as time goes by. */
2094
2095 #define TAG_THREADID 1 /* Echo the thread identifier. */
2096 #define TAG_EXISTS 2 /* Is this process defined enough to
2097 fetch registers and its stack? */
2098 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2099 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2100 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2101 the process. */
2102
2103 static int
2104 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2105 struct gdb_ext_thread_info *info)
2106 {
2107 struct remote_state *rs = get_remote_state ();
2108 int mask, length;
2109 int tag;
2110 threadref ref;
2111 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2112 int retval = 1;
2113
2114 /* info->threadid = 0; FIXME: implement zero_threadref. */
2115 info->active = 0;
2116 info->display[0] = '\0';
2117 info->shortname[0] = '\0';
2118 info->more_display[0] = '\0';
2119
2120 /* Assume the characters indicating the packet type have been
2121 stripped. */
2122 pkt = unpack_int (pkt, &mask); /* arg mask */
2123 pkt = unpack_threadid (pkt, &ref);
2124
2125 if (mask == 0)
2126 warning (_("Incomplete response to threadinfo request."));
2127 if (!threadmatch (&ref, expectedref))
2128 { /* This is an answer to a different request. */
2129 warning (_("ERROR RMT Thread info mismatch."));
2130 return 0;
2131 }
2132 copy_threadref (&info->threadid, &ref);
2133
2134 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2135
2136 /* Packets are terminated with nulls. */
2137 while ((pkt < limit) && mask && *pkt)
2138 {
2139 pkt = unpack_int (pkt, &tag); /* tag */
2140 pkt = unpack_byte (pkt, &length); /* length */
2141 if (!(tag & mask)) /* Tags out of synch with mask. */
2142 {
2143 warning (_("ERROR RMT: threadinfo tag mismatch."));
2144 retval = 0;
2145 break;
2146 }
2147 if (tag == TAG_THREADID)
2148 {
2149 if (length != 16)
2150 {
2151 warning (_("ERROR RMT: length of threadid is not 16."));
2152 retval = 0;
2153 break;
2154 }
2155 pkt = unpack_threadid (pkt, &ref);
2156 mask = mask & ~TAG_THREADID;
2157 continue;
2158 }
2159 if (tag == TAG_EXISTS)
2160 {
2161 info->active = stub_unpack_int (pkt, length);
2162 pkt += length;
2163 mask = mask & ~(TAG_EXISTS);
2164 if (length > 8)
2165 {
2166 warning (_("ERROR RMT: 'exists' length too long."));
2167 retval = 0;
2168 break;
2169 }
2170 continue;
2171 }
2172 if (tag == TAG_THREADNAME)
2173 {
2174 pkt = unpack_string (pkt, &info->shortname[0], length);
2175 mask = mask & ~TAG_THREADNAME;
2176 continue;
2177 }
2178 if (tag == TAG_DISPLAY)
2179 {
2180 pkt = unpack_string (pkt, &info->display[0], length);
2181 mask = mask & ~TAG_DISPLAY;
2182 continue;
2183 }
2184 if (tag == TAG_MOREDISPLAY)
2185 {
2186 pkt = unpack_string (pkt, &info->more_display[0], length);
2187 mask = mask & ~TAG_MOREDISPLAY;
2188 continue;
2189 }
2190 warning (_("ERROR RMT: unknown thread info tag."));
2191 break; /* Not a tag we know about. */
2192 }
2193 return retval;
2194 }
2195
2196 static int
2197 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2198 struct gdb_ext_thread_info *info)
2199 {
2200 struct remote_state *rs = get_remote_state ();
2201 int result;
2202
2203 pack_threadinfo_request (rs->buf, fieldset, threadid);
2204 putpkt (rs->buf);
2205 getpkt (&rs->buf, &rs->buf_size, 0);
2206
2207 if (rs->buf[0] == '\0')
2208 return 0;
2209
2210 result = remote_unpack_thread_info_response (rs->buf + 2,
2211 threadid, info);
2212 return result;
2213 }
2214
2215 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2216
2217 static char *
2218 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2219 threadref *nextthread)
2220 {
2221 *pkt++ = 'q'; /* info query packet */
2222 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2223 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2224 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2225 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2226 *pkt = '\0';
2227 return pkt;
2228 }
2229
2230 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2231
2232 static int
2233 parse_threadlist_response (char *pkt, int result_limit,
2234 threadref *original_echo, threadref *resultlist,
2235 int *doneflag)
2236 {
2237 struct remote_state *rs = get_remote_state ();
2238 char *limit;
2239 int count, resultcount, done;
2240
2241 resultcount = 0;
2242 /* Assume the 'q' and 'M chars have been stripped. */
2243 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2244 /* done parse past here */
2245 pkt = unpack_byte (pkt, &count); /* count field */
2246 pkt = unpack_nibble (pkt, &done);
2247 /* The first threadid is the argument threadid. */
2248 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2249 while ((count-- > 0) && (pkt < limit))
2250 {
2251 pkt = unpack_threadid (pkt, resultlist++);
2252 if (resultcount++ >= result_limit)
2253 break;
2254 }
2255 if (doneflag)
2256 *doneflag = done;
2257 return resultcount;
2258 }
2259
2260 static int
2261 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2262 int *done, int *result_count, threadref *threadlist)
2263 {
2264 struct remote_state *rs = get_remote_state ();
2265 static threadref echo_nextthread;
2266 int result = 1;
2267
2268 /* Trancate result limit to be smaller than the packet size. */
2269 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10) >= get_remote_packet_size ())
2270 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2271
2272 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2273 putpkt (rs->buf);
2274 getpkt (&rs->buf, &rs->buf_size, 0);
2275
2276 if (*rs->buf == '\0')
2277 *result_count = 0;
2278 else
2279 *result_count =
2280 parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
2281 threadlist, done);
2282
2283 if (!threadmatch (&echo_nextthread, nextthread))
2284 {
2285 /* FIXME: This is a good reason to drop the packet. */
2286 /* Possably, there is a duplicate response. */
2287 /* Possabilities :
2288 retransmit immediatly - race conditions
2289 retransmit after timeout - yes
2290 exit
2291 wait for packet, then exit
2292 */
2293 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2294 return 0; /* I choose simply exiting. */
2295 }
2296 if (*result_count <= 0)
2297 {
2298 if (*done != 1)
2299 {
2300 warning (_("RMT ERROR : failed to get remote thread list."));
2301 result = 0;
2302 }
2303 return result; /* break; */
2304 }
2305 if (*result_count > result_limit)
2306 {
2307 *result_count = 0;
2308 warning (_("RMT ERROR: threadlist response longer than requested."));
2309 return 0;
2310 }
2311 return result;
2312 }
2313
2314 /* This is the interface between remote and threads, remotes upper
2315 interface. */
2316
2317 /* remote_find_new_threads retrieves the thread list and for each
2318 thread in the list, looks up the thread in GDB's internal list,
2319 adding the thread if it does not already exist. This involves
2320 getting partial thread lists from the remote target so, polling the
2321 quit_flag is required. */
2322
2323
2324 /* About this many threadisds fit in a packet. */
2325
2326 #define MAXTHREADLISTRESULTS 32
2327
2328 static int
2329 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2330 int looplimit)
2331 {
2332 int done, i, result_count;
2333 int startflag = 1;
2334 int result = 1;
2335 int loopcount = 0;
2336 static threadref nextthread;
2337 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
2338
2339 done = 0;
2340 while (!done)
2341 {
2342 if (loopcount++ > looplimit)
2343 {
2344 result = 0;
2345 warning (_("Remote fetch threadlist -infinite loop-."));
2346 break;
2347 }
2348 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
2349 &done, &result_count, resultthreadlist))
2350 {
2351 result = 0;
2352 break;
2353 }
2354 /* Clear for later iterations. */
2355 startflag = 0;
2356 /* Setup to resume next batch of thread references, set nextthread. */
2357 if (result_count >= 1)
2358 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
2359 i = 0;
2360 while (result_count--)
2361 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
2362 break;
2363 }
2364 return result;
2365 }
2366
2367 static int
2368 remote_newthread_step (threadref *ref, void *context)
2369 {
2370 int pid = ptid_get_pid (inferior_ptid);
2371 ptid_t ptid = ptid_build (pid, 0, threadref_to_int (ref));
2372
2373 if (!in_thread_list (ptid))
2374 add_thread (ptid);
2375 return 1; /* continue iterator */
2376 }
2377
2378 #define CRAZY_MAX_THREADS 1000
2379
2380 static ptid_t
2381 remote_current_thread (ptid_t oldpid)
2382 {
2383 struct remote_state *rs = get_remote_state ();
2384
2385 putpkt ("qC");
2386 getpkt (&rs->buf, &rs->buf_size, 0);
2387 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2388 return read_ptid (&rs->buf[2], NULL);
2389 else
2390 return oldpid;
2391 }
2392
2393 /* Find new threads for info threads command.
2394 * Original version, using John Metzler's thread protocol.
2395 */
2396
2397 static void
2398 remote_find_new_threads (void)
2399 {
2400 remote_threadlist_iterator (remote_newthread_step, 0,
2401 CRAZY_MAX_THREADS);
2402 }
2403
2404 #if defined(HAVE_LIBEXPAT)
2405
2406 typedef struct thread_item
2407 {
2408 ptid_t ptid;
2409 char *extra;
2410 int core;
2411 } thread_item_t;
2412 DEF_VEC_O(thread_item_t);
2413
2414 struct threads_parsing_context
2415 {
2416 VEC (thread_item_t) *items;
2417 };
2418
2419 static void
2420 start_thread (struct gdb_xml_parser *parser,
2421 const struct gdb_xml_element *element,
2422 void *user_data, VEC(gdb_xml_value_s) *attributes)
2423 {
2424 struct threads_parsing_context *data = user_data;
2425
2426 struct thread_item item;
2427 char *id;
2428
2429 id = VEC_index (gdb_xml_value_s, attributes, 0)->value;
2430 item.ptid = read_ptid (id, NULL);
2431
2432 if (VEC_length (gdb_xml_value_s, attributes) > 1)
2433 item.core = *(ULONGEST *) VEC_index (gdb_xml_value_s, attributes, 1)->value;
2434 else
2435 item.core = -1;
2436
2437 item.extra = 0;
2438
2439 VEC_safe_push (thread_item_t, data->items, &item);
2440 }
2441
2442 static void
2443 end_thread (struct gdb_xml_parser *parser,
2444 const struct gdb_xml_element *element,
2445 void *user_data, const char *body_text)
2446 {
2447 struct threads_parsing_context *data = user_data;
2448
2449 if (body_text && *body_text)
2450 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2451 }
2452
2453 const struct gdb_xml_attribute thread_attributes[] = {
2454 { "id", GDB_XML_AF_NONE, NULL, NULL },
2455 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2456 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2457 };
2458
2459 const struct gdb_xml_element thread_children[] = {
2460 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2461 };
2462
2463 const struct gdb_xml_element threads_children[] = {
2464 { "thread", thread_attributes, thread_children,
2465 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2466 start_thread, end_thread },
2467 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2468 };
2469
2470 const struct gdb_xml_element threads_elements[] = {
2471 { "threads", NULL, threads_children,
2472 GDB_XML_EF_NONE, NULL, NULL },
2473 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2474 };
2475
2476 #endif
2477
2478 /*
2479 * Find all threads for info threads command.
2480 * Uses new thread protocol contributed by Cisco.
2481 * Falls back and attempts to use the older method (above)
2482 * if the target doesn't respond to the new method.
2483 */
2484
2485 static void
2486 remote_threads_info (struct target_ops *ops)
2487 {
2488 struct remote_state *rs = get_remote_state ();
2489 char *bufp;
2490 ptid_t new_thread;
2491
2492 if (remote_desc == 0) /* paranoia */
2493 error (_("Command can only be used when connected to the remote target."));
2494
2495 #if defined(HAVE_LIBEXPAT)
2496 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2497 {
2498 char *xml = target_read_stralloc (&current_target,
2499 TARGET_OBJECT_THREADS, NULL);
2500
2501 struct cleanup *back_to = make_cleanup (xfree, xml);
2502 if (xml && *xml)
2503 {
2504 struct gdb_xml_parser *parser;
2505 struct threads_parsing_context context;
2506 struct cleanup *back_to = make_cleanup (null_cleanup, NULL);
2507
2508 context.items = 0;
2509 parser = gdb_xml_create_parser_and_cleanup (_("threads"),
2510 threads_elements,
2511 &context);
2512
2513 gdb_xml_use_dtd (parser, "threads.dtd");
2514
2515 if (gdb_xml_parse (parser, xml) == 0)
2516 {
2517 int i;
2518 struct thread_item *item;
2519
2520 for (i = 0; VEC_iterate (thread_item_t, context.items, i, item); ++i)
2521 {
2522 if (!ptid_equal (item->ptid, null_ptid))
2523 {
2524 struct private_thread_info *info;
2525 /* In non-stop mode, we assume new found threads
2526 are running until proven otherwise with a
2527 stop reply. In all-stop, we can only get
2528 here if all threads are stopped. */
2529 int running = non_stop ? 1 : 0;
2530
2531 remote_notice_new_inferior (item->ptid, running);
2532
2533 info = demand_private_info (item->ptid);
2534 info->core = item->core;
2535 info->extra = item->extra;
2536 item->extra = 0;
2537 }
2538 xfree (item->extra);
2539 }
2540 }
2541
2542 VEC_free (thread_item_t, context.items);
2543 }
2544
2545 do_cleanups (back_to);
2546 return;
2547 }
2548 #endif
2549
2550 if (use_threadinfo_query)
2551 {
2552 putpkt ("qfThreadInfo");
2553 getpkt (&rs->buf, &rs->buf_size, 0);
2554 bufp = rs->buf;
2555 if (bufp[0] != '\0') /* q packet recognized */
2556 {
2557 while (*bufp++ == 'm') /* reply contains one or more TID */
2558 {
2559 do
2560 {
2561 new_thread = read_ptid (bufp, &bufp);
2562 if (!ptid_equal (new_thread, null_ptid))
2563 {
2564 /* In non-stop mode, we assume new found threads
2565 are running until proven otherwise with a
2566 stop reply. In all-stop, we can only get
2567 here if all threads are stopped. */
2568 int running = non_stop ? 1 : 0;
2569
2570 remote_notice_new_inferior (new_thread, running);
2571 }
2572 }
2573 while (*bufp++ == ','); /* comma-separated list */
2574 putpkt ("qsThreadInfo");
2575 getpkt (&rs->buf, &rs->buf_size, 0);
2576 bufp = rs->buf;
2577 }
2578 return; /* done */
2579 }
2580 }
2581
2582 /* Only qfThreadInfo is supported in non-stop mode. */
2583 if (non_stop)
2584 return;
2585
2586 /* Else fall back to old method based on jmetzler protocol. */
2587 use_threadinfo_query = 0;
2588 remote_find_new_threads ();
2589 return;
2590 }
2591
2592 /*
2593 * Collect a descriptive string about the given thread.
2594 * The target may say anything it wants to about the thread
2595 * (typically info about its blocked / runnable state, name, etc.).
2596 * This string will appear in the info threads display.
2597 *
2598 * Optional: targets are not required to implement this function.
2599 */
2600
2601 static char *
2602 remote_threads_extra_info (struct thread_info *tp)
2603 {
2604 struct remote_state *rs = get_remote_state ();
2605 int result;
2606 int set;
2607 threadref id;
2608 struct gdb_ext_thread_info threadinfo;
2609 static char display_buf[100]; /* arbitrary... */
2610 int n = 0; /* position in display_buf */
2611
2612 if (remote_desc == 0) /* paranoia */
2613 internal_error (__FILE__, __LINE__,
2614 _("remote_threads_extra_info"));
2615
2616 if (ptid_equal (tp->ptid, magic_null_ptid)
2617 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_tid (tp->ptid) == 0))
2618 /* This is the main thread which was added by GDB. The remote
2619 server doesn't know about it. */
2620 return NULL;
2621
2622 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2623 {
2624 struct thread_info *info = find_thread_ptid (tp->ptid);
2625 if (info && info->private)
2626 return info->private->extra;
2627 else
2628 return NULL;
2629 }
2630
2631 if (use_threadextra_query)
2632 {
2633 char *b = rs->buf;
2634 char *endb = rs->buf + get_remote_packet_size ();
2635
2636 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2637 b += strlen (b);
2638 write_ptid (b, endb, tp->ptid);
2639
2640 putpkt (rs->buf);
2641 getpkt (&rs->buf, &rs->buf_size, 0);
2642 if (rs->buf[0] != 0)
2643 {
2644 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2645 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2646 display_buf [result] = '\0';
2647 return display_buf;
2648 }
2649 }
2650
2651 /* If the above query fails, fall back to the old method. */
2652 use_threadextra_query = 0;
2653 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2654 | TAG_MOREDISPLAY | TAG_DISPLAY;
2655 int_to_threadref (&id, ptid_get_tid (tp->ptid));
2656 if (remote_get_threadinfo (&id, set, &threadinfo))
2657 if (threadinfo.active)
2658 {
2659 if (*threadinfo.shortname)
2660 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2661 " Name: %s,", threadinfo.shortname);
2662 if (*threadinfo.display)
2663 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2664 " State: %s,", threadinfo.display);
2665 if (*threadinfo.more_display)
2666 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2667 " Priority: %s", threadinfo.more_display);
2668
2669 if (n > 0)
2670 {
2671 /* For purely cosmetic reasons, clear up trailing commas. */
2672 if (',' == display_buf[n-1])
2673 display_buf[n-1] = ' ';
2674 return display_buf;
2675 }
2676 }
2677 return NULL;
2678 }
2679 \f
2680
2681 /* Implement the to_get_ada_task_ptid function for the remote targets. */
2682
2683 static ptid_t
2684 remote_get_ada_task_ptid (long lwp, long thread)
2685 {
2686 return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
2687 }
2688 \f
2689
2690 /* Restart the remote side; this is an extended protocol operation. */
2691
2692 static void
2693 extended_remote_restart (void)
2694 {
2695 struct remote_state *rs = get_remote_state ();
2696
2697 /* Send the restart command; for reasons I don't understand the
2698 remote side really expects a number after the "R". */
2699 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
2700 putpkt (rs->buf);
2701
2702 remote_fileio_reset ();
2703 }
2704 \f
2705 /* Clean up connection to a remote debugger. */
2706
2707 static void
2708 remote_close (int quitting)
2709 {
2710 if (remote_desc == NULL)
2711 return; /* already closed */
2712
2713 /* Make sure we leave stdin registered in the event loop, and we
2714 don't leave the async SIGINT signal handler installed. */
2715 remote_terminal_ours ();
2716
2717 serial_close (remote_desc);
2718 remote_desc = NULL;
2719
2720 /* We don't have a connection to the remote stub anymore. Get rid
2721 of all the inferiors and their threads we were controlling. */
2722 discard_all_inferiors ();
2723
2724 /* We're no longer interested in any of these events. */
2725 discard_pending_stop_replies (-1);
2726
2727 if (remote_async_inferior_event_token)
2728 delete_async_event_handler (&remote_async_inferior_event_token);
2729 if (remote_async_get_pending_events_token)
2730 delete_async_event_handler (&remote_async_get_pending_events_token);
2731 }
2732
2733 /* Query the remote side for the text, data and bss offsets. */
2734
2735 static void
2736 get_offsets (void)
2737 {
2738 struct remote_state *rs = get_remote_state ();
2739 char *buf;
2740 char *ptr;
2741 int lose, num_segments = 0, do_sections, do_segments;
2742 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
2743 struct section_offsets *offs;
2744 struct symfile_segment_data *data;
2745
2746 if (symfile_objfile == NULL)
2747 return;
2748
2749 putpkt ("qOffsets");
2750 getpkt (&rs->buf, &rs->buf_size, 0);
2751 buf = rs->buf;
2752
2753 if (buf[0] == '\000')
2754 return; /* Return silently. Stub doesn't support
2755 this command. */
2756 if (buf[0] == 'E')
2757 {
2758 warning (_("Remote failure reply: %s"), buf);
2759 return;
2760 }
2761
2762 /* Pick up each field in turn. This used to be done with scanf, but
2763 scanf will make trouble if CORE_ADDR size doesn't match
2764 conversion directives correctly. The following code will work
2765 with any size of CORE_ADDR. */
2766 text_addr = data_addr = bss_addr = 0;
2767 ptr = buf;
2768 lose = 0;
2769
2770 if (strncmp (ptr, "Text=", 5) == 0)
2771 {
2772 ptr += 5;
2773 /* Don't use strtol, could lose on big values. */
2774 while (*ptr && *ptr != ';')
2775 text_addr = (text_addr << 4) + fromhex (*ptr++);
2776
2777 if (strncmp (ptr, ";Data=", 6) == 0)
2778 {
2779 ptr += 6;
2780 while (*ptr && *ptr != ';')
2781 data_addr = (data_addr << 4) + fromhex (*ptr++);
2782 }
2783 else
2784 lose = 1;
2785
2786 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
2787 {
2788 ptr += 5;
2789 while (*ptr && *ptr != ';')
2790 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
2791
2792 if (bss_addr != data_addr)
2793 warning (_("Target reported unsupported offsets: %s"), buf);
2794 }
2795 else
2796 lose = 1;
2797 }
2798 else if (strncmp (ptr, "TextSeg=", 8) == 0)
2799 {
2800 ptr += 8;
2801 /* Don't use strtol, could lose on big values. */
2802 while (*ptr && *ptr != ';')
2803 text_addr = (text_addr << 4) + fromhex (*ptr++);
2804 num_segments = 1;
2805
2806 if (strncmp (ptr, ";DataSeg=", 9) == 0)
2807 {
2808 ptr += 9;
2809 while (*ptr && *ptr != ';')
2810 data_addr = (data_addr << 4) + fromhex (*ptr++);
2811 num_segments++;
2812 }
2813 }
2814 else
2815 lose = 1;
2816
2817 if (lose)
2818 error (_("Malformed response to offset query, %s"), buf);
2819 else if (*ptr != '\0')
2820 warning (_("Target reported unsupported offsets: %s"), buf);
2821
2822 offs = ((struct section_offsets *)
2823 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
2824 memcpy (offs, symfile_objfile->section_offsets,
2825 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
2826
2827 data = get_symfile_segment_data (symfile_objfile->obfd);
2828 do_segments = (data != NULL);
2829 do_sections = num_segments == 0;
2830
2831 if (num_segments > 0)
2832 {
2833 segments[0] = text_addr;
2834 segments[1] = data_addr;
2835 }
2836 /* If we have two segments, we can still try to relocate everything
2837 by assuming that the .text and .data offsets apply to the whole
2838 text and data segments. Convert the offsets given in the packet
2839 to base addresses for symfile_map_offsets_to_segments. */
2840 else if (data && data->num_segments == 2)
2841 {
2842 segments[0] = data->segment_bases[0] + text_addr;
2843 segments[1] = data->segment_bases[1] + data_addr;
2844 num_segments = 2;
2845 }
2846 /* If the object file has only one segment, assume that it is text
2847 rather than data; main programs with no writable data are rare,
2848 but programs with no code are useless. Of course the code might
2849 have ended up in the data segment... to detect that we would need
2850 the permissions here. */
2851 else if (data && data->num_segments == 1)
2852 {
2853 segments[0] = data->segment_bases[0] + text_addr;
2854 num_segments = 1;
2855 }
2856 /* There's no way to relocate by segment. */
2857 else
2858 do_segments = 0;
2859
2860 if (do_segments)
2861 {
2862 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
2863 offs, num_segments, segments);
2864
2865 if (ret == 0 && !do_sections)
2866 error (_("Can not handle qOffsets TextSeg response with this symbol file"));
2867
2868 if (ret > 0)
2869 do_sections = 0;
2870 }
2871
2872 if (data)
2873 free_symfile_segment_data (data);
2874
2875 if (do_sections)
2876 {
2877 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
2878
2879 /* This is a temporary kludge to force data and bss to use the same offsets
2880 because that's what nlmconv does now. The real solution requires changes
2881 to the stub and remote.c that I don't have time to do right now. */
2882
2883 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
2884 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
2885 }
2886
2887 objfile_relocate (symfile_objfile, offs);
2888 }
2889
2890 /* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
2891 threads we know are stopped already. This is used during the
2892 initial remote connection in non-stop mode --- threads that are
2893 reported as already being stopped are left stopped. */
2894
2895 static int
2896 set_stop_requested_callback (struct thread_info *thread, void *data)
2897 {
2898 /* If we have a stop reply for this thread, it must be stopped. */
2899 if (peek_stop_reply (thread->ptid))
2900 set_stop_requested (thread->ptid, 1);
2901
2902 return 0;
2903 }
2904
2905 /* Stub for catch_exception. */
2906
2907 struct start_remote_args
2908 {
2909 int from_tty;
2910
2911 /* The current target. */
2912 struct target_ops *target;
2913
2914 /* Non-zero if this is an extended-remote target. */
2915 int extended_p;
2916 };
2917
2918 /* Send interrupt_sequence to remote target. */
2919 static void
2920 send_interrupt_sequence ()
2921 {
2922 if (interrupt_sequence_mode == interrupt_sequence_control_c)
2923 serial_write (remote_desc, "\x03", 1);
2924 else if (interrupt_sequence_mode == interrupt_sequence_break)
2925 serial_send_break (remote_desc);
2926 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
2927 {
2928 serial_send_break (remote_desc);
2929 serial_write (remote_desc, "g", 1);
2930 }
2931 else
2932 internal_error (__FILE__, __LINE__,
2933 _("Invalid value for interrupt_sequence_mode: %s."),
2934 interrupt_sequence_mode);
2935 }
2936
2937 static void
2938 remote_start_remote (struct ui_out *uiout, void *opaque)
2939 {
2940 struct start_remote_args *args = opaque;
2941 struct remote_state *rs = get_remote_state ();
2942 struct packet_config *noack_config;
2943 char *wait_status = NULL;
2944
2945 immediate_quit++; /* Allow user to interrupt it. */
2946
2947 /* Ack any packet which the remote side has already sent. */
2948 serial_write (remote_desc, "+", 1);
2949
2950 if (interrupt_on_connect)
2951 send_interrupt_sequence ();
2952
2953 /* The first packet we send to the target is the optional "supported
2954 packets" request. If the target can answer this, it will tell us
2955 which later probes to skip. */
2956 remote_query_supported ();
2957
2958 /* Next, we possibly activate noack mode.
2959
2960 If the QStartNoAckMode packet configuration is set to AUTO,
2961 enable noack mode if the stub reported a wish for it with
2962 qSupported.
2963
2964 If set to TRUE, then enable noack mode even if the stub didn't
2965 report it in qSupported. If the stub doesn't reply OK, the
2966 session ends with an error.
2967
2968 If FALSE, then don't activate noack mode, regardless of what the
2969 stub claimed should be the default with qSupported. */
2970
2971 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
2972
2973 if (noack_config->detect == AUTO_BOOLEAN_TRUE
2974 || (noack_config->detect == AUTO_BOOLEAN_AUTO
2975 && noack_config->support == PACKET_ENABLE))
2976 {
2977 putpkt ("QStartNoAckMode");
2978 getpkt (&rs->buf, &rs->buf_size, 0);
2979 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
2980 rs->noack_mode = 1;
2981 }
2982
2983 if (args->extended_p)
2984 {
2985 /* Tell the remote that we are using the extended protocol. */
2986 putpkt ("!");
2987 getpkt (&rs->buf, &rs->buf_size, 0);
2988 }
2989
2990 /* Next, if the target can specify a description, read it. We do
2991 this before anything involving memory or registers. */
2992 target_find_description ();
2993
2994 /* Next, now that we know something about the target, update the
2995 address spaces in the program spaces. */
2996 update_address_spaces ();
2997
2998 /* On OSs where the list of libraries is global to all
2999 processes, we fetch them early. */
3000 if (gdbarch_has_global_solist (target_gdbarch))
3001 solib_add (NULL, args->from_tty, args->target, auto_solib_add);
3002
3003 if (non_stop)
3004 {
3005 if (!rs->non_stop_aware)
3006 error (_("Non-stop mode requested, but remote does not support non-stop"));
3007
3008 putpkt ("QNonStop:1");
3009 getpkt (&rs->buf, &rs->buf_size, 0);
3010
3011 if (strcmp (rs->buf, "OK") != 0)
3012 error ("Remote refused setting non-stop mode with: %s", rs->buf);
3013
3014 /* Find about threads and processes the stub is already
3015 controlling. We default to adding them in the running state.
3016 The '?' query below will then tell us about which threads are
3017 stopped. */
3018 remote_threads_info (args->target);
3019 }
3020 else if (rs->non_stop_aware)
3021 {
3022 /* Don't assume that the stub can operate in all-stop mode.
3023 Request it explicitely. */
3024 putpkt ("QNonStop:0");
3025 getpkt (&rs->buf, &rs->buf_size, 0);
3026
3027 if (strcmp (rs->buf, "OK") != 0)
3028 error ("Remote refused setting all-stop mode with: %s", rs->buf);
3029 }
3030
3031 /* Check whether the target is running now. */
3032 putpkt ("?");
3033 getpkt (&rs->buf, &rs->buf_size, 0);
3034
3035 if (!non_stop)
3036 {
3037 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3038 {
3039 if (!args->extended_p)
3040 error (_("The target is not running (try extended-remote?)"));
3041
3042 /* We're connected, but not running. Drop out before we
3043 call start_remote. */
3044 return;
3045 }
3046 else
3047 {
3048 /* Save the reply for later. */
3049 wait_status = alloca (strlen (rs->buf) + 1);
3050 strcpy (wait_status, rs->buf);
3051 }
3052
3053 /* Let the stub know that we want it to return the thread. */
3054 set_continue_thread (minus_one_ptid);
3055
3056 /* Without this, some commands which require an active target
3057 (such as kill) won't work. This variable serves (at least)
3058 double duty as both the pid of the target process (if it has
3059 such), and as a flag indicating that a target is active.
3060 These functions should be split out into seperate variables,
3061 especially since GDB will someday have a notion of debugging
3062 several processes. */
3063 inferior_ptid = magic_null_ptid;
3064
3065 /* Now, if we have thread information, update inferior_ptid. */
3066 inferior_ptid = remote_current_thread (inferior_ptid);
3067
3068 remote_add_inferior (ptid_get_pid (inferior_ptid), -1);
3069
3070 /* Always add the main thread. */
3071 add_thread_silent (inferior_ptid);
3072
3073 get_offsets (); /* Get text, data & bss offsets. */
3074
3075 /* If we could not find a description using qXfer, and we know
3076 how to do it some other way, try again. This is not
3077 supported for non-stop; it could be, but it is tricky if
3078 there are no stopped threads when we connect. */
3079 if (remote_read_description_p (args->target)
3080 && gdbarch_target_desc (target_gdbarch) == NULL)
3081 {
3082 target_clear_description ();
3083 target_find_description ();
3084 }
3085
3086 /* Use the previously fetched status. */
3087 gdb_assert (wait_status != NULL);
3088 strcpy (rs->buf, wait_status);
3089 rs->cached_wait_status = 1;
3090
3091 immediate_quit--;
3092 start_remote (args->from_tty); /* Initialize gdb process mechanisms. */
3093 }
3094 else
3095 {
3096 /* Clear WFI global state. Do this before finding about new
3097 threads and inferiors, and setting the current inferior.
3098 Otherwise we would clear the proceed status of the current
3099 inferior when we want its stop_soon state to be preserved
3100 (see notice_new_inferior). */
3101 init_wait_for_inferior ();
3102
3103 /* In non-stop, we will either get an "OK", meaning that there
3104 are no stopped threads at this time; or, a regular stop
3105 reply. In the latter case, there may be more than one thread
3106 stopped --- we pull them all out using the vStopped
3107 mechanism. */
3108 if (strcmp (rs->buf, "OK") != 0)
3109 {
3110 struct stop_reply *stop_reply;
3111 struct cleanup *old_chain;
3112
3113 stop_reply = stop_reply_xmalloc ();
3114 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
3115
3116 remote_parse_stop_reply (rs->buf, stop_reply);
3117 discard_cleanups (old_chain);
3118
3119 /* get_pending_stop_replies acks this one, and gets the rest
3120 out. */
3121 pending_stop_reply = stop_reply;
3122 remote_get_pending_stop_replies ();
3123
3124 /* Make sure that threads that were stopped remain
3125 stopped. */
3126 iterate_over_threads (set_stop_requested_callback, NULL);
3127 }
3128
3129 if (target_can_async_p ())
3130 target_async (inferior_event_handler, 0);
3131
3132 if (thread_count () == 0)
3133 {
3134 if (!args->extended_p)
3135 error (_("The target is not running (try extended-remote?)"));
3136
3137 /* We're connected, but not running. Drop out before we
3138 call start_remote. */
3139 return;
3140 }
3141
3142 /* Let the stub know that we want it to return the thread. */
3143
3144 /* Force the stub to choose a thread. */
3145 set_general_thread (null_ptid);
3146
3147 /* Query it. */
3148 inferior_ptid = remote_current_thread (minus_one_ptid);
3149 if (ptid_equal (inferior_ptid, minus_one_ptid))
3150 error (_("remote didn't report the current thread in non-stop mode"));
3151
3152 get_offsets (); /* Get text, data & bss offsets. */
3153
3154 /* In non-stop mode, any cached wait status will be stored in
3155 the stop reply queue. */
3156 gdb_assert (wait_status == NULL);
3157 }
3158
3159 /* If we connected to a live target, do some additional setup. */
3160 if (target_has_execution)
3161 {
3162 if (exec_bfd) /* No use without an exec file. */
3163 remote_check_symbols (symfile_objfile);
3164 }
3165
3166 /* Possibly the target has been engaged in a trace run started
3167 previously; find out where things are at. */
3168 if (remote_get_trace_status (current_trace_status ()) != -1)
3169 {
3170 struct uploaded_tp *uploaded_tps = NULL;
3171 struct uploaded_tsv *uploaded_tsvs = NULL;
3172
3173 if (current_trace_status ()->running)
3174 printf_filtered (_("Trace is already running on the target.\n"));
3175
3176 /* Get trace state variables first, they may be checked when
3177 parsing uploaded commands. */
3178
3179 remote_upload_trace_state_variables (&uploaded_tsvs);
3180
3181 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3182
3183 remote_upload_tracepoints (&uploaded_tps);
3184
3185 merge_uploaded_tracepoints (&uploaded_tps);
3186 }
3187
3188 /* If breakpoints are global, insert them now. */
3189 if (gdbarch_has_global_breakpoints (target_gdbarch)
3190 && breakpoints_always_inserted_mode ())
3191 insert_breakpoints ();
3192 }
3193
3194 /* Open a connection to a remote debugger.
3195 NAME is the filename used for communication. */
3196
3197 static void
3198 remote_open (char *name, int from_tty)
3199 {
3200 remote_open_1 (name, from_tty, &remote_ops, 0);
3201 }
3202
3203 /* Open a connection to a remote debugger using the extended
3204 remote gdb protocol. NAME is the filename used for communication. */
3205
3206 static void
3207 extended_remote_open (char *name, int from_tty)
3208 {
3209 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3210 }
3211
3212 /* Generic code for opening a connection to a remote target. */
3213
3214 static void
3215 init_all_packet_configs (void)
3216 {
3217 int i;
3218 for (i = 0; i < PACKET_MAX; i++)
3219 update_packet_config (&remote_protocol_packets[i]);
3220 }
3221
3222 /* Symbol look-up. */
3223
3224 static void
3225 remote_check_symbols (struct objfile *objfile)
3226 {
3227 struct remote_state *rs = get_remote_state ();
3228 char *msg, *reply, *tmp;
3229 struct minimal_symbol *sym;
3230 int end;
3231
3232 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
3233 return;
3234
3235 /* Make sure the remote is pointing at the right process. */
3236 set_general_process ();
3237
3238 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3239 because we need both at the same time. */
3240 msg = alloca (get_remote_packet_size ());
3241
3242 /* Invite target to request symbol lookups. */
3243
3244 putpkt ("qSymbol::");
3245 getpkt (&rs->buf, &rs->buf_size, 0);
3246 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
3247 reply = rs->buf;
3248
3249 while (strncmp (reply, "qSymbol:", 8) == 0)
3250 {
3251 tmp = &reply[8];
3252 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
3253 msg[end] = '\0';
3254 sym = lookup_minimal_symbol (msg, NULL, NULL);
3255 if (sym == NULL)
3256 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
3257 else
3258 {
3259 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
3260 CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
3261
3262 /* If this is a function address, return the start of code
3263 instead of any data function descriptor. */
3264 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch,
3265 sym_addr,
3266 &current_target);
3267
3268 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
3269 phex_nz (sym_addr, addr_size), &reply[8]);
3270 }
3271
3272 putpkt (msg);
3273 getpkt (&rs->buf, &rs->buf_size, 0);
3274 reply = rs->buf;
3275 }
3276 }
3277
3278 static struct serial *
3279 remote_serial_open (char *name)
3280 {
3281 static int udp_warning = 0;
3282
3283 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3284 of in ser-tcp.c, because it is the remote protocol assuming that the
3285 serial connection is reliable and not the serial connection promising
3286 to be. */
3287 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
3288 {
3289 warning (_("\
3290 The remote protocol may be unreliable over UDP.\n\
3291 Some events may be lost, rendering further debugging impossible."));
3292 udp_warning = 1;
3293 }
3294
3295 return serial_open (name);
3296 }
3297
3298 /* This type describes each known response to the qSupported
3299 packet. */
3300 struct protocol_feature
3301 {
3302 /* The name of this protocol feature. */
3303 const char *name;
3304
3305 /* The default for this protocol feature. */
3306 enum packet_support default_support;
3307
3308 /* The function to call when this feature is reported, or after
3309 qSupported processing if the feature is not supported.
3310 The first argument points to this structure. The second
3311 argument indicates whether the packet requested support be
3312 enabled, disabled, or probed (or the default, if this function
3313 is being called at the end of processing and this feature was
3314 not reported). The third argument may be NULL; if not NULL, it
3315 is a NUL-terminated string taken from the packet following
3316 this feature's name and an equals sign. */
3317 void (*func) (const struct protocol_feature *, enum packet_support,
3318 const char *);
3319
3320 /* The corresponding packet for this feature. Only used if
3321 FUNC is remote_supported_packet. */
3322 int packet;
3323 };
3324
3325 static void
3326 remote_supported_packet (const struct protocol_feature *feature,
3327 enum packet_support support,
3328 const char *argument)
3329 {
3330 if (argument)
3331 {
3332 warning (_("Remote qSupported response supplied an unexpected value for"
3333 " \"%s\"."), feature->name);
3334 return;
3335 }
3336
3337 if (remote_protocol_packets[feature->packet].support
3338 == PACKET_SUPPORT_UNKNOWN)
3339 remote_protocol_packets[feature->packet].support = support;
3340 }
3341
3342 static void
3343 remote_packet_size (const struct protocol_feature *feature,
3344 enum packet_support support, const char *value)
3345 {
3346 struct remote_state *rs = get_remote_state ();
3347
3348 int packet_size;
3349 char *value_end;
3350
3351 if (support != PACKET_ENABLE)
3352 return;
3353
3354 if (value == NULL || *value == '\0')
3355 {
3356 warning (_("Remote target reported \"%s\" without a size."),
3357 feature->name);
3358 return;
3359 }
3360
3361 errno = 0;
3362 packet_size = strtol (value, &value_end, 16);
3363 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3364 {
3365 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3366 feature->name, value);
3367 return;
3368 }
3369
3370 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3371 {
3372 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3373 packet_size, MAX_REMOTE_PACKET_SIZE);
3374 packet_size = MAX_REMOTE_PACKET_SIZE;
3375 }
3376
3377 /* Record the new maximum packet size. */
3378 rs->explicit_packet_size = packet_size;
3379 }
3380
3381 static void
3382 remote_multi_process_feature (const struct protocol_feature *feature,
3383 enum packet_support support, const char *value)
3384 {
3385 struct remote_state *rs = get_remote_state ();
3386 rs->multi_process_aware = (support == PACKET_ENABLE);
3387 }
3388
3389 static void
3390 remote_non_stop_feature (const struct protocol_feature *feature,
3391 enum packet_support support, const char *value)
3392 {
3393 struct remote_state *rs = get_remote_state ();
3394 rs->non_stop_aware = (support == PACKET_ENABLE);
3395 }
3396
3397 static void
3398 remote_cond_tracepoint_feature (const struct protocol_feature *feature,
3399 enum packet_support support,
3400 const char *value)
3401 {
3402 struct remote_state *rs = get_remote_state ();
3403 rs->cond_tracepoints = (support == PACKET_ENABLE);
3404 }
3405
3406 static void
3407 remote_fast_tracepoint_feature (const struct protocol_feature *feature,
3408 enum packet_support support,
3409 const char *value)
3410 {
3411 struct remote_state *rs = get_remote_state ();
3412 rs->fast_tracepoints = (support == PACKET_ENABLE);
3413 }
3414
3415 static void
3416 remote_disconnected_tracing_feature (const struct protocol_feature *feature,
3417 enum packet_support support,
3418 const char *value)
3419 {
3420 struct remote_state *rs = get_remote_state ();
3421 rs->disconnected_tracing = (support == PACKET_ENABLE);
3422 }
3423
3424 static struct protocol_feature remote_protocol_features[] = {
3425 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
3426 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
3427 PACKET_qXfer_auxv },
3428 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3429 PACKET_qXfer_features },
3430 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3431 PACKET_qXfer_libraries },
3432 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
3433 PACKET_qXfer_memory_map },
3434 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3435 PACKET_qXfer_spu_read },
3436 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3437 PACKET_qXfer_spu_write },
3438 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3439 PACKET_qXfer_osdata },
3440 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
3441 PACKET_qXfer_threads },
3442 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3443 PACKET_QPassSignals },
3444 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
3445 PACKET_QStartNoAckMode },
3446 { "multiprocess", PACKET_DISABLE, remote_multi_process_feature, -1 },
3447 { "QNonStop", PACKET_DISABLE, remote_non_stop_feature, -1 },
3448 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
3449 PACKET_qXfer_siginfo_read },
3450 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
3451 PACKET_qXfer_siginfo_write },
3452 { "ConditionalTracepoints", PACKET_DISABLE, remote_cond_tracepoint_feature,
3453 PACKET_ConditionalTracepoints },
3454 { "FastTracepoints", PACKET_DISABLE, remote_fast_tracepoint_feature,
3455 PACKET_FastTracepoints },
3456 { "DisconnectedTracing", PACKET_DISABLE, remote_disconnected_tracing_feature,
3457 -1 },
3458 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
3459 PACKET_bc },
3460 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
3461 PACKET_bs },
3462 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
3463 PACKET_TracepointSource },
3464 };
3465
3466 static char *remote_support_xml;
3467
3468 /* Register string appended to "xmlRegisters=" in qSupported query. */
3469
3470 void
3471 register_remote_support_xml (const char *xml ATTRIBUTE_UNUSED)
3472 {
3473 #if defined(HAVE_LIBEXPAT)
3474 if (remote_support_xml == NULL)
3475 remote_support_xml = concat ("xmlRegisters=", xml, NULL);
3476 else
3477 {
3478 char *copy = xstrdup (remote_support_xml + 13);
3479 char *p = strtok (copy, ",");
3480
3481 do
3482 {
3483 if (strcmp (p, xml) == 0)
3484 {
3485 /* already there */
3486 xfree (copy);
3487 return;
3488 }
3489 }
3490 while ((p = strtok (NULL, ",")) != NULL);
3491 xfree (copy);
3492
3493 p = concat (remote_support_xml, ",", xml, NULL);
3494 xfree (remote_support_xml);
3495 remote_support_xml = p;
3496 }
3497 #endif
3498 }
3499
3500 static char *
3501 remote_query_supported_append (char *msg, const char *append)
3502 {
3503 if (msg)
3504 {
3505 char *p = concat (msg, ";", append, NULL);
3506 xfree (msg);
3507 return p;
3508 }
3509 else
3510 return xstrdup (append);
3511 }
3512
3513 static void
3514 remote_query_supported (void)
3515 {
3516 struct remote_state *rs = get_remote_state ();
3517 char *next;
3518 int i;
3519 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
3520
3521 /* The packet support flags are handled differently for this packet
3522 than for most others. We treat an error, a disabled packet, and
3523 an empty response identically: any features which must be reported
3524 to be used will be automatically disabled. An empty buffer
3525 accomplishes this, since that is also the representation for a list
3526 containing no features. */
3527
3528 rs->buf[0] = 0;
3529 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
3530 {
3531 char *q = NULL;
3532 const char *qsupported = gdbarch_qsupported (target_gdbarch);
3533
3534 if (rs->extended)
3535 q = remote_query_supported_append (q, "multiprocess+");
3536
3537 if (qsupported)
3538 q = remote_query_supported_append (q, qsupported);
3539
3540 if (remote_support_xml)
3541 q = remote_query_supported_append (q, remote_support_xml);
3542
3543 if (q)
3544 {
3545 char *p = concat ("qSupported:", q, NULL);
3546 xfree (q);
3547 putpkt (p);
3548 xfree (p);
3549 }
3550 else
3551 putpkt ("qSupported");
3552
3553 getpkt (&rs->buf, &rs->buf_size, 0);
3554
3555 /* If an error occured, warn, but do not return - just reset the
3556 buffer to empty and go on to disable features. */
3557 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
3558 == PACKET_ERROR)
3559 {
3560 warning (_("Remote failure reply: %s"), rs->buf);
3561 rs->buf[0] = 0;
3562 }
3563 }
3564
3565 memset (seen, 0, sizeof (seen));
3566
3567 next = rs->buf;
3568 while (*next)
3569 {
3570 enum packet_support is_supported;
3571 char *p, *end, *name_end, *value;
3572
3573 /* First separate out this item from the rest of the packet. If
3574 there's another item after this, we overwrite the separator
3575 (terminated strings are much easier to work with). */
3576 p = next;
3577 end = strchr (p, ';');
3578 if (end == NULL)
3579 {
3580 end = p + strlen (p);
3581 next = end;
3582 }
3583 else
3584 {
3585 *end = '\0';
3586 next = end + 1;
3587
3588 if (end == p)
3589 {
3590 warning (_("empty item in \"qSupported\" response"));
3591 continue;
3592 }
3593 }
3594
3595 name_end = strchr (p, '=');
3596 if (name_end)
3597 {
3598 /* This is a name=value entry. */
3599 is_supported = PACKET_ENABLE;
3600 value = name_end + 1;
3601 *name_end = '\0';
3602 }
3603 else
3604 {
3605 value = NULL;
3606 switch (end[-1])
3607 {
3608 case '+':
3609 is_supported = PACKET_ENABLE;
3610 break;
3611
3612 case '-':
3613 is_supported = PACKET_DISABLE;
3614 break;
3615
3616 case '?':
3617 is_supported = PACKET_SUPPORT_UNKNOWN;
3618 break;
3619
3620 default:
3621 warning (_("unrecognized item \"%s\" in \"qSupported\" response"), p);
3622 continue;
3623 }
3624 end[-1] = '\0';
3625 }
3626
3627 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
3628 if (strcmp (remote_protocol_features[i].name, p) == 0)
3629 {
3630 const struct protocol_feature *feature;
3631
3632 seen[i] = 1;
3633 feature = &remote_protocol_features[i];
3634 feature->func (feature, is_supported, value);
3635 break;
3636 }
3637 }
3638
3639 /* If we increased the packet size, make sure to increase the global
3640 buffer size also. We delay this until after parsing the entire
3641 qSupported packet, because this is the same buffer we were
3642 parsing. */
3643 if (rs->buf_size < rs->explicit_packet_size)
3644 {
3645 rs->buf_size = rs->explicit_packet_size;
3646 rs->buf = xrealloc (rs->buf, rs->buf_size);
3647 }
3648
3649 /* Handle the defaults for unmentioned features. */
3650 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
3651 if (!seen[i])
3652 {
3653 const struct protocol_feature *feature;
3654
3655 feature = &remote_protocol_features[i];
3656 feature->func (feature, feature->default_support, NULL);
3657 }
3658 }
3659
3660
3661 static void
3662 remote_open_1 (char *name, int from_tty, struct target_ops *target, int extended_p)
3663 {
3664 struct remote_state *rs = get_remote_state ();
3665
3666 if (name == 0)
3667 error (_("To open a remote debug connection, you need to specify what\n"
3668 "serial device is attached to the remote system\n"
3669 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
3670
3671 /* See FIXME above. */
3672 if (!target_async_permitted)
3673 wait_forever_enabled_p = 1;
3674
3675 /* If we're connected to a running target, target_preopen will kill it.
3676 But if we're connected to a target system with no running process,
3677 then we will still be connected when it returns. Ask this question
3678 first, before target_preopen has a chance to kill anything. */
3679 if (remote_desc != NULL && !have_inferiors ())
3680 {
3681 if (!from_tty
3682 || query (_("Already connected to a remote target. Disconnect? ")))
3683 pop_target ();
3684 else
3685 error (_("Still connected."));
3686 }
3687
3688 target_preopen (from_tty);
3689
3690 unpush_target (target);
3691
3692 /* This time without a query. If we were connected to an
3693 extended-remote target and target_preopen killed the running
3694 process, we may still be connected. If we are starting "target
3695 remote" now, the extended-remote target will not have been
3696 removed by unpush_target. */
3697 if (remote_desc != NULL && !have_inferiors ())
3698 pop_target ();
3699
3700 /* Make sure we send the passed signals list the next time we resume. */
3701 xfree (last_pass_packet);
3702 last_pass_packet = NULL;
3703
3704 remote_fileio_reset ();
3705 reopen_exec_file ();
3706 reread_symbols ();
3707
3708 remote_desc = remote_serial_open (name);
3709 if (!remote_desc)
3710 perror_with_name (name);
3711
3712 if (baud_rate != -1)
3713 {
3714 if (serial_setbaudrate (remote_desc, baud_rate))
3715 {
3716 /* The requested speed could not be set. Error out to
3717 top level after closing remote_desc. Take care to
3718 set remote_desc to NULL to avoid closing remote_desc
3719 more than once. */
3720 serial_close (remote_desc);
3721 remote_desc = NULL;
3722 perror_with_name (name);
3723 }
3724 }
3725
3726 serial_raw (remote_desc);
3727
3728 /* If there is something sitting in the buffer we might take it as a
3729 response to a command, which would be bad. */
3730 serial_flush_input (remote_desc);
3731
3732 if (from_tty)
3733 {
3734 puts_filtered ("Remote debugging using ");
3735 puts_filtered (name);
3736 puts_filtered ("\n");
3737 }
3738 push_target (target); /* Switch to using remote target now. */
3739
3740 /* Register extra event sources in the event loop. */
3741 remote_async_inferior_event_token
3742 = create_async_event_handler (remote_async_inferior_event_handler,
3743 NULL);
3744 remote_async_get_pending_events_token
3745 = create_async_event_handler (remote_async_get_pending_events_handler,
3746 NULL);
3747
3748 /* Reset the target state; these things will be queried either by
3749 remote_query_supported or as they are needed. */
3750 init_all_packet_configs ();
3751 rs->cached_wait_status = 0;
3752 rs->explicit_packet_size = 0;
3753 rs->noack_mode = 0;
3754 rs->multi_process_aware = 0;
3755 rs->extended = extended_p;
3756 rs->non_stop_aware = 0;
3757 rs->waiting_for_stop_reply = 0;
3758 rs->ctrlc_pending_p = 0;
3759
3760 general_thread = not_sent_ptid;
3761 continue_thread = not_sent_ptid;
3762
3763 /* Probe for ability to use "ThreadInfo" query, as required. */
3764 use_threadinfo_query = 1;
3765 use_threadextra_query = 1;
3766
3767 if (target_async_permitted)
3768 {
3769 /* With this target we start out by owning the terminal. */
3770 remote_async_terminal_ours_p = 1;
3771
3772 /* FIXME: cagney/1999-09-23: During the initial connection it is
3773 assumed that the target is already ready and able to respond to
3774 requests. Unfortunately remote_start_remote() eventually calls
3775 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
3776 around this. Eventually a mechanism that allows
3777 wait_for_inferior() to expect/get timeouts will be
3778 implemented. */
3779 wait_forever_enabled_p = 0;
3780 }
3781
3782 /* First delete any symbols previously loaded from shared libraries. */
3783 no_shared_libraries (NULL, 0);
3784
3785 /* Start afresh. */
3786 init_thread_list ();
3787
3788 /* Start the remote connection. If error() or QUIT, discard this
3789 target (we'd otherwise be in an inconsistent state) and then
3790 propogate the error on up the exception chain. This ensures that
3791 the caller doesn't stumble along blindly assuming that the
3792 function succeeded. The CLI doesn't have this problem but other
3793 UI's, such as MI do.
3794
3795 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
3796 this function should return an error indication letting the
3797 caller restore the previous state. Unfortunately the command
3798 ``target remote'' is directly wired to this function making that
3799 impossible. On a positive note, the CLI side of this problem has
3800 been fixed - the function set_cmd_context() makes it possible for
3801 all the ``target ....'' commands to share a common callback
3802 function. See cli-dump.c. */
3803 {
3804 struct gdb_exception ex;
3805 struct start_remote_args args;
3806
3807 args.from_tty = from_tty;
3808 args.target = target;
3809 args.extended_p = extended_p;
3810
3811 ex = catch_exception (uiout, remote_start_remote, &args, RETURN_MASK_ALL);
3812 if (ex.reason < 0)
3813 {
3814 /* Pop the partially set up target - unless something else did
3815 already before throwing the exception. */
3816 if (remote_desc != NULL)
3817 pop_target ();
3818 if (target_async_permitted)
3819 wait_forever_enabled_p = 1;
3820 throw_exception (ex);
3821 }
3822 }
3823
3824 if (target_async_permitted)
3825 wait_forever_enabled_p = 1;
3826 }
3827
3828 /* This takes a program previously attached to and detaches it. After
3829 this is done, GDB can be used to debug some other program. We
3830 better not have left any breakpoints in the target program or it'll
3831 die when it hits one. */
3832
3833 static void
3834 remote_detach_1 (char *args, int from_tty, int extended)
3835 {
3836 int pid = ptid_get_pid (inferior_ptid);
3837 struct remote_state *rs = get_remote_state ();
3838
3839 if (args)
3840 error (_("Argument given to \"detach\" when remotely debugging."));
3841
3842 if (!target_has_execution)
3843 error (_("No process to detach from."));
3844
3845 /* Tell the remote target to detach. */
3846 if (remote_multi_process_p (rs))
3847 sprintf (rs->buf, "D;%x", pid);
3848 else
3849 strcpy (rs->buf, "D");
3850
3851 putpkt (rs->buf);
3852 getpkt (&rs->buf, &rs->buf_size, 0);
3853
3854 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
3855 ;
3856 else if (rs->buf[0] == '\0')
3857 error (_("Remote doesn't know how to detach"));
3858 else
3859 error (_("Can't detach process."));
3860
3861 if (from_tty)
3862 {
3863 if (remote_multi_process_p (rs))
3864 printf_filtered (_("Detached from remote %s.\n"),
3865 target_pid_to_str (pid_to_ptid (pid)));
3866 else
3867 {
3868 if (extended)
3869 puts_filtered (_("Detached from remote process.\n"));
3870 else
3871 puts_filtered (_("Ending remote debugging.\n"));
3872 }
3873 }
3874
3875 discard_pending_stop_replies (pid);
3876 target_mourn_inferior ();
3877 }
3878
3879 static void
3880 remote_detach (struct target_ops *ops, char *args, int from_tty)
3881 {
3882 remote_detach_1 (args, from_tty, 0);
3883 }
3884
3885 static void
3886 extended_remote_detach (struct target_ops *ops, char *args, int from_tty)
3887 {
3888 remote_detach_1 (args, from_tty, 1);
3889 }
3890
3891 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
3892
3893 static void
3894 remote_disconnect (struct target_ops *target, char *args, int from_tty)
3895 {
3896 if (args)
3897 error (_("Argument given to \"disconnect\" when remotely debugging."));
3898
3899 /* Make sure we unpush even the extended remote targets; mourn
3900 won't do it. So call remote_mourn_1 directly instead of
3901 target_mourn_inferior. */
3902 remote_mourn_1 (target);
3903
3904 if (from_tty)
3905 puts_filtered ("Ending remote debugging.\n");
3906 }
3907
3908 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
3909 be chatty about it. */
3910
3911 static void
3912 extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
3913 {
3914 struct remote_state *rs = get_remote_state ();
3915 int pid;
3916 char *wait_status = NULL;
3917
3918 pid = parse_pid_to_attach (args);
3919
3920 /* Remote PID can be freely equal to getpid, do not check it here the same
3921 way as in other targets. */
3922
3923 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
3924 error (_("This target does not support attaching to a process"));
3925
3926 sprintf (rs->buf, "vAttach;%x", pid);
3927 putpkt (rs->buf);
3928 getpkt (&rs->buf, &rs->buf_size, 0);
3929
3930 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
3931 {
3932 if (from_tty)
3933 printf_unfiltered (_("Attached to %s\n"),
3934 target_pid_to_str (pid_to_ptid (pid)));
3935
3936 if (!non_stop)
3937 {
3938 /* Save the reply for later. */
3939 wait_status = alloca (strlen (rs->buf) + 1);
3940 strcpy (wait_status, rs->buf);
3941 }
3942 else if (strcmp (rs->buf, "OK") != 0)
3943 error (_("Attaching to %s failed with: %s"),
3944 target_pid_to_str (pid_to_ptid (pid)),
3945 rs->buf);
3946 }
3947 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
3948 error (_("This target does not support attaching to a process"));
3949 else
3950 error (_("Attaching to %s failed"),
3951 target_pid_to_str (pid_to_ptid (pid)));
3952
3953 set_current_inferior (remote_add_inferior (pid, 1));
3954
3955 inferior_ptid = pid_to_ptid (pid);
3956
3957 if (non_stop)
3958 {
3959 struct thread_info *thread;
3960
3961 /* Get list of threads. */
3962 remote_threads_info (target);
3963
3964 thread = first_thread_of_process (pid);
3965 if (thread)
3966 inferior_ptid = thread->ptid;
3967 else
3968 inferior_ptid = pid_to_ptid (pid);
3969
3970 /* Invalidate our notion of the remote current thread. */
3971 record_currthread (minus_one_ptid);
3972 }
3973 else
3974 {
3975 /* Now, if we have thread information, update inferior_ptid. */
3976 inferior_ptid = remote_current_thread (inferior_ptid);
3977
3978 /* Add the main thread to the thread list. */
3979 add_thread_silent (inferior_ptid);
3980 }
3981
3982 /* Next, if the target can specify a description, read it. We do
3983 this before anything involving memory or registers. */
3984 target_find_description ();
3985
3986 if (!non_stop)
3987 {
3988 /* Use the previously fetched status. */
3989 gdb_assert (wait_status != NULL);
3990
3991 if (target_can_async_p ())
3992 {
3993 struct stop_reply *stop_reply;
3994 struct cleanup *old_chain;
3995
3996 stop_reply = stop_reply_xmalloc ();
3997 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
3998 remote_parse_stop_reply (wait_status, stop_reply);
3999 discard_cleanups (old_chain);
4000 push_stop_reply (stop_reply);
4001
4002 target_async (inferior_event_handler, 0);
4003 }
4004 else
4005 {
4006 gdb_assert (wait_status != NULL);
4007 strcpy (rs->buf, wait_status);
4008 rs->cached_wait_status = 1;
4009 }
4010 }
4011 else
4012 gdb_assert (wait_status == NULL);
4013 }
4014
4015 static void
4016 extended_remote_attach (struct target_ops *ops, char *args, int from_tty)
4017 {
4018 extended_remote_attach_1 (ops, args, from_tty);
4019 }
4020
4021 /* Convert hex digit A to a number. */
4022
4023 static int
4024 fromhex (int a)
4025 {
4026 if (a >= '0' && a <= '9')
4027 return a - '0';
4028 else if (a >= 'a' && a <= 'f')
4029 return a - 'a' + 10;
4030 else if (a >= 'A' && a <= 'F')
4031 return a - 'A' + 10;
4032 else
4033 error (_("Reply contains invalid hex digit %d"), a);
4034 }
4035
4036 int
4037 hex2bin (const char *hex, gdb_byte *bin, int count)
4038 {
4039 int i;
4040
4041 for (i = 0; i < count; i++)
4042 {
4043 if (hex[0] == 0 || hex[1] == 0)
4044 {
4045 /* Hex string is short, or of uneven length.
4046 Return the count that has been converted so far. */
4047 return i;
4048 }
4049 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
4050 hex += 2;
4051 }
4052 return i;
4053 }
4054
4055 /* Convert number NIB to a hex digit. */
4056
4057 static int
4058 tohex (int nib)
4059 {
4060 if (nib < 10)
4061 return '0' + nib;
4062 else
4063 return 'a' + nib - 10;
4064 }
4065
4066 int
4067 bin2hex (const gdb_byte *bin, char *hex, int count)
4068 {
4069 int i;
4070 /* May use a length, or a nul-terminated string as input. */
4071 if (count == 0)
4072 count = strlen ((char *) bin);
4073
4074 for (i = 0; i < count; i++)
4075 {
4076 *hex++ = tohex ((*bin >> 4) & 0xf);
4077 *hex++ = tohex (*bin++ & 0xf);
4078 }
4079 *hex = 0;
4080 return i;
4081 }
4082 \f
4083 /* Check for the availability of vCont. This function should also check
4084 the response. */
4085
4086 static void
4087 remote_vcont_probe (struct remote_state *rs)
4088 {
4089 char *buf;
4090
4091 strcpy (rs->buf, "vCont?");
4092 putpkt (rs->buf);
4093 getpkt (&rs->buf, &rs->buf_size, 0);
4094 buf = rs->buf;
4095
4096 /* Make sure that the features we assume are supported. */
4097 if (strncmp (buf, "vCont", 5) == 0)
4098 {
4099 char *p = &buf[5];
4100 int support_s, support_S, support_c, support_C;
4101
4102 support_s = 0;
4103 support_S = 0;
4104 support_c = 0;
4105 support_C = 0;
4106 rs->support_vCont_t = 0;
4107 while (p && *p == ';')
4108 {
4109 p++;
4110 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4111 support_s = 1;
4112 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4113 support_S = 1;
4114 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4115 support_c = 1;
4116 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4117 support_C = 1;
4118 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4119 rs->support_vCont_t = 1;
4120
4121 p = strchr (p, ';');
4122 }
4123
4124 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4125 BUF will make packet_ok disable the packet. */
4126 if (!support_s || !support_S || !support_c || !support_C)
4127 buf[0] = 0;
4128 }
4129
4130 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4131 }
4132
4133 /* Helper function for building "vCont" resumptions. Write a
4134 resumption to P. ENDP points to one-passed-the-end of the buffer
4135 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4136 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4137 resumed thread should be single-stepped and/or signalled. If PTID
4138 equals minus_one_ptid, then all threads are resumed; if PTID
4139 represents a process, then all threads of the process are resumed;
4140 the thread to be stepped and/or signalled is given in the global
4141 INFERIOR_PTID. */
4142
4143 static char *
4144 append_resumption (char *p, char *endp,
4145 ptid_t ptid, int step, enum target_signal siggnal)
4146 {
4147 struct remote_state *rs = get_remote_state ();
4148
4149 if (step && siggnal != TARGET_SIGNAL_0)
4150 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4151 else if (step)
4152 p += xsnprintf (p, endp - p, ";s");
4153 else if (siggnal != TARGET_SIGNAL_0)
4154 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4155 else
4156 p += xsnprintf (p, endp - p, ";c");
4157
4158 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4159 {
4160 ptid_t nptid;
4161
4162 /* All (-1) threads of process. */
4163 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
4164
4165 p += xsnprintf (p, endp - p, ":");
4166 p = write_ptid (p, endp, nptid);
4167 }
4168 else if (!ptid_equal (ptid, minus_one_ptid))
4169 {
4170 p += xsnprintf (p, endp - p, ":");
4171 p = write_ptid (p, endp, ptid);
4172 }
4173
4174 return p;
4175 }
4176
4177 /* Resume the remote inferior by using a "vCont" packet. The thread
4178 to be resumed is PTID; STEP and SIGGNAL indicate whether the
4179 resumed thread should be single-stepped and/or signalled. If PTID
4180 equals minus_one_ptid, then all threads are resumed; the thread to
4181 be stepped and/or signalled is given in the global INFERIOR_PTID.
4182 This function returns non-zero iff it resumes the inferior.
4183
4184 This function issues a strict subset of all possible vCont commands at the
4185 moment. */
4186
4187 static int
4188 remote_vcont_resume (ptid_t ptid, int step, enum target_signal siggnal)
4189 {
4190 struct remote_state *rs = get_remote_state ();
4191 char *p;
4192 char *endp;
4193
4194 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
4195 remote_vcont_probe (rs);
4196
4197 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
4198 return 0;
4199
4200 p = rs->buf;
4201 endp = rs->buf + get_remote_packet_size ();
4202
4203 /* If we could generate a wider range of packets, we'd have to worry
4204 about overflowing BUF. Should there be a generic
4205 "multi-part-packet" packet? */
4206
4207 p += xsnprintf (p, endp - p, "vCont");
4208
4209 if (ptid_equal (ptid, magic_null_ptid))
4210 {
4211 /* MAGIC_NULL_PTID means that we don't have any active threads,
4212 so we don't have any TID numbers the inferior will
4213 understand. Make sure to only send forms that do not specify
4214 a TID. */
4215 p = append_resumption (p, endp, minus_one_ptid, step, siggnal);
4216 }
4217 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
4218 {
4219 /* Resume all threads (of all processes, or of a single
4220 process), with preference for INFERIOR_PTID. This assumes
4221 inferior_ptid belongs to the set of all threads we are about
4222 to resume. */
4223 if (step || siggnal != TARGET_SIGNAL_0)
4224 {
4225 /* Step inferior_ptid, with or without signal. */
4226 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
4227 }
4228
4229 /* And continue others without a signal. */
4230 p = append_resumption (p, endp, ptid, /*step=*/ 0, TARGET_SIGNAL_0);
4231 }
4232 else
4233 {
4234 /* Scheduler locking; resume only PTID. */
4235 p = append_resumption (p, endp, ptid, step, siggnal);
4236 }
4237
4238 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4239 putpkt (rs->buf);
4240
4241 if (non_stop)
4242 {
4243 /* In non-stop, the stub replies to vCont with "OK". The stop
4244 reply will be reported asynchronously by means of a `%Stop'
4245 notification. */
4246 getpkt (&rs->buf, &rs->buf_size, 0);
4247 if (strcmp (rs->buf, "OK") != 0)
4248 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4249 }
4250
4251 return 1;
4252 }
4253
4254 /* Tell the remote machine to resume. */
4255
4256 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
4257
4258 static int last_sent_step;
4259
4260 static void
4261 remote_resume (struct target_ops *ops,
4262 ptid_t ptid, int step, enum target_signal siggnal)
4263 {
4264 struct remote_state *rs = get_remote_state ();
4265 char *buf;
4266
4267 last_sent_signal = siggnal;
4268 last_sent_step = step;
4269
4270 /* Update the inferior on signals to silently pass, if they've changed. */
4271 remote_pass_signals ();
4272
4273 /* The vCont packet doesn't need to specify threads via Hc. */
4274 /* No reverse support (yet) for vCont. */
4275 if (execution_direction != EXEC_REVERSE)
4276 if (remote_vcont_resume (ptid, step, siggnal))
4277 goto done;
4278
4279 /* All other supported resume packets do use Hc, so set the continue
4280 thread. */
4281 if (ptid_equal (ptid, minus_one_ptid))
4282 set_continue_thread (any_thread_ptid);
4283 else
4284 set_continue_thread (ptid);
4285
4286 buf = rs->buf;
4287 if (execution_direction == EXEC_REVERSE)
4288 {
4289 /* We don't pass signals to the target in reverse exec mode. */
4290 if (info_verbose && siggnal != TARGET_SIGNAL_0)
4291 warning (" - Can't pass signal %d to target in reverse: ignored.\n",
4292 siggnal);
4293
4294 if (step
4295 && remote_protocol_packets[PACKET_bs].support == PACKET_DISABLE)
4296 error (_("Remote reverse-step not supported."));
4297 if (!step
4298 && remote_protocol_packets[PACKET_bc].support == PACKET_DISABLE)
4299 error (_("Remote reverse-continue not supported."));
4300
4301 strcpy (buf, step ? "bs" : "bc");
4302 }
4303 else if (siggnal != TARGET_SIGNAL_0)
4304 {
4305 buf[0] = step ? 'S' : 'C';
4306 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
4307 buf[2] = tohex (((int) siggnal) & 0xf);
4308 buf[3] = '\0';
4309 }
4310 else
4311 strcpy (buf, step ? "s" : "c");
4312
4313 putpkt (buf);
4314
4315 done:
4316 /* We are about to start executing the inferior, let's register it
4317 with the event loop. NOTE: this is the one place where all the
4318 execution commands end up. We could alternatively do this in each
4319 of the execution commands in infcmd.c. */
4320 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4321 into infcmd.c in order to allow inferior function calls to work
4322 NOT asynchronously. */
4323 if (target_can_async_p ())
4324 target_async (inferior_event_handler, 0);
4325
4326 /* We've just told the target to resume. The remote server will
4327 wait for the inferior to stop, and then send a stop reply. In
4328 the mean time, we can't start another command/query ourselves
4329 because the stub wouldn't be ready to process it. This applies
4330 only to the base all-stop protocol, however. In non-stop (which
4331 only supports vCont), the stub replies with an "OK", and is
4332 immediate able to process further serial input. */
4333 if (!non_stop)
4334 rs->waiting_for_stop_reply = 1;
4335 }
4336 \f
4337
4338 /* Set up the signal handler for SIGINT, while the target is
4339 executing, ovewriting the 'regular' SIGINT signal handler. */
4340 static void
4341 initialize_sigint_signal_handler (void)
4342 {
4343 signal (SIGINT, handle_remote_sigint);
4344 }
4345
4346 /* Signal handler for SIGINT, while the target is executing. */
4347 static void
4348 handle_remote_sigint (int sig)
4349 {
4350 signal (sig, handle_remote_sigint_twice);
4351 mark_async_signal_handler_wrapper (sigint_remote_token);
4352 }
4353
4354 /* Signal handler for SIGINT, installed after SIGINT has already been
4355 sent once. It will take effect the second time that the user sends
4356 a ^C. */
4357 static void
4358 handle_remote_sigint_twice (int sig)
4359 {
4360 signal (sig, handle_remote_sigint);
4361 mark_async_signal_handler_wrapper (sigint_remote_twice_token);
4362 }
4363
4364 /* Perform the real interruption of the target execution, in response
4365 to a ^C. */
4366 static void
4367 async_remote_interrupt (gdb_client_data arg)
4368 {
4369 if (remote_debug)
4370 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
4371
4372 target_stop (inferior_ptid);
4373 }
4374
4375 /* Perform interrupt, if the first attempt did not succeed. Just give
4376 up on the target alltogether. */
4377 void
4378 async_remote_interrupt_twice (gdb_client_data arg)
4379 {
4380 if (remote_debug)
4381 fprintf_unfiltered (gdb_stdlog, "remote_interrupt_twice called\n");
4382
4383 interrupt_query ();
4384 }
4385
4386 /* Reinstall the usual SIGINT handlers, after the target has
4387 stopped. */
4388 static void
4389 cleanup_sigint_signal_handler (void *dummy)
4390 {
4391 signal (SIGINT, handle_sigint);
4392 }
4393
4394 /* Send ^C to target to halt it. Target will respond, and send us a
4395 packet. */
4396 static void (*ofunc) (int);
4397
4398 /* The command line interface's stop routine. This function is installed
4399 as a signal handler for SIGINT. The first time a user requests a
4400 stop, we call remote_stop to send a break or ^C. If there is no
4401 response from the target (it didn't stop when the user requested it),
4402 we ask the user if he'd like to detach from the target. */
4403 static void
4404 remote_interrupt (int signo)
4405 {
4406 /* If this doesn't work, try more severe steps. */
4407 signal (signo, remote_interrupt_twice);
4408
4409 gdb_call_async_signal_handler (sigint_remote_token, 1);
4410 }
4411
4412 /* The user typed ^C twice. */
4413
4414 static void
4415 remote_interrupt_twice (int signo)
4416 {
4417 signal (signo, ofunc);
4418 gdb_call_async_signal_handler (sigint_remote_twice_token, 1);
4419 signal (signo, remote_interrupt);
4420 }
4421
4422 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
4423 thread, all threads of a remote process, or all threads of all
4424 processes. */
4425
4426 static void
4427 remote_stop_ns (ptid_t ptid)
4428 {
4429 struct remote_state *rs = get_remote_state ();
4430 char *p = rs->buf;
4431 char *endp = rs->buf + get_remote_packet_size ();
4432
4433 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
4434 remote_vcont_probe (rs);
4435
4436 if (!rs->support_vCont_t)
4437 error (_("Remote server does not support stopping threads"));
4438
4439 if (ptid_equal (ptid, minus_one_ptid)
4440 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4441 p += xsnprintf (p, endp - p, "vCont;t");
4442 else
4443 {
4444 ptid_t nptid;
4445
4446 p += xsnprintf (p, endp - p, "vCont;t:");
4447
4448 if (ptid_is_pid (ptid))
4449 /* All (-1) threads of process. */
4450 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
4451 else
4452 {
4453 /* Small optimization: if we already have a stop reply for
4454 this thread, no use in telling the stub we want this
4455 stopped. */
4456 if (peek_stop_reply (ptid))
4457 return;
4458
4459 nptid = ptid;
4460 }
4461
4462 p = write_ptid (p, endp, nptid);
4463 }
4464
4465 /* In non-stop, we get an immediate OK reply. The stop reply will
4466 come in asynchronously by notification. */
4467 putpkt (rs->buf);
4468 getpkt (&rs->buf, &rs->buf_size, 0);
4469 if (strcmp (rs->buf, "OK") != 0)
4470 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
4471 }
4472
4473 /* All-stop version of target_stop. Sends a break or a ^C to stop the
4474 remote target. It is undefined which thread of which process
4475 reports the stop. */
4476
4477 static void
4478 remote_stop_as (ptid_t ptid)
4479 {
4480 struct remote_state *rs = get_remote_state ();
4481
4482 rs->ctrlc_pending_p = 1;
4483
4484 /* If the inferior is stopped already, but the core didn't know
4485 about it yet, just ignore the request. The cached wait status
4486 will be collected in remote_wait. */
4487 if (rs->cached_wait_status)
4488 return;
4489
4490 /* Send interrupt_sequence to remote target. */
4491 send_interrupt_sequence ();
4492 }
4493
4494 /* This is the generic stop called via the target vector. When a target
4495 interrupt is requested, either by the command line or the GUI, we
4496 will eventually end up here. */
4497
4498 static void
4499 remote_stop (ptid_t ptid)
4500 {
4501 if (remote_debug)
4502 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
4503
4504 if (non_stop)
4505 remote_stop_ns (ptid);
4506 else
4507 remote_stop_as (ptid);
4508 }
4509
4510 /* Ask the user what to do when an interrupt is received. */
4511
4512 static void
4513 interrupt_query (void)
4514 {
4515 target_terminal_ours ();
4516
4517 if (target_can_async_p ())
4518 {
4519 signal (SIGINT, handle_sigint);
4520 deprecated_throw_reason (RETURN_QUIT);
4521 }
4522 else
4523 {
4524 if (query (_("Interrupted while waiting for the program.\n\
4525 Give up (and stop debugging it)? ")))
4526 {
4527 pop_target ();
4528 deprecated_throw_reason (RETURN_QUIT);
4529 }
4530 }
4531
4532 target_terminal_inferior ();
4533 }
4534
4535 /* Enable/disable target terminal ownership. Most targets can use
4536 terminal groups to control terminal ownership. Remote targets are
4537 different in that explicit transfer of ownership to/from GDB/target
4538 is required. */
4539
4540 static void
4541 remote_terminal_inferior (void)
4542 {
4543 if (!target_async_permitted)
4544 /* Nothing to do. */
4545 return;
4546
4547 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
4548 idempotent. The event-loop GDB talking to an asynchronous target
4549 with a synchronous command calls this function from both
4550 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
4551 transfer the terminal to the target when it shouldn't this guard
4552 can go away. */
4553 if (!remote_async_terminal_ours_p)
4554 return;
4555 delete_file_handler (input_fd);
4556 remote_async_terminal_ours_p = 0;
4557 initialize_sigint_signal_handler ();
4558 /* NOTE: At this point we could also register our selves as the
4559 recipient of all input. Any characters typed could then be
4560 passed on down to the target. */
4561 }
4562
4563 static void
4564 remote_terminal_ours (void)
4565 {
4566 if (!target_async_permitted)
4567 /* Nothing to do. */
4568 return;
4569
4570 /* See FIXME in remote_terminal_inferior. */
4571 if (remote_async_terminal_ours_p)
4572 return;
4573 cleanup_sigint_signal_handler (NULL);
4574 add_file_handler (input_fd, stdin_event_handler, 0);
4575 remote_async_terminal_ours_p = 1;
4576 }
4577
4578 void
4579 remote_console_output (char *msg)
4580 {
4581 char *p;
4582
4583 for (p = msg; p[0] && p[1]; p += 2)
4584 {
4585 char tb[2];
4586 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
4587 tb[0] = c;
4588 tb[1] = 0;
4589 fputs_unfiltered (tb, gdb_stdtarg);
4590 }
4591 gdb_flush (gdb_stdtarg);
4592 }
4593
4594 typedef struct cached_reg
4595 {
4596 int num;
4597 gdb_byte data[MAX_REGISTER_SIZE];
4598 } cached_reg_t;
4599
4600 DEF_VEC_O(cached_reg_t);
4601
4602 struct stop_reply
4603 {
4604 struct stop_reply *next;
4605
4606 ptid_t ptid;
4607
4608 struct target_waitstatus ws;
4609
4610 VEC(cached_reg_t) *regcache;
4611
4612 int stopped_by_watchpoint_p;
4613 CORE_ADDR watch_data_address;
4614
4615 int solibs_changed;
4616 int replay_event;
4617
4618 int core;
4619 };
4620
4621 /* The list of already fetched and acknowledged stop events. */
4622 static struct stop_reply *stop_reply_queue;
4623
4624 static struct stop_reply *
4625 stop_reply_xmalloc (void)
4626 {
4627 struct stop_reply *r = XMALLOC (struct stop_reply);
4628 r->next = NULL;
4629 return r;
4630 }
4631
4632 static void
4633 stop_reply_xfree (struct stop_reply *r)
4634 {
4635 if (r != NULL)
4636 {
4637 VEC_free (cached_reg_t, r->regcache);
4638 xfree (r);
4639 }
4640 }
4641
4642 /* Discard all pending stop replies of inferior PID. If PID is -1,
4643 discard everything. */
4644
4645 static void
4646 discard_pending_stop_replies (int pid)
4647 {
4648 struct stop_reply *prev = NULL, *reply, *next;
4649
4650 /* Discard the in-flight notification. */
4651 if (pending_stop_reply != NULL
4652 && (pid == -1
4653 || ptid_get_pid (pending_stop_reply->ptid) == pid))
4654 {
4655 stop_reply_xfree (pending_stop_reply);
4656 pending_stop_reply = NULL;
4657 }
4658
4659 /* Discard the stop replies we have already pulled with
4660 vStopped. */
4661 for (reply = stop_reply_queue; reply; reply = next)
4662 {
4663 next = reply->next;
4664 if (pid == -1
4665 || ptid_get_pid (reply->ptid) == pid)
4666 {
4667 if (reply == stop_reply_queue)
4668 stop_reply_queue = reply->next;
4669 else
4670 prev->next = reply->next;
4671
4672 stop_reply_xfree (reply);
4673 }
4674 else
4675 prev = reply;
4676 }
4677 }
4678
4679 /* Cleanup wrapper. */
4680
4681 static void
4682 do_stop_reply_xfree (void *arg)
4683 {
4684 struct stop_reply *r = arg;
4685 stop_reply_xfree (r);
4686 }
4687
4688 /* Look for a queued stop reply belonging to PTID. If one is found,
4689 remove it from the queue, and return it. Returns NULL if none is
4690 found. If there are still queued events left to process, tell the
4691 event loop to get back to target_wait soon. */
4692
4693 static struct stop_reply *
4694 queued_stop_reply (ptid_t ptid)
4695 {
4696 struct stop_reply *it;
4697 struct stop_reply **it_link;
4698
4699 it = stop_reply_queue;
4700 it_link = &stop_reply_queue;
4701 while (it)
4702 {
4703 if (ptid_match (it->ptid, ptid))
4704 {
4705 *it_link = it->next;
4706 it->next = NULL;
4707 break;
4708 }
4709
4710 it_link = &it->next;
4711 it = *it_link;
4712 }
4713
4714 if (stop_reply_queue)
4715 /* There's still at least an event left. */
4716 mark_async_event_handler (remote_async_inferior_event_token);
4717
4718 return it;
4719 }
4720
4721 /* Push a fully parsed stop reply in the stop reply queue. Since we
4722 know that we now have at least one queued event left to pass to the
4723 core side, tell the event loop to get back to target_wait soon. */
4724
4725 static void
4726 push_stop_reply (struct stop_reply *new_event)
4727 {
4728 struct stop_reply *event;
4729
4730 if (stop_reply_queue)
4731 {
4732 for (event = stop_reply_queue;
4733 event && event->next;
4734 event = event->next)
4735 ;
4736
4737 event->next = new_event;
4738 }
4739 else
4740 stop_reply_queue = new_event;
4741
4742 mark_async_event_handler (remote_async_inferior_event_token);
4743 }
4744
4745 /* Returns true if we have a stop reply for PTID. */
4746
4747 static int
4748 peek_stop_reply (ptid_t ptid)
4749 {
4750 struct stop_reply *it;
4751
4752 for (it = stop_reply_queue; it; it = it->next)
4753 if (ptid_equal (ptid, it->ptid))
4754 {
4755 if (it->ws.kind == TARGET_WAITKIND_STOPPED)
4756 return 1;
4757 }
4758
4759 return 0;
4760 }
4761
4762 /* Parse the stop reply in BUF. Either the function succeeds, and the
4763 result is stored in EVENT, or throws an error. */
4764
4765 static void
4766 remote_parse_stop_reply (char *buf, struct stop_reply *event)
4767 {
4768 struct remote_arch_state *rsa = get_remote_arch_state ();
4769 ULONGEST addr;
4770 char *p;
4771
4772 event->ptid = null_ptid;
4773 event->ws.kind = TARGET_WAITKIND_IGNORE;
4774 event->ws.value.integer = 0;
4775 event->solibs_changed = 0;
4776 event->replay_event = 0;
4777 event->stopped_by_watchpoint_p = 0;
4778 event->regcache = NULL;
4779 event->core = -1;
4780
4781 switch (buf[0])
4782 {
4783 case 'T': /* Status with PC, SP, FP, ... */
4784 /* Expedited reply, containing Signal, {regno, reg} repeat. */
4785 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
4786 ss = signal number
4787 n... = register number
4788 r... = register contents
4789 */
4790
4791 p = &buf[3]; /* after Txx */
4792 while (*p)
4793 {
4794 char *p1;
4795 char *p_temp;
4796 int fieldsize;
4797 LONGEST pnum = 0;
4798
4799 /* If the packet contains a register number, save it in
4800 pnum and set p1 to point to the character following it.
4801 Otherwise p1 points to p. */
4802
4803 /* If this packet is an awatch packet, don't parse the 'a'
4804 as a register number. */
4805
4806 if (strncmp (p, "awatch", strlen("awatch")) != 0
4807 && strncmp (p, "core", strlen ("core") != 0))
4808 {
4809 /* Read the ``P'' register number. */
4810 pnum = strtol (p, &p_temp, 16);
4811 p1 = p_temp;
4812 }
4813 else
4814 p1 = p;
4815
4816 if (p1 == p) /* No register number present here. */
4817 {
4818 p1 = strchr (p, ':');
4819 if (p1 == NULL)
4820 error (_("Malformed packet(a) (missing colon): %s\n\
4821 Packet: '%s'\n"),
4822 p, buf);
4823 if (strncmp (p, "thread", p1 - p) == 0)
4824 event->ptid = read_ptid (++p1, &p);
4825 else if ((strncmp (p, "watch", p1 - p) == 0)
4826 || (strncmp (p, "rwatch", p1 - p) == 0)
4827 || (strncmp (p, "awatch", p1 - p) == 0))
4828 {
4829 event->stopped_by_watchpoint_p = 1;
4830 p = unpack_varlen_hex (++p1, &addr);
4831 event->watch_data_address = (CORE_ADDR) addr;
4832 }
4833 else if (strncmp (p, "library", p1 - p) == 0)
4834 {
4835 p1++;
4836 p_temp = p1;
4837 while (*p_temp && *p_temp != ';')
4838 p_temp++;
4839
4840 event->solibs_changed = 1;
4841 p = p_temp;
4842 }
4843 else if (strncmp (p, "replaylog", p1 - p) == 0)
4844 {
4845 /* NO_HISTORY event.
4846 p1 will indicate "begin" or "end", but
4847 it makes no difference for now, so ignore it. */
4848 event->replay_event = 1;
4849 p_temp = strchr (p1 + 1, ';');
4850 if (p_temp)
4851 p = p_temp;
4852 }
4853 else if (strncmp (p, "core", p1 - p) == 0)
4854 {
4855 ULONGEST c;
4856 p = unpack_varlen_hex (++p1, &c);
4857 event->core = c;
4858 }
4859 else
4860 {
4861 /* Silently skip unknown optional info. */
4862 p_temp = strchr (p1 + 1, ';');
4863 if (p_temp)
4864 p = p_temp;
4865 }
4866 }
4867 else
4868 {
4869 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
4870 cached_reg_t cached_reg;
4871
4872 p = p1;
4873
4874 if (*p != ':')
4875 error (_("Malformed packet(b) (missing colon): %s\n\
4876 Packet: '%s'\n"),
4877 p, buf);
4878 ++p;
4879
4880 if (reg == NULL)
4881 error (_("Remote sent bad register number %s: %s\n\
4882 Packet: '%s'\n"),
4883 hex_string (pnum), p, buf);
4884
4885 cached_reg.num = reg->regnum;
4886
4887 fieldsize = hex2bin (p, cached_reg.data,
4888 register_size (target_gdbarch,
4889 reg->regnum));
4890 p += 2 * fieldsize;
4891 if (fieldsize < register_size (target_gdbarch,
4892 reg->regnum))
4893 warning (_("Remote reply is too short: %s"), buf);
4894
4895 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
4896 }
4897
4898 if (*p != ';')
4899 error (_("Remote register badly formatted: %s\nhere: %s"),
4900 buf, p);
4901 ++p;
4902 }
4903 /* fall through */
4904 case 'S': /* Old style status, just signal only. */
4905 if (event->solibs_changed)
4906 event->ws.kind = TARGET_WAITKIND_LOADED;
4907 else if (event->replay_event)
4908 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
4909 else
4910 {
4911 event->ws.kind = TARGET_WAITKIND_STOPPED;
4912 event->ws.value.sig = (enum target_signal)
4913 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
4914 }
4915 break;
4916 case 'W': /* Target exited. */
4917 case 'X':
4918 {
4919 char *p;
4920 int pid;
4921 ULONGEST value;
4922
4923 /* GDB used to accept only 2 hex chars here. Stubs should
4924 only send more if they detect GDB supports multi-process
4925 support. */
4926 p = unpack_varlen_hex (&buf[1], &value);
4927
4928 if (buf[0] == 'W')
4929 {
4930 /* The remote process exited. */
4931 event->ws.kind = TARGET_WAITKIND_EXITED;
4932 event->ws.value.integer = value;
4933 }
4934 else
4935 {
4936 /* The remote process exited with a signal. */
4937 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
4938 event->ws.value.sig = (enum target_signal) value;
4939 }
4940
4941 /* If no process is specified, assume inferior_ptid. */
4942 pid = ptid_get_pid (inferior_ptid);
4943 if (*p == '\0')
4944 ;
4945 else if (*p == ';')
4946 {
4947 p++;
4948
4949 if (p == '\0')
4950 ;
4951 else if (strncmp (p,
4952 "process:", sizeof ("process:") - 1) == 0)
4953 {
4954 ULONGEST upid;
4955 p += sizeof ("process:") - 1;
4956 unpack_varlen_hex (p, &upid);
4957 pid = upid;
4958 }
4959 else
4960 error (_("unknown stop reply packet: %s"), buf);
4961 }
4962 else
4963 error (_("unknown stop reply packet: %s"), buf);
4964 event->ptid = pid_to_ptid (pid);
4965 }
4966 break;
4967 }
4968
4969 if (non_stop && ptid_equal (event->ptid, null_ptid))
4970 error (_("No process or thread specified in stop reply: %s"), buf);
4971 }
4972
4973 /* When the stub wants to tell GDB about a new stop reply, it sends a
4974 stop notification (%Stop). Those can come it at any time, hence,
4975 we have to make sure that any pending putpkt/getpkt sequence we're
4976 making is finished, before querying the stub for more events with
4977 vStopped. E.g., if we started a vStopped sequence immediatelly
4978 upon receiving the %Stop notification, something like this could
4979 happen:
4980
4981 1.1) --> Hg 1
4982 1.2) <-- OK
4983 1.3) --> g
4984 1.4) <-- %Stop
4985 1.5) --> vStopped
4986 1.6) <-- (registers reply to step #1.3)
4987
4988 Obviously, the reply in step #1.6 would be unexpected to a vStopped
4989 query.
4990
4991 To solve this, whenever we parse a %Stop notification sucessfully,
4992 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
4993 doing whatever we were doing:
4994
4995 2.1) --> Hg 1
4996 2.2) <-- OK
4997 2.3) --> g
4998 2.4) <-- %Stop
4999 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5000 2.5) <-- (registers reply to step #2.3)
5001
5002 Eventualy after step #2.5, we return to the event loop, which
5003 notices there's an event on the
5004 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5005 associated callback --- the function below. At this point, we're
5006 always safe to start a vStopped sequence. :
5007
5008 2.6) --> vStopped
5009 2.7) <-- T05 thread:2
5010 2.8) --> vStopped
5011 2.9) --> OK
5012 */
5013
5014 static void
5015 remote_get_pending_stop_replies (void)
5016 {
5017 struct remote_state *rs = get_remote_state ();
5018
5019 if (pending_stop_reply)
5020 {
5021 /* acknowledge */
5022 putpkt ("vStopped");
5023
5024 /* Now we can rely on it. */
5025 push_stop_reply (pending_stop_reply);
5026 pending_stop_reply = NULL;
5027
5028 while (1)
5029 {
5030 getpkt (&rs->buf, &rs->buf_size, 0);
5031 if (strcmp (rs->buf, "OK") == 0)
5032 break;
5033 else
5034 {
5035 struct cleanup *old_chain;
5036 struct stop_reply *stop_reply = stop_reply_xmalloc ();
5037
5038 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
5039 remote_parse_stop_reply (rs->buf, stop_reply);
5040
5041 /* acknowledge */
5042 putpkt ("vStopped");
5043
5044 if (stop_reply->ws.kind != TARGET_WAITKIND_IGNORE)
5045 {
5046 /* Now we can rely on it. */
5047 discard_cleanups (old_chain);
5048 push_stop_reply (stop_reply);
5049 }
5050 else
5051 /* We got an unknown stop reply. */
5052 do_cleanups (old_chain);
5053 }
5054 }
5055 }
5056 }
5057
5058
5059 /* Called when it is decided that STOP_REPLY holds the info of the
5060 event that is to be returned to the core. This function always
5061 destroys STOP_REPLY. */
5062
5063 static ptid_t
5064 process_stop_reply (struct stop_reply *stop_reply,
5065 struct target_waitstatus *status)
5066 {
5067 ptid_t ptid;
5068 struct thread_info *info;
5069
5070 *status = stop_reply->ws;
5071 ptid = stop_reply->ptid;
5072
5073 /* If no thread/process was reported by the stub, assume the current
5074 inferior. */
5075 if (ptid_equal (ptid, null_ptid))
5076 ptid = inferior_ptid;
5077
5078 if (status->kind != TARGET_WAITKIND_EXITED
5079 && status->kind != TARGET_WAITKIND_SIGNALLED)
5080 {
5081 /* Expedited registers. */
5082 if (stop_reply->regcache)
5083 {
5084 struct regcache *regcache
5085 = get_thread_arch_regcache (ptid, target_gdbarch);
5086 cached_reg_t *reg;
5087 int ix;
5088
5089 for (ix = 0;
5090 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5091 ix++)
5092 regcache_raw_supply (regcache, reg->num, reg->data);
5093 VEC_free (cached_reg_t, stop_reply->regcache);
5094 }
5095
5096 remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
5097 remote_watch_data_address = stop_reply->watch_data_address;
5098
5099 remote_notice_new_inferior (ptid, 0);
5100 demand_private_info (ptid)->core = stop_reply->core;
5101 }
5102
5103 stop_reply_xfree (stop_reply);
5104 return ptid;
5105 }
5106
5107 /* The non-stop mode version of target_wait. */
5108
5109 static ptid_t
5110 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
5111 {
5112 struct remote_state *rs = get_remote_state ();
5113 struct stop_reply *stop_reply;
5114 int ret;
5115
5116 /* If in non-stop mode, get out of getpkt even if a
5117 notification is received. */
5118
5119 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5120 0 /* forever */);
5121 while (1)
5122 {
5123 if (ret != -1)
5124 switch (rs->buf[0])
5125 {
5126 case 'E': /* Error of some sort. */
5127 /* We're out of sync with the target now. Did it continue
5128 or not? We can't tell which thread it was in non-stop,
5129 so just ignore this. */
5130 warning (_("Remote failure reply: %s"), rs->buf);
5131 break;
5132 case 'O': /* Console output. */
5133 remote_console_output (rs->buf + 1);
5134 break;
5135 default:
5136 warning (_("Invalid remote reply: %s"), rs->buf);
5137 break;
5138 }
5139
5140 /* Acknowledge a pending stop reply that may have arrived in the
5141 mean time. */
5142 if (pending_stop_reply != NULL)
5143 remote_get_pending_stop_replies ();
5144
5145 /* If indeed we noticed a stop reply, we're done. */
5146 stop_reply = queued_stop_reply (ptid);
5147 if (stop_reply != NULL)
5148 return process_stop_reply (stop_reply, status);
5149
5150 /* Still no event. If we're just polling for an event, then
5151 return to the event loop. */
5152 if (options & TARGET_WNOHANG)
5153 {
5154 status->kind = TARGET_WAITKIND_IGNORE;
5155 return minus_one_ptid;
5156 }
5157
5158 /* Otherwise do a blocking wait. */
5159 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5160 1 /* forever */);
5161 }
5162 }
5163
5164 /* Wait until the remote machine stops, then return, storing status in
5165 STATUS just as `wait' would. */
5166
5167 static ptid_t
5168 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
5169 {
5170 struct remote_state *rs = get_remote_state ();
5171 ptid_t event_ptid = null_ptid;
5172 char *buf;
5173 struct stop_reply *stop_reply;
5174
5175 again:
5176
5177 status->kind = TARGET_WAITKIND_IGNORE;
5178 status->value.integer = 0;
5179
5180 stop_reply = queued_stop_reply (ptid);
5181 if (stop_reply != NULL)
5182 return process_stop_reply (stop_reply, status);
5183
5184 if (rs->cached_wait_status)
5185 /* Use the cached wait status, but only once. */
5186 rs->cached_wait_status = 0;
5187 else
5188 {
5189 int ret;
5190
5191 if (!target_is_async_p ())
5192 {
5193 ofunc = signal (SIGINT, remote_interrupt);
5194 /* If the user hit C-c before this packet, or between packets,
5195 pretend that it was hit right here. */
5196 if (quit_flag)
5197 {
5198 quit_flag = 0;
5199 remote_interrupt (SIGINT);
5200 }
5201 }
5202
5203 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5204 _never_ wait for ever -> test on target_is_async_p().
5205 However, before we do that we need to ensure that the caller
5206 knows how to take the target into/out of async mode. */
5207 ret = getpkt_sane (&rs->buf, &rs->buf_size, wait_forever_enabled_p);
5208 if (!target_is_async_p ())
5209 signal (SIGINT, ofunc);
5210 }
5211
5212 buf = rs->buf;
5213
5214 remote_stopped_by_watchpoint_p = 0;
5215
5216 /* We got something. */
5217 rs->waiting_for_stop_reply = 0;
5218
5219 /* Assume that the target has acknowledged Ctrl-C unless we receive
5220 an 'F' or 'O' packet. */
5221 if (buf[0] != 'F' && buf[0] != 'O')
5222 rs->ctrlc_pending_p = 0;
5223
5224 switch (buf[0])
5225 {
5226 case 'E': /* Error of some sort. */
5227 /* We're out of sync with the target now. Did it continue or
5228 not? Not is more likely, so report a stop. */
5229 warning (_("Remote failure reply: %s"), buf);
5230 status->kind = TARGET_WAITKIND_STOPPED;
5231 status->value.sig = TARGET_SIGNAL_0;
5232 break;
5233 case 'F': /* File-I/O request. */
5234 remote_fileio_request (buf, rs->ctrlc_pending_p);
5235 rs->ctrlc_pending_p = 0;
5236 break;
5237 case 'T': case 'S': case 'X': case 'W':
5238 {
5239 struct stop_reply *stop_reply;
5240 struct cleanup *old_chain;
5241
5242 stop_reply = stop_reply_xmalloc ();
5243 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
5244 remote_parse_stop_reply (buf, stop_reply);
5245 discard_cleanups (old_chain);
5246 event_ptid = process_stop_reply (stop_reply, status);
5247 break;
5248 }
5249 case 'O': /* Console output. */
5250 remote_console_output (buf + 1);
5251
5252 /* The target didn't really stop; keep waiting. */
5253 rs->waiting_for_stop_reply = 1;
5254
5255 break;
5256 case '\0':
5257 if (last_sent_signal != TARGET_SIGNAL_0)
5258 {
5259 /* Zero length reply means that we tried 'S' or 'C' and the
5260 remote system doesn't support it. */
5261 target_terminal_ours_for_output ();
5262 printf_filtered
5263 ("Can't send signals to this remote system. %s not sent.\n",
5264 target_signal_to_name (last_sent_signal));
5265 last_sent_signal = TARGET_SIGNAL_0;
5266 target_terminal_inferior ();
5267
5268 strcpy ((char *) buf, last_sent_step ? "s" : "c");
5269 putpkt ((char *) buf);
5270
5271 /* We just told the target to resume, so a stop reply is in
5272 order. */
5273 rs->waiting_for_stop_reply = 1;
5274 break;
5275 }
5276 /* else fallthrough */
5277 default:
5278 warning (_("Invalid remote reply: %s"), buf);
5279 /* Keep waiting. */
5280 rs->waiting_for_stop_reply = 1;
5281 break;
5282 }
5283
5284 if (status->kind == TARGET_WAITKIND_IGNORE)
5285 {
5286 /* Nothing interesting happened. If we're doing a non-blocking
5287 poll, we're done. Otherwise, go back to waiting. */
5288 if (options & TARGET_WNOHANG)
5289 return minus_one_ptid;
5290 else
5291 goto again;
5292 }
5293 else if (status->kind != TARGET_WAITKIND_EXITED
5294 && status->kind != TARGET_WAITKIND_SIGNALLED)
5295 {
5296 if (!ptid_equal (event_ptid, null_ptid))
5297 record_currthread (event_ptid);
5298 else
5299 event_ptid = inferior_ptid;
5300 }
5301 else
5302 /* A process exit. Invalidate our notion of current thread. */
5303 record_currthread (minus_one_ptid);
5304
5305 return event_ptid;
5306 }
5307
5308 /* Wait until the remote machine stops, then return, storing status in
5309 STATUS just as `wait' would. */
5310
5311 static ptid_t
5312 remote_wait (struct target_ops *ops,
5313 ptid_t ptid, struct target_waitstatus *status, int options)
5314 {
5315 ptid_t event_ptid;
5316
5317 if (non_stop)
5318 event_ptid = remote_wait_ns (ptid, status, options);
5319 else
5320 event_ptid = remote_wait_as (ptid, status, options);
5321
5322 if (target_can_async_p ())
5323 {
5324 /* If there are are events left in the queue tell the event loop
5325 to return here. */
5326 if (stop_reply_queue)
5327 mark_async_event_handler (remote_async_inferior_event_token);
5328 }
5329
5330 return event_ptid;
5331 }
5332
5333 /* Fetch a single register using a 'p' packet. */
5334
5335 static int
5336 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
5337 {
5338 struct remote_state *rs = get_remote_state ();
5339 char *buf, *p;
5340 char regp[MAX_REGISTER_SIZE];
5341 int i;
5342
5343 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
5344 return 0;
5345
5346 if (reg->pnum == -1)
5347 return 0;
5348
5349 p = rs->buf;
5350 *p++ = 'p';
5351 p += hexnumstr (p, reg->pnum);
5352 *p++ = '\0';
5353 putpkt (rs->buf);
5354 getpkt (&rs->buf, &rs->buf_size, 0);
5355
5356 buf = rs->buf;
5357
5358 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
5359 {
5360 case PACKET_OK:
5361 break;
5362 case PACKET_UNKNOWN:
5363 return 0;
5364 case PACKET_ERROR:
5365 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
5366 gdbarch_register_name (get_regcache_arch (regcache),
5367 reg->regnum),
5368 buf);
5369 }
5370
5371 /* If this register is unfetchable, tell the regcache. */
5372 if (buf[0] == 'x')
5373 {
5374 regcache_raw_supply (regcache, reg->regnum, NULL);
5375 return 1;
5376 }
5377
5378 /* Otherwise, parse and supply the value. */
5379 p = buf;
5380 i = 0;
5381 while (p[0] != 0)
5382 {
5383 if (p[1] == 0)
5384 error (_("fetch_register_using_p: early buf termination"));
5385
5386 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
5387 p += 2;
5388 }
5389 regcache_raw_supply (regcache, reg->regnum, regp);
5390 return 1;
5391 }
5392
5393 /* Fetch the registers included in the target's 'g' packet. */
5394
5395 static int
5396 send_g_packet (void)
5397 {
5398 struct remote_state *rs = get_remote_state ();
5399 int buf_len;
5400
5401 sprintf (rs->buf, "g");
5402 remote_send (&rs->buf, &rs->buf_size);
5403
5404 /* We can get out of synch in various cases. If the first character
5405 in the buffer is not a hex character, assume that has happened
5406 and try to fetch another packet to read. */
5407 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
5408 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
5409 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
5410 && rs->buf[0] != 'x') /* New: unavailable register value. */
5411 {
5412 if (remote_debug)
5413 fprintf_unfiltered (gdb_stdlog,
5414 "Bad register packet; fetching a new packet\n");
5415 getpkt (&rs->buf, &rs->buf_size, 0);
5416 }
5417
5418 buf_len = strlen (rs->buf);
5419
5420 /* Sanity check the received packet. */
5421 if (buf_len % 2 != 0)
5422 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
5423
5424 return buf_len / 2;
5425 }
5426
5427 static void
5428 process_g_packet (struct regcache *regcache)
5429 {
5430 struct gdbarch *gdbarch = get_regcache_arch (regcache);
5431 struct remote_state *rs = get_remote_state ();
5432 struct remote_arch_state *rsa = get_remote_arch_state ();
5433 int i, buf_len;
5434 char *p;
5435 char *regs;
5436
5437 buf_len = strlen (rs->buf);
5438
5439 /* Further sanity checks, with knowledge of the architecture. */
5440 if (buf_len > 2 * rsa->sizeof_g_packet)
5441 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
5442
5443 /* Save the size of the packet sent to us by the target. It is used
5444 as a heuristic when determining the max size of packets that the
5445 target can safely receive. */
5446 if (rsa->actual_register_packet_size == 0)
5447 rsa->actual_register_packet_size = buf_len;
5448
5449 /* If this is smaller than we guessed the 'g' packet would be,
5450 update our records. A 'g' reply that doesn't include a register's
5451 value implies either that the register is not available, or that
5452 the 'p' packet must be used. */
5453 if (buf_len < 2 * rsa->sizeof_g_packet)
5454 {
5455 rsa->sizeof_g_packet = buf_len / 2;
5456
5457 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
5458 {
5459 if (rsa->regs[i].pnum == -1)
5460 continue;
5461
5462 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
5463 rsa->regs[i].in_g_packet = 0;
5464 else
5465 rsa->regs[i].in_g_packet = 1;
5466 }
5467 }
5468
5469 regs = alloca (rsa->sizeof_g_packet);
5470
5471 /* Unimplemented registers read as all bits zero. */
5472 memset (regs, 0, rsa->sizeof_g_packet);
5473
5474 /* Reply describes registers byte by byte, each byte encoded as two
5475 hex characters. Suck them all up, then supply them to the
5476 register cacheing/storage mechanism. */
5477
5478 p = rs->buf;
5479 for (i = 0; i < rsa->sizeof_g_packet; i++)
5480 {
5481 if (p[0] == 0 || p[1] == 0)
5482 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
5483 internal_error (__FILE__, __LINE__,
5484 "unexpected end of 'g' packet reply");
5485
5486 if (p[0] == 'x' && p[1] == 'x')
5487 regs[i] = 0; /* 'x' */
5488 else
5489 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
5490 p += 2;
5491 }
5492
5493 {
5494 int i;
5495 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
5496 {
5497 struct packet_reg *r = &rsa->regs[i];
5498 if (r->in_g_packet)
5499 {
5500 if (r->offset * 2 >= strlen (rs->buf))
5501 /* This shouldn't happen - we adjusted in_g_packet above. */
5502 internal_error (__FILE__, __LINE__,
5503 "unexpected end of 'g' packet reply");
5504 else if (rs->buf[r->offset * 2] == 'x')
5505 {
5506 gdb_assert (r->offset * 2 < strlen (rs->buf));
5507 /* The register isn't available, mark it as such (at
5508 the same time setting the value to zero). */
5509 regcache_raw_supply (regcache, r->regnum, NULL);
5510 }
5511 else
5512 regcache_raw_supply (regcache, r->regnum,
5513 regs + r->offset);
5514 }
5515 }
5516 }
5517 }
5518
5519 static void
5520 fetch_registers_using_g (struct regcache *regcache)
5521 {
5522 send_g_packet ();
5523 process_g_packet (regcache);
5524 }
5525
5526 static void
5527 remote_fetch_registers (struct target_ops *ops,
5528 struct regcache *regcache, int regnum)
5529 {
5530 struct remote_arch_state *rsa = get_remote_arch_state ();
5531 int i;
5532
5533 set_general_thread (inferior_ptid);
5534
5535 if (regnum >= 0)
5536 {
5537 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
5538 gdb_assert (reg != NULL);
5539
5540 /* If this register might be in the 'g' packet, try that first -
5541 we are likely to read more than one register. If this is the
5542 first 'g' packet, we might be overly optimistic about its
5543 contents, so fall back to 'p'. */
5544 if (reg->in_g_packet)
5545 {
5546 fetch_registers_using_g (regcache);
5547 if (reg->in_g_packet)
5548 return;
5549 }
5550
5551 if (fetch_register_using_p (regcache, reg))
5552 return;
5553
5554 /* This register is not available. */
5555 regcache_raw_supply (regcache, reg->regnum, NULL);
5556
5557 return;
5558 }
5559
5560 fetch_registers_using_g (regcache);
5561
5562 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5563 if (!rsa->regs[i].in_g_packet)
5564 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
5565 {
5566 /* This register is not available. */
5567 regcache_raw_supply (regcache, i, NULL);
5568 }
5569 }
5570
5571 /* Prepare to store registers. Since we may send them all (using a
5572 'G' request), we have to read out the ones we don't want to change
5573 first. */
5574
5575 static void
5576 remote_prepare_to_store (struct regcache *regcache)
5577 {
5578 struct remote_arch_state *rsa = get_remote_arch_state ();
5579 int i;
5580 gdb_byte buf[MAX_REGISTER_SIZE];
5581
5582 /* Make sure the entire registers array is valid. */
5583 switch (remote_protocol_packets[PACKET_P].support)
5584 {
5585 case PACKET_DISABLE:
5586 case PACKET_SUPPORT_UNKNOWN:
5587 /* Make sure all the necessary registers are cached. */
5588 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5589 if (rsa->regs[i].in_g_packet)
5590 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5591 break;
5592 case PACKET_ENABLE:
5593 break;
5594 }
5595 }
5596
5597 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
5598 packet was not recognized. */
5599
5600 static int
5601 store_register_using_P (const struct regcache *regcache,
5602 struct packet_reg *reg)
5603 {
5604 struct gdbarch *gdbarch = get_regcache_arch (regcache);
5605 struct remote_state *rs = get_remote_state ();
5606 /* Try storing a single register. */
5607 char *buf = rs->buf;
5608 gdb_byte regp[MAX_REGISTER_SIZE];
5609 char *p;
5610
5611 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
5612 return 0;
5613
5614 if (reg->pnum == -1)
5615 return 0;
5616
5617 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5618 p = buf + strlen (buf);
5619 regcache_raw_collect (regcache, reg->regnum, regp);
5620 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
5621 putpkt (rs->buf);
5622 getpkt (&rs->buf, &rs->buf_size, 0);
5623
5624 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
5625 {
5626 case PACKET_OK:
5627 return 1;
5628 case PACKET_ERROR:
5629 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
5630 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
5631 case PACKET_UNKNOWN:
5632 return 0;
5633 default:
5634 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
5635 }
5636 }
5637
5638 /* Store register REGNUM, or all registers if REGNUM == -1, from the
5639 contents of the register cache buffer. FIXME: ignores errors. */
5640
5641 static void
5642 store_registers_using_G (const struct regcache *regcache)
5643 {
5644 struct remote_state *rs = get_remote_state ();
5645 struct remote_arch_state *rsa = get_remote_arch_state ();
5646 gdb_byte *regs;
5647 char *p;
5648
5649 /* Extract all the registers in the regcache copying them into a
5650 local buffer. */
5651 {
5652 int i;
5653 regs = alloca (rsa->sizeof_g_packet);
5654 memset (regs, 0, rsa->sizeof_g_packet);
5655 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5656 {
5657 struct packet_reg *r = &rsa->regs[i];
5658 if (r->in_g_packet)
5659 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
5660 }
5661 }
5662
5663 /* Command describes registers byte by byte,
5664 each byte encoded as two hex characters. */
5665 p = rs->buf;
5666 *p++ = 'G';
5667 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
5668 updated. */
5669 bin2hex (regs, p, rsa->sizeof_g_packet);
5670 putpkt (rs->buf);
5671 getpkt (&rs->buf, &rs->buf_size, 0);
5672 if (packet_check_result (rs->buf) == PACKET_ERROR)
5673 error (_("Could not write registers; remote failure reply '%s'"),
5674 rs->buf);
5675 }
5676
5677 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
5678 of the register cache buffer. FIXME: ignores errors. */
5679
5680 static void
5681 remote_store_registers (struct target_ops *ops,
5682 struct regcache *regcache, int regnum)
5683 {
5684 struct remote_arch_state *rsa = get_remote_arch_state ();
5685 int i;
5686
5687 set_general_thread (inferior_ptid);
5688
5689 if (regnum >= 0)
5690 {
5691 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
5692 gdb_assert (reg != NULL);
5693
5694 /* Always prefer to store registers using the 'P' packet if
5695 possible; we often change only a small number of registers.
5696 Sometimes we change a larger number; we'd need help from a
5697 higher layer to know to use 'G'. */
5698 if (store_register_using_P (regcache, reg))
5699 return;
5700
5701 /* For now, don't complain if we have no way to write the
5702 register. GDB loses track of unavailable registers too
5703 easily. Some day, this may be an error. We don't have
5704 any way to read the register, either... */
5705 if (!reg->in_g_packet)
5706 return;
5707
5708 store_registers_using_G (regcache);
5709 return;
5710 }
5711
5712 store_registers_using_G (regcache);
5713
5714 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5715 if (!rsa->regs[i].in_g_packet)
5716 if (!store_register_using_P (regcache, &rsa->regs[i]))
5717 /* See above for why we do not issue an error here. */
5718 continue;
5719 }
5720 \f
5721
5722 /* Return the number of hex digits in num. */
5723
5724 static int
5725 hexnumlen (ULONGEST num)
5726 {
5727 int i;
5728
5729 for (i = 0; num != 0; i++)
5730 num >>= 4;
5731
5732 return max (i, 1);
5733 }
5734
5735 /* Set BUF to the minimum number of hex digits representing NUM. */
5736
5737 static int
5738 hexnumstr (char *buf, ULONGEST num)
5739 {
5740 int len = hexnumlen (num);
5741 return hexnumnstr (buf, num, len);
5742 }
5743
5744
5745 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
5746
5747 static int
5748 hexnumnstr (char *buf, ULONGEST num, int width)
5749 {
5750 int i;
5751
5752 buf[width] = '\0';
5753
5754 for (i = width - 1; i >= 0; i--)
5755 {
5756 buf[i] = "0123456789abcdef"[(num & 0xf)];
5757 num >>= 4;
5758 }
5759
5760 return width;
5761 }
5762
5763 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
5764
5765 static CORE_ADDR
5766 remote_address_masked (CORE_ADDR addr)
5767 {
5768 int address_size = remote_address_size;
5769 /* If "remoteaddresssize" was not set, default to target address size. */
5770 if (!address_size)
5771 address_size = gdbarch_addr_bit (target_gdbarch);
5772
5773 if (address_size > 0
5774 && address_size < (sizeof (ULONGEST) * 8))
5775 {
5776 /* Only create a mask when that mask can safely be constructed
5777 in a ULONGEST variable. */
5778 ULONGEST mask = 1;
5779 mask = (mask << address_size) - 1;
5780 addr &= mask;
5781 }
5782 return addr;
5783 }
5784
5785 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
5786 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
5787 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
5788 (which may be more than *OUT_LEN due to escape characters). The
5789 total number of bytes in the output buffer will be at most
5790 OUT_MAXLEN. */
5791
5792 static int
5793 remote_escape_output (const gdb_byte *buffer, int len,
5794 gdb_byte *out_buf, int *out_len,
5795 int out_maxlen)
5796 {
5797 int input_index, output_index;
5798
5799 output_index = 0;
5800 for (input_index = 0; input_index < len; input_index++)
5801 {
5802 gdb_byte b = buffer[input_index];
5803
5804 if (b == '$' || b == '#' || b == '}')
5805 {
5806 /* These must be escaped. */
5807 if (output_index + 2 > out_maxlen)
5808 break;
5809 out_buf[output_index++] = '}';
5810 out_buf[output_index++] = b ^ 0x20;
5811 }
5812 else
5813 {
5814 if (output_index + 1 > out_maxlen)
5815 break;
5816 out_buf[output_index++] = b;
5817 }
5818 }
5819
5820 *out_len = input_index;
5821 return output_index;
5822 }
5823
5824 /* Convert BUFFER, escaped data LEN bytes long, into binary data
5825 in OUT_BUF. Return the number of bytes written to OUT_BUF.
5826 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
5827
5828 This function reverses remote_escape_output. It allows more
5829 escaped characters than that function does, in particular because
5830 '*' must be escaped to avoid the run-length encoding processing
5831 in reading packets. */
5832
5833 static int
5834 remote_unescape_input (const gdb_byte *buffer, int len,
5835 gdb_byte *out_buf, int out_maxlen)
5836 {
5837 int input_index, output_index;
5838 int escaped;
5839
5840 output_index = 0;
5841 escaped = 0;
5842 for (input_index = 0; input_index < len; input_index++)
5843 {
5844 gdb_byte b = buffer[input_index];
5845
5846 if (output_index + 1 > out_maxlen)
5847 {
5848 warning (_("Received too much data from remote target;"
5849 " ignoring overflow."));
5850 return output_index;
5851 }
5852
5853 if (escaped)
5854 {
5855 out_buf[output_index++] = b ^ 0x20;
5856 escaped = 0;
5857 }
5858 else if (b == '}')
5859 escaped = 1;
5860 else
5861 out_buf[output_index++] = b;
5862 }
5863
5864 if (escaped)
5865 error (_("Unmatched escape character in target response."));
5866
5867 return output_index;
5868 }
5869
5870 /* Determine whether the remote target supports binary downloading.
5871 This is accomplished by sending a no-op memory write of zero length
5872 to the target at the specified address. It does not suffice to send
5873 the whole packet, since many stubs strip the eighth bit and
5874 subsequently compute a wrong checksum, which causes real havoc with
5875 remote_write_bytes.
5876
5877 NOTE: This can still lose if the serial line is not eight-bit
5878 clean. In cases like this, the user should clear "remote
5879 X-packet". */
5880
5881 static void
5882 check_binary_download (CORE_ADDR addr)
5883 {
5884 struct remote_state *rs = get_remote_state ();
5885
5886 switch (remote_protocol_packets[PACKET_X].support)
5887 {
5888 case PACKET_DISABLE:
5889 break;
5890 case PACKET_ENABLE:
5891 break;
5892 case PACKET_SUPPORT_UNKNOWN:
5893 {
5894 char *p;
5895
5896 p = rs->buf;
5897 *p++ = 'X';
5898 p += hexnumstr (p, (ULONGEST) addr);
5899 *p++ = ',';
5900 p += hexnumstr (p, (ULONGEST) 0);
5901 *p++ = ':';
5902 *p = '\0';
5903
5904 putpkt_binary (rs->buf, (int) (p - rs->buf));
5905 getpkt (&rs->buf, &rs->buf_size, 0);
5906
5907 if (rs->buf[0] == '\0')
5908 {
5909 if (remote_debug)
5910 fprintf_unfiltered (gdb_stdlog,
5911 "binary downloading NOT suppported by target\n");
5912 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
5913 }
5914 else
5915 {
5916 if (remote_debug)
5917 fprintf_unfiltered (gdb_stdlog,
5918 "binary downloading suppported by target\n");
5919 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
5920 }
5921 break;
5922 }
5923 }
5924 }
5925
5926 /* Write memory data directly to the remote machine.
5927 This does not inform the data cache; the data cache uses this.
5928 HEADER is the starting part of the packet.
5929 MEMADDR is the address in the remote memory space.
5930 MYADDR is the address of the buffer in our space.
5931 LEN is the number of bytes.
5932 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
5933 should send data as binary ('X'), or hex-encoded ('M').
5934
5935 The function creates packet of the form
5936 <HEADER><ADDRESS>,<LENGTH>:<DATA>
5937
5938 where encoding of <DATA> is termined by PACKET_FORMAT.
5939
5940 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
5941 are omitted.
5942
5943 Returns the number of bytes transferred, or 0 (setting errno) for
5944 error. Only transfer a single packet. */
5945
5946 static int
5947 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
5948 const gdb_byte *myaddr, int len,
5949 char packet_format, int use_length)
5950 {
5951 struct remote_state *rs = get_remote_state ();
5952 char *p;
5953 char *plen = NULL;
5954 int plenlen = 0;
5955 int todo;
5956 int nr_bytes;
5957 int payload_size;
5958 int payload_length;
5959 int header_length;
5960
5961 if (packet_format != 'X' && packet_format != 'M')
5962 internal_error (__FILE__, __LINE__,
5963 "remote_write_bytes_aux: bad packet format");
5964
5965 if (len <= 0)
5966 return 0;
5967
5968 payload_size = get_memory_write_packet_size ();
5969
5970 /* The packet buffer will be large enough for the payload;
5971 get_memory_packet_size ensures this. */
5972 rs->buf[0] = '\0';
5973
5974 /* Compute the size of the actual payload by subtracting out the
5975 packet header and footer overhead: "$M<memaddr>,<len>:...#nn".
5976 */
5977 payload_size -= strlen ("$,:#NN");
5978 if (!use_length)
5979 /* The comma won't be used. */
5980 payload_size += 1;
5981 header_length = strlen (header);
5982 payload_size -= header_length;
5983 payload_size -= hexnumlen (memaddr);
5984
5985 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
5986
5987 strcat (rs->buf, header);
5988 p = rs->buf + strlen (header);
5989
5990 /* Compute a best guess of the number of bytes actually transfered. */
5991 if (packet_format == 'X')
5992 {
5993 /* Best guess at number of bytes that will fit. */
5994 todo = min (len, payload_size);
5995 if (use_length)
5996 payload_size -= hexnumlen (todo);
5997 todo = min (todo, payload_size);
5998 }
5999 else
6000 {
6001 /* Num bytes that will fit. */
6002 todo = min (len, payload_size / 2);
6003 if (use_length)
6004 payload_size -= hexnumlen (todo);
6005 todo = min (todo, payload_size / 2);
6006 }
6007
6008 if (todo <= 0)
6009 internal_error (__FILE__, __LINE__,
6010 _("minumum packet size too small to write data"));
6011
6012 /* If we already need another packet, then try to align the end
6013 of this packet to a useful boundary. */
6014 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6015 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6016
6017 /* Append "<memaddr>". */
6018 memaddr = remote_address_masked (memaddr);
6019 p += hexnumstr (p, (ULONGEST) memaddr);
6020
6021 if (use_length)
6022 {
6023 /* Append ",". */
6024 *p++ = ',';
6025
6026 /* Append <len>. Retain the location/size of <len>. It may need to
6027 be adjusted once the packet body has been created. */
6028 plen = p;
6029 plenlen = hexnumstr (p, (ULONGEST) todo);
6030 p += plenlen;
6031 }
6032
6033 /* Append ":". */
6034 *p++ = ':';
6035 *p = '\0';
6036
6037 /* Append the packet body. */
6038 if (packet_format == 'X')
6039 {
6040 /* Binary mode. Send target system values byte by byte, in
6041 increasing byte addresses. Only escape certain critical
6042 characters. */
6043 payload_length = remote_escape_output (myaddr, todo, p, &nr_bytes,
6044 payload_size);
6045
6046 /* If not all TODO bytes fit, then we'll need another packet. Make
6047 a second try to keep the end of the packet aligned. Don't do
6048 this if the packet is tiny. */
6049 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6050 {
6051 int new_nr_bytes;
6052
6053 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6054 - memaddr);
6055 if (new_nr_bytes != nr_bytes)
6056 payload_length = remote_escape_output (myaddr, new_nr_bytes,
6057 p, &nr_bytes,
6058 payload_size);
6059 }
6060
6061 p += payload_length;
6062 if (use_length && nr_bytes < todo)
6063 {
6064 /* Escape chars have filled up the buffer prematurely,
6065 and we have actually sent fewer bytes than planned.
6066 Fix-up the length field of the packet. Use the same
6067 number of characters as before. */
6068 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6069 *plen = ':'; /* overwrite \0 from hexnumnstr() */
6070 }
6071 }
6072 else
6073 {
6074 /* Normal mode: Send target system values byte by byte, in
6075 increasing byte addresses. Each byte is encoded as a two hex
6076 value. */
6077 nr_bytes = bin2hex (myaddr, p, todo);
6078 p += 2 * nr_bytes;
6079 }
6080
6081 putpkt_binary (rs->buf, (int) (p - rs->buf));
6082 getpkt (&rs->buf, &rs->buf_size, 0);
6083
6084 if (rs->buf[0] == 'E')
6085 {
6086 /* There is no correspondance between what the remote protocol
6087 uses for errors and errno codes. We would like a cleaner way
6088 of representing errors (big enough to include errno codes,
6089 bfd_error codes, and others). But for now just return EIO. */
6090 errno = EIO;
6091 return 0;
6092 }
6093
6094 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6095 fewer bytes than we'd planned. */
6096 return nr_bytes;
6097 }
6098
6099 /* Write memory data directly to the remote machine.
6100 This does not inform the data cache; the data cache uses this.
6101 MEMADDR is the address in the remote memory space.
6102 MYADDR is the address of the buffer in our space.
6103 LEN is the number of bytes.
6104
6105 Returns number of bytes transferred, or 0 (setting errno) for
6106 error. Only transfer a single packet. */
6107
6108 int
6109 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
6110 {
6111 char *packet_format = 0;
6112
6113 /* Check whether the target supports binary download. */
6114 check_binary_download (memaddr);
6115
6116 switch (remote_protocol_packets[PACKET_X].support)
6117 {
6118 case PACKET_ENABLE:
6119 packet_format = "X";
6120 break;
6121 case PACKET_DISABLE:
6122 packet_format = "M";
6123 break;
6124 case PACKET_SUPPORT_UNKNOWN:
6125 internal_error (__FILE__, __LINE__,
6126 _("remote_write_bytes: bad internal state"));
6127 default:
6128 internal_error (__FILE__, __LINE__, _("bad switch"));
6129 }
6130
6131 return remote_write_bytes_aux (packet_format,
6132 memaddr, myaddr, len, packet_format[0], 1);
6133 }
6134
6135 /* Read memory data directly from the remote machine.
6136 This does not use the data cache; the data cache uses this.
6137 MEMADDR is the address in the remote memory space.
6138 MYADDR is the address of the buffer in our space.
6139 LEN is the number of bytes.
6140
6141 Returns number of bytes transferred, or 0 for error. */
6142
6143 /* NOTE: cagney/1999-10-18: This function (and its siblings in other
6144 remote targets) shouldn't attempt to read the entire buffer.
6145 Instead it should read a single packet worth of data and then
6146 return the byte size of that packet to the caller. The caller (its
6147 caller and its callers caller ;-) already contains code for
6148 handling partial reads. */
6149
6150 int
6151 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
6152 {
6153 struct remote_state *rs = get_remote_state ();
6154 int max_buf_size; /* Max size of packet output buffer. */
6155 int origlen;
6156
6157 if (len <= 0)
6158 return 0;
6159
6160 max_buf_size = get_memory_read_packet_size ();
6161 /* The packet buffer will be large enough for the payload;
6162 get_memory_packet_size ensures this. */
6163
6164 origlen = len;
6165 while (len > 0)
6166 {
6167 char *p;
6168 int todo;
6169 int i;
6170
6171 todo = min (len, max_buf_size / 2); /* num bytes that will fit */
6172
6173 /* construct "m"<memaddr>","<len>" */
6174 /* sprintf (rs->buf, "m%lx,%x", (unsigned long) memaddr, todo); */
6175 memaddr = remote_address_masked (memaddr);
6176 p = rs->buf;
6177 *p++ = 'm';
6178 p += hexnumstr (p, (ULONGEST) memaddr);
6179 *p++ = ',';
6180 p += hexnumstr (p, (ULONGEST) todo);
6181 *p = '\0';
6182
6183 putpkt (rs->buf);
6184 getpkt (&rs->buf, &rs->buf_size, 0);
6185
6186 if (rs->buf[0] == 'E'
6187 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6188 && rs->buf[3] == '\0')
6189 {
6190 /* There is no correspondance between what the remote
6191 protocol uses for errors and errno codes. We would like
6192 a cleaner way of representing errors (big enough to
6193 include errno codes, bfd_error codes, and others). But
6194 for now just return EIO. */
6195 errno = EIO;
6196 return 0;
6197 }
6198
6199 /* Reply describes memory byte by byte,
6200 each byte encoded as two hex characters. */
6201
6202 p = rs->buf;
6203 if ((i = hex2bin (p, myaddr, todo)) < todo)
6204 {
6205 /* Reply is short. This means that we were able to read
6206 only part of what we wanted to. */
6207 return i + (origlen - len);
6208 }
6209 myaddr += todo;
6210 memaddr += todo;
6211 len -= todo;
6212 }
6213 return origlen;
6214 }
6215 \f
6216
6217 /* Remote notification handler. */
6218
6219 static void
6220 handle_notification (char *buf, size_t length)
6221 {
6222 if (strncmp (buf, "Stop:", 5) == 0)
6223 {
6224 if (pending_stop_reply)
6225 {
6226 /* We've already parsed the in-flight stop-reply, but the
6227 stub for some reason thought we didn't, possibly due to
6228 timeout on its side. Just ignore it. */
6229 if (remote_debug)
6230 fprintf_unfiltered (gdb_stdlog, "ignoring resent notification\n");
6231 }
6232 else
6233 {
6234 struct cleanup *old_chain;
6235 struct stop_reply *reply = stop_reply_xmalloc ();
6236 old_chain = make_cleanup (do_stop_reply_xfree, reply);
6237
6238 remote_parse_stop_reply (buf + 5, reply);
6239
6240 discard_cleanups (old_chain);
6241
6242 /* Be careful to only set it after parsing, since an error
6243 may be thrown then. */
6244 pending_stop_reply = reply;
6245
6246 /* Notify the event loop there's a stop reply to acknowledge
6247 and that there may be more events to fetch. */
6248 mark_async_event_handler (remote_async_get_pending_events_token);
6249
6250 if (remote_debug)
6251 fprintf_unfiltered (gdb_stdlog, "stop notification captured\n");
6252 }
6253 }
6254 else
6255 /* We ignore notifications we don't recognize, for compatibility
6256 with newer stubs. */
6257 ;
6258 }
6259
6260 \f
6261 /* Read or write LEN bytes from inferior memory at MEMADDR,
6262 transferring to or from debugger address BUFFER. Write to inferior
6263 if SHOULD_WRITE is nonzero. Returns length of data written or
6264 read; 0 for error. TARGET is unused. */
6265
6266 static int
6267 remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
6268 int should_write, struct mem_attrib *attrib,
6269 struct target_ops *target)
6270 {
6271 int res;
6272
6273 set_general_thread (inferior_ptid);
6274
6275 if (should_write)
6276 res = remote_write_bytes (mem_addr, buffer, mem_len);
6277 else
6278 res = remote_read_bytes (mem_addr, buffer, mem_len);
6279
6280 return res;
6281 }
6282
6283 /* Sends a packet with content determined by the printf format string
6284 FORMAT and the remaining arguments, then gets the reply. Returns
6285 whether the packet was a success, a failure, or unknown. */
6286
6287 static enum packet_result
6288 remote_send_printf (const char *format, ...)
6289 {
6290 struct remote_state *rs = get_remote_state ();
6291 int max_size = get_remote_packet_size ();
6292
6293 va_list ap;
6294 va_start (ap, format);
6295
6296 rs->buf[0] = '\0';
6297 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
6298 internal_error (__FILE__, __LINE__, "Too long remote packet.");
6299
6300 if (putpkt (rs->buf) < 0)
6301 error (_("Communication problem with target."));
6302
6303 rs->buf[0] = '\0';
6304 getpkt (&rs->buf, &rs->buf_size, 0);
6305
6306 return packet_check_result (rs->buf);
6307 }
6308
6309 static void
6310 restore_remote_timeout (void *p)
6311 {
6312 int value = *(int *)p;
6313 remote_timeout = value;
6314 }
6315
6316 /* Flash writing can take quite some time. We'll set
6317 effectively infinite timeout for flash operations.
6318 In future, we'll need to decide on a better approach. */
6319 static const int remote_flash_timeout = 1000;
6320
6321 static void
6322 remote_flash_erase (struct target_ops *ops,
6323 ULONGEST address, LONGEST length)
6324 {
6325 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
6326 int saved_remote_timeout = remote_timeout;
6327 enum packet_result ret;
6328
6329 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6330 &saved_remote_timeout);
6331 remote_timeout = remote_flash_timeout;
6332
6333 ret = remote_send_printf ("vFlashErase:%s,%s",
6334 phex (address, addr_size),
6335 phex (length, 4));
6336 switch (ret)
6337 {
6338 case PACKET_UNKNOWN:
6339 error (_("Remote target does not support flash erase"));
6340 case PACKET_ERROR:
6341 error (_("Error erasing flash with vFlashErase packet"));
6342 default:
6343 break;
6344 }
6345
6346 do_cleanups (back_to);
6347 }
6348
6349 static LONGEST
6350 remote_flash_write (struct target_ops *ops,
6351 ULONGEST address, LONGEST length,
6352 const gdb_byte *data)
6353 {
6354 int saved_remote_timeout = remote_timeout;
6355 int ret;
6356 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6357 &saved_remote_timeout);
6358
6359 remote_timeout = remote_flash_timeout;
6360 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
6361 do_cleanups (back_to);
6362
6363 return ret;
6364 }
6365
6366 static void
6367 remote_flash_done (struct target_ops *ops)
6368 {
6369 int saved_remote_timeout = remote_timeout;
6370 int ret;
6371 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6372 &saved_remote_timeout);
6373
6374 remote_timeout = remote_flash_timeout;
6375 ret = remote_send_printf ("vFlashDone");
6376 do_cleanups (back_to);
6377
6378 switch (ret)
6379 {
6380 case PACKET_UNKNOWN:
6381 error (_("Remote target does not support vFlashDone"));
6382 case PACKET_ERROR:
6383 error (_("Error finishing flash operation"));
6384 default:
6385 break;
6386 }
6387 }
6388
6389 static void
6390 remote_files_info (struct target_ops *ignore)
6391 {
6392 puts_filtered ("Debugging a target over a serial line.\n");
6393 }
6394 \f
6395 /* Stuff for dealing with the packets which are part of this protocol.
6396 See comment at top of file for details. */
6397
6398 /* Read a single character from the remote end. */
6399
6400 static int
6401 readchar (int timeout)
6402 {
6403 int ch;
6404
6405 ch = serial_readchar (remote_desc, timeout);
6406
6407 if (ch >= 0)
6408 return ch;
6409
6410 switch ((enum serial_rc) ch)
6411 {
6412 case SERIAL_EOF:
6413 pop_target ();
6414 error (_("Remote connection closed"));
6415 /* no return */
6416 case SERIAL_ERROR:
6417 perror_with_name (_("Remote communication error"));
6418 /* no return */
6419 case SERIAL_TIMEOUT:
6420 break;
6421 }
6422 return ch;
6423 }
6424
6425 /* Send the command in *BUF to the remote machine, and read the reply
6426 into *BUF. Report an error if we get an error reply. Resize
6427 *BUF using xrealloc if necessary to hold the result, and update
6428 *SIZEOF_BUF. */
6429
6430 static void
6431 remote_send (char **buf,
6432 long *sizeof_buf)
6433 {
6434 putpkt (*buf);
6435 getpkt (buf, sizeof_buf, 0);
6436
6437 if ((*buf)[0] == 'E')
6438 error (_("Remote failure reply: %s"), *buf);
6439 }
6440
6441 /* Return a pointer to an xmalloc'ed string representing an escaped
6442 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
6443 etc. The caller is responsible for releasing the returned
6444 memory. */
6445
6446 static char *
6447 escape_buffer (const char *buf, int n)
6448 {
6449 struct cleanup *old_chain;
6450 struct ui_file *stb;
6451 char *str;
6452
6453 stb = mem_fileopen ();
6454 old_chain = make_cleanup_ui_file_delete (stb);
6455
6456 fputstrn_unfiltered (buf, n, 0, stb);
6457 str = ui_file_xstrdup (stb, NULL);
6458 do_cleanups (old_chain);
6459 return str;
6460 }
6461
6462 /* Display a null-terminated packet on stdout, for debugging, using C
6463 string notation. */
6464
6465 static void
6466 print_packet (char *buf)
6467 {
6468 puts_filtered ("\"");
6469 fputstr_filtered (buf, '"', gdb_stdout);
6470 puts_filtered ("\"");
6471 }
6472
6473 int
6474 putpkt (char *buf)
6475 {
6476 return putpkt_binary (buf, strlen (buf));
6477 }
6478
6479 /* Send a packet to the remote machine, with error checking. The data
6480 of the packet is in BUF. The string in BUF can be at most
6481 get_remote_packet_size () - 5 to account for the $, # and checksum,
6482 and for a possible /0 if we are debugging (remote_debug) and want
6483 to print the sent packet as a string. */
6484
6485 static int
6486 putpkt_binary (char *buf, int cnt)
6487 {
6488 struct remote_state *rs = get_remote_state ();
6489 int i;
6490 unsigned char csum = 0;
6491 char *buf2 = alloca (cnt + 6);
6492
6493 int ch;
6494 int tcount = 0;
6495 char *p;
6496
6497 /* Catch cases like trying to read memory or listing threads while
6498 we're waiting for a stop reply. The remote server wouldn't be
6499 ready to handle this request, so we'd hang and timeout. We don't
6500 have to worry about this in synchronous mode, because in that
6501 case it's not possible to issue a command while the target is
6502 running. This is not a problem in non-stop mode, because in that
6503 case, the stub is always ready to process serial input. */
6504 if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
6505 error (_("Cannot execute this command while the target is running."));
6506
6507 /* We're sending out a new packet. Make sure we don't look at a
6508 stale cached response. */
6509 rs->cached_wait_status = 0;
6510
6511 /* Copy the packet into buffer BUF2, encapsulating it
6512 and giving it a checksum. */
6513
6514 p = buf2;
6515 *p++ = '$';
6516
6517 for (i = 0; i < cnt; i++)
6518 {
6519 csum += buf[i];
6520 *p++ = buf[i];
6521 }
6522 *p++ = '#';
6523 *p++ = tohex ((csum >> 4) & 0xf);
6524 *p++ = tohex (csum & 0xf);
6525
6526 /* Send it over and over until we get a positive ack. */
6527
6528 while (1)
6529 {
6530 int started_error_output = 0;
6531
6532 if (remote_debug)
6533 {
6534 struct cleanup *old_chain;
6535 char *str;
6536
6537 *p = '\0';
6538 str = escape_buffer (buf2, p - buf2);
6539 old_chain = make_cleanup (xfree, str);
6540 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
6541 gdb_flush (gdb_stdlog);
6542 do_cleanups (old_chain);
6543 }
6544 if (serial_write (remote_desc, buf2, p - buf2))
6545 perror_with_name (_("putpkt: write failed"));
6546
6547 /* If this is a no acks version of the remote protocol, send the
6548 packet and move on. */
6549 if (rs->noack_mode)
6550 break;
6551
6552 /* Read until either a timeout occurs (-2) or '+' is read.
6553 Handle any notification that arrives in the mean time. */
6554 while (1)
6555 {
6556 ch = readchar (remote_timeout);
6557
6558 if (remote_debug)
6559 {
6560 switch (ch)
6561 {
6562 case '+':
6563 case '-':
6564 case SERIAL_TIMEOUT:
6565 case '$':
6566 case '%':
6567 if (started_error_output)
6568 {
6569 putchar_unfiltered ('\n');
6570 started_error_output = 0;
6571 }
6572 }
6573 }
6574
6575 switch (ch)
6576 {
6577 case '+':
6578 if (remote_debug)
6579 fprintf_unfiltered (gdb_stdlog, "Ack\n");
6580 return 1;
6581 case '-':
6582 if (remote_debug)
6583 fprintf_unfiltered (gdb_stdlog, "Nak\n");
6584 case SERIAL_TIMEOUT:
6585 tcount++;
6586 if (tcount > 3)
6587 return 0;
6588 break; /* Retransmit buffer. */
6589 case '$':
6590 {
6591 if (remote_debug)
6592 fprintf_unfiltered (gdb_stdlog,
6593 "Packet instead of Ack, ignoring it\n");
6594 /* It's probably an old response sent because an ACK
6595 was lost. Gobble up the packet and ack it so it
6596 doesn't get retransmitted when we resend this
6597 packet. */
6598 skip_frame ();
6599 serial_write (remote_desc, "+", 1);
6600 continue; /* Now, go look for +. */
6601 }
6602
6603 case '%':
6604 {
6605 int val;
6606
6607 /* If we got a notification, handle it, and go back to looking
6608 for an ack. */
6609 /* We've found the start of a notification. Now
6610 collect the data. */
6611 val = read_frame (&rs->buf, &rs->buf_size);
6612 if (val >= 0)
6613 {
6614 if (remote_debug)
6615 {
6616 struct cleanup *old_chain;
6617 char *str;
6618
6619 str = escape_buffer (rs->buf, val);
6620 old_chain = make_cleanup (xfree, str);
6621 fprintf_unfiltered (gdb_stdlog,
6622 " Notification received: %s\n",
6623 str);
6624 do_cleanups (old_chain);
6625 }
6626 handle_notification (rs->buf, val);
6627 /* We're in sync now, rewait for the ack. */
6628 tcount = 0;
6629 }
6630 else
6631 {
6632 if (remote_debug)
6633 {
6634 if (!started_error_output)
6635 {
6636 started_error_output = 1;
6637 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
6638 }
6639 fputc_unfiltered (ch & 0177, gdb_stdlog);
6640 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
6641 }
6642 }
6643 continue;
6644 }
6645 /* fall-through */
6646 default:
6647 if (remote_debug)
6648 {
6649 if (!started_error_output)
6650 {
6651 started_error_output = 1;
6652 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
6653 }
6654 fputc_unfiltered (ch & 0177, gdb_stdlog);
6655 }
6656 continue;
6657 }
6658 break; /* Here to retransmit. */
6659 }
6660
6661 #if 0
6662 /* This is wrong. If doing a long backtrace, the user should be
6663 able to get out next time we call QUIT, without anything as
6664 violent as interrupt_query. If we want to provide a way out of
6665 here without getting to the next QUIT, it should be based on
6666 hitting ^C twice as in remote_wait. */
6667 if (quit_flag)
6668 {
6669 quit_flag = 0;
6670 interrupt_query ();
6671 }
6672 #endif
6673 }
6674 return 0;
6675 }
6676
6677 /* Come here after finding the start of a frame when we expected an
6678 ack. Do our best to discard the rest of this packet. */
6679
6680 static void
6681 skip_frame (void)
6682 {
6683 int c;
6684
6685 while (1)
6686 {
6687 c = readchar (remote_timeout);
6688 switch (c)
6689 {
6690 case SERIAL_TIMEOUT:
6691 /* Nothing we can do. */
6692 return;
6693 case '#':
6694 /* Discard the two bytes of checksum and stop. */
6695 c = readchar (remote_timeout);
6696 if (c >= 0)
6697 c = readchar (remote_timeout);
6698
6699 return;
6700 case '*': /* Run length encoding. */
6701 /* Discard the repeat count. */
6702 c = readchar (remote_timeout);
6703 if (c < 0)
6704 return;
6705 break;
6706 default:
6707 /* A regular character. */
6708 break;
6709 }
6710 }
6711 }
6712
6713 /* Come here after finding the start of the frame. Collect the rest
6714 into *BUF, verifying the checksum, length, and handling run-length
6715 compression. NUL terminate the buffer. If there is not enough room,
6716 expand *BUF using xrealloc.
6717
6718 Returns -1 on error, number of characters in buffer (ignoring the
6719 trailing NULL) on success. (could be extended to return one of the
6720 SERIAL status indications). */
6721
6722 static long
6723 read_frame (char **buf_p,
6724 long *sizeof_buf)
6725 {
6726 unsigned char csum;
6727 long bc;
6728 int c;
6729 char *buf = *buf_p;
6730 struct remote_state *rs = get_remote_state ();
6731
6732 csum = 0;
6733 bc = 0;
6734
6735 while (1)
6736 {
6737 c = readchar (remote_timeout);
6738 switch (c)
6739 {
6740 case SERIAL_TIMEOUT:
6741 if (remote_debug)
6742 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
6743 return -1;
6744 case '$':
6745 if (remote_debug)
6746 fputs_filtered ("Saw new packet start in middle of old one\n",
6747 gdb_stdlog);
6748 return -1; /* Start a new packet, count retries. */
6749 case '#':
6750 {
6751 unsigned char pktcsum;
6752 int check_0 = 0;
6753 int check_1 = 0;
6754
6755 buf[bc] = '\0';
6756
6757 check_0 = readchar (remote_timeout);
6758 if (check_0 >= 0)
6759 check_1 = readchar (remote_timeout);
6760
6761 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
6762 {
6763 if (remote_debug)
6764 fputs_filtered ("Timeout in checksum, retrying\n",
6765 gdb_stdlog);
6766 return -1;
6767 }
6768 else if (check_0 < 0 || check_1 < 0)
6769 {
6770 if (remote_debug)
6771 fputs_filtered ("Communication error in checksum\n",
6772 gdb_stdlog);
6773 return -1;
6774 }
6775
6776 /* Don't recompute the checksum; with no ack packets we
6777 don't have any way to indicate a packet retransmission
6778 is necessary. */
6779 if (rs->noack_mode)
6780 return bc;
6781
6782 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
6783 if (csum == pktcsum)
6784 return bc;
6785
6786 if (remote_debug)
6787 {
6788 struct cleanup *old_chain;
6789 char *str;
6790
6791 str = escape_buffer (buf, bc);
6792 old_chain = make_cleanup (xfree, str);
6793 fprintf_unfiltered (gdb_stdlog,
6794 "\
6795 Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
6796 pktcsum, csum, str);
6797 do_cleanups (old_chain);
6798 }
6799 /* Number of characters in buffer ignoring trailing
6800 NULL. */
6801 return -1;
6802 }
6803 case '*': /* Run length encoding. */
6804 {
6805 int repeat;
6806 csum += c;
6807
6808 c = readchar (remote_timeout);
6809 csum += c;
6810 repeat = c - ' ' + 3; /* Compute repeat count. */
6811
6812 /* The character before ``*'' is repeated. */
6813
6814 if (repeat > 0 && repeat <= 255 && bc > 0)
6815 {
6816 if (bc + repeat - 1 >= *sizeof_buf - 1)
6817 {
6818 /* Make some more room in the buffer. */
6819 *sizeof_buf += repeat;
6820 *buf_p = xrealloc (*buf_p, *sizeof_buf);
6821 buf = *buf_p;
6822 }
6823
6824 memset (&buf[bc], buf[bc - 1], repeat);
6825 bc += repeat;
6826 continue;
6827 }
6828
6829 buf[bc] = '\0';
6830 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
6831 return -1;
6832 }
6833 default:
6834 if (bc >= *sizeof_buf - 1)
6835 {
6836 /* Make some more room in the buffer. */
6837 *sizeof_buf *= 2;
6838 *buf_p = xrealloc (*buf_p, *sizeof_buf);
6839 buf = *buf_p;
6840 }
6841
6842 buf[bc++] = c;
6843 csum += c;
6844 continue;
6845 }
6846 }
6847 }
6848
6849 /* Read a packet from the remote machine, with error checking, and
6850 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
6851 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
6852 rather than timing out; this is used (in synchronous mode) to wait
6853 for a target that is is executing user code to stop. */
6854 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
6855 don't have to change all the calls to getpkt to deal with the
6856 return value, because at the moment I don't know what the right
6857 thing to do it for those. */
6858 void
6859 getpkt (char **buf,
6860 long *sizeof_buf,
6861 int forever)
6862 {
6863 int timed_out;
6864
6865 timed_out = getpkt_sane (buf, sizeof_buf, forever);
6866 }
6867
6868
6869 /* Read a packet from the remote machine, with error checking, and
6870 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
6871 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
6872 rather than timing out; this is used (in synchronous mode) to wait
6873 for a target that is is executing user code to stop. If FOREVER ==
6874 0, this function is allowed to time out gracefully and return an
6875 indication of this to the caller. Otherwise return the number of
6876 bytes read. If EXPECTING_NOTIF, consider receiving a notification
6877 enough reason to return to the caller. */
6878
6879 static int
6880 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
6881 int expecting_notif)
6882 {
6883 struct remote_state *rs = get_remote_state ();
6884 int c;
6885 int tries;
6886 int timeout;
6887 int val = -1;
6888
6889 /* We're reading a new response. Make sure we don't look at a
6890 previously cached response. */
6891 rs->cached_wait_status = 0;
6892
6893 strcpy (*buf, "timeout");
6894
6895 if (forever)
6896 timeout = watchdog > 0 ? watchdog : -1;
6897 else if (expecting_notif)
6898 timeout = 0; /* There should already be a char in the buffer. If
6899 not, bail out. */
6900 else
6901 timeout = remote_timeout;
6902
6903 #define MAX_TRIES 3
6904
6905 /* Process any number of notifications, and then return when
6906 we get a packet. */
6907 for (;;)
6908 {
6909 /* If we get a timeout or bad checksm, retry up to MAX_TRIES
6910 times. */
6911 for (tries = 1; tries <= MAX_TRIES; tries++)
6912 {
6913 /* This can loop forever if the remote side sends us
6914 characters continuously, but if it pauses, we'll get
6915 SERIAL_TIMEOUT from readchar because of timeout. Then
6916 we'll count that as a retry.
6917
6918 Note that even when forever is set, we will only wait
6919 forever prior to the start of a packet. After that, we
6920 expect characters to arrive at a brisk pace. They should
6921 show up within remote_timeout intervals. */
6922 do
6923 c = readchar (timeout);
6924 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
6925
6926 if (c == SERIAL_TIMEOUT)
6927 {
6928 if (expecting_notif)
6929 return -1; /* Don't complain, it's normal to not get
6930 anything in this case. */
6931
6932 if (forever) /* Watchdog went off? Kill the target. */
6933 {
6934 QUIT;
6935 pop_target ();
6936 error (_("Watchdog timeout has expired. Target detached."));
6937 }
6938 if (remote_debug)
6939 fputs_filtered ("Timed out.\n", gdb_stdlog);
6940 }
6941 else
6942 {
6943 /* We've found the start of a packet or notification.
6944 Now collect the data. */
6945 val = read_frame (buf, sizeof_buf);
6946 if (val >= 0)
6947 break;
6948 }
6949
6950 serial_write (remote_desc, "-", 1);
6951 }
6952
6953 if (tries > MAX_TRIES)
6954 {
6955 /* We have tried hard enough, and just can't receive the
6956 packet/notification. Give up. */
6957 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
6958
6959 /* Skip the ack char if we're in no-ack mode. */
6960 if (!rs->noack_mode)
6961 serial_write (remote_desc, "+", 1);
6962 return -1;
6963 }
6964
6965 /* If we got an ordinary packet, return that to our caller. */
6966 if (c == '$')
6967 {
6968 if (remote_debug)
6969 {
6970 struct cleanup *old_chain;
6971 char *str;
6972
6973 str = escape_buffer (*buf, val);
6974 old_chain = make_cleanup (xfree, str);
6975 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
6976 do_cleanups (old_chain);
6977 }
6978
6979 /* Skip the ack char if we're in no-ack mode. */
6980 if (!rs->noack_mode)
6981 serial_write (remote_desc, "+", 1);
6982 return val;
6983 }
6984
6985 /* If we got a notification, handle it, and go back to looking
6986 for a packet. */
6987 else
6988 {
6989 gdb_assert (c == '%');
6990
6991 if (remote_debug)
6992 {
6993 struct cleanup *old_chain;
6994 char *str;
6995
6996 str = escape_buffer (*buf, val);
6997 old_chain = make_cleanup (xfree, str);
6998 fprintf_unfiltered (gdb_stdlog,
6999 " Notification received: %s\n",
7000 str);
7001 do_cleanups (old_chain);
7002 }
7003
7004 handle_notification (*buf, val);
7005
7006 /* Notifications require no acknowledgement. */
7007
7008 if (expecting_notif)
7009 return -1;
7010 }
7011 }
7012 }
7013
7014 static int
7015 getpkt_sane (char **buf, long *sizeof_buf, int forever)
7016 {
7017 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0);
7018 }
7019
7020 static int
7021 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever)
7022 {
7023 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1);
7024 }
7025
7026 \f
7027 static void
7028 remote_kill (struct target_ops *ops)
7029 {
7030 /* Use catch_errors so the user can quit from gdb even when we
7031 aren't on speaking terms with the remote system. */
7032 catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
7033
7034 /* Don't wait for it to die. I'm not really sure it matters whether
7035 we do or not. For the existing stubs, kill is a noop. */
7036 target_mourn_inferior ();
7037 }
7038
7039 static int
7040 remote_vkill (int pid, struct remote_state *rs)
7041 {
7042 if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7043 return -1;
7044
7045 /* Tell the remote target to detach. */
7046 sprintf (rs->buf, "vKill;%x", pid);
7047 putpkt (rs->buf);
7048 getpkt (&rs->buf, &rs->buf_size, 0);
7049
7050 if (packet_ok (rs->buf,
7051 &remote_protocol_packets[PACKET_vKill]) == PACKET_OK)
7052 return 0;
7053 else if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7054 return -1;
7055 else
7056 return 1;
7057 }
7058
7059 static void
7060 extended_remote_kill (struct target_ops *ops)
7061 {
7062 int res;
7063 int pid = ptid_get_pid (inferior_ptid);
7064 struct remote_state *rs = get_remote_state ();
7065
7066 res = remote_vkill (pid, rs);
7067 if (res == -1 && !remote_multi_process_p (rs))
7068 {
7069 /* Don't try 'k' on a multi-process aware stub -- it has no way
7070 to specify the pid. */
7071
7072 putpkt ("k");
7073 #if 0
7074 getpkt (&rs->buf, &rs->buf_size, 0);
7075 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7076 res = 1;
7077 #else
7078 /* Don't wait for it to die. I'm not really sure it matters whether
7079 we do or not. For the existing stubs, kill is a noop. */
7080 res = 0;
7081 #endif
7082 }
7083
7084 if (res != 0)
7085 error (_("Can't kill process"));
7086
7087 target_mourn_inferior ();
7088 }
7089
7090 static void
7091 remote_mourn (struct target_ops *ops)
7092 {
7093 remote_mourn_1 (ops);
7094 }
7095
7096 /* Worker function for remote_mourn. */
7097 static void
7098 remote_mourn_1 (struct target_ops *target)
7099 {
7100 unpush_target (target);
7101
7102 /* remote_close takes care of doing most of the clean up. */
7103 generic_mourn_inferior ();
7104 }
7105
7106 static void
7107 extended_remote_mourn_1 (struct target_ops *target)
7108 {
7109 struct remote_state *rs = get_remote_state ();
7110
7111 /* In case we got here due to an error, but we're going to stay
7112 connected. */
7113 rs->waiting_for_stop_reply = 0;
7114
7115 /* We're no longer interested in these events. */
7116 discard_pending_stop_replies (ptid_get_pid (inferior_ptid));
7117
7118 /* If the current general thread belonged to the process we just
7119 detached from or has exited, the remote side current general
7120 thread becomes undefined. Considering a case like this:
7121
7122 - We just got here due to a detach.
7123 - The process that we're detaching from happens to immediately
7124 report a global breakpoint being hit in non-stop mode, in the
7125 same thread we had selected before.
7126 - GDB attaches to this process again.
7127 - This event happens to be the next event we handle.
7128
7129 GDB would consider that the current general thread didn't need to
7130 be set on the stub side (with Hg), since for all it knew,
7131 GENERAL_THREAD hadn't changed.
7132
7133 Notice that although in all-stop mode, the remote server always
7134 sets the current thread to the thread reporting the stop event,
7135 that doesn't happen in non-stop mode; in non-stop, the stub *must
7136 not* change the current thread when reporting a breakpoint hit,
7137 due to the decoupling of event reporting and event handling.
7138
7139 To keep things simple, we always invalidate our notion of the
7140 current thread. */
7141 record_currthread (minus_one_ptid);
7142
7143 /* Unlike "target remote", we do not want to unpush the target; then
7144 the next time the user says "run", we won't be connected. */
7145
7146 /* Call common code to mark the inferior as not running. */
7147 generic_mourn_inferior ();
7148
7149 if (!have_inferiors ())
7150 {
7151 if (!remote_multi_process_p (rs))
7152 {
7153 /* Check whether the target is running now - some remote stubs
7154 automatically restart after kill. */
7155 putpkt ("?");
7156 getpkt (&rs->buf, &rs->buf_size, 0);
7157
7158 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7159 {
7160 /* Assume that the target has been restarted. Set inferior_ptid
7161 so that bits of core GDB realizes there's something here, e.g.,
7162 so that the user can say "kill" again. */
7163 inferior_ptid = magic_null_ptid;
7164 }
7165 }
7166 }
7167 }
7168
7169 static void
7170 extended_remote_mourn (struct target_ops *ops)
7171 {
7172 extended_remote_mourn_1 (ops);
7173 }
7174
7175 static int
7176 extended_remote_run (char *args)
7177 {
7178 struct remote_state *rs = get_remote_state ();
7179 int len;
7180
7181 /* If the user has disabled vRun support, or we have detected that
7182 support is not available, do not try it. */
7183 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7184 return -1;
7185
7186 strcpy (rs->buf, "vRun;");
7187 len = strlen (rs->buf);
7188
7189 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
7190 error (_("Remote file name too long for run packet"));
7191 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
7192
7193 gdb_assert (args != NULL);
7194 if (*args)
7195 {
7196 struct cleanup *back_to;
7197 int i;
7198 char **argv;
7199
7200 argv = gdb_buildargv (args);
7201 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
7202 for (i = 0; argv[i] != NULL; i++)
7203 {
7204 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
7205 error (_("Argument list too long for run packet"));
7206 rs->buf[len++] = ';';
7207 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
7208 }
7209 do_cleanups (back_to);
7210 }
7211
7212 rs->buf[len++] = '\0';
7213
7214 putpkt (rs->buf);
7215 getpkt (&rs->buf, &rs->buf_size, 0);
7216
7217 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
7218 {
7219 /* We have a wait response; we don't need it, though. All is well. */
7220 return 0;
7221 }
7222 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7223 /* It wasn't disabled before, but it is now. */
7224 return -1;
7225 else
7226 {
7227 if (remote_exec_file[0] == '\0')
7228 error (_("Running the default executable on the remote target failed; "
7229 "try \"set remote exec-file\"?"));
7230 else
7231 error (_("Running \"%s\" on the remote target failed"),
7232 remote_exec_file);
7233 }
7234 }
7235
7236 /* In the extended protocol we want to be able to do things like
7237 "run" and have them basically work as expected. So we need
7238 a special create_inferior function. We support changing the
7239 executable file and the command line arguments, but not the
7240 environment. */
7241
7242 static void
7243 extended_remote_create_inferior_1 (char *exec_file, char *args,
7244 char **env, int from_tty)
7245 {
7246 /* If running asynchronously, register the target file descriptor
7247 with the event loop. */
7248 if (target_can_async_p ())
7249 target_async (inferior_event_handler, 0);
7250
7251 /* Now restart the remote server. */
7252 if (extended_remote_run (args) == -1)
7253 {
7254 /* vRun was not supported. Fail if we need it to do what the
7255 user requested. */
7256 if (remote_exec_file[0])
7257 error (_("Remote target does not support \"set remote exec-file\""));
7258 if (args[0])
7259 error (_("Remote target does not support \"set args\" or run <ARGS>"));
7260
7261 /* Fall back to "R". */
7262 extended_remote_restart ();
7263 }
7264
7265 if (!have_inferiors ())
7266 {
7267 /* Clean up from the last time we ran, before we mark the target
7268 running again. This will mark breakpoints uninserted, and
7269 get_offsets may insert breakpoints. */
7270 init_thread_list ();
7271 init_wait_for_inferior ();
7272 }
7273
7274 /* Now mark the inferior as running before we do anything else. */
7275 inferior_ptid = magic_null_ptid;
7276
7277 /* Now, if we have thread information, update inferior_ptid. */
7278 inferior_ptid = remote_current_thread (inferior_ptid);
7279
7280 remote_add_inferior (ptid_get_pid (inferior_ptid), 0);
7281 add_thread_silent (inferior_ptid);
7282
7283 /* Get updated offsets, if the stub uses qOffsets. */
7284 get_offsets ();
7285 }
7286
7287 static void
7288 extended_remote_create_inferior (struct target_ops *ops,
7289 char *exec_file, char *args,
7290 char **env, int from_tty)
7291 {
7292 extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
7293 }
7294 \f
7295
7296 /* Insert a breakpoint. On targets that have software breakpoint
7297 support, we ask the remote target to do the work; on targets
7298 which don't, we insert a traditional memory breakpoint. */
7299
7300 static int
7301 remote_insert_breakpoint (struct gdbarch *gdbarch,
7302 struct bp_target_info *bp_tgt)
7303 {
7304 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
7305 If it succeeds, then set the support to PACKET_ENABLE. If it
7306 fails, and the user has explicitly requested the Z support then
7307 report an error, otherwise, mark it disabled and go on. */
7308
7309 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
7310 {
7311 CORE_ADDR addr = bp_tgt->placed_address;
7312 struct remote_state *rs;
7313 char *p;
7314 int bpsize;
7315
7316 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
7317
7318 rs = get_remote_state ();
7319 p = rs->buf;
7320
7321 *(p++) = 'Z';
7322 *(p++) = '0';
7323 *(p++) = ',';
7324 addr = (ULONGEST) remote_address_masked (addr);
7325 p += hexnumstr (p, addr);
7326 sprintf (p, ",%d", bpsize);
7327
7328 putpkt (rs->buf);
7329 getpkt (&rs->buf, &rs->buf_size, 0);
7330
7331 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
7332 {
7333 case PACKET_ERROR:
7334 return -1;
7335 case PACKET_OK:
7336 bp_tgt->placed_address = addr;
7337 bp_tgt->placed_size = bpsize;
7338 return 0;
7339 case PACKET_UNKNOWN:
7340 break;
7341 }
7342 }
7343
7344 return memory_insert_breakpoint (gdbarch, bp_tgt);
7345 }
7346
7347 static int
7348 remote_remove_breakpoint (struct gdbarch *gdbarch,
7349 struct bp_target_info *bp_tgt)
7350 {
7351 CORE_ADDR addr = bp_tgt->placed_address;
7352 struct remote_state *rs = get_remote_state ();
7353
7354 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
7355 {
7356 char *p = rs->buf;
7357
7358 *(p++) = 'z';
7359 *(p++) = '0';
7360 *(p++) = ',';
7361
7362 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
7363 p += hexnumstr (p, addr);
7364 sprintf (p, ",%d", bp_tgt->placed_size);
7365
7366 putpkt (rs->buf);
7367 getpkt (&rs->buf, &rs->buf_size, 0);
7368
7369 return (rs->buf[0] == 'E');
7370 }
7371
7372 return memory_remove_breakpoint (gdbarch, bp_tgt);
7373 }
7374
7375 static int
7376 watchpoint_to_Z_packet (int type)
7377 {
7378 switch (type)
7379 {
7380 case hw_write:
7381 return Z_PACKET_WRITE_WP;
7382 break;
7383 case hw_read:
7384 return Z_PACKET_READ_WP;
7385 break;
7386 case hw_access:
7387 return Z_PACKET_ACCESS_WP;
7388 break;
7389 default:
7390 internal_error (__FILE__, __LINE__,
7391 _("hw_bp_to_z: bad watchpoint type %d"), type);
7392 }
7393 }
7394
7395 static int
7396 remote_insert_watchpoint (CORE_ADDR addr, int len, int type)
7397 {
7398 struct remote_state *rs = get_remote_state ();
7399 char *p;
7400 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
7401
7402 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
7403 return 1;
7404
7405 sprintf (rs->buf, "Z%x,", packet);
7406 p = strchr (rs->buf, '\0');
7407 addr = remote_address_masked (addr);
7408 p += hexnumstr (p, (ULONGEST) addr);
7409 sprintf (p, ",%x", len);
7410
7411 putpkt (rs->buf);
7412 getpkt (&rs->buf, &rs->buf_size, 0);
7413
7414 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
7415 {
7416 case PACKET_ERROR:
7417 return -1;
7418 case PACKET_UNKNOWN:
7419 return 1;
7420 case PACKET_OK:
7421 return 0;
7422 }
7423 internal_error (__FILE__, __LINE__,
7424 _("remote_insert_watchpoint: reached end of function"));
7425 }
7426
7427
7428 static int
7429 remote_remove_watchpoint (CORE_ADDR addr, int len, int type)
7430 {
7431 struct remote_state *rs = get_remote_state ();
7432 char *p;
7433 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
7434
7435 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
7436 return -1;
7437
7438 sprintf (rs->buf, "z%x,", packet);
7439 p = strchr (rs->buf, '\0');
7440 addr = remote_address_masked (addr);
7441 p += hexnumstr (p, (ULONGEST) addr);
7442 sprintf (p, ",%x", len);
7443 putpkt (rs->buf);
7444 getpkt (&rs->buf, &rs->buf_size, 0);
7445
7446 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
7447 {
7448 case PACKET_ERROR:
7449 case PACKET_UNKNOWN:
7450 return -1;
7451 case PACKET_OK:
7452 return 0;
7453 }
7454 internal_error (__FILE__, __LINE__,
7455 _("remote_remove_watchpoint: reached end of function"));
7456 }
7457
7458
7459 int remote_hw_watchpoint_limit = -1;
7460 int remote_hw_breakpoint_limit = -1;
7461
7462 static int
7463 remote_check_watch_resources (int type, int cnt, int ot)
7464 {
7465 if (type == bp_hardware_breakpoint)
7466 {
7467 if (remote_hw_breakpoint_limit == 0)
7468 return 0;
7469 else if (remote_hw_breakpoint_limit < 0)
7470 return 1;
7471 else if (cnt <= remote_hw_breakpoint_limit)
7472 return 1;
7473 }
7474 else
7475 {
7476 if (remote_hw_watchpoint_limit == 0)
7477 return 0;
7478 else if (remote_hw_watchpoint_limit < 0)
7479 return 1;
7480 else if (ot)
7481 return -1;
7482 else if (cnt <= remote_hw_watchpoint_limit)
7483 return 1;
7484 }
7485 return -1;
7486 }
7487
7488 static int
7489 remote_stopped_by_watchpoint (void)
7490 {
7491 return remote_stopped_by_watchpoint_p;
7492 }
7493
7494 static int
7495 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
7496 {
7497 int rc = 0;
7498 if (remote_stopped_by_watchpoint ())
7499 {
7500 *addr_p = remote_watch_data_address;
7501 rc = 1;
7502 }
7503
7504 return rc;
7505 }
7506
7507
7508 static int
7509 remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
7510 struct bp_target_info *bp_tgt)
7511 {
7512 CORE_ADDR addr;
7513 struct remote_state *rs;
7514 char *p;
7515
7516 /* The length field should be set to the size of a breakpoint
7517 instruction, even though we aren't inserting one ourselves. */
7518
7519 gdbarch_remote_breakpoint_from_pc
7520 (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
7521
7522 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
7523 return -1;
7524
7525 rs = get_remote_state ();
7526 p = rs->buf;
7527
7528 *(p++) = 'Z';
7529 *(p++) = '1';
7530 *(p++) = ',';
7531
7532 addr = remote_address_masked (bp_tgt->placed_address);
7533 p += hexnumstr (p, (ULONGEST) addr);
7534 sprintf (p, ",%x", bp_tgt->placed_size);
7535
7536 putpkt (rs->buf);
7537 getpkt (&rs->buf, &rs->buf_size, 0);
7538
7539 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
7540 {
7541 case PACKET_ERROR:
7542 case PACKET_UNKNOWN:
7543 return -1;
7544 case PACKET_OK:
7545 return 0;
7546 }
7547 internal_error (__FILE__, __LINE__,
7548 _("remote_insert_hw_breakpoint: reached end of function"));
7549 }
7550
7551
7552 static int
7553 remote_remove_hw_breakpoint (struct gdbarch *gdbarch,
7554 struct bp_target_info *bp_tgt)
7555 {
7556 CORE_ADDR addr;
7557 struct remote_state *rs = get_remote_state ();
7558 char *p = rs->buf;
7559
7560 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
7561 return -1;
7562
7563 *(p++) = 'z';
7564 *(p++) = '1';
7565 *(p++) = ',';
7566
7567 addr = remote_address_masked (bp_tgt->placed_address);
7568 p += hexnumstr (p, (ULONGEST) addr);
7569 sprintf (p, ",%x", bp_tgt->placed_size);
7570
7571 putpkt (rs->buf);
7572 getpkt (&rs->buf, &rs->buf_size, 0);
7573
7574 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
7575 {
7576 case PACKET_ERROR:
7577 case PACKET_UNKNOWN:
7578 return -1;
7579 case PACKET_OK:
7580 return 0;
7581 }
7582 internal_error (__FILE__, __LINE__,
7583 _("remote_remove_hw_breakpoint: reached end of function"));
7584 }
7585
7586 /* Table used by the crc32 function to calcuate the checksum. */
7587
7588 static unsigned long crc32_table[256] =
7589 {0, 0};
7590
7591 static unsigned long
7592 crc32 (const unsigned char *buf, int len, unsigned int crc)
7593 {
7594 if (!crc32_table[1])
7595 {
7596 /* Initialize the CRC table and the decoding table. */
7597 int i, j;
7598 unsigned int c;
7599
7600 for (i = 0; i < 256; i++)
7601 {
7602 for (c = i << 24, j = 8; j > 0; --j)
7603 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
7604 crc32_table[i] = c;
7605 }
7606 }
7607
7608 while (len--)
7609 {
7610 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
7611 buf++;
7612 }
7613 return crc;
7614 }
7615
7616 /* Verify memory using the "qCRC:" request. */
7617
7618 static int
7619 remote_verify_memory (struct target_ops *ops,
7620 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
7621 {
7622 struct remote_state *rs = get_remote_state ();
7623 unsigned long host_crc, target_crc;
7624 char *tmp;
7625
7626 /* FIXME: assumes lma can fit into long. */
7627 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
7628 (long) lma, (long) size);
7629 putpkt (rs->buf);
7630
7631 /* Be clever; compute the host_crc before waiting for target
7632 reply. */
7633 host_crc = crc32 (data, size, 0xffffffff);
7634
7635 getpkt (&rs->buf, &rs->buf_size, 0);
7636 if (rs->buf[0] == 'E')
7637 return -1;
7638
7639 if (rs->buf[0] != 'C')
7640 error (_("remote target does not support this operation"));
7641
7642 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
7643 target_crc = target_crc * 16 + fromhex (*tmp);
7644
7645 return (host_crc == target_crc);
7646 }
7647
7648 /* compare-sections command
7649
7650 With no arguments, compares each loadable section in the exec bfd
7651 with the same memory range on the target, and reports mismatches.
7652 Useful for verifying the image on the target against the exec file. */
7653
7654 static void
7655 compare_sections_command (char *args, int from_tty)
7656 {
7657 asection *s;
7658 struct cleanup *old_chain;
7659 char *sectdata;
7660 const char *sectname;
7661 bfd_size_type size;
7662 bfd_vma lma;
7663 int matched = 0;
7664 int mismatched = 0;
7665 int res;
7666
7667 if (!exec_bfd)
7668 error (_("command cannot be used without an exec file"));
7669
7670 for (s = exec_bfd->sections; s; s = s->next)
7671 {
7672 if (!(s->flags & SEC_LOAD))
7673 continue; /* skip non-loadable section */
7674
7675 size = bfd_get_section_size (s);
7676 if (size == 0)
7677 continue; /* skip zero-length section */
7678
7679 sectname = bfd_get_section_name (exec_bfd, s);
7680 if (args && strcmp (args, sectname) != 0)
7681 continue; /* not the section selected by user */
7682
7683 matched = 1; /* do this section */
7684 lma = s->lma;
7685
7686 sectdata = xmalloc (size);
7687 old_chain = make_cleanup (xfree, sectdata);
7688 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
7689
7690 res = target_verify_memory (sectdata, lma, size);
7691
7692 if (res == -1)
7693 error (_("target memory fault, section %s, range %s -- %s"), sectname,
7694 paddress (target_gdbarch, lma),
7695 paddress (target_gdbarch, lma + size));
7696
7697 printf_filtered ("Section %s, range %s -- %s: ", sectname,
7698 paddress (target_gdbarch, lma),
7699 paddress (target_gdbarch, lma + size));
7700 if (res)
7701 printf_filtered ("matched.\n");
7702 else
7703 {
7704 printf_filtered ("MIS-MATCHED!\n");
7705 mismatched++;
7706 }
7707
7708 do_cleanups (old_chain);
7709 }
7710 if (mismatched > 0)
7711 warning (_("One or more sections of the remote executable does not match\n\
7712 the loaded file\n"));
7713 if (args && !matched)
7714 printf_filtered (_("No loaded section named '%s'.\n"), args);
7715 }
7716
7717 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
7718 into remote target. The number of bytes written to the remote
7719 target is returned, or -1 for error. */
7720
7721 static LONGEST
7722 remote_write_qxfer (struct target_ops *ops, const char *object_name,
7723 const char *annex, const gdb_byte *writebuf,
7724 ULONGEST offset, LONGEST len,
7725 struct packet_config *packet)
7726 {
7727 int i, buf_len;
7728 ULONGEST n;
7729 struct remote_state *rs = get_remote_state ();
7730 int max_size = get_memory_write_packet_size ();
7731
7732 if (packet->support == PACKET_DISABLE)
7733 return -1;
7734
7735 /* Insert header. */
7736 i = snprintf (rs->buf, max_size,
7737 "qXfer:%s:write:%s:%s:",
7738 object_name, annex ? annex : "",
7739 phex_nz (offset, sizeof offset));
7740 max_size -= (i + 1);
7741
7742 /* Escape as much data as fits into rs->buf. */
7743 buf_len = remote_escape_output
7744 (writebuf, len, (rs->buf + i), &max_size, max_size);
7745
7746 if (putpkt_binary (rs->buf, i + buf_len) < 0
7747 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
7748 || packet_ok (rs->buf, packet) != PACKET_OK)
7749 return -1;
7750
7751 unpack_varlen_hex (rs->buf, &n);
7752 return n;
7753 }
7754
7755 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
7756 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
7757 number of bytes read is returned, or 0 for EOF, or -1 for error.
7758 The number of bytes read may be less than LEN without indicating an
7759 EOF. PACKET is checked and updated to indicate whether the remote
7760 target supports this object. */
7761
7762 static LONGEST
7763 remote_read_qxfer (struct target_ops *ops, const char *object_name,
7764 const char *annex,
7765 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
7766 struct packet_config *packet)
7767 {
7768 static char *finished_object;
7769 static char *finished_annex;
7770 static ULONGEST finished_offset;
7771
7772 struct remote_state *rs = get_remote_state ();
7773 LONGEST i, n, packet_len;
7774
7775 if (packet->support == PACKET_DISABLE)
7776 return -1;
7777
7778 /* Check whether we've cached an end-of-object packet that matches
7779 this request. */
7780 if (finished_object)
7781 {
7782 if (strcmp (object_name, finished_object) == 0
7783 && strcmp (annex ? annex : "", finished_annex) == 0
7784 && offset == finished_offset)
7785 return 0;
7786
7787 /* Otherwise, we're now reading something different. Discard
7788 the cache. */
7789 xfree (finished_object);
7790 xfree (finished_annex);
7791 finished_object = NULL;
7792 finished_annex = NULL;
7793 }
7794
7795 /* Request only enough to fit in a single packet. The actual data
7796 may not, since we don't know how much of it will need to be escaped;
7797 the target is free to respond with slightly less data. We subtract
7798 five to account for the response type and the protocol frame. */
7799 n = min (get_remote_packet_size () - 5, len);
7800 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
7801 object_name, annex ? annex : "",
7802 phex_nz (offset, sizeof offset),
7803 phex_nz (n, sizeof n));
7804 i = putpkt (rs->buf);
7805 if (i < 0)
7806 return -1;
7807
7808 rs->buf[0] = '\0';
7809 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
7810 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
7811 return -1;
7812
7813 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
7814 error (_("Unknown remote qXfer reply: %s"), rs->buf);
7815
7816 /* 'm' means there is (or at least might be) more data after this
7817 batch. That does not make sense unless there's at least one byte
7818 of data in this reply. */
7819 if (rs->buf[0] == 'm' && packet_len == 1)
7820 error (_("Remote qXfer reply contained no data."));
7821
7822 /* Got some data. */
7823 i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
7824
7825 /* 'l' is an EOF marker, possibly including a final block of data,
7826 or possibly empty. If we have the final block of a non-empty
7827 object, record this fact to bypass a subsequent partial read. */
7828 if (rs->buf[0] == 'l' && offset + i > 0)
7829 {
7830 finished_object = xstrdup (object_name);
7831 finished_annex = xstrdup (annex ? annex : "");
7832 finished_offset = offset + i;
7833 }
7834
7835 return i;
7836 }
7837
7838 static LONGEST
7839 remote_xfer_partial (struct target_ops *ops, enum target_object object,
7840 const char *annex, gdb_byte *readbuf,
7841 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
7842 {
7843 struct remote_state *rs;
7844 int i;
7845 char *p2;
7846 char query_type;
7847
7848 set_general_thread (inferior_ptid);
7849
7850 rs = get_remote_state ();
7851
7852 /* Handle memory using the standard memory routines. */
7853 if (object == TARGET_OBJECT_MEMORY)
7854 {
7855 int xfered;
7856 errno = 0;
7857
7858 /* If the remote target is connected but not running, we should
7859 pass this request down to a lower stratum (e.g. the executable
7860 file). */
7861 if (!target_has_execution)
7862 return 0;
7863
7864 if (writebuf != NULL)
7865 xfered = remote_write_bytes (offset, writebuf, len);
7866 else
7867 xfered = remote_read_bytes (offset, readbuf, len);
7868
7869 if (xfered > 0)
7870 return xfered;
7871 else if (xfered == 0 && errno == 0)
7872 return 0;
7873 else
7874 return -1;
7875 }
7876
7877 /* Handle SPU memory using qxfer packets. */
7878 if (object == TARGET_OBJECT_SPU)
7879 {
7880 if (readbuf)
7881 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
7882 &remote_protocol_packets
7883 [PACKET_qXfer_spu_read]);
7884 else
7885 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
7886 &remote_protocol_packets
7887 [PACKET_qXfer_spu_write]);
7888 }
7889
7890 /* Handle extra signal info using qxfer packets. */
7891 if (object == TARGET_OBJECT_SIGNAL_INFO)
7892 {
7893 if (readbuf)
7894 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
7895 &remote_protocol_packets
7896 [PACKET_qXfer_siginfo_read]);
7897 else
7898 return remote_write_qxfer (ops, "siginfo", annex, writebuf, offset, len,
7899 &remote_protocol_packets
7900 [PACKET_qXfer_siginfo_write]);
7901 }
7902
7903 /* Only handle flash writes. */
7904 if (writebuf != NULL)
7905 {
7906 LONGEST xfered;
7907
7908 switch (object)
7909 {
7910 case TARGET_OBJECT_FLASH:
7911 xfered = remote_flash_write (ops, offset, len, writebuf);
7912
7913 if (xfered > 0)
7914 return xfered;
7915 else if (xfered == 0 && errno == 0)
7916 return 0;
7917 else
7918 return -1;
7919
7920 default:
7921 return -1;
7922 }
7923 }
7924
7925 /* Map pre-existing objects onto letters. DO NOT do this for new
7926 objects!!! Instead specify new query packets. */
7927 switch (object)
7928 {
7929 case TARGET_OBJECT_AVR:
7930 query_type = 'R';
7931 break;
7932
7933 case TARGET_OBJECT_AUXV:
7934 gdb_assert (annex == NULL);
7935 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
7936 &remote_protocol_packets[PACKET_qXfer_auxv]);
7937
7938 case TARGET_OBJECT_AVAILABLE_FEATURES:
7939 return remote_read_qxfer
7940 (ops, "features", annex, readbuf, offset, len,
7941 &remote_protocol_packets[PACKET_qXfer_features]);
7942
7943 case TARGET_OBJECT_LIBRARIES:
7944 return remote_read_qxfer
7945 (ops, "libraries", annex, readbuf, offset, len,
7946 &remote_protocol_packets[PACKET_qXfer_libraries]);
7947
7948 case TARGET_OBJECT_MEMORY_MAP:
7949 gdb_assert (annex == NULL);
7950 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
7951 &remote_protocol_packets[PACKET_qXfer_memory_map]);
7952
7953 case TARGET_OBJECT_OSDATA:
7954 /* Should only get here if we're connected. */
7955 gdb_assert (remote_desc);
7956 return remote_read_qxfer
7957 (ops, "osdata", annex, readbuf, offset, len,
7958 &remote_protocol_packets[PACKET_qXfer_osdata]);
7959
7960 case TARGET_OBJECT_THREADS:
7961 gdb_assert (annex == NULL);
7962 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
7963 &remote_protocol_packets[PACKET_qXfer_threads]);
7964
7965 default:
7966 return -1;
7967 }
7968
7969 /* Note: a zero OFFSET and LEN can be used to query the minimum
7970 buffer size. */
7971 if (offset == 0 && len == 0)
7972 return (get_remote_packet_size ());
7973 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
7974 large enough let the caller deal with it. */
7975 if (len < get_remote_packet_size ())
7976 return -1;
7977 len = get_remote_packet_size ();
7978
7979 /* Except for querying the minimum buffer size, target must be open. */
7980 if (!remote_desc)
7981 error (_("remote query is only available after target open"));
7982
7983 gdb_assert (annex != NULL);
7984 gdb_assert (readbuf != NULL);
7985
7986 p2 = rs->buf;
7987 *p2++ = 'q';
7988 *p2++ = query_type;
7989
7990 /* We used one buffer char for the remote protocol q command and
7991 another for the query type. As the remote protocol encapsulation
7992 uses 4 chars plus one extra in case we are debugging
7993 (remote_debug), we have PBUFZIZ - 7 left to pack the query
7994 string. */
7995 i = 0;
7996 while (annex[i] && (i < (get_remote_packet_size () - 8)))
7997 {
7998 /* Bad caller may have sent forbidden characters. */
7999 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
8000 *p2++ = annex[i];
8001 i++;
8002 }
8003 *p2 = '\0';
8004 gdb_assert (annex[i] == '\0');
8005
8006 i = putpkt (rs->buf);
8007 if (i < 0)
8008 return i;
8009
8010 getpkt (&rs->buf, &rs->buf_size, 0);
8011 strcpy ((char *) readbuf, rs->buf);
8012
8013 return strlen ((char *) readbuf);
8014 }
8015
8016 static int
8017 remote_search_memory (struct target_ops* ops,
8018 CORE_ADDR start_addr, ULONGEST search_space_len,
8019 const gdb_byte *pattern, ULONGEST pattern_len,
8020 CORE_ADDR *found_addrp)
8021 {
8022 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
8023 struct remote_state *rs = get_remote_state ();
8024 int max_size = get_memory_write_packet_size ();
8025 struct packet_config *packet =
8026 &remote_protocol_packets[PACKET_qSearch_memory];
8027 /* number of packet bytes used to encode the pattern,
8028 this could be more than PATTERN_LEN due to escape characters */
8029 int escaped_pattern_len;
8030 /* amount of pattern that was encodable in the packet */
8031 int used_pattern_len;
8032 int i;
8033 int found;
8034 ULONGEST found_addr;
8035
8036 /* Don't go to the target if we don't have to.
8037 This is done before checking packet->support to avoid the possibility that
8038 a success for this edge case means the facility works in general. */
8039 if (pattern_len > search_space_len)
8040 return 0;
8041 if (pattern_len == 0)
8042 {
8043 *found_addrp = start_addr;
8044 return 1;
8045 }
8046
8047 /* If we already know the packet isn't supported, fall back to the simple
8048 way of searching memory. */
8049
8050 if (packet->support == PACKET_DISABLE)
8051 {
8052 /* Target doesn't provided special support, fall back and use the
8053 standard support (copy memory and do the search here). */
8054 return simple_search_memory (ops, start_addr, search_space_len,
8055 pattern, pattern_len, found_addrp);
8056 }
8057
8058 /* Insert header. */
8059 i = snprintf (rs->buf, max_size,
8060 "qSearch:memory:%s;%s;",
8061 phex_nz (start_addr, addr_size),
8062 phex_nz (search_space_len, sizeof (search_space_len)));
8063 max_size -= (i + 1);
8064
8065 /* Escape as much data as fits into rs->buf. */
8066 escaped_pattern_len =
8067 remote_escape_output (pattern, pattern_len, (rs->buf + i),
8068 &used_pattern_len, max_size);
8069
8070 /* Bail if the pattern is too large. */
8071 if (used_pattern_len != pattern_len)
8072 error ("Pattern is too large to transmit to remote target.");
8073
8074 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
8075 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8076 || packet_ok (rs->buf, packet) != PACKET_OK)
8077 {
8078 /* The request may not have worked because the command is not
8079 supported. If so, fall back to the simple way. */
8080 if (packet->support == PACKET_DISABLE)
8081 {
8082 return simple_search_memory (ops, start_addr, search_space_len,
8083 pattern, pattern_len, found_addrp);
8084 }
8085 return -1;
8086 }
8087
8088 if (rs->buf[0] == '0')
8089 found = 0;
8090 else if (rs->buf[0] == '1')
8091 {
8092 found = 1;
8093 if (rs->buf[1] != ',')
8094 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
8095 unpack_varlen_hex (rs->buf + 2, &found_addr);
8096 *found_addrp = found_addr;
8097 }
8098 else
8099 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
8100
8101 return found;
8102 }
8103
8104 static void
8105 remote_rcmd (char *command,
8106 struct ui_file *outbuf)
8107 {
8108 struct remote_state *rs = get_remote_state ();
8109 char *p = rs->buf;
8110
8111 if (!remote_desc)
8112 error (_("remote rcmd is only available after target open"));
8113
8114 /* Send a NULL command across as an empty command. */
8115 if (command == NULL)
8116 command = "";
8117
8118 /* The query prefix. */
8119 strcpy (rs->buf, "qRcmd,");
8120 p = strchr (rs->buf, '\0');
8121
8122 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/) > get_remote_packet_size ())
8123 error (_("\"monitor\" command ``%s'' is too long."), command);
8124
8125 /* Encode the actual command. */
8126 bin2hex ((gdb_byte *) command, p, 0);
8127
8128 if (putpkt (rs->buf) < 0)
8129 error (_("Communication problem with target."));
8130
8131 /* get/display the response */
8132 while (1)
8133 {
8134 char *buf;
8135
8136 /* XXX - see also remote_get_noisy_reply(). */
8137 rs->buf[0] = '\0';
8138 getpkt (&rs->buf, &rs->buf_size, 0);
8139 buf = rs->buf;
8140 if (buf[0] == '\0')
8141 error (_("Target does not support this command."));
8142 if (buf[0] == 'O' && buf[1] != 'K')
8143 {
8144 remote_console_output (buf + 1); /* 'O' message from stub. */
8145 continue;
8146 }
8147 if (strcmp (buf, "OK") == 0)
8148 break;
8149 if (strlen (buf) == 3 && buf[0] == 'E'
8150 && isdigit (buf[1]) && isdigit (buf[2]))
8151 {
8152 error (_("Protocol error with Rcmd"));
8153 }
8154 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
8155 {
8156 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
8157 fputc_unfiltered (c, outbuf);
8158 }
8159 break;
8160 }
8161 }
8162
8163 static VEC(mem_region_s) *
8164 remote_memory_map (struct target_ops *ops)
8165 {
8166 VEC(mem_region_s) *result = NULL;
8167 char *text = target_read_stralloc (&current_target,
8168 TARGET_OBJECT_MEMORY_MAP, NULL);
8169
8170 if (text)
8171 {
8172 struct cleanup *back_to = make_cleanup (xfree, text);
8173 result = parse_memory_map (text);
8174 do_cleanups (back_to);
8175 }
8176
8177 return result;
8178 }
8179
8180 static void
8181 packet_command (char *args, int from_tty)
8182 {
8183 struct remote_state *rs = get_remote_state ();
8184
8185 if (!remote_desc)
8186 error (_("command can only be used with remote target"));
8187
8188 if (!args)
8189 error (_("remote-packet command requires packet text as argument"));
8190
8191 puts_filtered ("sending: ");
8192 print_packet (args);
8193 puts_filtered ("\n");
8194 putpkt (args);
8195
8196 getpkt (&rs->buf, &rs->buf_size, 0);
8197 puts_filtered ("received: ");
8198 print_packet (rs->buf);
8199 puts_filtered ("\n");
8200 }
8201
8202 #if 0
8203 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
8204
8205 static void display_thread_info (struct gdb_ext_thread_info *info);
8206
8207 static void threadset_test_cmd (char *cmd, int tty);
8208
8209 static void threadalive_test (char *cmd, int tty);
8210
8211 static void threadlist_test_cmd (char *cmd, int tty);
8212
8213 int get_and_display_threadinfo (threadref *ref);
8214
8215 static void threadinfo_test_cmd (char *cmd, int tty);
8216
8217 static int thread_display_step (threadref *ref, void *context);
8218
8219 static void threadlist_update_test_cmd (char *cmd, int tty);
8220
8221 static void init_remote_threadtests (void);
8222
8223 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
8224
8225 static void
8226 threadset_test_cmd (char *cmd, int tty)
8227 {
8228 int sample_thread = SAMPLE_THREAD;
8229
8230 printf_filtered (_("Remote threadset test\n"));
8231 set_general_thread (sample_thread);
8232 }
8233
8234
8235 static void
8236 threadalive_test (char *cmd, int tty)
8237 {
8238 int sample_thread = SAMPLE_THREAD;
8239 int pid = ptid_get_pid (inferior_ptid);
8240 ptid_t ptid = ptid_build (pid, 0, sample_thread);
8241
8242 if (remote_thread_alive (ptid))
8243 printf_filtered ("PASS: Thread alive test\n");
8244 else
8245 printf_filtered ("FAIL: Thread alive test\n");
8246 }
8247
8248 void output_threadid (char *title, threadref *ref);
8249
8250 void
8251 output_threadid (char *title, threadref *ref)
8252 {
8253 char hexid[20];
8254
8255 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
8256 hexid[16] = 0;
8257 printf_filtered ("%s %s\n", title, (&hexid[0]));
8258 }
8259
8260 static void
8261 threadlist_test_cmd (char *cmd, int tty)
8262 {
8263 int startflag = 1;
8264 threadref nextthread;
8265 int done, result_count;
8266 threadref threadlist[3];
8267
8268 printf_filtered ("Remote Threadlist test\n");
8269 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
8270 &result_count, &threadlist[0]))
8271 printf_filtered ("FAIL: threadlist test\n");
8272 else
8273 {
8274 threadref *scan = threadlist;
8275 threadref *limit = scan + result_count;
8276
8277 while (scan < limit)
8278 output_threadid (" thread ", scan++);
8279 }
8280 }
8281
8282 void
8283 display_thread_info (struct gdb_ext_thread_info *info)
8284 {
8285 output_threadid ("Threadid: ", &info->threadid);
8286 printf_filtered ("Name: %s\n ", info->shortname);
8287 printf_filtered ("State: %s\n", info->display);
8288 printf_filtered ("other: %s\n\n", info->more_display);
8289 }
8290
8291 int
8292 get_and_display_threadinfo (threadref *ref)
8293 {
8294 int result;
8295 int set;
8296 struct gdb_ext_thread_info threadinfo;
8297
8298 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
8299 | TAG_MOREDISPLAY | TAG_DISPLAY;
8300 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
8301 display_thread_info (&threadinfo);
8302 return result;
8303 }
8304
8305 static void
8306 threadinfo_test_cmd (char *cmd, int tty)
8307 {
8308 int athread = SAMPLE_THREAD;
8309 threadref thread;
8310 int set;
8311
8312 int_to_threadref (&thread, athread);
8313 printf_filtered ("Remote Threadinfo test\n");
8314 if (!get_and_display_threadinfo (&thread))
8315 printf_filtered ("FAIL cannot get thread info\n");
8316 }
8317
8318 static int
8319 thread_display_step (threadref *ref, void *context)
8320 {
8321 /* output_threadid(" threadstep ",ref); *//* simple test */
8322 return get_and_display_threadinfo (ref);
8323 }
8324
8325 static void
8326 threadlist_update_test_cmd (char *cmd, int tty)
8327 {
8328 printf_filtered ("Remote Threadlist update test\n");
8329 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
8330 }
8331
8332 static void
8333 init_remote_threadtests (void)
8334 {
8335 add_com ("tlist", class_obscure, threadlist_test_cmd, _("\
8336 Fetch and print the remote list of thread identifiers, one pkt only"));
8337 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
8338 _("Fetch and display info about one thread"));
8339 add_com ("tset", class_obscure, threadset_test_cmd,
8340 _("Test setting to a different thread"));
8341 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
8342 _("Iterate through updating all remote thread info"));
8343 add_com ("talive", class_obscure, threadalive_test,
8344 _(" Remote thread alive test "));
8345 }
8346
8347 #endif /* 0 */
8348
8349 /* Convert a thread ID to a string. Returns the string in a static
8350 buffer. */
8351
8352 static char *
8353 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
8354 {
8355 static char buf[64];
8356 struct remote_state *rs = get_remote_state ();
8357
8358 if (ptid_is_pid (ptid))
8359 {
8360 /* Printing an inferior target id. */
8361
8362 /* When multi-process extensions are off, there's no way in the
8363 remote protocol to know the remote process id, if there's any
8364 at all. There's one exception --- when we're connected with
8365 target extended-remote, and we manually attached to a process
8366 with "attach PID". We don't record anywhere a flag that
8367 allows us to distinguish that case from the case of
8368 connecting with extended-remote and the stub already being
8369 attached to a process, and reporting yes to qAttached, hence
8370 no smart special casing here. */
8371 if (!remote_multi_process_p (rs))
8372 {
8373 xsnprintf (buf, sizeof buf, "Remote target");
8374 return buf;
8375 }
8376
8377 return normal_pid_to_str (ptid);
8378 }
8379 else
8380 {
8381 if (ptid_equal (magic_null_ptid, ptid))
8382 xsnprintf (buf, sizeof buf, "Thread <main>");
8383 else if (remote_multi_process_p (rs))
8384 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
8385 ptid_get_pid (ptid), ptid_get_tid (ptid));
8386 else
8387 xsnprintf (buf, sizeof buf, "Thread %ld",
8388 ptid_get_tid (ptid));
8389 return buf;
8390 }
8391 }
8392
8393 /* Get the address of the thread local variable in OBJFILE which is
8394 stored at OFFSET within the thread local storage for thread PTID. */
8395
8396 static CORE_ADDR
8397 remote_get_thread_local_address (struct target_ops *ops,
8398 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
8399 {
8400 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
8401 {
8402 struct remote_state *rs = get_remote_state ();
8403 char *p = rs->buf;
8404 char *endp = rs->buf + get_remote_packet_size ();
8405 enum packet_result result;
8406
8407 strcpy (p, "qGetTLSAddr:");
8408 p += strlen (p);
8409 p = write_ptid (p, endp, ptid);
8410 *p++ = ',';
8411 p += hexnumstr (p, offset);
8412 *p++ = ',';
8413 p += hexnumstr (p, lm);
8414 *p++ = '\0';
8415
8416 putpkt (rs->buf);
8417 getpkt (&rs->buf, &rs->buf_size, 0);
8418 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_qGetTLSAddr]);
8419 if (result == PACKET_OK)
8420 {
8421 ULONGEST result;
8422
8423 unpack_varlen_hex (rs->buf, &result);
8424 return result;
8425 }
8426 else if (result == PACKET_UNKNOWN)
8427 throw_error (TLS_GENERIC_ERROR,
8428 _("Remote target doesn't support qGetTLSAddr packet"));
8429 else
8430 throw_error (TLS_GENERIC_ERROR,
8431 _("Remote target failed to process qGetTLSAddr request"));
8432 }
8433 else
8434 throw_error (TLS_GENERIC_ERROR,
8435 _("TLS not supported or disabled on this target"));
8436 /* Not reached. */
8437 return 0;
8438 }
8439
8440 /* Support for inferring a target description based on the current
8441 architecture and the size of a 'g' packet. While the 'g' packet
8442 can have any size (since optional registers can be left off the
8443 end), some sizes are easily recognizable given knowledge of the
8444 approximate architecture. */
8445
8446 struct remote_g_packet_guess
8447 {
8448 int bytes;
8449 const struct target_desc *tdesc;
8450 };
8451 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
8452 DEF_VEC_O(remote_g_packet_guess_s);
8453
8454 struct remote_g_packet_data
8455 {
8456 VEC(remote_g_packet_guess_s) *guesses;
8457 };
8458
8459 static struct gdbarch_data *remote_g_packet_data_handle;
8460
8461 static void *
8462 remote_g_packet_data_init (struct obstack *obstack)
8463 {
8464 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
8465 }
8466
8467 void
8468 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
8469 const struct target_desc *tdesc)
8470 {
8471 struct remote_g_packet_data *data
8472 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
8473 struct remote_g_packet_guess new_guess, *guess;
8474 int ix;
8475
8476 gdb_assert (tdesc != NULL);
8477
8478 for (ix = 0;
8479 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
8480 ix++)
8481 if (guess->bytes == bytes)
8482 internal_error (__FILE__, __LINE__,
8483 "Duplicate g packet description added for size %d",
8484 bytes);
8485
8486 new_guess.bytes = bytes;
8487 new_guess.tdesc = tdesc;
8488 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
8489 }
8490
8491 /* Return 1 if remote_read_description would do anything on this target
8492 and architecture, 0 otherwise. */
8493
8494 static int
8495 remote_read_description_p (struct target_ops *target)
8496 {
8497 struct remote_g_packet_data *data
8498 = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
8499
8500 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
8501 return 1;
8502
8503 return 0;
8504 }
8505
8506 static const struct target_desc *
8507 remote_read_description (struct target_ops *target)
8508 {
8509 struct remote_g_packet_data *data
8510 = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
8511
8512 /* Do not try this during initial connection, when we do not know
8513 whether there is a running but stopped thread. */
8514 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
8515 return NULL;
8516
8517 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
8518 {
8519 struct remote_g_packet_guess *guess;
8520 int ix;
8521 int bytes = send_g_packet ();
8522
8523 for (ix = 0;
8524 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
8525 ix++)
8526 if (guess->bytes == bytes)
8527 return guess->tdesc;
8528
8529 /* We discard the g packet. A minor optimization would be to
8530 hold on to it, and fill the register cache once we have selected
8531 an architecture, but it's too tricky to do safely. */
8532 }
8533
8534 return NULL;
8535 }
8536
8537 /* Remote file transfer support. This is host-initiated I/O, not
8538 target-initiated; for target-initiated, see remote-fileio.c. */
8539
8540 /* If *LEFT is at least the length of STRING, copy STRING to
8541 *BUFFER, update *BUFFER to point to the new end of the buffer, and
8542 decrease *LEFT. Otherwise raise an error. */
8543
8544 static void
8545 remote_buffer_add_string (char **buffer, int *left, char *string)
8546 {
8547 int len = strlen (string);
8548
8549 if (len > *left)
8550 error (_("Packet too long for target."));
8551
8552 memcpy (*buffer, string, len);
8553 *buffer += len;
8554 *left -= len;
8555
8556 /* NUL-terminate the buffer as a convenience, if there is
8557 room. */
8558 if (*left)
8559 **buffer = '\0';
8560 }
8561
8562 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
8563 *BUFFER, update *BUFFER to point to the new end of the buffer, and
8564 decrease *LEFT. Otherwise raise an error. */
8565
8566 static void
8567 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
8568 int len)
8569 {
8570 if (2 * len > *left)
8571 error (_("Packet too long for target."));
8572
8573 bin2hex (bytes, *buffer, len);
8574 *buffer += 2 * len;
8575 *left -= 2 * len;
8576
8577 /* NUL-terminate the buffer as a convenience, if there is
8578 room. */
8579 if (*left)
8580 **buffer = '\0';
8581 }
8582
8583 /* If *LEFT is large enough, convert VALUE to hex and add it to
8584 *BUFFER, update *BUFFER to point to the new end of the buffer, and
8585 decrease *LEFT. Otherwise raise an error. */
8586
8587 static void
8588 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
8589 {
8590 int len = hexnumlen (value);
8591
8592 if (len > *left)
8593 error (_("Packet too long for target."));
8594
8595 hexnumstr (*buffer, value);
8596 *buffer += len;
8597 *left -= len;
8598
8599 /* NUL-terminate the buffer as a convenience, if there is
8600 room. */
8601 if (*left)
8602 **buffer = '\0';
8603 }
8604
8605 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
8606 value, *REMOTE_ERRNO to the remote error number or zero if none
8607 was included, and *ATTACHMENT to point to the start of the annex
8608 if any. The length of the packet isn't needed here; there may
8609 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
8610
8611 Return 0 if the packet could be parsed, -1 if it could not. If
8612 -1 is returned, the other variables may not be initialized. */
8613
8614 static int
8615 remote_hostio_parse_result (char *buffer, int *retcode,
8616 int *remote_errno, char **attachment)
8617 {
8618 char *p, *p2;
8619
8620 *remote_errno = 0;
8621 *attachment = NULL;
8622
8623 if (buffer[0] != 'F')
8624 return -1;
8625
8626 errno = 0;
8627 *retcode = strtol (&buffer[1], &p, 16);
8628 if (errno != 0 || p == &buffer[1])
8629 return -1;
8630
8631 /* Check for ",errno". */
8632 if (*p == ',')
8633 {
8634 errno = 0;
8635 *remote_errno = strtol (p + 1, &p2, 16);
8636 if (errno != 0 || p + 1 == p2)
8637 return -1;
8638 p = p2;
8639 }
8640
8641 /* Check for ";attachment". If there is no attachment, the
8642 packet should end here. */
8643 if (*p == ';')
8644 {
8645 *attachment = p + 1;
8646 return 0;
8647 }
8648 else if (*p == '\0')
8649 return 0;
8650 else
8651 return -1;
8652 }
8653
8654 /* Send a prepared I/O packet to the target and read its response.
8655 The prepared packet is in the global RS->BUF before this function
8656 is called, and the answer is there when we return.
8657
8658 COMMAND_BYTES is the length of the request to send, which may include
8659 binary data. WHICH_PACKET is the packet configuration to check
8660 before attempting a packet. If an error occurs, *REMOTE_ERRNO
8661 is set to the error number and -1 is returned. Otherwise the value
8662 returned by the function is returned.
8663
8664 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
8665 attachment is expected; an error will be reported if there's a
8666 mismatch. If one is found, *ATTACHMENT will be set to point into
8667 the packet buffer and *ATTACHMENT_LEN will be set to the
8668 attachment's length. */
8669
8670 static int
8671 remote_hostio_send_command (int command_bytes, int which_packet,
8672 int *remote_errno, char **attachment,
8673 int *attachment_len)
8674 {
8675 struct remote_state *rs = get_remote_state ();
8676 int ret, bytes_read;
8677 char *attachment_tmp;
8678
8679 if (!remote_desc
8680 || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
8681 {
8682 *remote_errno = FILEIO_ENOSYS;
8683 return -1;
8684 }
8685
8686 putpkt_binary (rs->buf, command_bytes);
8687 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8688
8689 /* If it timed out, something is wrong. Don't try to parse the
8690 buffer. */
8691 if (bytes_read < 0)
8692 {
8693 *remote_errno = FILEIO_EINVAL;
8694 return -1;
8695 }
8696
8697 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
8698 {
8699 case PACKET_ERROR:
8700 *remote_errno = FILEIO_EINVAL;
8701 return -1;
8702 case PACKET_UNKNOWN:
8703 *remote_errno = FILEIO_ENOSYS;
8704 return -1;
8705 case PACKET_OK:
8706 break;
8707 }
8708
8709 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
8710 &attachment_tmp))
8711 {
8712 *remote_errno = FILEIO_EINVAL;
8713 return -1;
8714 }
8715
8716 /* Make sure we saw an attachment if and only if we expected one. */
8717 if ((attachment_tmp == NULL && attachment != NULL)
8718 || (attachment_tmp != NULL && attachment == NULL))
8719 {
8720 *remote_errno = FILEIO_EINVAL;
8721 return -1;
8722 }
8723
8724 /* If an attachment was found, it must point into the packet buffer;
8725 work out how many bytes there were. */
8726 if (attachment_tmp != NULL)
8727 {
8728 *attachment = attachment_tmp;
8729 *attachment_len = bytes_read - (*attachment - rs->buf);
8730 }
8731
8732 return ret;
8733 }
8734
8735 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
8736 remote file descriptor, or -1 if an error occurs (and set
8737 *REMOTE_ERRNO). */
8738
8739 static int
8740 remote_hostio_open (const char *filename, int flags, int mode,
8741 int *remote_errno)
8742 {
8743 struct remote_state *rs = get_remote_state ();
8744 char *p = rs->buf;
8745 int left = get_remote_packet_size () - 1;
8746
8747 remote_buffer_add_string (&p, &left, "vFile:open:");
8748
8749 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
8750 strlen (filename));
8751 remote_buffer_add_string (&p, &left, ",");
8752
8753 remote_buffer_add_int (&p, &left, flags);
8754 remote_buffer_add_string (&p, &left, ",");
8755
8756 remote_buffer_add_int (&p, &left, mode);
8757
8758 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
8759 remote_errno, NULL, NULL);
8760 }
8761
8762 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
8763 Return the number of bytes written, or -1 if an error occurs (and
8764 set *REMOTE_ERRNO). */
8765
8766 static int
8767 remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
8768 ULONGEST offset, int *remote_errno)
8769 {
8770 struct remote_state *rs = get_remote_state ();
8771 char *p = rs->buf;
8772 int left = get_remote_packet_size ();
8773 int out_len;
8774
8775 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
8776
8777 remote_buffer_add_int (&p, &left, fd);
8778 remote_buffer_add_string (&p, &left, ",");
8779
8780 remote_buffer_add_int (&p, &left, offset);
8781 remote_buffer_add_string (&p, &left, ",");
8782
8783 p += remote_escape_output (write_buf, len, p, &out_len,
8784 get_remote_packet_size () - (p - rs->buf));
8785
8786 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
8787 remote_errno, NULL, NULL);
8788 }
8789
8790 /* Read up to LEN bytes FD on the remote target into READ_BUF
8791 Return the number of bytes read, or -1 if an error occurs (and
8792 set *REMOTE_ERRNO). */
8793
8794 static int
8795 remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
8796 ULONGEST offset, int *remote_errno)
8797 {
8798 struct remote_state *rs = get_remote_state ();
8799 char *p = rs->buf;
8800 char *attachment;
8801 int left = get_remote_packet_size ();
8802 int ret, attachment_len;
8803 int read_len;
8804
8805 remote_buffer_add_string (&p, &left, "vFile:pread:");
8806
8807 remote_buffer_add_int (&p, &left, fd);
8808 remote_buffer_add_string (&p, &left, ",");
8809
8810 remote_buffer_add_int (&p, &left, len);
8811 remote_buffer_add_string (&p, &left, ",");
8812
8813 remote_buffer_add_int (&p, &left, offset);
8814
8815 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
8816 remote_errno, &attachment,
8817 &attachment_len);
8818
8819 if (ret < 0)
8820 return ret;
8821
8822 read_len = remote_unescape_input (attachment, attachment_len,
8823 read_buf, len);
8824 if (read_len != ret)
8825 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
8826
8827 return ret;
8828 }
8829
8830 /* Close FD on the remote target. Return 0, or -1 if an error occurs
8831 (and set *REMOTE_ERRNO). */
8832
8833 static int
8834 remote_hostio_close (int fd, int *remote_errno)
8835 {
8836 struct remote_state *rs = get_remote_state ();
8837 char *p = rs->buf;
8838 int left = get_remote_packet_size () - 1;
8839
8840 remote_buffer_add_string (&p, &left, "vFile:close:");
8841
8842 remote_buffer_add_int (&p, &left, fd);
8843
8844 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
8845 remote_errno, NULL, NULL);
8846 }
8847
8848 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
8849 occurs (and set *REMOTE_ERRNO). */
8850
8851 static int
8852 remote_hostio_unlink (const char *filename, int *remote_errno)
8853 {
8854 struct remote_state *rs = get_remote_state ();
8855 char *p = rs->buf;
8856 int left = get_remote_packet_size () - 1;
8857
8858 remote_buffer_add_string (&p, &left, "vFile:unlink:");
8859
8860 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
8861 strlen (filename));
8862
8863 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
8864 remote_errno, NULL, NULL);
8865 }
8866
8867 static int
8868 remote_fileio_errno_to_host (int errnum)
8869 {
8870 switch (errnum)
8871 {
8872 case FILEIO_EPERM:
8873 return EPERM;
8874 case FILEIO_ENOENT:
8875 return ENOENT;
8876 case FILEIO_EINTR:
8877 return EINTR;
8878 case FILEIO_EIO:
8879 return EIO;
8880 case FILEIO_EBADF:
8881 return EBADF;
8882 case FILEIO_EACCES:
8883 return EACCES;
8884 case FILEIO_EFAULT:
8885 return EFAULT;
8886 case FILEIO_EBUSY:
8887 return EBUSY;
8888 case FILEIO_EEXIST:
8889 return EEXIST;
8890 case FILEIO_ENODEV:
8891 return ENODEV;
8892 case FILEIO_ENOTDIR:
8893 return ENOTDIR;
8894 case FILEIO_EISDIR:
8895 return EISDIR;
8896 case FILEIO_EINVAL:
8897 return EINVAL;
8898 case FILEIO_ENFILE:
8899 return ENFILE;
8900 case FILEIO_EMFILE:
8901 return EMFILE;
8902 case FILEIO_EFBIG:
8903 return EFBIG;
8904 case FILEIO_ENOSPC:
8905 return ENOSPC;
8906 case FILEIO_ESPIPE:
8907 return ESPIPE;
8908 case FILEIO_EROFS:
8909 return EROFS;
8910 case FILEIO_ENOSYS:
8911 return ENOSYS;
8912 case FILEIO_ENAMETOOLONG:
8913 return ENAMETOOLONG;
8914 }
8915 return -1;
8916 }
8917
8918 static char *
8919 remote_hostio_error (int errnum)
8920 {
8921 int host_error = remote_fileio_errno_to_host (errnum);
8922
8923 if (host_error == -1)
8924 error (_("Unknown remote I/O error %d"), errnum);
8925 else
8926 error (_("Remote I/O error: %s"), safe_strerror (host_error));
8927 }
8928
8929 static void
8930 remote_hostio_close_cleanup (void *opaque)
8931 {
8932 int fd = *(int *) opaque;
8933 int remote_errno;
8934
8935 remote_hostio_close (fd, &remote_errno);
8936 }
8937
8938
8939 static void *
8940 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
8941 {
8942 const char *filename = bfd_get_filename (abfd);
8943 int fd, remote_errno;
8944 int *stream;
8945
8946 gdb_assert (remote_filename_p (filename));
8947
8948 fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
8949 if (fd == -1)
8950 {
8951 errno = remote_fileio_errno_to_host (remote_errno);
8952 bfd_set_error (bfd_error_system_call);
8953 return NULL;
8954 }
8955
8956 stream = xmalloc (sizeof (int));
8957 *stream = fd;
8958 return stream;
8959 }
8960
8961 static int
8962 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
8963 {
8964 int fd = *(int *)stream;
8965 int remote_errno;
8966
8967 xfree (stream);
8968
8969 /* Ignore errors on close; these may happen if the remote
8970 connection was already torn down. */
8971 remote_hostio_close (fd, &remote_errno);
8972
8973 return 1;
8974 }
8975
8976 static file_ptr
8977 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
8978 file_ptr nbytes, file_ptr offset)
8979 {
8980 int fd = *(int *)stream;
8981 int remote_errno;
8982 file_ptr pos, bytes;
8983
8984 pos = 0;
8985 while (nbytes > pos)
8986 {
8987 bytes = remote_hostio_pread (fd, (char *)buf + pos, nbytes - pos,
8988 offset + pos, &remote_errno);
8989 if (bytes == 0)
8990 /* Success, but no bytes, means end-of-file. */
8991 break;
8992 if (bytes == -1)
8993 {
8994 errno = remote_fileio_errno_to_host (remote_errno);
8995 bfd_set_error (bfd_error_system_call);
8996 return -1;
8997 }
8998
8999 pos += bytes;
9000 }
9001
9002 return pos;
9003 }
9004
9005 static int
9006 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
9007 {
9008 /* FIXME: We should probably implement remote_hostio_stat. */
9009 sb->st_size = INT_MAX;
9010 return 0;
9011 }
9012
9013 int
9014 remote_filename_p (const char *filename)
9015 {
9016 return strncmp (filename, "remote:", 7) == 0;
9017 }
9018
9019 bfd *
9020 remote_bfd_open (const char *remote_file, const char *target)
9021 {
9022 return bfd_openr_iovec (remote_file, target,
9023 remote_bfd_iovec_open, NULL,
9024 remote_bfd_iovec_pread,
9025 remote_bfd_iovec_close,
9026 remote_bfd_iovec_stat);
9027 }
9028
9029 void
9030 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
9031 {
9032 struct cleanup *back_to, *close_cleanup;
9033 int retcode, fd, remote_errno, bytes, io_size;
9034 FILE *file;
9035 gdb_byte *buffer;
9036 int bytes_in_buffer;
9037 int saw_eof;
9038 ULONGEST offset;
9039
9040 if (!remote_desc)
9041 error (_("command can only be used with remote target"));
9042
9043 file = fopen (local_file, "rb");
9044 if (file == NULL)
9045 perror_with_name (local_file);
9046 back_to = make_cleanup_fclose (file);
9047
9048 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
9049 | FILEIO_O_TRUNC),
9050 0700, &remote_errno);
9051 if (fd == -1)
9052 remote_hostio_error (remote_errno);
9053
9054 /* Send up to this many bytes at once. They won't all fit in the
9055 remote packet limit, so we'll transfer slightly fewer. */
9056 io_size = get_remote_packet_size ();
9057 buffer = xmalloc (io_size);
9058 make_cleanup (xfree, buffer);
9059
9060 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
9061
9062 bytes_in_buffer = 0;
9063 saw_eof = 0;
9064 offset = 0;
9065 while (bytes_in_buffer || !saw_eof)
9066 {
9067 if (!saw_eof)
9068 {
9069 bytes = fread (buffer + bytes_in_buffer, 1, io_size - bytes_in_buffer,
9070 file);
9071 if (bytes == 0)
9072 {
9073 if (ferror (file))
9074 error (_("Error reading %s."), local_file);
9075 else
9076 {
9077 /* EOF. Unless there is something still in the
9078 buffer from the last iteration, we are done. */
9079 saw_eof = 1;
9080 if (bytes_in_buffer == 0)
9081 break;
9082 }
9083 }
9084 }
9085 else
9086 bytes = 0;
9087
9088 bytes += bytes_in_buffer;
9089 bytes_in_buffer = 0;
9090
9091 retcode = remote_hostio_pwrite (fd, buffer, bytes, offset, &remote_errno);
9092
9093 if (retcode < 0)
9094 remote_hostio_error (remote_errno);
9095 else if (retcode == 0)
9096 error (_("Remote write of %d bytes returned 0!"), bytes);
9097 else if (retcode < bytes)
9098 {
9099 /* Short write. Save the rest of the read data for the next
9100 write. */
9101 bytes_in_buffer = bytes - retcode;
9102 memmove (buffer, buffer + retcode, bytes_in_buffer);
9103 }
9104
9105 offset += retcode;
9106 }
9107
9108 discard_cleanups (close_cleanup);
9109 if (remote_hostio_close (fd, &remote_errno))
9110 remote_hostio_error (remote_errno);
9111
9112 if (from_tty)
9113 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
9114 do_cleanups (back_to);
9115 }
9116
9117 void
9118 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
9119 {
9120 struct cleanup *back_to, *close_cleanup;
9121 int fd, remote_errno, bytes, io_size;
9122 FILE *file;
9123 gdb_byte *buffer;
9124 ULONGEST offset;
9125
9126 if (!remote_desc)
9127 error (_("command can only be used with remote target"));
9128
9129 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
9130 if (fd == -1)
9131 remote_hostio_error (remote_errno);
9132
9133 file = fopen (local_file, "wb");
9134 if (file == NULL)
9135 perror_with_name (local_file);
9136 back_to = make_cleanup_fclose (file);
9137
9138 /* Send up to this many bytes at once. They won't all fit in the
9139 remote packet limit, so we'll transfer slightly fewer. */
9140 io_size = get_remote_packet_size ();
9141 buffer = xmalloc (io_size);
9142 make_cleanup (xfree, buffer);
9143
9144 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
9145
9146 offset = 0;
9147 while (1)
9148 {
9149 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
9150 if (bytes == 0)
9151 /* Success, but no bytes, means end-of-file. */
9152 break;
9153 if (bytes == -1)
9154 remote_hostio_error (remote_errno);
9155
9156 offset += bytes;
9157
9158 bytes = fwrite (buffer, 1, bytes, file);
9159 if (bytes == 0)
9160 perror_with_name (local_file);
9161 }
9162
9163 discard_cleanups (close_cleanup);
9164 if (remote_hostio_close (fd, &remote_errno))
9165 remote_hostio_error (remote_errno);
9166
9167 if (from_tty)
9168 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
9169 do_cleanups (back_to);
9170 }
9171
9172 void
9173 remote_file_delete (const char *remote_file, int from_tty)
9174 {
9175 int retcode, remote_errno;
9176
9177 if (!remote_desc)
9178 error (_("command can only be used with remote target"));
9179
9180 retcode = remote_hostio_unlink (remote_file, &remote_errno);
9181 if (retcode == -1)
9182 remote_hostio_error (remote_errno);
9183
9184 if (from_tty)
9185 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
9186 }
9187
9188 static void
9189 remote_put_command (char *args, int from_tty)
9190 {
9191 struct cleanup *back_to;
9192 char **argv;
9193
9194 if (args == NULL)
9195 error_no_arg (_("file to put"));
9196
9197 argv = gdb_buildargv (args);
9198 back_to = make_cleanup_freeargv (argv);
9199 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
9200 error (_("Invalid parameters to remote put"));
9201
9202 remote_file_put (argv[0], argv[1], from_tty);
9203
9204 do_cleanups (back_to);
9205 }
9206
9207 static void
9208 remote_get_command (char *args, int from_tty)
9209 {
9210 struct cleanup *back_to;
9211 char **argv;
9212
9213 if (args == NULL)
9214 error_no_arg (_("file to get"));
9215
9216 argv = gdb_buildargv (args);
9217 back_to = make_cleanup_freeargv (argv);
9218 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
9219 error (_("Invalid parameters to remote get"));
9220
9221 remote_file_get (argv[0], argv[1], from_tty);
9222
9223 do_cleanups (back_to);
9224 }
9225
9226 static void
9227 remote_delete_command (char *args, int from_tty)
9228 {
9229 struct cleanup *back_to;
9230 char **argv;
9231
9232 if (args == NULL)
9233 error_no_arg (_("file to delete"));
9234
9235 argv = gdb_buildargv (args);
9236 back_to = make_cleanup_freeargv (argv);
9237 if (argv[0] == NULL || argv[1] != NULL)
9238 error (_("Invalid parameters to remote delete"));
9239
9240 remote_file_delete (argv[0], from_tty);
9241
9242 do_cleanups (back_to);
9243 }
9244
9245 static void
9246 remote_command (char *args, int from_tty)
9247 {
9248 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
9249 }
9250
9251 static int
9252 remote_can_execute_reverse (void)
9253 {
9254 if (remote_protocol_packets[PACKET_bs].support == PACKET_ENABLE
9255 || remote_protocol_packets[PACKET_bc].support == PACKET_ENABLE)
9256 return 1;
9257 else
9258 return 0;
9259 }
9260
9261 static int
9262 remote_supports_non_stop (void)
9263 {
9264 return 1;
9265 }
9266
9267 static int
9268 remote_supports_multi_process (void)
9269 {
9270 struct remote_state *rs = get_remote_state ();
9271 return remote_multi_process_p (rs);
9272 }
9273
9274 int
9275 remote_supports_cond_tracepoints (void)
9276 {
9277 struct remote_state *rs = get_remote_state ();
9278 return rs->cond_tracepoints;
9279 }
9280
9281 int
9282 remote_supports_fast_tracepoints (void)
9283 {
9284 struct remote_state *rs = get_remote_state ();
9285 return rs->fast_tracepoints;
9286 }
9287
9288 static void
9289 remote_trace_init (void)
9290 {
9291 putpkt ("QTinit");
9292 remote_get_noisy_reply (&target_buf, &target_buf_size);
9293 if (strcmp (target_buf, "OK") != 0)
9294 error (_("Target does not support this command."));
9295 }
9296
9297 static void free_actions_list (char **actions_list);
9298 static void free_actions_list_cleanup_wrapper (void *);
9299 static void
9300 free_actions_list_cleanup_wrapper (void *al)
9301 {
9302 free_actions_list (al);
9303 }
9304
9305 static void
9306 free_actions_list (char **actions_list)
9307 {
9308 int ndx;
9309
9310 if (actions_list == 0)
9311 return;
9312
9313 for (ndx = 0; actions_list[ndx]; ndx++)
9314 xfree (actions_list[ndx]);
9315
9316 xfree (actions_list);
9317 }
9318
9319 /* Recursive routine to walk through command list including loops, and
9320 download packets for each command. */
9321
9322 static void
9323 remote_download_command_source (int num, ULONGEST addr,
9324 struct command_line *cmds)
9325 {
9326 struct remote_state *rs = get_remote_state ();
9327 struct command_line *cmd;
9328
9329 for (cmd = cmds; cmd; cmd = cmd->next)
9330 {
9331 QUIT; /* allow user to bail out with ^C */
9332 strcpy (rs->buf, "QTDPsrc:");
9333 encode_source_string (num, addr, "cmd", cmd->line,
9334 rs->buf + strlen (rs->buf),
9335 rs->buf_size - strlen (rs->buf));
9336 putpkt (rs->buf);
9337 remote_get_noisy_reply (&target_buf, &target_buf_size);
9338 if (strcmp (target_buf, "OK"))
9339 warning (_("Target does not support source download."));
9340
9341 if (cmd->control_type == while_control
9342 || cmd->control_type == while_stepping_control)
9343 {
9344 remote_download_command_source (num, addr, *cmd->body_list);
9345
9346 QUIT; /* allow user to bail out with ^C */
9347 strcpy (rs->buf, "QTDPsrc:");
9348 encode_source_string (num, addr, "cmd", "end",
9349 rs->buf + strlen (rs->buf),
9350 rs->buf_size - strlen (rs->buf));
9351 putpkt (rs->buf);
9352 remote_get_noisy_reply (&target_buf, &target_buf_size);
9353 if (strcmp (target_buf, "OK"))
9354 warning (_("Target does not support source download."));
9355 }
9356 }
9357 }
9358
9359 static void
9360 remote_download_tracepoint (struct breakpoint *t)
9361 {
9362 struct bp_location *loc;
9363 CORE_ADDR tpaddr;
9364 char addrbuf[40];
9365 char buf[2048];
9366 char **tdp_actions;
9367 char **stepping_actions;
9368 int ndx;
9369 struct cleanup *old_chain = NULL;
9370 struct agent_expr *aexpr;
9371 struct cleanup *aexpr_chain = NULL;
9372 char *pkt;
9373
9374 /* Iterate over all the tracepoint locations. It's up to the target to
9375 notice multiple tracepoint packets with the same number but different
9376 addresses, and treat them as multiple locations. */
9377 for (loc = t->loc; loc; loc = loc->next)
9378 {
9379 encode_actions (t, loc, &tdp_actions, &stepping_actions);
9380 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
9381 tdp_actions);
9382 (void) make_cleanup (free_actions_list_cleanup_wrapper, stepping_actions);
9383
9384 tpaddr = loc->address;
9385 sprintf_vma (addrbuf, tpaddr);
9386 sprintf (buf, "QTDP:%x:%s:%c:%lx:%x", t->number,
9387 addrbuf, /* address */
9388 (t->enable_state == bp_enabled ? 'E' : 'D'),
9389 t->step_count, t->pass_count);
9390 /* Fast tracepoints are mostly handled by the target, but we can
9391 tell the target how big of an instruction block should be moved
9392 around. */
9393 if (t->type == bp_fast_tracepoint)
9394 {
9395 /* Only test for support at download time; we may not know
9396 target capabilities at definition time. */
9397 if (remote_supports_fast_tracepoints ())
9398 {
9399 int isize;
9400
9401 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch,
9402 tpaddr, &isize, NULL))
9403 sprintf (buf + strlen (buf), ":F%x", isize);
9404 else
9405 /* If it passed validation at definition but fails now,
9406 something is very wrong. */
9407 internal_error (__FILE__, __LINE__,
9408 "Fast tracepoint not valid during download");
9409 }
9410 else
9411 /* Fast tracepoints are functionally identical to regular
9412 tracepoints, so don't take lack of support as a reason to
9413 give up on the trace run. */
9414 warning (_("Target does not support fast tracepoints, downloading %d as regular tracepoint"), t->number);
9415 }
9416 /* If the tracepoint has a conditional, make it into an agent
9417 expression and append to the definition. */
9418 if (loc->cond)
9419 {
9420 /* Only test support at download time, we may not know target
9421 capabilities at definition time. */
9422 if (remote_supports_cond_tracepoints ())
9423 {
9424 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
9425 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
9426 sprintf (buf + strlen (buf), ":X%x,", aexpr->len);
9427 pkt = buf + strlen (buf);
9428 for (ndx = 0; ndx < aexpr->len; ++ndx)
9429 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
9430 *pkt = '\0';
9431 do_cleanups (aexpr_chain);
9432 }
9433 else
9434 warning (_("Target does not support conditional tracepoints, ignoring tp %d cond"), t->number);
9435 }
9436
9437 if (t->commands || *default_collect)
9438 strcat (buf, "-");
9439 putpkt (buf);
9440 remote_get_noisy_reply (&target_buf, &target_buf_size);
9441 if (strcmp (target_buf, "OK"))
9442 error (_("Target does not support tracepoints."));
9443
9444 /* do_single_steps (t); */
9445 if (tdp_actions)
9446 {
9447 for (ndx = 0; tdp_actions[ndx]; ndx++)
9448 {
9449 QUIT; /* allow user to bail out with ^C */
9450 sprintf (buf, "QTDP:-%x:%s:%s%c",
9451 t->number, addrbuf, /* address */
9452 tdp_actions[ndx],
9453 ((tdp_actions[ndx + 1] || stepping_actions)
9454 ? '-' : 0));
9455 putpkt (buf);
9456 remote_get_noisy_reply (&target_buf,
9457 &target_buf_size);
9458 if (strcmp (target_buf, "OK"))
9459 error (_("Error on target while setting tracepoints."));
9460 }
9461 }
9462 if (stepping_actions)
9463 {
9464 for (ndx = 0; stepping_actions[ndx]; ndx++)
9465 {
9466 QUIT; /* allow user to bail out with ^C */
9467 sprintf (buf, "QTDP:-%x:%s:%s%s%s",
9468 t->number, addrbuf, /* address */
9469 ((ndx == 0) ? "S" : ""),
9470 stepping_actions[ndx],
9471 (stepping_actions[ndx + 1] ? "-" : ""));
9472 putpkt (buf);
9473 remote_get_noisy_reply (&target_buf,
9474 &target_buf_size);
9475 if (strcmp (target_buf, "OK"))
9476 error (_("Error on target while setting tracepoints."));
9477 }
9478 }
9479
9480 if (remote_protocol_packets[PACKET_TracepointSource].support == PACKET_ENABLE)
9481 {
9482 if (t->addr_string)
9483 {
9484 strcpy (buf, "QTDPsrc:");
9485 encode_source_string (t->number, loc->address,
9486 "at", t->addr_string, buf + strlen (buf),
9487 2048 - strlen (buf));
9488
9489 putpkt (buf);
9490 remote_get_noisy_reply (&target_buf, &target_buf_size);
9491 if (strcmp (target_buf, "OK"))
9492 warning (_("Target does not support source download."));
9493 }
9494 if (t->cond_string)
9495 {
9496 strcpy (buf, "QTDPsrc:");
9497 encode_source_string (t->number, loc->address,
9498 "cond", t->cond_string, buf + strlen (buf),
9499 2048 - strlen (buf));
9500 putpkt (buf);
9501 remote_get_noisy_reply (&target_buf, &target_buf_size);
9502 if (strcmp (target_buf, "OK"))
9503 warning (_("Target does not support source download."));
9504 }
9505 remote_download_command_source (t->number, loc->address,
9506 breakpoint_commands (t));
9507 }
9508
9509 do_cleanups (old_chain);
9510 }
9511 }
9512
9513 static void
9514 remote_download_trace_state_variable (struct trace_state_variable *tsv)
9515 {
9516 struct remote_state *rs = get_remote_state ();
9517 char *p;
9518
9519 sprintf (rs->buf, "QTDV:%x:%s:%x:",
9520 tsv->number, phex ((ULONGEST) tsv->initial_value, 8), tsv->builtin);
9521 p = rs->buf + strlen (rs->buf);
9522 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
9523 error (_("Trace state variable name too long for tsv definition packet"));
9524 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, 0);
9525 *p++ = '\0';
9526 putpkt (rs->buf);
9527 remote_get_noisy_reply (&target_buf, &target_buf_size);
9528 if (*target_buf == '\0')
9529 error (_("Target does not support this command."));
9530 if (strcmp (target_buf, "OK") != 0)
9531 error (_("Error on target while downloading trace state variable."));
9532 }
9533
9534 static void
9535 remote_trace_set_readonly_regions (void)
9536 {
9537 asection *s;
9538 bfd_size_type size;
9539 bfd_vma lma;
9540 int anysecs = 0;
9541
9542 if (!exec_bfd)
9543 return; /* No information to give. */
9544
9545 strcpy (target_buf, "QTro");
9546 for (s = exec_bfd->sections; s; s = s->next)
9547 {
9548 char tmp1[40], tmp2[40];
9549
9550 if ((s->flags & SEC_LOAD) == 0 ||
9551 /* (s->flags & SEC_CODE) == 0 || */
9552 (s->flags & SEC_READONLY) == 0)
9553 continue;
9554
9555 anysecs = 1;
9556 lma = s->lma;
9557 size = bfd_get_section_size (s);
9558 sprintf_vma (tmp1, lma);
9559 sprintf_vma (tmp2, lma + size);
9560 sprintf (target_buf + strlen (target_buf),
9561 ":%s,%s", tmp1, tmp2);
9562 }
9563 if (anysecs)
9564 {
9565 putpkt (target_buf);
9566 getpkt (&target_buf, &target_buf_size, 0);
9567 }
9568 }
9569
9570 static void
9571 remote_trace_start (void)
9572 {
9573 putpkt ("QTStart");
9574 remote_get_noisy_reply (&target_buf, &target_buf_size);
9575 if (*target_buf == '\0')
9576 error (_("Target does not support this command."));
9577 if (strcmp (target_buf, "OK") != 0)
9578 error (_("Bogus reply from target: %s"), target_buf);
9579 }
9580
9581 static int
9582 remote_get_trace_status (struct trace_status *ts)
9583 {
9584 char *p, *p1, *p_temp;
9585 ULONGEST val;
9586 /* FIXME we need to get register block size some other way */
9587 extern int trace_regblock_size;
9588 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
9589
9590 putpkt ("qTStatus");
9591 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
9592
9593 /* If the remote target doesn't do tracing, flag it. */
9594 if (*p == '\0')
9595 return -1;
9596
9597 /* We're working with a live target. */
9598 ts->from_file = 0;
9599
9600 /* Set some defaults. */
9601 ts->running_known = 0;
9602 ts->stop_reason = trace_stop_reason_unknown;
9603 ts->traceframe_count = -1;
9604 ts->buffer_free = 0;
9605
9606 if (*p++ != 'T')
9607 error (_("Bogus trace status reply from target: %s"), target_buf);
9608
9609 parse_trace_status (p, ts);
9610
9611 return ts->running;
9612 }
9613
9614 static void
9615 remote_trace_stop (void)
9616 {
9617 putpkt ("QTStop");
9618 remote_get_noisy_reply (&target_buf, &target_buf_size);
9619 if (*target_buf == '\0')
9620 error (_("Target does not support this command."));
9621 if (strcmp (target_buf, "OK") != 0)
9622 error (_("Bogus reply from target: %s"), target_buf);
9623 }
9624
9625 static int
9626 remote_trace_find (enum trace_find_type type, int num,
9627 ULONGEST addr1, ULONGEST addr2,
9628 int *tpp)
9629 {
9630 struct remote_state *rs = get_remote_state ();
9631 char *p, *reply;
9632 int target_frameno = -1, target_tracept = -1;
9633
9634 p = rs->buf;
9635 strcpy (p, "QTFrame:");
9636 p = strchr (p, '\0');
9637 switch (type)
9638 {
9639 case tfind_number:
9640 sprintf (p, "%x", num);
9641 break;
9642 case tfind_pc:
9643 sprintf (p, "pc:%s", phex_nz (addr1, 0));
9644 break;
9645 case tfind_tp:
9646 sprintf (p, "tdp:%x", num);
9647 break;
9648 case tfind_range:
9649 sprintf (p, "range:%s:%s", phex_nz (addr1, 0), phex_nz (addr2, 0));
9650 break;
9651 case tfind_outside:
9652 sprintf (p, "outside:%s:%s", phex_nz (addr1, 0), phex_nz (addr2, 0));
9653 break;
9654 default:
9655 error ("Unknown trace find type %d", type);
9656 }
9657
9658 putpkt (rs->buf);
9659 reply = remote_get_noisy_reply (&(rs->buf), &sizeof_pkt);
9660 if (*reply == '\0')
9661 error (_("Target does not support this command."));
9662
9663 while (reply && *reply)
9664 switch (*reply)
9665 {
9666 case 'F':
9667 p = ++reply;
9668 target_frameno = (int) strtol (p, &reply, 16);
9669 if (reply == p)
9670 error (_("Unable to parse trace frame number"));
9671 if (target_frameno == -1)
9672 return -1;
9673 break;
9674 case 'T':
9675 p = ++reply;
9676 target_tracept = (int) strtol (p, &reply, 16);
9677 if (reply == p)
9678 error (_("Unable to parse tracepoint number"));
9679 break;
9680 case 'O': /* "OK"? */
9681 if (reply[1] == 'K' && reply[2] == '\0')
9682 reply += 2;
9683 else
9684 error (_("Bogus reply from target: %s"), reply);
9685 break;
9686 default:
9687 error (_("Bogus reply from target: %s"), reply);
9688 }
9689 if (tpp)
9690 *tpp = target_tracept;
9691 return target_frameno;
9692 }
9693
9694 static int
9695 remote_get_trace_state_variable_value (int tsvnum, LONGEST *val)
9696 {
9697 struct remote_state *rs = get_remote_state ();
9698 char *reply;
9699 ULONGEST uval;
9700
9701 sprintf (rs->buf, "qTV:%x", tsvnum);
9702 putpkt (rs->buf);
9703 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9704 if (reply && *reply)
9705 {
9706 if (*reply == 'V')
9707 {
9708 unpack_varlen_hex (reply + 1, &uval);
9709 *val = (LONGEST) uval;
9710 return 1;
9711 }
9712 }
9713 return 0;
9714 }
9715
9716 static int
9717 remote_save_trace_data (const char *filename)
9718 {
9719 struct remote_state *rs = get_remote_state ();
9720 char *p, *reply;
9721
9722 p = rs->buf;
9723 strcpy (p, "QTSave:");
9724 p += strlen (p);
9725 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
9726 error (_("Remote file name too long for trace save packet"));
9727 p += 2 * bin2hex ((gdb_byte *) filename, p, 0);
9728 *p++ = '\0';
9729 putpkt (rs->buf);
9730 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9731 if (*reply != '\0')
9732 error (_("Target does not support this command."));
9733 if (strcmp (reply, "OK") != 0)
9734 error (_("Bogus reply from target: %s"), reply);
9735 return 0;
9736 }
9737
9738 /* This is basically a memory transfer, but needs to be its own packet
9739 because we don't know how the target actually organizes its trace
9740 memory, plus we want to be able to ask for as much as possible, but
9741 not be unhappy if we don't get as much as we ask for. */
9742
9743 static LONGEST
9744 remote_get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
9745 {
9746 struct remote_state *rs = get_remote_state ();
9747 char *reply;
9748 char *p;
9749 int rslt;
9750
9751 p = rs->buf;
9752 strcpy (p, "qTBuffer:");
9753 p += strlen (p);
9754 p += hexnumstr (p, offset);
9755 *p++ = ',';
9756 p += hexnumstr (p, len);
9757 *p++ = '\0';
9758
9759 putpkt (rs->buf);
9760 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9761 if (reply && *reply)
9762 {
9763 /* 'l' by itself means we're at the end of the buffer and
9764 there is nothing more to get. */
9765 if (*reply == 'l')
9766 return 0;
9767
9768 /* Convert the reply into binary. Limit the number of bytes to
9769 convert according to our passed-in buffer size, rather than
9770 what was returned in the packet; if the target is
9771 unexpectedly generous and gives us a bigger reply than we
9772 asked for, we don't want to crash. */
9773 rslt = hex2bin (target_buf, buf, len);
9774 return rslt;
9775 }
9776
9777 /* Something went wrong, flag as an error. */
9778 return -1;
9779 }
9780
9781 static void
9782 remote_set_disconnected_tracing (int val)
9783 {
9784 struct remote_state *rs = get_remote_state ();
9785
9786 if (rs->disconnected_tracing)
9787 {
9788 char *reply;
9789
9790 sprintf (rs->buf, "QTDisconnected:%x", val);
9791 putpkt (rs->buf);
9792 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9793 if (*reply == '\0')
9794 error (_("Target does not support this command."));
9795 if (strcmp (reply, "OK") != 0)
9796 error (_("Bogus reply from target: %s"), reply);
9797 }
9798 else if (val)
9799 warning (_("Target does not support disconnected tracing."));
9800 }
9801
9802 static int
9803 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
9804 {
9805 struct thread_info *info = find_thread_ptid (ptid);
9806 if (info && info->private)
9807 return info->private->core;
9808 return -1;
9809 }
9810
9811 static void
9812 remote_set_circular_trace_buffer (int val)
9813 {
9814 struct remote_state *rs = get_remote_state ();
9815 char *reply;
9816
9817 sprintf (rs->buf, "QTBuffer:circular:%x", val);
9818 putpkt (rs->buf);
9819 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9820 if (*reply == '\0')
9821 error (_("Target does not support this command."));
9822 if (strcmp (reply, "OK") != 0)
9823 error (_("Bogus reply from target: %s"), reply);
9824 }
9825
9826 static void
9827 init_remote_ops (void)
9828 {
9829 remote_ops.to_shortname = "remote";
9830 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
9831 remote_ops.to_doc =
9832 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
9833 Specify the serial device it is connected to\n\
9834 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
9835 remote_ops.to_open = remote_open;
9836 remote_ops.to_close = remote_close;
9837 remote_ops.to_detach = remote_detach;
9838 remote_ops.to_disconnect = remote_disconnect;
9839 remote_ops.to_resume = remote_resume;
9840 remote_ops.to_wait = remote_wait;
9841 remote_ops.to_fetch_registers = remote_fetch_registers;
9842 remote_ops.to_store_registers = remote_store_registers;
9843 remote_ops.to_prepare_to_store = remote_prepare_to_store;
9844 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
9845 remote_ops.to_files_info = remote_files_info;
9846 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
9847 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
9848 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
9849 remote_ops.to_stopped_data_address = remote_stopped_data_address;
9850 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
9851 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
9852 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
9853 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
9854 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
9855 remote_ops.to_kill = remote_kill;
9856 remote_ops.to_load = generic_load;
9857 remote_ops.to_mourn_inferior = remote_mourn;
9858 remote_ops.to_thread_alive = remote_thread_alive;
9859 remote_ops.to_find_new_threads = remote_threads_info;
9860 remote_ops.to_pid_to_str = remote_pid_to_str;
9861 remote_ops.to_extra_thread_info = remote_threads_extra_info;
9862 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
9863 remote_ops.to_stop = remote_stop;
9864 remote_ops.to_xfer_partial = remote_xfer_partial;
9865 remote_ops.to_rcmd = remote_rcmd;
9866 remote_ops.to_log_command = serial_log_command;
9867 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
9868 remote_ops.to_stratum = process_stratum;
9869 remote_ops.to_has_all_memory = default_child_has_all_memory;
9870 remote_ops.to_has_memory = default_child_has_memory;
9871 remote_ops.to_has_stack = default_child_has_stack;
9872 remote_ops.to_has_registers = default_child_has_registers;
9873 remote_ops.to_has_execution = default_child_has_execution;
9874 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
9875 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
9876 remote_ops.to_magic = OPS_MAGIC;
9877 remote_ops.to_memory_map = remote_memory_map;
9878 remote_ops.to_flash_erase = remote_flash_erase;
9879 remote_ops.to_flash_done = remote_flash_done;
9880 remote_ops.to_read_description = remote_read_description;
9881 remote_ops.to_search_memory = remote_search_memory;
9882 remote_ops.to_can_async_p = remote_can_async_p;
9883 remote_ops.to_is_async_p = remote_is_async_p;
9884 remote_ops.to_async = remote_async;
9885 remote_ops.to_async_mask = remote_async_mask;
9886 remote_ops.to_terminal_inferior = remote_terminal_inferior;
9887 remote_ops.to_terminal_ours = remote_terminal_ours;
9888 remote_ops.to_supports_non_stop = remote_supports_non_stop;
9889 remote_ops.to_supports_multi_process = remote_supports_multi_process;
9890 remote_ops.to_trace_init = remote_trace_init;
9891 remote_ops.to_download_tracepoint = remote_download_tracepoint;
9892 remote_ops.to_download_trace_state_variable = remote_download_trace_state_variable;
9893 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
9894 remote_ops.to_trace_start = remote_trace_start;
9895 remote_ops.to_get_trace_status = remote_get_trace_status;
9896 remote_ops.to_trace_stop = remote_trace_stop;
9897 remote_ops.to_trace_find = remote_trace_find;
9898 remote_ops.to_get_trace_state_variable_value = remote_get_trace_state_variable_value;
9899 remote_ops.to_save_trace_data = remote_save_trace_data;
9900 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
9901 remote_ops.to_upload_trace_state_variables = remote_upload_trace_state_variables;
9902 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
9903 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
9904 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
9905 remote_ops.to_core_of_thread = remote_core_of_thread;
9906 remote_ops.to_verify_memory = remote_verify_memory;
9907 }
9908
9909 /* Set up the extended remote vector by making a copy of the standard
9910 remote vector and adding to it. */
9911
9912 static void
9913 init_extended_remote_ops (void)
9914 {
9915 extended_remote_ops = remote_ops;
9916
9917 extended_remote_ops.to_shortname = "extended-remote";
9918 extended_remote_ops.to_longname =
9919 "Extended remote serial target in gdb-specific protocol";
9920 extended_remote_ops.to_doc =
9921 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
9922 Specify the serial device it is connected to (e.g. /dev/ttya).";
9923 extended_remote_ops.to_open = extended_remote_open;
9924 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
9925 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
9926 extended_remote_ops.to_detach = extended_remote_detach;
9927 extended_remote_ops.to_attach = extended_remote_attach;
9928 extended_remote_ops.to_kill = extended_remote_kill;
9929 }
9930
9931 static int
9932 remote_can_async_p (void)
9933 {
9934 if (!target_async_permitted)
9935 /* We only enable async when the user specifically asks for it. */
9936 return 0;
9937
9938 /* We're async whenever the serial device is. */
9939 return remote_async_mask_value && serial_can_async_p (remote_desc);
9940 }
9941
9942 static int
9943 remote_is_async_p (void)
9944 {
9945 if (!target_async_permitted)
9946 /* We only enable async when the user specifically asks for it. */
9947 return 0;
9948
9949 /* We're async whenever the serial device is. */
9950 return remote_async_mask_value && serial_is_async_p (remote_desc);
9951 }
9952
9953 /* Pass the SERIAL event on and up to the client. One day this code
9954 will be able to delay notifying the client of an event until the
9955 point where an entire packet has been received. */
9956
9957 static void (*async_client_callback) (enum inferior_event_type event_type,
9958 void *context);
9959 static void *async_client_context;
9960 static serial_event_ftype remote_async_serial_handler;
9961
9962 static void
9963 remote_async_serial_handler (struct serial *scb, void *context)
9964 {
9965 /* Don't propogate error information up to the client. Instead let
9966 the client find out about the error by querying the target. */
9967 async_client_callback (INF_REG_EVENT, async_client_context);
9968 }
9969
9970 static void
9971 remote_async_inferior_event_handler (gdb_client_data data)
9972 {
9973 inferior_event_handler (INF_REG_EVENT, NULL);
9974 }
9975
9976 static void
9977 remote_async_get_pending_events_handler (gdb_client_data data)
9978 {
9979 remote_get_pending_stop_replies ();
9980 }
9981
9982 static void
9983 remote_async (void (*callback) (enum inferior_event_type event_type,
9984 void *context), void *context)
9985 {
9986 if (remote_async_mask_value == 0)
9987 internal_error (__FILE__, __LINE__,
9988 _("Calling remote_async when async is masked"));
9989
9990 if (callback != NULL)
9991 {
9992 serial_async (remote_desc, remote_async_serial_handler, NULL);
9993 async_client_callback = callback;
9994 async_client_context = context;
9995 }
9996 else
9997 serial_async (remote_desc, NULL, NULL);
9998 }
9999
10000 static int
10001 remote_async_mask (int new_mask)
10002 {
10003 int curr_mask = remote_async_mask_value;
10004 remote_async_mask_value = new_mask;
10005 return curr_mask;
10006 }
10007
10008 static void
10009 set_remote_cmd (char *args, int from_tty)
10010 {
10011 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
10012 }
10013
10014 static void
10015 show_remote_cmd (char *args, int from_tty)
10016 {
10017 /* We can't just use cmd_show_list here, because we want to skip
10018 the redundant "show remote Z-packet" and the legacy aliases. */
10019 struct cleanup *showlist_chain;
10020 struct cmd_list_element *list = remote_show_cmdlist;
10021
10022 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
10023 for (; list != NULL; list = list->next)
10024 if (strcmp (list->name, "Z-packet") == 0)
10025 continue;
10026 else if (list->type == not_set_cmd)
10027 /* Alias commands are exactly like the original, except they
10028 don't have the normal type. */
10029 continue;
10030 else
10031 {
10032 struct cleanup *option_chain
10033 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
10034 ui_out_field_string (uiout, "name", list->name);
10035 ui_out_text (uiout, ": ");
10036 if (list->type == show_cmd)
10037 do_setshow_command ((char *) NULL, from_tty, list);
10038 else
10039 cmd_func (list, NULL, from_tty);
10040 /* Close the tuple. */
10041 do_cleanups (option_chain);
10042 }
10043
10044 /* Close the tuple. */
10045 do_cleanups (showlist_chain);
10046 }
10047
10048
10049 /* Function to be called whenever a new objfile (shlib) is detected. */
10050 static void
10051 remote_new_objfile (struct objfile *objfile)
10052 {
10053 if (remote_desc != 0) /* Have a remote connection. */
10054 remote_check_symbols (objfile);
10055 }
10056
10057 /* Pull all the tracepoints defined on the target and create local
10058 data structures representing them. We don't want to create real
10059 tracepoints yet, we don't want to mess up the user's existing
10060 collection. */
10061
10062 static int
10063 remote_upload_tracepoints (struct uploaded_tp **utpp)
10064 {
10065 struct remote_state *rs = get_remote_state ();
10066 char *p;
10067
10068 /* Ask for a first packet of tracepoint definition. */
10069 putpkt ("qTfP");
10070 getpkt (&rs->buf, &rs->buf_size, 0);
10071 p = rs->buf;
10072 while (*p && *p != 'l')
10073 {
10074 parse_tracepoint_definition (p, utpp);
10075 /* Ask for another packet of tracepoint definition. */
10076 putpkt ("qTsP");
10077 getpkt (&rs->buf, &rs->buf_size, 0);
10078 p = rs->buf;
10079 }
10080 return 0;
10081 }
10082
10083 static int
10084 remote_upload_trace_state_variables (struct uploaded_tsv **utsvp)
10085 {
10086 struct remote_state *rs = get_remote_state ();
10087 char *p;
10088
10089 /* Ask for a first packet of variable definition. */
10090 putpkt ("qTfV");
10091 getpkt (&rs->buf, &rs->buf_size, 0);
10092 p = rs->buf;
10093 while (*p && *p != 'l')
10094 {
10095 parse_tsv_definition (p, utsvp);
10096 /* Ask for another packet of variable definition. */
10097 putpkt ("qTsV");
10098 getpkt (&rs->buf, &rs->buf_size, 0);
10099 p = rs->buf;
10100 }
10101 return 0;
10102 }
10103
10104 void
10105 _initialize_remote (void)
10106 {
10107 struct remote_state *rs;
10108 struct cmd_list_element *cmd;
10109 char *cmd_name;
10110
10111 /* architecture specific data */
10112 remote_gdbarch_data_handle =
10113 gdbarch_data_register_post_init (init_remote_state);
10114 remote_g_packet_data_handle =
10115 gdbarch_data_register_pre_init (remote_g_packet_data_init);
10116
10117 /* Initialize the per-target state. At the moment there is only one
10118 of these, not one per target. Only one target is active at a
10119 time. The default buffer size is unimportant; it will be expanded
10120 whenever a larger buffer is needed. */
10121 rs = get_remote_state_raw ();
10122 rs->buf_size = 400;
10123 rs->buf = xmalloc (rs->buf_size);
10124
10125 init_remote_ops ();
10126 add_target (&remote_ops);
10127
10128 init_extended_remote_ops ();
10129 add_target (&extended_remote_ops);
10130
10131 /* Hook into new objfile notification. */
10132 observer_attach_new_objfile (remote_new_objfile);
10133
10134 /* Set up signal handlers. */
10135 sigint_remote_token =
10136 create_async_signal_handler (async_remote_interrupt, NULL);
10137 sigint_remote_twice_token =
10138 create_async_signal_handler (inferior_event_handler_wrapper, NULL);
10139
10140 #if 0
10141 init_remote_threadtests ();
10142 #endif
10143
10144 /* set/show remote ... */
10145
10146 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
10147 Remote protocol specific variables\n\
10148 Configure various remote-protocol specific variables such as\n\
10149 the packets being used"),
10150 &remote_set_cmdlist, "set remote ",
10151 0 /* allow-unknown */, &setlist);
10152 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
10153 Remote protocol specific variables\n\
10154 Configure various remote-protocol specific variables such as\n\
10155 the packets being used"),
10156 &remote_show_cmdlist, "show remote ",
10157 0 /* allow-unknown */, &showlist);
10158
10159 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
10160 Compare section data on target to the exec file.\n\
10161 Argument is a single section name (default: all loaded sections)."),
10162 &cmdlist);
10163
10164 add_cmd ("packet", class_maintenance, packet_command, _("\
10165 Send an arbitrary packet to a remote target.\n\
10166 maintenance packet TEXT\n\
10167 If GDB is talking to an inferior via the GDB serial protocol, then\n\
10168 this command sends the string TEXT to the inferior, and displays the\n\
10169 response packet. GDB supplies the initial `$' character, and the\n\
10170 terminating `#' character and checksum."),
10171 &maintenancelist);
10172
10173 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
10174 Set whether to send break if interrupted."), _("\
10175 Show whether to send break if interrupted."), _("\
10176 If set, a break, instead of a cntrl-c, is sent to the remote target."),
10177 set_remotebreak, show_remotebreak,
10178 &setlist, &showlist);
10179 cmd_name = "remotebreak";
10180 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
10181 deprecate_cmd (cmd, "set remote interrupt-sequence");
10182 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
10183 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
10184 deprecate_cmd (cmd, "show remote interrupt-sequence");
10185
10186 add_setshow_enum_cmd ("interrupt-sequence", class_support,
10187 interrupt_sequence_modes, &interrupt_sequence_mode, _("\
10188 Set interrupt sequence to remote target."), _("\
10189 Show interrupt sequence to remote target."), _("\
10190 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
10191 NULL, show_interrupt_sequence,
10192 &remote_set_cmdlist,
10193 &remote_show_cmdlist);
10194
10195 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
10196 &interrupt_on_connect, _("\
10197 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
10198 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
10199 If set, interrupt sequence is sent to remote target."),
10200 NULL, NULL,
10201 &remote_set_cmdlist, &remote_show_cmdlist);
10202
10203 /* Install commands for configuring memory read/write packets. */
10204
10205 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
10206 Set the maximum number of bytes per memory write packet (deprecated)."),
10207 &setlist);
10208 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
10209 Show the maximum number of bytes per memory write packet (deprecated)."),
10210 &showlist);
10211 add_cmd ("memory-write-packet-size", no_class,
10212 set_memory_write_packet_size, _("\
10213 Set the maximum number of bytes per memory-write packet.\n\
10214 Specify the number of bytes in a packet or 0 (zero) for the\n\
10215 default packet size. The actual limit is further reduced\n\
10216 dependent on the target. Specify ``fixed'' to disable the\n\
10217 further restriction and ``limit'' to enable that restriction."),
10218 &remote_set_cmdlist);
10219 add_cmd ("memory-read-packet-size", no_class,
10220 set_memory_read_packet_size, _("\
10221 Set the maximum number of bytes per memory-read packet.\n\
10222 Specify the number of bytes in a packet or 0 (zero) for the\n\
10223 default packet size. The actual limit is further reduced\n\
10224 dependent on the target. Specify ``fixed'' to disable the\n\
10225 further restriction and ``limit'' to enable that restriction."),
10226 &remote_set_cmdlist);
10227 add_cmd ("memory-write-packet-size", no_class,
10228 show_memory_write_packet_size,
10229 _("Show the maximum number of bytes per memory-write packet."),
10230 &remote_show_cmdlist);
10231 add_cmd ("memory-read-packet-size", no_class,
10232 show_memory_read_packet_size,
10233 _("Show the maximum number of bytes per memory-read packet."),
10234 &remote_show_cmdlist);
10235
10236 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
10237 &remote_hw_watchpoint_limit, _("\
10238 Set the maximum number of target hardware watchpoints."), _("\
10239 Show the maximum number of target hardware watchpoints."), _("\
10240 Specify a negative limit for unlimited."),
10241 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware watchpoints is %s. */
10242 &remote_set_cmdlist, &remote_show_cmdlist);
10243 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
10244 &remote_hw_breakpoint_limit, _("\
10245 Set the maximum number of target hardware breakpoints."), _("\
10246 Show the maximum number of target hardware breakpoints."), _("\
10247 Specify a negative limit for unlimited."),
10248 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware breakpoints is %s. */
10249 &remote_set_cmdlist, &remote_show_cmdlist);
10250
10251 add_setshow_integer_cmd ("remoteaddresssize", class_obscure,
10252 &remote_address_size, _("\
10253 Set the maximum size of the address (in bits) in a memory packet."), _("\
10254 Show the maximum size of the address (in bits) in a memory packet."), NULL,
10255 NULL,
10256 NULL, /* FIXME: i18n: */
10257 &setlist, &showlist);
10258
10259 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
10260 "X", "binary-download", 1);
10261
10262 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
10263 "vCont", "verbose-resume", 0);
10264
10265 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
10266 "QPassSignals", "pass-signals", 0);
10267
10268 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
10269 "qSymbol", "symbol-lookup", 0);
10270
10271 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
10272 "P", "set-register", 1);
10273
10274 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
10275 "p", "fetch-register", 1);
10276
10277 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
10278 "Z0", "software-breakpoint", 0);
10279
10280 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
10281 "Z1", "hardware-breakpoint", 0);
10282
10283 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
10284 "Z2", "write-watchpoint", 0);
10285
10286 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
10287 "Z3", "read-watchpoint", 0);
10288
10289 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
10290 "Z4", "access-watchpoint", 0);
10291
10292 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
10293 "qXfer:auxv:read", "read-aux-vector", 0);
10294
10295 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
10296 "qXfer:features:read", "target-features", 0);
10297
10298 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
10299 "qXfer:libraries:read", "library-info", 0);
10300
10301 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
10302 "qXfer:memory-map:read", "memory-map", 0);
10303
10304 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
10305 "qXfer:spu:read", "read-spu-object", 0);
10306
10307 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
10308 "qXfer:spu:write", "write-spu-object", 0);
10309
10310 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
10311 "qXfer:osdata:read", "osdata", 0);
10312
10313 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
10314 "qXfer:threads:read", "threads", 0);
10315
10316 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
10317 "qXfer:siginfo:read", "read-siginfo-object", 0);
10318
10319 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
10320 "qXfer:siginfo:write", "write-siginfo-object", 0);
10321
10322 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
10323 "qGetTLSAddr", "get-thread-local-storage-address",
10324 0);
10325
10326 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
10327 "bc", "reverse-continue", 0);
10328
10329 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
10330 "bs", "reverse-step", 0);
10331
10332 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
10333 "qSupported", "supported-packets", 0);
10334
10335 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
10336 "qSearch:memory", "search-memory", 0);
10337
10338 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
10339 "vFile:open", "hostio-open", 0);
10340
10341 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
10342 "vFile:pread", "hostio-pread", 0);
10343
10344 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
10345 "vFile:pwrite", "hostio-pwrite", 0);
10346
10347 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
10348 "vFile:close", "hostio-close", 0);
10349
10350 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
10351 "vFile:unlink", "hostio-unlink", 0);
10352
10353 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
10354 "vAttach", "attach", 0);
10355
10356 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
10357 "vRun", "run", 0);
10358
10359 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
10360 "QStartNoAckMode", "noack", 0);
10361
10362 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
10363 "vKill", "kill", 0);
10364
10365 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
10366 "qAttached", "query-attached", 0);
10367
10368 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
10369 "ConditionalTracepoints", "conditional-tracepoints", 0);
10370 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
10371 "FastTracepoints", "fast-tracepoints", 0);
10372
10373 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
10374 "TracepointSource", "TracepointSource", 0);
10375
10376 /* Keep the old ``set remote Z-packet ...'' working. Each individual
10377 Z sub-packet has its own set and show commands, but users may
10378 have sets to this variable in their .gdbinit files (or in their
10379 documentation). */
10380 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
10381 &remote_Z_packet_detect, _("\
10382 Set use of remote protocol `Z' packets"), _("\
10383 Show use of remote protocol `Z' packets "), _("\
10384 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
10385 packets."),
10386 set_remote_protocol_Z_packet_cmd,
10387 show_remote_protocol_Z_packet_cmd, /* FIXME: i18n: Use of remote protocol `Z' packets is %s. */
10388 &remote_set_cmdlist, &remote_show_cmdlist);
10389
10390 add_prefix_cmd ("remote", class_files, remote_command, _("\
10391 Manipulate files on the remote system\n\
10392 Transfer files to and from the remote target system."),
10393 &remote_cmdlist, "remote ",
10394 0 /* allow-unknown */, &cmdlist);
10395
10396 add_cmd ("put", class_files, remote_put_command,
10397 _("Copy a local file to the remote system."),
10398 &remote_cmdlist);
10399
10400 add_cmd ("get", class_files, remote_get_command,
10401 _("Copy a remote file to the local system."),
10402 &remote_cmdlist);
10403
10404 add_cmd ("delete", class_files, remote_delete_command,
10405 _("Delete a remote file."),
10406 &remote_cmdlist);
10407
10408 remote_exec_file = xstrdup ("");
10409 add_setshow_string_noescape_cmd ("exec-file", class_files,
10410 &remote_exec_file, _("\
10411 Set the remote pathname for \"run\""), _("\
10412 Show the remote pathname for \"run\""), NULL, NULL, NULL,
10413 &remote_set_cmdlist, &remote_show_cmdlist);
10414
10415 /* Eventually initialize fileio. See fileio.c */
10416 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
10417
10418 /* Take advantage of the fact that the LWP field is not used, to tag
10419 special ptids with it set to != 0. */
10420 magic_null_ptid = ptid_build (42000, 1, -1);
10421 not_sent_ptid = ptid_build (42000, 1, -2);
10422 any_thread_ptid = ptid_build (42000, 1, 0);
10423
10424 target_buf_size = 2048;
10425 target_buf = xmalloc (target_buf_size);
10426 }
10427