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