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