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