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