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