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