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