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