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