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