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