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