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