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