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