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