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