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