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