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