Fix several "set remote foo-packet on/off" commands.
[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. */
1071 enum auto_boolean detect;
1072
1073 /* Does the target support this packet? */
1074 enum packet_support support;
1075 };
1076
1077 /* Analyze a packet's return value and update the packet config
1078 accordingly. */
1079
1080 enum packet_result
1081 {
1082 PACKET_ERROR,
1083 PACKET_OK,
1084 PACKET_UNKNOWN
1085 };
1086
1087 static enum packet_support packet_config_support (struct packet_config *config);
1088 static enum packet_support packet_support (int packet);
1089
1090 static void
1091 show_packet_config_cmd (struct packet_config *config)
1092 {
1093 char *support = "internal-error";
1094
1095 switch (packet_config_support (config))
1096 {
1097 case PACKET_ENABLE:
1098 support = "enabled";
1099 break;
1100 case PACKET_DISABLE:
1101 support = "disabled";
1102 break;
1103 case PACKET_SUPPORT_UNKNOWN:
1104 support = "unknown";
1105 break;
1106 }
1107 switch (config->detect)
1108 {
1109 case AUTO_BOOLEAN_AUTO:
1110 printf_filtered (_("Support for the `%s' packet "
1111 "is auto-detected, currently %s.\n"),
1112 config->name, support);
1113 break;
1114 case AUTO_BOOLEAN_TRUE:
1115 case AUTO_BOOLEAN_FALSE:
1116 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1117 config->name, support);
1118 break;
1119 }
1120 }
1121
1122 static void
1123 add_packet_config_cmd (struct packet_config *config, const char *name,
1124 const char *title, int legacy)
1125 {
1126 char *set_doc;
1127 char *show_doc;
1128 char *cmd_name;
1129
1130 config->name = name;
1131 config->title = title;
1132 config->detect = AUTO_BOOLEAN_AUTO;
1133 config->support = PACKET_SUPPORT_UNKNOWN;
1134 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1135 name, title);
1136 show_doc = xstrprintf ("Show current use of remote "
1137 "protocol `%s' (%s) packet",
1138 name, title);
1139 /* set/show TITLE-packet {auto,on,off} */
1140 cmd_name = xstrprintf ("%s-packet", title);
1141 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1142 &config->detect, set_doc,
1143 show_doc, NULL, /* help_doc */
1144 NULL,
1145 show_remote_protocol_packet_cmd,
1146 &remote_set_cmdlist, &remote_show_cmdlist);
1147 /* The command code copies the documentation strings. */
1148 xfree (set_doc);
1149 xfree (show_doc);
1150 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1151 if (legacy)
1152 {
1153 char *legacy_name;
1154
1155 legacy_name = xstrprintf ("%s-packet", name);
1156 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1157 &remote_set_cmdlist);
1158 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1159 &remote_show_cmdlist);
1160 }
1161 }
1162
1163 static enum packet_result
1164 packet_check_result (const char *buf)
1165 {
1166 if (buf[0] != '\0')
1167 {
1168 /* The stub recognized the packet request. Check that the
1169 operation succeeded. */
1170 if (buf[0] == 'E'
1171 && isxdigit (buf[1]) && isxdigit (buf[2])
1172 && buf[3] == '\0')
1173 /* "Enn" - definitly an error. */
1174 return PACKET_ERROR;
1175
1176 /* Always treat "E." as an error. This will be used for
1177 more verbose error messages, such as E.memtypes. */
1178 if (buf[0] == 'E' && buf[1] == '.')
1179 return PACKET_ERROR;
1180
1181 /* The packet may or may not be OK. Just assume it is. */
1182 return PACKET_OK;
1183 }
1184 else
1185 /* The stub does not support the packet. */
1186 return PACKET_UNKNOWN;
1187 }
1188
1189 static enum packet_result
1190 packet_ok (const char *buf, struct packet_config *config)
1191 {
1192 enum packet_result result;
1193
1194 if (config->detect != AUTO_BOOLEAN_TRUE
1195 && config->support == PACKET_DISABLE)
1196 internal_error (__FILE__, __LINE__,
1197 _("packet_ok: attempt to use a disabled packet"));
1198
1199 result = packet_check_result (buf);
1200 switch (result)
1201 {
1202 case PACKET_OK:
1203 case PACKET_ERROR:
1204 /* The stub recognized the packet request. */
1205 if (config->support == PACKET_SUPPORT_UNKNOWN)
1206 {
1207 if (remote_debug)
1208 fprintf_unfiltered (gdb_stdlog,
1209 "Packet %s (%s) is supported\n",
1210 config->name, config->title);
1211 config->support = PACKET_ENABLE;
1212 }
1213 break;
1214 case PACKET_UNKNOWN:
1215 /* The stub does not support the packet. */
1216 if (config->detect == AUTO_BOOLEAN_AUTO
1217 && config->support == PACKET_ENABLE)
1218 {
1219 /* If the stub previously indicated that the packet was
1220 supported then there is a protocol error. */
1221 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1222 config->name, config->title);
1223 }
1224 else if (config->detect == AUTO_BOOLEAN_TRUE)
1225 {
1226 /* The user set it wrong. */
1227 error (_("Enabled packet %s (%s) not recognized by stub"),
1228 config->name, config->title);
1229 }
1230
1231 if (remote_debug)
1232 fprintf_unfiltered (gdb_stdlog,
1233 "Packet %s (%s) is NOT supported\n",
1234 config->name, config->title);
1235 config->support = PACKET_DISABLE;
1236 break;
1237 }
1238
1239 return result;
1240 }
1241
1242 enum {
1243 PACKET_vCont = 0,
1244 PACKET_X,
1245 PACKET_qSymbol,
1246 PACKET_P,
1247 PACKET_p,
1248 PACKET_Z0,
1249 PACKET_Z1,
1250 PACKET_Z2,
1251 PACKET_Z3,
1252 PACKET_Z4,
1253 PACKET_vFile_open,
1254 PACKET_vFile_pread,
1255 PACKET_vFile_pwrite,
1256 PACKET_vFile_close,
1257 PACKET_vFile_unlink,
1258 PACKET_vFile_readlink,
1259 PACKET_qXfer_auxv,
1260 PACKET_qXfer_features,
1261 PACKET_qXfer_libraries,
1262 PACKET_qXfer_libraries_svr4,
1263 PACKET_qXfer_memory_map,
1264 PACKET_qXfer_spu_read,
1265 PACKET_qXfer_spu_write,
1266 PACKET_qXfer_osdata,
1267 PACKET_qXfer_threads,
1268 PACKET_qXfer_statictrace_read,
1269 PACKET_qXfer_traceframe_info,
1270 PACKET_qXfer_uib,
1271 PACKET_qGetTIBAddr,
1272 PACKET_qGetTLSAddr,
1273 PACKET_qSupported,
1274 PACKET_qTStatus,
1275 PACKET_QPassSignals,
1276 PACKET_QProgramSignals,
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 /* Generic code for opening a connection to a remote target. */
3636
3637 static void
3638 init_all_packet_configs (void)
3639 {
3640 int i;
3641
3642 for (i = 0; i < PACKET_MAX; i++)
3643 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3644 }
3645
3646 /* Symbol look-up. */
3647
3648 static void
3649 remote_check_symbols (void)
3650 {
3651 struct remote_state *rs = get_remote_state ();
3652 char *msg, *reply, *tmp;
3653 struct bound_minimal_symbol sym;
3654 int end;
3655
3656 /* The remote side has no concept of inferiors that aren't running
3657 yet, it only knows about running processes. If we're connected
3658 but our current inferior is not running, we should not invite the
3659 remote target to request symbol lookups related to its
3660 (unrelated) current process. */
3661 if (!target_has_execution)
3662 return;
3663
3664 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
3665 return;
3666
3667 /* Make sure the remote is pointing at the right process. Note
3668 there's no way to select "no process". */
3669 set_general_process ();
3670
3671 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3672 because we need both at the same time. */
3673 msg = alloca (get_remote_packet_size ());
3674
3675 /* Invite target to request symbol lookups. */
3676
3677 putpkt ("qSymbol::");
3678 getpkt (&rs->buf, &rs->buf_size, 0);
3679 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
3680 reply = rs->buf;
3681
3682 while (strncmp (reply, "qSymbol:", 8) == 0)
3683 {
3684 struct bound_minimal_symbol sym;
3685
3686 tmp = &reply[8];
3687 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
3688 msg[end] = '\0';
3689 sym = lookup_minimal_symbol (msg, NULL, NULL);
3690 if (sym.minsym == NULL)
3691 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
3692 else
3693 {
3694 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
3695 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
3696
3697 /* If this is a function address, return the start of code
3698 instead of any data function descriptor. */
3699 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
3700 sym_addr,
3701 &current_target);
3702
3703 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
3704 phex_nz (sym_addr, addr_size), &reply[8]);
3705 }
3706
3707 putpkt (msg);
3708 getpkt (&rs->buf, &rs->buf_size, 0);
3709 reply = rs->buf;
3710 }
3711 }
3712
3713 static struct serial *
3714 remote_serial_open (char *name)
3715 {
3716 static int udp_warning = 0;
3717
3718 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3719 of in ser-tcp.c, because it is the remote protocol assuming that the
3720 serial connection is reliable and not the serial connection promising
3721 to be. */
3722 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
3723 {
3724 warning (_("The remote protocol may be unreliable over UDP.\n"
3725 "Some events may be lost, rendering further debugging "
3726 "impossible."));
3727 udp_warning = 1;
3728 }
3729
3730 return serial_open (name);
3731 }
3732
3733 /* Inform the target of our permission settings. The permission flags
3734 work without this, but if the target knows the settings, it can do
3735 a couple things. First, it can add its own check, to catch cases
3736 that somehow manage to get by the permissions checks in target
3737 methods. Second, if the target is wired to disallow particular
3738 settings (for instance, a system in the field that is not set up to
3739 be able to stop at a breakpoint), it can object to any unavailable
3740 permissions. */
3741
3742 void
3743 remote_set_permissions (struct target_ops *self)
3744 {
3745 struct remote_state *rs = get_remote_state ();
3746
3747 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3748 "WriteReg:%x;WriteMem:%x;"
3749 "InsertBreak:%x;InsertTrace:%x;"
3750 "InsertFastTrace:%x;Stop:%x",
3751 may_write_registers, may_write_memory,
3752 may_insert_breakpoints, may_insert_tracepoints,
3753 may_insert_fast_tracepoints, may_stop);
3754 putpkt (rs->buf);
3755 getpkt (&rs->buf, &rs->buf_size, 0);
3756
3757 /* If the target didn't like the packet, warn the user. Do not try
3758 to undo the user's settings, that would just be maddening. */
3759 if (strcmp (rs->buf, "OK") != 0)
3760 warning (_("Remote refused setting permissions with: %s"), rs->buf);
3761 }
3762
3763 /* This type describes each known response to the qSupported
3764 packet. */
3765 struct protocol_feature
3766 {
3767 /* The name of this protocol feature. */
3768 const char *name;
3769
3770 /* The default for this protocol feature. */
3771 enum packet_support default_support;
3772
3773 /* The function to call when this feature is reported, or after
3774 qSupported processing if the feature is not supported.
3775 The first argument points to this structure. The second
3776 argument indicates whether the packet requested support be
3777 enabled, disabled, or probed (or the default, if this function
3778 is being called at the end of processing and this feature was
3779 not reported). The third argument may be NULL; if not NULL, it
3780 is a NUL-terminated string taken from the packet following
3781 this feature's name and an equals sign. */
3782 void (*func) (const struct protocol_feature *, enum packet_support,
3783 const char *);
3784
3785 /* The corresponding packet for this feature. Only used if
3786 FUNC is remote_supported_packet. */
3787 int packet;
3788 };
3789
3790 static void
3791 remote_supported_packet (const struct protocol_feature *feature,
3792 enum packet_support support,
3793 const char *argument)
3794 {
3795 if (argument)
3796 {
3797 warning (_("Remote qSupported response supplied an unexpected value for"
3798 " \"%s\"."), feature->name);
3799 return;
3800 }
3801
3802 remote_protocol_packets[feature->packet].support = support;
3803 }
3804
3805 static void
3806 remote_packet_size (const struct protocol_feature *feature,
3807 enum packet_support support, const char *value)
3808 {
3809 struct remote_state *rs = get_remote_state ();
3810
3811 int packet_size;
3812 char *value_end;
3813
3814 if (support != PACKET_ENABLE)
3815 return;
3816
3817 if (value == NULL || *value == '\0')
3818 {
3819 warning (_("Remote target reported \"%s\" without a size."),
3820 feature->name);
3821 return;
3822 }
3823
3824 errno = 0;
3825 packet_size = strtol (value, &value_end, 16);
3826 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3827 {
3828 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3829 feature->name, value);
3830 return;
3831 }
3832
3833 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3834 {
3835 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3836 packet_size, MAX_REMOTE_PACKET_SIZE);
3837 packet_size = MAX_REMOTE_PACKET_SIZE;
3838 }
3839
3840 /* Record the new maximum packet size. */
3841 rs->explicit_packet_size = packet_size;
3842 }
3843
3844 static const struct protocol_feature remote_protocol_features[] = {
3845 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
3846 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
3847 PACKET_qXfer_auxv },
3848 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3849 PACKET_qXfer_features },
3850 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3851 PACKET_qXfer_libraries },
3852 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
3853 PACKET_qXfer_libraries_svr4 },
3854 { "augmented-libraries-svr4-read", PACKET_DISABLE,
3855 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
3856 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
3857 PACKET_qXfer_memory_map },
3858 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3859 PACKET_qXfer_spu_read },
3860 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3861 PACKET_qXfer_spu_write },
3862 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3863 PACKET_qXfer_osdata },
3864 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
3865 PACKET_qXfer_threads },
3866 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
3867 PACKET_qXfer_traceframe_info },
3868 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3869 PACKET_QPassSignals },
3870 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
3871 PACKET_QProgramSignals },
3872 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
3873 PACKET_QStartNoAckMode },
3874 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
3875 PACKET_multiprocess_feature },
3876 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
3877 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
3878 PACKET_qXfer_siginfo_read },
3879 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
3880 PACKET_qXfer_siginfo_write },
3881 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
3882 PACKET_ConditionalTracepoints },
3883 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3884 PACKET_ConditionalBreakpoints },
3885 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
3886 PACKET_BreakpointCommands },
3887 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
3888 PACKET_FastTracepoints },
3889 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
3890 PACKET_StaticTracepoints },
3891 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
3892 PACKET_InstallInTrace},
3893 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
3894 PACKET_DisconnectedTracing_feature },
3895 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
3896 PACKET_bc },
3897 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
3898 PACKET_bs },
3899 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
3900 PACKET_TracepointSource },
3901 { "QAllow", PACKET_DISABLE, remote_supported_packet,
3902 PACKET_QAllow },
3903 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
3904 PACKET_EnableDisableTracepoints_feature },
3905 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
3906 PACKET_qXfer_fdpic },
3907 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
3908 PACKET_qXfer_uib },
3909 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
3910 PACKET_QDisableRandomization },
3911 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
3912 { "QTBuffer:size", PACKET_DISABLE,
3913 remote_supported_packet, PACKET_QTBuffer_size},
3914 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
3915 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
3916 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
3917 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
3918 PACKET_qXfer_btrace }
3919 };
3920
3921 static char *remote_support_xml;
3922
3923 /* Register string appended to "xmlRegisters=" in qSupported query. */
3924
3925 void
3926 register_remote_support_xml (const char *xml)
3927 {
3928 #if defined(HAVE_LIBEXPAT)
3929 if (remote_support_xml == NULL)
3930 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
3931 else
3932 {
3933 char *copy = xstrdup (remote_support_xml + 13);
3934 char *p = strtok (copy, ",");
3935
3936 do
3937 {
3938 if (strcmp (p, xml) == 0)
3939 {
3940 /* already there */
3941 xfree (copy);
3942 return;
3943 }
3944 }
3945 while ((p = strtok (NULL, ",")) != NULL);
3946 xfree (copy);
3947
3948 remote_support_xml = reconcat (remote_support_xml,
3949 remote_support_xml, ",", xml,
3950 (char *) NULL);
3951 }
3952 #endif
3953 }
3954
3955 static char *
3956 remote_query_supported_append (char *msg, const char *append)
3957 {
3958 if (msg)
3959 return reconcat (msg, msg, ";", append, (char *) NULL);
3960 else
3961 return xstrdup (append);
3962 }
3963
3964 static void
3965 remote_query_supported (void)
3966 {
3967 struct remote_state *rs = get_remote_state ();
3968 char *next;
3969 int i;
3970 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
3971
3972 /* The packet support flags are handled differently for this packet
3973 than for most others. We treat an error, a disabled packet, and
3974 an empty response identically: any features which must be reported
3975 to be used will be automatically disabled. An empty buffer
3976 accomplishes this, since that is also the representation for a list
3977 containing no features. */
3978
3979 rs->buf[0] = 0;
3980 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
3981 {
3982 char *q = NULL;
3983 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
3984
3985 q = remote_query_supported_append (q, "multiprocess+");
3986
3987 if (remote_support_xml)
3988 q = remote_query_supported_append (q, remote_support_xml);
3989
3990 q = remote_query_supported_append (q, "qRelocInsn+");
3991
3992 q = reconcat (q, "qSupported:", q, (char *) NULL);
3993 putpkt (q);
3994
3995 do_cleanups (old_chain);
3996
3997 getpkt (&rs->buf, &rs->buf_size, 0);
3998
3999 /* If an error occured, warn, but do not return - just reset the
4000 buffer to empty and go on to disable features. */
4001 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4002 == PACKET_ERROR)
4003 {
4004 warning (_("Remote failure reply: %s"), rs->buf);
4005 rs->buf[0] = 0;
4006 }
4007 }
4008
4009 memset (seen, 0, sizeof (seen));
4010
4011 next = rs->buf;
4012 while (*next)
4013 {
4014 enum packet_support is_supported;
4015 char *p, *end, *name_end, *value;
4016
4017 /* First separate out this item from the rest of the packet. If
4018 there's another item after this, we overwrite the separator
4019 (terminated strings are much easier to work with). */
4020 p = next;
4021 end = strchr (p, ';');
4022 if (end == NULL)
4023 {
4024 end = p + strlen (p);
4025 next = end;
4026 }
4027 else
4028 {
4029 *end = '\0';
4030 next = end + 1;
4031
4032 if (end == p)
4033 {
4034 warning (_("empty item in \"qSupported\" response"));
4035 continue;
4036 }
4037 }
4038
4039 name_end = strchr (p, '=');
4040 if (name_end)
4041 {
4042 /* This is a name=value entry. */
4043 is_supported = PACKET_ENABLE;
4044 value = name_end + 1;
4045 *name_end = '\0';
4046 }
4047 else
4048 {
4049 value = NULL;
4050 switch (end[-1])
4051 {
4052 case '+':
4053 is_supported = PACKET_ENABLE;
4054 break;
4055
4056 case '-':
4057 is_supported = PACKET_DISABLE;
4058 break;
4059
4060 case '?':
4061 is_supported = PACKET_SUPPORT_UNKNOWN;
4062 break;
4063
4064 default:
4065 warning (_("unrecognized item \"%s\" "
4066 "in \"qSupported\" response"), p);
4067 continue;
4068 }
4069 end[-1] = '\0';
4070 }
4071
4072 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4073 if (strcmp (remote_protocol_features[i].name, p) == 0)
4074 {
4075 const struct protocol_feature *feature;
4076
4077 seen[i] = 1;
4078 feature = &remote_protocol_features[i];
4079 feature->func (feature, is_supported, value);
4080 break;
4081 }
4082 }
4083
4084 /* If we increased the packet size, make sure to increase the global
4085 buffer size also. We delay this until after parsing the entire
4086 qSupported packet, because this is the same buffer we were
4087 parsing. */
4088 if (rs->buf_size < rs->explicit_packet_size)
4089 {
4090 rs->buf_size = rs->explicit_packet_size;
4091 rs->buf = xrealloc (rs->buf, rs->buf_size);
4092 }
4093
4094 /* Handle the defaults for unmentioned features. */
4095 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4096 if (!seen[i])
4097 {
4098 const struct protocol_feature *feature;
4099
4100 feature = &remote_protocol_features[i];
4101 feature->func (feature, feature->default_support, NULL);
4102 }
4103 }
4104
4105 /* Remove any of the remote.c targets from target stack. Upper targets depend
4106 on it so remove them first. */
4107
4108 static void
4109 remote_unpush_target (void)
4110 {
4111 pop_all_targets_above (process_stratum - 1);
4112 }
4113
4114 static void
4115 remote_open_1 (char *name, int from_tty,
4116 struct target_ops *target, int extended_p)
4117 {
4118 struct remote_state *rs = get_remote_state ();
4119
4120 if (name == 0)
4121 error (_("To open a remote debug connection, you need to specify what\n"
4122 "serial device is attached to the remote system\n"
4123 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4124
4125 /* See FIXME above. */
4126 if (!target_async_permitted)
4127 wait_forever_enabled_p = 1;
4128
4129 /* If we're connected to a running target, target_preopen will kill it.
4130 Ask this question first, before target_preopen has a chance to kill
4131 anything. */
4132 if (rs->remote_desc != NULL && !have_inferiors ())
4133 {
4134 if (from_tty
4135 && !query (_("Already connected to a remote target. Disconnect? ")))
4136 error (_("Still connected."));
4137 }
4138
4139 /* Here the possibly existing remote target gets unpushed. */
4140 target_preopen (from_tty);
4141
4142 /* Make sure we send the passed signals list the next time we resume. */
4143 xfree (rs->last_pass_packet);
4144 rs->last_pass_packet = NULL;
4145
4146 /* Make sure we send the program signals list the next time we
4147 resume. */
4148 xfree (rs->last_program_signals_packet);
4149 rs->last_program_signals_packet = NULL;
4150
4151 remote_fileio_reset ();
4152 reopen_exec_file ();
4153 reread_symbols ();
4154
4155 rs->remote_desc = remote_serial_open (name);
4156 if (!rs->remote_desc)
4157 perror_with_name (name);
4158
4159 if (baud_rate != -1)
4160 {
4161 if (serial_setbaudrate (rs->remote_desc, baud_rate))
4162 {
4163 /* The requested speed could not be set. Error out to
4164 top level after closing remote_desc. Take care to
4165 set remote_desc to NULL to avoid closing remote_desc
4166 more than once. */
4167 serial_close (rs->remote_desc);
4168 rs->remote_desc = NULL;
4169 perror_with_name (name);
4170 }
4171 }
4172
4173 serial_raw (rs->remote_desc);
4174
4175 /* If there is something sitting in the buffer we might take it as a
4176 response to a command, which would be bad. */
4177 serial_flush_input (rs->remote_desc);
4178
4179 if (from_tty)
4180 {
4181 puts_filtered ("Remote debugging using ");
4182 puts_filtered (name);
4183 puts_filtered ("\n");
4184 }
4185 push_target (target); /* Switch to using remote target now. */
4186
4187 /* Register extra event sources in the event loop. */
4188 remote_async_inferior_event_token
4189 = create_async_event_handler (remote_async_inferior_event_handler,
4190 NULL);
4191 rs->notif_state = remote_notif_state_allocate ();
4192
4193 /* Reset the target state; these things will be queried either by
4194 remote_query_supported or as they are needed. */
4195 init_all_packet_configs ();
4196 rs->cached_wait_status = 0;
4197 rs->explicit_packet_size = 0;
4198 rs->noack_mode = 0;
4199 rs->extended = extended_p;
4200 rs->waiting_for_stop_reply = 0;
4201 rs->ctrlc_pending_p = 0;
4202
4203 rs->general_thread = not_sent_ptid;
4204 rs->continue_thread = not_sent_ptid;
4205 rs->remote_traceframe_number = -1;
4206
4207 /* Probe for ability to use "ThreadInfo" query, as required. */
4208 rs->use_threadinfo_query = 1;
4209 rs->use_threadextra_query = 1;
4210
4211 if (target_async_permitted)
4212 {
4213 /* With this target we start out by owning the terminal. */
4214 remote_async_terminal_ours_p = 1;
4215
4216 /* FIXME: cagney/1999-09-23: During the initial connection it is
4217 assumed that the target is already ready and able to respond to
4218 requests. Unfortunately remote_start_remote() eventually calls
4219 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4220 around this. Eventually a mechanism that allows
4221 wait_for_inferior() to expect/get timeouts will be
4222 implemented. */
4223 wait_forever_enabled_p = 0;
4224 }
4225
4226 /* First delete any symbols previously loaded from shared libraries. */
4227 no_shared_libraries (NULL, 0);
4228
4229 /* Start afresh. */
4230 init_thread_list ();
4231
4232 /* Start the remote connection. If error() or QUIT, discard this
4233 target (we'd otherwise be in an inconsistent state) and then
4234 propogate the error on up the exception chain. This ensures that
4235 the caller doesn't stumble along blindly assuming that the
4236 function succeeded. The CLI doesn't have this problem but other
4237 UI's, such as MI do.
4238
4239 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4240 this function should return an error indication letting the
4241 caller restore the previous state. Unfortunately the command
4242 ``target remote'' is directly wired to this function making that
4243 impossible. On a positive note, the CLI side of this problem has
4244 been fixed - the function set_cmd_context() makes it possible for
4245 all the ``target ....'' commands to share a common callback
4246 function. See cli-dump.c. */
4247 {
4248 volatile struct gdb_exception ex;
4249
4250 TRY_CATCH (ex, RETURN_MASK_ALL)
4251 {
4252 remote_start_remote (from_tty, target, extended_p);
4253 }
4254 if (ex.reason < 0)
4255 {
4256 /* Pop the partially set up target - unless something else did
4257 already before throwing the exception. */
4258 if (rs->remote_desc != NULL)
4259 remote_unpush_target ();
4260 if (target_async_permitted)
4261 wait_forever_enabled_p = 1;
4262 throw_exception (ex);
4263 }
4264 }
4265
4266 if (target_async_permitted)
4267 wait_forever_enabled_p = 1;
4268 }
4269
4270 /* This takes a program previously attached to and detaches it. After
4271 this is done, GDB can be used to debug some other program. We
4272 better not have left any breakpoints in the target program or it'll
4273 die when it hits one. */
4274
4275 static void
4276 remote_detach_1 (const char *args, int from_tty, int extended)
4277 {
4278 int pid = ptid_get_pid (inferior_ptid);
4279 struct remote_state *rs = get_remote_state ();
4280
4281 if (args)
4282 error (_("Argument given to \"detach\" when remotely debugging."));
4283
4284 if (!target_has_execution)
4285 error (_("No process to detach from."));
4286
4287 if (from_tty)
4288 {
4289 char *exec_file = get_exec_file (0);
4290 if (exec_file == NULL)
4291 exec_file = "";
4292 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4293 target_pid_to_str (pid_to_ptid (pid)));
4294 gdb_flush (gdb_stdout);
4295 }
4296
4297 /* Tell the remote target to detach. */
4298 if (remote_multi_process_p (rs))
4299 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4300 else
4301 strcpy (rs->buf, "D");
4302
4303 putpkt (rs->buf);
4304 getpkt (&rs->buf, &rs->buf_size, 0);
4305
4306 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4307 ;
4308 else if (rs->buf[0] == '\0')
4309 error (_("Remote doesn't know how to detach"));
4310 else
4311 error (_("Can't detach process."));
4312
4313 if (from_tty && !extended)
4314 puts_filtered (_("Ending remote debugging.\n"));
4315
4316 target_mourn_inferior ();
4317 }
4318
4319 static void
4320 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4321 {
4322 remote_detach_1 (args, from_tty, 0);
4323 }
4324
4325 static void
4326 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
4327 {
4328 remote_detach_1 (args, from_tty, 1);
4329 }
4330
4331 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4332
4333 static void
4334 remote_disconnect (struct target_ops *target, char *args, int from_tty)
4335 {
4336 if (args)
4337 error (_("Argument given to \"disconnect\" when remotely debugging."));
4338
4339 /* Make sure we unpush even the extended remote targets; mourn
4340 won't do it. So call remote_mourn_1 directly instead of
4341 target_mourn_inferior. */
4342 remote_mourn_1 (target);
4343
4344 if (from_tty)
4345 puts_filtered ("Ending remote debugging.\n");
4346 }
4347
4348 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4349 be chatty about it. */
4350
4351 static void
4352 extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
4353 {
4354 struct remote_state *rs = get_remote_state ();
4355 int pid;
4356 char *wait_status = NULL;
4357
4358 pid = parse_pid_to_attach (args);
4359
4360 /* Remote PID can be freely equal to getpid, do not check it here the same
4361 way as in other targets. */
4362
4363 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
4364 error (_("This target does not support attaching to a process"));
4365
4366 if (from_tty)
4367 {
4368 char *exec_file = get_exec_file (0);
4369
4370 if (exec_file)
4371 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4372 target_pid_to_str (pid_to_ptid (pid)));
4373 else
4374 printf_unfiltered (_("Attaching to %s\n"),
4375 target_pid_to_str (pid_to_ptid (pid)));
4376
4377 gdb_flush (gdb_stdout);
4378 }
4379
4380 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
4381 putpkt (rs->buf);
4382 getpkt (&rs->buf, &rs->buf_size, 0);
4383
4384 switch (packet_ok (rs->buf,
4385 &remote_protocol_packets[PACKET_vAttach]))
4386 {
4387 case PACKET_OK:
4388 if (!non_stop)
4389 {
4390 /* Save the reply for later. */
4391 wait_status = alloca (strlen (rs->buf) + 1);
4392 strcpy (wait_status, rs->buf);
4393 }
4394 else if (strcmp (rs->buf, "OK") != 0)
4395 error (_("Attaching to %s failed with: %s"),
4396 target_pid_to_str (pid_to_ptid (pid)),
4397 rs->buf);
4398 break;
4399 case PACKET_UNKNOWN:
4400 error (_("This target does not support attaching to a process"));
4401 default:
4402 error (_("Attaching to %s failed"),
4403 target_pid_to_str (pid_to_ptid (pid)));
4404 }
4405
4406 set_current_inferior (remote_add_inferior (0, pid, 1));
4407
4408 inferior_ptid = pid_to_ptid (pid);
4409
4410 if (non_stop)
4411 {
4412 struct thread_info *thread;
4413
4414 /* Get list of threads. */
4415 remote_threads_info (target);
4416
4417 thread = first_thread_of_process (pid);
4418 if (thread)
4419 inferior_ptid = thread->ptid;
4420 else
4421 inferior_ptid = pid_to_ptid (pid);
4422
4423 /* Invalidate our notion of the remote current thread. */
4424 record_currthread (rs, minus_one_ptid);
4425 }
4426 else
4427 {
4428 /* Now, if we have thread information, update inferior_ptid. */
4429 inferior_ptid = remote_current_thread (inferior_ptid);
4430
4431 /* Add the main thread to the thread list. */
4432 add_thread_silent (inferior_ptid);
4433 }
4434
4435 /* Next, if the target can specify a description, read it. We do
4436 this before anything involving memory or registers. */
4437 target_find_description ();
4438
4439 if (!non_stop)
4440 {
4441 /* Use the previously fetched status. */
4442 gdb_assert (wait_status != NULL);
4443
4444 if (target_can_async_p ())
4445 {
4446 struct notif_event *reply
4447 = remote_notif_parse (&notif_client_stop, wait_status);
4448
4449 push_stop_reply ((struct stop_reply *) reply);
4450
4451 target_async (inferior_event_handler, 0);
4452 }
4453 else
4454 {
4455 gdb_assert (wait_status != NULL);
4456 strcpy (rs->buf, wait_status);
4457 rs->cached_wait_status = 1;
4458 }
4459 }
4460 else
4461 gdb_assert (wait_status == NULL);
4462 }
4463
4464 static void
4465 extended_remote_attach (struct target_ops *ops, char *args, int from_tty)
4466 {
4467 extended_remote_attach_1 (ops, args, from_tty);
4468 }
4469
4470 \f
4471 /* Check for the availability of vCont. This function should also check
4472 the response. */
4473
4474 static void
4475 remote_vcont_probe (struct remote_state *rs)
4476 {
4477 char *buf;
4478
4479 strcpy (rs->buf, "vCont?");
4480 putpkt (rs->buf);
4481 getpkt (&rs->buf, &rs->buf_size, 0);
4482 buf = rs->buf;
4483
4484 /* Make sure that the features we assume are supported. */
4485 if (strncmp (buf, "vCont", 5) == 0)
4486 {
4487 char *p = &buf[5];
4488 int support_s, support_S, support_c, support_C;
4489
4490 support_s = 0;
4491 support_S = 0;
4492 support_c = 0;
4493 support_C = 0;
4494 rs->supports_vCont.t = 0;
4495 rs->supports_vCont.r = 0;
4496 while (p && *p == ';')
4497 {
4498 p++;
4499 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4500 support_s = 1;
4501 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4502 support_S = 1;
4503 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4504 support_c = 1;
4505 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4506 support_C = 1;
4507 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4508 rs->supports_vCont.t = 1;
4509 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4510 rs->supports_vCont.r = 1;
4511
4512 p = strchr (p, ';');
4513 }
4514
4515 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4516 BUF will make packet_ok disable the packet. */
4517 if (!support_s || !support_S || !support_c || !support_C)
4518 buf[0] = 0;
4519 }
4520
4521 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4522 }
4523
4524 /* Helper function for building "vCont" resumptions. Write a
4525 resumption to P. ENDP points to one-passed-the-end of the buffer
4526 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4527 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4528 resumed thread should be single-stepped and/or signalled. If PTID
4529 equals minus_one_ptid, then all threads are resumed; if PTID
4530 represents a process, then all threads of the process are resumed;
4531 the thread to be stepped and/or signalled is given in the global
4532 INFERIOR_PTID. */
4533
4534 static char *
4535 append_resumption (char *p, char *endp,
4536 ptid_t ptid, int step, enum gdb_signal siggnal)
4537 {
4538 struct remote_state *rs = get_remote_state ();
4539
4540 if (step && siggnal != GDB_SIGNAL_0)
4541 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4542 else if (step
4543 /* GDB is willing to range step. */
4544 && use_range_stepping
4545 /* Target supports range stepping. */
4546 && rs->supports_vCont.r
4547 /* We don't currently support range stepping multiple
4548 threads with a wildcard (though the protocol allows it,
4549 so stubs shouldn't make an active effort to forbid
4550 it). */
4551 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4552 {
4553 struct thread_info *tp;
4554
4555 if (ptid_equal (ptid, minus_one_ptid))
4556 {
4557 /* If we don't know about the target thread's tid, then
4558 we're resuming magic_null_ptid (see caller). */
4559 tp = find_thread_ptid (magic_null_ptid);
4560 }
4561 else
4562 tp = find_thread_ptid (ptid);
4563 gdb_assert (tp != NULL);
4564
4565 if (tp->control.may_range_step)
4566 {
4567 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4568
4569 p += xsnprintf (p, endp - p, ";r%s,%s",
4570 phex_nz (tp->control.step_range_start,
4571 addr_size),
4572 phex_nz (tp->control.step_range_end,
4573 addr_size));
4574 }
4575 else
4576 p += xsnprintf (p, endp - p, ";s");
4577 }
4578 else if (step)
4579 p += xsnprintf (p, endp - p, ";s");
4580 else if (siggnal != GDB_SIGNAL_0)
4581 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4582 else
4583 p += xsnprintf (p, endp - p, ";c");
4584
4585 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4586 {
4587 ptid_t nptid;
4588
4589 /* All (-1) threads of process. */
4590 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
4591
4592 p += xsnprintf (p, endp - p, ":");
4593 p = write_ptid (p, endp, nptid);
4594 }
4595 else if (!ptid_equal (ptid, minus_one_ptid))
4596 {
4597 p += xsnprintf (p, endp - p, ":");
4598 p = write_ptid (p, endp, ptid);
4599 }
4600
4601 return p;
4602 }
4603
4604 /* Append a vCont continue-with-signal action for threads that have a
4605 non-zero stop signal. */
4606
4607 static char *
4608 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4609 {
4610 struct thread_info *thread;
4611
4612 ALL_THREADS (thread)
4613 if (ptid_match (thread->ptid, ptid)
4614 && !ptid_equal (inferior_ptid, thread->ptid)
4615 && thread->suspend.stop_signal != GDB_SIGNAL_0
4616 && signal_pass_state (thread->suspend.stop_signal))
4617 {
4618 p = append_resumption (p, endp, thread->ptid,
4619 0, thread->suspend.stop_signal);
4620 thread->suspend.stop_signal = GDB_SIGNAL_0;
4621 }
4622
4623 return p;
4624 }
4625
4626 /* Resume the remote inferior by using a "vCont" packet. The thread
4627 to be resumed is PTID; STEP and SIGGNAL indicate whether the
4628 resumed thread should be single-stepped and/or signalled. If PTID
4629 equals minus_one_ptid, then all threads are resumed; the thread to
4630 be stepped and/or signalled is given in the global INFERIOR_PTID.
4631 This function returns non-zero iff it resumes the inferior.
4632
4633 This function issues a strict subset of all possible vCont commands at the
4634 moment. */
4635
4636 static int
4637 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
4638 {
4639 struct remote_state *rs = get_remote_state ();
4640 char *p;
4641 char *endp;
4642
4643 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
4644 remote_vcont_probe (rs);
4645
4646 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
4647 return 0;
4648
4649 p = rs->buf;
4650 endp = rs->buf + get_remote_packet_size ();
4651
4652 /* If we could generate a wider range of packets, we'd have to worry
4653 about overflowing BUF. Should there be a generic
4654 "multi-part-packet" packet? */
4655
4656 p += xsnprintf (p, endp - p, "vCont");
4657
4658 if (ptid_equal (ptid, magic_null_ptid))
4659 {
4660 /* MAGIC_NULL_PTID means that we don't have any active threads,
4661 so we don't have any TID numbers the inferior will
4662 understand. Make sure to only send forms that do not specify
4663 a TID. */
4664 append_resumption (p, endp, minus_one_ptid, step, siggnal);
4665 }
4666 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
4667 {
4668 /* Resume all threads (of all processes, or of a single
4669 process), with preference for INFERIOR_PTID. This assumes
4670 inferior_ptid belongs to the set of all threads we are about
4671 to resume. */
4672 if (step || siggnal != GDB_SIGNAL_0)
4673 {
4674 /* Step inferior_ptid, with or without signal. */
4675 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
4676 }
4677
4678 /* Also pass down any pending signaled resumption for other
4679 threads not the current. */
4680 p = append_pending_thread_resumptions (p, endp, ptid);
4681
4682 /* And continue others without a signal. */
4683 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
4684 }
4685 else
4686 {
4687 /* Scheduler locking; resume only PTID. */
4688 append_resumption (p, endp, ptid, step, siggnal);
4689 }
4690
4691 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4692 putpkt (rs->buf);
4693
4694 if (non_stop)
4695 {
4696 /* In non-stop, the stub replies to vCont with "OK". The stop
4697 reply will be reported asynchronously by means of a `%Stop'
4698 notification. */
4699 getpkt (&rs->buf, &rs->buf_size, 0);
4700 if (strcmp (rs->buf, "OK") != 0)
4701 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4702 }
4703
4704 return 1;
4705 }
4706
4707 /* Tell the remote machine to resume. */
4708
4709 static void
4710 remote_resume (struct target_ops *ops,
4711 ptid_t ptid, int step, enum gdb_signal siggnal)
4712 {
4713 struct remote_state *rs = get_remote_state ();
4714 char *buf;
4715
4716 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
4717 (explained in remote-notif.c:handle_notification) so
4718 remote_notif_process is not called. We need find a place where
4719 it is safe to start a 'vNotif' sequence. It is good to do it
4720 before resuming inferior, because inferior was stopped and no RSP
4721 traffic at that moment. */
4722 if (!non_stop)
4723 remote_notif_process (rs->notif_state, &notif_client_stop);
4724
4725 rs->last_sent_signal = siggnal;
4726 rs->last_sent_step = step;
4727
4728 /* The vCont packet doesn't need to specify threads via Hc. */
4729 /* No reverse support (yet) for vCont. */
4730 if (execution_direction != EXEC_REVERSE)
4731 if (remote_vcont_resume (ptid, step, siggnal))
4732 goto done;
4733
4734 /* All other supported resume packets do use Hc, so set the continue
4735 thread. */
4736 if (ptid_equal (ptid, minus_one_ptid))
4737 set_continue_thread (any_thread_ptid);
4738 else
4739 set_continue_thread (ptid);
4740
4741 buf = rs->buf;
4742 if (execution_direction == EXEC_REVERSE)
4743 {
4744 /* We don't pass signals to the target in reverse exec mode. */
4745 if (info_verbose && siggnal != GDB_SIGNAL_0)
4746 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
4747 siggnal);
4748
4749 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
4750 error (_("Remote reverse-step not supported."));
4751 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
4752 error (_("Remote reverse-continue not supported."));
4753
4754 strcpy (buf, step ? "bs" : "bc");
4755 }
4756 else if (siggnal != GDB_SIGNAL_0)
4757 {
4758 buf[0] = step ? 'S' : 'C';
4759 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
4760 buf[2] = tohex (((int) siggnal) & 0xf);
4761 buf[3] = '\0';
4762 }
4763 else
4764 strcpy (buf, step ? "s" : "c");
4765
4766 putpkt (buf);
4767
4768 done:
4769 /* We are about to start executing the inferior, let's register it
4770 with the event loop. NOTE: this is the one place where all the
4771 execution commands end up. We could alternatively do this in each
4772 of the execution commands in infcmd.c. */
4773 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4774 into infcmd.c in order to allow inferior function calls to work
4775 NOT asynchronously. */
4776 if (target_can_async_p ())
4777 target_async (inferior_event_handler, 0);
4778
4779 /* We've just told the target to resume. The remote server will
4780 wait for the inferior to stop, and then send a stop reply. In
4781 the mean time, we can't start another command/query ourselves
4782 because the stub wouldn't be ready to process it. This applies
4783 only to the base all-stop protocol, however. In non-stop (which
4784 only supports vCont), the stub replies with an "OK", and is
4785 immediate able to process further serial input. */
4786 if (!non_stop)
4787 rs->waiting_for_stop_reply = 1;
4788 }
4789 \f
4790
4791 /* Set up the signal handler for SIGINT, while the target is
4792 executing, ovewriting the 'regular' SIGINT signal handler. */
4793 static void
4794 async_initialize_sigint_signal_handler (void)
4795 {
4796 signal (SIGINT, async_handle_remote_sigint);
4797 }
4798
4799 /* Signal handler for SIGINT, while the target is executing. */
4800 static void
4801 async_handle_remote_sigint (int sig)
4802 {
4803 signal (sig, async_handle_remote_sigint_twice);
4804 mark_async_signal_handler (async_sigint_remote_token);
4805 }
4806
4807 /* Signal handler for SIGINT, installed after SIGINT has already been
4808 sent once. It will take effect the second time that the user sends
4809 a ^C. */
4810 static void
4811 async_handle_remote_sigint_twice (int sig)
4812 {
4813 signal (sig, async_handle_remote_sigint);
4814 mark_async_signal_handler (async_sigint_remote_twice_token);
4815 }
4816
4817 /* Perform the real interruption of the target execution, in response
4818 to a ^C. */
4819 static void
4820 async_remote_interrupt (gdb_client_data arg)
4821 {
4822 if (remote_debug)
4823 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
4824
4825 target_stop (inferior_ptid);
4826 }
4827
4828 /* Perform interrupt, if the first attempt did not succeed. Just give
4829 up on the target alltogether. */
4830 static void
4831 async_remote_interrupt_twice (gdb_client_data arg)
4832 {
4833 if (remote_debug)
4834 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
4835
4836 interrupt_query ();
4837 }
4838
4839 /* Reinstall the usual SIGINT handlers, after the target has
4840 stopped. */
4841 static void
4842 async_cleanup_sigint_signal_handler (void *dummy)
4843 {
4844 signal (SIGINT, handle_sigint);
4845 }
4846
4847 /* Send ^C to target to halt it. Target will respond, and send us a
4848 packet. */
4849 static void (*ofunc) (int);
4850
4851 /* The command line interface's stop routine. This function is installed
4852 as a signal handler for SIGINT. The first time a user requests a
4853 stop, we call remote_stop to send a break or ^C. If there is no
4854 response from the target (it didn't stop when the user requested it),
4855 we ask the user if he'd like to detach from the target. */
4856 static void
4857 sync_remote_interrupt (int signo)
4858 {
4859 /* If this doesn't work, try more severe steps. */
4860 signal (signo, sync_remote_interrupt_twice);
4861
4862 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
4863 }
4864
4865 /* The user typed ^C twice. */
4866
4867 static void
4868 sync_remote_interrupt_twice (int signo)
4869 {
4870 signal (signo, ofunc);
4871 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
4872 signal (signo, sync_remote_interrupt);
4873 }
4874
4875 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
4876 thread, all threads of a remote process, or all threads of all
4877 processes. */
4878
4879 static void
4880 remote_stop_ns (ptid_t ptid)
4881 {
4882 struct remote_state *rs = get_remote_state ();
4883 char *p = rs->buf;
4884 char *endp = rs->buf + get_remote_packet_size ();
4885
4886 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
4887 remote_vcont_probe (rs);
4888
4889 if (!rs->supports_vCont.t)
4890 error (_("Remote server does not support stopping threads"));
4891
4892 if (ptid_equal (ptid, minus_one_ptid)
4893 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4894 p += xsnprintf (p, endp - p, "vCont;t");
4895 else
4896 {
4897 ptid_t nptid;
4898
4899 p += xsnprintf (p, endp - p, "vCont;t:");
4900
4901 if (ptid_is_pid (ptid))
4902 /* All (-1) threads of process. */
4903 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
4904 else
4905 {
4906 /* Small optimization: if we already have a stop reply for
4907 this thread, no use in telling the stub we want this
4908 stopped. */
4909 if (peek_stop_reply (ptid))
4910 return;
4911
4912 nptid = ptid;
4913 }
4914
4915 write_ptid (p, endp, nptid);
4916 }
4917
4918 /* In non-stop, we get an immediate OK reply. The stop reply will
4919 come in asynchronously by notification. */
4920 putpkt (rs->buf);
4921 getpkt (&rs->buf, &rs->buf_size, 0);
4922 if (strcmp (rs->buf, "OK") != 0)
4923 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
4924 }
4925
4926 /* All-stop version of target_stop. Sends a break or a ^C to stop the
4927 remote target. It is undefined which thread of which process
4928 reports the stop. */
4929
4930 static void
4931 remote_stop_as (ptid_t ptid)
4932 {
4933 struct remote_state *rs = get_remote_state ();
4934
4935 rs->ctrlc_pending_p = 1;
4936
4937 /* If the inferior is stopped already, but the core didn't know
4938 about it yet, just ignore the request. The cached wait status
4939 will be collected in remote_wait. */
4940 if (rs->cached_wait_status)
4941 return;
4942
4943 /* Send interrupt_sequence to remote target. */
4944 send_interrupt_sequence ();
4945 }
4946
4947 /* This is the generic stop called via the target vector. When a target
4948 interrupt is requested, either by the command line or the GUI, we
4949 will eventually end up here. */
4950
4951 static void
4952 remote_stop (struct target_ops *self, ptid_t ptid)
4953 {
4954 if (remote_debug)
4955 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
4956
4957 if (non_stop)
4958 remote_stop_ns (ptid);
4959 else
4960 remote_stop_as (ptid);
4961 }
4962
4963 /* Ask the user what to do when an interrupt is received. */
4964
4965 static void
4966 interrupt_query (void)
4967 {
4968 target_terminal_ours ();
4969
4970 if (target_can_async_p ())
4971 {
4972 signal (SIGINT, handle_sigint);
4973 quit ();
4974 }
4975 else
4976 {
4977 if (query (_("Interrupted while waiting for the program.\n\
4978 Give up (and stop debugging it)? ")))
4979 {
4980 remote_unpush_target ();
4981 quit ();
4982 }
4983 }
4984
4985 target_terminal_inferior ();
4986 }
4987
4988 /* Enable/disable target terminal ownership. Most targets can use
4989 terminal groups to control terminal ownership. Remote targets are
4990 different in that explicit transfer of ownership to/from GDB/target
4991 is required. */
4992
4993 static void
4994 remote_terminal_inferior (struct target_ops *self)
4995 {
4996 if (!target_async_permitted)
4997 /* Nothing to do. */
4998 return;
4999
5000 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5001 idempotent. The event-loop GDB talking to an asynchronous target
5002 with a synchronous command calls this function from both
5003 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5004 transfer the terminal to the target when it shouldn't this guard
5005 can go away. */
5006 if (!remote_async_terminal_ours_p)
5007 return;
5008 delete_file_handler (input_fd);
5009 remote_async_terminal_ours_p = 0;
5010 async_initialize_sigint_signal_handler ();
5011 /* NOTE: At this point we could also register our selves as the
5012 recipient of all input. Any characters typed could then be
5013 passed on down to the target. */
5014 }
5015
5016 static void
5017 remote_terminal_ours (struct target_ops *self)
5018 {
5019 if (!target_async_permitted)
5020 /* Nothing to do. */
5021 return;
5022
5023 /* See FIXME in remote_terminal_inferior. */
5024 if (remote_async_terminal_ours_p)
5025 return;
5026 async_cleanup_sigint_signal_handler (NULL);
5027 add_file_handler (input_fd, stdin_event_handler, 0);
5028 remote_async_terminal_ours_p = 1;
5029 }
5030
5031 static void
5032 remote_console_output (char *msg)
5033 {
5034 char *p;
5035
5036 for (p = msg; p[0] && p[1]; p += 2)
5037 {
5038 char tb[2];
5039 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5040
5041 tb[0] = c;
5042 tb[1] = 0;
5043 fputs_unfiltered (tb, gdb_stdtarg);
5044 }
5045 gdb_flush (gdb_stdtarg);
5046 }
5047
5048 typedef struct cached_reg
5049 {
5050 int num;
5051 gdb_byte data[MAX_REGISTER_SIZE];
5052 } cached_reg_t;
5053
5054 DEF_VEC_O(cached_reg_t);
5055
5056 typedef struct stop_reply
5057 {
5058 struct notif_event base;
5059
5060 /* The identifier of the thread about this event */
5061 ptid_t ptid;
5062
5063 /* The remote state this event is associated with. When the remote
5064 connection, represented by a remote_state object, is closed,
5065 all the associated stop_reply events should be released. */
5066 struct remote_state *rs;
5067
5068 struct target_waitstatus ws;
5069
5070 /* Expedited registers. This makes remote debugging a bit more
5071 efficient for those targets that provide critical registers as
5072 part of their normal status mechanism (as another roundtrip to
5073 fetch them is avoided). */
5074 VEC(cached_reg_t) *regcache;
5075
5076 int stopped_by_watchpoint_p;
5077 CORE_ADDR watch_data_address;
5078
5079 int core;
5080 } *stop_reply_p;
5081
5082 DECLARE_QUEUE_P (stop_reply_p);
5083 DEFINE_QUEUE_P (stop_reply_p);
5084 /* The list of already fetched and acknowledged stop events. This
5085 queue is used for notification Stop, and other notifications
5086 don't need queue for their events, because the notification events
5087 of Stop can't be consumed immediately, so that events should be
5088 queued first, and be consumed by remote_wait_{ns,as} one per
5089 time. Other notifications can consume their events immediately,
5090 so queue is not needed for them. */
5091 static QUEUE (stop_reply_p) *stop_reply_queue;
5092
5093 static void
5094 stop_reply_xfree (struct stop_reply *r)
5095 {
5096 notif_event_xfree ((struct notif_event *) r);
5097 }
5098
5099 static void
5100 remote_notif_stop_parse (struct notif_client *self, char *buf,
5101 struct notif_event *event)
5102 {
5103 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5104 }
5105
5106 static void
5107 remote_notif_stop_ack (struct notif_client *self, char *buf,
5108 struct notif_event *event)
5109 {
5110 struct stop_reply *stop_reply = (struct stop_reply *) event;
5111
5112 /* acknowledge */
5113 putpkt ((char *) self->ack_command);
5114
5115 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5116 /* We got an unknown stop reply. */
5117 error (_("Unknown stop reply"));
5118
5119 push_stop_reply (stop_reply);
5120 }
5121
5122 static int
5123 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5124 {
5125 /* We can't get pending events in remote_notif_process for
5126 notification stop, and we have to do this in remote_wait_ns
5127 instead. If we fetch all queued events from stub, remote stub
5128 may exit and we have no chance to process them back in
5129 remote_wait_ns. */
5130 mark_async_event_handler (remote_async_inferior_event_token);
5131 return 0;
5132 }
5133
5134 static void
5135 stop_reply_dtr (struct notif_event *event)
5136 {
5137 struct stop_reply *r = (struct stop_reply *) event;
5138
5139 VEC_free (cached_reg_t, r->regcache);
5140 }
5141
5142 static struct notif_event *
5143 remote_notif_stop_alloc_reply (void)
5144 {
5145 struct notif_event *r
5146 = (struct notif_event *) XNEW (struct stop_reply);
5147
5148 r->dtr = stop_reply_dtr;
5149
5150 return r;
5151 }
5152
5153 /* A client of notification Stop. */
5154
5155 struct notif_client notif_client_stop =
5156 {
5157 "Stop",
5158 "vStopped",
5159 remote_notif_stop_parse,
5160 remote_notif_stop_ack,
5161 remote_notif_stop_can_get_pending_events,
5162 remote_notif_stop_alloc_reply,
5163 REMOTE_NOTIF_STOP,
5164 };
5165
5166 /* A parameter to pass data in and out. */
5167
5168 struct queue_iter_param
5169 {
5170 void *input;
5171 struct stop_reply *output;
5172 };
5173
5174 /* Remove stop replies in the queue if its pid is equal to the given
5175 inferior's pid. */
5176
5177 static int
5178 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5179 QUEUE_ITER (stop_reply_p) *iter,
5180 stop_reply_p event,
5181 void *data)
5182 {
5183 struct queue_iter_param *param = data;
5184 struct inferior *inf = param->input;
5185
5186 if (ptid_get_pid (event->ptid) == inf->pid)
5187 {
5188 stop_reply_xfree (event);
5189 QUEUE_remove_elem (stop_reply_p, q, iter);
5190 }
5191
5192 return 1;
5193 }
5194
5195 /* Discard all pending stop replies of inferior INF. */
5196
5197 static void
5198 discard_pending_stop_replies (struct inferior *inf)
5199 {
5200 int i;
5201 struct queue_iter_param param;
5202 struct stop_reply *reply;
5203 struct remote_state *rs = get_remote_state ();
5204 struct remote_notif_state *rns = rs->notif_state;
5205
5206 /* This function can be notified when an inferior exists. When the
5207 target is not remote, the notification state is NULL. */
5208 if (rs->remote_desc == NULL)
5209 return;
5210
5211 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
5212
5213 /* Discard the in-flight notification. */
5214 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
5215 {
5216 stop_reply_xfree (reply);
5217 rns->pending_event[notif_client_stop.id] = NULL;
5218 }
5219
5220 param.input = inf;
5221 param.output = NULL;
5222 /* Discard the stop replies we have already pulled with
5223 vStopped. */
5224 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5225 remove_stop_reply_for_inferior, &param);
5226 }
5227
5228 /* If its remote state is equal to the given remote state,
5229 remove EVENT from the stop reply queue. */
5230
5231 static int
5232 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5233 QUEUE_ITER (stop_reply_p) *iter,
5234 stop_reply_p event,
5235 void *data)
5236 {
5237 struct queue_iter_param *param = data;
5238 struct remote_state *rs = param->input;
5239
5240 if (event->rs == rs)
5241 {
5242 stop_reply_xfree (event);
5243 QUEUE_remove_elem (stop_reply_p, q, iter);
5244 }
5245
5246 return 1;
5247 }
5248
5249 /* Discard the stop replies for RS in stop_reply_queue. */
5250
5251 static void
5252 discard_pending_stop_replies_in_queue (struct remote_state *rs)
5253 {
5254 struct queue_iter_param param;
5255
5256 param.input = rs;
5257 param.output = NULL;
5258 /* Discard the stop replies we have already pulled with
5259 vStopped. */
5260 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5261 remove_stop_reply_of_remote_state, &param);
5262 }
5263
5264 /* A parameter to pass data in and out. */
5265
5266 static int
5267 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5268 QUEUE_ITER (stop_reply_p) *iter,
5269 stop_reply_p event,
5270 void *data)
5271 {
5272 struct queue_iter_param *param = data;
5273 ptid_t *ptid = param->input;
5274
5275 if (ptid_match (event->ptid, *ptid))
5276 {
5277 param->output = event;
5278 QUEUE_remove_elem (stop_reply_p, q, iter);
5279 return 0;
5280 }
5281
5282 return 1;
5283 }
5284
5285 /* Remove the first reply in 'stop_reply_queue' which matches
5286 PTID. */
5287
5288 static struct stop_reply *
5289 remote_notif_remove_queued_reply (ptid_t ptid)
5290 {
5291 struct queue_iter_param param;
5292
5293 param.input = &ptid;
5294 param.output = NULL;
5295
5296 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5297 remote_notif_remove_once_on_match, &param);
5298 if (notif_debug)
5299 fprintf_unfiltered (gdb_stdlog,
5300 "notif: discard queued event: 'Stop' in %s\n",
5301 target_pid_to_str (ptid));
5302
5303 return param.output;
5304 }
5305
5306 /* Look for a queued stop reply belonging to PTID. If one is found,
5307 remove it from the queue, and return it. Returns NULL if none is
5308 found. If there are still queued events left to process, tell the
5309 event loop to get back to target_wait soon. */
5310
5311 static struct stop_reply *
5312 queued_stop_reply (ptid_t ptid)
5313 {
5314 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
5315
5316 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
5317 /* There's still at least an event left. */
5318 mark_async_event_handler (remote_async_inferior_event_token);
5319
5320 return r;
5321 }
5322
5323 /* Push a fully parsed stop reply in the stop reply queue. Since we
5324 know that we now have at least one queued event left to pass to the
5325 core side, tell the event loop to get back to target_wait soon. */
5326
5327 static void
5328 push_stop_reply (struct stop_reply *new_event)
5329 {
5330 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
5331
5332 if (notif_debug)
5333 fprintf_unfiltered (gdb_stdlog,
5334 "notif: push 'Stop' %s to queue %d\n",
5335 target_pid_to_str (new_event->ptid),
5336 QUEUE_length (stop_reply_p,
5337 stop_reply_queue));
5338
5339 mark_async_event_handler (remote_async_inferior_event_token);
5340 }
5341
5342 static int
5343 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5344 QUEUE_ITER (stop_reply_p) *iter,
5345 struct stop_reply *event,
5346 void *data)
5347 {
5348 ptid_t *ptid = data;
5349
5350 return !(ptid_equal (*ptid, event->ptid)
5351 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5352 }
5353
5354 /* Returns true if we have a stop reply for PTID. */
5355
5356 static int
5357 peek_stop_reply (ptid_t ptid)
5358 {
5359 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5360 stop_reply_match_ptid_and_ws, &ptid);
5361 }
5362
5363 /* Parse the stop reply in BUF. Either the function succeeds, and the
5364 result is stored in EVENT, or throws an error. */
5365
5366 static void
5367 remote_parse_stop_reply (char *buf, struct stop_reply *event)
5368 {
5369 struct remote_arch_state *rsa = get_remote_arch_state ();
5370 ULONGEST addr;
5371 char *p;
5372
5373 event->ptid = null_ptid;
5374 event->rs = get_remote_state ();
5375 event->ws.kind = TARGET_WAITKIND_IGNORE;
5376 event->ws.value.integer = 0;
5377 event->stopped_by_watchpoint_p = 0;
5378 event->regcache = NULL;
5379 event->core = -1;
5380
5381 switch (buf[0])
5382 {
5383 case 'T': /* Status with PC, SP, FP, ... */
5384 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5385 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5386 ss = signal number
5387 n... = register number
5388 r... = register contents
5389 */
5390
5391 p = &buf[3]; /* after Txx */
5392 while (*p)
5393 {
5394 char *p1;
5395 char *p_temp;
5396 int fieldsize;
5397 LONGEST pnum = 0;
5398
5399 /* If the packet contains a register number, save it in
5400 pnum and set p1 to point to the character following it.
5401 Otherwise p1 points to p. */
5402
5403 /* If this packet is an awatch packet, don't parse the 'a'
5404 as a register number. */
5405
5406 if (strncmp (p, "awatch", strlen("awatch")) != 0
5407 && strncmp (p, "core", strlen ("core") != 0))
5408 {
5409 /* Read the ``P'' register number. */
5410 pnum = strtol (p, &p_temp, 16);
5411 p1 = p_temp;
5412 }
5413 else
5414 p1 = p;
5415
5416 if (p1 == p) /* No register number present here. */
5417 {
5418 p1 = strchr (p, ':');
5419 if (p1 == NULL)
5420 error (_("Malformed packet(a) (missing colon): %s\n\
5421 Packet: '%s'\n"),
5422 p, buf);
5423 if (strncmp (p, "thread", p1 - p) == 0)
5424 event->ptid = read_ptid (++p1, &p);
5425 else if ((strncmp (p, "watch", p1 - p) == 0)
5426 || (strncmp (p, "rwatch", p1 - p) == 0)
5427 || (strncmp (p, "awatch", p1 - p) == 0))
5428 {
5429 event->stopped_by_watchpoint_p = 1;
5430 p = unpack_varlen_hex (++p1, &addr);
5431 event->watch_data_address = (CORE_ADDR) addr;
5432 }
5433 else if (strncmp (p, "library", p1 - p) == 0)
5434 {
5435 p1++;
5436 p_temp = p1;
5437 while (*p_temp && *p_temp != ';')
5438 p_temp++;
5439
5440 event->ws.kind = TARGET_WAITKIND_LOADED;
5441 p = p_temp;
5442 }
5443 else if (strncmp (p, "replaylog", p1 - p) == 0)
5444 {
5445 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5446 /* p1 will indicate "begin" or "end", but it makes
5447 no difference for now, so ignore it. */
5448 p_temp = strchr (p1 + 1, ';');
5449 if (p_temp)
5450 p = p_temp;
5451 }
5452 else if (strncmp (p, "core", p1 - p) == 0)
5453 {
5454 ULONGEST c;
5455
5456 p = unpack_varlen_hex (++p1, &c);
5457 event->core = c;
5458 }
5459 else
5460 {
5461 /* Silently skip unknown optional info. */
5462 p_temp = strchr (p1 + 1, ';');
5463 if (p_temp)
5464 p = p_temp;
5465 }
5466 }
5467 else
5468 {
5469 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5470 cached_reg_t cached_reg;
5471
5472 p = p1;
5473
5474 if (*p != ':')
5475 error (_("Malformed packet(b) (missing colon): %s\n\
5476 Packet: '%s'\n"),
5477 p, buf);
5478 ++p;
5479
5480 if (reg == NULL)
5481 error (_("Remote sent bad register number %s: %s\n\
5482 Packet: '%s'\n"),
5483 hex_string (pnum), p, buf);
5484
5485 cached_reg.num = reg->regnum;
5486
5487 fieldsize = hex2bin (p, cached_reg.data,
5488 register_size (target_gdbarch (),
5489 reg->regnum));
5490 p += 2 * fieldsize;
5491 if (fieldsize < register_size (target_gdbarch (),
5492 reg->regnum))
5493 warning (_("Remote reply is too short: %s"), buf);
5494
5495 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5496 }
5497
5498 if (*p != ';')
5499 error (_("Remote register badly formatted: %s\nhere: %s"),
5500 buf, p);
5501 ++p;
5502 }
5503
5504 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
5505 break;
5506
5507 /* fall through */
5508 case 'S': /* Old style status, just signal only. */
5509 {
5510 int sig;
5511
5512 event->ws.kind = TARGET_WAITKIND_STOPPED;
5513 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
5514 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
5515 event->ws.value.sig = (enum gdb_signal) sig;
5516 else
5517 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5518 }
5519 break;
5520 case 'W': /* Target exited. */
5521 case 'X':
5522 {
5523 char *p;
5524 int pid;
5525 ULONGEST value;
5526
5527 /* GDB used to accept only 2 hex chars here. Stubs should
5528 only send more if they detect GDB supports multi-process
5529 support. */
5530 p = unpack_varlen_hex (&buf[1], &value);
5531
5532 if (buf[0] == 'W')
5533 {
5534 /* The remote process exited. */
5535 event->ws.kind = TARGET_WAITKIND_EXITED;
5536 event->ws.value.integer = value;
5537 }
5538 else
5539 {
5540 /* The remote process exited with a signal. */
5541 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
5542 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
5543 event->ws.value.sig = (enum gdb_signal) value;
5544 else
5545 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5546 }
5547
5548 /* If no process is specified, assume inferior_ptid. */
5549 pid = ptid_get_pid (inferior_ptid);
5550 if (*p == '\0')
5551 ;
5552 else if (*p == ';')
5553 {
5554 p++;
5555
5556 if (p == '\0')
5557 ;
5558 else if (strncmp (p,
5559 "process:", sizeof ("process:") - 1) == 0)
5560 {
5561 ULONGEST upid;
5562
5563 p += sizeof ("process:") - 1;
5564 unpack_varlen_hex (p, &upid);
5565 pid = upid;
5566 }
5567 else
5568 error (_("unknown stop reply packet: %s"), buf);
5569 }
5570 else
5571 error (_("unknown stop reply packet: %s"), buf);
5572 event->ptid = pid_to_ptid (pid);
5573 }
5574 break;
5575 }
5576
5577 if (non_stop && ptid_equal (event->ptid, null_ptid))
5578 error (_("No process or thread specified in stop reply: %s"), buf);
5579 }
5580
5581 /* When the stub wants to tell GDB about a new notification reply, it
5582 sends a notification (%Stop, for example). Those can come it at
5583 any time, hence, we have to make sure that any pending
5584 putpkt/getpkt sequence we're making is finished, before querying
5585 the stub for more events with the corresponding ack command
5586 (vStopped, for example). E.g., if we started a vStopped sequence
5587 immediately upon receiving the notification, something like this
5588 could happen:
5589
5590 1.1) --> Hg 1
5591 1.2) <-- OK
5592 1.3) --> g
5593 1.4) <-- %Stop
5594 1.5) --> vStopped
5595 1.6) <-- (registers reply to step #1.3)
5596
5597 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5598 query.
5599
5600 To solve this, whenever we parse a %Stop notification successfully,
5601 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5602 doing whatever we were doing:
5603
5604 2.1) --> Hg 1
5605 2.2) <-- OK
5606 2.3) --> g
5607 2.4) <-- %Stop
5608 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5609 2.5) <-- (registers reply to step #2.3)
5610
5611 Eventualy after step #2.5, we return to the event loop, which
5612 notices there's an event on the
5613 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5614 associated callback --- the function below. At this point, we're
5615 always safe to start a vStopped sequence. :
5616
5617 2.6) --> vStopped
5618 2.7) <-- T05 thread:2
5619 2.8) --> vStopped
5620 2.9) --> OK
5621 */
5622
5623 void
5624 remote_notif_get_pending_events (struct notif_client *nc)
5625 {
5626 struct remote_state *rs = get_remote_state ();
5627
5628 if (rs->notif_state->pending_event[nc->id] != NULL)
5629 {
5630 if (notif_debug)
5631 fprintf_unfiltered (gdb_stdlog,
5632 "notif: process: '%s' ack pending event\n",
5633 nc->name);
5634
5635 /* acknowledge */
5636 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
5637 rs->notif_state->pending_event[nc->id] = NULL;
5638
5639 while (1)
5640 {
5641 getpkt (&rs->buf, &rs->buf_size, 0);
5642 if (strcmp (rs->buf, "OK") == 0)
5643 break;
5644 else
5645 remote_notif_ack (nc, rs->buf);
5646 }
5647 }
5648 else
5649 {
5650 if (notif_debug)
5651 fprintf_unfiltered (gdb_stdlog,
5652 "notif: process: '%s' no pending reply\n",
5653 nc->name);
5654 }
5655 }
5656
5657 /* Called when it is decided that STOP_REPLY holds the info of the
5658 event that is to be returned to the core. This function always
5659 destroys STOP_REPLY. */
5660
5661 static ptid_t
5662 process_stop_reply (struct stop_reply *stop_reply,
5663 struct target_waitstatus *status)
5664 {
5665 ptid_t ptid;
5666
5667 *status = stop_reply->ws;
5668 ptid = stop_reply->ptid;
5669
5670 /* If no thread/process was reported by the stub, assume the current
5671 inferior. */
5672 if (ptid_equal (ptid, null_ptid))
5673 ptid = inferior_ptid;
5674
5675 if (status->kind != TARGET_WAITKIND_EXITED
5676 && status->kind != TARGET_WAITKIND_SIGNALLED)
5677 {
5678 struct remote_state *rs = get_remote_state ();
5679
5680 /* Expedited registers. */
5681 if (stop_reply->regcache)
5682 {
5683 struct regcache *regcache
5684 = get_thread_arch_regcache (ptid, target_gdbarch ());
5685 cached_reg_t *reg;
5686 int ix;
5687
5688 for (ix = 0;
5689 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5690 ix++)
5691 regcache_raw_supply (regcache, reg->num, reg->data);
5692 VEC_free (cached_reg_t, stop_reply->regcache);
5693 }
5694
5695 rs->remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
5696 rs->remote_watch_data_address = stop_reply->watch_data_address;
5697
5698 remote_notice_new_inferior (ptid, 0);
5699 demand_private_info (ptid)->core = stop_reply->core;
5700 }
5701
5702 stop_reply_xfree (stop_reply);
5703 return ptid;
5704 }
5705
5706 /* The non-stop mode version of target_wait. */
5707
5708 static ptid_t
5709 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
5710 {
5711 struct remote_state *rs = get_remote_state ();
5712 struct stop_reply *stop_reply;
5713 int ret;
5714 int is_notif = 0;
5715
5716 /* If in non-stop mode, get out of getpkt even if a
5717 notification is received. */
5718
5719 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5720 0 /* forever */, &is_notif);
5721 while (1)
5722 {
5723 if (ret != -1 && !is_notif)
5724 switch (rs->buf[0])
5725 {
5726 case 'E': /* Error of some sort. */
5727 /* We're out of sync with the target now. Did it continue
5728 or not? We can't tell which thread it was in non-stop,
5729 so just ignore this. */
5730 warning (_("Remote failure reply: %s"), rs->buf);
5731 break;
5732 case 'O': /* Console output. */
5733 remote_console_output (rs->buf + 1);
5734 break;
5735 default:
5736 warning (_("Invalid remote reply: %s"), rs->buf);
5737 break;
5738 }
5739
5740 /* Acknowledge a pending stop reply that may have arrived in the
5741 mean time. */
5742 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
5743 remote_notif_get_pending_events (&notif_client_stop);
5744
5745 /* If indeed we noticed a stop reply, we're done. */
5746 stop_reply = queued_stop_reply (ptid);
5747 if (stop_reply != NULL)
5748 return process_stop_reply (stop_reply, status);
5749
5750 /* Still no event. If we're just polling for an event, then
5751 return to the event loop. */
5752 if (options & TARGET_WNOHANG)
5753 {
5754 status->kind = TARGET_WAITKIND_IGNORE;
5755 return minus_one_ptid;
5756 }
5757
5758 /* Otherwise do a blocking wait. */
5759 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5760 1 /* forever */, &is_notif);
5761 }
5762 }
5763
5764 /* Wait until the remote machine stops, then return, storing status in
5765 STATUS just as `wait' would. */
5766
5767 static ptid_t
5768 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
5769 {
5770 struct remote_state *rs = get_remote_state ();
5771 ptid_t event_ptid = null_ptid;
5772 char *buf;
5773 struct stop_reply *stop_reply;
5774
5775 again:
5776
5777 status->kind = TARGET_WAITKIND_IGNORE;
5778 status->value.integer = 0;
5779
5780 stop_reply = queued_stop_reply (ptid);
5781 if (stop_reply != NULL)
5782 return process_stop_reply (stop_reply, status);
5783
5784 if (rs->cached_wait_status)
5785 /* Use the cached wait status, but only once. */
5786 rs->cached_wait_status = 0;
5787 else
5788 {
5789 int ret;
5790 int is_notif;
5791
5792 if (!target_is_async_p ())
5793 {
5794 ofunc = signal (SIGINT, sync_remote_interrupt);
5795 /* If the user hit C-c before this packet, or between packets,
5796 pretend that it was hit right here. */
5797 if (check_quit_flag ())
5798 {
5799 clear_quit_flag ();
5800 sync_remote_interrupt (SIGINT);
5801 }
5802 }
5803
5804 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5805 _never_ wait for ever -> test on target_is_async_p().
5806 However, before we do that we need to ensure that the caller
5807 knows how to take the target into/out of async mode. */
5808 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5809 wait_forever_enabled_p, &is_notif);
5810
5811 if (!target_is_async_p ())
5812 signal (SIGINT, ofunc);
5813
5814 /* GDB gets a notification. Return to core as this event is
5815 not interesting. */
5816 if (ret != -1 && is_notif)
5817 return minus_one_ptid;
5818 }
5819
5820 buf = rs->buf;
5821
5822 rs->remote_stopped_by_watchpoint_p = 0;
5823
5824 /* We got something. */
5825 rs->waiting_for_stop_reply = 0;
5826
5827 /* Assume that the target has acknowledged Ctrl-C unless we receive
5828 an 'F' or 'O' packet. */
5829 if (buf[0] != 'F' && buf[0] != 'O')
5830 rs->ctrlc_pending_p = 0;
5831
5832 switch (buf[0])
5833 {
5834 case 'E': /* Error of some sort. */
5835 /* We're out of sync with the target now. Did it continue or
5836 not? Not is more likely, so report a stop. */
5837 warning (_("Remote failure reply: %s"), buf);
5838 status->kind = TARGET_WAITKIND_STOPPED;
5839 status->value.sig = GDB_SIGNAL_0;
5840 break;
5841 case 'F': /* File-I/O request. */
5842 remote_fileio_request (buf, rs->ctrlc_pending_p);
5843 rs->ctrlc_pending_p = 0;
5844 break;
5845 case 'T': case 'S': case 'X': case 'W':
5846 {
5847 struct stop_reply *stop_reply
5848 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
5849 rs->buf);
5850
5851 event_ptid = process_stop_reply (stop_reply, status);
5852 break;
5853 }
5854 case 'O': /* Console output. */
5855 remote_console_output (buf + 1);
5856
5857 /* The target didn't really stop; keep waiting. */
5858 rs->waiting_for_stop_reply = 1;
5859
5860 break;
5861 case '\0':
5862 if (rs->last_sent_signal != GDB_SIGNAL_0)
5863 {
5864 /* Zero length reply means that we tried 'S' or 'C' and the
5865 remote system doesn't support it. */
5866 target_terminal_ours_for_output ();
5867 printf_filtered
5868 ("Can't send signals to this remote system. %s not sent.\n",
5869 gdb_signal_to_name (rs->last_sent_signal));
5870 rs->last_sent_signal = GDB_SIGNAL_0;
5871 target_terminal_inferior ();
5872
5873 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
5874 putpkt ((char *) buf);
5875
5876 /* We just told the target to resume, so a stop reply is in
5877 order. */
5878 rs->waiting_for_stop_reply = 1;
5879 break;
5880 }
5881 /* else fallthrough */
5882 default:
5883 warning (_("Invalid remote reply: %s"), buf);
5884 /* Keep waiting. */
5885 rs->waiting_for_stop_reply = 1;
5886 break;
5887 }
5888
5889 if (status->kind == TARGET_WAITKIND_IGNORE)
5890 {
5891 /* Nothing interesting happened. If we're doing a non-blocking
5892 poll, we're done. Otherwise, go back to waiting. */
5893 if (options & TARGET_WNOHANG)
5894 return minus_one_ptid;
5895 else
5896 goto again;
5897 }
5898 else if (status->kind != TARGET_WAITKIND_EXITED
5899 && status->kind != TARGET_WAITKIND_SIGNALLED)
5900 {
5901 if (!ptid_equal (event_ptid, null_ptid))
5902 record_currthread (rs, event_ptid);
5903 else
5904 event_ptid = inferior_ptid;
5905 }
5906 else
5907 /* A process exit. Invalidate our notion of current thread. */
5908 record_currthread (rs, minus_one_ptid);
5909
5910 return event_ptid;
5911 }
5912
5913 /* Wait until the remote machine stops, then return, storing status in
5914 STATUS just as `wait' would. */
5915
5916 static ptid_t
5917 remote_wait (struct target_ops *ops,
5918 ptid_t ptid, struct target_waitstatus *status, int options)
5919 {
5920 ptid_t event_ptid;
5921
5922 if (non_stop)
5923 event_ptid = remote_wait_ns (ptid, status, options);
5924 else
5925 event_ptid = remote_wait_as (ptid, status, options);
5926
5927 if (target_can_async_p ())
5928 {
5929 /* If there are are events left in the queue tell the event loop
5930 to return here. */
5931 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
5932 mark_async_event_handler (remote_async_inferior_event_token);
5933 }
5934
5935 return event_ptid;
5936 }
5937
5938 /* Fetch a single register using a 'p' packet. */
5939
5940 static int
5941 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
5942 {
5943 struct remote_state *rs = get_remote_state ();
5944 char *buf, *p;
5945 char regp[MAX_REGISTER_SIZE];
5946 int i;
5947
5948 if (packet_support (PACKET_p) == PACKET_DISABLE)
5949 return 0;
5950
5951 if (reg->pnum == -1)
5952 return 0;
5953
5954 p = rs->buf;
5955 *p++ = 'p';
5956 p += hexnumstr (p, reg->pnum);
5957 *p++ = '\0';
5958 putpkt (rs->buf);
5959 getpkt (&rs->buf, &rs->buf_size, 0);
5960
5961 buf = rs->buf;
5962
5963 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
5964 {
5965 case PACKET_OK:
5966 break;
5967 case PACKET_UNKNOWN:
5968 return 0;
5969 case PACKET_ERROR:
5970 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
5971 gdbarch_register_name (get_regcache_arch (regcache),
5972 reg->regnum),
5973 buf);
5974 }
5975
5976 /* If this register is unfetchable, tell the regcache. */
5977 if (buf[0] == 'x')
5978 {
5979 regcache_raw_supply (regcache, reg->regnum, NULL);
5980 return 1;
5981 }
5982
5983 /* Otherwise, parse and supply the value. */
5984 p = buf;
5985 i = 0;
5986 while (p[0] != 0)
5987 {
5988 if (p[1] == 0)
5989 error (_("fetch_register_using_p: early buf termination"));
5990
5991 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
5992 p += 2;
5993 }
5994 regcache_raw_supply (regcache, reg->regnum, regp);
5995 return 1;
5996 }
5997
5998 /* Fetch the registers included in the target's 'g' packet. */
5999
6000 static int
6001 send_g_packet (void)
6002 {
6003 struct remote_state *rs = get_remote_state ();
6004 int buf_len;
6005
6006 xsnprintf (rs->buf, get_remote_packet_size (), "g");
6007 remote_send (&rs->buf, &rs->buf_size);
6008
6009 /* We can get out of synch in various cases. If the first character
6010 in the buffer is not a hex character, assume that has happened
6011 and try to fetch another packet to read. */
6012 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6013 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6014 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6015 && rs->buf[0] != 'x') /* New: unavailable register value. */
6016 {
6017 if (remote_debug)
6018 fprintf_unfiltered (gdb_stdlog,
6019 "Bad register packet; fetching a new packet\n");
6020 getpkt (&rs->buf, &rs->buf_size, 0);
6021 }
6022
6023 buf_len = strlen (rs->buf);
6024
6025 /* Sanity check the received packet. */
6026 if (buf_len % 2 != 0)
6027 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6028
6029 return buf_len / 2;
6030 }
6031
6032 static void
6033 process_g_packet (struct regcache *regcache)
6034 {
6035 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6036 struct remote_state *rs = get_remote_state ();
6037 struct remote_arch_state *rsa = get_remote_arch_state ();
6038 int i, buf_len;
6039 char *p;
6040 char *regs;
6041
6042 buf_len = strlen (rs->buf);
6043
6044 /* Further sanity checks, with knowledge of the architecture. */
6045 if (buf_len > 2 * rsa->sizeof_g_packet)
6046 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6047
6048 /* Save the size of the packet sent to us by the target. It is used
6049 as a heuristic when determining the max size of packets that the
6050 target can safely receive. */
6051 if (rsa->actual_register_packet_size == 0)
6052 rsa->actual_register_packet_size = buf_len;
6053
6054 /* If this is smaller than we guessed the 'g' packet would be,
6055 update our records. A 'g' reply that doesn't include a register's
6056 value implies either that the register is not available, or that
6057 the 'p' packet must be used. */
6058 if (buf_len < 2 * rsa->sizeof_g_packet)
6059 {
6060 rsa->sizeof_g_packet = buf_len / 2;
6061
6062 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6063 {
6064 if (rsa->regs[i].pnum == -1)
6065 continue;
6066
6067 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6068 rsa->regs[i].in_g_packet = 0;
6069 else
6070 rsa->regs[i].in_g_packet = 1;
6071 }
6072 }
6073
6074 regs = alloca (rsa->sizeof_g_packet);
6075
6076 /* Unimplemented registers read as all bits zero. */
6077 memset (regs, 0, rsa->sizeof_g_packet);
6078
6079 /* Reply describes registers byte by byte, each byte encoded as two
6080 hex characters. Suck them all up, then supply them to the
6081 register cacheing/storage mechanism. */
6082
6083 p = rs->buf;
6084 for (i = 0; i < rsa->sizeof_g_packet; i++)
6085 {
6086 if (p[0] == 0 || p[1] == 0)
6087 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6088 internal_error (__FILE__, __LINE__,
6089 _("unexpected end of 'g' packet reply"));
6090
6091 if (p[0] == 'x' && p[1] == 'x')
6092 regs[i] = 0; /* 'x' */
6093 else
6094 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6095 p += 2;
6096 }
6097
6098 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6099 {
6100 struct packet_reg *r = &rsa->regs[i];
6101
6102 if (r->in_g_packet)
6103 {
6104 if (r->offset * 2 >= strlen (rs->buf))
6105 /* This shouldn't happen - we adjusted in_g_packet above. */
6106 internal_error (__FILE__, __LINE__,
6107 _("unexpected end of 'g' packet reply"));
6108 else if (rs->buf[r->offset * 2] == 'x')
6109 {
6110 gdb_assert (r->offset * 2 < strlen (rs->buf));
6111 /* The register isn't available, mark it as such (at
6112 the same time setting the value to zero). */
6113 regcache_raw_supply (regcache, r->regnum, NULL);
6114 }
6115 else
6116 regcache_raw_supply (regcache, r->regnum,
6117 regs + r->offset);
6118 }
6119 }
6120 }
6121
6122 static void
6123 fetch_registers_using_g (struct regcache *regcache)
6124 {
6125 send_g_packet ();
6126 process_g_packet (regcache);
6127 }
6128
6129 /* Make the remote selected traceframe match GDB's selected
6130 traceframe. */
6131
6132 static void
6133 set_remote_traceframe (void)
6134 {
6135 int newnum;
6136 struct remote_state *rs = get_remote_state ();
6137
6138 if (rs->remote_traceframe_number == get_traceframe_number ())
6139 return;
6140
6141 /* Avoid recursion, remote_trace_find calls us again. */
6142 rs->remote_traceframe_number = get_traceframe_number ();
6143
6144 newnum = target_trace_find (tfind_number,
6145 get_traceframe_number (), 0, 0, NULL);
6146
6147 /* Should not happen. If it does, all bets are off. */
6148 if (newnum != get_traceframe_number ())
6149 warning (_("could not set remote traceframe"));
6150 }
6151
6152 static void
6153 remote_fetch_registers (struct target_ops *ops,
6154 struct regcache *regcache, int regnum)
6155 {
6156 struct remote_arch_state *rsa = get_remote_arch_state ();
6157 int i;
6158
6159 set_remote_traceframe ();
6160 set_general_thread (inferior_ptid);
6161
6162 if (regnum >= 0)
6163 {
6164 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6165
6166 gdb_assert (reg != NULL);
6167
6168 /* If this register might be in the 'g' packet, try that first -
6169 we are likely to read more than one register. If this is the
6170 first 'g' packet, we might be overly optimistic about its
6171 contents, so fall back to 'p'. */
6172 if (reg->in_g_packet)
6173 {
6174 fetch_registers_using_g (regcache);
6175 if (reg->in_g_packet)
6176 return;
6177 }
6178
6179 if (fetch_register_using_p (regcache, reg))
6180 return;
6181
6182 /* This register is not available. */
6183 regcache_raw_supply (regcache, reg->regnum, NULL);
6184
6185 return;
6186 }
6187
6188 fetch_registers_using_g (regcache);
6189
6190 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6191 if (!rsa->regs[i].in_g_packet)
6192 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
6193 {
6194 /* This register is not available. */
6195 regcache_raw_supply (regcache, i, NULL);
6196 }
6197 }
6198
6199 /* Prepare to store registers. Since we may send them all (using a
6200 'G' request), we have to read out the ones we don't want to change
6201 first. */
6202
6203 static void
6204 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
6205 {
6206 struct remote_arch_state *rsa = get_remote_arch_state ();
6207 int i;
6208 gdb_byte buf[MAX_REGISTER_SIZE];
6209
6210 /* Make sure the entire registers array is valid. */
6211 switch (packet_support (PACKET_P))
6212 {
6213 case PACKET_DISABLE:
6214 case PACKET_SUPPORT_UNKNOWN:
6215 /* Make sure all the necessary registers are cached. */
6216 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6217 if (rsa->regs[i].in_g_packet)
6218 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
6219 break;
6220 case PACKET_ENABLE:
6221 break;
6222 }
6223 }
6224
6225 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
6226 packet was not recognized. */
6227
6228 static int
6229 store_register_using_P (const struct regcache *regcache,
6230 struct packet_reg *reg)
6231 {
6232 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6233 struct remote_state *rs = get_remote_state ();
6234 /* Try storing a single register. */
6235 char *buf = rs->buf;
6236 gdb_byte regp[MAX_REGISTER_SIZE];
6237 char *p;
6238
6239 if (packet_support (PACKET_P) == PACKET_DISABLE)
6240 return 0;
6241
6242 if (reg->pnum == -1)
6243 return 0;
6244
6245 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
6246 p = buf + strlen (buf);
6247 regcache_raw_collect (regcache, reg->regnum, regp);
6248 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
6249 putpkt (rs->buf);
6250 getpkt (&rs->buf, &rs->buf_size, 0);
6251
6252 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6253 {
6254 case PACKET_OK:
6255 return 1;
6256 case PACKET_ERROR:
6257 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6258 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
6259 case PACKET_UNKNOWN:
6260 return 0;
6261 default:
6262 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6263 }
6264 }
6265
6266 /* Store register REGNUM, or all registers if REGNUM == -1, from the
6267 contents of the register cache buffer. FIXME: ignores errors. */
6268
6269 static void
6270 store_registers_using_G (const struct regcache *regcache)
6271 {
6272 struct remote_state *rs = get_remote_state ();
6273 struct remote_arch_state *rsa = get_remote_arch_state ();
6274 gdb_byte *regs;
6275 char *p;
6276
6277 /* Extract all the registers in the regcache copying them into a
6278 local buffer. */
6279 {
6280 int i;
6281
6282 regs = alloca (rsa->sizeof_g_packet);
6283 memset (regs, 0, rsa->sizeof_g_packet);
6284 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6285 {
6286 struct packet_reg *r = &rsa->regs[i];
6287
6288 if (r->in_g_packet)
6289 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
6290 }
6291 }
6292
6293 /* Command describes registers byte by byte,
6294 each byte encoded as two hex characters. */
6295 p = rs->buf;
6296 *p++ = 'G';
6297 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6298 updated. */
6299 bin2hex (regs, p, rsa->sizeof_g_packet);
6300 putpkt (rs->buf);
6301 getpkt (&rs->buf, &rs->buf_size, 0);
6302 if (packet_check_result (rs->buf) == PACKET_ERROR)
6303 error (_("Could not write registers; remote failure reply '%s'"),
6304 rs->buf);
6305 }
6306
6307 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6308 of the register cache buffer. FIXME: ignores errors. */
6309
6310 static void
6311 remote_store_registers (struct target_ops *ops,
6312 struct regcache *regcache, int regnum)
6313 {
6314 struct remote_arch_state *rsa = get_remote_arch_state ();
6315 int i;
6316
6317 set_remote_traceframe ();
6318 set_general_thread (inferior_ptid);
6319
6320 if (regnum >= 0)
6321 {
6322 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6323
6324 gdb_assert (reg != NULL);
6325
6326 /* Always prefer to store registers using the 'P' packet if
6327 possible; we often change only a small number of registers.
6328 Sometimes we change a larger number; we'd need help from a
6329 higher layer to know to use 'G'. */
6330 if (store_register_using_P (regcache, reg))
6331 return;
6332
6333 /* For now, don't complain if we have no way to write the
6334 register. GDB loses track of unavailable registers too
6335 easily. Some day, this may be an error. We don't have
6336 any way to read the register, either... */
6337 if (!reg->in_g_packet)
6338 return;
6339
6340 store_registers_using_G (regcache);
6341 return;
6342 }
6343
6344 store_registers_using_G (regcache);
6345
6346 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6347 if (!rsa->regs[i].in_g_packet)
6348 if (!store_register_using_P (regcache, &rsa->regs[i]))
6349 /* See above for why we do not issue an error here. */
6350 continue;
6351 }
6352 \f
6353
6354 /* Return the number of hex digits in num. */
6355
6356 static int
6357 hexnumlen (ULONGEST num)
6358 {
6359 int i;
6360
6361 for (i = 0; num != 0; i++)
6362 num >>= 4;
6363
6364 return max (i, 1);
6365 }
6366
6367 /* Set BUF to the minimum number of hex digits representing NUM. */
6368
6369 static int
6370 hexnumstr (char *buf, ULONGEST num)
6371 {
6372 int len = hexnumlen (num);
6373
6374 return hexnumnstr (buf, num, len);
6375 }
6376
6377
6378 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
6379
6380 static int
6381 hexnumnstr (char *buf, ULONGEST num, int width)
6382 {
6383 int i;
6384
6385 buf[width] = '\0';
6386
6387 for (i = width - 1; i >= 0; i--)
6388 {
6389 buf[i] = "0123456789abcdef"[(num & 0xf)];
6390 num >>= 4;
6391 }
6392
6393 return width;
6394 }
6395
6396 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
6397
6398 static CORE_ADDR
6399 remote_address_masked (CORE_ADDR addr)
6400 {
6401 unsigned int address_size = remote_address_size;
6402
6403 /* If "remoteaddresssize" was not set, default to target address size. */
6404 if (!address_size)
6405 address_size = gdbarch_addr_bit (target_gdbarch ());
6406
6407 if (address_size > 0
6408 && address_size < (sizeof (ULONGEST) * 8))
6409 {
6410 /* Only create a mask when that mask can safely be constructed
6411 in a ULONGEST variable. */
6412 ULONGEST mask = 1;
6413
6414 mask = (mask << address_size) - 1;
6415 addr &= mask;
6416 }
6417 return addr;
6418 }
6419
6420 /* Determine whether the remote target supports binary downloading.
6421 This is accomplished by sending a no-op memory write of zero length
6422 to the target at the specified address. It does not suffice to send
6423 the whole packet, since many stubs strip the eighth bit and
6424 subsequently compute a wrong checksum, which causes real havoc with
6425 remote_write_bytes.
6426
6427 NOTE: This can still lose if the serial line is not eight-bit
6428 clean. In cases like this, the user should clear "remote
6429 X-packet". */
6430
6431 static void
6432 check_binary_download (CORE_ADDR addr)
6433 {
6434 struct remote_state *rs = get_remote_state ();
6435
6436 switch (packet_support (PACKET_X))
6437 {
6438 case PACKET_DISABLE:
6439 break;
6440 case PACKET_ENABLE:
6441 break;
6442 case PACKET_SUPPORT_UNKNOWN:
6443 {
6444 char *p;
6445
6446 p = rs->buf;
6447 *p++ = 'X';
6448 p += hexnumstr (p, (ULONGEST) addr);
6449 *p++ = ',';
6450 p += hexnumstr (p, (ULONGEST) 0);
6451 *p++ = ':';
6452 *p = '\0';
6453
6454 putpkt_binary (rs->buf, (int) (p - rs->buf));
6455 getpkt (&rs->buf, &rs->buf_size, 0);
6456
6457 if (rs->buf[0] == '\0')
6458 {
6459 if (remote_debug)
6460 fprintf_unfiltered (gdb_stdlog,
6461 "binary downloading NOT "
6462 "supported by target\n");
6463 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
6464 }
6465 else
6466 {
6467 if (remote_debug)
6468 fprintf_unfiltered (gdb_stdlog,
6469 "binary downloading supported by target\n");
6470 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
6471 }
6472 break;
6473 }
6474 }
6475 }
6476
6477 /* Write memory data directly to the remote machine.
6478 This does not inform the data cache; the data cache uses this.
6479 HEADER is the starting part of the packet.
6480 MEMADDR is the address in the remote memory space.
6481 MYADDR is the address of the buffer in our space.
6482 LEN is the number of bytes.
6483 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6484 should send data as binary ('X'), or hex-encoded ('M').
6485
6486 The function creates packet of the form
6487 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6488
6489 where encoding of <DATA> is termined by PACKET_FORMAT.
6490
6491 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6492 are omitted.
6493
6494 Return the transferred status, error or OK (an
6495 'enum target_xfer_status' value). Save the number of bytes
6496 transferred in *XFERED_LEN. Only transfer a single packet. */
6497
6498 static enum target_xfer_status
6499 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
6500 const gdb_byte *myaddr, ULONGEST len,
6501 ULONGEST *xfered_len, char packet_format,
6502 int use_length)
6503 {
6504 struct remote_state *rs = get_remote_state ();
6505 char *p;
6506 char *plen = NULL;
6507 int plenlen = 0;
6508 int todo;
6509 int nr_bytes;
6510 int payload_size;
6511 int payload_length;
6512 int header_length;
6513
6514 if (packet_format != 'X' && packet_format != 'M')
6515 internal_error (__FILE__, __LINE__,
6516 _("remote_write_bytes_aux: bad packet format"));
6517
6518 if (len == 0)
6519 return TARGET_XFER_EOF;
6520
6521 payload_size = get_memory_write_packet_size ();
6522
6523 /* The packet buffer will be large enough for the payload;
6524 get_memory_packet_size ensures this. */
6525 rs->buf[0] = '\0';
6526
6527 /* Compute the size of the actual payload by subtracting out the
6528 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6529
6530 payload_size -= strlen ("$,:#NN");
6531 if (!use_length)
6532 /* The comma won't be used. */
6533 payload_size += 1;
6534 header_length = strlen (header);
6535 payload_size -= header_length;
6536 payload_size -= hexnumlen (memaddr);
6537
6538 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
6539
6540 strcat (rs->buf, header);
6541 p = rs->buf + strlen (header);
6542
6543 /* Compute a best guess of the number of bytes actually transfered. */
6544 if (packet_format == 'X')
6545 {
6546 /* Best guess at number of bytes that will fit. */
6547 todo = min (len, payload_size);
6548 if (use_length)
6549 payload_size -= hexnumlen (todo);
6550 todo = min (todo, payload_size);
6551 }
6552 else
6553 {
6554 /* Num bytes that will fit. */
6555 todo = min (len, payload_size / 2);
6556 if (use_length)
6557 payload_size -= hexnumlen (todo);
6558 todo = min (todo, payload_size / 2);
6559 }
6560
6561 if (todo <= 0)
6562 internal_error (__FILE__, __LINE__,
6563 _("minimum packet size too small to write data"));
6564
6565 /* If we already need another packet, then try to align the end
6566 of this packet to a useful boundary. */
6567 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6568 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6569
6570 /* Append "<memaddr>". */
6571 memaddr = remote_address_masked (memaddr);
6572 p += hexnumstr (p, (ULONGEST) memaddr);
6573
6574 if (use_length)
6575 {
6576 /* Append ",". */
6577 *p++ = ',';
6578
6579 /* Append <len>. Retain the location/size of <len>. It may need to
6580 be adjusted once the packet body has been created. */
6581 plen = p;
6582 plenlen = hexnumstr (p, (ULONGEST) todo);
6583 p += plenlen;
6584 }
6585
6586 /* Append ":". */
6587 *p++ = ':';
6588 *p = '\0';
6589
6590 /* Append the packet body. */
6591 if (packet_format == 'X')
6592 {
6593 /* Binary mode. Send target system values byte by byte, in
6594 increasing byte addresses. Only escape certain critical
6595 characters. */
6596 payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
6597 &nr_bytes, payload_size);
6598
6599 /* If not all TODO bytes fit, then we'll need another packet. Make
6600 a second try to keep the end of the packet aligned. Don't do
6601 this if the packet is tiny. */
6602 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6603 {
6604 int new_nr_bytes;
6605
6606 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6607 - memaddr);
6608 if (new_nr_bytes != nr_bytes)
6609 payload_length = remote_escape_output (myaddr, new_nr_bytes,
6610 (gdb_byte *) p, &nr_bytes,
6611 payload_size);
6612 }
6613
6614 p += payload_length;
6615 if (use_length && nr_bytes < todo)
6616 {
6617 /* Escape chars have filled up the buffer prematurely,
6618 and we have actually sent fewer bytes than planned.
6619 Fix-up the length field of the packet. Use the same
6620 number of characters as before. */
6621 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6622 *plen = ':'; /* overwrite \0 from hexnumnstr() */
6623 }
6624 }
6625 else
6626 {
6627 /* Normal mode: Send target system values byte by byte, in
6628 increasing byte addresses. Each byte is encoded as a two hex
6629 value. */
6630 nr_bytes = bin2hex (myaddr, p, todo);
6631 p += 2 * nr_bytes;
6632 }
6633
6634 putpkt_binary (rs->buf, (int) (p - rs->buf));
6635 getpkt (&rs->buf, &rs->buf_size, 0);
6636
6637 if (rs->buf[0] == 'E')
6638 return TARGET_XFER_E_IO;
6639
6640 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6641 fewer bytes than we'd planned. */
6642 *xfered_len = (ULONGEST) nr_bytes;
6643 return TARGET_XFER_OK;
6644 }
6645
6646 /* Write memory data directly to the remote machine.
6647 This does not inform the data cache; the data cache uses this.
6648 MEMADDR is the address in the remote memory space.
6649 MYADDR is the address of the buffer in our space.
6650 LEN is the number of bytes.
6651
6652 Return the transferred status, error or OK (an
6653 'enum target_xfer_status' value). Save the number of bytes
6654 transferred in *XFERED_LEN. Only transfer a single packet. */
6655
6656 static enum target_xfer_status
6657 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
6658 ULONGEST *xfered_len)
6659 {
6660 char *packet_format = 0;
6661
6662 /* Check whether the target supports binary download. */
6663 check_binary_download (memaddr);
6664
6665 switch (packet_support (PACKET_X))
6666 {
6667 case PACKET_ENABLE:
6668 packet_format = "X";
6669 break;
6670 case PACKET_DISABLE:
6671 packet_format = "M";
6672 break;
6673 case PACKET_SUPPORT_UNKNOWN:
6674 internal_error (__FILE__, __LINE__,
6675 _("remote_write_bytes: bad internal state"));
6676 default:
6677 internal_error (__FILE__, __LINE__, _("bad switch"));
6678 }
6679
6680 return remote_write_bytes_aux (packet_format,
6681 memaddr, myaddr, len, xfered_len,
6682 packet_format[0], 1);
6683 }
6684
6685 /* Read memory data directly from the remote machine.
6686 This does not use the data cache; the data cache uses this.
6687 MEMADDR is the address in the remote memory space.
6688 MYADDR is the address of the buffer in our space.
6689 LEN is the number of bytes.
6690
6691 Return the transferred status, error or OK (an
6692 'enum target_xfer_status' value). Save the number of bytes
6693 transferred in *XFERED_LEN. */
6694
6695 static enum target_xfer_status
6696 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len,
6697 ULONGEST *xfered_len)
6698 {
6699 struct remote_state *rs = get_remote_state ();
6700 int max_buf_size; /* Max size of packet output buffer. */
6701 char *p;
6702 int todo;
6703 int i;
6704
6705 max_buf_size = get_memory_read_packet_size ();
6706 /* The packet buffer will be large enough for the payload;
6707 get_memory_packet_size ensures this. */
6708
6709 /* Number if bytes that will fit. */
6710 todo = min (len, max_buf_size / 2);
6711
6712 /* Construct "m"<memaddr>","<len>". */
6713 memaddr = remote_address_masked (memaddr);
6714 p = rs->buf;
6715 *p++ = 'm';
6716 p += hexnumstr (p, (ULONGEST) memaddr);
6717 *p++ = ',';
6718 p += hexnumstr (p, (ULONGEST) todo);
6719 *p = '\0';
6720 putpkt (rs->buf);
6721 getpkt (&rs->buf, &rs->buf_size, 0);
6722 if (rs->buf[0] == 'E'
6723 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6724 && rs->buf[3] == '\0')
6725 return TARGET_XFER_E_IO;
6726 /* Reply describes memory byte by byte, each byte encoded as two hex
6727 characters. */
6728 p = rs->buf;
6729 i = hex2bin (p, myaddr, todo);
6730 /* Return what we have. Let higher layers handle partial reads. */
6731 *xfered_len = (ULONGEST) i;
6732 return TARGET_XFER_OK;
6733 }
6734
6735 /* Using the set of read-only target sections of remote, read live
6736 read-only memory.
6737
6738 For interface/parameters/return description see target.h,
6739 to_xfer_partial. */
6740
6741 static enum target_xfer_status
6742 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
6743 ULONGEST memaddr, ULONGEST len,
6744 ULONGEST *xfered_len)
6745 {
6746 struct target_section *secp;
6747 struct target_section_table *table;
6748
6749 secp = target_section_by_addr (ops, memaddr);
6750 if (secp != NULL
6751 && (bfd_get_section_flags (secp->the_bfd_section->owner,
6752 secp->the_bfd_section)
6753 & SEC_READONLY))
6754 {
6755 struct target_section *p;
6756 ULONGEST memend = memaddr + len;
6757
6758 table = target_get_section_table (ops);
6759
6760 for (p = table->sections; p < table->sections_end; p++)
6761 {
6762 if (memaddr >= p->addr)
6763 {
6764 if (memend <= p->endaddr)
6765 {
6766 /* Entire transfer is within this section. */
6767 return remote_read_bytes_1 (memaddr, readbuf, len,
6768 xfered_len);
6769 }
6770 else if (memaddr >= p->endaddr)
6771 {
6772 /* This section ends before the transfer starts. */
6773 continue;
6774 }
6775 else
6776 {
6777 /* This section overlaps the transfer. Just do half. */
6778 len = p->endaddr - memaddr;
6779 return remote_read_bytes_1 (memaddr, readbuf, len,
6780 xfered_len);
6781 }
6782 }
6783 }
6784 }
6785
6786 return TARGET_XFER_EOF;
6787 }
6788
6789 /* Similar to remote_read_bytes_1, but it reads from the remote stub
6790 first if the requested memory is unavailable in traceframe.
6791 Otherwise, fall back to remote_read_bytes_1. */
6792
6793 static enum target_xfer_status
6794 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
6795 gdb_byte *myaddr, ULONGEST len, ULONGEST *xfered_len)
6796 {
6797 if (len == 0)
6798 return 0;
6799
6800 if (get_traceframe_number () != -1)
6801 {
6802 VEC(mem_range_s) *available;
6803
6804 /* If we fail to get the set of available memory, then the
6805 target does not support querying traceframe info, and so we
6806 attempt reading from the traceframe anyway (assuming the
6807 target implements the old QTro packet then). */
6808 if (traceframe_available_memory (&available, memaddr, len))
6809 {
6810 struct cleanup *old_chain;
6811
6812 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
6813
6814 if (VEC_empty (mem_range_s, available)
6815 || VEC_index (mem_range_s, available, 0)->start != memaddr)
6816 {
6817 enum target_xfer_status res;
6818
6819 /* Don't read into the traceframe's available
6820 memory. */
6821 if (!VEC_empty (mem_range_s, available))
6822 {
6823 LONGEST oldlen = len;
6824
6825 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
6826 gdb_assert (len <= oldlen);
6827 }
6828
6829 do_cleanups (old_chain);
6830
6831 /* This goes through the topmost target again. */
6832 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
6833 len, xfered_len);
6834 if (res == TARGET_XFER_OK)
6835 return TARGET_XFER_OK;
6836 else
6837 {
6838 /* No use trying further, we know some memory starting
6839 at MEMADDR isn't available. */
6840 *xfered_len = len;
6841 return TARGET_XFER_UNAVAILABLE;
6842 }
6843 }
6844
6845 /* Don't try to read more than how much is available, in
6846 case the target implements the deprecated QTro packet to
6847 cater for older GDBs (the target's knowledge of read-only
6848 sections may be outdated by now). */
6849 len = VEC_index (mem_range_s, available, 0)->length;
6850
6851 do_cleanups (old_chain);
6852 }
6853 }
6854
6855 return remote_read_bytes_1 (memaddr, myaddr, len, xfered_len);
6856 }
6857
6858 \f
6859
6860 /* Sends a packet with content determined by the printf format string
6861 FORMAT and the remaining arguments, then gets the reply. Returns
6862 whether the packet was a success, a failure, or unknown. */
6863
6864 static enum packet_result
6865 remote_send_printf (const char *format, ...)
6866 {
6867 struct remote_state *rs = get_remote_state ();
6868 int max_size = get_remote_packet_size ();
6869 va_list ap;
6870
6871 va_start (ap, format);
6872
6873 rs->buf[0] = '\0';
6874 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
6875 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
6876
6877 if (putpkt (rs->buf) < 0)
6878 error (_("Communication problem with target."));
6879
6880 rs->buf[0] = '\0';
6881 getpkt (&rs->buf, &rs->buf_size, 0);
6882
6883 return packet_check_result (rs->buf);
6884 }
6885
6886 static void
6887 restore_remote_timeout (void *p)
6888 {
6889 int value = *(int *)p;
6890
6891 remote_timeout = value;
6892 }
6893
6894 /* Flash writing can take quite some time. We'll set
6895 effectively infinite timeout for flash operations.
6896 In future, we'll need to decide on a better approach. */
6897 static const int remote_flash_timeout = 1000;
6898
6899 static void
6900 remote_flash_erase (struct target_ops *ops,
6901 ULONGEST address, LONGEST length)
6902 {
6903 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6904 int saved_remote_timeout = remote_timeout;
6905 enum packet_result ret;
6906 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6907 &saved_remote_timeout);
6908
6909 remote_timeout = remote_flash_timeout;
6910
6911 ret = remote_send_printf ("vFlashErase:%s,%s",
6912 phex (address, addr_size),
6913 phex (length, 4));
6914 switch (ret)
6915 {
6916 case PACKET_UNKNOWN:
6917 error (_("Remote target does not support flash erase"));
6918 case PACKET_ERROR:
6919 error (_("Error erasing flash with vFlashErase packet"));
6920 default:
6921 break;
6922 }
6923
6924 do_cleanups (back_to);
6925 }
6926
6927 static enum target_xfer_status
6928 remote_flash_write (struct target_ops *ops, ULONGEST address,
6929 ULONGEST length, ULONGEST *xfered_len,
6930 const gdb_byte *data)
6931 {
6932 int saved_remote_timeout = remote_timeout;
6933 enum target_xfer_status ret;
6934 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6935 &saved_remote_timeout);
6936
6937 remote_timeout = remote_flash_timeout;
6938 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length,
6939 xfered_len,'X', 0);
6940 do_cleanups (back_to);
6941
6942 return ret;
6943 }
6944
6945 static void
6946 remote_flash_done (struct target_ops *ops)
6947 {
6948 int saved_remote_timeout = remote_timeout;
6949 int ret;
6950 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6951 &saved_remote_timeout);
6952
6953 remote_timeout = remote_flash_timeout;
6954 ret = remote_send_printf ("vFlashDone");
6955 do_cleanups (back_to);
6956
6957 switch (ret)
6958 {
6959 case PACKET_UNKNOWN:
6960 error (_("Remote target does not support vFlashDone"));
6961 case PACKET_ERROR:
6962 error (_("Error finishing flash operation"));
6963 default:
6964 break;
6965 }
6966 }
6967
6968 static void
6969 remote_files_info (struct target_ops *ignore)
6970 {
6971 puts_filtered ("Debugging a target over a serial line.\n");
6972 }
6973 \f
6974 /* Stuff for dealing with the packets which are part of this protocol.
6975 See comment at top of file for details. */
6976
6977 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
6978 error to higher layers. Called when a serial error is detected.
6979 The exception message is STRING, followed by a colon and a blank,
6980 the system error message for errno at function entry and final dot
6981 for output compatibility with throw_perror_with_name. */
6982
6983 static void
6984 unpush_and_perror (const char *string)
6985 {
6986 int saved_errno = errno;
6987
6988 remote_unpush_target ();
6989 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
6990 safe_strerror (saved_errno));
6991 }
6992
6993 /* Read a single character from the remote end. */
6994
6995 static int
6996 readchar (int timeout)
6997 {
6998 int ch;
6999 struct remote_state *rs = get_remote_state ();
7000
7001 ch = serial_readchar (rs->remote_desc, timeout);
7002
7003 if (ch >= 0)
7004 return ch;
7005
7006 switch ((enum serial_rc) ch)
7007 {
7008 case SERIAL_EOF:
7009 remote_unpush_target ();
7010 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7011 /* no return */
7012 case SERIAL_ERROR:
7013 unpush_and_perror (_("Remote communication error. "
7014 "Target disconnected."));
7015 /* no return */
7016 case SERIAL_TIMEOUT:
7017 break;
7018 }
7019 return ch;
7020 }
7021
7022 /* Wrapper for serial_write that closes the target and throws if
7023 writing fails. */
7024
7025 static void
7026 remote_serial_write (const char *str, int len)
7027 {
7028 struct remote_state *rs = get_remote_state ();
7029
7030 if (serial_write (rs->remote_desc, str, len))
7031 {
7032 unpush_and_perror (_("Remote communication error. "
7033 "Target disconnected."));
7034 }
7035 }
7036
7037 /* Send the command in *BUF to the remote machine, and read the reply
7038 into *BUF. Report an error if we get an error reply. Resize
7039 *BUF using xrealloc if necessary to hold the result, and update
7040 *SIZEOF_BUF. */
7041
7042 static void
7043 remote_send (char **buf,
7044 long *sizeof_buf)
7045 {
7046 putpkt (*buf);
7047 getpkt (buf, sizeof_buf, 0);
7048
7049 if ((*buf)[0] == 'E')
7050 error (_("Remote failure reply: %s"), *buf);
7051 }
7052
7053 /* Return a pointer to an xmalloc'ed string representing an escaped
7054 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7055 etc. The caller is responsible for releasing the returned
7056 memory. */
7057
7058 static char *
7059 escape_buffer (const char *buf, int n)
7060 {
7061 struct cleanup *old_chain;
7062 struct ui_file *stb;
7063 char *str;
7064
7065 stb = mem_fileopen ();
7066 old_chain = make_cleanup_ui_file_delete (stb);
7067
7068 fputstrn_unfiltered (buf, n, 0, stb);
7069 str = ui_file_xstrdup (stb, NULL);
7070 do_cleanups (old_chain);
7071 return str;
7072 }
7073
7074 /* Display a null-terminated packet on stdout, for debugging, using C
7075 string notation. */
7076
7077 static void
7078 print_packet (char *buf)
7079 {
7080 puts_filtered ("\"");
7081 fputstr_filtered (buf, '"', gdb_stdout);
7082 puts_filtered ("\"");
7083 }
7084
7085 int
7086 putpkt (char *buf)
7087 {
7088 return putpkt_binary (buf, strlen (buf));
7089 }
7090
7091 /* Send a packet to the remote machine, with error checking. The data
7092 of the packet is in BUF. The string in BUF can be at most
7093 get_remote_packet_size () - 5 to account for the $, # and checksum,
7094 and for a possible /0 if we are debugging (remote_debug) and want
7095 to print the sent packet as a string. */
7096
7097 static int
7098 putpkt_binary (char *buf, int cnt)
7099 {
7100 struct remote_state *rs = get_remote_state ();
7101 int i;
7102 unsigned char csum = 0;
7103 char *buf2 = alloca (cnt + 6);
7104
7105 int ch;
7106 int tcount = 0;
7107 char *p;
7108 char *message;
7109
7110 /* Catch cases like trying to read memory or listing threads while
7111 we're waiting for a stop reply. The remote server wouldn't be
7112 ready to handle this request, so we'd hang and timeout. We don't
7113 have to worry about this in synchronous mode, because in that
7114 case it's not possible to issue a command while the target is
7115 running. This is not a problem in non-stop mode, because in that
7116 case, the stub is always ready to process serial input. */
7117 if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
7118 error (_("Cannot execute this command while the target is running."));
7119
7120 /* We're sending out a new packet. Make sure we don't look at a
7121 stale cached response. */
7122 rs->cached_wait_status = 0;
7123
7124 /* Copy the packet into buffer BUF2, encapsulating it
7125 and giving it a checksum. */
7126
7127 p = buf2;
7128 *p++ = '$';
7129
7130 for (i = 0; i < cnt; i++)
7131 {
7132 csum += buf[i];
7133 *p++ = buf[i];
7134 }
7135 *p++ = '#';
7136 *p++ = tohex ((csum >> 4) & 0xf);
7137 *p++ = tohex (csum & 0xf);
7138
7139 /* Send it over and over until we get a positive ack. */
7140
7141 while (1)
7142 {
7143 int started_error_output = 0;
7144
7145 if (remote_debug)
7146 {
7147 struct cleanup *old_chain;
7148 char *str;
7149
7150 *p = '\0';
7151 str = escape_buffer (buf2, p - buf2);
7152 old_chain = make_cleanup (xfree, str);
7153 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
7154 gdb_flush (gdb_stdlog);
7155 do_cleanups (old_chain);
7156 }
7157 remote_serial_write (buf2, p - buf2);
7158
7159 /* If this is a no acks version of the remote protocol, send the
7160 packet and move on. */
7161 if (rs->noack_mode)
7162 break;
7163
7164 /* Read until either a timeout occurs (-2) or '+' is read.
7165 Handle any notification that arrives in the mean time. */
7166 while (1)
7167 {
7168 ch = readchar (remote_timeout);
7169
7170 if (remote_debug)
7171 {
7172 switch (ch)
7173 {
7174 case '+':
7175 case '-':
7176 case SERIAL_TIMEOUT:
7177 case '$':
7178 case '%':
7179 if (started_error_output)
7180 {
7181 putchar_unfiltered ('\n');
7182 started_error_output = 0;
7183 }
7184 }
7185 }
7186
7187 switch (ch)
7188 {
7189 case '+':
7190 if (remote_debug)
7191 fprintf_unfiltered (gdb_stdlog, "Ack\n");
7192 return 1;
7193 case '-':
7194 if (remote_debug)
7195 fprintf_unfiltered (gdb_stdlog, "Nak\n");
7196 /* FALLTHROUGH */
7197 case SERIAL_TIMEOUT:
7198 tcount++;
7199 if (tcount > 3)
7200 return 0;
7201 break; /* Retransmit buffer. */
7202 case '$':
7203 {
7204 if (remote_debug)
7205 fprintf_unfiltered (gdb_stdlog,
7206 "Packet instead of Ack, ignoring it\n");
7207 /* It's probably an old response sent because an ACK
7208 was lost. Gobble up the packet and ack it so it
7209 doesn't get retransmitted when we resend this
7210 packet. */
7211 skip_frame ();
7212 remote_serial_write ("+", 1);
7213 continue; /* Now, go look for +. */
7214 }
7215
7216 case '%':
7217 {
7218 int val;
7219
7220 /* If we got a notification, handle it, and go back to looking
7221 for an ack. */
7222 /* We've found the start of a notification. Now
7223 collect the data. */
7224 val = read_frame (&rs->buf, &rs->buf_size);
7225 if (val >= 0)
7226 {
7227 if (remote_debug)
7228 {
7229 struct cleanup *old_chain;
7230 char *str;
7231
7232 str = escape_buffer (rs->buf, val);
7233 old_chain = make_cleanup (xfree, str);
7234 fprintf_unfiltered (gdb_stdlog,
7235 " Notification received: %s\n",
7236 str);
7237 do_cleanups (old_chain);
7238 }
7239 handle_notification (rs->notif_state, rs->buf);
7240 /* We're in sync now, rewait for the ack. */
7241 tcount = 0;
7242 }
7243 else
7244 {
7245 if (remote_debug)
7246 {
7247 if (!started_error_output)
7248 {
7249 started_error_output = 1;
7250 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7251 }
7252 fputc_unfiltered (ch & 0177, gdb_stdlog);
7253 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7254 }
7255 }
7256 continue;
7257 }
7258 /* fall-through */
7259 default:
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 }
7269 continue;
7270 }
7271 break; /* Here to retransmit. */
7272 }
7273
7274 #if 0
7275 /* This is wrong. If doing a long backtrace, the user should be
7276 able to get out next time we call QUIT, without anything as
7277 violent as interrupt_query. If we want to provide a way out of
7278 here without getting to the next QUIT, it should be based on
7279 hitting ^C twice as in remote_wait. */
7280 if (quit_flag)
7281 {
7282 quit_flag = 0;
7283 interrupt_query ();
7284 }
7285 #endif
7286 }
7287 return 0;
7288 }
7289
7290 /* Come here after finding the start of a frame when we expected an
7291 ack. Do our best to discard the rest of this packet. */
7292
7293 static void
7294 skip_frame (void)
7295 {
7296 int c;
7297
7298 while (1)
7299 {
7300 c = readchar (remote_timeout);
7301 switch (c)
7302 {
7303 case SERIAL_TIMEOUT:
7304 /* Nothing we can do. */
7305 return;
7306 case '#':
7307 /* Discard the two bytes of checksum and stop. */
7308 c = readchar (remote_timeout);
7309 if (c >= 0)
7310 c = readchar (remote_timeout);
7311
7312 return;
7313 case '*': /* Run length encoding. */
7314 /* Discard the repeat count. */
7315 c = readchar (remote_timeout);
7316 if (c < 0)
7317 return;
7318 break;
7319 default:
7320 /* A regular character. */
7321 break;
7322 }
7323 }
7324 }
7325
7326 /* Come here after finding the start of the frame. Collect the rest
7327 into *BUF, verifying the checksum, length, and handling run-length
7328 compression. NUL terminate the buffer. If there is not enough room,
7329 expand *BUF using xrealloc.
7330
7331 Returns -1 on error, number of characters in buffer (ignoring the
7332 trailing NULL) on success. (could be extended to return one of the
7333 SERIAL status indications). */
7334
7335 static long
7336 read_frame (char **buf_p,
7337 long *sizeof_buf)
7338 {
7339 unsigned char csum;
7340 long bc;
7341 int c;
7342 char *buf = *buf_p;
7343 struct remote_state *rs = get_remote_state ();
7344
7345 csum = 0;
7346 bc = 0;
7347
7348 while (1)
7349 {
7350 c = readchar (remote_timeout);
7351 switch (c)
7352 {
7353 case SERIAL_TIMEOUT:
7354 if (remote_debug)
7355 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
7356 return -1;
7357 case '$':
7358 if (remote_debug)
7359 fputs_filtered ("Saw new packet start in middle of old one\n",
7360 gdb_stdlog);
7361 return -1; /* Start a new packet, count retries. */
7362 case '#':
7363 {
7364 unsigned char pktcsum;
7365 int check_0 = 0;
7366 int check_1 = 0;
7367
7368 buf[bc] = '\0';
7369
7370 check_0 = readchar (remote_timeout);
7371 if (check_0 >= 0)
7372 check_1 = readchar (remote_timeout);
7373
7374 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7375 {
7376 if (remote_debug)
7377 fputs_filtered ("Timeout in checksum, retrying\n",
7378 gdb_stdlog);
7379 return -1;
7380 }
7381 else if (check_0 < 0 || check_1 < 0)
7382 {
7383 if (remote_debug)
7384 fputs_filtered ("Communication error in checksum\n",
7385 gdb_stdlog);
7386 return -1;
7387 }
7388
7389 /* Don't recompute the checksum; with no ack packets we
7390 don't have any way to indicate a packet retransmission
7391 is necessary. */
7392 if (rs->noack_mode)
7393 return bc;
7394
7395 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
7396 if (csum == pktcsum)
7397 return bc;
7398
7399 if (remote_debug)
7400 {
7401 struct cleanup *old_chain;
7402 char *str;
7403
7404 str = escape_buffer (buf, bc);
7405 old_chain = make_cleanup (xfree, str);
7406 fprintf_unfiltered (gdb_stdlog,
7407 "Bad checksum, sentsum=0x%x, "
7408 "csum=0x%x, buf=%s\n",
7409 pktcsum, csum, str);
7410 do_cleanups (old_chain);
7411 }
7412 /* Number of characters in buffer ignoring trailing
7413 NULL. */
7414 return -1;
7415 }
7416 case '*': /* Run length encoding. */
7417 {
7418 int repeat;
7419
7420 csum += c;
7421 c = readchar (remote_timeout);
7422 csum += c;
7423 repeat = c - ' ' + 3; /* Compute repeat count. */
7424
7425 /* The character before ``*'' is repeated. */
7426
7427 if (repeat > 0 && repeat <= 255 && bc > 0)
7428 {
7429 if (bc + repeat - 1 >= *sizeof_buf - 1)
7430 {
7431 /* Make some more room in the buffer. */
7432 *sizeof_buf += repeat;
7433 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7434 buf = *buf_p;
7435 }
7436
7437 memset (&buf[bc], buf[bc - 1], repeat);
7438 bc += repeat;
7439 continue;
7440 }
7441
7442 buf[bc] = '\0';
7443 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
7444 return -1;
7445 }
7446 default:
7447 if (bc >= *sizeof_buf - 1)
7448 {
7449 /* Make some more room in the buffer. */
7450 *sizeof_buf *= 2;
7451 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7452 buf = *buf_p;
7453 }
7454
7455 buf[bc++] = c;
7456 csum += c;
7457 continue;
7458 }
7459 }
7460 }
7461
7462 /* Read a packet from the remote machine, with error checking, and
7463 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7464 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7465 rather than timing out; this is used (in synchronous mode) to wait
7466 for a target that is is executing user code to stop. */
7467 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7468 don't have to change all the calls to getpkt to deal with the
7469 return value, because at the moment I don't know what the right
7470 thing to do it for those. */
7471 void
7472 getpkt (char **buf,
7473 long *sizeof_buf,
7474 int forever)
7475 {
7476 int timed_out;
7477
7478 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7479 }
7480
7481
7482 /* Read a packet from the remote machine, with error checking, and
7483 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7484 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7485 rather than timing out; this is used (in synchronous mode) to wait
7486 for a target that is is executing user code to stop. If FOREVER ==
7487 0, this function is allowed to time out gracefully and return an
7488 indication of this to the caller. Otherwise return the number of
7489 bytes read. If EXPECTING_NOTIF, consider receiving a notification
7490 enough reason to return to the caller. *IS_NOTIF is an output
7491 boolean that indicates whether *BUF holds a notification or not
7492 (a regular packet). */
7493
7494 static int
7495 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
7496 int expecting_notif, int *is_notif)
7497 {
7498 struct remote_state *rs = get_remote_state ();
7499 int c;
7500 int tries;
7501 int timeout;
7502 int val = -1;
7503
7504 /* We're reading a new response. Make sure we don't look at a
7505 previously cached response. */
7506 rs->cached_wait_status = 0;
7507
7508 strcpy (*buf, "timeout");
7509
7510 if (forever)
7511 timeout = watchdog > 0 ? watchdog : -1;
7512 else if (expecting_notif)
7513 timeout = 0; /* There should already be a char in the buffer. If
7514 not, bail out. */
7515 else
7516 timeout = remote_timeout;
7517
7518 #define MAX_TRIES 3
7519
7520 /* Process any number of notifications, and then return when
7521 we get a packet. */
7522 for (;;)
7523 {
7524 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
7525 times. */
7526 for (tries = 1; tries <= MAX_TRIES; tries++)
7527 {
7528 /* This can loop forever if the remote side sends us
7529 characters continuously, but if it pauses, we'll get
7530 SERIAL_TIMEOUT from readchar because of timeout. Then
7531 we'll count that as a retry.
7532
7533 Note that even when forever is set, we will only wait
7534 forever prior to the start of a packet. After that, we
7535 expect characters to arrive at a brisk pace. They should
7536 show up within remote_timeout intervals. */
7537 do
7538 c = readchar (timeout);
7539 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
7540
7541 if (c == SERIAL_TIMEOUT)
7542 {
7543 if (expecting_notif)
7544 return -1; /* Don't complain, it's normal to not get
7545 anything in this case. */
7546
7547 if (forever) /* Watchdog went off? Kill the target. */
7548 {
7549 QUIT;
7550 remote_unpush_target ();
7551 throw_error (TARGET_CLOSE_ERROR,
7552 _("Watchdog timeout has expired. "
7553 "Target detached."));
7554 }
7555 if (remote_debug)
7556 fputs_filtered ("Timed out.\n", gdb_stdlog);
7557 }
7558 else
7559 {
7560 /* We've found the start of a packet or notification.
7561 Now collect the data. */
7562 val = read_frame (buf, sizeof_buf);
7563 if (val >= 0)
7564 break;
7565 }
7566
7567 remote_serial_write ("-", 1);
7568 }
7569
7570 if (tries > MAX_TRIES)
7571 {
7572 /* We have tried hard enough, and just can't receive the
7573 packet/notification. Give up. */
7574 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
7575
7576 /* Skip the ack char if we're in no-ack mode. */
7577 if (!rs->noack_mode)
7578 remote_serial_write ("+", 1);
7579 return -1;
7580 }
7581
7582 /* If we got an ordinary packet, return that to our caller. */
7583 if (c == '$')
7584 {
7585 if (remote_debug)
7586 {
7587 struct cleanup *old_chain;
7588 char *str;
7589
7590 str = escape_buffer (*buf, val);
7591 old_chain = make_cleanup (xfree, str);
7592 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7593 do_cleanups (old_chain);
7594 }
7595
7596 /* Skip the ack char if we're in no-ack mode. */
7597 if (!rs->noack_mode)
7598 remote_serial_write ("+", 1);
7599 if (is_notif != NULL)
7600 *is_notif = 0;
7601 return val;
7602 }
7603
7604 /* If we got a notification, handle it, and go back to looking
7605 for a packet. */
7606 else
7607 {
7608 gdb_assert (c == '%');
7609
7610 if (remote_debug)
7611 {
7612 struct cleanup *old_chain;
7613 char *str;
7614
7615 str = escape_buffer (*buf, val);
7616 old_chain = make_cleanup (xfree, str);
7617 fprintf_unfiltered (gdb_stdlog,
7618 " Notification received: %s\n",
7619 str);
7620 do_cleanups (old_chain);
7621 }
7622 if (is_notif != NULL)
7623 *is_notif = 1;
7624
7625 handle_notification (rs->notif_state, *buf);
7626
7627 /* Notifications require no acknowledgement. */
7628
7629 if (expecting_notif)
7630 return val;
7631 }
7632 }
7633 }
7634
7635 static int
7636 getpkt_sane (char **buf, long *sizeof_buf, int forever)
7637 {
7638 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
7639 }
7640
7641 static int
7642 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
7643 int *is_notif)
7644 {
7645 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
7646 is_notif);
7647 }
7648
7649 \f
7650 static void
7651 remote_kill (struct target_ops *ops)
7652 {
7653 volatile struct gdb_exception ex;
7654
7655 /* Catch errors so the user can quit from gdb even when we
7656 aren't on speaking terms with the remote system. */
7657 TRY_CATCH (ex, RETURN_MASK_ERROR)
7658 {
7659 putpkt ("k");
7660 }
7661 if (ex.reason < 0)
7662 {
7663 if (ex.error == TARGET_CLOSE_ERROR)
7664 {
7665 /* If we got an (EOF) error that caused the target
7666 to go away, then we're done, that's what we wanted.
7667 "k" is susceptible to cause a premature EOF, given
7668 that the remote server isn't actually required to
7669 reply to "k", and it can happen that it doesn't
7670 even get to reply ACK to the "k". */
7671 return;
7672 }
7673
7674 /* Otherwise, something went wrong. We didn't actually kill
7675 the target. Just propagate the exception, and let the
7676 user or higher layers decide what to do. */
7677 throw_exception (ex);
7678 }
7679
7680 /* We've killed the remote end, we get to mourn it. Since this is
7681 target remote, single-process, mourning the inferior also
7682 unpushes remote_ops. */
7683 target_mourn_inferior ();
7684 }
7685
7686 static int
7687 remote_vkill (int pid, struct remote_state *rs)
7688 {
7689 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
7690 return -1;
7691
7692 /* Tell the remote target to detach. */
7693 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
7694 putpkt (rs->buf);
7695 getpkt (&rs->buf, &rs->buf_size, 0);
7696
7697 switch (packet_ok (rs->buf,
7698 &remote_protocol_packets[PACKET_vKill]))
7699 {
7700 case PACKET_OK:
7701 return 0;
7702 case PACKET_ERROR:
7703 return 1;
7704 case PACKET_UNKNOWN:
7705 return -1;
7706 default:
7707 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7708 }
7709 }
7710
7711 static void
7712 extended_remote_kill (struct target_ops *ops)
7713 {
7714 int res;
7715 int pid = ptid_get_pid (inferior_ptid);
7716 struct remote_state *rs = get_remote_state ();
7717
7718 res = remote_vkill (pid, rs);
7719 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
7720 {
7721 /* Don't try 'k' on a multi-process aware stub -- it has no way
7722 to specify the pid. */
7723
7724 putpkt ("k");
7725 #if 0
7726 getpkt (&rs->buf, &rs->buf_size, 0);
7727 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7728 res = 1;
7729 #else
7730 /* Don't wait for it to die. I'm not really sure it matters whether
7731 we do or not. For the existing stubs, kill is a noop. */
7732 res = 0;
7733 #endif
7734 }
7735
7736 if (res != 0)
7737 error (_("Can't kill process"));
7738
7739 target_mourn_inferior ();
7740 }
7741
7742 static void
7743 remote_mourn (struct target_ops *ops)
7744 {
7745 remote_mourn_1 (ops);
7746 }
7747
7748 /* Worker function for remote_mourn. */
7749 static void
7750 remote_mourn_1 (struct target_ops *target)
7751 {
7752 unpush_target (target);
7753
7754 /* remote_close takes care of doing most of the clean up. */
7755 generic_mourn_inferior ();
7756 }
7757
7758 static void
7759 extended_remote_mourn_1 (struct target_ops *target)
7760 {
7761 struct remote_state *rs = get_remote_state ();
7762
7763 /* In case we got here due to an error, but we're going to stay
7764 connected. */
7765 rs->waiting_for_stop_reply = 0;
7766
7767 /* If the current general thread belonged to the process we just
7768 detached from or has exited, the remote side current general
7769 thread becomes undefined. Considering a case like this:
7770
7771 - We just got here due to a detach.
7772 - The process that we're detaching from happens to immediately
7773 report a global breakpoint being hit in non-stop mode, in the
7774 same thread we had selected before.
7775 - GDB attaches to this process again.
7776 - This event happens to be the next event we handle.
7777
7778 GDB would consider that the current general thread didn't need to
7779 be set on the stub side (with Hg), since for all it knew,
7780 GENERAL_THREAD hadn't changed.
7781
7782 Notice that although in all-stop mode, the remote server always
7783 sets the current thread to the thread reporting the stop event,
7784 that doesn't happen in non-stop mode; in non-stop, the stub *must
7785 not* change the current thread when reporting a breakpoint hit,
7786 due to the decoupling of event reporting and event handling.
7787
7788 To keep things simple, we always invalidate our notion of the
7789 current thread. */
7790 record_currthread (rs, minus_one_ptid);
7791
7792 /* Unlike "target remote", we do not want to unpush the target; then
7793 the next time the user says "run", we won't be connected. */
7794
7795 /* Call common code to mark the inferior as not running. */
7796 generic_mourn_inferior ();
7797
7798 if (!have_inferiors ())
7799 {
7800 if (!remote_multi_process_p (rs))
7801 {
7802 /* Check whether the target is running now - some remote stubs
7803 automatically restart after kill. */
7804 putpkt ("?");
7805 getpkt (&rs->buf, &rs->buf_size, 0);
7806
7807 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7808 {
7809 /* Assume that the target has been restarted. Set
7810 inferior_ptid so that bits of core GDB realizes
7811 there's something here, e.g., so that the user can
7812 say "kill" again. */
7813 inferior_ptid = magic_null_ptid;
7814 }
7815 }
7816 }
7817 }
7818
7819 static void
7820 extended_remote_mourn (struct target_ops *ops)
7821 {
7822 extended_remote_mourn_1 (ops);
7823 }
7824
7825 static int
7826 extended_remote_supports_disable_randomization (struct target_ops *self)
7827 {
7828 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
7829 }
7830
7831 static void
7832 extended_remote_disable_randomization (int val)
7833 {
7834 struct remote_state *rs = get_remote_state ();
7835 char *reply;
7836
7837 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
7838 val);
7839 putpkt (rs->buf);
7840 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
7841 if (*reply == '\0')
7842 error (_("Target does not support QDisableRandomization."));
7843 if (strcmp (reply, "OK") != 0)
7844 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
7845 }
7846
7847 static int
7848 extended_remote_run (char *args)
7849 {
7850 struct remote_state *rs = get_remote_state ();
7851 int len;
7852
7853 /* If the user has disabled vRun support, or we have detected that
7854 support is not available, do not try it. */
7855 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
7856 return -1;
7857
7858 strcpy (rs->buf, "vRun;");
7859 len = strlen (rs->buf);
7860
7861 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
7862 error (_("Remote file name too long for run packet"));
7863 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
7864 strlen (remote_exec_file));
7865
7866 gdb_assert (args != NULL);
7867 if (*args)
7868 {
7869 struct cleanup *back_to;
7870 int i;
7871 char **argv;
7872
7873 argv = gdb_buildargv (args);
7874 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
7875 for (i = 0; argv[i] != NULL; i++)
7876 {
7877 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
7878 error (_("Argument list too long for run packet"));
7879 rs->buf[len++] = ';';
7880 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
7881 strlen (argv[i]));
7882 }
7883 do_cleanups (back_to);
7884 }
7885
7886 rs->buf[len++] = '\0';
7887
7888 putpkt (rs->buf);
7889 getpkt (&rs->buf, &rs->buf_size, 0);
7890
7891 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
7892 {
7893 case PACKET_OK:
7894 /* We have a wait response. All is well. */
7895 return 0;
7896 case PACKET_UNKNOWN:
7897 return -1;
7898 case PACKET_ERROR:
7899 if (remote_exec_file[0] == '\0')
7900 error (_("Running the default executable on the remote target failed; "
7901 "try \"set remote exec-file\"?"));
7902 else
7903 error (_("Running \"%s\" on the remote target failed"),
7904 remote_exec_file);
7905 default:
7906 gdb_assert_not_reached (_("bad switch"));
7907 }
7908 }
7909
7910 /* In the extended protocol we want to be able to do things like
7911 "run" and have them basically work as expected. So we need
7912 a special create_inferior function. We support changing the
7913 executable file and the command line arguments, but not the
7914 environment. */
7915
7916 static void
7917 extended_remote_create_inferior (struct target_ops *ops,
7918 char *exec_file, char *args,
7919 char **env, int from_tty)
7920 {
7921 int run_worked;
7922 char *stop_reply;
7923 struct remote_state *rs = get_remote_state ();
7924
7925 /* If running asynchronously, register the target file descriptor
7926 with the event loop. */
7927 if (target_can_async_p ())
7928 target_async (inferior_event_handler, 0);
7929
7930 /* Disable address space randomization if requested (and supported). */
7931 if (extended_remote_supports_disable_randomization (ops))
7932 extended_remote_disable_randomization (disable_randomization);
7933
7934 /* Now restart the remote server. */
7935 run_worked = extended_remote_run (args) != -1;
7936 if (!run_worked)
7937 {
7938 /* vRun was not supported. Fail if we need it to do what the
7939 user requested. */
7940 if (remote_exec_file[0])
7941 error (_("Remote target does not support \"set remote exec-file\""));
7942 if (args[0])
7943 error (_("Remote target does not support \"set args\" or run <ARGS>"));
7944
7945 /* Fall back to "R". */
7946 extended_remote_restart ();
7947 }
7948
7949 if (!have_inferiors ())
7950 {
7951 /* Clean up from the last time we ran, before we mark the target
7952 running again. This will mark breakpoints uninserted, and
7953 get_offsets may insert breakpoints. */
7954 init_thread_list ();
7955 init_wait_for_inferior ();
7956 }
7957
7958 /* vRun's success return is a stop reply. */
7959 stop_reply = run_worked ? rs->buf : NULL;
7960 add_current_inferior_and_thread (stop_reply);
7961
7962 /* Get updated offsets, if the stub uses qOffsets. */
7963 get_offsets ();
7964 }
7965 \f
7966
7967 /* Given a location's target info BP_TGT and the packet buffer BUF, output
7968 the list of conditions (in agent expression bytecode format), if any, the
7969 target needs to evaluate. The output is placed into the packet buffer
7970 started from BUF and ended at BUF_END. */
7971
7972 static int
7973 remote_add_target_side_condition (struct gdbarch *gdbarch,
7974 struct bp_target_info *bp_tgt, char *buf,
7975 char *buf_end)
7976 {
7977 struct agent_expr *aexpr = NULL;
7978 int i, ix;
7979 char *pkt;
7980 char *buf_start = buf;
7981
7982 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
7983 return 0;
7984
7985 buf += strlen (buf);
7986 xsnprintf (buf, buf_end - buf, "%s", ";");
7987 buf++;
7988
7989 /* Send conditions to the target and free the vector. */
7990 for (ix = 0;
7991 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
7992 ix++)
7993 {
7994 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
7995 buf += strlen (buf);
7996 for (i = 0; i < aexpr->len; ++i)
7997 buf = pack_hex_byte (buf, aexpr->buf[i]);
7998 *buf = '\0';
7999 }
8000 return 0;
8001 }
8002
8003 static void
8004 remote_add_target_side_commands (struct gdbarch *gdbarch,
8005 struct bp_target_info *bp_tgt, char *buf)
8006 {
8007 struct agent_expr *aexpr = NULL;
8008 int i, ix;
8009
8010 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8011 return;
8012
8013 buf += strlen (buf);
8014
8015 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8016 buf += strlen (buf);
8017
8018 /* Concatenate all the agent expressions that are commands into the
8019 cmds parameter. */
8020 for (ix = 0;
8021 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8022 ix++)
8023 {
8024 sprintf (buf, "X%x,", aexpr->len);
8025 buf += strlen (buf);
8026 for (i = 0; i < aexpr->len; ++i)
8027 buf = pack_hex_byte (buf, aexpr->buf[i]);
8028 *buf = '\0';
8029 }
8030 }
8031
8032 /* Insert a breakpoint. On targets that have software breakpoint
8033 support, we ask the remote target to do the work; on targets
8034 which don't, we insert a traditional memory breakpoint. */
8035
8036 static int
8037 remote_insert_breakpoint (struct target_ops *ops,
8038 struct gdbarch *gdbarch,
8039 struct bp_target_info *bp_tgt)
8040 {
8041 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8042 If it succeeds, then set the support to PACKET_ENABLE. If it
8043 fails, and the user has explicitly requested the Z support then
8044 report an error, otherwise, mark it disabled and go on. */
8045
8046 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8047 {
8048 CORE_ADDR addr = bp_tgt->placed_address;
8049 struct remote_state *rs;
8050 char *p, *endbuf;
8051 int bpsize;
8052 struct condition_list *cond = NULL;
8053
8054 /* Make sure the remote is pointing at the right process, if
8055 necessary. */
8056 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8057 set_general_process ();
8058
8059 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8060
8061 rs = get_remote_state ();
8062 p = rs->buf;
8063 endbuf = rs->buf + get_remote_packet_size ();
8064
8065 *(p++) = 'Z';
8066 *(p++) = '0';
8067 *(p++) = ',';
8068 addr = (ULONGEST) remote_address_masked (addr);
8069 p += hexnumstr (p, addr);
8070 xsnprintf (p, endbuf - p, ",%d", bpsize);
8071
8072 if (remote_supports_cond_breakpoints (ops))
8073 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8074
8075 if (remote_can_run_breakpoint_commands (ops))
8076 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8077
8078 putpkt (rs->buf);
8079 getpkt (&rs->buf, &rs->buf_size, 0);
8080
8081 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
8082 {
8083 case PACKET_ERROR:
8084 return -1;
8085 case PACKET_OK:
8086 bp_tgt->placed_address = addr;
8087 bp_tgt->placed_size = bpsize;
8088 return 0;
8089 case PACKET_UNKNOWN:
8090 break;
8091 }
8092 }
8093
8094 /* If this breakpoint has target-side commands but this stub doesn't
8095 support Z0 packets, throw error. */
8096 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8097 throw_error (NOT_SUPPORTED_ERROR, _("\
8098 Target doesn't support breakpoints that have target side commands."));
8099
8100 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
8101 }
8102
8103 static int
8104 remote_remove_breakpoint (struct target_ops *ops,
8105 struct gdbarch *gdbarch,
8106 struct bp_target_info *bp_tgt)
8107 {
8108 CORE_ADDR addr = bp_tgt->placed_address;
8109 struct remote_state *rs = get_remote_state ();
8110
8111 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8112 {
8113 char *p = rs->buf;
8114 char *endbuf = rs->buf + get_remote_packet_size ();
8115
8116 /* Make sure the remote is pointing at the right process, if
8117 necessary. */
8118 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8119 set_general_process ();
8120
8121 *(p++) = 'z';
8122 *(p++) = '0';
8123 *(p++) = ',';
8124
8125 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8126 p += hexnumstr (p, addr);
8127 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
8128
8129 putpkt (rs->buf);
8130 getpkt (&rs->buf, &rs->buf_size, 0);
8131
8132 return (rs->buf[0] == 'E');
8133 }
8134
8135 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
8136 }
8137
8138 static int
8139 watchpoint_to_Z_packet (int type)
8140 {
8141 switch (type)
8142 {
8143 case hw_write:
8144 return Z_PACKET_WRITE_WP;
8145 break;
8146 case hw_read:
8147 return Z_PACKET_READ_WP;
8148 break;
8149 case hw_access:
8150 return Z_PACKET_ACCESS_WP;
8151 break;
8152 default:
8153 internal_error (__FILE__, __LINE__,
8154 _("hw_bp_to_z: bad watchpoint type %d"), type);
8155 }
8156 }
8157
8158 static int
8159 remote_insert_watchpoint (struct target_ops *self,
8160 CORE_ADDR addr, int len, int type,
8161 struct expression *cond)
8162 {
8163 struct remote_state *rs = get_remote_state ();
8164 char *endbuf = rs->buf + get_remote_packet_size ();
8165 char *p;
8166 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8167
8168 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8169 return 1;
8170
8171 /* Make sure the remote is pointing at the right process, if
8172 necessary. */
8173 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8174 set_general_process ();
8175
8176 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
8177 p = strchr (rs->buf, '\0');
8178 addr = remote_address_masked (addr);
8179 p += hexnumstr (p, (ULONGEST) addr);
8180 xsnprintf (p, endbuf - p, ",%x", len);
8181
8182 putpkt (rs->buf);
8183 getpkt (&rs->buf, &rs->buf_size, 0);
8184
8185 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8186 {
8187 case PACKET_ERROR:
8188 return -1;
8189 case PACKET_UNKNOWN:
8190 return 1;
8191 case PACKET_OK:
8192 return 0;
8193 }
8194 internal_error (__FILE__, __LINE__,
8195 _("remote_insert_watchpoint: reached end of function"));
8196 }
8197
8198 static int
8199 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8200 CORE_ADDR start, int length)
8201 {
8202 CORE_ADDR diff = remote_address_masked (addr - start);
8203
8204 return diff < length;
8205 }
8206
8207
8208 static int
8209 remote_remove_watchpoint (struct target_ops *self,
8210 CORE_ADDR addr, int len, int type,
8211 struct expression *cond)
8212 {
8213 struct remote_state *rs = get_remote_state ();
8214 char *endbuf = rs->buf + get_remote_packet_size ();
8215 char *p;
8216 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8217
8218 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8219 return -1;
8220
8221 /* Make sure the remote is pointing at the right process, if
8222 necessary. */
8223 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8224 set_general_process ();
8225
8226 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
8227 p = strchr (rs->buf, '\0');
8228 addr = remote_address_masked (addr);
8229 p += hexnumstr (p, (ULONGEST) addr);
8230 xsnprintf (p, endbuf - p, ",%x", len);
8231 putpkt (rs->buf);
8232 getpkt (&rs->buf, &rs->buf_size, 0);
8233
8234 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8235 {
8236 case PACKET_ERROR:
8237 case PACKET_UNKNOWN:
8238 return -1;
8239 case PACKET_OK:
8240 return 0;
8241 }
8242 internal_error (__FILE__, __LINE__,
8243 _("remote_remove_watchpoint: reached end of function"));
8244 }
8245
8246
8247 int remote_hw_watchpoint_limit = -1;
8248 int remote_hw_watchpoint_length_limit = -1;
8249 int remote_hw_breakpoint_limit = -1;
8250
8251 static int
8252 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8253 CORE_ADDR addr, int len)
8254 {
8255 if (remote_hw_watchpoint_length_limit == 0)
8256 return 0;
8257 else if (remote_hw_watchpoint_length_limit < 0)
8258 return 1;
8259 else if (len <= remote_hw_watchpoint_length_limit)
8260 return 1;
8261 else
8262 return 0;
8263 }
8264
8265 static int
8266 remote_check_watch_resources (struct target_ops *self,
8267 int type, int cnt, int ot)
8268 {
8269 if (type == bp_hardware_breakpoint)
8270 {
8271 if (remote_hw_breakpoint_limit == 0)
8272 return 0;
8273 else if (remote_hw_breakpoint_limit < 0)
8274 return 1;
8275 else if (cnt <= remote_hw_breakpoint_limit)
8276 return 1;
8277 }
8278 else
8279 {
8280 if (remote_hw_watchpoint_limit == 0)
8281 return 0;
8282 else if (remote_hw_watchpoint_limit < 0)
8283 return 1;
8284 else if (ot)
8285 return -1;
8286 else if (cnt <= remote_hw_watchpoint_limit)
8287 return 1;
8288 }
8289 return -1;
8290 }
8291
8292 static int
8293 remote_stopped_by_watchpoint (struct target_ops *ops)
8294 {
8295 struct remote_state *rs = get_remote_state ();
8296
8297 return rs->remote_stopped_by_watchpoint_p;
8298 }
8299
8300 static int
8301 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
8302 {
8303 struct remote_state *rs = get_remote_state ();
8304 int rc = 0;
8305
8306 if (remote_stopped_by_watchpoint (target))
8307 {
8308 *addr_p = rs->remote_watch_data_address;
8309 rc = 1;
8310 }
8311
8312 return rc;
8313 }
8314
8315
8316 static int
8317 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
8318 struct bp_target_info *bp_tgt)
8319 {
8320 CORE_ADDR addr;
8321 struct remote_state *rs;
8322 char *p, *endbuf;
8323 char *message;
8324
8325 /* The length field should be set to the size of a breakpoint
8326 instruction, even though we aren't inserting one ourselves. */
8327
8328 gdbarch_remote_breakpoint_from_pc
8329 (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
8330
8331 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
8332 return -1;
8333
8334 /* Make sure the remote is pointing at the right process, if
8335 necessary. */
8336 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8337 set_general_process ();
8338
8339 rs = get_remote_state ();
8340 p = rs->buf;
8341 endbuf = rs->buf + get_remote_packet_size ();
8342
8343 *(p++) = 'Z';
8344 *(p++) = '1';
8345 *(p++) = ',';
8346
8347 addr = remote_address_masked (bp_tgt->placed_address);
8348 p += hexnumstr (p, (ULONGEST) addr);
8349 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
8350
8351 if (remote_supports_cond_breakpoints (self))
8352 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8353
8354 if (remote_can_run_breakpoint_commands (self))
8355 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8356
8357 putpkt (rs->buf);
8358 getpkt (&rs->buf, &rs->buf_size, 0);
8359
8360 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8361 {
8362 case PACKET_ERROR:
8363 if (rs->buf[1] == '.')
8364 {
8365 message = strchr (rs->buf + 2, '.');
8366 if (message)
8367 error (_("Remote failure reply: %s"), message + 1);
8368 }
8369 return -1;
8370 case PACKET_UNKNOWN:
8371 return -1;
8372 case PACKET_OK:
8373 return 0;
8374 }
8375 internal_error (__FILE__, __LINE__,
8376 _("remote_insert_hw_breakpoint: reached end of function"));
8377 }
8378
8379
8380 static int
8381 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
8382 struct bp_target_info *bp_tgt)
8383 {
8384 CORE_ADDR addr;
8385 struct remote_state *rs = get_remote_state ();
8386 char *p = rs->buf;
8387 char *endbuf = rs->buf + get_remote_packet_size ();
8388
8389 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
8390 return -1;
8391
8392 /* Make sure the remote is pointing at the right process, if
8393 necessary. */
8394 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8395 set_general_process ();
8396
8397 *(p++) = 'z';
8398 *(p++) = '1';
8399 *(p++) = ',';
8400
8401 addr = remote_address_masked (bp_tgt->placed_address);
8402 p += hexnumstr (p, (ULONGEST) addr);
8403 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
8404
8405 putpkt (rs->buf);
8406 getpkt (&rs->buf, &rs->buf_size, 0);
8407
8408 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8409 {
8410 case PACKET_ERROR:
8411 case PACKET_UNKNOWN:
8412 return -1;
8413 case PACKET_OK:
8414 return 0;
8415 }
8416 internal_error (__FILE__, __LINE__,
8417 _("remote_remove_hw_breakpoint: reached end of function"));
8418 }
8419
8420 /* Verify memory using the "qCRC:" request. */
8421
8422 static int
8423 remote_verify_memory (struct target_ops *ops,
8424 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8425 {
8426 struct remote_state *rs = get_remote_state ();
8427 unsigned long host_crc, target_crc;
8428 char *tmp;
8429
8430 /* Make sure the remote is pointing at the right process. */
8431 set_general_process ();
8432
8433 /* FIXME: assumes lma can fit into long. */
8434 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8435 (long) lma, (long) size);
8436 putpkt (rs->buf);
8437
8438 /* Be clever; compute the host_crc before waiting for target
8439 reply. */
8440 host_crc = xcrc32 (data, size, 0xffffffff);
8441
8442 getpkt (&rs->buf, &rs->buf_size, 0);
8443 if (rs->buf[0] == 'E')
8444 return -1;
8445
8446 if (rs->buf[0] != 'C')
8447 error (_("remote target does not support this operation"));
8448
8449 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8450 target_crc = target_crc * 16 + fromhex (*tmp);
8451
8452 return (host_crc == target_crc);
8453 }
8454
8455 /* compare-sections command
8456
8457 With no arguments, compares each loadable section in the exec bfd
8458 with the same memory range on the target, and reports mismatches.
8459 Useful for verifying the image on the target against the exec file. */
8460
8461 static void
8462 compare_sections_command (char *args, int from_tty)
8463 {
8464 asection *s;
8465 struct cleanup *old_chain;
8466 gdb_byte *sectdata;
8467 const char *sectname;
8468 bfd_size_type size;
8469 bfd_vma lma;
8470 int matched = 0;
8471 int mismatched = 0;
8472 int res;
8473
8474 if (!exec_bfd)
8475 error (_("command cannot be used without an exec file"));
8476
8477 /* Make sure the remote is pointing at the right process. */
8478 set_general_process ();
8479
8480 for (s = exec_bfd->sections; s; s = s->next)
8481 {
8482 if (!(s->flags & SEC_LOAD))
8483 continue; /* Skip non-loadable section. */
8484
8485 size = bfd_get_section_size (s);
8486 if (size == 0)
8487 continue; /* Skip zero-length section. */
8488
8489 sectname = bfd_get_section_name (exec_bfd, s);
8490 if (args && strcmp (args, sectname) != 0)
8491 continue; /* Not the section selected by user. */
8492
8493 matched = 1; /* Do this section. */
8494 lma = s->lma;
8495
8496 sectdata = xmalloc (size);
8497 old_chain = make_cleanup (xfree, sectdata);
8498 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
8499
8500 res = target_verify_memory (sectdata, lma, size);
8501
8502 if (res == -1)
8503 error (_("target memory fault, section %s, range %s -- %s"), sectname,
8504 paddress (target_gdbarch (), lma),
8505 paddress (target_gdbarch (), lma + size));
8506
8507 printf_filtered ("Section %s, range %s -- %s: ", sectname,
8508 paddress (target_gdbarch (), lma),
8509 paddress (target_gdbarch (), lma + size));
8510 if (res)
8511 printf_filtered ("matched.\n");
8512 else
8513 {
8514 printf_filtered ("MIS-MATCHED!\n");
8515 mismatched++;
8516 }
8517
8518 do_cleanups (old_chain);
8519 }
8520 if (mismatched > 0)
8521 warning (_("One or more sections of the remote executable does not match\n\
8522 the loaded file\n"));
8523 if (args && !matched)
8524 printf_filtered (_("No loaded section named '%s'.\n"), args);
8525 }
8526
8527 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8528 into remote target. The number of bytes written to the remote
8529 target is returned, or -1 for error. */
8530
8531 static enum target_xfer_status
8532 remote_write_qxfer (struct target_ops *ops, const char *object_name,
8533 const char *annex, const gdb_byte *writebuf,
8534 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
8535 struct packet_config *packet)
8536 {
8537 int i, buf_len;
8538 ULONGEST n;
8539 struct remote_state *rs = get_remote_state ();
8540 int max_size = get_memory_write_packet_size ();
8541
8542 if (packet->support == PACKET_DISABLE)
8543 return TARGET_XFER_E_IO;
8544
8545 /* Insert header. */
8546 i = snprintf (rs->buf, max_size,
8547 "qXfer:%s:write:%s:%s:",
8548 object_name, annex ? annex : "",
8549 phex_nz (offset, sizeof offset));
8550 max_size -= (i + 1);
8551
8552 /* Escape as much data as fits into rs->buf. */
8553 buf_len = remote_escape_output
8554 (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
8555
8556 if (putpkt_binary (rs->buf, i + buf_len) < 0
8557 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8558 || packet_ok (rs->buf, packet) != PACKET_OK)
8559 return TARGET_XFER_E_IO;
8560
8561 unpack_varlen_hex (rs->buf, &n);
8562
8563 *xfered_len = n;
8564 return TARGET_XFER_OK;
8565 }
8566
8567 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8568 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8569 number of bytes read is returned, or 0 for EOF, or -1 for error.
8570 The number of bytes read may be less than LEN without indicating an
8571 EOF. PACKET is checked and updated to indicate whether the remote
8572 target supports this object. */
8573
8574 static enum target_xfer_status
8575 remote_read_qxfer (struct target_ops *ops, const char *object_name,
8576 const char *annex,
8577 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
8578 ULONGEST *xfered_len,
8579 struct packet_config *packet)
8580 {
8581 struct remote_state *rs = get_remote_state ();
8582 LONGEST i, n, packet_len;
8583
8584 if (packet->support == PACKET_DISABLE)
8585 return TARGET_XFER_E_IO;
8586
8587 /* Check whether we've cached an end-of-object packet that matches
8588 this request. */
8589 if (rs->finished_object)
8590 {
8591 if (strcmp (object_name, rs->finished_object) == 0
8592 && strcmp (annex ? annex : "", rs->finished_annex) == 0
8593 && offset == rs->finished_offset)
8594 return TARGET_XFER_EOF;
8595
8596
8597 /* Otherwise, we're now reading something different. Discard
8598 the cache. */
8599 xfree (rs->finished_object);
8600 xfree (rs->finished_annex);
8601 rs->finished_object = NULL;
8602 rs->finished_annex = NULL;
8603 }
8604
8605 /* Request only enough to fit in a single packet. The actual data
8606 may not, since we don't know how much of it will need to be escaped;
8607 the target is free to respond with slightly less data. We subtract
8608 five to account for the response type and the protocol frame. */
8609 n = min (get_remote_packet_size () - 5, len);
8610 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8611 object_name, annex ? annex : "",
8612 phex_nz (offset, sizeof offset),
8613 phex_nz (n, sizeof n));
8614 i = putpkt (rs->buf);
8615 if (i < 0)
8616 return TARGET_XFER_E_IO;
8617
8618 rs->buf[0] = '\0';
8619 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8620 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
8621 return TARGET_XFER_E_IO;
8622
8623 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8624 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8625
8626 /* 'm' means there is (or at least might be) more data after this
8627 batch. That does not make sense unless there's at least one byte
8628 of data in this reply. */
8629 if (rs->buf[0] == 'm' && packet_len == 1)
8630 error (_("Remote qXfer reply contained no data."));
8631
8632 /* Got some data. */
8633 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
8634 packet_len - 1, readbuf, n);
8635
8636 /* 'l' is an EOF marker, possibly including a final block of data,
8637 or possibly empty. If we have the final block of a non-empty
8638 object, record this fact to bypass a subsequent partial read. */
8639 if (rs->buf[0] == 'l' && offset + i > 0)
8640 {
8641 rs->finished_object = xstrdup (object_name);
8642 rs->finished_annex = xstrdup (annex ? annex : "");
8643 rs->finished_offset = offset + i;
8644 }
8645
8646 if (i == 0)
8647 return TARGET_XFER_EOF;
8648 else
8649 {
8650 *xfered_len = i;
8651 return TARGET_XFER_OK;
8652 }
8653 }
8654
8655 static enum target_xfer_status
8656 remote_xfer_partial (struct target_ops *ops, enum target_object object,
8657 const char *annex, gdb_byte *readbuf,
8658 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
8659 ULONGEST *xfered_len)
8660 {
8661 struct remote_state *rs;
8662 int i;
8663 char *p2;
8664 char query_type;
8665
8666 set_remote_traceframe ();
8667 set_general_thread (inferior_ptid);
8668
8669 rs = get_remote_state ();
8670
8671 /* Handle memory using the standard memory routines. */
8672 if (object == TARGET_OBJECT_MEMORY)
8673 {
8674 /* If the remote target is connected but not running, we should
8675 pass this request down to a lower stratum (e.g. the executable
8676 file). */
8677 if (!target_has_execution)
8678 return TARGET_XFER_EOF;
8679
8680 if (writebuf != NULL)
8681 return remote_write_bytes (offset, writebuf, len, xfered_len);
8682 else
8683 return remote_read_bytes (ops, offset, readbuf, len, xfered_len);
8684 }
8685
8686 /* Handle SPU memory using qxfer packets. */
8687 if (object == TARGET_OBJECT_SPU)
8688 {
8689 if (readbuf)
8690 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
8691 xfered_len, &remote_protocol_packets
8692 [PACKET_qXfer_spu_read]);
8693 else
8694 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
8695 xfered_len, &remote_protocol_packets
8696 [PACKET_qXfer_spu_write]);
8697 }
8698
8699 /* Handle extra signal info using qxfer packets. */
8700 if (object == TARGET_OBJECT_SIGNAL_INFO)
8701 {
8702 if (readbuf)
8703 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
8704 xfered_len, &remote_protocol_packets
8705 [PACKET_qXfer_siginfo_read]);
8706 else
8707 return remote_write_qxfer (ops, "siginfo", annex,
8708 writebuf, offset, len, xfered_len,
8709 &remote_protocol_packets
8710 [PACKET_qXfer_siginfo_write]);
8711 }
8712
8713 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8714 {
8715 if (readbuf)
8716 return remote_read_qxfer (ops, "statictrace", annex,
8717 readbuf, offset, len, xfered_len,
8718 &remote_protocol_packets
8719 [PACKET_qXfer_statictrace_read]);
8720 else
8721 return TARGET_XFER_E_IO;
8722 }
8723
8724 /* Only handle flash writes. */
8725 if (writebuf != NULL)
8726 {
8727 LONGEST xfered;
8728
8729 switch (object)
8730 {
8731 case TARGET_OBJECT_FLASH:
8732 return remote_flash_write (ops, offset, len, xfered_len,
8733 writebuf);
8734
8735 default:
8736 return TARGET_XFER_E_IO;
8737 }
8738 }
8739
8740 /* Map pre-existing objects onto letters. DO NOT do this for new
8741 objects!!! Instead specify new query packets. */
8742 switch (object)
8743 {
8744 case TARGET_OBJECT_AVR:
8745 query_type = 'R';
8746 break;
8747
8748 case TARGET_OBJECT_AUXV:
8749 gdb_assert (annex == NULL);
8750 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
8751 xfered_len,
8752 &remote_protocol_packets[PACKET_qXfer_auxv]);
8753
8754 case TARGET_OBJECT_AVAILABLE_FEATURES:
8755 return remote_read_qxfer
8756 (ops, "features", annex, readbuf, offset, len, xfered_len,
8757 &remote_protocol_packets[PACKET_qXfer_features]);
8758
8759 case TARGET_OBJECT_LIBRARIES:
8760 return remote_read_qxfer
8761 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
8762 &remote_protocol_packets[PACKET_qXfer_libraries]);
8763
8764 case TARGET_OBJECT_LIBRARIES_SVR4:
8765 return remote_read_qxfer
8766 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
8767 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
8768
8769 case TARGET_OBJECT_MEMORY_MAP:
8770 gdb_assert (annex == NULL);
8771 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
8772 xfered_len,
8773 &remote_protocol_packets[PACKET_qXfer_memory_map]);
8774
8775 case TARGET_OBJECT_OSDATA:
8776 /* Should only get here if we're connected. */
8777 gdb_assert (rs->remote_desc);
8778 return remote_read_qxfer
8779 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
8780 &remote_protocol_packets[PACKET_qXfer_osdata]);
8781
8782 case TARGET_OBJECT_THREADS:
8783 gdb_assert (annex == NULL);
8784 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
8785 xfered_len,
8786 &remote_protocol_packets[PACKET_qXfer_threads]);
8787
8788 case TARGET_OBJECT_TRACEFRAME_INFO:
8789 gdb_assert (annex == NULL);
8790 return remote_read_qxfer
8791 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
8792 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
8793
8794 case TARGET_OBJECT_FDPIC:
8795 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
8796 xfered_len,
8797 &remote_protocol_packets[PACKET_qXfer_fdpic]);
8798
8799 case TARGET_OBJECT_OPENVMS_UIB:
8800 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
8801 xfered_len,
8802 &remote_protocol_packets[PACKET_qXfer_uib]);
8803
8804 case TARGET_OBJECT_BTRACE:
8805 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
8806 xfered_len,
8807 &remote_protocol_packets[PACKET_qXfer_btrace]);
8808
8809 default:
8810 return TARGET_XFER_E_IO;
8811 }
8812
8813 /* Note: a zero OFFSET and LEN can be used to query the minimum
8814 buffer size. */
8815 if (offset == 0 && len == 0)
8816 return (get_remote_packet_size ());
8817 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
8818 large enough let the caller deal with it. */
8819 if (len < get_remote_packet_size ())
8820 return TARGET_XFER_E_IO;
8821 len = get_remote_packet_size ();
8822
8823 /* Except for querying the minimum buffer size, target must be open. */
8824 if (!rs->remote_desc)
8825 error (_("remote query is only available after target open"));
8826
8827 gdb_assert (annex != NULL);
8828 gdb_assert (readbuf != NULL);
8829
8830 p2 = rs->buf;
8831 *p2++ = 'q';
8832 *p2++ = query_type;
8833
8834 /* We used one buffer char for the remote protocol q command and
8835 another for the query type. As the remote protocol encapsulation
8836 uses 4 chars plus one extra in case we are debugging
8837 (remote_debug), we have PBUFZIZ - 7 left to pack the query
8838 string. */
8839 i = 0;
8840 while (annex[i] && (i < (get_remote_packet_size () - 8)))
8841 {
8842 /* Bad caller may have sent forbidden characters. */
8843 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
8844 *p2++ = annex[i];
8845 i++;
8846 }
8847 *p2 = '\0';
8848 gdb_assert (annex[i] == '\0');
8849
8850 i = putpkt (rs->buf);
8851 if (i < 0)
8852 return TARGET_XFER_E_IO;
8853
8854 getpkt (&rs->buf, &rs->buf_size, 0);
8855 strcpy ((char *) readbuf, rs->buf);
8856
8857 *xfered_len = strlen ((char *) readbuf);
8858 return TARGET_XFER_OK;
8859 }
8860
8861 static int
8862 remote_search_memory (struct target_ops* ops,
8863 CORE_ADDR start_addr, ULONGEST search_space_len,
8864 const gdb_byte *pattern, ULONGEST pattern_len,
8865 CORE_ADDR *found_addrp)
8866 {
8867 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8868 struct remote_state *rs = get_remote_state ();
8869 int max_size = get_memory_write_packet_size ();
8870 struct packet_config *packet =
8871 &remote_protocol_packets[PACKET_qSearch_memory];
8872 /* Number of packet bytes used to encode the pattern;
8873 this could be more than PATTERN_LEN due to escape characters. */
8874 int escaped_pattern_len;
8875 /* Amount of pattern that was encodable in the packet. */
8876 int used_pattern_len;
8877 int i;
8878 int found;
8879 ULONGEST found_addr;
8880
8881 /* Don't go to the target if we don't have to.
8882 This is done before checking packet->support to avoid the possibility that
8883 a success for this edge case means the facility works in general. */
8884 if (pattern_len > search_space_len)
8885 return 0;
8886 if (pattern_len == 0)
8887 {
8888 *found_addrp = start_addr;
8889 return 1;
8890 }
8891
8892 /* If we already know the packet isn't supported, fall back to the simple
8893 way of searching memory. */
8894
8895 if (packet_config_support (packet) == PACKET_DISABLE)
8896 {
8897 /* Target doesn't provided special support, fall back and use the
8898 standard support (copy memory and do the search here). */
8899 return simple_search_memory (ops, start_addr, search_space_len,
8900 pattern, pattern_len, found_addrp);
8901 }
8902
8903 /* Make sure the remote is pointing at the right process. */
8904 set_general_process ();
8905
8906 /* Insert header. */
8907 i = snprintf (rs->buf, max_size,
8908 "qSearch:memory:%s;%s;",
8909 phex_nz (start_addr, addr_size),
8910 phex_nz (search_space_len, sizeof (search_space_len)));
8911 max_size -= (i + 1);
8912
8913 /* Escape as much data as fits into rs->buf. */
8914 escaped_pattern_len =
8915 remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
8916 &used_pattern_len, max_size);
8917
8918 /* Bail if the pattern is too large. */
8919 if (used_pattern_len != pattern_len)
8920 error (_("Pattern is too large to transmit to remote target."));
8921
8922 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
8923 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8924 || packet_ok (rs->buf, packet) != PACKET_OK)
8925 {
8926 /* The request may not have worked because the command is not
8927 supported. If so, fall back to the simple way. */
8928 if (packet->support == PACKET_DISABLE)
8929 {
8930 return simple_search_memory (ops, start_addr, search_space_len,
8931 pattern, pattern_len, found_addrp);
8932 }
8933 return -1;
8934 }
8935
8936 if (rs->buf[0] == '0')
8937 found = 0;
8938 else if (rs->buf[0] == '1')
8939 {
8940 found = 1;
8941 if (rs->buf[1] != ',')
8942 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
8943 unpack_varlen_hex (rs->buf + 2, &found_addr);
8944 *found_addrp = found_addr;
8945 }
8946 else
8947 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
8948
8949 return found;
8950 }
8951
8952 static void
8953 remote_rcmd (struct target_ops *self, char *command,
8954 struct ui_file *outbuf)
8955 {
8956 struct remote_state *rs = get_remote_state ();
8957 char *p = rs->buf;
8958
8959 if (!rs->remote_desc)
8960 error (_("remote rcmd is only available after target open"));
8961
8962 /* Send a NULL command across as an empty command. */
8963 if (command == NULL)
8964 command = "";
8965
8966 /* The query prefix. */
8967 strcpy (rs->buf, "qRcmd,");
8968 p = strchr (rs->buf, '\0');
8969
8970 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
8971 > get_remote_packet_size ())
8972 error (_("\"monitor\" command ``%s'' is too long."), command);
8973
8974 /* Encode the actual command. */
8975 bin2hex ((gdb_byte *) command, p, strlen (command));
8976
8977 if (putpkt (rs->buf) < 0)
8978 error (_("Communication problem with target."));
8979
8980 /* get/display the response */
8981 while (1)
8982 {
8983 char *buf;
8984
8985 /* XXX - see also remote_get_noisy_reply(). */
8986 QUIT; /* Allow user to bail out with ^C. */
8987 rs->buf[0] = '\0';
8988 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
8989 {
8990 /* Timeout. Continue to (try to) read responses.
8991 This is better than stopping with an error, assuming the stub
8992 is still executing the (long) monitor command.
8993 If needed, the user can interrupt gdb using C-c, obtaining
8994 an effect similar to stop on timeout. */
8995 continue;
8996 }
8997 buf = rs->buf;
8998 if (buf[0] == '\0')
8999 error (_("Target does not support this command."));
9000 if (buf[0] == 'O' && buf[1] != 'K')
9001 {
9002 remote_console_output (buf + 1); /* 'O' message from stub. */
9003 continue;
9004 }
9005 if (strcmp (buf, "OK") == 0)
9006 break;
9007 if (strlen (buf) == 3 && buf[0] == 'E'
9008 && isdigit (buf[1]) && isdigit (buf[2]))
9009 {
9010 error (_("Protocol error with Rcmd"));
9011 }
9012 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9013 {
9014 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
9015
9016 fputc_unfiltered (c, outbuf);
9017 }
9018 break;
9019 }
9020 }
9021
9022 static VEC(mem_region_s) *
9023 remote_memory_map (struct target_ops *ops)
9024 {
9025 VEC(mem_region_s) *result = NULL;
9026 char *text = target_read_stralloc (&current_target,
9027 TARGET_OBJECT_MEMORY_MAP, NULL);
9028
9029 if (text)
9030 {
9031 struct cleanup *back_to = make_cleanup (xfree, text);
9032
9033 result = parse_memory_map (text);
9034 do_cleanups (back_to);
9035 }
9036
9037 return result;
9038 }
9039
9040 static void
9041 packet_command (char *args, int from_tty)
9042 {
9043 struct remote_state *rs = get_remote_state ();
9044
9045 if (!rs->remote_desc)
9046 error (_("command can only be used with remote target"));
9047
9048 if (!args)
9049 error (_("remote-packet command requires packet text as argument"));
9050
9051 puts_filtered ("sending: ");
9052 print_packet (args);
9053 puts_filtered ("\n");
9054 putpkt (args);
9055
9056 getpkt (&rs->buf, &rs->buf_size, 0);
9057 puts_filtered ("received: ");
9058 print_packet (rs->buf);
9059 puts_filtered ("\n");
9060 }
9061
9062 #if 0
9063 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
9064
9065 static void display_thread_info (struct gdb_ext_thread_info *info);
9066
9067 static void threadset_test_cmd (char *cmd, int tty);
9068
9069 static void threadalive_test (char *cmd, int tty);
9070
9071 static void threadlist_test_cmd (char *cmd, int tty);
9072
9073 int get_and_display_threadinfo (threadref *ref);
9074
9075 static void threadinfo_test_cmd (char *cmd, int tty);
9076
9077 static int thread_display_step (threadref *ref, void *context);
9078
9079 static void threadlist_update_test_cmd (char *cmd, int tty);
9080
9081 static void init_remote_threadtests (void);
9082
9083 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
9084
9085 static void
9086 threadset_test_cmd (char *cmd, int tty)
9087 {
9088 int sample_thread = SAMPLE_THREAD;
9089
9090 printf_filtered (_("Remote threadset test\n"));
9091 set_general_thread (sample_thread);
9092 }
9093
9094
9095 static void
9096 threadalive_test (char *cmd, int tty)
9097 {
9098 int sample_thread = SAMPLE_THREAD;
9099 int pid = ptid_get_pid (inferior_ptid);
9100 ptid_t ptid = ptid_build (pid, sample_thread, 0);
9101
9102 if (remote_thread_alive (ptid))
9103 printf_filtered ("PASS: Thread alive test\n");
9104 else
9105 printf_filtered ("FAIL: Thread alive test\n");
9106 }
9107
9108 void output_threadid (char *title, threadref *ref);
9109
9110 void
9111 output_threadid (char *title, threadref *ref)
9112 {
9113 char hexid[20];
9114
9115 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
9116 hexid[16] = 0;
9117 printf_filtered ("%s %s\n", title, (&hexid[0]));
9118 }
9119
9120 static void
9121 threadlist_test_cmd (char *cmd, int tty)
9122 {
9123 int startflag = 1;
9124 threadref nextthread;
9125 int done, result_count;
9126 threadref threadlist[3];
9127
9128 printf_filtered ("Remote Threadlist test\n");
9129 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9130 &result_count, &threadlist[0]))
9131 printf_filtered ("FAIL: threadlist test\n");
9132 else
9133 {
9134 threadref *scan = threadlist;
9135 threadref *limit = scan + result_count;
9136
9137 while (scan < limit)
9138 output_threadid (" thread ", scan++);
9139 }
9140 }
9141
9142 void
9143 display_thread_info (struct gdb_ext_thread_info *info)
9144 {
9145 output_threadid ("Threadid: ", &info->threadid);
9146 printf_filtered ("Name: %s\n ", info->shortname);
9147 printf_filtered ("State: %s\n", info->display);
9148 printf_filtered ("other: %s\n\n", info->more_display);
9149 }
9150
9151 int
9152 get_and_display_threadinfo (threadref *ref)
9153 {
9154 int result;
9155 int set;
9156 struct gdb_ext_thread_info threadinfo;
9157
9158 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9159 | TAG_MOREDISPLAY | TAG_DISPLAY;
9160 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9161 display_thread_info (&threadinfo);
9162 return result;
9163 }
9164
9165 static void
9166 threadinfo_test_cmd (char *cmd, int tty)
9167 {
9168 int athread = SAMPLE_THREAD;
9169 threadref thread;
9170 int set;
9171
9172 int_to_threadref (&thread, athread);
9173 printf_filtered ("Remote Threadinfo test\n");
9174 if (!get_and_display_threadinfo (&thread))
9175 printf_filtered ("FAIL cannot get thread info\n");
9176 }
9177
9178 static int
9179 thread_display_step (threadref *ref, void *context)
9180 {
9181 /* output_threadid(" threadstep ",ref); *//* simple test */
9182 return get_and_display_threadinfo (ref);
9183 }
9184
9185 static void
9186 threadlist_update_test_cmd (char *cmd, int tty)
9187 {
9188 printf_filtered ("Remote Threadlist update test\n");
9189 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9190 }
9191
9192 static void
9193 init_remote_threadtests (void)
9194 {
9195 add_com ("tlist", class_obscure, threadlist_test_cmd,
9196 _("Fetch and print the remote list of "
9197 "thread identifiers, one pkt only"));
9198 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
9199 _("Fetch and display info about one thread"));
9200 add_com ("tset", class_obscure, threadset_test_cmd,
9201 _("Test setting to a different thread"));
9202 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
9203 _("Iterate through updating all remote thread info"));
9204 add_com ("talive", class_obscure, threadalive_test,
9205 _(" Remote thread alive test "));
9206 }
9207
9208 #endif /* 0 */
9209
9210 /* Convert a thread ID to a string. Returns the string in a static
9211 buffer. */
9212
9213 static char *
9214 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
9215 {
9216 static char buf[64];
9217 struct remote_state *rs = get_remote_state ();
9218
9219 if (ptid_equal (ptid, null_ptid))
9220 return normal_pid_to_str (ptid);
9221 else if (ptid_is_pid (ptid))
9222 {
9223 /* Printing an inferior target id. */
9224
9225 /* When multi-process extensions are off, there's no way in the
9226 remote protocol to know the remote process id, if there's any
9227 at all. There's one exception --- when we're connected with
9228 target extended-remote, and we manually attached to a process
9229 with "attach PID". We don't record anywhere a flag that
9230 allows us to distinguish that case from the case of
9231 connecting with extended-remote and the stub already being
9232 attached to a process, and reporting yes to qAttached, hence
9233 no smart special casing here. */
9234 if (!remote_multi_process_p (rs))
9235 {
9236 xsnprintf (buf, sizeof buf, "Remote target");
9237 return buf;
9238 }
9239
9240 return normal_pid_to_str (ptid);
9241 }
9242 else
9243 {
9244 if (ptid_equal (magic_null_ptid, ptid))
9245 xsnprintf (buf, sizeof buf, "Thread <main>");
9246 else if (rs->extended && remote_multi_process_p (rs))
9247 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
9248 ptid_get_pid (ptid), ptid_get_lwp (ptid));
9249 else
9250 xsnprintf (buf, sizeof buf, "Thread %ld",
9251 ptid_get_lwp (ptid));
9252 return buf;
9253 }
9254 }
9255
9256 /* Get the address of the thread local variable in OBJFILE which is
9257 stored at OFFSET within the thread local storage for thread PTID. */
9258
9259 static CORE_ADDR
9260 remote_get_thread_local_address (struct target_ops *ops,
9261 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
9262 {
9263 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
9264 {
9265 struct remote_state *rs = get_remote_state ();
9266 char *p = rs->buf;
9267 char *endp = rs->buf + get_remote_packet_size ();
9268 enum packet_result result;
9269
9270 strcpy (p, "qGetTLSAddr:");
9271 p += strlen (p);
9272 p = write_ptid (p, endp, ptid);
9273 *p++ = ',';
9274 p += hexnumstr (p, offset);
9275 *p++ = ',';
9276 p += hexnumstr (p, lm);
9277 *p++ = '\0';
9278
9279 putpkt (rs->buf);
9280 getpkt (&rs->buf, &rs->buf_size, 0);
9281 result = packet_ok (rs->buf,
9282 &remote_protocol_packets[PACKET_qGetTLSAddr]);
9283 if (result == PACKET_OK)
9284 {
9285 ULONGEST result;
9286
9287 unpack_varlen_hex (rs->buf, &result);
9288 return result;
9289 }
9290 else if (result == PACKET_UNKNOWN)
9291 throw_error (TLS_GENERIC_ERROR,
9292 _("Remote target doesn't support qGetTLSAddr packet"));
9293 else
9294 throw_error (TLS_GENERIC_ERROR,
9295 _("Remote target failed to process qGetTLSAddr request"));
9296 }
9297 else
9298 throw_error (TLS_GENERIC_ERROR,
9299 _("TLS not supported or disabled on this target"));
9300 /* Not reached. */
9301 return 0;
9302 }
9303
9304 /* Provide thread local base, i.e. Thread Information Block address.
9305 Returns 1 if ptid is found and thread_local_base is non zero. */
9306
9307 static int
9308 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
9309 {
9310 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
9311 {
9312 struct remote_state *rs = get_remote_state ();
9313 char *p = rs->buf;
9314 char *endp = rs->buf + get_remote_packet_size ();
9315 enum packet_result result;
9316
9317 strcpy (p, "qGetTIBAddr:");
9318 p += strlen (p);
9319 p = write_ptid (p, endp, ptid);
9320 *p++ = '\0';
9321
9322 putpkt (rs->buf);
9323 getpkt (&rs->buf, &rs->buf_size, 0);
9324 result = packet_ok (rs->buf,
9325 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9326 if (result == PACKET_OK)
9327 {
9328 ULONGEST result;
9329
9330 unpack_varlen_hex (rs->buf, &result);
9331 if (addr)
9332 *addr = (CORE_ADDR) result;
9333 return 1;
9334 }
9335 else if (result == PACKET_UNKNOWN)
9336 error (_("Remote target doesn't support qGetTIBAddr packet"));
9337 else
9338 error (_("Remote target failed to process qGetTIBAddr request"));
9339 }
9340 else
9341 error (_("qGetTIBAddr not supported or disabled on this target"));
9342 /* Not reached. */
9343 return 0;
9344 }
9345
9346 /* Support for inferring a target description based on the current
9347 architecture and the size of a 'g' packet. While the 'g' packet
9348 can have any size (since optional registers can be left off the
9349 end), some sizes are easily recognizable given knowledge of the
9350 approximate architecture. */
9351
9352 struct remote_g_packet_guess
9353 {
9354 int bytes;
9355 const struct target_desc *tdesc;
9356 };
9357 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9358 DEF_VEC_O(remote_g_packet_guess_s);
9359
9360 struct remote_g_packet_data
9361 {
9362 VEC(remote_g_packet_guess_s) *guesses;
9363 };
9364
9365 static struct gdbarch_data *remote_g_packet_data_handle;
9366
9367 static void *
9368 remote_g_packet_data_init (struct obstack *obstack)
9369 {
9370 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9371 }
9372
9373 void
9374 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9375 const struct target_desc *tdesc)
9376 {
9377 struct remote_g_packet_data *data
9378 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9379 struct remote_g_packet_guess new_guess, *guess;
9380 int ix;
9381
9382 gdb_assert (tdesc != NULL);
9383
9384 for (ix = 0;
9385 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9386 ix++)
9387 if (guess->bytes == bytes)
9388 internal_error (__FILE__, __LINE__,
9389 _("Duplicate g packet description added for size %d"),
9390 bytes);
9391
9392 new_guess.bytes = bytes;
9393 new_guess.tdesc = tdesc;
9394 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9395 }
9396
9397 /* Return 1 if remote_read_description would do anything on this target
9398 and architecture, 0 otherwise. */
9399
9400 static int
9401 remote_read_description_p (struct target_ops *target)
9402 {
9403 struct remote_g_packet_data *data
9404 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9405
9406 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9407 return 1;
9408
9409 return 0;
9410 }
9411
9412 static const struct target_desc *
9413 remote_read_description (struct target_ops *target)
9414 {
9415 struct remote_g_packet_data *data
9416 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9417
9418 /* Do not try this during initial connection, when we do not know
9419 whether there is a running but stopped thread. */
9420 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
9421 return target->beneath->to_read_description (target->beneath);
9422
9423 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9424 {
9425 struct remote_g_packet_guess *guess;
9426 int ix;
9427 int bytes = send_g_packet ();
9428
9429 for (ix = 0;
9430 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9431 ix++)
9432 if (guess->bytes == bytes)
9433 return guess->tdesc;
9434
9435 /* We discard the g packet. A minor optimization would be to
9436 hold on to it, and fill the register cache once we have selected
9437 an architecture, but it's too tricky to do safely. */
9438 }
9439
9440 return target->beneath->to_read_description (target->beneath);
9441 }
9442
9443 /* Remote file transfer support. This is host-initiated I/O, not
9444 target-initiated; for target-initiated, see remote-fileio.c. */
9445
9446 /* If *LEFT is at least the length of STRING, copy STRING to
9447 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9448 decrease *LEFT. Otherwise raise an error. */
9449
9450 static void
9451 remote_buffer_add_string (char **buffer, int *left, char *string)
9452 {
9453 int len = strlen (string);
9454
9455 if (len > *left)
9456 error (_("Packet too long for target."));
9457
9458 memcpy (*buffer, string, len);
9459 *buffer += len;
9460 *left -= len;
9461
9462 /* NUL-terminate the buffer as a convenience, if there is
9463 room. */
9464 if (*left)
9465 **buffer = '\0';
9466 }
9467
9468 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9469 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9470 decrease *LEFT. Otherwise raise an error. */
9471
9472 static void
9473 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9474 int len)
9475 {
9476 if (2 * len > *left)
9477 error (_("Packet too long for target."));
9478
9479 bin2hex (bytes, *buffer, len);
9480 *buffer += 2 * len;
9481 *left -= 2 * len;
9482
9483 /* NUL-terminate the buffer as a convenience, if there is
9484 room. */
9485 if (*left)
9486 **buffer = '\0';
9487 }
9488
9489 /* If *LEFT is large enough, convert VALUE to hex and add it to
9490 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9491 decrease *LEFT. Otherwise raise an error. */
9492
9493 static void
9494 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9495 {
9496 int len = hexnumlen (value);
9497
9498 if (len > *left)
9499 error (_("Packet too long for target."));
9500
9501 hexnumstr (*buffer, value);
9502 *buffer += len;
9503 *left -= len;
9504
9505 /* NUL-terminate the buffer as a convenience, if there is
9506 room. */
9507 if (*left)
9508 **buffer = '\0';
9509 }
9510
9511 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9512 value, *REMOTE_ERRNO to the remote error number or zero if none
9513 was included, and *ATTACHMENT to point to the start of the annex
9514 if any. The length of the packet isn't needed here; there may
9515 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9516
9517 Return 0 if the packet could be parsed, -1 if it could not. If
9518 -1 is returned, the other variables may not be initialized. */
9519
9520 static int
9521 remote_hostio_parse_result (char *buffer, int *retcode,
9522 int *remote_errno, char **attachment)
9523 {
9524 char *p, *p2;
9525
9526 *remote_errno = 0;
9527 *attachment = NULL;
9528
9529 if (buffer[0] != 'F')
9530 return -1;
9531
9532 errno = 0;
9533 *retcode = strtol (&buffer[1], &p, 16);
9534 if (errno != 0 || p == &buffer[1])
9535 return -1;
9536
9537 /* Check for ",errno". */
9538 if (*p == ',')
9539 {
9540 errno = 0;
9541 *remote_errno = strtol (p + 1, &p2, 16);
9542 if (errno != 0 || p + 1 == p2)
9543 return -1;
9544 p = p2;
9545 }
9546
9547 /* Check for ";attachment". If there is no attachment, the
9548 packet should end here. */
9549 if (*p == ';')
9550 {
9551 *attachment = p + 1;
9552 return 0;
9553 }
9554 else if (*p == '\0')
9555 return 0;
9556 else
9557 return -1;
9558 }
9559
9560 /* Send a prepared I/O packet to the target and read its response.
9561 The prepared packet is in the global RS->BUF before this function
9562 is called, and the answer is there when we return.
9563
9564 COMMAND_BYTES is the length of the request to send, which may include
9565 binary data. WHICH_PACKET is the packet configuration to check
9566 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9567 is set to the error number and -1 is returned. Otherwise the value
9568 returned by the function is returned.
9569
9570 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9571 attachment is expected; an error will be reported if there's a
9572 mismatch. If one is found, *ATTACHMENT will be set to point into
9573 the packet buffer and *ATTACHMENT_LEN will be set to the
9574 attachment's length. */
9575
9576 static int
9577 remote_hostio_send_command (int command_bytes, int which_packet,
9578 int *remote_errno, char **attachment,
9579 int *attachment_len)
9580 {
9581 struct remote_state *rs = get_remote_state ();
9582 int ret, bytes_read;
9583 char *attachment_tmp;
9584
9585 if (!rs->remote_desc
9586 || packet_support (which_packet) == PACKET_DISABLE)
9587 {
9588 *remote_errno = FILEIO_ENOSYS;
9589 return -1;
9590 }
9591
9592 putpkt_binary (rs->buf, command_bytes);
9593 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9594
9595 /* If it timed out, something is wrong. Don't try to parse the
9596 buffer. */
9597 if (bytes_read < 0)
9598 {
9599 *remote_errno = FILEIO_EINVAL;
9600 return -1;
9601 }
9602
9603 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9604 {
9605 case PACKET_ERROR:
9606 *remote_errno = FILEIO_EINVAL;
9607 return -1;
9608 case PACKET_UNKNOWN:
9609 *remote_errno = FILEIO_ENOSYS;
9610 return -1;
9611 case PACKET_OK:
9612 break;
9613 }
9614
9615 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9616 &attachment_tmp))
9617 {
9618 *remote_errno = FILEIO_EINVAL;
9619 return -1;
9620 }
9621
9622 /* Make sure we saw an attachment if and only if we expected one. */
9623 if ((attachment_tmp == NULL && attachment != NULL)
9624 || (attachment_tmp != NULL && attachment == NULL))
9625 {
9626 *remote_errno = FILEIO_EINVAL;
9627 return -1;
9628 }
9629
9630 /* If an attachment was found, it must point into the packet buffer;
9631 work out how many bytes there were. */
9632 if (attachment_tmp != NULL)
9633 {
9634 *attachment = attachment_tmp;
9635 *attachment_len = bytes_read - (*attachment - rs->buf);
9636 }
9637
9638 return ret;
9639 }
9640
9641 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9642 remote file descriptor, or -1 if an error occurs (and set
9643 *REMOTE_ERRNO). */
9644
9645 static int
9646 remote_hostio_open (struct target_ops *self,
9647 const char *filename, int flags, int mode,
9648 int *remote_errno)
9649 {
9650 struct remote_state *rs = get_remote_state ();
9651 char *p = rs->buf;
9652 int left = get_remote_packet_size () - 1;
9653
9654 remote_buffer_add_string (&p, &left, "vFile:open:");
9655
9656 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9657 strlen (filename));
9658 remote_buffer_add_string (&p, &left, ",");
9659
9660 remote_buffer_add_int (&p, &left, flags);
9661 remote_buffer_add_string (&p, &left, ",");
9662
9663 remote_buffer_add_int (&p, &left, mode);
9664
9665 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9666 remote_errno, NULL, NULL);
9667 }
9668
9669 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9670 Return the number of bytes written, or -1 if an error occurs (and
9671 set *REMOTE_ERRNO). */
9672
9673 static int
9674 remote_hostio_pwrite (struct target_ops *self,
9675 int fd, const gdb_byte *write_buf, int len,
9676 ULONGEST offset, int *remote_errno)
9677 {
9678 struct remote_state *rs = get_remote_state ();
9679 char *p = rs->buf;
9680 int left = get_remote_packet_size ();
9681 int out_len;
9682
9683 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9684
9685 remote_buffer_add_int (&p, &left, fd);
9686 remote_buffer_add_string (&p, &left, ",");
9687
9688 remote_buffer_add_int (&p, &left, offset);
9689 remote_buffer_add_string (&p, &left, ",");
9690
9691 p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
9692 get_remote_packet_size () - (p - rs->buf));
9693
9694 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9695 remote_errno, NULL, NULL);
9696 }
9697
9698 /* Read up to LEN bytes FD on the remote target into READ_BUF
9699 Return the number of bytes read, or -1 if an error occurs (and
9700 set *REMOTE_ERRNO). */
9701
9702 static int
9703 remote_hostio_pread (struct target_ops *self,
9704 int fd, gdb_byte *read_buf, int len,
9705 ULONGEST offset, int *remote_errno)
9706 {
9707 struct remote_state *rs = get_remote_state ();
9708 char *p = rs->buf;
9709 char *attachment;
9710 int left = get_remote_packet_size ();
9711 int ret, attachment_len;
9712 int read_len;
9713
9714 remote_buffer_add_string (&p, &left, "vFile:pread:");
9715
9716 remote_buffer_add_int (&p, &left, fd);
9717 remote_buffer_add_string (&p, &left, ",");
9718
9719 remote_buffer_add_int (&p, &left, len);
9720 remote_buffer_add_string (&p, &left, ",");
9721
9722 remote_buffer_add_int (&p, &left, offset);
9723
9724 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9725 remote_errno, &attachment,
9726 &attachment_len);
9727
9728 if (ret < 0)
9729 return ret;
9730
9731 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9732 read_buf, len);
9733 if (read_len != ret)
9734 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9735
9736 return ret;
9737 }
9738
9739 /* Close FD on the remote target. Return 0, or -1 if an error occurs
9740 (and set *REMOTE_ERRNO). */
9741
9742 static int
9743 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
9744 {
9745 struct remote_state *rs = get_remote_state ();
9746 char *p = rs->buf;
9747 int left = get_remote_packet_size () - 1;
9748
9749 remote_buffer_add_string (&p, &left, "vFile:close:");
9750
9751 remote_buffer_add_int (&p, &left, fd);
9752
9753 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
9754 remote_errno, NULL, NULL);
9755 }
9756
9757 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
9758 occurs (and set *REMOTE_ERRNO). */
9759
9760 static int
9761 remote_hostio_unlink (struct target_ops *self,
9762 const char *filename, int *remote_errno)
9763 {
9764 struct remote_state *rs = get_remote_state ();
9765 char *p = rs->buf;
9766 int left = get_remote_packet_size () - 1;
9767
9768 remote_buffer_add_string (&p, &left, "vFile:unlink:");
9769
9770 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9771 strlen (filename));
9772
9773 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
9774 remote_errno, NULL, NULL);
9775 }
9776
9777 /* Read value of symbolic link FILENAME on the remote target. Return
9778 a null-terminated string allocated via xmalloc, or NULL if an error
9779 occurs (and set *REMOTE_ERRNO). */
9780
9781 static char *
9782 remote_hostio_readlink (struct target_ops *self,
9783 const char *filename, int *remote_errno)
9784 {
9785 struct remote_state *rs = get_remote_state ();
9786 char *p = rs->buf;
9787 char *attachment;
9788 int left = get_remote_packet_size ();
9789 int len, attachment_len;
9790 int read_len;
9791 char *ret;
9792
9793 remote_buffer_add_string (&p, &left, "vFile:readlink:");
9794
9795 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9796 strlen (filename));
9797
9798 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
9799 remote_errno, &attachment,
9800 &attachment_len);
9801
9802 if (len < 0)
9803 return NULL;
9804
9805 ret = xmalloc (len + 1);
9806
9807 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9808 (gdb_byte *) ret, len);
9809 if (read_len != len)
9810 error (_("Readlink returned %d, but %d bytes."), len, read_len);
9811
9812 ret[len] = '\0';
9813 return ret;
9814 }
9815
9816 static int
9817 remote_fileio_errno_to_host (int errnum)
9818 {
9819 switch (errnum)
9820 {
9821 case FILEIO_EPERM:
9822 return EPERM;
9823 case FILEIO_ENOENT:
9824 return ENOENT;
9825 case FILEIO_EINTR:
9826 return EINTR;
9827 case FILEIO_EIO:
9828 return EIO;
9829 case FILEIO_EBADF:
9830 return EBADF;
9831 case FILEIO_EACCES:
9832 return EACCES;
9833 case FILEIO_EFAULT:
9834 return EFAULT;
9835 case FILEIO_EBUSY:
9836 return EBUSY;
9837 case FILEIO_EEXIST:
9838 return EEXIST;
9839 case FILEIO_ENODEV:
9840 return ENODEV;
9841 case FILEIO_ENOTDIR:
9842 return ENOTDIR;
9843 case FILEIO_EISDIR:
9844 return EISDIR;
9845 case FILEIO_EINVAL:
9846 return EINVAL;
9847 case FILEIO_ENFILE:
9848 return ENFILE;
9849 case FILEIO_EMFILE:
9850 return EMFILE;
9851 case FILEIO_EFBIG:
9852 return EFBIG;
9853 case FILEIO_ENOSPC:
9854 return ENOSPC;
9855 case FILEIO_ESPIPE:
9856 return ESPIPE;
9857 case FILEIO_EROFS:
9858 return EROFS;
9859 case FILEIO_ENOSYS:
9860 return ENOSYS;
9861 case FILEIO_ENAMETOOLONG:
9862 return ENAMETOOLONG;
9863 }
9864 return -1;
9865 }
9866
9867 static char *
9868 remote_hostio_error (int errnum)
9869 {
9870 int host_error = remote_fileio_errno_to_host (errnum);
9871
9872 if (host_error == -1)
9873 error (_("Unknown remote I/O error %d"), errnum);
9874 else
9875 error (_("Remote I/O error: %s"), safe_strerror (host_error));
9876 }
9877
9878 static void
9879 remote_hostio_close_cleanup (void *opaque)
9880 {
9881 int fd = *(int *) opaque;
9882 int remote_errno;
9883
9884 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
9885 }
9886
9887
9888 static void *
9889 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
9890 {
9891 const char *filename = bfd_get_filename (abfd);
9892 int fd, remote_errno;
9893 int *stream;
9894
9895 gdb_assert (remote_filename_p (filename));
9896
9897 fd = remote_hostio_open (find_target_at (process_stratum),
9898 filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
9899 if (fd == -1)
9900 {
9901 errno = remote_fileio_errno_to_host (remote_errno);
9902 bfd_set_error (bfd_error_system_call);
9903 return NULL;
9904 }
9905
9906 stream = xmalloc (sizeof (int));
9907 *stream = fd;
9908 return stream;
9909 }
9910
9911 static int
9912 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
9913 {
9914 int fd = *(int *)stream;
9915 int remote_errno;
9916
9917 xfree (stream);
9918
9919 /* Ignore errors on close; these may happen if the remote
9920 connection was already torn down. */
9921 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
9922
9923 /* Zero means success. */
9924 return 0;
9925 }
9926
9927 static file_ptr
9928 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
9929 file_ptr nbytes, file_ptr offset)
9930 {
9931 int fd = *(int *)stream;
9932 int remote_errno;
9933 file_ptr pos, bytes;
9934
9935 pos = 0;
9936 while (nbytes > pos)
9937 {
9938 bytes = remote_hostio_pread (find_target_at (process_stratum),
9939 fd, (gdb_byte *) buf + pos, nbytes - pos,
9940 offset + pos, &remote_errno);
9941 if (bytes == 0)
9942 /* Success, but no bytes, means end-of-file. */
9943 break;
9944 if (bytes == -1)
9945 {
9946 errno = remote_fileio_errno_to_host (remote_errno);
9947 bfd_set_error (bfd_error_system_call);
9948 return -1;
9949 }
9950
9951 pos += bytes;
9952 }
9953
9954 return pos;
9955 }
9956
9957 static int
9958 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
9959 {
9960 /* FIXME: We should probably implement remote_hostio_stat. */
9961 sb->st_size = INT_MAX;
9962 return 0;
9963 }
9964
9965 int
9966 remote_filename_p (const char *filename)
9967 {
9968 return strncmp (filename,
9969 REMOTE_SYSROOT_PREFIX,
9970 sizeof (REMOTE_SYSROOT_PREFIX) - 1) == 0;
9971 }
9972
9973 bfd *
9974 remote_bfd_open (const char *remote_file, const char *target)
9975 {
9976 bfd *abfd = gdb_bfd_openr_iovec (remote_file, target,
9977 remote_bfd_iovec_open, NULL,
9978 remote_bfd_iovec_pread,
9979 remote_bfd_iovec_close,
9980 remote_bfd_iovec_stat);
9981
9982 return abfd;
9983 }
9984
9985 void
9986 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
9987 {
9988 struct cleanup *back_to, *close_cleanup;
9989 int retcode, fd, remote_errno, bytes, io_size;
9990 FILE *file;
9991 gdb_byte *buffer;
9992 int bytes_in_buffer;
9993 int saw_eof;
9994 ULONGEST offset;
9995 struct remote_state *rs = get_remote_state ();
9996
9997 if (!rs->remote_desc)
9998 error (_("command can only be used with remote target"));
9999
10000 file = gdb_fopen_cloexec (local_file, "rb");
10001 if (file == NULL)
10002 perror_with_name (local_file);
10003 back_to = make_cleanup_fclose (file);
10004
10005 fd = remote_hostio_open (find_target_at (process_stratum),
10006 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
10007 | FILEIO_O_TRUNC),
10008 0700, &remote_errno);
10009 if (fd == -1)
10010 remote_hostio_error (remote_errno);
10011
10012 /* Send up to this many bytes at once. They won't all fit in the
10013 remote packet limit, so we'll transfer slightly fewer. */
10014 io_size = get_remote_packet_size ();
10015 buffer = xmalloc (io_size);
10016 make_cleanup (xfree, buffer);
10017
10018 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10019
10020 bytes_in_buffer = 0;
10021 saw_eof = 0;
10022 offset = 0;
10023 while (bytes_in_buffer || !saw_eof)
10024 {
10025 if (!saw_eof)
10026 {
10027 bytes = fread (buffer + bytes_in_buffer, 1,
10028 io_size - bytes_in_buffer,
10029 file);
10030 if (bytes == 0)
10031 {
10032 if (ferror (file))
10033 error (_("Error reading %s."), local_file);
10034 else
10035 {
10036 /* EOF. Unless there is something still in the
10037 buffer from the last iteration, we are done. */
10038 saw_eof = 1;
10039 if (bytes_in_buffer == 0)
10040 break;
10041 }
10042 }
10043 }
10044 else
10045 bytes = 0;
10046
10047 bytes += bytes_in_buffer;
10048 bytes_in_buffer = 0;
10049
10050 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
10051 fd, buffer, bytes,
10052 offset, &remote_errno);
10053
10054 if (retcode < 0)
10055 remote_hostio_error (remote_errno);
10056 else if (retcode == 0)
10057 error (_("Remote write of %d bytes returned 0!"), bytes);
10058 else if (retcode < bytes)
10059 {
10060 /* Short write. Save the rest of the read data for the next
10061 write. */
10062 bytes_in_buffer = bytes - retcode;
10063 memmove (buffer, buffer + retcode, bytes_in_buffer);
10064 }
10065
10066 offset += retcode;
10067 }
10068
10069 discard_cleanups (close_cleanup);
10070 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
10071 remote_hostio_error (remote_errno);
10072
10073 if (from_tty)
10074 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10075 do_cleanups (back_to);
10076 }
10077
10078 void
10079 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10080 {
10081 struct cleanup *back_to, *close_cleanup;
10082 int fd, remote_errno, bytes, io_size;
10083 FILE *file;
10084 gdb_byte *buffer;
10085 ULONGEST offset;
10086 struct remote_state *rs = get_remote_state ();
10087
10088 if (!rs->remote_desc)
10089 error (_("command can only be used with remote target"));
10090
10091 fd = remote_hostio_open (find_target_at (process_stratum),
10092 remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
10093 if (fd == -1)
10094 remote_hostio_error (remote_errno);
10095
10096 file = gdb_fopen_cloexec (local_file, "wb");
10097 if (file == NULL)
10098 perror_with_name (local_file);
10099 back_to = make_cleanup_fclose (file);
10100
10101 /* Send up to this many bytes at once. They won't all fit in the
10102 remote packet limit, so we'll transfer slightly fewer. */
10103 io_size = get_remote_packet_size ();
10104 buffer = xmalloc (io_size);
10105 make_cleanup (xfree, buffer);
10106
10107 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10108
10109 offset = 0;
10110 while (1)
10111 {
10112 bytes = remote_hostio_pread (find_target_at (process_stratum),
10113 fd, buffer, io_size, offset, &remote_errno);
10114 if (bytes == 0)
10115 /* Success, but no bytes, means end-of-file. */
10116 break;
10117 if (bytes == -1)
10118 remote_hostio_error (remote_errno);
10119
10120 offset += bytes;
10121
10122 bytes = fwrite (buffer, 1, bytes, file);
10123 if (bytes == 0)
10124 perror_with_name (local_file);
10125 }
10126
10127 discard_cleanups (close_cleanup);
10128 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
10129 remote_hostio_error (remote_errno);
10130
10131 if (from_tty)
10132 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10133 do_cleanups (back_to);
10134 }
10135
10136 void
10137 remote_file_delete (const char *remote_file, int from_tty)
10138 {
10139 int retcode, remote_errno;
10140 struct remote_state *rs = get_remote_state ();
10141
10142 if (!rs->remote_desc)
10143 error (_("command can only be used with remote target"));
10144
10145 retcode = remote_hostio_unlink (find_target_at (process_stratum),
10146 remote_file, &remote_errno);
10147 if (retcode == -1)
10148 remote_hostio_error (remote_errno);
10149
10150 if (from_tty)
10151 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10152 }
10153
10154 static void
10155 remote_put_command (char *args, int from_tty)
10156 {
10157 struct cleanup *back_to;
10158 char **argv;
10159
10160 if (args == NULL)
10161 error_no_arg (_("file to put"));
10162
10163 argv = gdb_buildargv (args);
10164 back_to = make_cleanup_freeargv (argv);
10165 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10166 error (_("Invalid parameters to remote put"));
10167
10168 remote_file_put (argv[0], argv[1], from_tty);
10169
10170 do_cleanups (back_to);
10171 }
10172
10173 static void
10174 remote_get_command (char *args, int from_tty)
10175 {
10176 struct cleanup *back_to;
10177 char **argv;
10178
10179 if (args == NULL)
10180 error_no_arg (_("file to get"));
10181
10182 argv = gdb_buildargv (args);
10183 back_to = make_cleanup_freeargv (argv);
10184 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10185 error (_("Invalid parameters to remote get"));
10186
10187 remote_file_get (argv[0], argv[1], from_tty);
10188
10189 do_cleanups (back_to);
10190 }
10191
10192 static void
10193 remote_delete_command (char *args, int from_tty)
10194 {
10195 struct cleanup *back_to;
10196 char **argv;
10197
10198 if (args == NULL)
10199 error_no_arg (_("file to delete"));
10200
10201 argv = gdb_buildargv (args);
10202 back_to = make_cleanup_freeargv (argv);
10203 if (argv[0] == NULL || argv[1] != NULL)
10204 error (_("Invalid parameters to remote delete"));
10205
10206 remote_file_delete (argv[0], from_tty);
10207
10208 do_cleanups (back_to);
10209 }
10210
10211 static void
10212 remote_command (char *args, int from_tty)
10213 {
10214 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
10215 }
10216
10217 static int
10218 remote_can_execute_reverse (struct target_ops *self)
10219 {
10220 if (packet_support (PACKET_bs) == PACKET_ENABLE
10221 || packet_support (PACKET_bc) == PACKET_ENABLE)
10222 return 1;
10223 else
10224 return 0;
10225 }
10226
10227 static int
10228 remote_supports_non_stop (struct target_ops *self)
10229 {
10230 return 1;
10231 }
10232
10233 static int
10234 remote_supports_disable_randomization (struct target_ops *self)
10235 {
10236 /* Only supported in extended mode. */
10237 return 0;
10238 }
10239
10240 static int
10241 remote_supports_multi_process (struct target_ops *self)
10242 {
10243 struct remote_state *rs = get_remote_state ();
10244
10245 /* Only extended-remote handles being attached to multiple
10246 processes, even though plain remote can use the multi-process
10247 thread id extensions, so that GDB knows the target process's
10248 PID. */
10249 return rs->extended && remote_multi_process_p (rs);
10250 }
10251
10252 static int
10253 remote_supports_cond_tracepoints (void)
10254 {
10255 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
10256 }
10257
10258 static int
10259 remote_supports_cond_breakpoints (struct target_ops *self)
10260 {
10261 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
10262 }
10263
10264 static int
10265 remote_supports_fast_tracepoints (void)
10266 {
10267 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
10268 }
10269
10270 static int
10271 remote_supports_static_tracepoints (void)
10272 {
10273 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
10274 }
10275
10276 static int
10277 remote_supports_install_in_trace (void)
10278 {
10279 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
10280 }
10281
10282 static int
10283 remote_supports_enable_disable_tracepoint (struct target_ops *self)
10284 {
10285 return (packet_support (PACKET_EnableDisableTracepoints_feature)
10286 == PACKET_ENABLE);
10287 }
10288
10289 static int
10290 remote_supports_string_tracing (struct target_ops *self)
10291 {
10292 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
10293 }
10294
10295 static int
10296 remote_can_run_breakpoint_commands (struct target_ops *self)
10297 {
10298 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
10299 }
10300
10301 static void
10302 remote_trace_init (struct target_ops *self)
10303 {
10304 putpkt ("QTinit");
10305 remote_get_noisy_reply (&target_buf, &target_buf_size);
10306 if (strcmp (target_buf, "OK") != 0)
10307 error (_("Target does not support this command."));
10308 }
10309
10310 static void free_actions_list (char **actions_list);
10311 static void free_actions_list_cleanup_wrapper (void *);
10312 static void
10313 free_actions_list_cleanup_wrapper (void *al)
10314 {
10315 free_actions_list (al);
10316 }
10317
10318 static void
10319 free_actions_list (char **actions_list)
10320 {
10321 int ndx;
10322
10323 if (actions_list == 0)
10324 return;
10325
10326 for (ndx = 0; actions_list[ndx]; ndx++)
10327 xfree (actions_list[ndx]);
10328
10329 xfree (actions_list);
10330 }
10331
10332 /* Recursive routine to walk through command list including loops, and
10333 download packets for each command. */
10334
10335 static void
10336 remote_download_command_source (int num, ULONGEST addr,
10337 struct command_line *cmds)
10338 {
10339 struct remote_state *rs = get_remote_state ();
10340 struct command_line *cmd;
10341
10342 for (cmd = cmds; cmd; cmd = cmd->next)
10343 {
10344 QUIT; /* Allow user to bail out with ^C. */
10345 strcpy (rs->buf, "QTDPsrc:");
10346 encode_source_string (num, addr, "cmd", cmd->line,
10347 rs->buf + strlen (rs->buf),
10348 rs->buf_size - strlen (rs->buf));
10349 putpkt (rs->buf);
10350 remote_get_noisy_reply (&target_buf, &target_buf_size);
10351 if (strcmp (target_buf, "OK"))
10352 warning (_("Target does not support source download."));
10353
10354 if (cmd->control_type == while_control
10355 || cmd->control_type == while_stepping_control)
10356 {
10357 remote_download_command_source (num, addr, *cmd->body_list);
10358
10359 QUIT; /* Allow user to bail out with ^C. */
10360 strcpy (rs->buf, "QTDPsrc:");
10361 encode_source_string (num, addr, "cmd", "end",
10362 rs->buf + strlen (rs->buf),
10363 rs->buf_size - strlen (rs->buf));
10364 putpkt (rs->buf);
10365 remote_get_noisy_reply (&target_buf, &target_buf_size);
10366 if (strcmp (target_buf, "OK"))
10367 warning (_("Target does not support source download."));
10368 }
10369 }
10370 }
10371
10372 static void
10373 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
10374 {
10375 #define BUF_SIZE 2048
10376
10377 CORE_ADDR tpaddr;
10378 char addrbuf[40];
10379 char buf[BUF_SIZE];
10380 char **tdp_actions;
10381 char **stepping_actions;
10382 int ndx;
10383 struct cleanup *old_chain = NULL;
10384 struct agent_expr *aexpr;
10385 struct cleanup *aexpr_chain = NULL;
10386 char *pkt;
10387 struct breakpoint *b = loc->owner;
10388 struct tracepoint *t = (struct tracepoint *) b;
10389
10390 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
10391 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10392 tdp_actions);
10393 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10394 stepping_actions);
10395
10396 tpaddr = loc->address;
10397 sprintf_vma (addrbuf, tpaddr);
10398 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10399 addrbuf, /* address */
10400 (b->enable_state == bp_enabled ? 'E' : 'D'),
10401 t->step_count, t->pass_count);
10402 /* Fast tracepoints are mostly handled by the target, but we can
10403 tell the target how big of an instruction block should be moved
10404 around. */
10405 if (b->type == bp_fast_tracepoint)
10406 {
10407 /* Only test for support at download time; we may not know
10408 target capabilities at definition time. */
10409 if (remote_supports_fast_tracepoints ())
10410 {
10411 int isize;
10412
10413 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
10414 tpaddr, &isize, NULL))
10415 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10416 isize);
10417 else
10418 /* If it passed validation at definition but fails now,
10419 something is very wrong. */
10420 internal_error (__FILE__, __LINE__,
10421 _("Fast tracepoint not "
10422 "valid during download"));
10423 }
10424 else
10425 /* Fast tracepoints are functionally identical to regular
10426 tracepoints, so don't take lack of support as a reason to
10427 give up on the trace run. */
10428 warning (_("Target does not support fast tracepoints, "
10429 "downloading %d as regular tracepoint"), b->number);
10430 }
10431 else if (b->type == bp_static_tracepoint)
10432 {
10433 /* Only test for support at download time; we may not know
10434 target capabilities at definition time. */
10435 if (remote_supports_static_tracepoints ())
10436 {
10437 struct static_tracepoint_marker marker;
10438
10439 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10440 strcat (buf, ":S");
10441 else
10442 error (_("Static tracepoint not valid during download"));
10443 }
10444 else
10445 /* Fast tracepoints are functionally identical to regular
10446 tracepoints, so don't take lack of support as a reason
10447 to give up on the trace run. */
10448 error (_("Target does not support static tracepoints"));
10449 }
10450 /* If the tracepoint has a conditional, make it into an agent
10451 expression and append to the definition. */
10452 if (loc->cond)
10453 {
10454 /* Only test support at download time, we may not know target
10455 capabilities at definition time. */
10456 if (remote_supports_cond_tracepoints ())
10457 {
10458 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10459 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
10460 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10461 aexpr->len);
10462 pkt = buf + strlen (buf);
10463 for (ndx = 0; ndx < aexpr->len; ++ndx)
10464 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10465 *pkt = '\0';
10466 do_cleanups (aexpr_chain);
10467 }
10468 else
10469 warning (_("Target does not support conditional tracepoints, "
10470 "ignoring tp %d cond"), b->number);
10471 }
10472
10473 if (b->commands || *default_collect)
10474 strcat (buf, "-");
10475 putpkt (buf);
10476 remote_get_noisy_reply (&target_buf, &target_buf_size);
10477 if (strcmp (target_buf, "OK"))
10478 error (_("Target does not support tracepoints."));
10479
10480 /* do_single_steps (t); */
10481 if (tdp_actions)
10482 {
10483 for (ndx = 0; tdp_actions[ndx]; ndx++)
10484 {
10485 QUIT; /* Allow user to bail out with ^C. */
10486 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10487 b->number, addrbuf, /* address */
10488 tdp_actions[ndx],
10489 ((tdp_actions[ndx + 1] || stepping_actions)
10490 ? '-' : 0));
10491 putpkt (buf);
10492 remote_get_noisy_reply (&target_buf,
10493 &target_buf_size);
10494 if (strcmp (target_buf, "OK"))
10495 error (_("Error on target while setting tracepoints."));
10496 }
10497 }
10498 if (stepping_actions)
10499 {
10500 for (ndx = 0; stepping_actions[ndx]; ndx++)
10501 {
10502 QUIT; /* Allow user to bail out with ^C. */
10503 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10504 b->number, addrbuf, /* address */
10505 ((ndx == 0) ? "S" : ""),
10506 stepping_actions[ndx],
10507 (stepping_actions[ndx + 1] ? "-" : ""));
10508 putpkt (buf);
10509 remote_get_noisy_reply (&target_buf,
10510 &target_buf_size);
10511 if (strcmp (target_buf, "OK"))
10512 error (_("Error on target while setting tracepoints."));
10513 }
10514 }
10515
10516 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
10517 {
10518 if (b->addr_string)
10519 {
10520 strcpy (buf, "QTDPsrc:");
10521 encode_source_string (b->number, loc->address,
10522 "at", b->addr_string, buf + strlen (buf),
10523 2048 - strlen (buf));
10524
10525 putpkt (buf);
10526 remote_get_noisy_reply (&target_buf, &target_buf_size);
10527 if (strcmp (target_buf, "OK"))
10528 warning (_("Target does not support source download."));
10529 }
10530 if (b->cond_string)
10531 {
10532 strcpy (buf, "QTDPsrc:");
10533 encode_source_string (b->number, loc->address,
10534 "cond", b->cond_string, buf + strlen (buf),
10535 2048 - strlen (buf));
10536 putpkt (buf);
10537 remote_get_noisy_reply (&target_buf, &target_buf_size);
10538 if (strcmp (target_buf, "OK"))
10539 warning (_("Target does not support source download."));
10540 }
10541 remote_download_command_source (b->number, loc->address,
10542 breakpoint_commands (b));
10543 }
10544
10545 do_cleanups (old_chain);
10546 }
10547
10548 static int
10549 remote_can_download_tracepoint (struct target_ops *self)
10550 {
10551 struct remote_state *rs = get_remote_state ();
10552 struct trace_status *ts;
10553 int status;
10554
10555 /* Don't try to install tracepoints until we've relocated our
10556 symbols, and fetched and merged the target's tracepoint list with
10557 ours. */
10558 if (rs->starting_up)
10559 return 0;
10560
10561 ts = current_trace_status ();
10562 status = remote_get_trace_status (self, ts);
10563
10564 if (status == -1 || !ts->running_known || !ts->running)
10565 return 0;
10566
10567 /* If we are in a tracing experiment, but remote stub doesn't support
10568 installing tracepoint in trace, we have to return. */
10569 if (!remote_supports_install_in_trace ())
10570 return 0;
10571
10572 return 1;
10573 }
10574
10575
10576 static void
10577 remote_download_trace_state_variable (struct target_ops *self,
10578 struct trace_state_variable *tsv)
10579 {
10580 struct remote_state *rs = get_remote_state ();
10581 char *p;
10582
10583 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10584 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10585 tsv->builtin);
10586 p = rs->buf + strlen (rs->buf);
10587 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10588 error (_("Trace state variable name too long for tsv definition packet"));
10589 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
10590 *p++ = '\0';
10591 putpkt (rs->buf);
10592 remote_get_noisy_reply (&target_buf, &target_buf_size);
10593 if (*target_buf == '\0')
10594 error (_("Target does not support this command."));
10595 if (strcmp (target_buf, "OK") != 0)
10596 error (_("Error on target while downloading trace state variable."));
10597 }
10598
10599 static void
10600 remote_enable_tracepoint (struct target_ops *self,
10601 struct bp_location *location)
10602 {
10603 struct remote_state *rs = get_remote_state ();
10604 char addr_buf[40];
10605
10606 sprintf_vma (addr_buf, location->address);
10607 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10608 location->owner->number, addr_buf);
10609 putpkt (rs->buf);
10610 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10611 if (*rs->buf == '\0')
10612 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10613 if (strcmp (rs->buf, "OK") != 0)
10614 error (_("Error on target while enabling tracepoint."));
10615 }
10616
10617 static void
10618 remote_disable_tracepoint (struct target_ops *self,
10619 struct bp_location *location)
10620 {
10621 struct remote_state *rs = get_remote_state ();
10622 char addr_buf[40];
10623
10624 sprintf_vma (addr_buf, location->address);
10625 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10626 location->owner->number, addr_buf);
10627 putpkt (rs->buf);
10628 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10629 if (*rs->buf == '\0')
10630 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10631 if (strcmp (rs->buf, "OK") != 0)
10632 error (_("Error on target while disabling tracepoint."));
10633 }
10634
10635 static void
10636 remote_trace_set_readonly_regions (struct target_ops *self)
10637 {
10638 asection *s;
10639 bfd *abfd = NULL;
10640 bfd_size_type size;
10641 bfd_vma vma;
10642 int anysecs = 0;
10643 int offset = 0;
10644
10645 if (!exec_bfd)
10646 return; /* No information to give. */
10647
10648 strcpy (target_buf, "QTro");
10649 offset = strlen (target_buf);
10650 for (s = exec_bfd->sections; s; s = s->next)
10651 {
10652 char tmp1[40], tmp2[40];
10653 int sec_length;
10654
10655 if ((s->flags & SEC_LOAD) == 0 ||
10656 /* (s->flags & SEC_CODE) == 0 || */
10657 (s->flags & SEC_READONLY) == 0)
10658 continue;
10659
10660 anysecs = 1;
10661 vma = bfd_get_section_vma (abfd, s);
10662 size = bfd_get_section_size (s);
10663 sprintf_vma (tmp1, vma);
10664 sprintf_vma (tmp2, vma + size);
10665 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10666 if (offset + sec_length + 1 > target_buf_size)
10667 {
10668 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
10669 warning (_("\
10670 Too many sections for read-only sections definition packet."));
10671 break;
10672 }
10673 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10674 tmp1, tmp2);
10675 offset += sec_length;
10676 }
10677 if (anysecs)
10678 {
10679 putpkt (target_buf);
10680 getpkt (&target_buf, &target_buf_size, 0);
10681 }
10682 }
10683
10684 static void
10685 remote_trace_start (struct target_ops *self)
10686 {
10687 putpkt ("QTStart");
10688 remote_get_noisy_reply (&target_buf, &target_buf_size);
10689 if (*target_buf == '\0')
10690 error (_("Target does not support this command."));
10691 if (strcmp (target_buf, "OK") != 0)
10692 error (_("Bogus reply from target: %s"), target_buf);
10693 }
10694
10695 static int
10696 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
10697 {
10698 /* Initialize it just to avoid a GCC false warning. */
10699 char *p = NULL;
10700 /* FIXME we need to get register block size some other way. */
10701 extern int trace_regblock_size;
10702 volatile struct gdb_exception ex;
10703 enum packet_result result;
10704
10705 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
10706 return -1;
10707
10708 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10709
10710 putpkt ("qTStatus");
10711
10712 TRY_CATCH (ex, RETURN_MASK_ERROR)
10713 {
10714 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10715 }
10716 if (ex.reason < 0)
10717 {
10718 if (ex.error != TARGET_CLOSE_ERROR)
10719 {
10720 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10721 return -1;
10722 }
10723 throw_exception (ex);
10724 }
10725
10726 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
10727
10728 /* If the remote target doesn't do tracing, flag it. */
10729 if (result == PACKET_UNKNOWN)
10730 return -1;
10731
10732 /* We're working with a live target. */
10733 ts->filename = NULL;
10734
10735 if (*p++ != 'T')
10736 error (_("Bogus trace status reply from target: %s"), target_buf);
10737
10738 /* Function 'parse_trace_status' sets default value of each field of
10739 'ts' at first, so we don't have to do it here. */
10740 parse_trace_status (p, ts);
10741
10742 return ts->running;
10743 }
10744
10745 static void
10746 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
10747 struct uploaded_tp *utp)
10748 {
10749 struct remote_state *rs = get_remote_state ();
10750 char *reply;
10751 struct bp_location *loc;
10752 struct tracepoint *tp = (struct tracepoint *) bp;
10753 size_t size = get_remote_packet_size ();
10754
10755 if (tp)
10756 {
10757 tp->base.hit_count = 0;
10758 tp->traceframe_usage = 0;
10759 for (loc = tp->base.loc; loc; loc = loc->next)
10760 {
10761 /* If the tracepoint was never downloaded, don't go asking for
10762 any status. */
10763 if (tp->number_on_target == 0)
10764 continue;
10765 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
10766 phex_nz (loc->address, 0));
10767 putpkt (rs->buf);
10768 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10769 if (reply && *reply)
10770 {
10771 if (*reply == 'V')
10772 parse_tracepoint_status (reply + 1, bp, utp);
10773 }
10774 }
10775 }
10776 else if (utp)
10777 {
10778 utp->hit_count = 0;
10779 utp->traceframe_usage = 0;
10780 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
10781 phex_nz (utp->addr, 0));
10782 putpkt (rs->buf);
10783 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10784 if (reply && *reply)
10785 {
10786 if (*reply == 'V')
10787 parse_tracepoint_status (reply + 1, bp, utp);
10788 }
10789 }
10790 }
10791
10792 static void
10793 remote_trace_stop (struct target_ops *self)
10794 {
10795 putpkt ("QTStop");
10796 remote_get_noisy_reply (&target_buf, &target_buf_size);
10797 if (*target_buf == '\0')
10798 error (_("Target does not support this command."));
10799 if (strcmp (target_buf, "OK") != 0)
10800 error (_("Bogus reply from target: %s"), target_buf);
10801 }
10802
10803 static int
10804 remote_trace_find (struct target_ops *self,
10805 enum trace_find_type type, int num,
10806 CORE_ADDR addr1, CORE_ADDR addr2,
10807 int *tpp)
10808 {
10809 struct remote_state *rs = get_remote_state ();
10810 char *endbuf = rs->buf + get_remote_packet_size ();
10811 char *p, *reply;
10812 int target_frameno = -1, target_tracept = -1;
10813
10814 /* Lookups other than by absolute frame number depend on the current
10815 trace selected, so make sure it is correct on the remote end
10816 first. */
10817 if (type != tfind_number)
10818 set_remote_traceframe ();
10819
10820 p = rs->buf;
10821 strcpy (p, "QTFrame:");
10822 p = strchr (p, '\0');
10823 switch (type)
10824 {
10825 case tfind_number:
10826 xsnprintf (p, endbuf - p, "%x", num);
10827 break;
10828 case tfind_pc:
10829 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
10830 break;
10831 case tfind_tp:
10832 xsnprintf (p, endbuf - p, "tdp:%x", num);
10833 break;
10834 case tfind_range:
10835 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
10836 phex_nz (addr2, 0));
10837 break;
10838 case tfind_outside:
10839 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
10840 phex_nz (addr2, 0));
10841 break;
10842 default:
10843 error (_("Unknown trace find type %d"), type);
10844 }
10845
10846 putpkt (rs->buf);
10847 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
10848 if (*reply == '\0')
10849 error (_("Target does not support this command."));
10850
10851 while (reply && *reply)
10852 switch (*reply)
10853 {
10854 case 'F':
10855 p = ++reply;
10856 target_frameno = (int) strtol (p, &reply, 16);
10857 if (reply == p)
10858 error (_("Unable to parse trace frame number"));
10859 /* Don't update our remote traceframe number cache on failure
10860 to select a remote traceframe. */
10861 if (target_frameno == -1)
10862 return -1;
10863 break;
10864 case 'T':
10865 p = ++reply;
10866 target_tracept = (int) strtol (p, &reply, 16);
10867 if (reply == p)
10868 error (_("Unable to parse tracepoint number"));
10869 break;
10870 case 'O': /* "OK"? */
10871 if (reply[1] == 'K' && reply[2] == '\0')
10872 reply += 2;
10873 else
10874 error (_("Bogus reply from target: %s"), reply);
10875 break;
10876 default:
10877 error (_("Bogus reply from target: %s"), reply);
10878 }
10879 if (tpp)
10880 *tpp = target_tracept;
10881
10882 rs->remote_traceframe_number = target_frameno;
10883 return target_frameno;
10884 }
10885
10886 static int
10887 remote_get_trace_state_variable_value (struct target_ops *self,
10888 int tsvnum, LONGEST *val)
10889 {
10890 struct remote_state *rs = get_remote_state ();
10891 char *reply;
10892 ULONGEST uval;
10893
10894 set_remote_traceframe ();
10895
10896 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
10897 putpkt (rs->buf);
10898 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10899 if (reply && *reply)
10900 {
10901 if (*reply == 'V')
10902 {
10903 unpack_varlen_hex (reply + 1, &uval);
10904 *val = (LONGEST) uval;
10905 return 1;
10906 }
10907 }
10908 return 0;
10909 }
10910
10911 static int
10912 remote_save_trace_data (struct target_ops *self, const char *filename)
10913 {
10914 struct remote_state *rs = get_remote_state ();
10915 char *p, *reply;
10916
10917 p = rs->buf;
10918 strcpy (p, "QTSave:");
10919 p += strlen (p);
10920 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
10921 error (_("Remote file name too long for trace save packet"));
10922 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
10923 *p++ = '\0';
10924 putpkt (rs->buf);
10925 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10926 if (*reply == '\0')
10927 error (_("Target does not support this command."));
10928 if (strcmp (reply, "OK") != 0)
10929 error (_("Bogus reply from target: %s"), reply);
10930 return 0;
10931 }
10932
10933 /* This is basically a memory transfer, but needs to be its own packet
10934 because we don't know how the target actually organizes its trace
10935 memory, plus we want to be able to ask for as much as possible, but
10936 not be unhappy if we don't get as much as we ask for. */
10937
10938 static LONGEST
10939 remote_get_raw_trace_data (struct target_ops *self,
10940 gdb_byte *buf, ULONGEST offset, LONGEST len)
10941 {
10942 struct remote_state *rs = get_remote_state ();
10943 char *reply;
10944 char *p;
10945 int rslt;
10946
10947 p = rs->buf;
10948 strcpy (p, "qTBuffer:");
10949 p += strlen (p);
10950 p += hexnumstr (p, offset);
10951 *p++ = ',';
10952 p += hexnumstr (p, len);
10953 *p++ = '\0';
10954
10955 putpkt (rs->buf);
10956 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10957 if (reply && *reply)
10958 {
10959 /* 'l' by itself means we're at the end of the buffer and
10960 there is nothing more to get. */
10961 if (*reply == 'l')
10962 return 0;
10963
10964 /* Convert the reply into binary. Limit the number of bytes to
10965 convert according to our passed-in buffer size, rather than
10966 what was returned in the packet; if the target is
10967 unexpectedly generous and gives us a bigger reply than we
10968 asked for, we don't want to crash. */
10969 rslt = hex2bin (target_buf, buf, len);
10970 return rslt;
10971 }
10972
10973 /* Something went wrong, flag as an error. */
10974 return -1;
10975 }
10976
10977 static void
10978 remote_set_disconnected_tracing (struct target_ops *self, int val)
10979 {
10980 struct remote_state *rs = get_remote_state ();
10981
10982 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
10983 {
10984 char *reply;
10985
10986 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
10987 putpkt (rs->buf);
10988 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10989 if (*reply == '\0')
10990 error (_("Target does not support this command."));
10991 if (strcmp (reply, "OK") != 0)
10992 error (_("Bogus reply from target: %s"), reply);
10993 }
10994 else if (val)
10995 warning (_("Target does not support disconnected tracing."));
10996 }
10997
10998 static int
10999 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11000 {
11001 struct thread_info *info = find_thread_ptid (ptid);
11002
11003 if (info && info->private)
11004 return info->private->core;
11005 return -1;
11006 }
11007
11008 static void
11009 remote_set_circular_trace_buffer (struct target_ops *self, int val)
11010 {
11011 struct remote_state *rs = get_remote_state ();
11012 char *reply;
11013
11014 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
11015 putpkt (rs->buf);
11016 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11017 if (*reply == '\0')
11018 error (_("Target does not support this command."));
11019 if (strcmp (reply, "OK") != 0)
11020 error (_("Bogus reply from target: %s"), reply);
11021 }
11022
11023 static struct traceframe_info *
11024 remote_traceframe_info (struct target_ops *self)
11025 {
11026 char *text;
11027
11028 text = target_read_stralloc (&current_target,
11029 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11030 if (text != NULL)
11031 {
11032 struct traceframe_info *info;
11033 struct cleanup *back_to = make_cleanup (xfree, text);
11034
11035 info = parse_traceframe_info (text);
11036 do_cleanups (back_to);
11037 return info;
11038 }
11039
11040 return NULL;
11041 }
11042
11043 /* Handle the qTMinFTPILen packet. Returns the minimum length of
11044 instruction on which a fast tracepoint may be placed. Returns -1
11045 if the packet is not supported, and 0 if the minimum instruction
11046 length is unknown. */
11047
11048 static int
11049 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
11050 {
11051 struct remote_state *rs = get_remote_state ();
11052 char *reply;
11053
11054 /* If we're not debugging a process yet, the IPA can't be
11055 loaded. */
11056 if (!target_has_execution)
11057 return 0;
11058
11059 /* Make sure the remote is pointing at the right process. */
11060 set_general_process ();
11061
11062 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
11063 putpkt (rs->buf);
11064 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11065 if (*reply == '\0')
11066 return -1;
11067 else
11068 {
11069 ULONGEST min_insn_len;
11070
11071 unpack_varlen_hex (reply, &min_insn_len);
11072
11073 return (int) min_insn_len;
11074 }
11075 }
11076
11077 static void
11078 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
11079 {
11080 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
11081 {
11082 struct remote_state *rs = get_remote_state ();
11083 char *buf = rs->buf;
11084 char *endbuf = rs->buf + get_remote_packet_size ();
11085 enum packet_result result;
11086
11087 gdb_assert (val >= 0 || val == -1);
11088 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11089 /* Send -1 as literal "-1" to avoid host size dependency. */
11090 if (val < 0)
11091 {
11092 *buf++ = '-';
11093 buf += hexnumstr (buf, (ULONGEST) -val);
11094 }
11095 else
11096 buf += hexnumstr (buf, (ULONGEST) val);
11097
11098 putpkt (rs->buf);
11099 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11100 result = packet_ok (rs->buf,
11101 &remote_protocol_packets[PACKET_QTBuffer_size]);
11102
11103 if (result != PACKET_OK)
11104 warning (_("Bogus reply from target: %s"), rs->buf);
11105 }
11106 }
11107
11108 static int
11109 remote_set_trace_notes (struct target_ops *self,
11110 const char *user, const char *notes,
11111 const char *stop_notes)
11112 {
11113 struct remote_state *rs = get_remote_state ();
11114 char *reply;
11115 char *buf = rs->buf;
11116 char *endbuf = rs->buf + get_remote_packet_size ();
11117 int nbytes;
11118
11119 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11120 if (user)
11121 {
11122 buf += xsnprintf (buf, endbuf - buf, "user:");
11123 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
11124 buf += 2 * nbytes;
11125 *buf++ = ';';
11126 }
11127 if (notes)
11128 {
11129 buf += xsnprintf (buf, endbuf - buf, "notes:");
11130 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
11131 buf += 2 * nbytes;
11132 *buf++ = ';';
11133 }
11134 if (stop_notes)
11135 {
11136 buf += xsnprintf (buf, endbuf - buf, "tstop:");
11137 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
11138 buf += 2 * nbytes;
11139 *buf++ = ';';
11140 }
11141 /* Ensure the buffer is terminated. */
11142 *buf = '\0';
11143
11144 putpkt (rs->buf);
11145 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11146 if (*reply == '\0')
11147 return 0;
11148
11149 if (strcmp (reply, "OK") != 0)
11150 error (_("Bogus reply from target: %s"), reply);
11151
11152 return 1;
11153 }
11154
11155 static int
11156 remote_use_agent (struct target_ops *self, int use)
11157 {
11158 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
11159 {
11160 struct remote_state *rs = get_remote_state ();
11161
11162 /* If the stub supports QAgent. */
11163 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
11164 putpkt (rs->buf);
11165 getpkt (&rs->buf, &rs->buf_size, 0);
11166
11167 if (strcmp (rs->buf, "OK") == 0)
11168 {
11169 use_agent = use;
11170 return 1;
11171 }
11172 }
11173
11174 return 0;
11175 }
11176
11177 static int
11178 remote_can_use_agent (struct target_ops *self)
11179 {
11180 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
11181 }
11182
11183 struct btrace_target_info
11184 {
11185 /* The ptid of the traced thread. */
11186 ptid_t ptid;
11187 };
11188
11189 /* Check whether the target supports branch tracing. */
11190
11191 static int
11192 remote_supports_btrace (struct target_ops *self)
11193 {
11194 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
11195 return 0;
11196 if (packet_support (PACKET_Qbtrace_bts) != PACKET_ENABLE)
11197 return 0;
11198 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
11199 return 0;
11200
11201 return 1;
11202 }
11203
11204 /* Enable branch tracing. */
11205
11206 static struct btrace_target_info *
11207 remote_enable_btrace (struct target_ops *self, ptid_t ptid)
11208 {
11209 struct btrace_target_info *tinfo = NULL;
11210 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11211 struct remote_state *rs = get_remote_state ();
11212 char *buf = rs->buf;
11213 char *endbuf = rs->buf + get_remote_packet_size ();
11214
11215 if (packet_config_support (packet) != PACKET_ENABLE)
11216 error (_("Target does not support branch tracing."));
11217
11218 set_general_thread (ptid);
11219
11220 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11221 putpkt (rs->buf);
11222 getpkt (&rs->buf, &rs->buf_size, 0);
11223
11224 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11225 {
11226 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11227 error (_("Could not enable branch tracing for %s: %s"),
11228 target_pid_to_str (ptid), rs->buf + 2);
11229 else
11230 error (_("Could not enable branch tracing for %s."),
11231 target_pid_to_str (ptid));
11232 }
11233
11234 tinfo = xzalloc (sizeof (*tinfo));
11235 tinfo->ptid = ptid;
11236
11237 return tinfo;
11238 }
11239
11240 /* Disable branch tracing. */
11241
11242 static void
11243 remote_disable_btrace (struct target_ops *self,
11244 struct btrace_target_info *tinfo)
11245 {
11246 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
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 (tinfo->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 disable branch tracing for %s: %s"),
11264 target_pid_to_str (tinfo->ptid), rs->buf + 2);
11265 else
11266 error (_("Could not disable branch tracing for %s."),
11267 target_pid_to_str (tinfo->ptid));
11268 }
11269
11270 xfree (tinfo);
11271 }
11272
11273 /* Teardown branch tracing. */
11274
11275 static void
11276 remote_teardown_btrace (struct target_ops *self,
11277 struct btrace_target_info *tinfo)
11278 {
11279 /* We must not talk to the target during teardown. */
11280 xfree (tinfo);
11281 }
11282
11283 /* Read the branch trace. */
11284
11285 static enum btrace_error
11286 remote_read_btrace (struct target_ops *self,
11287 VEC (btrace_block_s) **btrace,
11288 struct btrace_target_info *tinfo,
11289 enum btrace_read_type type)
11290 {
11291 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11292 struct remote_state *rs = get_remote_state ();
11293 struct cleanup *cleanup;
11294 const char *annex;
11295 char *xml;
11296
11297 if (packet_config_support (packet) != PACKET_ENABLE)
11298 error (_("Target does not support branch tracing."));
11299
11300 #if !defined(HAVE_LIBEXPAT)
11301 error (_("Cannot process branch tracing result. XML parsing not supported."));
11302 #endif
11303
11304 switch (type)
11305 {
11306 case BTRACE_READ_ALL:
11307 annex = "all";
11308 break;
11309 case BTRACE_READ_NEW:
11310 annex = "new";
11311 break;
11312 case BTRACE_READ_DELTA:
11313 annex = "delta";
11314 break;
11315 default:
11316 internal_error (__FILE__, __LINE__,
11317 _("Bad branch tracing read type: %u."),
11318 (unsigned int) type);
11319 }
11320
11321 xml = target_read_stralloc (&current_target,
11322 TARGET_OBJECT_BTRACE, annex);
11323 if (xml == NULL)
11324 return BTRACE_ERR_UNKNOWN;
11325
11326 cleanup = make_cleanup (xfree, xml);
11327 *btrace = parse_xml_btrace (xml);
11328 do_cleanups (cleanup);
11329
11330 return BTRACE_ERR_NONE;
11331 }
11332
11333 static int
11334 remote_augmented_libraries_svr4_read (struct target_ops *self)
11335 {
11336 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
11337 == PACKET_ENABLE);
11338 }
11339
11340 /* Implementation of to_load. */
11341
11342 static void
11343 remote_load (struct target_ops *self, char *name, int from_tty)
11344 {
11345 generic_load (name, from_tty);
11346 }
11347
11348 static void
11349 init_remote_ops (void)
11350 {
11351 remote_ops.to_shortname = "remote";
11352 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
11353 remote_ops.to_doc =
11354 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11355 Specify the serial device it is connected to\n\
11356 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
11357 remote_ops.to_open = remote_open;
11358 remote_ops.to_close = remote_close;
11359 remote_ops.to_detach = remote_detach;
11360 remote_ops.to_disconnect = remote_disconnect;
11361 remote_ops.to_resume = remote_resume;
11362 remote_ops.to_wait = remote_wait;
11363 remote_ops.to_fetch_registers = remote_fetch_registers;
11364 remote_ops.to_store_registers = remote_store_registers;
11365 remote_ops.to_prepare_to_store = remote_prepare_to_store;
11366 remote_ops.to_files_info = remote_files_info;
11367 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11368 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
11369 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11370 remote_ops.to_stopped_data_address = remote_stopped_data_address;
11371 remote_ops.to_watchpoint_addr_within_range =
11372 remote_watchpoint_addr_within_range;
11373 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11374 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11375 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
11376 remote_ops.to_region_ok_for_hw_watchpoint
11377 = remote_region_ok_for_hw_watchpoint;
11378 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11379 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
11380 remote_ops.to_kill = remote_kill;
11381 remote_ops.to_load = remote_load;
11382 remote_ops.to_mourn_inferior = remote_mourn;
11383 remote_ops.to_pass_signals = remote_pass_signals;
11384 remote_ops.to_program_signals = remote_program_signals;
11385 remote_ops.to_thread_alive = remote_thread_alive;
11386 remote_ops.to_find_new_threads = remote_threads_info;
11387 remote_ops.to_pid_to_str = remote_pid_to_str;
11388 remote_ops.to_extra_thread_info = remote_threads_extra_info;
11389 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
11390 remote_ops.to_stop = remote_stop;
11391 remote_ops.to_xfer_partial = remote_xfer_partial;
11392 remote_ops.to_rcmd = remote_rcmd;
11393 remote_ops.to_log_command = serial_log_command;
11394 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
11395 remote_ops.to_stratum = process_stratum;
11396 remote_ops.to_has_all_memory = default_child_has_all_memory;
11397 remote_ops.to_has_memory = default_child_has_memory;
11398 remote_ops.to_has_stack = default_child_has_stack;
11399 remote_ops.to_has_registers = default_child_has_registers;
11400 remote_ops.to_has_execution = default_child_has_execution;
11401 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
11402 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
11403 remote_ops.to_magic = OPS_MAGIC;
11404 remote_ops.to_memory_map = remote_memory_map;
11405 remote_ops.to_flash_erase = remote_flash_erase;
11406 remote_ops.to_flash_done = remote_flash_done;
11407 remote_ops.to_read_description = remote_read_description;
11408 remote_ops.to_search_memory = remote_search_memory;
11409 remote_ops.to_can_async_p = remote_can_async_p;
11410 remote_ops.to_is_async_p = remote_is_async_p;
11411 remote_ops.to_async = remote_async;
11412 remote_ops.to_terminal_inferior = remote_terminal_inferior;
11413 remote_ops.to_terminal_ours = remote_terminal_ours;
11414 remote_ops.to_supports_non_stop = remote_supports_non_stop;
11415 remote_ops.to_supports_multi_process = remote_supports_multi_process;
11416 remote_ops.to_supports_disable_randomization
11417 = remote_supports_disable_randomization;
11418 remote_ops.to_fileio_open = remote_hostio_open;
11419 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11420 remote_ops.to_fileio_pread = remote_hostio_pread;
11421 remote_ops.to_fileio_close = remote_hostio_close;
11422 remote_ops.to_fileio_unlink = remote_hostio_unlink;
11423 remote_ops.to_fileio_readlink = remote_hostio_readlink;
11424 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
11425 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
11426 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
11427 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
11428 remote_ops.to_trace_init = remote_trace_init;
11429 remote_ops.to_download_tracepoint = remote_download_tracepoint;
11430 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
11431 remote_ops.to_download_trace_state_variable
11432 = remote_download_trace_state_variable;
11433 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11434 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
11435 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11436 remote_ops.to_trace_start = remote_trace_start;
11437 remote_ops.to_get_trace_status = remote_get_trace_status;
11438 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
11439 remote_ops.to_trace_stop = remote_trace_stop;
11440 remote_ops.to_trace_find = remote_trace_find;
11441 remote_ops.to_get_trace_state_variable_value
11442 = remote_get_trace_state_variable_value;
11443 remote_ops.to_save_trace_data = remote_save_trace_data;
11444 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
11445 remote_ops.to_upload_trace_state_variables
11446 = remote_upload_trace_state_variables;
11447 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
11448 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
11449 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
11450 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
11451 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
11452 remote_ops.to_set_trace_notes = remote_set_trace_notes;
11453 remote_ops.to_core_of_thread = remote_core_of_thread;
11454 remote_ops.to_verify_memory = remote_verify_memory;
11455 remote_ops.to_get_tib_address = remote_get_tib_address;
11456 remote_ops.to_set_permissions = remote_set_permissions;
11457 remote_ops.to_static_tracepoint_marker_at
11458 = remote_static_tracepoint_marker_at;
11459 remote_ops.to_static_tracepoint_markers_by_strid
11460 = remote_static_tracepoint_markers_by_strid;
11461 remote_ops.to_traceframe_info = remote_traceframe_info;
11462 remote_ops.to_use_agent = remote_use_agent;
11463 remote_ops.to_can_use_agent = remote_can_use_agent;
11464 remote_ops.to_supports_btrace = remote_supports_btrace;
11465 remote_ops.to_enable_btrace = remote_enable_btrace;
11466 remote_ops.to_disable_btrace = remote_disable_btrace;
11467 remote_ops.to_teardown_btrace = remote_teardown_btrace;
11468 remote_ops.to_read_btrace = remote_read_btrace;
11469 remote_ops.to_augmented_libraries_svr4_read =
11470 remote_augmented_libraries_svr4_read;
11471 }
11472
11473 /* Set up the extended remote vector by making a copy of the standard
11474 remote vector and adding to it. */
11475
11476 static void
11477 init_extended_remote_ops (void)
11478 {
11479 extended_remote_ops = remote_ops;
11480
11481 extended_remote_ops.to_shortname = "extended-remote";
11482 extended_remote_ops.to_longname =
11483 "Extended remote serial target in gdb-specific protocol";
11484 extended_remote_ops.to_doc =
11485 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11486 Specify the serial device it is connected to (e.g. /dev/ttya).";
11487 extended_remote_ops.to_open = extended_remote_open;
11488 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11489 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
11490 extended_remote_ops.to_detach = extended_remote_detach;
11491 extended_remote_ops.to_attach = extended_remote_attach;
11492 extended_remote_ops.to_kill = extended_remote_kill;
11493 extended_remote_ops.to_supports_disable_randomization
11494 = extended_remote_supports_disable_randomization;
11495 }
11496
11497 static int
11498 remote_can_async_p (struct target_ops *ops)
11499 {
11500 struct remote_state *rs = get_remote_state ();
11501
11502 if (!target_async_permitted)
11503 /* We only enable async when the user specifically asks for it. */
11504 return 0;
11505
11506 /* We're async whenever the serial device is. */
11507 return serial_can_async_p (rs->remote_desc);
11508 }
11509
11510 static int
11511 remote_is_async_p (struct target_ops *ops)
11512 {
11513 struct remote_state *rs = get_remote_state ();
11514
11515 if (!target_async_permitted)
11516 /* We only enable async when the user specifically asks for it. */
11517 return 0;
11518
11519 /* We're async whenever the serial device is. */
11520 return serial_is_async_p (rs->remote_desc);
11521 }
11522
11523 /* Pass the SERIAL event on and up to the client. One day this code
11524 will be able to delay notifying the client of an event until the
11525 point where an entire packet has been received. */
11526
11527 static serial_event_ftype remote_async_serial_handler;
11528
11529 static void
11530 remote_async_serial_handler (struct serial *scb, void *context)
11531 {
11532 struct remote_state *rs = context;
11533
11534 /* Don't propogate error information up to the client. Instead let
11535 the client find out about the error by querying the target. */
11536 rs->async_client_callback (INF_REG_EVENT, rs->async_client_context);
11537 }
11538
11539 static void
11540 remote_async_inferior_event_handler (gdb_client_data data)
11541 {
11542 inferior_event_handler (INF_REG_EVENT, NULL);
11543 }
11544
11545 static void
11546 remote_async (struct target_ops *ops,
11547 void (*callback) (enum inferior_event_type event_type,
11548 void *context),
11549 void *context)
11550 {
11551 struct remote_state *rs = get_remote_state ();
11552
11553 if (callback != NULL)
11554 {
11555 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
11556 rs->async_client_callback = callback;
11557 rs->async_client_context = context;
11558 }
11559 else
11560 serial_async (rs->remote_desc, NULL, NULL);
11561 }
11562
11563 static void
11564 set_remote_cmd (char *args, int from_tty)
11565 {
11566 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
11567 }
11568
11569 static void
11570 show_remote_cmd (char *args, int from_tty)
11571 {
11572 /* We can't just use cmd_show_list here, because we want to skip
11573 the redundant "show remote Z-packet" and the legacy aliases. */
11574 struct cleanup *showlist_chain;
11575 struct cmd_list_element *list = remote_show_cmdlist;
11576 struct ui_out *uiout = current_uiout;
11577
11578 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
11579 for (; list != NULL; list = list->next)
11580 if (strcmp (list->name, "Z-packet") == 0)
11581 continue;
11582 else if (list->type == not_set_cmd)
11583 /* Alias commands are exactly like the original, except they
11584 don't have the normal type. */
11585 continue;
11586 else
11587 {
11588 struct cleanup *option_chain
11589 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
11590
11591 ui_out_field_string (uiout, "name", list->name);
11592 ui_out_text (uiout, ": ");
11593 if (list->type == show_cmd)
11594 do_show_command ((char *) NULL, from_tty, list);
11595 else
11596 cmd_func (list, NULL, from_tty);
11597 /* Close the tuple. */
11598 do_cleanups (option_chain);
11599 }
11600
11601 /* Close the tuple. */
11602 do_cleanups (showlist_chain);
11603 }
11604
11605
11606 /* Function to be called whenever a new objfile (shlib) is detected. */
11607 static void
11608 remote_new_objfile (struct objfile *objfile)
11609 {
11610 struct remote_state *rs = get_remote_state ();
11611
11612 if (rs->remote_desc != 0) /* Have a remote connection. */
11613 remote_check_symbols ();
11614 }
11615
11616 /* Pull all the tracepoints defined on the target and create local
11617 data structures representing them. We don't want to create real
11618 tracepoints yet, we don't want to mess up the user's existing
11619 collection. */
11620
11621 static int
11622 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
11623 {
11624 struct remote_state *rs = get_remote_state ();
11625 char *p;
11626
11627 /* Ask for a first packet of tracepoint definition. */
11628 putpkt ("qTfP");
11629 getpkt (&rs->buf, &rs->buf_size, 0);
11630 p = rs->buf;
11631 while (*p && *p != 'l')
11632 {
11633 parse_tracepoint_definition (p, utpp);
11634 /* Ask for another packet of tracepoint definition. */
11635 putpkt ("qTsP");
11636 getpkt (&rs->buf, &rs->buf_size, 0);
11637 p = rs->buf;
11638 }
11639 return 0;
11640 }
11641
11642 static int
11643 remote_upload_trace_state_variables (struct target_ops *self,
11644 struct uploaded_tsv **utsvp)
11645 {
11646 struct remote_state *rs = get_remote_state ();
11647 char *p;
11648
11649 /* Ask for a first packet of variable definition. */
11650 putpkt ("qTfV");
11651 getpkt (&rs->buf, &rs->buf_size, 0);
11652 p = rs->buf;
11653 while (*p && *p != 'l')
11654 {
11655 parse_tsv_definition (p, utsvp);
11656 /* Ask for another packet of variable definition. */
11657 putpkt ("qTsV");
11658 getpkt (&rs->buf, &rs->buf_size, 0);
11659 p = rs->buf;
11660 }
11661 return 0;
11662 }
11663
11664 /* The "set/show range-stepping" show hook. */
11665
11666 static void
11667 show_range_stepping (struct ui_file *file, int from_tty,
11668 struct cmd_list_element *c,
11669 const char *value)
11670 {
11671 fprintf_filtered (file,
11672 _("Debugger's willingness to use range stepping "
11673 "is %s.\n"), value);
11674 }
11675
11676 /* The "set/show range-stepping" set hook. */
11677
11678 static void
11679 set_range_stepping (char *ignore_args, int from_tty,
11680 struct cmd_list_element *c)
11681 {
11682 struct remote_state *rs = get_remote_state ();
11683
11684 /* Whene enabling, check whether range stepping is actually
11685 supported by the target, and warn if not. */
11686 if (use_range_stepping)
11687 {
11688 if (rs->remote_desc != NULL)
11689 {
11690 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
11691 remote_vcont_probe (rs);
11692
11693 if (packet_support (PACKET_vCont) == PACKET_ENABLE
11694 && rs->supports_vCont.r)
11695 return;
11696 }
11697
11698 warning (_("Range stepping is not supported by the current target"));
11699 }
11700 }
11701
11702 void
11703 _initialize_remote (void)
11704 {
11705 struct remote_state *rs;
11706 struct cmd_list_element *cmd;
11707 const char *cmd_name;
11708
11709 /* architecture specific data */
11710 remote_gdbarch_data_handle =
11711 gdbarch_data_register_post_init (init_remote_state);
11712 remote_g_packet_data_handle =
11713 gdbarch_data_register_pre_init (remote_g_packet_data_init);
11714
11715 /* Initialize the per-target state. At the moment there is only one
11716 of these, not one per target. Only one target is active at a
11717 time. */
11718 remote_state = new_remote_state ();
11719
11720 init_remote_ops ();
11721 add_target (&remote_ops);
11722
11723 init_extended_remote_ops ();
11724 add_target (&extended_remote_ops);
11725
11726 /* Hook into new objfile notification. */
11727 observer_attach_new_objfile (remote_new_objfile);
11728 /* We're no longer interested in notification events of an inferior
11729 when it exits. */
11730 observer_attach_inferior_exit (discard_pending_stop_replies);
11731
11732 /* Set up signal handlers. */
11733 async_sigint_remote_token =
11734 create_async_signal_handler (async_remote_interrupt, NULL);
11735 async_sigint_remote_twice_token =
11736 create_async_signal_handler (async_remote_interrupt_twice, NULL);
11737
11738 #if 0
11739 init_remote_threadtests ();
11740 #endif
11741
11742 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
11743 /* set/show remote ... */
11744
11745 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
11746 Remote protocol specific variables\n\
11747 Configure various remote-protocol specific variables such as\n\
11748 the packets being used"),
11749 &remote_set_cmdlist, "set remote ",
11750 0 /* allow-unknown */, &setlist);
11751 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
11752 Remote protocol specific variables\n\
11753 Configure various remote-protocol specific variables such as\n\
11754 the packets being used"),
11755 &remote_show_cmdlist, "show remote ",
11756 0 /* allow-unknown */, &showlist);
11757
11758 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
11759 Compare section data on target to the exec file.\n\
11760 Argument is a single section name (default: all loaded sections)."),
11761 &cmdlist);
11762
11763 add_cmd ("packet", class_maintenance, packet_command, _("\
11764 Send an arbitrary packet to a remote target.\n\
11765 maintenance packet TEXT\n\
11766 If GDB is talking to an inferior via the GDB serial protocol, then\n\
11767 this command sends the string TEXT to the inferior, and displays the\n\
11768 response packet. GDB supplies the initial `$' character, and the\n\
11769 terminating `#' character and checksum."),
11770 &maintenancelist);
11771
11772 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
11773 Set whether to send break if interrupted."), _("\
11774 Show whether to send break if interrupted."), _("\
11775 If set, a break, instead of a cntrl-c, is sent to the remote target."),
11776 set_remotebreak, show_remotebreak,
11777 &setlist, &showlist);
11778 cmd_name = "remotebreak";
11779 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
11780 deprecate_cmd (cmd, "set remote interrupt-sequence");
11781 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
11782 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
11783 deprecate_cmd (cmd, "show remote interrupt-sequence");
11784
11785 add_setshow_enum_cmd ("interrupt-sequence", class_support,
11786 interrupt_sequence_modes, &interrupt_sequence_mode,
11787 _("\
11788 Set interrupt sequence to remote target."), _("\
11789 Show interrupt sequence to remote target."), _("\
11790 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
11791 NULL, show_interrupt_sequence,
11792 &remote_set_cmdlist,
11793 &remote_show_cmdlist);
11794
11795 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
11796 &interrupt_on_connect, _("\
11797 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11798 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11799 If set, interrupt sequence is sent to remote target."),
11800 NULL, NULL,
11801 &remote_set_cmdlist, &remote_show_cmdlist);
11802
11803 /* Install commands for configuring memory read/write packets. */
11804
11805 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
11806 Set the maximum number of bytes per memory write packet (deprecated)."),
11807 &setlist);
11808 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
11809 Show the maximum number of bytes per memory write packet (deprecated)."),
11810 &showlist);
11811 add_cmd ("memory-write-packet-size", no_class,
11812 set_memory_write_packet_size, _("\
11813 Set the maximum number of bytes per memory-write packet.\n\
11814 Specify the number of bytes in a packet or 0 (zero) for the\n\
11815 default packet size. The actual limit is further reduced\n\
11816 dependent on the target. Specify ``fixed'' to disable the\n\
11817 further restriction and ``limit'' to enable that restriction."),
11818 &remote_set_cmdlist);
11819 add_cmd ("memory-read-packet-size", no_class,
11820 set_memory_read_packet_size, _("\
11821 Set the maximum number of bytes per memory-read packet.\n\
11822 Specify the number of bytes in a packet or 0 (zero) for the\n\
11823 default packet size. The actual limit is further reduced\n\
11824 dependent on the target. Specify ``fixed'' to disable the\n\
11825 further restriction and ``limit'' to enable that restriction."),
11826 &remote_set_cmdlist);
11827 add_cmd ("memory-write-packet-size", no_class,
11828 show_memory_write_packet_size,
11829 _("Show the maximum number of bytes per memory-write packet."),
11830 &remote_show_cmdlist);
11831 add_cmd ("memory-read-packet-size", no_class,
11832 show_memory_read_packet_size,
11833 _("Show the maximum number of bytes per memory-read packet."),
11834 &remote_show_cmdlist);
11835
11836 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
11837 &remote_hw_watchpoint_limit, _("\
11838 Set the maximum number of target hardware watchpoints."), _("\
11839 Show the maximum number of target hardware watchpoints."), _("\
11840 Specify a negative limit for unlimited."),
11841 NULL, NULL, /* FIXME: i18n: The maximum
11842 number of target hardware
11843 watchpoints is %s. */
11844 &remote_set_cmdlist, &remote_show_cmdlist);
11845 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
11846 &remote_hw_watchpoint_length_limit, _("\
11847 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
11848 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
11849 Specify a negative limit for unlimited."),
11850 NULL, NULL, /* FIXME: i18n: The maximum
11851 length (in bytes) of a target
11852 hardware watchpoint is %s. */
11853 &remote_set_cmdlist, &remote_show_cmdlist);
11854 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
11855 &remote_hw_breakpoint_limit, _("\
11856 Set the maximum number of target hardware breakpoints."), _("\
11857 Show the maximum number of target hardware breakpoints."), _("\
11858 Specify a negative limit for unlimited."),
11859 NULL, NULL, /* FIXME: i18n: The maximum
11860 number of target hardware
11861 breakpoints is %s. */
11862 &remote_set_cmdlist, &remote_show_cmdlist);
11863
11864 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
11865 &remote_address_size, _("\
11866 Set the maximum size of the address (in bits) in a memory packet."), _("\
11867 Show the maximum size of the address (in bits) in a memory packet."), NULL,
11868 NULL,
11869 NULL, /* FIXME: i18n: */
11870 &setlist, &showlist);
11871
11872 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
11873 "X", "binary-download", 1);
11874
11875 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
11876 "vCont", "verbose-resume", 0);
11877
11878 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
11879 "QPassSignals", "pass-signals", 0);
11880
11881 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
11882 "QProgramSignals", "program-signals", 0);
11883
11884 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
11885 "qSymbol", "symbol-lookup", 0);
11886
11887 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
11888 "P", "set-register", 1);
11889
11890 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
11891 "p", "fetch-register", 1);
11892
11893 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
11894 "Z0", "software-breakpoint", 0);
11895
11896 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
11897 "Z1", "hardware-breakpoint", 0);
11898
11899 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
11900 "Z2", "write-watchpoint", 0);
11901
11902 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
11903 "Z3", "read-watchpoint", 0);
11904
11905 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
11906 "Z4", "access-watchpoint", 0);
11907
11908 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
11909 "qXfer:auxv:read", "read-aux-vector", 0);
11910
11911 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
11912 "qXfer:features:read", "target-features", 0);
11913
11914 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
11915 "qXfer:libraries:read", "library-info", 0);
11916
11917 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
11918 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
11919
11920 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
11921 "qXfer:memory-map:read", "memory-map", 0);
11922
11923 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
11924 "qXfer:spu:read", "read-spu-object", 0);
11925
11926 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
11927 "qXfer:spu:write", "write-spu-object", 0);
11928
11929 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
11930 "qXfer:osdata:read", "osdata", 0);
11931
11932 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
11933 "qXfer:threads:read", "threads", 0);
11934
11935 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
11936 "qXfer:siginfo:read", "read-siginfo-object", 0);
11937
11938 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
11939 "qXfer:siginfo:write", "write-siginfo-object", 0);
11940
11941 add_packet_config_cmd
11942 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
11943 "qXfer:traceframe-info:read", "traceframe-info", 0);
11944
11945 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
11946 "qXfer:uib:read", "unwind-info-block", 0);
11947
11948 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
11949 "qGetTLSAddr", "get-thread-local-storage-address",
11950 0);
11951
11952 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
11953 "qGetTIBAddr", "get-thread-information-block-address",
11954 0);
11955
11956 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
11957 "bc", "reverse-continue", 0);
11958
11959 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
11960 "bs", "reverse-step", 0);
11961
11962 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
11963 "qSupported", "supported-packets", 0);
11964
11965 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
11966 "qSearch:memory", "search-memory", 0);
11967
11968 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
11969 "qTStatus", "trace-status", 0);
11970
11971 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
11972 "vFile:open", "hostio-open", 0);
11973
11974 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
11975 "vFile:pread", "hostio-pread", 0);
11976
11977 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
11978 "vFile:pwrite", "hostio-pwrite", 0);
11979
11980 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
11981 "vFile:close", "hostio-close", 0);
11982
11983 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
11984 "vFile:unlink", "hostio-unlink", 0);
11985
11986 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
11987 "vFile:readlink", "hostio-readlink", 0);
11988
11989 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
11990 "vAttach", "attach", 0);
11991
11992 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
11993 "vRun", "run", 0);
11994
11995 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
11996 "QStartNoAckMode", "noack", 0);
11997
11998 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
11999 "vKill", "kill", 0);
12000
12001 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12002 "qAttached", "query-attached", 0);
12003
12004 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
12005 "ConditionalTracepoints",
12006 "conditional-tracepoints", 0);
12007
12008 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12009 "ConditionalBreakpoints",
12010 "conditional-breakpoints", 0);
12011
12012 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12013 "BreakpointCommands",
12014 "breakpoint-commands", 0);
12015
12016 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12017 "FastTracepoints", "fast-tracepoints", 0);
12018
12019 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12020 "TracepointSource", "TracepointSource", 0);
12021
12022 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12023 "QAllow", "allow", 0);
12024
12025 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12026 "StaticTracepoints", "static-tracepoints", 0);
12027
12028 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12029 "InstallInTrace", "install-in-trace", 0);
12030
12031 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12032 "qXfer:statictrace:read", "read-sdata-object", 0);
12033
12034 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12035 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12036
12037 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12038 "QDisableRandomization", "disable-randomization", 0);
12039
12040 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12041 "QAgent", "agent", 0);
12042
12043 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12044 "QTBuffer:size", "trace-buffer-size", 0);
12045
12046 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12047 "Qbtrace:off", "disable-btrace", 0);
12048
12049 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12050 "Qbtrace:bts", "enable-btrace", 0);
12051
12052 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12053 "qXfer:btrace", "read-btrace", 0);
12054
12055 /* Keep the old ``set remote Z-packet ...'' working. Each individual
12056 Z sub-packet has its own set and show commands, but users may
12057 have sets to this variable in their .gdbinit files (or in their
12058 documentation). */
12059 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
12060 &remote_Z_packet_detect, _("\
12061 Set use of remote protocol `Z' packets"), _("\
12062 Show use of remote protocol `Z' packets "), _("\
12063 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
12064 packets."),
12065 set_remote_protocol_Z_packet_cmd,
12066 show_remote_protocol_Z_packet_cmd,
12067 /* FIXME: i18n: Use of remote protocol
12068 `Z' packets is %s. */
12069 &remote_set_cmdlist, &remote_show_cmdlist);
12070
12071 add_prefix_cmd ("remote", class_files, remote_command, _("\
12072 Manipulate files on the remote system\n\
12073 Transfer files to and from the remote target system."),
12074 &remote_cmdlist, "remote ",
12075 0 /* allow-unknown */, &cmdlist);
12076
12077 add_cmd ("put", class_files, remote_put_command,
12078 _("Copy a local file to the remote system."),
12079 &remote_cmdlist);
12080
12081 add_cmd ("get", class_files, remote_get_command,
12082 _("Copy a remote file to the local system."),
12083 &remote_cmdlist);
12084
12085 add_cmd ("delete", class_files, remote_delete_command,
12086 _("Delete a remote file."),
12087 &remote_cmdlist);
12088
12089 remote_exec_file = xstrdup ("");
12090 add_setshow_string_noescape_cmd ("exec-file", class_files,
12091 &remote_exec_file, _("\
12092 Set the remote pathname for \"run\""), _("\
12093 Show the remote pathname for \"run\""), NULL, NULL, NULL,
12094 &remote_set_cmdlist, &remote_show_cmdlist);
12095
12096 add_setshow_boolean_cmd ("range-stepping", class_run,
12097 &use_range_stepping, _("\
12098 Enable or disable range stepping."), _("\
12099 Show whether target-assisted range stepping is enabled."), _("\
12100 If on, and the target supports it, when stepping a source line, GDB\n\
12101 tells the target to step the corresponding range of addresses itself instead\n\
12102 of issuing multiple single-steps. This speeds up source level\n\
12103 stepping. If off, GDB always issues single-steps, even if range\n\
12104 stepping is supported by the target. The default is on."),
12105 set_range_stepping,
12106 show_range_stepping,
12107 &setlist,
12108 &showlist);
12109
12110 /* Eventually initialize fileio. See fileio.c */
12111 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
12112
12113 /* Take advantage of the fact that the TID field is not used, to tag
12114 special ptids with it set to != 0. */
12115 magic_null_ptid = ptid_build (42000, -1, 1);
12116 not_sent_ptid = ptid_build (42000, -2, 1);
12117 any_thread_ptid = ptid_build (42000, 0, 1);
12118
12119 target_buf_size = 2048;
12120 target_buf = xmalloc (target_buf_size);
12121 }
12122
This page took 0.342005 seconds and 4 git commands to generate.