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