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