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