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