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