* gdbarch.sh: Document the return_value method. Explain that
[deliverable/binutils-gdb.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
4 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
5 Free Software Foundation, Inc.
6
7 This file is part of GDB.
8
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21
22 /* See the GDB User Guide for details of the GDB remote protocol. */
23
24 #include "defs.h"
25 #include "gdb_string.h"
26 #include <ctype.h>
27 #include <fcntl.h>
28 #include "inferior.h"
29 #include "bfd.h"
30 #include "symfile.h"
31 #include "exceptions.h"
32 #include "target.h"
33 /*#include "terminal.h" */
34 #include "gdbcmd.h"
35 #include "objfiles.h"
36 #include "gdb-stabs.h"
37 #include "gdbthread.h"
38 #include "remote.h"
39 #include "regcache.h"
40 #include "value.h"
41 #include "gdb_assert.h"
42 #include "observer.h"
43 #include "solib.h"
44 #include "cli/cli-decode.h"
45 #include "cli/cli-setshow.h"
46 #include "target-descriptions.h"
47
48 #include <ctype.h>
49 #include <sys/time.h>
50
51 #include "event-loop.h"
52 #include "event-top.h"
53 #include "inf-loop.h"
54
55 #include <signal.h>
56 #include "serial.h"
57
58 #include "gdbcore.h" /* for exec_bfd */
59
60 #include "remote-fileio.h"
61 #include "gdb/fileio.h"
62
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 int remote_async_mask_value = 1;
485
486 static struct target_ops extended_async_remote_ops;
487
488 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
489 ``forever'' still use the normal timeout mechanism. This is
490 currently used by the ASYNC code to guarentee that target reads
491 during the initial connect always time-out. Once getpkt has been
492 modified to return a timeout indication and, in turn
493 remote_wait()/wait_for_inferior() have gained a timeout parameter
494 this can go away. */
495 static int wait_forever_enabled_p = 1;
496
497
498 /* This variable chooses whether to send a ^C or a break when the user
499 requests program interruption. Although ^C is usually what remote
500 systems expect, and that is the default here, sometimes a break is
501 preferable instead. */
502
503 static int remote_break;
504
505 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
506 remote_open knows that we don't have a file open when the program
507 starts. */
508 static struct serial *remote_desc = NULL;
509
510 /* This variable sets the number of bits in an address that are to be
511 sent in a memory ("M" or "m") packet. Normally, after stripping
512 leading zeros, the entire address would be sent. This variable
513 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
514 initial implementation of remote.c restricted the address sent in
515 memory packets to ``host::sizeof long'' bytes - (typically 32
516 bits). Consequently, for 64 bit targets, the upper 32 bits of an
517 address was never sent. Since fixing this bug may cause a break in
518 some remote targets this variable is principly provided to
519 facilitate backward compatibility. */
520
521 static int remote_address_size;
522
523 /* Tempoary to track who currently owns the terminal. See
524 target_async_terminal_* for more details. */
525
526 static int remote_async_terminal_ours_p;
527
528 /* The executable file to use for "run" on the remote side. */
529
530 static char *remote_exec_file = "";
531
532 \f
533 /* User configurable variables for the number of characters in a
534 memory read/write packet. MIN (rsa->remote_packet_size,
535 rsa->sizeof_g_packet) is the default. Some targets need smaller
536 values (fifo overruns, et.al.) and some users need larger values
537 (speed up transfers). The variables ``preferred_*'' (the user
538 request), ``current_*'' (what was actually set) and ``forced_*''
539 (Positive - a soft limit, negative - a hard limit). */
540
541 struct memory_packet_config
542 {
543 char *name;
544 long size;
545 int fixed_p;
546 };
547
548 /* Compute the current size of a read/write packet. Since this makes
549 use of ``actual_register_packet_size'' the computation is dynamic. */
550
551 static long
552 get_memory_packet_size (struct memory_packet_config *config)
553 {
554 struct remote_state *rs = get_remote_state ();
555 struct remote_arch_state *rsa = get_remote_arch_state ();
556
557 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
558 law?) that some hosts don't cope very well with large alloca()
559 calls. Eventually the alloca() code will be replaced by calls to
560 xmalloc() and make_cleanups() allowing this restriction to either
561 be lifted or removed. */
562 #ifndef MAX_REMOTE_PACKET_SIZE
563 #define MAX_REMOTE_PACKET_SIZE 16384
564 #endif
565 /* NOTE: 20 ensures we can write at least one byte. */
566 #ifndef MIN_REMOTE_PACKET_SIZE
567 #define MIN_REMOTE_PACKET_SIZE 20
568 #endif
569 long what_they_get;
570 if (config->fixed_p)
571 {
572 if (config->size <= 0)
573 what_they_get = MAX_REMOTE_PACKET_SIZE;
574 else
575 what_they_get = config->size;
576 }
577 else
578 {
579 what_they_get = get_remote_packet_size ();
580 /* Limit the packet to the size specified by the user. */
581 if (config->size > 0
582 && what_they_get > config->size)
583 what_they_get = config->size;
584
585 /* Limit it to the size of the targets ``g'' response unless we have
586 permission from the stub to use a larger packet size. */
587 if (rs->explicit_packet_size == 0
588 && rsa->actual_register_packet_size > 0
589 && what_they_get > rsa->actual_register_packet_size)
590 what_they_get = rsa->actual_register_packet_size;
591 }
592 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
593 what_they_get = MAX_REMOTE_PACKET_SIZE;
594 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
595 what_they_get = MIN_REMOTE_PACKET_SIZE;
596
597 /* Make sure there is room in the global buffer for this packet
598 (including its trailing NUL byte). */
599 if (rs->buf_size < what_they_get + 1)
600 {
601 rs->buf_size = 2 * what_they_get;
602 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
603 }
604
605 return what_they_get;
606 }
607
608 /* Update the size of a read/write packet. If they user wants
609 something really big then do a sanity check. */
610
611 static void
612 set_memory_packet_size (char *args, struct memory_packet_config *config)
613 {
614 int fixed_p = config->fixed_p;
615 long size = config->size;
616 if (args == NULL)
617 error (_("Argument required (integer, `fixed' or `limited')."));
618 else if (strcmp (args, "hard") == 0
619 || strcmp (args, "fixed") == 0)
620 fixed_p = 1;
621 else if (strcmp (args, "soft") == 0
622 || strcmp (args, "limit") == 0)
623 fixed_p = 0;
624 else
625 {
626 char *end;
627 size = strtoul (args, &end, 0);
628 if (args == end)
629 error (_("Invalid %s (bad syntax)."), config->name);
630 #if 0
631 /* Instead of explicitly capping the size of a packet to
632 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
633 instead allowed to set the size to something arbitrarily
634 large. */
635 if (size > MAX_REMOTE_PACKET_SIZE)
636 error (_("Invalid %s (too large)."), config->name);
637 #endif
638 }
639 /* Extra checks? */
640 if (fixed_p && !config->fixed_p)
641 {
642 if (! query (_("The target may not be able to correctly handle a %s\n"
643 "of %ld bytes. Change the packet size? "),
644 config->name, size))
645 error (_("Packet size not changed."));
646 }
647 /* Update the config. */
648 config->fixed_p = fixed_p;
649 config->size = size;
650 }
651
652 static void
653 show_memory_packet_size (struct memory_packet_config *config)
654 {
655 printf_filtered (_("The %s is %ld. "), config->name, config->size);
656 if (config->fixed_p)
657 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
658 get_memory_packet_size (config));
659 else
660 printf_filtered (_("Packets are limited to %ld bytes.\n"),
661 get_memory_packet_size (config));
662 }
663
664 static struct memory_packet_config memory_write_packet_config =
665 {
666 "memory-write-packet-size",
667 };
668
669 static void
670 set_memory_write_packet_size (char *args, int from_tty)
671 {
672 set_memory_packet_size (args, &memory_write_packet_config);
673 }
674
675 static void
676 show_memory_write_packet_size (char *args, int from_tty)
677 {
678 show_memory_packet_size (&memory_write_packet_config);
679 }
680
681 static long
682 get_memory_write_packet_size (void)
683 {
684 return get_memory_packet_size (&memory_write_packet_config);
685 }
686
687 static struct memory_packet_config memory_read_packet_config =
688 {
689 "memory-read-packet-size",
690 };
691
692 static void
693 set_memory_read_packet_size (char *args, int from_tty)
694 {
695 set_memory_packet_size (args, &memory_read_packet_config);
696 }
697
698 static void
699 show_memory_read_packet_size (char *args, int from_tty)
700 {
701 show_memory_packet_size (&memory_read_packet_config);
702 }
703
704 static long
705 get_memory_read_packet_size (void)
706 {
707 long size = get_memory_packet_size (&memory_read_packet_config);
708 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
709 extra buffer size argument before the memory read size can be
710 increased beyond this. */
711 if (size > get_remote_packet_size ())
712 size = get_remote_packet_size ();
713 return size;
714 }
715
716 \f
717 /* Generic configuration support for packets the stub optionally
718 supports. Allows the user to specify the use of the packet as well
719 as allowing GDB to auto-detect support in the remote stub. */
720
721 enum packet_support
722 {
723 PACKET_SUPPORT_UNKNOWN = 0,
724 PACKET_ENABLE,
725 PACKET_DISABLE
726 };
727
728 struct packet_config
729 {
730 const char *name;
731 const char *title;
732 enum auto_boolean detect;
733 enum packet_support support;
734 };
735
736 /* Analyze a packet's return value and update the packet config
737 accordingly. */
738
739 enum packet_result
740 {
741 PACKET_ERROR,
742 PACKET_OK,
743 PACKET_UNKNOWN
744 };
745
746 static void
747 update_packet_config (struct packet_config *config)
748 {
749 switch (config->detect)
750 {
751 case AUTO_BOOLEAN_TRUE:
752 config->support = PACKET_ENABLE;
753 break;
754 case AUTO_BOOLEAN_FALSE:
755 config->support = PACKET_DISABLE;
756 break;
757 case AUTO_BOOLEAN_AUTO:
758 config->support = PACKET_SUPPORT_UNKNOWN;
759 break;
760 }
761 }
762
763 static void
764 show_packet_config_cmd (struct packet_config *config)
765 {
766 char *support = "internal-error";
767 switch (config->support)
768 {
769 case PACKET_ENABLE:
770 support = "enabled";
771 break;
772 case PACKET_DISABLE:
773 support = "disabled";
774 break;
775 case PACKET_SUPPORT_UNKNOWN:
776 support = "unknown";
777 break;
778 }
779 switch (config->detect)
780 {
781 case AUTO_BOOLEAN_AUTO:
782 printf_filtered (_("Support for the `%s' packet is auto-detected, currently %s.\n"),
783 config->name, support);
784 break;
785 case AUTO_BOOLEAN_TRUE:
786 case AUTO_BOOLEAN_FALSE:
787 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
788 config->name, support);
789 break;
790 }
791 }
792
793 static void
794 add_packet_config_cmd (struct packet_config *config, const char *name,
795 const char *title, int legacy)
796 {
797 char *set_doc;
798 char *show_doc;
799 char *cmd_name;
800
801 config->name = name;
802 config->title = title;
803 config->detect = AUTO_BOOLEAN_AUTO;
804 config->support = PACKET_SUPPORT_UNKNOWN;
805 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
806 name, title);
807 show_doc = xstrprintf ("Show current use of remote protocol `%s' (%s) packet",
808 name, title);
809 /* set/show TITLE-packet {auto,on,off} */
810 cmd_name = xstrprintf ("%s-packet", title);
811 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
812 &config->detect, set_doc, show_doc, NULL, /* help_doc */
813 set_remote_protocol_packet_cmd,
814 show_remote_protocol_packet_cmd,
815 &remote_set_cmdlist, &remote_show_cmdlist);
816 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
817 if (legacy)
818 {
819 char *legacy_name;
820 legacy_name = xstrprintf ("%s-packet", name);
821 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
822 &remote_set_cmdlist);
823 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
824 &remote_show_cmdlist);
825 }
826 }
827
828 static enum packet_result
829 packet_check_result (const char *buf)
830 {
831 if (buf[0] != '\0')
832 {
833 /* The stub recognized the packet request. Check that the
834 operation succeeded. */
835 if (buf[0] == 'E'
836 && isxdigit (buf[1]) && isxdigit (buf[2])
837 && buf[3] == '\0')
838 /* "Enn" - definitly an error. */
839 return PACKET_ERROR;
840
841 /* Always treat "E." as an error. This will be used for
842 more verbose error messages, such as E.memtypes. */
843 if (buf[0] == 'E' && buf[1] == '.')
844 return PACKET_ERROR;
845
846 /* The packet may or may not be OK. Just assume it is. */
847 return PACKET_OK;
848 }
849 else
850 /* The stub does not support the packet. */
851 return PACKET_UNKNOWN;
852 }
853
854 static enum packet_result
855 packet_ok (const char *buf, struct packet_config *config)
856 {
857 enum packet_result result;
858
859 result = packet_check_result (buf);
860 switch (result)
861 {
862 case PACKET_OK:
863 case PACKET_ERROR:
864 /* The stub recognized the packet request. */
865 switch (config->support)
866 {
867 case PACKET_SUPPORT_UNKNOWN:
868 if (remote_debug)
869 fprintf_unfiltered (gdb_stdlog,
870 "Packet %s (%s) is supported\n",
871 config->name, config->title);
872 config->support = PACKET_ENABLE;
873 break;
874 case PACKET_DISABLE:
875 internal_error (__FILE__, __LINE__,
876 _("packet_ok: attempt to use a disabled packet"));
877 break;
878 case PACKET_ENABLE:
879 break;
880 }
881 break;
882 case PACKET_UNKNOWN:
883 /* The stub does not support the packet. */
884 switch (config->support)
885 {
886 case PACKET_ENABLE:
887 if (config->detect == AUTO_BOOLEAN_AUTO)
888 /* If the stub previously indicated that the packet was
889 supported then there is a protocol error.. */
890 error (_("Protocol error: %s (%s) conflicting enabled responses."),
891 config->name, config->title);
892 else
893 /* The user set it wrong. */
894 error (_("Enabled packet %s (%s) not recognized by stub"),
895 config->name, config->title);
896 break;
897 case PACKET_SUPPORT_UNKNOWN:
898 if (remote_debug)
899 fprintf_unfiltered (gdb_stdlog,
900 "Packet %s (%s) is NOT supported\n",
901 config->name, config->title);
902 config->support = PACKET_DISABLE;
903 break;
904 case PACKET_DISABLE:
905 break;
906 }
907 break;
908 }
909
910 return result;
911 }
912
913 enum {
914 PACKET_vCont = 0,
915 PACKET_X,
916 PACKET_qSymbol,
917 PACKET_P,
918 PACKET_p,
919 PACKET_Z0,
920 PACKET_Z1,
921 PACKET_Z2,
922 PACKET_Z3,
923 PACKET_Z4,
924 PACKET_vFile_open,
925 PACKET_vFile_pread,
926 PACKET_vFile_pwrite,
927 PACKET_vFile_close,
928 PACKET_vFile_unlink,
929 PACKET_qXfer_auxv,
930 PACKET_qXfer_features,
931 PACKET_qXfer_libraries,
932 PACKET_qXfer_memory_map,
933 PACKET_qXfer_spu_read,
934 PACKET_qXfer_spu_write,
935 PACKET_qGetTLSAddr,
936 PACKET_qSupported,
937 PACKET_QPassSignals,
938 PACKET_vAttach,
939 PACKET_vRun,
940 PACKET_MAX
941 };
942
943 static struct packet_config remote_protocol_packets[PACKET_MAX];
944
945 static void
946 set_remote_protocol_packet_cmd (char *args, int from_tty,
947 struct cmd_list_element *c)
948 {
949 struct packet_config *packet;
950
951 for (packet = remote_protocol_packets;
952 packet < &remote_protocol_packets[PACKET_MAX];
953 packet++)
954 {
955 if (&packet->detect == c->var)
956 {
957 update_packet_config (packet);
958 return;
959 }
960 }
961 internal_error (__FILE__, __LINE__, "Could not find config for %s",
962 c->name);
963 }
964
965 static void
966 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
967 struct cmd_list_element *c,
968 const char *value)
969 {
970 struct packet_config *packet;
971
972 for (packet = remote_protocol_packets;
973 packet < &remote_protocol_packets[PACKET_MAX];
974 packet++)
975 {
976 if (&packet->detect == c->var)
977 {
978 show_packet_config_cmd (packet);
979 return;
980 }
981 }
982 internal_error (__FILE__, __LINE__, "Could not find config for %s",
983 c->name);
984 }
985
986 /* Should we try one of the 'Z' requests? */
987
988 enum Z_packet_type
989 {
990 Z_PACKET_SOFTWARE_BP,
991 Z_PACKET_HARDWARE_BP,
992 Z_PACKET_WRITE_WP,
993 Z_PACKET_READ_WP,
994 Z_PACKET_ACCESS_WP,
995 NR_Z_PACKET_TYPES
996 };
997
998 /* For compatibility with older distributions. Provide a ``set remote
999 Z-packet ...'' command that updates all the Z packet types. */
1000
1001 static enum auto_boolean remote_Z_packet_detect;
1002
1003 static void
1004 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1005 struct cmd_list_element *c)
1006 {
1007 int i;
1008 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1009 {
1010 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1011 update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
1012 }
1013 }
1014
1015 static void
1016 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1017 struct cmd_list_element *c,
1018 const char *value)
1019 {
1020 int i;
1021 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1022 {
1023 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1024 }
1025 }
1026
1027 /* Should we try the 'ThreadInfo' query packet?
1028
1029 This variable (NOT available to the user: auto-detect only!)
1030 determines whether GDB will use the new, simpler "ThreadInfo"
1031 query or the older, more complex syntax for thread queries.
1032 This is an auto-detect variable (set to true at each connect,
1033 and set to false when the target fails to recognize it). */
1034
1035 static int use_threadinfo_query;
1036 static int use_threadextra_query;
1037
1038 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1039 static struct async_signal_handler *sigint_remote_twice_token;
1040 static struct async_signal_handler *sigint_remote_token;
1041
1042 \f
1043
1044
1045 /* These are the threads which we last sent to the remote system.
1046 -1 for all or -2 for not sent yet. */
1047 static int general_thread;
1048 static int continue_thread;
1049
1050 /* Call this function as a result of
1051 1) A halt indication (T packet) containing a thread id
1052 2) A direct query of currthread
1053 3) Successful execution of set thread
1054 */
1055
1056 static void
1057 record_currthread (int currthread)
1058 {
1059 general_thread = currthread;
1060
1061 /* If this is a new thread, add it to GDB's thread list.
1062 If we leave it up to WFI to do this, bad things will happen. */
1063 if (!in_thread_list (pid_to_ptid (currthread)))
1064 add_thread (pid_to_ptid (currthread));
1065 }
1066
1067 static char *last_pass_packet;
1068
1069 /* If 'QPassSignals' is supported, tell the remote stub what signals
1070 it can simply pass through to the inferior without reporting. */
1071
1072 static void
1073 remote_pass_signals (void)
1074 {
1075 if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1076 {
1077 char *pass_packet, *p;
1078 int numsigs = (int) TARGET_SIGNAL_LAST;
1079 int count = 0, i;
1080
1081 gdb_assert (numsigs < 256);
1082 for (i = 0; i < numsigs; i++)
1083 {
1084 if (signal_stop_state (i) == 0
1085 && signal_print_state (i) == 0
1086 && signal_pass_state (i) == 1)
1087 count++;
1088 }
1089 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1090 strcpy (pass_packet, "QPassSignals:");
1091 p = pass_packet + strlen (pass_packet);
1092 for (i = 0; i < numsigs; i++)
1093 {
1094 if (signal_stop_state (i) == 0
1095 && signal_print_state (i) == 0
1096 && signal_pass_state (i) == 1)
1097 {
1098 if (i >= 16)
1099 *p++ = tohex (i >> 4);
1100 *p++ = tohex (i & 15);
1101 if (count)
1102 *p++ = ';';
1103 else
1104 break;
1105 count--;
1106 }
1107 }
1108 *p = 0;
1109 if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
1110 {
1111 struct remote_state *rs = get_remote_state ();
1112 char *buf = rs->buf;
1113
1114 putpkt (pass_packet);
1115 getpkt (&rs->buf, &rs->buf_size, 0);
1116 packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1117 if (last_pass_packet)
1118 xfree (last_pass_packet);
1119 last_pass_packet = pass_packet;
1120 }
1121 else
1122 xfree (pass_packet);
1123 }
1124 }
1125
1126 #define MAGIC_NULL_PID 42000
1127
1128 static void
1129 set_thread (int th, int gen)
1130 {
1131 struct remote_state *rs = get_remote_state ();
1132 char *buf = rs->buf;
1133 int state = gen ? general_thread : continue_thread;
1134
1135 if (state == th)
1136 return;
1137
1138 buf[0] = 'H';
1139 buf[1] = gen ? 'g' : 'c';
1140 if (th == MAGIC_NULL_PID)
1141 {
1142 buf[2] = '0';
1143 buf[3] = '\0';
1144 }
1145 else if (th < 0)
1146 xsnprintf (&buf[2], get_remote_packet_size () - 2, "-%x", -th);
1147 else
1148 xsnprintf (&buf[2], get_remote_packet_size () - 2, "%x", th);
1149 putpkt (buf);
1150 getpkt (&rs->buf, &rs->buf_size, 0);
1151 if (gen)
1152 general_thread = th;
1153 else
1154 continue_thread = th;
1155 }
1156 \f
1157 /* Return nonzero if the thread TH is still alive on the remote system. */
1158
1159 static int
1160 remote_thread_alive (ptid_t ptid)
1161 {
1162 struct remote_state *rs = get_remote_state ();
1163 int tid = PIDGET (ptid);
1164
1165 if (tid < 0)
1166 xsnprintf (rs->buf, get_remote_packet_size (), "T-%08x", -tid);
1167 else
1168 xsnprintf (rs->buf, get_remote_packet_size (), "T%08x", tid);
1169 putpkt (rs->buf);
1170 getpkt (&rs->buf, &rs->buf_size, 0);
1171 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1172 }
1173
1174 /* About these extended threadlist and threadinfo packets. They are
1175 variable length packets but, the fields within them are often fixed
1176 length. They are redundent enough to send over UDP as is the
1177 remote protocol in general. There is a matching unit test module
1178 in libstub. */
1179
1180 #define OPAQUETHREADBYTES 8
1181
1182 /* a 64 bit opaque identifier */
1183 typedef unsigned char threadref[OPAQUETHREADBYTES];
1184
1185 /* WARNING: This threadref data structure comes from the remote O.S.,
1186 libstub protocol encoding, and remote.c. it is not particularly
1187 changable. */
1188
1189 /* Right now, the internal structure is int. We want it to be bigger.
1190 Plan to fix this.
1191 */
1192
1193 typedef int gdb_threadref; /* Internal GDB thread reference. */
1194
1195 /* gdb_ext_thread_info is an internal GDB data structure which is
1196 equivalent to the reply of the remote threadinfo packet. */
1197
1198 struct gdb_ext_thread_info
1199 {
1200 threadref threadid; /* External form of thread reference. */
1201 int active; /* Has state interesting to GDB?
1202 regs, stack. */
1203 char display[256]; /* Brief state display, name,
1204 blocked/suspended. */
1205 char shortname[32]; /* To be used to name threads. */
1206 char more_display[256]; /* Long info, statistics, queue depth,
1207 whatever. */
1208 };
1209
1210 /* The volume of remote transfers can be limited by submitting
1211 a mask containing bits specifying the desired information.
1212 Use a union of these values as the 'selection' parameter to
1213 get_thread_info. FIXME: Make these TAG names more thread specific.
1214 */
1215
1216 #define TAG_THREADID 1
1217 #define TAG_EXISTS 2
1218 #define TAG_DISPLAY 4
1219 #define TAG_THREADNAME 8
1220 #define TAG_MOREDISPLAY 16
1221
1222 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1223
1224 char *unpack_varlen_hex (char *buff, ULONGEST *result);
1225
1226 static char *unpack_nibble (char *buf, int *val);
1227
1228 static char *pack_nibble (char *buf, int nibble);
1229
1230 static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
1231
1232 static char *unpack_byte (char *buf, int *value);
1233
1234 static char *pack_int (char *buf, int value);
1235
1236 static char *unpack_int (char *buf, int *value);
1237
1238 static char *unpack_string (char *src, char *dest, int length);
1239
1240 static char *pack_threadid (char *pkt, threadref *id);
1241
1242 static char *unpack_threadid (char *inbuf, threadref *id);
1243
1244 void int_to_threadref (threadref *id, int value);
1245
1246 static int threadref_to_int (threadref *ref);
1247
1248 static void copy_threadref (threadref *dest, threadref *src);
1249
1250 static int threadmatch (threadref *dest, threadref *src);
1251
1252 static char *pack_threadinfo_request (char *pkt, int mode,
1253 threadref *id);
1254
1255 static int remote_unpack_thread_info_response (char *pkt,
1256 threadref *expectedref,
1257 struct gdb_ext_thread_info
1258 *info);
1259
1260
1261 static int remote_get_threadinfo (threadref *threadid,
1262 int fieldset, /*TAG mask */
1263 struct gdb_ext_thread_info *info);
1264
1265 static char *pack_threadlist_request (char *pkt, int startflag,
1266 int threadcount,
1267 threadref *nextthread);
1268
1269 static int parse_threadlist_response (char *pkt,
1270 int result_limit,
1271 threadref *original_echo,
1272 threadref *resultlist,
1273 int *doneflag);
1274
1275 static int remote_get_threadlist (int startflag,
1276 threadref *nextthread,
1277 int result_limit,
1278 int *done,
1279 int *result_count,
1280 threadref *threadlist);
1281
1282 typedef int (*rmt_thread_action) (threadref *ref, void *context);
1283
1284 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1285 void *context, int looplimit);
1286
1287 static int remote_newthread_step (threadref *ref, void *context);
1288
1289 /* Encode 64 bits in 16 chars of hex. */
1290
1291 static const char hexchars[] = "0123456789abcdef";
1292
1293 static int
1294 ishex (int ch, int *val)
1295 {
1296 if ((ch >= 'a') && (ch <= 'f'))
1297 {
1298 *val = ch - 'a' + 10;
1299 return 1;
1300 }
1301 if ((ch >= 'A') && (ch <= 'F'))
1302 {
1303 *val = ch - 'A' + 10;
1304 return 1;
1305 }
1306 if ((ch >= '0') && (ch <= '9'))
1307 {
1308 *val = ch - '0';
1309 return 1;
1310 }
1311 return 0;
1312 }
1313
1314 static int
1315 stubhex (int ch)
1316 {
1317 if (ch >= 'a' && ch <= 'f')
1318 return ch - 'a' + 10;
1319 if (ch >= '0' && ch <= '9')
1320 return ch - '0';
1321 if (ch >= 'A' && ch <= 'F')
1322 return ch - 'A' + 10;
1323 return -1;
1324 }
1325
1326 static int
1327 stub_unpack_int (char *buff, int fieldlength)
1328 {
1329 int nibble;
1330 int retval = 0;
1331
1332 while (fieldlength)
1333 {
1334 nibble = stubhex (*buff++);
1335 retval |= nibble;
1336 fieldlength--;
1337 if (fieldlength)
1338 retval = retval << 4;
1339 }
1340 return retval;
1341 }
1342
1343 char *
1344 unpack_varlen_hex (char *buff, /* packet to parse */
1345 ULONGEST *result)
1346 {
1347 int nibble;
1348 ULONGEST retval = 0;
1349
1350 while (ishex (*buff, &nibble))
1351 {
1352 buff++;
1353 retval = retval << 4;
1354 retval |= nibble & 0x0f;
1355 }
1356 *result = retval;
1357 return buff;
1358 }
1359
1360 static char *
1361 unpack_nibble (char *buf, int *val)
1362 {
1363 *val = fromhex (*buf++);
1364 return buf;
1365 }
1366
1367 static char *
1368 pack_nibble (char *buf, int nibble)
1369 {
1370 *buf++ = hexchars[(nibble & 0x0f)];
1371 return buf;
1372 }
1373
1374 static char *
1375 pack_hex_byte (char *pkt, int byte)
1376 {
1377 *pkt++ = hexchars[(byte >> 4) & 0xf];
1378 *pkt++ = hexchars[(byte & 0xf)];
1379 return pkt;
1380 }
1381
1382 static char *
1383 unpack_byte (char *buf, int *value)
1384 {
1385 *value = stub_unpack_int (buf, 2);
1386 return buf + 2;
1387 }
1388
1389 static char *
1390 pack_int (char *buf, int value)
1391 {
1392 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
1393 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
1394 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
1395 buf = pack_hex_byte (buf, (value & 0xff));
1396 return buf;
1397 }
1398
1399 static char *
1400 unpack_int (char *buf, int *value)
1401 {
1402 *value = stub_unpack_int (buf, 8);
1403 return buf + 8;
1404 }
1405
1406 #if 0 /* Currently unused, uncomment when needed. */
1407 static char *pack_string (char *pkt, char *string);
1408
1409 static char *
1410 pack_string (char *pkt, char *string)
1411 {
1412 char ch;
1413 int len;
1414
1415 len = strlen (string);
1416 if (len > 200)
1417 len = 200; /* Bigger than most GDB packets, junk??? */
1418 pkt = pack_hex_byte (pkt, len);
1419 while (len-- > 0)
1420 {
1421 ch = *string++;
1422 if ((ch == '\0') || (ch == '#'))
1423 ch = '*'; /* Protect encapsulation. */
1424 *pkt++ = ch;
1425 }
1426 return pkt;
1427 }
1428 #endif /* 0 (unused) */
1429
1430 static char *
1431 unpack_string (char *src, char *dest, int length)
1432 {
1433 while (length--)
1434 *dest++ = *src++;
1435 *dest = '\0';
1436 return src;
1437 }
1438
1439 static char *
1440 pack_threadid (char *pkt, threadref *id)
1441 {
1442 char *limit;
1443 unsigned char *altid;
1444
1445 altid = (unsigned char *) id;
1446 limit = pkt + BUF_THREAD_ID_SIZE;
1447 while (pkt < limit)
1448 pkt = pack_hex_byte (pkt, *altid++);
1449 return pkt;
1450 }
1451
1452
1453 static char *
1454 unpack_threadid (char *inbuf, threadref *id)
1455 {
1456 char *altref;
1457 char *limit = inbuf + BUF_THREAD_ID_SIZE;
1458 int x, y;
1459
1460 altref = (char *) id;
1461
1462 while (inbuf < limit)
1463 {
1464 x = stubhex (*inbuf++);
1465 y = stubhex (*inbuf++);
1466 *altref++ = (x << 4) | y;
1467 }
1468 return inbuf;
1469 }
1470
1471 /* Externally, threadrefs are 64 bits but internally, they are still
1472 ints. This is due to a mismatch of specifications. We would like
1473 to use 64bit thread references internally. This is an adapter
1474 function. */
1475
1476 void
1477 int_to_threadref (threadref *id, int value)
1478 {
1479 unsigned char *scan;
1480
1481 scan = (unsigned char *) id;
1482 {
1483 int i = 4;
1484 while (i--)
1485 *scan++ = 0;
1486 }
1487 *scan++ = (value >> 24) & 0xff;
1488 *scan++ = (value >> 16) & 0xff;
1489 *scan++ = (value >> 8) & 0xff;
1490 *scan++ = (value & 0xff);
1491 }
1492
1493 static int
1494 threadref_to_int (threadref *ref)
1495 {
1496 int i, value = 0;
1497 unsigned char *scan;
1498
1499 scan = *ref;
1500 scan += 4;
1501 i = 4;
1502 while (i-- > 0)
1503 value = (value << 8) | ((*scan++) & 0xff);
1504 return value;
1505 }
1506
1507 static void
1508 copy_threadref (threadref *dest, threadref *src)
1509 {
1510 int i;
1511 unsigned char *csrc, *cdest;
1512
1513 csrc = (unsigned char *) src;
1514 cdest = (unsigned char *) dest;
1515 i = 8;
1516 while (i--)
1517 *cdest++ = *csrc++;
1518 }
1519
1520 static int
1521 threadmatch (threadref *dest, threadref *src)
1522 {
1523 /* Things are broken right now, so just assume we got a match. */
1524 #if 0
1525 unsigned char *srcp, *destp;
1526 int i, result;
1527 srcp = (char *) src;
1528 destp = (char *) dest;
1529
1530 result = 1;
1531 while (i-- > 0)
1532 result &= (*srcp++ == *destp++) ? 1 : 0;
1533 return result;
1534 #endif
1535 return 1;
1536 }
1537
1538 /*
1539 threadid:1, # always request threadid
1540 context_exists:2,
1541 display:4,
1542 unique_name:8,
1543 more_display:16
1544 */
1545
1546 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
1547
1548 static char *
1549 pack_threadinfo_request (char *pkt, int mode, threadref *id)
1550 {
1551 *pkt++ = 'q'; /* Info Query */
1552 *pkt++ = 'P'; /* process or thread info */
1553 pkt = pack_int (pkt, mode); /* mode */
1554 pkt = pack_threadid (pkt, id); /* threadid */
1555 *pkt = '\0'; /* terminate */
1556 return pkt;
1557 }
1558
1559 /* These values tag the fields in a thread info response packet. */
1560 /* Tagging the fields allows us to request specific fields and to
1561 add more fields as time goes by. */
1562
1563 #define TAG_THREADID 1 /* Echo the thread identifier. */
1564 #define TAG_EXISTS 2 /* Is this process defined enough to
1565 fetch registers and its stack? */
1566 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
1567 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
1568 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
1569 the process. */
1570
1571 static int
1572 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
1573 struct gdb_ext_thread_info *info)
1574 {
1575 struct remote_state *rs = get_remote_state ();
1576 int mask, length;
1577 int tag;
1578 threadref ref;
1579 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
1580 int retval = 1;
1581
1582 /* info->threadid = 0; FIXME: implement zero_threadref. */
1583 info->active = 0;
1584 info->display[0] = '\0';
1585 info->shortname[0] = '\0';
1586 info->more_display[0] = '\0';
1587
1588 /* Assume the characters indicating the packet type have been
1589 stripped. */
1590 pkt = unpack_int (pkt, &mask); /* arg mask */
1591 pkt = unpack_threadid (pkt, &ref);
1592
1593 if (mask == 0)
1594 warning (_("Incomplete response to threadinfo request."));
1595 if (!threadmatch (&ref, expectedref))
1596 { /* This is an answer to a different request. */
1597 warning (_("ERROR RMT Thread info mismatch."));
1598 return 0;
1599 }
1600 copy_threadref (&info->threadid, &ref);
1601
1602 /* Loop on tagged fields , try to bail if somthing goes wrong. */
1603
1604 /* Packets are terminated with nulls. */
1605 while ((pkt < limit) && mask && *pkt)
1606 {
1607 pkt = unpack_int (pkt, &tag); /* tag */
1608 pkt = unpack_byte (pkt, &length); /* length */
1609 if (!(tag & mask)) /* Tags out of synch with mask. */
1610 {
1611 warning (_("ERROR RMT: threadinfo tag mismatch."));
1612 retval = 0;
1613 break;
1614 }
1615 if (tag == TAG_THREADID)
1616 {
1617 if (length != 16)
1618 {
1619 warning (_("ERROR RMT: length of threadid is not 16."));
1620 retval = 0;
1621 break;
1622 }
1623 pkt = unpack_threadid (pkt, &ref);
1624 mask = mask & ~TAG_THREADID;
1625 continue;
1626 }
1627 if (tag == TAG_EXISTS)
1628 {
1629 info->active = stub_unpack_int (pkt, length);
1630 pkt += length;
1631 mask = mask & ~(TAG_EXISTS);
1632 if (length > 8)
1633 {
1634 warning (_("ERROR RMT: 'exists' length too long."));
1635 retval = 0;
1636 break;
1637 }
1638 continue;
1639 }
1640 if (tag == TAG_THREADNAME)
1641 {
1642 pkt = unpack_string (pkt, &info->shortname[0], length);
1643 mask = mask & ~TAG_THREADNAME;
1644 continue;
1645 }
1646 if (tag == TAG_DISPLAY)
1647 {
1648 pkt = unpack_string (pkt, &info->display[0], length);
1649 mask = mask & ~TAG_DISPLAY;
1650 continue;
1651 }
1652 if (tag == TAG_MOREDISPLAY)
1653 {
1654 pkt = unpack_string (pkt, &info->more_display[0], length);
1655 mask = mask & ~TAG_MOREDISPLAY;
1656 continue;
1657 }
1658 warning (_("ERROR RMT: unknown thread info tag."));
1659 break; /* Not a tag we know about. */
1660 }
1661 return retval;
1662 }
1663
1664 static int
1665 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
1666 struct gdb_ext_thread_info *info)
1667 {
1668 struct remote_state *rs = get_remote_state ();
1669 int result;
1670
1671 pack_threadinfo_request (rs->buf, fieldset, threadid);
1672 putpkt (rs->buf);
1673 getpkt (&rs->buf, &rs->buf_size, 0);
1674 result = remote_unpack_thread_info_response (rs->buf + 2,
1675 threadid, info);
1676 return result;
1677 }
1678
1679 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
1680
1681 static char *
1682 pack_threadlist_request (char *pkt, int startflag, int threadcount,
1683 threadref *nextthread)
1684 {
1685 *pkt++ = 'q'; /* info query packet */
1686 *pkt++ = 'L'; /* Process LIST or threadLIST request */
1687 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
1688 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
1689 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
1690 *pkt = '\0';
1691 return pkt;
1692 }
1693
1694 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
1695
1696 static int
1697 parse_threadlist_response (char *pkt, int result_limit,
1698 threadref *original_echo, threadref *resultlist,
1699 int *doneflag)
1700 {
1701 struct remote_state *rs = get_remote_state ();
1702 char *limit;
1703 int count, resultcount, done;
1704
1705 resultcount = 0;
1706 /* Assume the 'q' and 'M chars have been stripped. */
1707 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
1708 /* done parse past here */
1709 pkt = unpack_byte (pkt, &count); /* count field */
1710 pkt = unpack_nibble (pkt, &done);
1711 /* The first threadid is the argument threadid. */
1712 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
1713 while ((count-- > 0) && (pkt < limit))
1714 {
1715 pkt = unpack_threadid (pkt, resultlist++);
1716 if (resultcount++ >= result_limit)
1717 break;
1718 }
1719 if (doneflag)
1720 *doneflag = done;
1721 return resultcount;
1722 }
1723
1724 static int
1725 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
1726 int *done, int *result_count, threadref *threadlist)
1727 {
1728 struct remote_state *rs = get_remote_state ();
1729 static threadref echo_nextthread;
1730 int result = 1;
1731
1732 /* Trancate result limit to be smaller than the packet size. */
1733 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10) >= get_remote_packet_size ())
1734 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
1735
1736 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
1737 putpkt (rs->buf);
1738 getpkt (&rs->buf, &rs->buf_size, 0);
1739
1740 if (*rs->buf == '\0')
1741 *result_count = 0;
1742 else
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 int 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 /* Update the inferior on signals to silently pass, if they've changed. */
3097 remote_pass_signals ();
3098
3099 /* The vCont packet doesn't need to specify threads via Hc. */
3100 if (remote_vcont_resume (ptid, step, siggnal))
3101 return;
3102
3103 /* All other supported resume packets do use Hc, so call set_thread. */
3104 if (pid == -1)
3105 set_thread (0, 0); /* Run any thread. */
3106 else
3107 set_thread (pid, 0); /* Run this thread. */
3108
3109 buf = rs->buf;
3110 if (siggnal != TARGET_SIGNAL_0)
3111 {
3112 buf[0] = step ? 'S' : 'C';
3113 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
3114 buf[2] = tohex (((int) siggnal) & 0xf);
3115 buf[3] = '\0';
3116 }
3117 else
3118 strcpy (buf, step ? "s" : "c");
3119
3120 putpkt (buf);
3121 }
3122
3123 /* Same as remote_resume, but with async support. */
3124 static void
3125 remote_async_resume (ptid_t ptid, int step, enum target_signal siggnal)
3126 {
3127 remote_resume (ptid, step, siggnal);
3128
3129 /* We are about to start executing the inferior, let's register it
3130 with the event loop. NOTE: this is the one place where all the
3131 execution commands end up. We could alternatively do this in each
3132 of the execution commands in infcmd.c. */
3133 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
3134 into infcmd.c in order to allow inferior function calls to work
3135 NOT asynchronously. */
3136 if (target_can_async_p ())
3137 target_async (inferior_event_handler, 0);
3138 /* Tell the world that the target is now executing. */
3139 /* FIXME: cagney/1999-09-23: Is it the targets responsibility to set
3140 this? Instead, should the client of target just assume (for
3141 async targets) that the target is going to start executing? Is
3142 this information already found in the continuation block? */
3143 if (target_is_async_p ())
3144 target_executing = 1;
3145 }
3146 \f
3147
3148 /* Set up the signal handler for SIGINT, while the target is
3149 executing, ovewriting the 'regular' SIGINT signal handler. */
3150 static void
3151 initialize_sigint_signal_handler (void)
3152 {
3153 signal (SIGINT, handle_remote_sigint);
3154 }
3155
3156 /* Signal handler for SIGINT, while the target is executing. */
3157 static void
3158 handle_remote_sigint (int sig)
3159 {
3160 signal (sig, handle_remote_sigint_twice);
3161 mark_async_signal_handler_wrapper (sigint_remote_token);
3162 }
3163
3164 /* Signal handler for SIGINT, installed after SIGINT has already been
3165 sent once. It will take effect the second time that the user sends
3166 a ^C. */
3167 static void
3168 handle_remote_sigint_twice (int sig)
3169 {
3170 signal (sig, handle_remote_sigint);
3171 mark_async_signal_handler_wrapper (sigint_remote_twice_token);
3172 }
3173
3174 /* Perform the real interruption of the target execution, in response
3175 to a ^C. */
3176 static void
3177 async_remote_interrupt (gdb_client_data arg)
3178 {
3179 if (remote_debug)
3180 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
3181
3182 target_stop ();
3183 }
3184
3185 /* Perform interrupt, if the first attempt did not succeed. Just give
3186 up on the target alltogether. */
3187 void
3188 async_remote_interrupt_twice (gdb_client_data arg)
3189 {
3190 if (remote_debug)
3191 fprintf_unfiltered (gdb_stdlog, "remote_interrupt_twice called\n");
3192
3193 interrupt_query ();
3194 }
3195
3196 /* Reinstall the usual SIGINT handlers, after the target has
3197 stopped. */
3198 static void
3199 cleanup_sigint_signal_handler (void *dummy)
3200 {
3201 signal (SIGINT, handle_sigint);
3202 }
3203
3204 /* Send ^C to target to halt it. Target will respond, and send us a
3205 packet. */
3206 static void (*ofunc) (int);
3207
3208 /* The command line interface's stop routine. This function is installed
3209 as a signal handler for SIGINT. The first time a user requests a
3210 stop, we call remote_stop to send a break or ^C. If there is no
3211 response from the target (it didn't stop when the user requested it),
3212 we ask the user if he'd like to detach from the target. */
3213 static void
3214 remote_interrupt (int signo)
3215 {
3216 /* If this doesn't work, try more severe steps. */
3217 signal (signo, remote_interrupt_twice);
3218
3219 gdb_call_async_signal_handler (sigint_remote_token, 1);
3220 }
3221
3222 /* The user typed ^C twice. */
3223
3224 static void
3225 remote_interrupt_twice (int signo)
3226 {
3227 signal (signo, ofunc);
3228 gdb_call_async_signal_handler (sigint_remote_twice_token, 1);
3229 signal (signo, remote_interrupt);
3230 }
3231
3232 /* This is the generic stop called via the target vector. When a target
3233 interrupt is requested, either by the command line or the GUI, we
3234 will eventually end up here. */
3235 static void
3236 remote_stop (void)
3237 {
3238 /* Send a break or a ^C, depending on user preference. */
3239 if (remote_debug)
3240 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
3241
3242 if (remote_break)
3243 serial_send_break (remote_desc);
3244 else
3245 serial_write (remote_desc, "\003", 1);
3246 }
3247
3248 /* Ask the user what to do when an interrupt is received. */
3249
3250 static void
3251 interrupt_query (void)
3252 {
3253 target_terminal_ours ();
3254
3255 if (query ("Interrupted while waiting for the program.\n\
3256 Give up (and stop debugging it)? "))
3257 {
3258 target_mourn_inferior ();
3259 signal (SIGINT, handle_sigint);
3260 deprecated_throw_reason (RETURN_QUIT);
3261 }
3262
3263 target_terminal_inferior ();
3264 }
3265
3266 /* Enable/disable target terminal ownership. Most targets can use
3267 terminal groups to control terminal ownership. Remote targets are
3268 different in that explicit transfer of ownership to/from GDB/target
3269 is required. */
3270
3271 static void
3272 remote_async_terminal_inferior (void)
3273 {
3274 /* FIXME: cagney/1999-09-27: Shouldn't need to test for
3275 sync_execution here. This function should only be called when
3276 GDB is resuming the inferior in the forground. A background
3277 resume (``run&'') should leave GDB in control of the terminal and
3278 consequently should not call this code. */
3279 if (!sync_execution)
3280 return;
3281 /* FIXME: cagney/1999-09-27: Closely related to the above. Make
3282 calls target_terminal_*() idenpotent. The event-loop GDB talking
3283 to an asynchronous target with a synchronous command calls this
3284 function from both event-top.c and infrun.c/infcmd.c. Once GDB
3285 stops trying to transfer the terminal to the target when it
3286 shouldn't this guard can go away. */
3287 if (!remote_async_terminal_ours_p)
3288 return;
3289 delete_file_handler (input_fd);
3290 remote_async_terminal_ours_p = 0;
3291 initialize_sigint_signal_handler ();
3292 /* NOTE: At this point we could also register our selves as the
3293 recipient of all input. Any characters typed could then be
3294 passed on down to the target. */
3295 }
3296
3297 static void
3298 remote_async_terminal_ours (void)
3299 {
3300 /* See FIXME in remote_async_terminal_inferior. */
3301 if (!sync_execution)
3302 return;
3303 /* See FIXME in remote_async_terminal_inferior. */
3304 if (remote_async_terminal_ours_p)
3305 return;
3306 cleanup_sigint_signal_handler (NULL);
3307 add_file_handler (input_fd, stdin_event_handler, 0);
3308 remote_async_terminal_ours_p = 1;
3309 }
3310
3311 /* If nonzero, ignore the next kill. */
3312
3313 int kill_kludge;
3314
3315 void
3316 remote_console_output (char *msg)
3317 {
3318 char *p;
3319
3320 for (p = msg; p[0] && p[1]; p += 2)
3321 {
3322 char tb[2];
3323 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
3324 tb[0] = c;
3325 tb[1] = 0;
3326 fputs_unfiltered (tb, gdb_stdtarg);
3327 }
3328 gdb_flush (gdb_stdtarg);
3329 }
3330
3331 /* Wait until the remote machine stops, then return,
3332 storing status in STATUS just as `wait' would.
3333 Returns "pid", which in the case of a multi-threaded
3334 remote OS, is the thread-id. */
3335
3336 static ptid_t
3337 remote_wait (ptid_t ptid, struct target_waitstatus *status)
3338 {
3339 struct remote_state *rs = get_remote_state ();
3340 struct remote_arch_state *rsa = get_remote_arch_state ();
3341 ULONGEST thread_num = -1;
3342 ULONGEST addr;
3343 int solibs_changed = 0;
3344
3345 status->kind = TARGET_WAITKIND_EXITED;
3346 status->value.integer = 0;
3347
3348 while (1)
3349 {
3350 char *buf, *p;
3351
3352 if (rs->cached_wait_status)
3353 /* Use the cached wait status, but only once. */
3354 rs->cached_wait_status = 0;
3355 else
3356 {
3357 ofunc = signal (SIGINT, remote_interrupt);
3358 /* If the user hit C-c before this packet, or between packets,
3359 pretend that it was hit right here. */
3360 if (quit_flag)
3361 {
3362 quit_flag = 0;
3363 remote_interrupt (SIGINT);
3364 }
3365 getpkt (&rs->buf, &rs->buf_size, 1);
3366 signal (SIGINT, ofunc);
3367 }
3368
3369 buf = rs->buf;
3370
3371 remote_stopped_by_watchpoint_p = 0;
3372
3373 switch (buf[0])
3374 {
3375 case 'E': /* Error of some sort. */
3376 /* We're out of sync with the target now. Did it continue or not?
3377 Not is more likely, so report a stop. */
3378 warning (_("Remote failure reply: %s"), buf);
3379 status->kind = TARGET_WAITKIND_STOPPED;
3380 status->value.sig = TARGET_SIGNAL_0;
3381 goto got_status;
3382 case 'F': /* File-I/O request. */
3383 remote_fileio_request (buf);
3384 continue;
3385 case 'T': /* Status with PC, SP, FP, ... */
3386 {
3387 gdb_byte regs[MAX_REGISTER_SIZE];
3388
3389 /* Expedited reply, containing Signal, {regno, reg} repeat. */
3390 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
3391 ss = signal number
3392 n... = register number
3393 r... = register contents
3394 */
3395 p = &buf[3]; /* after Txx */
3396
3397 while (*p)
3398 {
3399 char *p1;
3400 char *p_temp;
3401 int fieldsize;
3402 LONGEST pnum = 0;
3403
3404 /* If the packet contains a register number save it in
3405 pnum and set p1 to point to the character following
3406 it. Otherwise p1 points to p. */
3407
3408 /* If this packet is an awatch packet, don't parse the
3409 'a' as a register number. */
3410
3411 if (strncmp (p, "awatch", strlen("awatch")) != 0)
3412 {
3413 /* Read the ``P'' register number. */
3414 pnum = strtol (p, &p_temp, 16);
3415 p1 = p_temp;
3416 }
3417 else
3418 p1 = p;
3419
3420 if (p1 == p) /* No register number present here. */
3421 {
3422 p1 = strchr (p, ':');
3423 if (p1 == NULL)
3424 error (_("Malformed packet(a) (missing colon): %s\n\
3425 Packet: '%s'\n"),
3426 p, buf);
3427 if (strncmp (p, "thread", p1 - p) == 0)
3428 {
3429 p_temp = unpack_varlen_hex (++p1, &thread_num);
3430 record_currthread (thread_num);
3431 p = p_temp;
3432 }
3433 else if ((strncmp (p, "watch", p1 - p) == 0)
3434 || (strncmp (p, "rwatch", p1 - p) == 0)
3435 || (strncmp (p, "awatch", p1 - p) == 0))
3436 {
3437 remote_stopped_by_watchpoint_p = 1;
3438 p = unpack_varlen_hex (++p1, &addr);
3439 remote_watch_data_address = (CORE_ADDR)addr;
3440 }
3441 else if (strncmp (p, "library", p1 - p) == 0)
3442 {
3443 p1++;
3444 p_temp = p1;
3445 while (*p_temp && *p_temp != ';')
3446 p_temp++;
3447
3448 solibs_changed = 1;
3449 p = p_temp;
3450 }
3451 else
3452 {
3453 /* Silently skip unknown optional info. */
3454 p_temp = strchr (p1 + 1, ';');
3455 if (p_temp)
3456 p = p_temp;
3457 }
3458 }
3459 else
3460 {
3461 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
3462 p = p1;
3463
3464 if (*p++ != ':')
3465 error (_("Malformed packet(b) (missing colon): %s\n\
3466 Packet: '%s'\n"),
3467 p, buf);
3468
3469 if (reg == NULL)
3470 error (_("Remote sent bad register number %s: %s\n\
3471 Packet: '%s'\n"),
3472 phex_nz (pnum, 0), p, buf);
3473
3474 fieldsize = hex2bin (p, regs,
3475 register_size (current_gdbarch,
3476 reg->regnum));
3477 p += 2 * fieldsize;
3478 if (fieldsize < register_size (current_gdbarch,
3479 reg->regnum))
3480 warning (_("Remote reply is too short: %s"), buf);
3481 regcache_raw_supply (get_current_regcache (),
3482 reg->regnum, regs);
3483 }
3484
3485 if (*p++ != ';')
3486 error (_("Remote register badly formatted: %s\nhere: %s"),
3487 buf, p);
3488 }
3489 }
3490 /* fall through */
3491 case 'S': /* Old style status, just signal only. */
3492 if (solibs_changed)
3493 status->kind = TARGET_WAITKIND_LOADED;
3494 else
3495 {
3496 status->kind = TARGET_WAITKIND_STOPPED;
3497 status->value.sig = (enum target_signal)
3498 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3499 }
3500
3501 if (buf[3] == 'p')
3502 {
3503 thread_num = strtol ((const char *) &buf[4], NULL, 16);
3504 record_currthread (thread_num);
3505 }
3506 goto got_status;
3507 case 'W': /* Target exited. */
3508 {
3509 /* The remote process exited. */
3510 status->kind = TARGET_WAITKIND_EXITED;
3511 status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
3512 goto got_status;
3513 }
3514 case 'X':
3515 status->kind = TARGET_WAITKIND_SIGNALLED;
3516 status->value.sig = (enum target_signal)
3517 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3518 kill_kludge = 1;
3519
3520 goto got_status;
3521 case 'O': /* Console output. */
3522 remote_console_output (buf + 1);
3523 continue;
3524 case '\0':
3525 if (last_sent_signal != TARGET_SIGNAL_0)
3526 {
3527 /* Zero length reply means that we tried 'S' or 'C' and
3528 the remote system doesn't support it. */
3529 target_terminal_ours_for_output ();
3530 printf_filtered
3531 ("Can't send signals to this remote system. %s not sent.\n",
3532 target_signal_to_name (last_sent_signal));
3533 last_sent_signal = TARGET_SIGNAL_0;
3534 target_terminal_inferior ();
3535
3536 strcpy ((char *) buf, last_sent_step ? "s" : "c");
3537 putpkt ((char *) buf);
3538 continue;
3539 }
3540 /* else fallthrough */
3541 default:
3542 warning (_("Invalid remote reply: %s"), buf);
3543 continue;
3544 }
3545 }
3546 got_status:
3547 if (thread_num != -1)
3548 {
3549 return pid_to_ptid (thread_num);
3550 }
3551 return inferior_ptid;
3552 }
3553
3554 /* Async version of remote_wait. */
3555 static ptid_t
3556 remote_async_wait (ptid_t ptid, struct target_waitstatus *status)
3557 {
3558 struct remote_state *rs = get_remote_state ();
3559 struct remote_arch_state *rsa = get_remote_arch_state ();
3560 ULONGEST thread_num = -1;
3561 ULONGEST addr;
3562 int solibs_changed = 0;
3563
3564 status->kind = TARGET_WAITKIND_EXITED;
3565 status->value.integer = 0;
3566
3567 remote_stopped_by_watchpoint_p = 0;
3568
3569 while (1)
3570 {
3571 char *buf, *p;
3572
3573 if (rs->cached_wait_status)
3574 /* Use the cached wait status, but only once. */
3575 rs->cached_wait_status = 0;
3576 else
3577 {
3578 if (!target_is_async_p ())
3579 {
3580 ofunc = signal (SIGINT, remote_interrupt);
3581 /* If the user hit C-c before this packet, or between packets,
3582 pretend that it was hit right here. */
3583 if (quit_flag)
3584 {
3585 quit_flag = 0;
3586 remote_interrupt (SIGINT);
3587 }
3588 }
3589 /* FIXME: cagney/1999-09-27: If we're in async mode we should
3590 _never_ wait for ever -> test on target_is_async_p().
3591 However, before we do that we need to ensure that the caller
3592 knows how to take the target into/out of async mode. */
3593 getpkt (&rs->buf, &rs->buf_size, wait_forever_enabled_p);
3594 if (!target_is_async_p ())
3595 signal (SIGINT, ofunc);
3596 }
3597
3598 buf = rs->buf;
3599
3600 switch (buf[0])
3601 {
3602 case 'E': /* Error of some sort. */
3603 /* We're out of sync with the target now. Did it continue or not?
3604 Not is more likely, so report a stop. */
3605 warning (_("Remote failure reply: %s"), buf);
3606 status->kind = TARGET_WAITKIND_STOPPED;
3607 status->value.sig = TARGET_SIGNAL_0;
3608 goto got_status;
3609 case 'F': /* File-I/O request. */
3610 remote_fileio_request (buf);
3611 continue;
3612 case 'T': /* Status with PC, SP, FP, ... */
3613 {
3614 gdb_byte regs[MAX_REGISTER_SIZE];
3615
3616 /* Expedited reply, containing Signal, {regno, reg} repeat. */
3617 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
3618 ss = signal number
3619 n... = register number
3620 r... = register contents
3621 */
3622 p = &buf[3]; /* after Txx */
3623
3624 while (*p)
3625 {
3626 char *p1;
3627 char *p_temp;
3628 int fieldsize;
3629 long pnum = 0;
3630
3631 /* If the packet contains a register number, save it
3632 in pnum and set p1 to point to the character
3633 following it. Otherwise p1 points to p. */
3634
3635 /* If this packet is an awatch packet, don't parse the 'a'
3636 as a register number. */
3637
3638 if (strncmp (p, "awatch", strlen("awatch")) != 0)
3639 {
3640 /* Read the register number. */
3641 pnum = strtol (p, &p_temp, 16);
3642 p1 = p_temp;
3643 }
3644 else
3645 p1 = p;
3646
3647 if (p1 == p) /* No register number present here. */
3648 {
3649 p1 = strchr (p, ':');
3650 if (p1 == NULL)
3651 error (_("Malformed packet(a) (missing colon): %s\n\
3652 Packet: '%s'\n"),
3653 p, buf);
3654 if (strncmp (p, "thread", p1 - p) == 0)
3655 {
3656 p_temp = unpack_varlen_hex (++p1, &thread_num);
3657 record_currthread (thread_num);
3658 p = p_temp;
3659 }
3660 else if ((strncmp (p, "watch", p1 - p) == 0)
3661 || (strncmp (p, "rwatch", p1 - p) == 0)
3662 || (strncmp (p, "awatch", p1 - p) == 0))
3663 {
3664 remote_stopped_by_watchpoint_p = 1;
3665 p = unpack_varlen_hex (++p1, &addr);
3666 remote_watch_data_address = (CORE_ADDR)addr;
3667 }
3668 else if (strncmp (p, "library", p1 - p) == 0)
3669 {
3670 p1++;
3671 p_temp = p1;
3672 while (*p_temp && *p_temp != ';')
3673 p_temp++;
3674
3675 solibs_changed = 1;
3676 p = p_temp;
3677 }
3678 else
3679 {
3680 /* Silently skip unknown optional info. */
3681 p_temp = strchr (p1 + 1, ';');
3682 if (p_temp)
3683 p = p_temp;
3684 }
3685 }
3686
3687 else
3688 {
3689 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
3690 p = p1;
3691 if (*p++ != ':')
3692 error (_("Malformed packet(b) (missing colon): %s\n\
3693 Packet: '%s'\n"),
3694 p, buf);
3695
3696 if (reg == NULL)
3697 error (_("Remote sent bad register number %ld: %s\n\
3698 Packet: '%s'\n"),
3699 pnum, p, buf);
3700
3701 fieldsize = hex2bin (p, regs,
3702 register_size (current_gdbarch,
3703 reg->regnum));
3704 p += 2 * fieldsize;
3705 if (fieldsize < register_size (current_gdbarch,
3706 reg->regnum))
3707 warning (_("Remote reply is too short: %s"), buf);
3708 regcache_raw_supply (get_current_regcache (),
3709 reg->regnum, regs);
3710 }
3711
3712 if (*p++ != ';')
3713 error (_("Remote register badly formatted: %s\nhere: %s"),
3714 buf, p);
3715 }
3716 }
3717 /* fall through */
3718 case 'S': /* Old style status, just signal only. */
3719 if (solibs_changed)
3720 status->kind = TARGET_WAITKIND_LOADED;
3721 else
3722 {
3723 status->kind = TARGET_WAITKIND_STOPPED;
3724 status->value.sig = (enum target_signal)
3725 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3726 }
3727
3728 if (buf[3] == 'p')
3729 {
3730 thread_num = strtol ((const char *) &buf[4], NULL, 16);
3731 record_currthread (thread_num);
3732 }
3733 goto got_status;
3734 case 'W': /* Target exited. */
3735 {
3736 /* The remote process exited. */
3737 status->kind = TARGET_WAITKIND_EXITED;
3738 status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
3739 goto got_status;
3740 }
3741 case 'X':
3742 status->kind = TARGET_WAITKIND_SIGNALLED;
3743 status->value.sig = (enum target_signal)
3744 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3745 kill_kludge = 1;
3746
3747 goto got_status;
3748 case 'O': /* Console output. */
3749 remote_console_output (buf + 1);
3750 /* Return immediately to the event loop. The event loop will
3751 still be waiting on the inferior afterwards. */
3752 status->kind = TARGET_WAITKIND_IGNORE;
3753 goto got_status;
3754 case '\0':
3755 if (last_sent_signal != TARGET_SIGNAL_0)
3756 {
3757 /* Zero length reply means that we tried 'S' or 'C' and
3758 the remote system doesn't support it. */
3759 target_terminal_ours_for_output ();
3760 printf_filtered
3761 ("Can't send signals to this remote system. %s not sent.\n",
3762 target_signal_to_name (last_sent_signal));
3763 last_sent_signal = TARGET_SIGNAL_0;
3764 target_terminal_inferior ();
3765
3766 strcpy ((char *) buf, last_sent_step ? "s" : "c");
3767 putpkt ((char *) buf);
3768 continue;
3769 }
3770 /* else fallthrough */
3771 default:
3772 warning (_("Invalid remote reply: %s"), buf);
3773 continue;
3774 }
3775 }
3776 got_status:
3777 if (thread_num != -1)
3778 {
3779 return pid_to_ptid (thread_num);
3780 }
3781 return inferior_ptid;
3782 }
3783
3784 /* Fetch a single register using a 'p' packet. */
3785
3786 static int
3787 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
3788 {
3789 struct remote_state *rs = get_remote_state ();
3790 char *buf, *p;
3791 char regp[MAX_REGISTER_SIZE];
3792 int i;
3793
3794 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
3795 return 0;
3796
3797 if (reg->pnum == -1)
3798 return 0;
3799
3800 p = rs->buf;
3801 *p++ = 'p';
3802 p += hexnumstr (p, reg->pnum);
3803 *p++ = '\0';
3804 remote_send (&rs->buf, &rs->buf_size);
3805
3806 buf = rs->buf;
3807
3808 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
3809 {
3810 case PACKET_OK:
3811 break;
3812 case PACKET_UNKNOWN:
3813 return 0;
3814 case PACKET_ERROR:
3815 error (_("Could not fetch register \"%s\""),
3816 gdbarch_register_name (get_regcache_arch (regcache), reg->regnum));
3817 }
3818
3819 /* If this register is unfetchable, tell the regcache. */
3820 if (buf[0] == 'x')
3821 {
3822 regcache_raw_supply (regcache, reg->regnum, NULL);
3823 return 1;
3824 }
3825
3826 /* Otherwise, parse and supply the value. */
3827 p = buf;
3828 i = 0;
3829 while (p[0] != 0)
3830 {
3831 if (p[1] == 0)
3832 error (_("fetch_register_using_p: early buf termination"));
3833
3834 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
3835 p += 2;
3836 }
3837 regcache_raw_supply (regcache, reg->regnum, regp);
3838 return 1;
3839 }
3840
3841 /* Fetch the registers included in the target's 'g' packet. */
3842
3843 static int
3844 send_g_packet (void)
3845 {
3846 struct remote_state *rs = get_remote_state ();
3847 int i, buf_len;
3848 char *p;
3849 char *regs;
3850
3851 sprintf (rs->buf, "g");
3852 remote_send (&rs->buf, &rs->buf_size);
3853
3854 /* We can get out of synch in various cases. If the first character
3855 in the buffer is not a hex character, assume that has happened
3856 and try to fetch another packet to read. */
3857 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
3858 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
3859 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
3860 && rs->buf[0] != 'x') /* New: unavailable register value. */
3861 {
3862 if (remote_debug)
3863 fprintf_unfiltered (gdb_stdlog,
3864 "Bad register packet; fetching a new packet\n");
3865 getpkt (&rs->buf, &rs->buf_size, 0);
3866 }
3867
3868 buf_len = strlen (rs->buf);
3869
3870 /* Sanity check the received packet. */
3871 if (buf_len % 2 != 0)
3872 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
3873
3874 return buf_len / 2;
3875 }
3876
3877 static void
3878 process_g_packet (struct regcache *regcache)
3879 {
3880 struct gdbarch *gdbarch = get_regcache_arch (regcache);
3881 struct remote_state *rs = get_remote_state ();
3882 struct remote_arch_state *rsa = get_remote_arch_state ();
3883 int i, buf_len;
3884 char *p;
3885 char *regs;
3886
3887 buf_len = strlen (rs->buf);
3888
3889 /* Further sanity checks, with knowledge of the architecture. */
3890 if (buf_len > 2 * rsa->sizeof_g_packet)
3891 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
3892
3893 /* Save the size of the packet sent to us by the target. It is used
3894 as a heuristic when determining the max size of packets that the
3895 target can safely receive. */
3896 if (rsa->actual_register_packet_size == 0)
3897 rsa->actual_register_packet_size = buf_len;
3898
3899 /* If this is smaller than we guessed the 'g' packet would be,
3900 update our records. A 'g' reply that doesn't include a register's
3901 value implies either that the register is not available, or that
3902 the 'p' packet must be used. */
3903 if (buf_len < 2 * rsa->sizeof_g_packet)
3904 {
3905 rsa->sizeof_g_packet = buf_len / 2;
3906
3907 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
3908 {
3909 if (rsa->regs[i].pnum == -1)
3910 continue;
3911
3912 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
3913 rsa->regs[i].in_g_packet = 0;
3914 else
3915 rsa->regs[i].in_g_packet = 1;
3916 }
3917 }
3918
3919 regs = alloca (rsa->sizeof_g_packet);
3920
3921 /* Unimplemented registers read as all bits zero. */
3922 memset (regs, 0, rsa->sizeof_g_packet);
3923
3924 /* Reply describes registers byte by byte, each byte encoded as two
3925 hex characters. Suck them all up, then supply them to the
3926 register cacheing/storage mechanism. */
3927
3928 p = rs->buf;
3929 for (i = 0; i < rsa->sizeof_g_packet; i++)
3930 {
3931 if (p[0] == 0 || p[1] == 0)
3932 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
3933 internal_error (__FILE__, __LINE__,
3934 "unexpected end of 'g' packet reply");
3935
3936 if (p[0] == 'x' && p[1] == 'x')
3937 regs[i] = 0; /* 'x' */
3938 else
3939 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
3940 p += 2;
3941 }
3942
3943 {
3944 int i;
3945 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
3946 {
3947 struct packet_reg *r = &rsa->regs[i];
3948 if (r->in_g_packet)
3949 {
3950 if (r->offset * 2 >= strlen (rs->buf))
3951 /* This shouldn't happen - we adjusted in_g_packet above. */
3952 internal_error (__FILE__, __LINE__,
3953 "unexpected end of 'g' packet reply");
3954 else if (rs->buf[r->offset * 2] == 'x')
3955 {
3956 gdb_assert (r->offset * 2 < strlen (rs->buf));
3957 /* The register isn't available, mark it as such (at
3958 the same time setting the value to zero). */
3959 regcache_raw_supply (regcache, r->regnum, NULL);
3960 }
3961 else
3962 regcache_raw_supply (regcache, r->regnum,
3963 regs + r->offset);
3964 }
3965 }
3966 }
3967 }
3968
3969 static void
3970 fetch_registers_using_g (struct regcache *regcache)
3971 {
3972 send_g_packet ();
3973 process_g_packet (regcache);
3974 }
3975
3976 static void
3977 remote_fetch_registers (struct regcache *regcache, int regnum)
3978 {
3979 struct remote_state *rs = get_remote_state ();
3980 struct remote_arch_state *rsa = get_remote_arch_state ();
3981 int i;
3982
3983 set_thread (PIDGET (inferior_ptid), 1);
3984
3985 if (regnum >= 0)
3986 {
3987 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
3988 gdb_assert (reg != NULL);
3989
3990 /* If this register might be in the 'g' packet, try that first -
3991 we are likely to read more than one register. If this is the
3992 first 'g' packet, we might be overly optimistic about its
3993 contents, so fall back to 'p'. */
3994 if (reg->in_g_packet)
3995 {
3996 fetch_registers_using_g (regcache);
3997 if (reg->in_g_packet)
3998 return;
3999 }
4000
4001 if (fetch_register_using_p (regcache, reg))
4002 return;
4003
4004 /* This register is not available. */
4005 regcache_raw_supply (regcache, reg->regnum, NULL);
4006
4007 return;
4008 }
4009
4010 fetch_registers_using_g (regcache);
4011
4012 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
4013 if (!rsa->regs[i].in_g_packet)
4014 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
4015 {
4016 /* This register is not available. */
4017 regcache_raw_supply (regcache, i, NULL);
4018 }
4019 }
4020
4021 /* Prepare to store registers. Since we may send them all (using a
4022 'G' request), we have to read out the ones we don't want to change
4023 first. */
4024
4025 static void
4026 remote_prepare_to_store (struct regcache *regcache)
4027 {
4028 struct remote_arch_state *rsa = get_remote_arch_state ();
4029 int i;
4030 gdb_byte buf[MAX_REGISTER_SIZE];
4031
4032 /* Make sure the entire registers array is valid. */
4033 switch (remote_protocol_packets[PACKET_P].support)
4034 {
4035 case PACKET_DISABLE:
4036 case PACKET_SUPPORT_UNKNOWN:
4037 /* Make sure all the necessary registers are cached. */
4038 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
4039 if (rsa->regs[i].in_g_packet)
4040 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
4041 break;
4042 case PACKET_ENABLE:
4043 break;
4044 }
4045 }
4046
4047 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
4048 packet was not recognized. */
4049
4050 static int
4051 store_register_using_P (const struct regcache *regcache, struct packet_reg *reg)
4052 {
4053 struct gdbarch *gdbarch = get_regcache_arch (regcache);
4054 struct remote_state *rs = get_remote_state ();
4055 struct remote_arch_state *rsa = get_remote_arch_state ();
4056 /* Try storing a single register. */
4057 char *buf = rs->buf;
4058 gdb_byte regp[MAX_REGISTER_SIZE];
4059 char *p;
4060
4061 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
4062 return 0;
4063
4064 if (reg->pnum == -1)
4065 return 0;
4066
4067 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
4068 p = buf + strlen (buf);
4069 regcache_raw_collect (regcache, reg->regnum, regp);
4070 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
4071 remote_send (&rs->buf, &rs->buf_size);
4072
4073 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
4074 {
4075 case PACKET_OK:
4076 return 1;
4077 case PACKET_ERROR:
4078 error (_("Could not write register \"%s\""),
4079 gdbarch_register_name (gdbarch, reg->regnum));
4080 case PACKET_UNKNOWN:
4081 return 0;
4082 default:
4083 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
4084 }
4085 }
4086
4087 /* Store register REGNUM, or all registers if REGNUM == -1, from the
4088 contents of the register cache buffer. FIXME: ignores errors. */
4089
4090 static void
4091 store_registers_using_G (const struct regcache *regcache)
4092 {
4093 struct remote_state *rs = get_remote_state ();
4094 struct remote_arch_state *rsa = get_remote_arch_state ();
4095 gdb_byte *regs;
4096 char *p;
4097
4098 /* Extract all the registers in the regcache copying them into a
4099 local buffer. */
4100 {
4101 int i;
4102 regs = alloca (rsa->sizeof_g_packet);
4103 memset (regs, 0, rsa->sizeof_g_packet);
4104 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
4105 {
4106 struct packet_reg *r = &rsa->regs[i];
4107 if (r->in_g_packet)
4108 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
4109 }
4110 }
4111
4112 /* Command describes registers byte by byte,
4113 each byte encoded as two hex characters. */
4114 p = rs->buf;
4115 *p++ = 'G';
4116 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
4117 updated. */
4118 bin2hex (regs, p, rsa->sizeof_g_packet);
4119 remote_send (&rs->buf, &rs->buf_size);
4120 }
4121
4122 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
4123 of the register cache buffer. FIXME: ignores errors. */
4124
4125 static void
4126 remote_store_registers (struct regcache *regcache, int regnum)
4127 {
4128 struct remote_state *rs = get_remote_state ();
4129 struct remote_arch_state *rsa = get_remote_arch_state ();
4130 int i;
4131
4132 set_thread (PIDGET (inferior_ptid), 1);
4133
4134 if (regnum >= 0)
4135 {
4136 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
4137 gdb_assert (reg != NULL);
4138
4139 /* Always prefer to store registers using the 'P' packet if
4140 possible; we often change only a small number of registers.
4141 Sometimes we change a larger number; we'd need help from a
4142 higher layer to know to use 'G'. */
4143 if (store_register_using_P (regcache, reg))
4144 return;
4145
4146 /* For now, don't complain if we have no way to write the
4147 register. GDB loses track of unavailable registers too
4148 easily. Some day, this may be an error. We don't have
4149 any way to read the register, either... */
4150 if (!reg->in_g_packet)
4151 return;
4152
4153 store_registers_using_G (regcache);
4154 return;
4155 }
4156
4157 store_registers_using_G (regcache);
4158
4159 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
4160 if (!rsa->regs[i].in_g_packet)
4161 if (!store_register_using_P (regcache, &rsa->regs[i]))
4162 /* See above for why we do not issue an error here. */
4163 continue;
4164 }
4165 \f
4166
4167 /* Return the number of hex digits in num. */
4168
4169 static int
4170 hexnumlen (ULONGEST num)
4171 {
4172 int i;
4173
4174 for (i = 0; num != 0; i++)
4175 num >>= 4;
4176
4177 return max (i, 1);
4178 }
4179
4180 /* Set BUF to the minimum number of hex digits representing NUM. */
4181
4182 static int
4183 hexnumstr (char *buf, ULONGEST num)
4184 {
4185 int len = hexnumlen (num);
4186 return hexnumnstr (buf, num, len);
4187 }
4188
4189
4190 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
4191
4192 static int
4193 hexnumnstr (char *buf, ULONGEST num, int width)
4194 {
4195 int i;
4196
4197 buf[width] = '\0';
4198
4199 for (i = width - 1; i >= 0; i--)
4200 {
4201 buf[i] = "0123456789abcdef"[(num & 0xf)];
4202 num >>= 4;
4203 }
4204
4205 return width;
4206 }
4207
4208 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
4209
4210 static CORE_ADDR
4211 remote_address_masked (CORE_ADDR addr)
4212 {
4213 int address_size = remote_address_size;
4214 /* If "remoteaddresssize" was not set, default to target address size. */
4215 if (!address_size)
4216 address_size = gdbarch_addr_bit (current_gdbarch);
4217
4218 if (address_size > 0
4219 && address_size < (sizeof (ULONGEST) * 8))
4220 {
4221 /* Only create a mask when that mask can safely be constructed
4222 in a ULONGEST variable. */
4223 ULONGEST mask = 1;
4224 mask = (mask << address_size) - 1;
4225 addr &= mask;
4226 }
4227 return addr;
4228 }
4229
4230 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
4231 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
4232 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
4233 (which may be more than *OUT_LEN due to escape characters). The
4234 total number of bytes in the output buffer will be at most
4235 OUT_MAXLEN. */
4236
4237 static int
4238 remote_escape_output (const gdb_byte *buffer, int len,
4239 gdb_byte *out_buf, int *out_len,
4240 int out_maxlen)
4241 {
4242 int input_index, output_index;
4243
4244 output_index = 0;
4245 for (input_index = 0; input_index < len; input_index++)
4246 {
4247 gdb_byte b = buffer[input_index];
4248
4249 if (b == '$' || b == '#' || b == '}')
4250 {
4251 /* These must be escaped. */
4252 if (output_index + 2 > out_maxlen)
4253 break;
4254 out_buf[output_index++] = '}';
4255 out_buf[output_index++] = b ^ 0x20;
4256 }
4257 else
4258 {
4259 if (output_index + 1 > out_maxlen)
4260 break;
4261 out_buf[output_index++] = b;
4262 }
4263 }
4264
4265 *out_len = input_index;
4266 return output_index;
4267 }
4268
4269 /* Convert BUFFER, escaped data LEN bytes long, into binary data
4270 in OUT_BUF. Return the number of bytes written to OUT_BUF.
4271 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
4272
4273 This function reverses remote_escape_output. It allows more
4274 escaped characters than that function does, in particular because
4275 '*' must be escaped to avoid the run-length encoding processing
4276 in reading packets. */
4277
4278 static int
4279 remote_unescape_input (const gdb_byte *buffer, int len,
4280 gdb_byte *out_buf, int out_maxlen)
4281 {
4282 int input_index, output_index;
4283 int escaped;
4284
4285 output_index = 0;
4286 escaped = 0;
4287 for (input_index = 0; input_index < len; input_index++)
4288 {
4289 gdb_byte b = buffer[input_index];
4290
4291 if (output_index + 1 > out_maxlen)
4292 {
4293 warning (_("Received too much data from remote target;"
4294 " ignoring overflow."));
4295 return output_index;
4296 }
4297
4298 if (escaped)
4299 {
4300 out_buf[output_index++] = b ^ 0x20;
4301 escaped = 0;
4302 }
4303 else if (b == '}')
4304 escaped = 1;
4305 else
4306 out_buf[output_index++] = b;
4307 }
4308
4309 if (escaped)
4310 error (_("Unmatched escape character in target response."));
4311
4312 return output_index;
4313 }
4314
4315 /* Determine whether the remote target supports binary downloading.
4316 This is accomplished by sending a no-op memory write of zero length
4317 to the target at the specified address. It does not suffice to send
4318 the whole packet, since many stubs strip the eighth bit and
4319 subsequently compute a wrong checksum, which causes real havoc with
4320 remote_write_bytes.
4321
4322 NOTE: This can still lose if the serial line is not eight-bit
4323 clean. In cases like this, the user should clear "remote
4324 X-packet". */
4325
4326 static void
4327 check_binary_download (CORE_ADDR addr)
4328 {
4329 struct remote_state *rs = get_remote_state ();
4330
4331 switch (remote_protocol_packets[PACKET_X].support)
4332 {
4333 case PACKET_DISABLE:
4334 break;
4335 case PACKET_ENABLE:
4336 break;
4337 case PACKET_SUPPORT_UNKNOWN:
4338 {
4339 char *p;
4340
4341 p = rs->buf;
4342 *p++ = 'X';
4343 p += hexnumstr (p, (ULONGEST) addr);
4344 *p++ = ',';
4345 p += hexnumstr (p, (ULONGEST) 0);
4346 *p++ = ':';
4347 *p = '\0';
4348
4349 putpkt_binary (rs->buf, (int) (p - rs->buf));
4350 getpkt (&rs->buf, &rs->buf_size, 0);
4351
4352 if (rs->buf[0] == '\0')
4353 {
4354 if (remote_debug)
4355 fprintf_unfiltered (gdb_stdlog,
4356 "binary downloading NOT suppported by target\n");
4357 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
4358 }
4359 else
4360 {
4361 if (remote_debug)
4362 fprintf_unfiltered (gdb_stdlog,
4363 "binary downloading suppported by target\n");
4364 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
4365 }
4366 break;
4367 }
4368 }
4369 }
4370
4371 /* Write memory data directly to the remote machine.
4372 This does not inform the data cache; the data cache uses this.
4373 HEADER is the starting part of the packet.
4374 MEMADDR is the address in the remote memory space.
4375 MYADDR is the address of the buffer in our space.
4376 LEN is the number of bytes.
4377 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
4378 should send data as binary ('X'), or hex-encoded ('M').
4379
4380 The function creates packet of the form
4381 <HEADER><ADDRESS>,<LENGTH>:<DATA>
4382
4383 where encoding of <DATA> is termined by PACKET_FORMAT.
4384
4385 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
4386 are omitted.
4387
4388 Returns the number of bytes transferred, or 0 (setting errno) for
4389 error. Only transfer a single packet. */
4390
4391 static int
4392 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
4393 const gdb_byte *myaddr, int len,
4394 char packet_format, int use_length)
4395 {
4396 struct remote_state *rs = get_remote_state ();
4397 char *p;
4398 char *plen = NULL;
4399 int plenlen = 0;
4400 int todo;
4401 int nr_bytes;
4402 int payload_size;
4403 int payload_length;
4404 int header_length;
4405
4406 if (packet_format != 'X' && packet_format != 'M')
4407 internal_error (__FILE__, __LINE__,
4408 "remote_write_bytes_aux: bad packet format");
4409
4410 if (len <= 0)
4411 return 0;
4412
4413 payload_size = get_memory_write_packet_size ();
4414
4415 /* The packet buffer will be large enough for the payload;
4416 get_memory_packet_size ensures this. */
4417 rs->buf[0] = '\0';
4418
4419 /* Compute the size of the actual payload by subtracting out the
4420 packet header and footer overhead: "$M<memaddr>,<len>:...#nn".
4421 */
4422 payload_size -= strlen ("$,:#NN");
4423 if (!use_length)
4424 /* The comma won't be used. */
4425 payload_size += 1;
4426 header_length = strlen (header);
4427 payload_size -= header_length;
4428 payload_size -= hexnumlen (memaddr);
4429
4430 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
4431
4432 strcat (rs->buf, header);
4433 p = rs->buf + strlen (header);
4434
4435 /* Compute a best guess of the number of bytes actually transfered. */
4436 if (packet_format == 'X')
4437 {
4438 /* Best guess at number of bytes that will fit. */
4439 todo = min (len, payload_size);
4440 if (use_length)
4441 payload_size -= hexnumlen (todo);
4442 todo = min (todo, payload_size);
4443 }
4444 else
4445 {
4446 /* Num bytes that will fit. */
4447 todo = min (len, payload_size / 2);
4448 if (use_length)
4449 payload_size -= hexnumlen (todo);
4450 todo = min (todo, payload_size / 2);
4451 }
4452
4453 if (todo <= 0)
4454 internal_error (__FILE__, __LINE__,
4455 _("minumum packet size too small to write data"));
4456
4457 /* If we already need another packet, then try to align the end
4458 of this packet to a useful boundary. */
4459 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
4460 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
4461
4462 /* Append "<memaddr>". */
4463 memaddr = remote_address_masked (memaddr);
4464 p += hexnumstr (p, (ULONGEST) memaddr);
4465
4466 if (use_length)
4467 {
4468 /* Append ",". */
4469 *p++ = ',';
4470
4471 /* Append <len>. Retain the location/size of <len>. It may need to
4472 be adjusted once the packet body has been created. */
4473 plen = p;
4474 plenlen = hexnumstr (p, (ULONGEST) todo);
4475 p += plenlen;
4476 }
4477
4478 /* Append ":". */
4479 *p++ = ':';
4480 *p = '\0';
4481
4482 /* Append the packet body. */
4483 if (packet_format == 'X')
4484 {
4485 /* Binary mode. Send target system values byte by byte, in
4486 increasing byte addresses. Only escape certain critical
4487 characters. */
4488 payload_length = remote_escape_output (myaddr, todo, p, &nr_bytes,
4489 payload_size);
4490
4491 /* If not all TODO bytes fit, then we'll need another packet. Make
4492 a second try to keep the end of the packet aligned. Don't do
4493 this if the packet is tiny. */
4494 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
4495 {
4496 int new_nr_bytes;
4497
4498 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
4499 - memaddr);
4500 if (new_nr_bytes != nr_bytes)
4501 payload_length = remote_escape_output (myaddr, new_nr_bytes,
4502 p, &nr_bytes,
4503 payload_size);
4504 }
4505
4506 p += payload_length;
4507 if (use_length && nr_bytes < todo)
4508 {
4509 /* Escape chars have filled up the buffer prematurely,
4510 and we have actually sent fewer bytes than planned.
4511 Fix-up the length field of the packet. Use the same
4512 number of characters as before. */
4513 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
4514 *plen = ':'; /* overwrite \0 from hexnumnstr() */
4515 }
4516 }
4517 else
4518 {
4519 /* Normal mode: Send target system values byte by byte, in
4520 increasing byte addresses. Each byte is encoded as a two hex
4521 value. */
4522 nr_bytes = bin2hex (myaddr, p, todo);
4523 p += 2 * nr_bytes;
4524 }
4525
4526 putpkt_binary (rs->buf, (int) (p - rs->buf));
4527 getpkt (&rs->buf, &rs->buf_size, 0);
4528
4529 if (rs->buf[0] == 'E')
4530 {
4531 /* There is no correspondance between what the remote protocol
4532 uses for errors and errno codes. We would like a cleaner way
4533 of representing errors (big enough to include errno codes,
4534 bfd_error codes, and others). But for now just return EIO. */
4535 errno = EIO;
4536 return 0;
4537 }
4538
4539 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
4540 fewer bytes than we'd planned. */
4541 return nr_bytes;
4542 }
4543
4544 /* Write memory data directly to the remote machine.
4545 This does not inform the data cache; the data cache uses this.
4546 MEMADDR is the address in the remote memory space.
4547 MYADDR is the address of the buffer in our space.
4548 LEN is the number of bytes.
4549
4550 Returns number of bytes transferred, or 0 (setting errno) for
4551 error. Only transfer a single packet. */
4552
4553 int
4554 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
4555 {
4556 char *packet_format = 0;
4557
4558 /* Check whether the target supports binary download. */
4559 check_binary_download (memaddr);
4560
4561 switch (remote_protocol_packets[PACKET_X].support)
4562 {
4563 case PACKET_ENABLE:
4564 packet_format = "X";
4565 break;
4566 case PACKET_DISABLE:
4567 packet_format = "M";
4568 break;
4569 case PACKET_SUPPORT_UNKNOWN:
4570 internal_error (__FILE__, __LINE__,
4571 _("remote_write_bytes: bad internal state"));
4572 default:
4573 internal_error (__FILE__, __LINE__, _("bad switch"));
4574 }
4575
4576 return remote_write_bytes_aux (packet_format,
4577 memaddr, myaddr, len, packet_format[0], 1);
4578 }
4579
4580 /* Read memory data directly from the remote machine.
4581 This does not use the data cache; the data cache uses this.
4582 MEMADDR is the address in the remote memory space.
4583 MYADDR is the address of the buffer in our space.
4584 LEN is the number of bytes.
4585
4586 Returns number of bytes transferred, or 0 for error. */
4587
4588 /* NOTE: cagney/1999-10-18: This function (and its siblings in other
4589 remote targets) shouldn't attempt to read the entire buffer.
4590 Instead it should read a single packet worth of data and then
4591 return the byte size of that packet to the caller. The caller (its
4592 caller and its callers caller ;-) already contains code for
4593 handling partial reads. */
4594
4595 int
4596 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
4597 {
4598 struct remote_state *rs = get_remote_state ();
4599 int max_buf_size; /* Max size of packet output buffer. */
4600 int origlen;
4601
4602 if (len <= 0)
4603 return 0;
4604
4605 max_buf_size = get_memory_read_packet_size ();
4606 /* The packet buffer will be large enough for the payload;
4607 get_memory_packet_size ensures this. */
4608
4609 origlen = len;
4610 while (len > 0)
4611 {
4612 char *p;
4613 int todo;
4614 int i;
4615
4616 todo = min (len, max_buf_size / 2); /* num bytes that will fit */
4617
4618 /* construct "m"<memaddr>","<len>" */
4619 /* sprintf (rs->buf, "m%lx,%x", (unsigned long) memaddr, todo); */
4620 memaddr = remote_address_masked (memaddr);
4621 p = rs->buf;
4622 *p++ = 'm';
4623 p += hexnumstr (p, (ULONGEST) memaddr);
4624 *p++ = ',';
4625 p += hexnumstr (p, (ULONGEST) todo);
4626 *p = '\0';
4627
4628 putpkt (rs->buf);
4629 getpkt (&rs->buf, &rs->buf_size, 0);
4630
4631 if (rs->buf[0] == 'E'
4632 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
4633 && rs->buf[3] == '\0')
4634 {
4635 /* There is no correspondance between what the remote
4636 protocol uses for errors and errno codes. We would like
4637 a cleaner way of representing errors (big enough to
4638 include errno codes, bfd_error codes, and others). But
4639 for now just return EIO. */
4640 errno = EIO;
4641 return 0;
4642 }
4643
4644 /* Reply describes memory byte by byte,
4645 each byte encoded as two hex characters. */
4646
4647 p = rs->buf;
4648 if ((i = hex2bin (p, myaddr, todo)) < todo)
4649 {
4650 /* Reply is short. This means that we were able to read
4651 only part of what we wanted to. */
4652 return i + (origlen - len);
4653 }
4654 myaddr += todo;
4655 memaddr += todo;
4656 len -= todo;
4657 }
4658 return origlen;
4659 }
4660 \f
4661 /* Read or write LEN bytes from inferior memory at MEMADDR,
4662 transferring to or from debugger address BUFFER. Write to inferior
4663 if SHOULD_WRITE is nonzero. Returns length of data written or
4664 read; 0 for error. TARGET is unused. */
4665
4666 static int
4667 remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
4668 int should_write, struct mem_attrib *attrib,
4669 struct target_ops *target)
4670 {
4671 int res;
4672
4673 if (should_write)
4674 res = remote_write_bytes (mem_addr, buffer, mem_len);
4675 else
4676 res = remote_read_bytes (mem_addr, buffer, mem_len);
4677
4678 return res;
4679 }
4680
4681 /* Sends a packet with content determined by the printf format string
4682 FORMAT and the remaining arguments, then gets the reply. Returns
4683 whether the packet was a success, a failure, or unknown. */
4684
4685 enum packet_result
4686 remote_send_printf (const char *format, ...)
4687 {
4688 struct remote_state *rs = get_remote_state ();
4689 int max_size = get_remote_packet_size ();
4690
4691 va_list ap;
4692 va_start (ap, format);
4693
4694 rs->buf[0] = '\0';
4695 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
4696 internal_error (__FILE__, __LINE__, "Too long remote packet.");
4697
4698 if (putpkt (rs->buf) < 0)
4699 error (_("Communication problem with target."));
4700
4701 rs->buf[0] = '\0';
4702 getpkt (&rs->buf, &rs->buf_size, 0);
4703
4704 return packet_check_result (rs->buf);
4705 }
4706
4707 static void
4708 restore_remote_timeout (void *p)
4709 {
4710 int value = *(int *)p;
4711 remote_timeout = value;
4712 }
4713
4714 /* Flash writing can take quite some time. We'll set
4715 effectively infinite timeout for flash operations.
4716 In future, we'll need to decide on a better approach. */
4717 static const int remote_flash_timeout = 1000;
4718
4719 static void
4720 remote_flash_erase (struct target_ops *ops,
4721 ULONGEST address, LONGEST length)
4722 {
4723 int saved_remote_timeout = remote_timeout;
4724 enum packet_result ret;
4725
4726 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
4727 &saved_remote_timeout);
4728 remote_timeout = remote_flash_timeout;
4729
4730 ret = remote_send_printf ("vFlashErase:%s,%s",
4731 paddr (address),
4732 phex (length, 4));
4733 switch (ret)
4734 {
4735 case PACKET_UNKNOWN:
4736 error (_("Remote target does not support flash erase"));
4737 case PACKET_ERROR:
4738 error (_("Error erasing flash with vFlashErase packet"));
4739 default:
4740 break;
4741 }
4742
4743 do_cleanups (back_to);
4744 }
4745
4746 static LONGEST
4747 remote_flash_write (struct target_ops *ops,
4748 ULONGEST address, LONGEST length,
4749 const gdb_byte *data)
4750 {
4751 int saved_remote_timeout = remote_timeout;
4752 int ret;
4753 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
4754 &saved_remote_timeout);
4755
4756 remote_timeout = remote_flash_timeout;
4757 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
4758 do_cleanups (back_to);
4759
4760 return ret;
4761 }
4762
4763 static void
4764 remote_flash_done (struct target_ops *ops)
4765 {
4766 int saved_remote_timeout = remote_timeout;
4767 int ret;
4768 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
4769 &saved_remote_timeout);
4770
4771 remote_timeout = remote_flash_timeout;
4772 ret = remote_send_printf ("vFlashDone");
4773 do_cleanups (back_to);
4774
4775 switch (ret)
4776 {
4777 case PACKET_UNKNOWN:
4778 error (_("Remote target does not support vFlashDone"));
4779 case PACKET_ERROR:
4780 error (_("Error finishing flash operation"));
4781 default:
4782 break;
4783 }
4784 }
4785
4786 static void
4787 remote_files_info (struct target_ops *ignore)
4788 {
4789 puts_filtered ("Debugging a target over a serial line.\n");
4790 }
4791 \f
4792 /* Stuff for dealing with the packets which are part of this protocol.
4793 See comment at top of file for details. */
4794
4795 /* Read a single character from the remote end. */
4796
4797 static int
4798 readchar (int timeout)
4799 {
4800 int ch;
4801
4802 ch = serial_readchar (remote_desc, timeout);
4803
4804 if (ch >= 0)
4805 return ch;
4806
4807 switch ((enum serial_rc) ch)
4808 {
4809 case SERIAL_EOF:
4810 target_mourn_inferior ();
4811 error (_("Remote connection closed"));
4812 /* no return */
4813 case SERIAL_ERROR:
4814 perror_with_name (_("Remote communication error"));
4815 /* no return */
4816 case SERIAL_TIMEOUT:
4817 break;
4818 }
4819 return ch;
4820 }
4821
4822 /* Send the command in *BUF to the remote machine, and read the reply
4823 into *BUF. Report an error if we get an error reply. Resize
4824 *BUF using xrealloc if necessary to hold the result, and update
4825 *SIZEOF_BUF. */
4826
4827 static void
4828 remote_send (char **buf,
4829 long *sizeof_buf)
4830 {
4831 putpkt (*buf);
4832 getpkt (buf, sizeof_buf, 0);
4833
4834 if ((*buf)[0] == 'E')
4835 error (_("Remote failure reply: %s"), *buf);
4836 }
4837
4838 /* Display a null-terminated packet on stdout, for debugging, using C
4839 string notation. */
4840
4841 static void
4842 print_packet (char *buf)
4843 {
4844 puts_filtered ("\"");
4845 fputstr_filtered (buf, '"', gdb_stdout);
4846 puts_filtered ("\"");
4847 }
4848
4849 int
4850 putpkt (char *buf)
4851 {
4852 return putpkt_binary (buf, strlen (buf));
4853 }
4854
4855 /* Send a packet to the remote machine, with error checking. The data
4856 of the packet is in BUF. The string in BUF can be at most
4857 get_remote_packet_size () - 5 to account for the $, # and checksum,
4858 and for a possible /0 if we are debugging (remote_debug) and want
4859 to print the sent packet as a string. */
4860
4861 static int
4862 putpkt_binary (char *buf, int cnt)
4863 {
4864 struct remote_state *rs = get_remote_state ();
4865 int i;
4866 unsigned char csum = 0;
4867 char *buf2 = alloca (cnt + 6);
4868
4869 int ch;
4870 int tcount = 0;
4871 char *p;
4872
4873 /* We're sending out a new packet. Make sure we don't look at a
4874 stale cached response. */
4875 rs->cached_wait_status = 0;
4876
4877 /* Copy the packet into buffer BUF2, encapsulating it
4878 and giving it a checksum. */
4879
4880 p = buf2;
4881 *p++ = '$';
4882
4883 for (i = 0; i < cnt; i++)
4884 {
4885 csum += buf[i];
4886 *p++ = buf[i];
4887 }
4888 *p++ = '#';
4889 *p++ = tohex ((csum >> 4) & 0xf);
4890 *p++ = tohex (csum & 0xf);
4891
4892 /* Send it over and over until we get a positive ack. */
4893
4894 while (1)
4895 {
4896 int started_error_output = 0;
4897
4898 if (remote_debug)
4899 {
4900 *p = '\0';
4901 fprintf_unfiltered (gdb_stdlog, "Sending packet: ");
4902 fputstrn_unfiltered (buf2, p - buf2, 0, gdb_stdlog);
4903 fprintf_unfiltered (gdb_stdlog, "...");
4904 gdb_flush (gdb_stdlog);
4905 }
4906 if (serial_write (remote_desc, buf2, p - buf2))
4907 perror_with_name (_("putpkt: write failed"));
4908
4909 /* Read until either a timeout occurs (-2) or '+' is read. */
4910 while (1)
4911 {
4912 ch = readchar (remote_timeout);
4913
4914 if (remote_debug)
4915 {
4916 switch (ch)
4917 {
4918 case '+':
4919 case '-':
4920 case SERIAL_TIMEOUT:
4921 case '$':
4922 if (started_error_output)
4923 {
4924 putchar_unfiltered ('\n');
4925 started_error_output = 0;
4926 }
4927 }
4928 }
4929
4930 switch (ch)
4931 {
4932 case '+':
4933 if (remote_debug)
4934 fprintf_unfiltered (gdb_stdlog, "Ack\n");
4935 return 1;
4936 case '-':
4937 if (remote_debug)
4938 fprintf_unfiltered (gdb_stdlog, "Nak\n");
4939 case SERIAL_TIMEOUT:
4940 tcount++;
4941 if (tcount > 3)
4942 return 0;
4943 break; /* Retransmit buffer. */
4944 case '$':
4945 {
4946 if (remote_debug)
4947 fprintf_unfiltered (gdb_stdlog,
4948 "Packet instead of Ack, ignoring it\n");
4949 /* It's probably an old response sent because an ACK
4950 was lost. Gobble up the packet and ack it so it
4951 doesn't get retransmitted when we resend this
4952 packet. */
4953 skip_frame ();
4954 serial_write (remote_desc, "+", 1);
4955 continue; /* Now, go look for +. */
4956 }
4957 default:
4958 if (remote_debug)
4959 {
4960 if (!started_error_output)
4961 {
4962 started_error_output = 1;
4963 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
4964 }
4965 fputc_unfiltered (ch & 0177, gdb_stdlog);
4966 }
4967 continue;
4968 }
4969 break; /* Here to retransmit. */
4970 }
4971
4972 #if 0
4973 /* This is wrong. If doing a long backtrace, the user should be
4974 able to get out next time we call QUIT, without anything as
4975 violent as interrupt_query. If we want to provide a way out of
4976 here without getting to the next QUIT, it should be based on
4977 hitting ^C twice as in remote_wait. */
4978 if (quit_flag)
4979 {
4980 quit_flag = 0;
4981 interrupt_query ();
4982 }
4983 #endif
4984 }
4985 }
4986
4987 /* Come here after finding the start of a frame when we expected an
4988 ack. Do our best to discard the rest of this packet. */
4989
4990 static void
4991 skip_frame (void)
4992 {
4993 int c;
4994
4995 while (1)
4996 {
4997 c = readchar (remote_timeout);
4998 switch (c)
4999 {
5000 case SERIAL_TIMEOUT:
5001 /* Nothing we can do. */
5002 return;
5003 case '#':
5004 /* Discard the two bytes of checksum and stop. */
5005 c = readchar (remote_timeout);
5006 if (c >= 0)
5007 c = readchar (remote_timeout);
5008
5009 return;
5010 case '*': /* Run length encoding. */
5011 /* Discard the repeat count. */
5012 c = readchar (remote_timeout);
5013 if (c < 0)
5014 return;
5015 break;
5016 default:
5017 /* A regular character. */
5018 break;
5019 }
5020 }
5021 }
5022
5023 /* Come here after finding the start of the frame. Collect the rest
5024 into *BUF, verifying the checksum, length, and handling run-length
5025 compression. NUL terminate the buffer. If there is not enough room,
5026 expand *BUF using xrealloc.
5027
5028 Returns -1 on error, number of characters in buffer (ignoring the
5029 trailing NULL) on success. (could be extended to return one of the
5030 SERIAL status indications). */
5031
5032 static long
5033 read_frame (char **buf_p,
5034 long *sizeof_buf)
5035 {
5036 unsigned char csum;
5037 long bc;
5038 int c;
5039 char *buf = *buf_p;
5040
5041 csum = 0;
5042 bc = 0;
5043
5044 while (1)
5045 {
5046 c = readchar (remote_timeout);
5047 switch (c)
5048 {
5049 case SERIAL_TIMEOUT:
5050 if (remote_debug)
5051 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
5052 return -1;
5053 case '$':
5054 if (remote_debug)
5055 fputs_filtered ("Saw new packet start in middle of old one\n",
5056 gdb_stdlog);
5057 return -1; /* Start a new packet, count retries. */
5058 case '#':
5059 {
5060 unsigned char pktcsum;
5061 int check_0 = 0;
5062 int check_1 = 0;
5063
5064 buf[bc] = '\0';
5065
5066 check_0 = readchar (remote_timeout);
5067 if (check_0 >= 0)
5068 check_1 = readchar (remote_timeout);
5069
5070 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
5071 {
5072 if (remote_debug)
5073 fputs_filtered ("Timeout in checksum, retrying\n",
5074 gdb_stdlog);
5075 return -1;
5076 }
5077 else if (check_0 < 0 || check_1 < 0)
5078 {
5079 if (remote_debug)
5080 fputs_filtered ("Communication error in checksum\n",
5081 gdb_stdlog);
5082 return -1;
5083 }
5084
5085 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
5086 if (csum == pktcsum)
5087 return bc;
5088
5089 if (remote_debug)
5090 {
5091 fprintf_filtered (gdb_stdlog,
5092 "Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
5093 pktcsum, csum);
5094 fputstrn_filtered (buf, bc, 0, gdb_stdlog);
5095 fputs_filtered ("\n", gdb_stdlog);
5096 }
5097 /* Number of characters in buffer ignoring trailing
5098 NULL. */
5099 return -1;
5100 }
5101 case '*': /* Run length encoding. */
5102 {
5103 int repeat;
5104 csum += c;
5105
5106 c = readchar (remote_timeout);
5107 csum += c;
5108 repeat = c - ' ' + 3; /* Compute repeat count. */
5109
5110 /* The character before ``*'' is repeated. */
5111
5112 if (repeat > 0 && repeat <= 255 && bc > 0)
5113 {
5114 if (bc + repeat - 1 >= *sizeof_buf - 1)
5115 {
5116 /* Make some more room in the buffer. */
5117 *sizeof_buf += repeat;
5118 *buf_p = xrealloc (*buf_p, *sizeof_buf);
5119 buf = *buf_p;
5120 }
5121
5122 memset (&buf[bc], buf[bc - 1], repeat);
5123 bc += repeat;
5124 continue;
5125 }
5126
5127 buf[bc] = '\0';
5128 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
5129 return -1;
5130 }
5131 default:
5132 if (bc >= *sizeof_buf - 1)
5133 {
5134 /* Make some more room in the buffer. */
5135 *sizeof_buf *= 2;
5136 *buf_p = xrealloc (*buf_p, *sizeof_buf);
5137 buf = *buf_p;
5138 }
5139
5140 buf[bc++] = c;
5141 csum += c;
5142 continue;
5143 }
5144 }
5145 }
5146
5147 /* Read a packet from the remote machine, with error checking, and
5148 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
5149 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
5150 rather than timing out; this is used (in synchronous mode) to wait
5151 for a target that is is executing user code to stop. */
5152 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
5153 don't have to change all the calls to getpkt to deal with the
5154 return value, because at the moment I don't know what the right
5155 thing to do it for those. */
5156 void
5157 getpkt (char **buf,
5158 long *sizeof_buf,
5159 int forever)
5160 {
5161 int timed_out;
5162
5163 timed_out = getpkt_sane (buf, sizeof_buf, forever);
5164 }
5165
5166
5167 /* Read a packet from the remote machine, with error checking, and
5168 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
5169 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
5170 rather than timing out; this is used (in synchronous mode) to wait
5171 for a target that is is executing user code to stop. If FOREVER ==
5172 0, this function is allowed to time out gracefully and return an
5173 indication of this to the caller. Otherwise return the number
5174 of bytes read. */
5175 static int
5176 getpkt_sane (char **buf, long *sizeof_buf, int forever)
5177 {
5178 struct remote_state *rs = get_remote_state ();
5179 int c;
5180 int tries;
5181 int timeout;
5182 int val;
5183
5184 /* We're reading a new response. Make sure we don't look at a
5185 previously cached response. */
5186 rs->cached_wait_status = 0;
5187
5188 strcpy (*buf, "timeout");
5189
5190 if (forever)
5191 {
5192 timeout = watchdog > 0 ? watchdog : -1;
5193 }
5194
5195 else
5196 timeout = remote_timeout;
5197
5198 #define MAX_TRIES 3
5199
5200 for (tries = 1; tries <= MAX_TRIES; tries++)
5201 {
5202 /* This can loop forever if the remote side sends us characters
5203 continuously, but if it pauses, we'll get a zero from
5204 readchar because of timeout. Then we'll count that as a
5205 retry. */
5206
5207 /* Note that we will only wait forever prior to the start of a
5208 packet. After that, we expect characters to arrive at a
5209 brisk pace. They should show up within remote_timeout
5210 intervals. */
5211
5212 do
5213 {
5214 c = readchar (timeout);
5215
5216 if (c == SERIAL_TIMEOUT)
5217 {
5218 if (forever) /* Watchdog went off? Kill the target. */
5219 {
5220 QUIT;
5221 target_mourn_inferior ();
5222 error (_("Watchdog timeout has expired. Target detached."));
5223 }
5224 if (remote_debug)
5225 fputs_filtered ("Timed out.\n", gdb_stdlog);
5226 goto retry;
5227 }
5228 }
5229 while (c != '$');
5230
5231 /* We've found the start of a packet, now collect the data. */
5232
5233 val = read_frame (buf, sizeof_buf);
5234
5235 if (val >= 0)
5236 {
5237 if (remote_debug)
5238 {
5239 fprintf_unfiltered (gdb_stdlog, "Packet received: ");
5240 fputstrn_unfiltered (*buf, val, 0, gdb_stdlog);
5241 fprintf_unfiltered (gdb_stdlog, "\n");
5242 }
5243 serial_write (remote_desc, "+", 1);
5244 return val;
5245 }
5246
5247 /* Try the whole thing again. */
5248 retry:
5249 serial_write (remote_desc, "-", 1);
5250 }
5251
5252 /* We have tried hard enough, and just can't receive the packet.
5253 Give up. */
5254
5255 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
5256 serial_write (remote_desc, "+", 1);
5257 return -1;
5258 }
5259 \f
5260 static void
5261 remote_kill (void)
5262 {
5263 /* For some mysterious reason, wait_for_inferior calls kill instead of
5264 mourn after it gets TARGET_WAITKIND_SIGNALLED. Work around it. */
5265 if (kill_kludge)
5266 {
5267 kill_kludge = 0;
5268 target_mourn_inferior ();
5269 return;
5270 }
5271
5272 /* Use catch_errors so the user can quit from gdb even when we aren't on
5273 speaking terms with the remote system. */
5274 catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
5275
5276 /* Don't wait for it to die. I'm not really sure it matters whether
5277 we do or not. For the existing stubs, kill is a noop. */
5278 target_mourn_inferior ();
5279 }
5280
5281 /* Async version of remote_kill. */
5282 static void
5283 remote_async_kill (void)
5284 {
5285 /* Unregister the file descriptor from the event loop. */
5286 if (target_is_async_p ())
5287 serial_async (remote_desc, NULL, 0);
5288
5289 /* For some mysterious reason, wait_for_inferior calls kill instead of
5290 mourn after it gets TARGET_WAITKIND_SIGNALLED. Work around it. */
5291 if (kill_kludge)
5292 {
5293 kill_kludge = 0;
5294 target_mourn_inferior ();
5295 return;
5296 }
5297
5298 /* Use catch_errors so the user can quit from gdb even when we
5299 aren't on speaking terms with the remote system. */
5300 catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
5301
5302 /* Don't wait for it to die. I'm not really sure it matters whether
5303 we do or not. For the existing stubs, kill is a noop. */
5304 target_mourn_inferior ();
5305 }
5306
5307 static void
5308 remote_mourn (void)
5309 {
5310 remote_mourn_1 (&remote_ops);
5311 }
5312
5313 static void
5314 remote_async_mourn (void)
5315 {
5316 remote_mourn_1 (&remote_async_ops);
5317 }
5318
5319 /* Worker function for remote_mourn. */
5320 static void
5321 remote_mourn_1 (struct target_ops *target)
5322 {
5323 unpush_target (target);
5324 generic_mourn_inferior ();
5325 }
5326
5327 static void
5328 extended_remote_mourn_1 (struct target_ops *target)
5329 {
5330 struct remote_state *rs = get_remote_state ();
5331
5332 /* Unlike "target remote", we do not want to unpush the target; then
5333 the next time the user says "run", we won't be connected. */
5334
5335 /* Call common code to mark the inferior as not running. */
5336 generic_mourn_inferior ();
5337
5338 /* Check whether the target is running now - some remote stubs
5339 automatically restart after kill. */
5340 putpkt ("?");
5341 getpkt (&rs->buf, &rs->buf_size, 0);
5342
5343 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
5344 {
5345 /* Assume that the target has been restarted. Set inferior_ptid
5346 so that bits of core GDB realizes there's something here, e.g.,
5347 so that the user can say "kill" again. */
5348 inferior_ptid = pid_to_ptid (MAGIC_NULL_PID);
5349 }
5350 else
5351 {
5352 /* Mark this (still pushed) target as not executable until we
5353 restart it. */
5354 target_mark_exited (target);
5355 }
5356 }
5357
5358 static void
5359 extended_remote_mourn (void)
5360 {
5361 extended_remote_mourn_1 (&extended_remote_ops);
5362 }
5363
5364 static void
5365 extended_async_remote_mourn (void)
5366 {
5367 extended_remote_mourn_1 (&extended_async_remote_ops);
5368 }
5369
5370 static int
5371 extended_remote_run (char *args)
5372 {
5373 struct remote_state *rs = get_remote_state ();
5374 char *p;
5375 int len;
5376
5377 /* If the user has disabled vRun support, or we have detected that
5378 support is not available, do not try it. */
5379 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
5380 return -1;
5381
5382 strcpy (rs->buf, "vRun;");
5383 len = strlen (rs->buf);
5384
5385 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
5386 error (_("Remote file name too long for run packet"));
5387 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
5388
5389 if (*args)
5390 {
5391 struct cleanup *back_to;
5392 int i;
5393 char **argv;
5394
5395 argv = buildargv (args);
5396 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
5397 for (i = 0; argv[i] != NULL; i++)
5398 {
5399 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
5400 error (_("Argument list too long for run packet"));
5401 rs->buf[len++] = ';';
5402 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
5403 }
5404 do_cleanups (back_to);
5405 }
5406
5407 rs->buf[len++] = '\0';
5408
5409 putpkt (rs->buf);
5410 getpkt (&rs->buf, &rs->buf_size, 0);
5411
5412 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
5413 {
5414 /* We have a wait response; we don't need it, though. All is well. */
5415 return 0;
5416 }
5417 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
5418 /* It wasn't disabled before, but it is now. */
5419 return -1;
5420 else
5421 {
5422 if (remote_exec_file[0] == '\0')
5423 error (_("Running the default executable on the remote target failed; "
5424 "try \"set remote exec-file\"?"));
5425 else
5426 error (_("Running \"%s\" on the remote target failed"),
5427 remote_exec_file);
5428 }
5429 }
5430
5431 /* In the extended protocol we want to be able to do things like
5432 "run" and have them basically work as expected. So we need
5433 a special create_inferior function. We support changing the
5434 executable file and the command line arguments, but not the
5435 environment. */
5436
5437 static void
5438 extended_remote_create_inferior_1 (char *exec_file, char *args,
5439 char **env, int from_tty,
5440 int async_p)
5441 {
5442 /* If running asynchronously, register the target file descriptor
5443 with the event loop. */
5444 if (async_p && target_can_async_p ())
5445 target_async (inferior_event_handler, 0);
5446
5447 /* Now restart the remote server. */
5448 if (extended_remote_run (args) == -1)
5449 {
5450 /* vRun was not supported. Fail if we need it to do what the
5451 user requested. */
5452 if (remote_exec_file[0])
5453 error (_("Remote target does not support \"set remote exec-file\""));
5454 if (args[0])
5455 error (_("Remote target does not support \"set args\" or run <ARGS>"));
5456
5457 /* Fall back to "R". */
5458 extended_remote_restart ();
5459 }
5460
5461 /* Now mark the inferior as running before we do anything else. */
5462 attach_flag = 0;
5463 inferior_ptid = pid_to_ptid (MAGIC_NULL_PID);
5464 if (async_p)
5465 target_mark_running (&extended_async_remote_ops);
5466 else
5467 target_mark_running (&extended_remote_ops);
5468
5469 /* Get updated offsets, if the stub uses qOffsets. */
5470 get_offsets ();
5471
5472 /* Clean up from the last time we were running. */
5473 init_thread_list ();
5474 init_wait_for_inferior ();
5475 }
5476
5477 static void
5478 extended_remote_create_inferior (char *exec_file, char *args,
5479 char **env, int from_tty)
5480 {
5481 extended_remote_create_inferior_1 (exec_file, args, env, from_tty, 0);
5482 }
5483
5484 static void
5485 extended_remote_async_create_inferior (char *exec_file, char *args,
5486 char **env, int from_tty)
5487 {
5488 extended_remote_create_inferior_1 (exec_file, args, env, from_tty, 1);
5489 }
5490 \f
5491
5492 /* Insert a breakpoint. On targets that have software breakpoint
5493 support, we ask the remote target to do the work; on targets
5494 which don't, we insert a traditional memory breakpoint. */
5495
5496 static int
5497 remote_insert_breakpoint (struct bp_target_info *bp_tgt)
5498 {
5499 CORE_ADDR addr = bp_tgt->placed_address;
5500 struct remote_state *rs = get_remote_state ();
5501
5502 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
5503 If it succeeds, then set the support to PACKET_ENABLE. If it
5504 fails, and the user has explicitly requested the Z support then
5505 report an error, otherwise, mark it disabled and go on. */
5506
5507 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
5508 {
5509 char *p = rs->buf;
5510
5511 *(p++) = 'Z';
5512 *(p++) = '0';
5513 *(p++) = ',';
5514 gdbarch_breakpoint_from_pc
5515 (current_gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
5516 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
5517 p += hexnumstr (p, addr);
5518 sprintf (p, ",%d", bp_tgt->placed_size);
5519
5520 putpkt (rs->buf);
5521 getpkt (&rs->buf, &rs->buf_size, 0);
5522
5523 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
5524 {
5525 case PACKET_ERROR:
5526 return -1;
5527 case PACKET_OK:
5528 return 0;
5529 case PACKET_UNKNOWN:
5530 break;
5531 }
5532 }
5533
5534 return memory_insert_breakpoint (bp_tgt);
5535 }
5536
5537 static int
5538 remote_remove_breakpoint (struct bp_target_info *bp_tgt)
5539 {
5540 CORE_ADDR addr = bp_tgt->placed_address;
5541 struct remote_state *rs = get_remote_state ();
5542 int bp_size;
5543
5544 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
5545 {
5546 char *p = rs->buf;
5547
5548 *(p++) = 'z';
5549 *(p++) = '0';
5550 *(p++) = ',';
5551
5552 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
5553 p += hexnumstr (p, addr);
5554 sprintf (p, ",%d", bp_tgt->placed_size);
5555
5556 putpkt (rs->buf);
5557 getpkt (&rs->buf, &rs->buf_size, 0);
5558
5559 return (rs->buf[0] == 'E');
5560 }
5561
5562 return memory_remove_breakpoint (bp_tgt);
5563 }
5564
5565 static int
5566 watchpoint_to_Z_packet (int type)
5567 {
5568 switch (type)
5569 {
5570 case hw_write:
5571 return Z_PACKET_WRITE_WP;
5572 break;
5573 case hw_read:
5574 return Z_PACKET_READ_WP;
5575 break;
5576 case hw_access:
5577 return Z_PACKET_ACCESS_WP;
5578 break;
5579 default:
5580 internal_error (__FILE__, __LINE__,
5581 _("hw_bp_to_z: bad watchpoint type %d"), type);
5582 }
5583 }
5584
5585 static int
5586 remote_insert_watchpoint (CORE_ADDR addr, int len, int type)
5587 {
5588 struct remote_state *rs = get_remote_state ();
5589 char *p;
5590 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
5591
5592 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
5593 return -1;
5594
5595 sprintf (rs->buf, "Z%x,", packet);
5596 p = strchr (rs->buf, '\0');
5597 addr = remote_address_masked (addr);
5598 p += hexnumstr (p, (ULONGEST) addr);
5599 sprintf (p, ",%x", len);
5600
5601 putpkt (rs->buf);
5602 getpkt (&rs->buf, &rs->buf_size, 0);
5603
5604 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
5605 {
5606 case PACKET_ERROR:
5607 case PACKET_UNKNOWN:
5608 return -1;
5609 case PACKET_OK:
5610 return 0;
5611 }
5612 internal_error (__FILE__, __LINE__,
5613 _("remote_insert_watchpoint: reached end of function"));
5614 }
5615
5616
5617 static int
5618 remote_remove_watchpoint (CORE_ADDR addr, int len, int type)
5619 {
5620 struct remote_state *rs = get_remote_state ();
5621 char *p;
5622 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
5623
5624 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
5625 return -1;
5626
5627 sprintf (rs->buf, "z%x,", packet);
5628 p = strchr (rs->buf, '\0');
5629 addr = remote_address_masked (addr);
5630 p += hexnumstr (p, (ULONGEST) addr);
5631 sprintf (p, ",%x", len);
5632 putpkt (rs->buf);
5633 getpkt (&rs->buf, &rs->buf_size, 0);
5634
5635 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
5636 {
5637 case PACKET_ERROR:
5638 case PACKET_UNKNOWN:
5639 return -1;
5640 case PACKET_OK:
5641 return 0;
5642 }
5643 internal_error (__FILE__, __LINE__,
5644 _("remote_remove_watchpoint: reached end of function"));
5645 }
5646
5647
5648 int remote_hw_watchpoint_limit = -1;
5649 int remote_hw_breakpoint_limit = -1;
5650
5651 static int
5652 remote_check_watch_resources (int type, int cnt, int ot)
5653 {
5654 if (type == bp_hardware_breakpoint)
5655 {
5656 if (remote_hw_breakpoint_limit == 0)
5657 return 0;
5658 else if (remote_hw_breakpoint_limit < 0)
5659 return 1;
5660 else if (cnt <= remote_hw_breakpoint_limit)
5661 return 1;
5662 }
5663 else
5664 {
5665 if (remote_hw_watchpoint_limit == 0)
5666 return 0;
5667 else if (remote_hw_watchpoint_limit < 0)
5668 return 1;
5669 else if (ot)
5670 return -1;
5671 else if (cnt <= remote_hw_watchpoint_limit)
5672 return 1;
5673 }
5674 return -1;
5675 }
5676
5677 static int
5678 remote_stopped_by_watchpoint (void)
5679 {
5680 return remote_stopped_by_watchpoint_p;
5681 }
5682
5683 static int
5684 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
5685 {
5686 int rc = 0;
5687 if (remote_stopped_by_watchpoint ())
5688 {
5689 *addr_p = remote_watch_data_address;
5690 rc = 1;
5691 }
5692
5693 return rc;
5694 }
5695
5696
5697 static int
5698 remote_insert_hw_breakpoint (struct bp_target_info *bp_tgt)
5699 {
5700 CORE_ADDR addr;
5701 struct remote_state *rs = get_remote_state ();
5702 char *p = rs->buf;
5703
5704 /* The length field should be set to the size of a breakpoint
5705 instruction, even though we aren't inserting one ourselves. */
5706
5707 gdbarch_breakpoint_from_pc
5708 (current_gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
5709
5710 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5711 return -1;
5712
5713 *(p++) = 'Z';
5714 *(p++) = '1';
5715 *(p++) = ',';
5716
5717 addr = remote_address_masked (bp_tgt->placed_address);
5718 p += hexnumstr (p, (ULONGEST) addr);
5719 sprintf (p, ",%x", bp_tgt->placed_size);
5720
5721 putpkt (rs->buf);
5722 getpkt (&rs->buf, &rs->buf_size, 0);
5723
5724 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
5725 {
5726 case PACKET_ERROR:
5727 case PACKET_UNKNOWN:
5728 return -1;
5729 case PACKET_OK:
5730 return 0;
5731 }
5732 internal_error (__FILE__, __LINE__,
5733 _("remote_insert_hw_breakpoint: reached end of function"));
5734 }
5735
5736
5737 static int
5738 remote_remove_hw_breakpoint (struct bp_target_info *bp_tgt)
5739 {
5740 CORE_ADDR addr;
5741 struct remote_state *rs = get_remote_state ();
5742 char *p = rs->buf;
5743
5744 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5745 return -1;
5746
5747 *(p++) = 'z';
5748 *(p++) = '1';
5749 *(p++) = ',';
5750
5751 addr = remote_address_masked (bp_tgt->placed_address);
5752 p += hexnumstr (p, (ULONGEST) addr);
5753 sprintf (p, ",%x", bp_tgt->placed_size);
5754
5755 putpkt (rs->buf);
5756 getpkt (&rs->buf, &rs->buf_size, 0);
5757
5758 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
5759 {
5760 case PACKET_ERROR:
5761 case PACKET_UNKNOWN:
5762 return -1;
5763 case PACKET_OK:
5764 return 0;
5765 }
5766 internal_error (__FILE__, __LINE__,
5767 _("remote_remove_hw_breakpoint: reached end of function"));
5768 }
5769
5770 /* Some targets are only capable of doing downloads, and afterwards
5771 they switch to the remote serial protocol. This function provides
5772 a clean way to get from the download target to the remote target.
5773 It's basically just a wrapper so that we don't have to expose any
5774 of the internal workings of remote.c.
5775
5776 Prior to calling this routine, you should shutdown the current
5777 target code, else you will get the "A program is being debugged
5778 already..." message. Usually a call to pop_target() suffices. */
5779
5780 void
5781 push_remote_target (char *name, int from_tty)
5782 {
5783 printf_filtered (_("Switching to remote protocol\n"));
5784 remote_open (name, from_tty);
5785 }
5786
5787 /* Table used by the crc32 function to calcuate the checksum. */
5788
5789 static unsigned long crc32_table[256] =
5790 {0, 0};
5791
5792 static unsigned long
5793 crc32 (unsigned char *buf, int len, unsigned int crc)
5794 {
5795 if (!crc32_table[1])
5796 {
5797 /* Initialize the CRC table and the decoding table. */
5798 int i, j;
5799 unsigned int c;
5800
5801 for (i = 0; i < 256; i++)
5802 {
5803 for (c = i << 24, j = 8; j > 0; --j)
5804 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
5805 crc32_table[i] = c;
5806 }
5807 }
5808
5809 while (len--)
5810 {
5811 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
5812 buf++;
5813 }
5814 return crc;
5815 }
5816
5817 /* compare-sections command
5818
5819 With no arguments, compares each loadable section in the exec bfd
5820 with the same memory range on the target, and reports mismatches.
5821 Useful for verifying the image on the target against the exec file.
5822 Depends on the target understanding the new "qCRC:" request. */
5823
5824 /* FIXME: cagney/1999-10-26: This command should be broken down into a
5825 target method (target verify memory) and generic version of the
5826 actual command. This will allow other high-level code (especially
5827 generic_load()) to make use of this target functionality. */
5828
5829 static void
5830 compare_sections_command (char *args, int from_tty)
5831 {
5832 struct remote_state *rs = get_remote_state ();
5833 asection *s;
5834 unsigned long host_crc, target_crc;
5835 extern bfd *exec_bfd;
5836 struct cleanup *old_chain;
5837 char *tmp;
5838 char *sectdata;
5839 const char *sectname;
5840 bfd_size_type size;
5841 bfd_vma lma;
5842 int matched = 0;
5843 int mismatched = 0;
5844
5845 if (!exec_bfd)
5846 error (_("command cannot be used without an exec file"));
5847 if (!current_target.to_shortname ||
5848 strcmp (current_target.to_shortname, "remote") != 0)
5849 error (_("command can only be used with remote target"));
5850
5851 for (s = exec_bfd->sections; s; s = s->next)
5852 {
5853 if (!(s->flags & SEC_LOAD))
5854 continue; /* skip non-loadable section */
5855
5856 size = bfd_get_section_size (s);
5857 if (size == 0)
5858 continue; /* skip zero-length section */
5859
5860 sectname = bfd_get_section_name (exec_bfd, s);
5861 if (args && strcmp (args, sectname) != 0)
5862 continue; /* not the section selected by user */
5863
5864 matched = 1; /* do this section */
5865 lma = s->lma;
5866 /* FIXME: assumes lma can fit into long. */
5867 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
5868 (long) lma, (long) size);
5869 putpkt (rs->buf);
5870
5871 /* Be clever; compute the host_crc before waiting for target
5872 reply. */
5873 sectdata = xmalloc (size);
5874 old_chain = make_cleanup (xfree, sectdata);
5875 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
5876 host_crc = crc32 ((unsigned char *) sectdata, size, 0xffffffff);
5877
5878 getpkt (&rs->buf, &rs->buf_size, 0);
5879 if (rs->buf[0] == 'E')
5880 error (_("target memory fault, section %s, range 0x%s -- 0x%s"),
5881 sectname, paddr (lma), paddr (lma + size));
5882 if (rs->buf[0] != 'C')
5883 error (_("remote target does not support this operation"));
5884
5885 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
5886 target_crc = target_crc * 16 + fromhex (*tmp);
5887
5888 printf_filtered ("Section %s, range 0x%s -- 0x%s: ",
5889 sectname, paddr (lma), paddr (lma + size));
5890 if (host_crc == target_crc)
5891 printf_filtered ("matched.\n");
5892 else
5893 {
5894 printf_filtered ("MIS-MATCHED!\n");
5895 mismatched++;
5896 }
5897
5898 do_cleanups (old_chain);
5899 }
5900 if (mismatched > 0)
5901 warning (_("One or more sections of the remote executable does not match\n\
5902 the loaded file\n"));
5903 if (args && !matched)
5904 printf_filtered (_("No loaded section named '%s'.\n"), args);
5905 }
5906
5907 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
5908 into remote target. The number of bytes written to the remote
5909 target is returned, or -1 for error. */
5910
5911 static LONGEST
5912 remote_write_qxfer (struct target_ops *ops, const char *object_name,
5913 const char *annex, const gdb_byte *writebuf,
5914 ULONGEST offset, LONGEST len,
5915 struct packet_config *packet)
5916 {
5917 int i, buf_len;
5918 ULONGEST n;
5919 gdb_byte *wbuf;
5920 struct remote_state *rs = get_remote_state ();
5921 int max_size = get_memory_write_packet_size ();
5922
5923 if (packet->support == PACKET_DISABLE)
5924 return -1;
5925
5926 /* Insert header. */
5927 i = snprintf (rs->buf, max_size,
5928 "qXfer:%s:write:%s:%s:",
5929 object_name, annex ? annex : "",
5930 phex_nz (offset, sizeof offset));
5931 max_size -= (i + 1);
5932
5933 /* Escape as much data as fits into rs->buf. */
5934 buf_len = remote_escape_output
5935 (writebuf, len, (rs->buf + i), &max_size, max_size);
5936
5937 if (putpkt_binary (rs->buf, i + buf_len) < 0
5938 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
5939 || packet_ok (rs->buf, packet) != PACKET_OK)
5940 return -1;
5941
5942 unpack_varlen_hex (rs->buf, &n);
5943 return n;
5944 }
5945
5946 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
5947 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
5948 number of bytes read is returned, or 0 for EOF, or -1 for error.
5949 The number of bytes read may be less than LEN without indicating an
5950 EOF. PACKET is checked and updated to indicate whether the remote
5951 target supports this object. */
5952
5953 static LONGEST
5954 remote_read_qxfer (struct target_ops *ops, const char *object_name,
5955 const char *annex,
5956 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
5957 struct packet_config *packet)
5958 {
5959 static char *finished_object;
5960 static char *finished_annex;
5961 static ULONGEST finished_offset;
5962
5963 struct remote_state *rs = get_remote_state ();
5964 unsigned int total = 0;
5965 LONGEST i, n, packet_len;
5966
5967 if (packet->support == PACKET_DISABLE)
5968 return -1;
5969
5970 /* Check whether we've cached an end-of-object packet that matches
5971 this request. */
5972 if (finished_object)
5973 {
5974 if (strcmp (object_name, finished_object) == 0
5975 && strcmp (annex ? annex : "", finished_annex) == 0
5976 && offset == finished_offset)
5977 return 0;
5978
5979 /* Otherwise, we're now reading something different. Discard
5980 the cache. */
5981 xfree (finished_object);
5982 xfree (finished_annex);
5983 finished_object = NULL;
5984 finished_annex = NULL;
5985 }
5986
5987 /* Request only enough to fit in a single packet. The actual data
5988 may not, since we don't know how much of it will need to be escaped;
5989 the target is free to respond with slightly less data. We subtract
5990 five to account for the response type and the protocol frame. */
5991 n = min (get_remote_packet_size () - 5, len);
5992 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
5993 object_name, annex ? annex : "",
5994 phex_nz (offset, sizeof offset),
5995 phex_nz (n, sizeof n));
5996 i = putpkt (rs->buf);
5997 if (i < 0)
5998 return -1;
5999
6000 rs->buf[0] = '\0';
6001 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
6002 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
6003 return -1;
6004
6005 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
6006 error (_("Unknown remote qXfer reply: %s"), rs->buf);
6007
6008 /* 'm' means there is (or at least might be) more data after this
6009 batch. That does not make sense unless there's at least one byte
6010 of data in this reply. */
6011 if (rs->buf[0] == 'm' && packet_len == 1)
6012 error (_("Remote qXfer reply contained no data."));
6013
6014 /* Got some data. */
6015 i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
6016
6017 /* 'l' is an EOF marker, possibly including a final block of data,
6018 or possibly empty. If we have the final block of a non-empty
6019 object, record this fact to bypass a subsequent partial read. */
6020 if (rs->buf[0] == 'l' && offset + i > 0)
6021 {
6022 finished_object = xstrdup (object_name);
6023 finished_annex = xstrdup (annex ? annex : "");
6024 finished_offset = offset + i;
6025 }
6026
6027 return i;
6028 }
6029
6030 static LONGEST
6031 remote_xfer_partial (struct target_ops *ops, enum target_object object,
6032 const char *annex, gdb_byte *readbuf,
6033 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
6034 {
6035 struct remote_state *rs = get_remote_state ();
6036 int i;
6037 char *p2;
6038 char query_type;
6039
6040 /* Handle memory using the standard memory routines. */
6041 if (object == TARGET_OBJECT_MEMORY)
6042 {
6043 int xfered;
6044 errno = 0;
6045
6046 /* If the remote target is connected but not running, we should
6047 pass this request down to a lower stratum (e.g. the executable
6048 file). */
6049 if (!target_has_execution)
6050 return 0;
6051
6052 if (writebuf != NULL)
6053 xfered = remote_write_bytes (offset, writebuf, len);
6054 else
6055 xfered = remote_read_bytes (offset, readbuf, len);
6056
6057 if (xfered > 0)
6058 return xfered;
6059 else if (xfered == 0 && errno == 0)
6060 return 0;
6061 else
6062 return -1;
6063 }
6064
6065 /* Handle SPU memory using qxfer packets. */
6066 if (object == TARGET_OBJECT_SPU)
6067 {
6068 if (readbuf)
6069 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
6070 &remote_protocol_packets
6071 [PACKET_qXfer_spu_read]);
6072 else
6073 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
6074 &remote_protocol_packets
6075 [PACKET_qXfer_spu_write]);
6076 }
6077
6078 /* Only handle flash writes. */
6079 if (writebuf != NULL)
6080 {
6081 LONGEST xfered;
6082
6083 switch (object)
6084 {
6085 case TARGET_OBJECT_FLASH:
6086 xfered = remote_flash_write (ops, offset, len, writebuf);
6087
6088 if (xfered > 0)
6089 return xfered;
6090 else if (xfered == 0 && errno == 0)
6091 return 0;
6092 else
6093 return -1;
6094
6095 default:
6096 return -1;
6097 }
6098 }
6099
6100 /* Map pre-existing objects onto letters. DO NOT do this for new
6101 objects!!! Instead specify new query packets. */
6102 switch (object)
6103 {
6104 case TARGET_OBJECT_AVR:
6105 query_type = 'R';
6106 break;
6107
6108 case TARGET_OBJECT_AUXV:
6109 gdb_assert (annex == NULL);
6110 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
6111 &remote_protocol_packets[PACKET_qXfer_auxv]);
6112
6113 case TARGET_OBJECT_AVAILABLE_FEATURES:
6114 return remote_read_qxfer
6115 (ops, "features", annex, readbuf, offset, len,
6116 &remote_protocol_packets[PACKET_qXfer_features]);
6117
6118 case TARGET_OBJECT_LIBRARIES:
6119 return remote_read_qxfer
6120 (ops, "libraries", annex, readbuf, offset, len,
6121 &remote_protocol_packets[PACKET_qXfer_libraries]);
6122
6123 case TARGET_OBJECT_MEMORY_MAP:
6124 gdb_assert (annex == NULL);
6125 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
6126 &remote_protocol_packets[PACKET_qXfer_memory_map]);
6127
6128 default:
6129 return -1;
6130 }
6131
6132 /* Note: a zero OFFSET and LEN can be used to query the minimum
6133 buffer size. */
6134 if (offset == 0 && len == 0)
6135 return (get_remote_packet_size ());
6136 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
6137 large enough let the caller deal with it. */
6138 if (len < get_remote_packet_size ())
6139 return -1;
6140 len = get_remote_packet_size ();
6141
6142 /* Except for querying the minimum buffer size, target must be open. */
6143 if (!remote_desc)
6144 error (_("remote query is only available after target open"));
6145
6146 gdb_assert (annex != NULL);
6147 gdb_assert (readbuf != NULL);
6148
6149 p2 = rs->buf;
6150 *p2++ = 'q';
6151 *p2++ = query_type;
6152
6153 /* We used one buffer char for the remote protocol q command and
6154 another for the query type. As the remote protocol encapsulation
6155 uses 4 chars plus one extra in case we are debugging
6156 (remote_debug), we have PBUFZIZ - 7 left to pack the query
6157 string. */
6158 i = 0;
6159 while (annex[i] && (i < (get_remote_packet_size () - 8)))
6160 {
6161 /* Bad caller may have sent forbidden characters. */
6162 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
6163 *p2++ = annex[i];
6164 i++;
6165 }
6166 *p2 = '\0';
6167 gdb_assert (annex[i] == '\0');
6168
6169 i = putpkt (rs->buf);
6170 if (i < 0)
6171 return i;
6172
6173 getpkt (&rs->buf, &rs->buf_size, 0);
6174 strcpy ((char *) readbuf, rs->buf);
6175
6176 return strlen ((char *) readbuf);
6177 }
6178
6179 static void
6180 remote_rcmd (char *command,
6181 struct ui_file *outbuf)
6182 {
6183 struct remote_state *rs = get_remote_state ();
6184 char *p = rs->buf;
6185
6186 if (!remote_desc)
6187 error (_("remote rcmd is only available after target open"));
6188
6189 /* Send a NULL command across as an empty command. */
6190 if (command == NULL)
6191 command = "";
6192
6193 /* The query prefix. */
6194 strcpy (rs->buf, "qRcmd,");
6195 p = strchr (rs->buf, '\0');
6196
6197 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/) > get_remote_packet_size ())
6198 error (_("\"monitor\" command ``%s'' is too long."), command);
6199
6200 /* Encode the actual command. */
6201 bin2hex ((gdb_byte *) command, p, 0);
6202
6203 if (putpkt (rs->buf) < 0)
6204 error (_("Communication problem with target."));
6205
6206 /* get/display the response */
6207 while (1)
6208 {
6209 char *buf;
6210
6211 /* XXX - see also tracepoint.c:remote_get_noisy_reply(). */
6212 rs->buf[0] = '\0';
6213 getpkt (&rs->buf, &rs->buf_size, 0);
6214 buf = rs->buf;
6215 if (buf[0] == '\0')
6216 error (_("Target does not support this command."));
6217 if (buf[0] == 'O' && buf[1] != 'K')
6218 {
6219 remote_console_output (buf + 1); /* 'O' message from stub. */
6220 continue;
6221 }
6222 if (strcmp (buf, "OK") == 0)
6223 break;
6224 if (strlen (buf) == 3 && buf[0] == 'E'
6225 && isdigit (buf[1]) && isdigit (buf[2]))
6226 {
6227 error (_("Protocol error with Rcmd"));
6228 }
6229 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
6230 {
6231 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
6232 fputc_unfiltered (c, outbuf);
6233 }
6234 break;
6235 }
6236 }
6237
6238 static VEC(mem_region_s) *
6239 remote_memory_map (struct target_ops *ops)
6240 {
6241 VEC(mem_region_s) *result = NULL;
6242 char *text = target_read_stralloc (&current_target,
6243 TARGET_OBJECT_MEMORY_MAP, NULL);
6244
6245 if (text)
6246 {
6247 struct cleanup *back_to = make_cleanup (xfree, text);
6248 result = parse_memory_map (text);
6249 do_cleanups (back_to);
6250 }
6251
6252 return result;
6253 }
6254
6255 static void
6256 packet_command (char *args, int from_tty)
6257 {
6258 struct remote_state *rs = get_remote_state ();
6259
6260 if (!remote_desc)
6261 error (_("command can only be used with remote target"));
6262
6263 if (!args)
6264 error (_("remote-packet command requires packet text as argument"));
6265
6266 puts_filtered ("sending: ");
6267 print_packet (args);
6268 puts_filtered ("\n");
6269 putpkt (args);
6270
6271 getpkt (&rs->buf, &rs->buf_size, 0);
6272 puts_filtered ("received: ");
6273 print_packet (rs->buf);
6274 puts_filtered ("\n");
6275 }
6276
6277 #if 0
6278 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
6279
6280 static void display_thread_info (struct gdb_ext_thread_info *info);
6281
6282 static void threadset_test_cmd (char *cmd, int tty);
6283
6284 static void threadalive_test (char *cmd, int tty);
6285
6286 static void threadlist_test_cmd (char *cmd, int tty);
6287
6288 int get_and_display_threadinfo (threadref *ref);
6289
6290 static void threadinfo_test_cmd (char *cmd, int tty);
6291
6292 static int thread_display_step (threadref *ref, void *context);
6293
6294 static void threadlist_update_test_cmd (char *cmd, int tty);
6295
6296 static void init_remote_threadtests (void);
6297
6298 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
6299
6300 static void
6301 threadset_test_cmd (char *cmd, int tty)
6302 {
6303 int sample_thread = SAMPLE_THREAD;
6304
6305 printf_filtered (_("Remote threadset test\n"));
6306 set_thread (sample_thread, 1);
6307 }
6308
6309
6310 static void
6311 threadalive_test (char *cmd, int tty)
6312 {
6313 int sample_thread = SAMPLE_THREAD;
6314
6315 if (remote_thread_alive (pid_to_ptid (sample_thread)))
6316 printf_filtered ("PASS: Thread alive test\n");
6317 else
6318 printf_filtered ("FAIL: Thread alive test\n");
6319 }
6320
6321 void output_threadid (char *title, threadref *ref);
6322
6323 void
6324 output_threadid (char *title, threadref *ref)
6325 {
6326 char hexid[20];
6327
6328 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
6329 hexid[16] = 0;
6330 printf_filtered ("%s %s\n", title, (&hexid[0]));
6331 }
6332
6333 static void
6334 threadlist_test_cmd (char *cmd, int tty)
6335 {
6336 int startflag = 1;
6337 threadref nextthread;
6338 int done, result_count;
6339 threadref threadlist[3];
6340
6341 printf_filtered ("Remote Threadlist test\n");
6342 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
6343 &result_count, &threadlist[0]))
6344 printf_filtered ("FAIL: threadlist test\n");
6345 else
6346 {
6347 threadref *scan = threadlist;
6348 threadref *limit = scan + result_count;
6349
6350 while (scan < limit)
6351 output_threadid (" thread ", scan++);
6352 }
6353 }
6354
6355 void
6356 display_thread_info (struct gdb_ext_thread_info *info)
6357 {
6358 output_threadid ("Threadid: ", &info->threadid);
6359 printf_filtered ("Name: %s\n ", info->shortname);
6360 printf_filtered ("State: %s\n", info->display);
6361 printf_filtered ("other: %s\n\n", info->more_display);
6362 }
6363
6364 int
6365 get_and_display_threadinfo (threadref *ref)
6366 {
6367 int result;
6368 int set;
6369 struct gdb_ext_thread_info threadinfo;
6370
6371 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
6372 | TAG_MOREDISPLAY | TAG_DISPLAY;
6373 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
6374 display_thread_info (&threadinfo);
6375 return result;
6376 }
6377
6378 static void
6379 threadinfo_test_cmd (char *cmd, int tty)
6380 {
6381 int athread = SAMPLE_THREAD;
6382 threadref thread;
6383 int set;
6384
6385 int_to_threadref (&thread, athread);
6386 printf_filtered ("Remote Threadinfo test\n");
6387 if (!get_and_display_threadinfo (&thread))
6388 printf_filtered ("FAIL cannot get thread info\n");
6389 }
6390
6391 static int
6392 thread_display_step (threadref *ref, void *context)
6393 {
6394 /* output_threadid(" threadstep ",ref); *//* simple test */
6395 return get_and_display_threadinfo (ref);
6396 }
6397
6398 static void
6399 threadlist_update_test_cmd (char *cmd, int tty)
6400 {
6401 printf_filtered ("Remote Threadlist update test\n");
6402 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
6403 }
6404
6405 static void
6406 init_remote_threadtests (void)
6407 {
6408 add_com ("tlist", class_obscure, threadlist_test_cmd, _("\
6409 Fetch and print the remote list of thread identifiers, one pkt only"));
6410 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
6411 _("Fetch and display info about one thread"));
6412 add_com ("tset", class_obscure, threadset_test_cmd,
6413 _("Test setting to a different thread"));
6414 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
6415 _("Iterate through updating all remote thread info"));
6416 add_com ("talive", class_obscure, threadalive_test,
6417 _(" Remote thread alive test "));
6418 }
6419
6420 #endif /* 0 */
6421
6422 /* Convert a thread ID to a string. Returns the string in a static
6423 buffer. */
6424
6425 static char *
6426 remote_pid_to_str (ptid_t ptid)
6427 {
6428 static char buf[32];
6429
6430 xsnprintf (buf, sizeof buf, "Thread %d", ptid_get_pid (ptid));
6431 return buf;
6432 }
6433
6434 /* Get the address of the thread local variable in OBJFILE which is
6435 stored at OFFSET within the thread local storage for thread PTID. */
6436
6437 static CORE_ADDR
6438 remote_get_thread_local_address (ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
6439 {
6440 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
6441 {
6442 struct remote_state *rs = get_remote_state ();
6443 char *p = rs->buf;
6444 enum packet_result result;
6445
6446 strcpy (p, "qGetTLSAddr:");
6447 p += strlen (p);
6448 p += hexnumstr (p, PIDGET (ptid));
6449 *p++ = ',';
6450 p += hexnumstr (p, offset);
6451 *p++ = ',';
6452 p += hexnumstr (p, lm);
6453 *p++ = '\0';
6454
6455 putpkt (rs->buf);
6456 getpkt (&rs->buf, &rs->buf_size, 0);
6457 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_qGetTLSAddr]);
6458 if (result == PACKET_OK)
6459 {
6460 ULONGEST result;
6461
6462 unpack_varlen_hex (rs->buf, &result);
6463 return result;
6464 }
6465 else if (result == PACKET_UNKNOWN)
6466 throw_error (TLS_GENERIC_ERROR,
6467 _("Remote target doesn't support qGetTLSAddr packet"));
6468 else
6469 throw_error (TLS_GENERIC_ERROR,
6470 _("Remote target failed to process qGetTLSAddr request"));
6471 }
6472 else
6473 throw_error (TLS_GENERIC_ERROR,
6474 _("TLS not supported or disabled on this target"));
6475 /* Not reached. */
6476 return 0;
6477 }
6478
6479 /* Support for inferring a target description based on the current
6480 architecture and the size of a 'g' packet. While the 'g' packet
6481 can have any size (since optional registers can be left off the
6482 end), some sizes are easily recognizable given knowledge of the
6483 approximate architecture. */
6484
6485 struct remote_g_packet_guess
6486 {
6487 int bytes;
6488 const struct target_desc *tdesc;
6489 };
6490 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
6491 DEF_VEC_O(remote_g_packet_guess_s);
6492
6493 struct remote_g_packet_data
6494 {
6495 VEC(remote_g_packet_guess_s) *guesses;
6496 };
6497
6498 static struct gdbarch_data *remote_g_packet_data_handle;
6499
6500 static void *
6501 remote_g_packet_data_init (struct obstack *obstack)
6502 {
6503 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
6504 }
6505
6506 void
6507 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
6508 const struct target_desc *tdesc)
6509 {
6510 struct remote_g_packet_data *data
6511 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
6512 struct remote_g_packet_guess new_guess, *guess;
6513 int ix;
6514
6515 gdb_assert (tdesc != NULL);
6516
6517 for (ix = 0;
6518 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
6519 ix++)
6520 if (guess->bytes == bytes)
6521 internal_error (__FILE__, __LINE__,
6522 "Duplicate g packet description added for size %d",
6523 bytes);
6524
6525 new_guess.bytes = bytes;
6526 new_guess.tdesc = tdesc;
6527 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
6528 }
6529
6530 static const struct target_desc *
6531 remote_read_description (struct target_ops *target)
6532 {
6533 struct remote_g_packet_data *data
6534 = gdbarch_data (current_gdbarch, remote_g_packet_data_handle);
6535
6536 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
6537 {
6538 struct remote_g_packet_guess *guess;
6539 int ix;
6540 int bytes = send_g_packet ();
6541
6542 for (ix = 0;
6543 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
6544 ix++)
6545 if (guess->bytes == bytes)
6546 return guess->tdesc;
6547
6548 /* We discard the g packet. A minor optimization would be to
6549 hold on to it, and fill the register cache once we have selected
6550 an architecture, but it's too tricky to do safely. */
6551 }
6552
6553 return NULL;
6554 }
6555
6556 /* Remote file transfer support. This is host-initiated I/O, not
6557 target-initiated; for target-initiated, see remote-fileio.c. */
6558
6559 /* If *LEFT is at least the length of STRING, copy STRING to
6560 *BUFFER, update *BUFFER to point to the new end of the buffer, and
6561 decrease *LEFT. Otherwise raise an error. */
6562
6563 static void
6564 remote_buffer_add_string (char **buffer, int *left, char *string)
6565 {
6566 int len = strlen (string);
6567
6568 if (len > *left)
6569 error (_("Packet too long for target."));
6570
6571 memcpy (*buffer, string, len);
6572 *buffer += len;
6573 *left -= len;
6574
6575 /* NUL-terminate the buffer as a convenience, if there is
6576 room. */
6577 if (*left)
6578 **buffer = '\0';
6579 }
6580
6581 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
6582 *BUFFER, update *BUFFER to point to the new end of the buffer, and
6583 decrease *LEFT. Otherwise raise an error. */
6584
6585 static void
6586 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
6587 int len)
6588 {
6589 if (2 * len > *left)
6590 error (_("Packet too long for target."));
6591
6592 bin2hex (bytes, *buffer, len);
6593 *buffer += 2 * len;
6594 *left -= 2 * len;
6595
6596 /* NUL-terminate the buffer as a convenience, if there is
6597 room. */
6598 if (*left)
6599 **buffer = '\0';
6600 }
6601
6602 /* If *LEFT is large enough, convert VALUE to hex and add it to
6603 *BUFFER, update *BUFFER to point to the new end of the buffer, and
6604 decrease *LEFT. Otherwise raise an error. */
6605
6606 static void
6607 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
6608 {
6609 int len = hexnumlen (value);
6610
6611 if (len > *left)
6612 error (_("Packet too long for target."));
6613
6614 hexnumstr (*buffer, value);
6615 *buffer += len;
6616 *left -= len;
6617
6618 /* NUL-terminate the buffer as a convenience, if there is
6619 room. */
6620 if (*left)
6621 **buffer = '\0';
6622 }
6623
6624 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
6625 value, *REMOTE_ERRNO to the remote error number or zero if none
6626 was included, and *ATTACHMENT to point to the start of the annex
6627 if any. The length of the packet isn't needed here; there may
6628 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
6629
6630 Return 0 if the packet could be parsed, -1 if it could not. If
6631 -1 is returned, the other variables may not be initialized. */
6632
6633 static int
6634 remote_hostio_parse_result (char *buffer, int *retcode,
6635 int *remote_errno, char **attachment)
6636 {
6637 char *p, *p2;
6638
6639 *remote_errno = 0;
6640 *attachment = NULL;
6641
6642 if (buffer[0] != 'F')
6643 return -1;
6644
6645 errno = 0;
6646 *retcode = strtol (&buffer[1], &p, 16);
6647 if (errno != 0 || p == &buffer[1])
6648 return -1;
6649
6650 /* Check for ",errno". */
6651 if (*p == ',')
6652 {
6653 errno = 0;
6654 *remote_errno = strtol (p + 1, &p2, 16);
6655 if (errno != 0 || p + 1 == p2)
6656 return -1;
6657 p = p2;
6658 }
6659
6660 /* Check for ";attachment". If there is no attachment, the
6661 packet should end here. */
6662 if (*p == ';')
6663 {
6664 *attachment = p + 1;
6665 return 0;
6666 }
6667 else if (*p == '\0')
6668 return 0;
6669 else
6670 return -1;
6671 }
6672
6673 /* Send a prepared I/O packet to the target and read its response.
6674 The prepared packet is in the global RS->BUF before this function
6675 is called, and the answer is there when we return.
6676
6677 COMMAND_BYTES is the length of the request to send, which may include
6678 binary data. WHICH_PACKET is the packet configuration to check
6679 before attempting a packet. If an error occurs, *REMOTE_ERRNO
6680 is set to the error number and -1 is returned. Otherwise the value
6681 returned by the function is returned.
6682
6683 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
6684 attachment is expected; an error will be reported if there's a
6685 mismatch. If one is found, *ATTACHMENT will be set to point into
6686 the packet buffer and *ATTACHMENT_LEN will be set to the
6687 attachment's length. */
6688
6689 static int
6690 remote_hostio_send_command (int command_bytes, int which_packet,
6691 int *remote_errno, char **attachment,
6692 int *attachment_len)
6693 {
6694 struct remote_state *rs = get_remote_state ();
6695 int ret, bytes_read;
6696 char *attachment_tmp;
6697
6698 if (remote_protocol_packets[which_packet].support == PACKET_DISABLE)
6699 {
6700 *remote_errno = FILEIO_ENOSYS;
6701 return -1;
6702 }
6703
6704 putpkt_binary (rs->buf, command_bytes);
6705 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
6706
6707 /* If it timed out, something is wrong. Don't try to parse the
6708 buffer. */
6709 if (bytes_read < 0)
6710 {
6711 *remote_errno = FILEIO_EINVAL;
6712 return -1;
6713 }
6714
6715 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
6716 {
6717 case PACKET_ERROR:
6718 *remote_errno = FILEIO_EINVAL;
6719 return -1;
6720 case PACKET_UNKNOWN:
6721 *remote_errno = FILEIO_ENOSYS;
6722 return -1;
6723 case PACKET_OK:
6724 break;
6725 }
6726
6727 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
6728 &attachment_tmp))
6729 {
6730 *remote_errno = FILEIO_EINVAL;
6731 return -1;
6732 }
6733
6734 /* Make sure we saw an attachment if and only if we expected one. */
6735 if ((attachment_tmp == NULL && attachment != NULL)
6736 || (attachment_tmp != NULL && attachment == NULL))
6737 {
6738 *remote_errno = FILEIO_EINVAL;
6739 return -1;
6740 }
6741
6742 /* If an attachment was found, it must point into the packet buffer;
6743 work out how many bytes there were. */
6744 if (attachment_tmp != NULL)
6745 {
6746 *attachment = attachment_tmp;
6747 *attachment_len = bytes_read - (*attachment - rs->buf);
6748 }
6749
6750 return ret;
6751 }
6752
6753 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
6754 remote file descriptor, or -1 if an error occurs (and set
6755 *REMOTE_ERRNO). */
6756
6757 static int
6758 remote_hostio_open (const char *filename, int flags, int mode,
6759 int *remote_errno)
6760 {
6761 struct remote_state *rs = get_remote_state ();
6762 char *p = rs->buf;
6763 int left = get_remote_packet_size () - 1;
6764
6765 remote_buffer_add_string (&p, &left, "vFile:open:");
6766
6767 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
6768 strlen (filename));
6769 remote_buffer_add_string (&p, &left, ",");
6770
6771 remote_buffer_add_int (&p, &left, flags);
6772 remote_buffer_add_string (&p, &left, ",");
6773
6774 remote_buffer_add_int (&p, &left, mode);
6775
6776 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
6777 remote_errno, NULL, NULL);
6778 }
6779
6780 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
6781 Return the number of bytes written, or -1 if an error occurs (and
6782 set *REMOTE_ERRNO). */
6783
6784 static int
6785 remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
6786 ULONGEST offset, int *remote_errno)
6787 {
6788 struct remote_state *rs = get_remote_state ();
6789 char *p = rs->buf;
6790 int left = get_remote_packet_size ();
6791 int out_len;
6792
6793 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
6794
6795 remote_buffer_add_int (&p, &left, fd);
6796 remote_buffer_add_string (&p, &left, ",");
6797
6798 remote_buffer_add_int (&p, &left, offset);
6799 remote_buffer_add_string (&p, &left, ",");
6800
6801 p += remote_escape_output (write_buf, len, p, &out_len,
6802 get_remote_packet_size () - (p - rs->buf));
6803
6804 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
6805 remote_errno, NULL, NULL);
6806 }
6807
6808 /* Read up to LEN bytes FD on the remote target into READ_BUF
6809 Return the number of bytes read, or -1 if an error occurs (and
6810 set *REMOTE_ERRNO). */
6811
6812 static int
6813 remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
6814 ULONGEST offset, int *remote_errno)
6815 {
6816 struct remote_state *rs = get_remote_state ();
6817 char *p = rs->buf;
6818 char *attachment;
6819 int left = get_remote_packet_size ();
6820 int ret, attachment_len;
6821 int read_len;
6822
6823 remote_buffer_add_string (&p, &left, "vFile:pread:");
6824
6825 remote_buffer_add_int (&p, &left, fd);
6826 remote_buffer_add_string (&p, &left, ",");
6827
6828 remote_buffer_add_int (&p, &left, len);
6829 remote_buffer_add_string (&p, &left, ",");
6830
6831 remote_buffer_add_int (&p, &left, offset);
6832
6833 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
6834 remote_errno, &attachment,
6835 &attachment_len);
6836
6837 if (ret < 0)
6838 return ret;
6839
6840 read_len = remote_unescape_input (attachment, attachment_len,
6841 read_buf, len);
6842 if (read_len != ret)
6843 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
6844
6845 return ret;
6846 }
6847
6848 /* Close FD on the remote target. Return 0, or -1 if an error occurs
6849 (and set *REMOTE_ERRNO). */
6850
6851 static int
6852 remote_hostio_close (int fd, int *remote_errno)
6853 {
6854 struct remote_state *rs = get_remote_state ();
6855 char *p = rs->buf;
6856 int left = get_remote_packet_size () - 1;
6857
6858 remote_buffer_add_string (&p, &left, "vFile:close:");
6859
6860 remote_buffer_add_int (&p, &left, fd);
6861
6862 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
6863 remote_errno, NULL, NULL);
6864 }
6865
6866 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
6867 occurs (and set *REMOTE_ERRNO). */
6868
6869 static int
6870 remote_hostio_unlink (const char *filename, int *remote_errno)
6871 {
6872 struct remote_state *rs = get_remote_state ();
6873 char *p = rs->buf;
6874 int left = get_remote_packet_size () - 1;
6875
6876 remote_buffer_add_string (&p, &left, "vFile:unlink:");
6877
6878 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
6879 strlen (filename));
6880
6881 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
6882 remote_errno, NULL, NULL);
6883 }
6884
6885 static int
6886 remote_fileio_errno_to_host (int errnum)
6887 {
6888 switch (errnum)
6889 {
6890 case FILEIO_EPERM:
6891 return EPERM;
6892 case FILEIO_ENOENT:
6893 return ENOENT;
6894 case FILEIO_EINTR:
6895 return EINTR;
6896 case FILEIO_EIO:
6897 return EIO;
6898 case FILEIO_EBADF:
6899 return EBADF;
6900 case FILEIO_EACCES:
6901 return EACCES;
6902 case FILEIO_EFAULT:
6903 return EFAULT;
6904 case FILEIO_EBUSY:
6905 return EBUSY;
6906 case FILEIO_EEXIST:
6907 return EEXIST;
6908 case FILEIO_ENODEV:
6909 return ENODEV;
6910 case FILEIO_ENOTDIR:
6911 return ENOTDIR;
6912 case FILEIO_EISDIR:
6913 return EISDIR;
6914 case FILEIO_EINVAL:
6915 return EINVAL;
6916 case FILEIO_ENFILE:
6917 return ENFILE;
6918 case FILEIO_EMFILE:
6919 return EMFILE;
6920 case FILEIO_EFBIG:
6921 return EFBIG;
6922 case FILEIO_ENOSPC:
6923 return ENOSPC;
6924 case FILEIO_ESPIPE:
6925 return ESPIPE;
6926 case FILEIO_EROFS:
6927 return EROFS;
6928 case FILEIO_ENOSYS:
6929 return ENOSYS;
6930 case FILEIO_ENAMETOOLONG:
6931 return ENAMETOOLONG;
6932 }
6933 return -1;
6934 }
6935
6936 static char *
6937 remote_hostio_error (int errnum)
6938 {
6939 int host_error = remote_fileio_errno_to_host (errnum);
6940
6941 if (host_error == -1)
6942 error (_("Unknown remote I/O error %d"), errnum);
6943 else
6944 error (_("Remote I/O error: %s"), safe_strerror (host_error));
6945 }
6946
6947 static void
6948 fclose_cleanup (void *file)
6949 {
6950 fclose (file);
6951 }
6952
6953 static void
6954 remote_hostio_close_cleanup (void *opaque)
6955 {
6956 int fd = *(int *) opaque;
6957 int remote_errno;
6958
6959 remote_hostio_close (fd, &remote_errno);
6960 }
6961
6962 void
6963 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
6964 {
6965 struct cleanup *back_to, *close_cleanup;
6966 int retcode, fd, remote_errno, bytes, io_size;
6967 FILE *file;
6968 gdb_byte *buffer;
6969 int bytes_in_buffer;
6970 int saw_eof;
6971 ULONGEST offset;
6972
6973 if (!remote_desc)
6974 error (_("command can only be used with remote target"));
6975
6976 file = fopen (local_file, "rb");
6977 if (file == NULL)
6978 perror_with_name (local_file);
6979 back_to = make_cleanup (fclose_cleanup, file);
6980
6981 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
6982 | FILEIO_O_TRUNC),
6983 0700, &remote_errno);
6984 if (fd == -1)
6985 remote_hostio_error (remote_errno);
6986
6987 /* Send up to this many bytes at once. They won't all fit in the
6988 remote packet limit, so we'll transfer slightly fewer. */
6989 io_size = get_remote_packet_size ();
6990 buffer = xmalloc (io_size);
6991 make_cleanup (xfree, buffer);
6992
6993 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
6994
6995 bytes_in_buffer = 0;
6996 saw_eof = 0;
6997 offset = 0;
6998 while (bytes_in_buffer || !saw_eof)
6999 {
7000 if (!saw_eof)
7001 {
7002 bytes = fread (buffer + bytes_in_buffer, 1, io_size - bytes_in_buffer,
7003 file);
7004 if (bytes == 0)
7005 {
7006 if (ferror (file))
7007 error (_("Error reading %s."), local_file);
7008 else
7009 {
7010 /* EOF. Unless there is something still in the
7011 buffer from the last iteration, we are done. */
7012 saw_eof = 1;
7013 if (bytes_in_buffer == 0)
7014 break;
7015 }
7016 }
7017 }
7018 else
7019 bytes = 0;
7020
7021 bytes += bytes_in_buffer;
7022 bytes_in_buffer = 0;
7023
7024 retcode = remote_hostio_pwrite (fd, buffer, bytes, offset, &remote_errno);
7025
7026 if (retcode < 0)
7027 remote_hostio_error (remote_errno);
7028 else if (retcode == 0)
7029 error (_("Remote write of %d bytes returned 0!"), bytes);
7030 else if (retcode < bytes)
7031 {
7032 /* Short write. Save the rest of the read data for the next
7033 write. */
7034 bytes_in_buffer = bytes - retcode;
7035 memmove (buffer, buffer + retcode, bytes_in_buffer);
7036 }
7037
7038 offset += retcode;
7039 }
7040
7041 discard_cleanups (close_cleanup);
7042 if (remote_hostio_close (fd, &remote_errno))
7043 remote_hostio_error (remote_errno);
7044
7045 if (from_tty)
7046 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
7047 do_cleanups (back_to);
7048 }
7049
7050 void
7051 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
7052 {
7053 struct cleanup *back_to, *close_cleanup;
7054 int retcode, fd, remote_errno, bytes, io_size;
7055 FILE *file;
7056 gdb_byte *buffer;
7057 ULONGEST offset;
7058
7059 if (!remote_desc)
7060 error (_("command can only be used with remote target"));
7061
7062 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
7063 if (fd == -1)
7064 remote_hostio_error (remote_errno);
7065
7066 file = fopen (local_file, "wb");
7067 if (file == NULL)
7068 perror_with_name (local_file);
7069 back_to = make_cleanup (fclose_cleanup, file);
7070
7071 /* Send up to this many bytes at once. They won't all fit in the
7072 remote packet limit, so we'll transfer slightly fewer. */
7073 io_size = get_remote_packet_size ();
7074 buffer = xmalloc (io_size);
7075 make_cleanup (xfree, buffer);
7076
7077 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
7078
7079 offset = 0;
7080 while (1)
7081 {
7082 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
7083 if (bytes == 0)
7084 /* Success, but no bytes, means end-of-file. */
7085 break;
7086 if (bytes == -1)
7087 remote_hostio_error (remote_errno);
7088
7089 offset += bytes;
7090
7091 bytes = fwrite (buffer, 1, bytes, file);
7092 if (bytes == 0)
7093 perror_with_name (local_file);
7094 }
7095
7096 discard_cleanups (close_cleanup);
7097 if (remote_hostio_close (fd, &remote_errno))
7098 remote_hostio_error (remote_errno);
7099
7100 if (from_tty)
7101 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
7102 do_cleanups (back_to);
7103 }
7104
7105 void
7106 remote_file_delete (const char *remote_file, int from_tty)
7107 {
7108 int retcode, remote_errno;
7109
7110 if (!remote_desc)
7111 error (_("command can only be used with remote target"));
7112
7113 retcode = remote_hostio_unlink (remote_file, &remote_errno);
7114 if (retcode == -1)
7115 remote_hostio_error (remote_errno);
7116
7117 if (from_tty)
7118 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
7119 }
7120
7121 static void
7122 remote_put_command (char *args, int from_tty)
7123 {
7124 struct cleanup *back_to;
7125 char **argv;
7126
7127 argv = buildargv (args);
7128 if (argv == NULL)
7129 nomem (0);
7130 back_to = make_cleanup_freeargv (argv);
7131 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
7132 error (_("Invalid parameters to remote put"));
7133
7134 remote_file_put (argv[0], argv[1], from_tty);
7135
7136 do_cleanups (back_to);
7137 }
7138
7139 static void
7140 remote_get_command (char *args, int from_tty)
7141 {
7142 struct cleanup *back_to;
7143 char **argv;
7144
7145 argv = buildargv (args);
7146 if (argv == NULL)
7147 nomem (0);
7148 back_to = make_cleanup_freeargv (argv);
7149 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
7150 error (_("Invalid parameters to remote get"));
7151
7152 remote_file_get (argv[0], argv[1], from_tty);
7153
7154 do_cleanups (back_to);
7155 }
7156
7157 static void
7158 remote_delete_command (char *args, int from_tty)
7159 {
7160 struct cleanup *back_to;
7161 char **argv;
7162
7163 argv = buildargv (args);
7164 if (argv == NULL)
7165 nomem (0);
7166 back_to = make_cleanup_freeargv (argv);
7167 if (argv[0] == NULL || argv[1] != NULL)
7168 error (_("Invalid parameters to remote delete"));
7169
7170 remote_file_delete (argv[0], from_tty);
7171
7172 do_cleanups (back_to);
7173 }
7174
7175 static void
7176 remote_command (char *args, int from_tty)
7177 {
7178 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
7179 }
7180
7181 static int
7182 remote_return_zero (void)
7183 {
7184 return 0;
7185 }
7186
7187 static void
7188 init_remote_ops (void)
7189 {
7190 remote_ops.to_shortname = "remote";
7191 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
7192 remote_ops.to_doc =
7193 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
7194 Specify the serial device it is connected to\n\
7195 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
7196 remote_ops.to_open = remote_open;
7197 remote_ops.to_close = remote_close;
7198 remote_ops.to_detach = remote_detach;
7199 remote_ops.to_disconnect = remote_disconnect;
7200 remote_ops.to_resume = remote_resume;
7201 remote_ops.to_wait = remote_wait;
7202 remote_ops.to_fetch_registers = remote_fetch_registers;
7203 remote_ops.to_store_registers = remote_store_registers;
7204 remote_ops.to_prepare_to_store = remote_prepare_to_store;
7205 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
7206 remote_ops.to_files_info = remote_files_info;
7207 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
7208 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
7209 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
7210 remote_ops.to_stopped_data_address = remote_stopped_data_address;
7211 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
7212 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
7213 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
7214 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
7215 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
7216 remote_ops.to_kill = remote_kill;
7217 remote_ops.to_load = generic_load;
7218 remote_ops.to_mourn_inferior = remote_mourn;
7219 remote_ops.to_thread_alive = remote_thread_alive;
7220 remote_ops.to_find_new_threads = remote_threads_info;
7221 remote_ops.to_pid_to_str = remote_pid_to_str;
7222 remote_ops.to_extra_thread_info = remote_threads_extra_info;
7223 remote_ops.to_stop = remote_stop;
7224 remote_ops.to_xfer_partial = remote_xfer_partial;
7225 remote_ops.to_rcmd = remote_rcmd;
7226 remote_ops.to_log_command = serial_log_command;
7227 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
7228 remote_ops.to_stratum = process_stratum;
7229 remote_ops.to_has_all_memory = 1;
7230 remote_ops.to_has_memory = 1;
7231 remote_ops.to_has_stack = 1;
7232 remote_ops.to_has_registers = 1;
7233 remote_ops.to_has_execution = 1;
7234 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
7235 remote_ops.to_magic = OPS_MAGIC;
7236 remote_ops.to_memory_map = remote_memory_map;
7237 remote_ops.to_flash_erase = remote_flash_erase;
7238 remote_ops.to_flash_done = remote_flash_done;
7239 remote_ops.to_read_description = remote_read_description;
7240 remote_ops.to_can_async_p = remote_return_zero;
7241 remote_ops.to_is_async_p = remote_return_zero;
7242 }
7243
7244 /* Set up the extended remote vector by making a copy of the standard
7245 remote vector and adding to it. */
7246
7247 static void
7248 init_extended_remote_ops (void)
7249 {
7250 extended_remote_ops = remote_ops;
7251
7252 extended_remote_ops.to_shortname = "extended-remote";
7253 extended_remote_ops.to_longname =
7254 "Extended remote serial target in gdb-specific protocol";
7255 extended_remote_ops.to_doc =
7256 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
7257 Specify the serial device it is connected to (e.g. /dev/ttya).",
7258 extended_remote_ops.to_open = extended_remote_open;
7259 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
7260 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
7261 extended_remote_ops.to_detach = extended_remote_detach;
7262 extended_remote_ops.to_attach = extended_remote_attach;
7263 }
7264
7265 static int
7266 remote_can_async_p (void)
7267 {
7268 /* We're async whenever the serial device is. */
7269 return remote_async_mask_value && serial_can_async_p (remote_desc);
7270 }
7271
7272 static int
7273 remote_is_async_p (void)
7274 {
7275 /* We're async whenever the serial device is. */
7276 return remote_async_mask_value && serial_is_async_p (remote_desc);
7277 }
7278
7279 /* Pass the SERIAL event on and up to the client. One day this code
7280 will be able to delay notifying the client of an event until the
7281 point where an entire packet has been received. */
7282
7283 static void (*async_client_callback) (enum inferior_event_type event_type,
7284 void *context);
7285 static void *async_client_context;
7286 static serial_event_ftype remote_async_serial_handler;
7287
7288 static void
7289 remote_async_serial_handler (struct serial *scb, void *context)
7290 {
7291 /* Don't propogate error information up to the client. Instead let
7292 the client find out about the error by querying the target. */
7293 async_client_callback (INF_REG_EVENT, async_client_context);
7294 }
7295
7296 static void
7297 remote_async (void (*callback) (enum inferior_event_type event_type,
7298 void *context), void *context)
7299 {
7300 if (remote_async_mask_value == 0)
7301 internal_error (__FILE__, __LINE__,
7302 _("Calling remote_async when async is masked"));
7303
7304 if (callback != NULL)
7305 {
7306 serial_async (remote_desc, remote_async_serial_handler, NULL);
7307 async_client_callback = callback;
7308 async_client_context = context;
7309 }
7310 else
7311 serial_async (remote_desc, NULL, NULL);
7312 }
7313
7314 static int
7315 remote_async_mask (int new_mask)
7316 {
7317 int curr_mask = remote_async_mask_value;
7318 remote_async_mask_value = new_mask;
7319 return curr_mask;
7320 }
7321
7322 /* Target async and target extended-async.
7323
7324 This are temporary targets, until it is all tested. Eventually
7325 async support will be incorporated int the usual 'remote'
7326 target. */
7327
7328 static void
7329 init_remote_async_ops (void)
7330 {
7331 remote_async_ops.to_shortname = "async";
7332 remote_async_ops.to_longname =
7333 "Remote serial target in async version of the gdb-specific protocol";
7334 remote_async_ops.to_doc =
7335 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
7336 Specify the serial device it is connected to (e.g. /dev/ttya).";
7337 remote_async_ops.to_open = remote_async_open;
7338 remote_async_ops.to_close = remote_close;
7339 remote_async_ops.to_detach = remote_detach;
7340 remote_async_ops.to_disconnect = remote_disconnect;
7341 remote_async_ops.to_resume = remote_async_resume;
7342 remote_async_ops.to_wait = remote_async_wait;
7343 remote_async_ops.to_fetch_registers = remote_fetch_registers;
7344 remote_async_ops.to_store_registers = remote_store_registers;
7345 remote_async_ops.to_prepare_to_store = remote_prepare_to_store;
7346 remote_async_ops.deprecated_xfer_memory = remote_xfer_memory;
7347 remote_async_ops.to_files_info = remote_files_info;
7348 remote_async_ops.to_insert_breakpoint = remote_insert_breakpoint;
7349 remote_async_ops.to_remove_breakpoint = remote_remove_breakpoint;
7350 remote_async_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
7351 remote_async_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
7352 remote_async_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
7353 remote_async_ops.to_insert_watchpoint = remote_insert_watchpoint;
7354 remote_async_ops.to_remove_watchpoint = remote_remove_watchpoint;
7355 remote_async_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
7356 remote_async_ops.to_stopped_data_address = remote_stopped_data_address;
7357 remote_async_ops.to_terminal_inferior = remote_async_terminal_inferior;
7358 remote_async_ops.to_terminal_ours = remote_async_terminal_ours;
7359 remote_async_ops.to_kill = remote_async_kill;
7360 remote_async_ops.to_load = generic_load;
7361 remote_async_ops.to_mourn_inferior = remote_async_mourn;
7362 remote_async_ops.to_thread_alive = remote_thread_alive;
7363 remote_async_ops.to_find_new_threads = remote_threads_info;
7364 remote_async_ops.to_pid_to_str = remote_pid_to_str;
7365 remote_async_ops.to_extra_thread_info = remote_threads_extra_info;
7366 remote_async_ops.to_stop = remote_stop;
7367 remote_async_ops.to_xfer_partial = remote_xfer_partial;
7368 remote_async_ops.to_rcmd = remote_rcmd;
7369 remote_async_ops.to_get_thread_local_address
7370 = remote_get_thread_local_address;
7371 remote_async_ops.to_stratum = process_stratum;
7372 remote_async_ops.to_has_all_memory = 1;
7373 remote_async_ops.to_has_memory = 1;
7374 remote_async_ops.to_has_stack = 1;
7375 remote_async_ops.to_has_registers = 1;
7376 remote_async_ops.to_has_execution = 1;
7377 remote_async_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
7378 remote_async_ops.to_can_async_p = remote_can_async_p;
7379 remote_async_ops.to_is_async_p = remote_is_async_p;
7380 remote_async_ops.to_async = remote_async;
7381 remote_async_ops.to_async_mask = remote_async_mask;
7382 remote_async_ops.to_magic = OPS_MAGIC;
7383 remote_async_ops.to_memory_map = remote_memory_map;
7384 remote_async_ops.to_flash_erase = remote_flash_erase;
7385 remote_async_ops.to_flash_done = remote_flash_done;
7386 remote_async_ops.to_read_description = remote_read_description;
7387 }
7388
7389 /* Set up the async extended remote vector by making a copy of the standard
7390 remote vector and adding to it. */
7391
7392 static void
7393 init_extended_async_remote_ops (void)
7394 {
7395 extended_async_remote_ops = remote_async_ops;
7396
7397 extended_async_remote_ops.to_shortname = "extended-async";
7398 extended_async_remote_ops.to_longname =
7399 "Extended remote serial target in async gdb-specific protocol";
7400 extended_async_remote_ops.to_doc =
7401 "Use a remote computer via a serial line, using an async gdb-specific protocol.\n\
7402 Specify the serial device it is connected to (e.g. /dev/ttya).",
7403 extended_async_remote_ops.to_open = extended_remote_async_open;
7404 extended_async_remote_ops.to_create_inferior = extended_remote_async_create_inferior;
7405 extended_async_remote_ops.to_mourn_inferior = extended_async_remote_mourn;
7406 extended_async_remote_ops.to_detach = extended_remote_detach;
7407 extended_async_remote_ops.to_attach = extended_async_remote_attach;
7408 }
7409
7410 static void
7411 set_remote_cmd (char *args, int from_tty)
7412 {
7413 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
7414 }
7415
7416 static void
7417 show_remote_cmd (char *args, int from_tty)
7418 {
7419 /* We can't just use cmd_show_list here, because we want to skip
7420 the redundant "show remote Z-packet" and the legacy aliases. */
7421 struct cleanup *showlist_chain;
7422 struct cmd_list_element *list = remote_show_cmdlist;
7423
7424 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
7425 for (; list != NULL; list = list->next)
7426 if (strcmp (list->name, "Z-packet") == 0)
7427 continue;
7428 else if (list->type == not_set_cmd)
7429 /* Alias commands are exactly like the original, except they
7430 don't have the normal type. */
7431 continue;
7432 else
7433 {
7434 struct cleanup *option_chain
7435 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
7436 ui_out_field_string (uiout, "name", list->name);
7437 ui_out_text (uiout, ": ");
7438 if (list->type == show_cmd)
7439 do_setshow_command ((char *) NULL, from_tty, list);
7440 else
7441 cmd_func (list, NULL, from_tty);
7442 /* Close the tuple. */
7443 do_cleanups (option_chain);
7444 }
7445
7446 /* Close the tuple. */
7447 do_cleanups (showlist_chain);
7448 }
7449
7450
7451 /* Function to be called whenever a new objfile (shlib) is detected. */
7452 static void
7453 remote_new_objfile (struct objfile *objfile)
7454 {
7455 if (remote_desc != 0) /* Have a remote connection. */
7456 remote_check_symbols (objfile);
7457 }
7458
7459 void
7460 _initialize_remote (void)
7461 {
7462 struct remote_state *rs;
7463
7464 /* architecture specific data */
7465 remote_gdbarch_data_handle =
7466 gdbarch_data_register_post_init (init_remote_state);
7467 remote_g_packet_data_handle =
7468 gdbarch_data_register_pre_init (remote_g_packet_data_init);
7469
7470 /* Initialize the per-target state. At the moment there is only one
7471 of these, not one per target. Only one target is active at a
7472 time. The default buffer size is unimportant; it will be expanded
7473 whenever a larger buffer is needed. */
7474 rs = get_remote_state_raw ();
7475 rs->buf_size = 400;
7476 rs->buf = xmalloc (rs->buf_size);
7477
7478 init_remote_ops ();
7479 add_target (&remote_ops);
7480
7481 init_extended_remote_ops ();
7482 add_target (&extended_remote_ops);
7483
7484 init_remote_async_ops ();
7485 add_target (&remote_async_ops);
7486
7487 init_extended_async_remote_ops ();
7488 add_target (&extended_async_remote_ops);
7489
7490 /* Hook into new objfile notification. */
7491 observer_attach_new_objfile (remote_new_objfile);
7492
7493 /* Set up signal handlers. */
7494 sigint_remote_token =
7495 create_async_signal_handler (async_remote_interrupt, NULL);
7496 sigint_remote_twice_token =
7497 create_async_signal_handler (inferior_event_handler_wrapper, NULL);
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 }
This page took 0.248374 seconds and 4 git commands to generate.