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