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