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