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