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