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