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