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