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