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