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