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