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