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