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