]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
* c-arm.texi: Add tutorial on ARM unwinding pseudo ops.
[thirdparty/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. */
2bc416ba 277 /* long size in bytes; == register_size (current_gdbarch, regnum);
23860348 278 at present. */
c9f4d572
UW
279 /* char *name; == gdbarch_register_name (current_gdbarch, regnum);
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{
451fbdda 312 return gdbarch_data (current_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{
f57d151a 448 if (regnum < 0 && regnum >= gdbarch_num_regs (current_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;
f57d151a 462 for (i = 0; i < gdbarch_num_regs (current_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. */
2403 sym_addr = gdbarch_convert_from_func_ptr_addr (current_gdbarch,
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,
2bc416ba 3591 register_size (current_gdbarch,
23860348 3592 reg->regnum));
6c3f2dbf 3593 p += 2 * fieldsize;
2bc416ba 3594 if (fieldsize < register_size (current_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)
4108 address_size = gdbarch_addr_bit (current_gdbarch);
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
JZ
5375
5376 gdbarch_breakpoint_from_pc
7c0f6dcc 5377 (current_gdbarch, &addr, &bpsize);
4fff2411
JZ
5378
5379 rs = get_remote_state ();
5380 p = rs->buf;
802188a7 5381
96baa820
JM
5382 *(p++) = 'Z';
5383 *(p++) = '0';
5384 *(p++) = ',';
7c0f6dcc 5385 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 5386 p += hexnumstr (p, addr);
7c0f6dcc 5387 sprintf (p, ",%d", bpsize);
802188a7 5388
6d820c5c
DJ
5389 putpkt (rs->buf);
5390 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 5391
6d820c5c 5392 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 5393 {
d471ea57
AC
5394 case PACKET_ERROR:
5395 return -1;
5396 case PACKET_OK:
7c0f6dcc
JL
5397 bp_tgt->placed_address = addr;
5398 bp_tgt->placed_size = bpsize;
d471ea57
AC
5399 return 0;
5400 case PACKET_UNKNOWN:
5401 break;
96baa820
JM
5402 }
5403 }
c906108c 5404
8181d85f 5405 return memory_insert_breakpoint (bp_tgt);
c906108c
SS
5406}
5407
5408static int
8181d85f 5409remote_remove_breakpoint (struct bp_target_info *bp_tgt)
c906108c 5410{
8181d85f 5411 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 5412 struct remote_state *rs = get_remote_state ();
96baa820
JM
5413 int bp_size;
5414
444abaca 5415 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
96baa820 5416 {
6d820c5c 5417 char *p = rs->buf;
802188a7 5418
96baa820
JM
5419 *(p++) = 'z';
5420 *(p++) = '0';
5421 *(p++) = ',';
5422
8181d85f
DJ
5423 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
5424 p += hexnumstr (p, addr);
5425 sprintf (p, ",%d", bp_tgt->placed_size);
802188a7 5426
6d820c5c
DJ
5427 putpkt (rs->buf);
5428 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 5429
6d820c5c 5430 return (rs->buf[0] == 'E');
96baa820
JM
5431 }
5432
8181d85f 5433 return memory_remove_breakpoint (bp_tgt);
c906108c
SS
5434}
5435
d471ea57
AC
5436static int
5437watchpoint_to_Z_packet (int type)
5438{
5439 switch (type)
5440 {
5441 case hw_write:
bb858e6a 5442 return Z_PACKET_WRITE_WP;
d471ea57
AC
5443 break;
5444 case hw_read:
bb858e6a 5445 return Z_PACKET_READ_WP;
d471ea57
AC
5446 break;
5447 case hw_access:
bb858e6a 5448 return Z_PACKET_ACCESS_WP;
d471ea57
AC
5449 break;
5450 default:
8e65ff28 5451 internal_error (__FILE__, __LINE__,
e2e0b3e5 5452 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
5453 }
5454}
5455
3c3bea1c 5456static int
fba45db2 5457remote_insert_watchpoint (CORE_ADDR addr, int len, int type)
96baa820 5458{
d01949b6 5459 struct remote_state *rs = get_remote_state ();
e514a9d6 5460 char *p;
d471ea57 5461 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 5462
444abaca 5463 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
5cffb350 5464 return -1;
802188a7 5465
6d820c5c
DJ
5466 sprintf (rs->buf, "Z%x,", packet);
5467 p = strchr (rs->buf, '\0');
96baa820
JM
5468 addr = remote_address_masked (addr);
5469 p += hexnumstr (p, (ULONGEST) addr);
d4f3574e 5470 sprintf (p, ",%x", len);
802188a7 5471
6d820c5c
DJ
5472 putpkt (rs->buf);
5473 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 5474
6d820c5c 5475 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
5476 {
5477 case PACKET_ERROR:
5478 case PACKET_UNKNOWN:
5479 return -1;
5480 case PACKET_OK:
5481 return 0;
5482 }
8e65ff28 5483 internal_error (__FILE__, __LINE__,
e2e0b3e5 5484 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
5485}
5486
d471ea57 5487
3c3bea1c 5488static int
fba45db2 5489remote_remove_watchpoint (CORE_ADDR addr, int len, int type)
96baa820 5490{
d01949b6 5491 struct remote_state *rs = get_remote_state ();
e514a9d6 5492 char *p;
d471ea57
AC
5493 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
5494
444abaca 5495 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
5cffb350 5496 return -1;
802188a7 5497
6d820c5c
DJ
5498 sprintf (rs->buf, "z%x,", packet);
5499 p = strchr (rs->buf, '\0');
96baa820
JM
5500 addr = remote_address_masked (addr);
5501 p += hexnumstr (p, (ULONGEST) addr);
d4f3574e 5502 sprintf (p, ",%x", len);
6d820c5c
DJ
5503 putpkt (rs->buf);
5504 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 5505
6d820c5c 5506 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
5507 {
5508 case PACKET_ERROR:
5509 case PACKET_UNKNOWN:
5510 return -1;
5511 case PACKET_OK:
5512 return 0;
5513 }
8e65ff28 5514 internal_error (__FILE__, __LINE__,
e2e0b3e5 5515 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
5516}
5517
3c3bea1c 5518
501eef12
AC
5519int remote_hw_watchpoint_limit = -1;
5520int remote_hw_breakpoint_limit = -1;
d471ea57 5521
b9362cc7 5522static int
3c3bea1c 5523remote_check_watch_resources (int type, int cnt, int ot)
96baa820 5524{
3c3bea1c
GS
5525 if (type == bp_hardware_breakpoint)
5526 {
5527 if (remote_hw_breakpoint_limit == 0)
5528 return 0;
501eef12
AC
5529 else if (remote_hw_breakpoint_limit < 0)
5530 return 1;
3c3bea1c
GS
5531 else if (cnt <= remote_hw_breakpoint_limit)
5532 return 1;
5533 }
5534 else
5535 {
5536 if (remote_hw_watchpoint_limit == 0)
5537 return 0;
501eef12
AC
5538 else if (remote_hw_watchpoint_limit < 0)
5539 return 1;
3c3bea1c
GS
5540 else if (ot)
5541 return -1;
5542 else if (cnt <= remote_hw_watchpoint_limit)
5543 return 1;
5544 }
5545 return -1;
5546}
5547
b9362cc7 5548static int
3c3bea1c
GS
5549remote_stopped_by_watchpoint (void)
5550{
5551 return remote_stopped_by_watchpoint_p;
5552}
5553
4aa7a7f5
JJ
5554static int
5555remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 5556{
4aa7a7f5 5557 int rc = 0;
d983da9c 5558 if (remote_stopped_by_watchpoint ())
4aa7a7f5
JJ
5559 {
5560 *addr_p = remote_watch_data_address;
5561 rc = 1;
5562 }
5563
5564 return rc;
3c3bea1c
GS
5565}
5566
5567
5568static int
8181d85f 5569remote_insert_hw_breakpoint (struct bp_target_info *bp_tgt)
3c3bea1c 5570{
8181d85f 5571 CORE_ADDR addr;
4fff2411
JZ
5572 struct remote_state *rs;
5573 char *p;
802188a7 5574
c8189ed1 5575 /* The length field should be set to the size of a breakpoint
8181d85f 5576 instruction, even though we aren't inserting one ourselves. */
c8189ed1 5577
3b3b875c
UW
5578 gdbarch_breakpoint_from_pc
5579 (current_gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
3c3bea1c 5580
444abaca 5581 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5cffb350 5582 return -1;
2bc416ba 5583
4fff2411
JZ
5584 rs = get_remote_state ();
5585 p = rs->buf;
5586
96baa820
JM
5587 *(p++) = 'Z';
5588 *(p++) = '1';
5589 *(p++) = ',';
802188a7 5590
8181d85f 5591 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 5592 p += hexnumstr (p, (ULONGEST) addr);
8181d85f 5593 sprintf (p, ",%x", bp_tgt->placed_size);
96baa820 5594
6d820c5c
DJ
5595 putpkt (rs->buf);
5596 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 5597
6d820c5c 5598 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
5599 {
5600 case PACKET_ERROR:
5601 case PACKET_UNKNOWN:
5602 return -1;
5603 case PACKET_OK:
5604 return 0;
5605 }
8e65ff28 5606 internal_error (__FILE__, __LINE__,
e2e0b3e5 5607 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
5608}
5609
d471ea57 5610
802188a7 5611static int
8181d85f 5612remote_remove_hw_breakpoint (struct bp_target_info *bp_tgt)
96baa820 5613{
8181d85f 5614 CORE_ADDR addr;
d01949b6 5615 struct remote_state *rs = get_remote_state ();
6d820c5c 5616 char *p = rs->buf;
c8189ed1 5617
444abaca 5618 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5cffb350 5619 return -1;
802188a7 5620
96baa820
JM
5621 *(p++) = 'z';
5622 *(p++) = '1';
5623 *(p++) = ',';
802188a7 5624
8181d85f 5625 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 5626 p += hexnumstr (p, (ULONGEST) addr);
8181d85f 5627 sprintf (p, ",%x", bp_tgt->placed_size);
96baa820 5628
6d820c5c
DJ
5629 putpkt (rs->buf);
5630 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 5631
6d820c5c 5632 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
5633 {
5634 case PACKET_ERROR:
5635 case PACKET_UNKNOWN:
5636 return -1;
5637 case PACKET_OK:
5638 return 0;
5639 }
8e65ff28 5640 internal_error (__FILE__, __LINE__,
e2e0b3e5 5641 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 5642}
96baa820 5643
c906108c
SS
5644/* Some targets are only capable of doing downloads, and afterwards
5645 they switch to the remote serial protocol. This function provides
5646 a clean way to get from the download target to the remote target.
5647 It's basically just a wrapper so that we don't have to expose any
5648 of the internal workings of remote.c.
5649
5650 Prior to calling this routine, you should shutdown the current
5651 target code, else you will get the "A program is being debugged
5652 already..." message. Usually a call to pop_target() suffices. */
5653
5654void
fba45db2 5655push_remote_target (char *name, int from_tty)
c906108c 5656{
a3f17187 5657 printf_filtered (_("Switching to remote protocol\n"));
c906108c
SS
5658 remote_open (name, from_tty);
5659}
5660
23860348 5661/* Table used by the crc32 function to calcuate the checksum. */
c906108c 5662
c5aa993b
JM
5663static unsigned long crc32_table[256] =
5664{0, 0};
c906108c
SS
5665
5666static unsigned long
fba45db2 5667crc32 (unsigned char *buf, int len, unsigned int crc)
c906108c 5668{
c5aa993b 5669 if (!crc32_table[1])
c906108c 5670 {
23860348 5671 /* Initialize the CRC table and the decoding table. */
c906108c
SS
5672 int i, j;
5673 unsigned int c;
5674
5675 for (i = 0; i < 256; i++)
c5aa993b
JM
5676 {
5677 for (c = i << 24, j = 8; j > 0; --j)
5678 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
5679 crc32_table[i] = c;
5680 }
c906108c
SS
5681 }
5682
5683 while (len--)
5684 {
5685 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
5686 buf++;
5687 }
5688 return crc;
5689}
5690
5691/* compare-sections command
5692
5693 With no arguments, compares each loadable section in the exec bfd
5694 with the same memory range on the target, and reports mismatches.
5695 Useful for verifying the image on the target against the exec file.
5696 Depends on the target understanding the new "qCRC:" request. */
5697
e514a9d6
JM
5698/* FIXME: cagney/1999-10-26: This command should be broken down into a
5699 target method (target verify memory) and generic version of the
5700 actual command. This will allow other high-level code (especially
23860348 5701 generic_load()) to make use of this target functionality. */
e514a9d6 5702
c906108c 5703static void
fba45db2 5704compare_sections_command (char *args, int from_tty)
c906108c 5705{
d01949b6 5706 struct remote_state *rs = get_remote_state ();
c906108c
SS
5707 asection *s;
5708 unsigned long host_crc, target_crc;
5709 extern bfd *exec_bfd;
5710 struct cleanup *old_chain;
085dd6e6
JM
5711 char *tmp;
5712 char *sectdata;
ce359b09 5713 const char *sectname;
c906108c
SS
5714 bfd_size_type size;
5715 bfd_vma lma;
5716 int matched = 0;
5717 int mismatched = 0;
5718
5719 if (!exec_bfd)
8a3fe4f8 5720 error (_("command cannot be used without an exec file"));
c906108c
SS
5721 if (!current_target.to_shortname ||
5722 strcmp (current_target.to_shortname, "remote") != 0)
8a3fe4f8 5723 error (_("command can only be used with remote target"));
c906108c 5724
c5aa993b 5725 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
5726 {
5727 if (!(s->flags & SEC_LOAD))
c5aa993b 5728 continue; /* skip non-loadable section */
c906108c 5729
2c500098 5730 size = bfd_get_section_size (s);
c906108c 5731 if (size == 0)
c5aa993b 5732 continue; /* skip zero-length section */
c906108c 5733
ce359b09 5734 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 5735 if (args && strcmp (args, sectname) != 0)
c5aa993b 5736 continue; /* not the section selected by user */
c906108c 5737
c5aa993b 5738 matched = 1; /* do this section */
c906108c 5739 lma = s->lma;
23860348 5740 /* FIXME: assumes lma can fit into long. */
ea9c271d 5741 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
ecbc58df 5742 (long) lma, (long) size);
6d820c5c 5743 putpkt (rs->buf);
c906108c 5744
23860348
MS
5745 /* Be clever; compute the host_crc before waiting for target
5746 reply. */
c906108c 5747 sectdata = xmalloc (size);
b8c9b27d 5748 old_chain = make_cleanup (xfree, sectdata);
c906108c
SS
5749 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
5750 host_crc = crc32 ((unsigned char *) sectdata, size, 0xffffffff);
5751
6d820c5c
DJ
5752 getpkt (&rs->buf, &rs->buf_size, 0);
5753 if (rs->buf[0] == 'E')
8a3fe4f8 5754 error (_("target memory fault, section %s, range 0x%s -- 0x%s"),
823ca731 5755 sectname, paddr (lma), paddr (lma + size));
6d820c5c 5756 if (rs->buf[0] != 'C')
8a3fe4f8 5757 error (_("remote target does not support this operation"));
c906108c 5758
6d820c5c 5759 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
c906108c
SS
5760 target_crc = target_crc * 16 + fromhex (*tmp);
5761
d4f3574e
SS
5762 printf_filtered ("Section %s, range 0x%s -- 0x%s: ",
5763 sectname, paddr (lma), paddr (lma + size));
c906108c
SS
5764 if (host_crc == target_crc)
5765 printf_filtered ("matched.\n");
5766 else
c5aa993b
JM
5767 {
5768 printf_filtered ("MIS-MATCHED!\n");
5769 mismatched++;
5770 }
c906108c
SS
5771
5772 do_cleanups (old_chain);
5773 }
5774 if (mismatched > 0)
8a3fe4f8
AC
5775 warning (_("One or more sections of the remote executable does not match\n\
5776the loaded file\n"));
c906108c 5777 if (args && !matched)
a3f17187 5778 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
5779}
5780
0e7f50da
UW
5781/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
5782 into remote target. The number of bytes written to the remote
5783 target is returned, or -1 for error. */
5784
5785static LONGEST
5786remote_write_qxfer (struct target_ops *ops, const char *object_name,
5787 const char *annex, const gdb_byte *writebuf,
5788 ULONGEST offset, LONGEST len,
5789 struct packet_config *packet)
5790{
5791 int i, buf_len;
5792 ULONGEST n;
5793 gdb_byte *wbuf;
5794 struct remote_state *rs = get_remote_state ();
5795 int max_size = get_memory_write_packet_size ();
5796
5797 if (packet->support == PACKET_DISABLE)
5798 return -1;
5799
5800 /* Insert header. */
5801 i = snprintf (rs->buf, max_size,
5802 "qXfer:%s:write:%s:%s:",
5803 object_name, annex ? annex : "",
5804 phex_nz (offset, sizeof offset));
5805 max_size -= (i + 1);
5806
5807 /* Escape as much data as fits into rs->buf. */
5808 buf_len = remote_escape_output
5809 (writebuf, len, (rs->buf + i), &max_size, max_size);
5810
5811 if (putpkt_binary (rs->buf, i + buf_len) < 0
5812 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
5813 || packet_ok (rs->buf, packet) != PACKET_OK)
5814 return -1;
5815
5816 unpack_varlen_hex (rs->buf, &n);
5817 return n;
5818}
5819
0876f84a
DJ
5820/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
5821 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
5822 number of bytes read is returned, or 0 for EOF, or -1 for error.
5823 The number of bytes read may be less than LEN without indicating an
5824 EOF. PACKET is checked and updated to indicate whether the remote
5825 target supports this object. */
5826
5827static LONGEST
5828remote_read_qxfer (struct target_ops *ops, const char *object_name,
5829 const char *annex,
5830 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
5831 struct packet_config *packet)
5832{
5833 static char *finished_object;
5834 static char *finished_annex;
5835 static ULONGEST finished_offset;
5836
5837 struct remote_state *rs = get_remote_state ();
5838 unsigned int total = 0;
5839 LONGEST i, n, packet_len;
5840
5841 if (packet->support == PACKET_DISABLE)
5842 return -1;
5843
5844 /* Check whether we've cached an end-of-object packet that matches
5845 this request. */
5846 if (finished_object)
5847 {
5848 if (strcmp (object_name, finished_object) == 0
5849 && strcmp (annex ? annex : "", finished_annex) == 0
5850 && offset == finished_offset)
5851 return 0;
5852
5853 /* Otherwise, we're now reading something different. Discard
5854 the cache. */
5855 xfree (finished_object);
5856 xfree (finished_annex);
5857 finished_object = NULL;
5858 finished_annex = NULL;
5859 }
5860
5861 /* Request only enough to fit in a single packet. The actual data
5862 may not, since we don't know how much of it will need to be escaped;
5863 the target is free to respond with slightly less data. We subtract
5864 five to account for the response type and the protocol frame. */
5865 n = min (get_remote_packet_size () - 5, len);
5866 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
5867 object_name, annex ? annex : "",
5868 phex_nz (offset, sizeof offset),
5869 phex_nz (n, sizeof n));
5870 i = putpkt (rs->buf);
5871 if (i < 0)
5872 return -1;
5873
5874 rs->buf[0] = '\0';
5875 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
5876 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
5877 return -1;
5878
5879 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
5880 error (_("Unknown remote qXfer reply: %s"), rs->buf);
5881
5882 /* 'm' means there is (or at least might be) more data after this
5883 batch. That does not make sense unless there's at least one byte
5884 of data in this reply. */
5885 if (rs->buf[0] == 'm' && packet_len == 1)
5886 error (_("Remote qXfer reply contained no data."));
5887
5888 /* Got some data. */
5889 i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
5890
5891 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
5892 or possibly empty. If we have the final block of a non-empty
5893 object, record this fact to bypass a subsequent partial read. */
5894 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a
DJ
5895 {
5896 finished_object = xstrdup (object_name);
5897 finished_annex = xstrdup (annex ? annex : "");
5898 finished_offset = offset + i;
5899 }
5900
5901 return i;
5902}
5903
1e3ff5ad 5904static LONGEST
4b8a223f 5905remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5
MK
5906 const char *annex, gdb_byte *readbuf,
5907 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
c906108c 5908{
d01949b6 5909 struct remote_state *rs = get_remote_state ();
c906108c 5910 int i;
6d820c5c 5911 char *p2;
1e3ff5ad 5912 char query_type;
c906108c 5913
b2182ed2 5914 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
5915 if (object == TARGET_OBJECT_MEMORY)
5916 {
5917 int xfered;
5918 errno = 0;
5919
2d717e4f
DJ
5920 /* If the remote target is connected but not running, we should
5921 pass this request down to a lower stratum (e.g. the executable
5922 file). */
5923 if (!target_has_execution)
5924 return 0;
5925
21e3b9b9 5926 if (writebuf != NULL)
b2182ed2 5927 xfered = remote_write_bytes (offset, writebuf, len);
21e3b9b9 5928 else
b2182ed2 5929 xfered = remote_read_bytes (offset, readbuf, len);
21e3b9b9
DJ
5930
5931 if (xfered > 0)
5932 return xfered;
5933 else if (xfered == 0 && errno == 0)
5934 return 0;
5935 else
5936 return -1;
5937 }
5938
0e7f50da
UW
5939 /* Handle SPU memory using qxfer packets. */
5940 if (object == TARGET_OBJECT_SPU)
5941 {
5942 if (readbuf)
5943 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
5944 &remote_protocol_packets
5945 [PACKET_qXfer_spu_read]);
5946 else
5947 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
5948 &remote_protocol_packets
5949 [PACKET_qXfer_spu_write]);
5950 }
5951
a76d924d
DJ
5952 /* Only handle flash writes. */
5953 if (writebuf != NULL)
5954 {
5955 LONGEST xfered;
5956
5957 switch (object)
5958 {
5959 case TARGET_OBJECT_FLASH:
5960 xfered = remote_flash_write (ops, offset, len, writebuf);
5961
5962 if (xfered > 0)
5963 return xfered;
5964 else if (xfered == 0 && errno == 0)
5965 return 0;
5966 else
5967 return -1;
5968
5969 default:
5970 return -1;
5971 }
5972 }
4b8a223f 5973
1e3ff5ad
AC
5974 /* Map pre-existing objects onto letters. DO NOT do this for new
5975 objects!!! Instead specify new query packets. */
5976 switch (object)
c906108c 5977 {
1e3ff5ad
AC
5978 case TARGET_OBJECT_AVR:
5979 query_type = 'R';
5980 break;
802188a7
RM
5981
5982 case TARGET_OBJECT_AUXV:
0876f84a
DJ
5983 gdb_assert (annex == NULL);
5984 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
5985 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 5986
23181151
DJ
5987 case TARGET_OBJECT_AVAILABLE_FEATURES:
5988 return remote_read_qxfer
5989 (ops, "features", annex, readbuf, offset, len,
5990 &remote_protocol_packets[PACKET_qXfer_features]);
5991
cfa9d6d9
DJ
5992 case TARGET_OBJECT_LIBRARIES:
5993 return remote_read_qxfer
5994 (ops, "libraries", annex, readbuf, offset, len,
5995 &remote_protocol_packets[PACKET_qXfer_libraries]);
5996
fd79ecee
DJ
5997 case TARGET_OBJECT_MEMORY_MAP:
5998 gdb_assert (annex == NULL);
5999 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
6000 &remote_protocol_packets[PACKET_qXfer_memory_map]);
6001
1e3ff5ad 6002 default:
c906108c
SS
6003 return -1;
6004 }
6005
4b8a223f 6006 /* Note: a zero OFFSET and LEN can be used to query the minimum
1e3ff5ad 6007 buffer size. */
4b8a223f 6008 if (offset == 0 && len == 0)
ea9c271d
DJ
6009 return (get_remote_packet_size ());
6010 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 6011 large enough let the caller deal with it. */
ea9c271d 6012 if (len < get_remote_packet_size ())
1e3ff5ad 6013 return -1;
ea9c271d 6014 len = get_remote_packet_size ();
1e3ff5ad 6015
23860348 6016 /* Except for querying the minimum buffer size, target must be open. */
c5aa993b 6017 if (!remote_desc)
8a3fe4f8 6018 error (_("remote query is only available after target open"));
c906108c 6019
1e3ff5ad 6020 gdb_assert (annex != NULL);
4b8a223f 6021 gdb_assert (readbuf != NULL);
c906108c 6022
6d820c5c 6023 p2 = rs->buf;
c906108c
SS
6024 *p2++ = 'q';
6025 *p2++ = query_type;
6026
23860348
MS
6027 /* We used one buffer char for the remote protocol q command and
6028 another for the query type. As the remote protocol encapsulation
6029 uses 4 chars plus one extra in case we are debugging
6030 (remote_debug), we have PBUFZIZ - 7 left to pack the query
6031 string. */
c906108c 6032 i = 0;
ea9c271d 6033 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 6034 {
1e3ff5ad
AC
6035 /* Bad caller may have sent forbidden characters. */
6036 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
6037 *p2++ = annex[i];
c906108c
SS
6038 i++;
6039 }
1e3ff5ad
AC
6040 *p2 = '\0';
6041 gdb_assert (annex[i] == '\0');
c906108c 6042
6d820c5c 6043 i = putpkt (rs->buf);
c5aa993b
JM
6044 if (i < 0)
6045 return i;
c906108c 6046
6d820c5c
DJ
6047 getpkt (&rs->buf, &rs->buf_size, 0);
6048 strcpy ((char *) readbuf, rs->buf);
c906108c 6049
cfd77fa1 6050 return strlen ((char *) readbuf);
c906108c
SS
6051}
6052
08388c79
DE
6053static int
6054remote_search_memory (struct target_ops* ops,
6055 CORE_ADDR start_addr, ULONGEST search_space_len,
6056 const gdb_byte *pattern, ULONGEST pattern_len,
6057 CORE_ADDR *found_addrp)
6058{
6059 struct remote_state *rs = get_remote_state ();
6060 int max_size = get_memory_write_packet_size ();
6061 struct packet_config *packet =
6062 &remote_protocol_packets[PACKET_qSearch_memory];
6063 /* number of packet bytes used to encode the pattern,
6064 this could be more than PATTERN_LEN due to escape characters */
6065 int escaped_pattern_len;
6066 /* amount of pattern that was encodable in the packet */
6067 int used_pattern_len;
6068 int i;
6069 int found;
6070 ULONGEST found_addr;
6071
6072 /* Don't go to the target if we don't have to.
6073 This is done before checking packet->support to avoid the possibility that
6074 a success for this edge case means the facility works in general. */
6075 if (pattern_len > search_space_len)
6076 return 0;
6077 if (pattern_len == 0)
6078 {
6079 *found_addrp = start_addr;
6080 return 1;
6081 }
6082
6083 /* If we already know the packet isn't supported, fall back to the simple
6084 way of searching memory. */
6085
6086 if (packet->support == PACKET_DISABLE)
6087 {
6088 /* Target doesn't provided special support, fall back and use the
6089 standard support (copy memory and do the search here). */
6090 return simple_search_memory (ops, start_addr, search_space_len,
6091 pattern, pattern_len, found_addrp);
6092 }
6093
6094 /* Insert header. */
6095 i = snprintf (rs->buf, max_size,
6096 "qSearch:memory:%s;%s;",
6097 paddr_nz (start_addr),
6098 phex_nz (search_space_len, sizeof (search_space_len)));
6099 max_size -= (i + 1);
6100
6101 /* Escape as much data as fits into rs->buf. */
6102 escaped_pattern_len =
6103 remote_escape_output (pattern, pattern_len, (rs->buf + i),
6104 &used_pattern_len, max_size);
6105
6106 /* Bail if the pattern is too large. */
6107 if (used_pattern_len != pattern_len)
10e0fa18 6108 error ("Pattern is too large to transmit to remote target.");
08388c79
DE
6109
6110 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
6111 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
6112 || packet_ok (rs->buf, packet) != PACKET_OK)
6113 {
6114 /* The request may not have worked because the command is not
6115 supported. If so, fall back to the simple way. */
6116 if (packet->support == PACKET_DISABLE)
6117 {
6118 return simple_search_memory (ops, start_addr, search_space_len,
6119 pattern, pattern_len, found_addrp);
6120 }
6121 return -1;
6122 }
6123
6124 if (rs->buf[0] == '0')
6125 found = 0;
6126 else if (rs->buf[0] == '1')
6127 {
6128 found = 1;
6129 if (rs->buf[1] != ',')
10e0fa18 6130 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
6131 unpack_varlen_hex (rs->buf + 2, &found_addr);
6132 *found_addrp = found_addr;
6133 }
6134 else
10e0fa18 6135 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
6136
6137 return found;
6138}
6139
96baa820
JM
6140static void
6141remote_rcmd (char *command,
d9fcf2fb 6142 struct ui_file *outbuf)
96baa820 6143{
d01949b6 6144 struct remote_state *rs = get_remote_state ();
2e9f7625 6145 char *p = rs->buf;
96baa820
JM
6146
6147 if (!remote_desc)
8a3fe4f8 6148 error (_("remote rcmd is only available after target open"));
96baa820 6149
23860348 6150 /* Send a NULL command across as an empty command. */
7be570e7
JM
6151 if (command == NULL)
6152 command = "";
6153
23860348 6154 /* The query prefix. */
2e9f7625
DJ
6155 strcpy (rs->buf, "qRcmd,");
6156 p = strchr (rs->buf, '\0');
96baa820 6157
2e9f7625 6158 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/) > get_remote_packet_size ())
8a3fe4f8 6159 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 6160
23860348 6161 /* Encode the actual command. */
cfd77fa1 6162 bin2hex ((gdb_byte *) command, p, 0);
96baa820 6163
6d820c5c 6164 if (putpkt (rs->buf) < 0)
8a3fe4f8 6165 error (_("Communication problem with target."));
96baa820
JM
6166
6167 /* get/display the response */
6168 while (1)
6169 {
2e9f7625
DJ
6170 char *buf;
6171
23860348 6172 /* XXX - see also tracepoint.c:remote_get_noisy_reply(). */
2e9f7625 6173 rs->buf[0] = '\0';
6d820c5c 6174 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 6175 buf = rs->buf;
96baa820 6176 if (buf[0] == '\0')
8a3fe4f8 6177 error (_("Target does not support this command."));
96baa820
JM
6178 if (buf[0] == 'O' && buf[1] != 'K')
6179 {
23860348 6180 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
6181 continue;
6182 }
6183 if (strcmp (buf, "OK") == 0)
6184 break;
7be570e7
JM
6185 if (strlen (buf) == 3 && buf[0] == 'E'
6186 && isdigit (buf[1]) && isdigit (buf[2]))
6187 {
8a3fe4f8 6188 error (_("Protocol error with Rcmd"));
7be570e7 6189 }
96baa820
JM
6190 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
6191 {
6192 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
6193 fputc_unfiltered (c, outbuf);
6194 }
6195 break;
6196 }
6197}
6198
fd79ecee
DJ
6199static VEC(mem_region_s) *
6200remote_memory_map (struct target_ops *ops)
6201{
6202 VEC(mem_region_s) *result = NULL;
6203 char *text = target_read_stralloc (&current_target,
6204 TARGET_OBJECT_MEMORY_MAP, NULL);
6205
6206 if (text)
6207 {
6208 struct cleanup *back_to = make_cleanup (xfree, text);
6209 result = parse_memory_map (text);
6210 do_cleanups (back_to);
6211 }
6212
6213 return result;
6214}
6215
c906108c 6216static void
fba45db2 6217packet_command (char *args, int from_tty)
c906108c 6218{
d01949b6 6219 struct remote_state *rs = get_remote_state ();
c906108c 6220
c5aa993b 6221 if (!remote_desc)
8a3fe4f8 6222 error (_("command can only be used with remote target"));
c906108c 6223
c5aa993b 6224 if (!args)
8a3fe4f8 6225 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
6226
6227 puts_filtered ("sending: ");
6228 print_packet (args);
6229 puts_filtered ("\n");
6230 putpkt (args);
6231
6d820c5c 6232 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 6233 puts_filtered ("received: ");
6d820c5c 6234 print_packet (rs->buf);
c906108c
SS
6235 puts_filtered ("\n");
6236}
6237
6238#if 0
23860348 6239/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 6240
a14ed312 6241static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 6242
a14ed312 6243static void threadset_test_cmd (char *cmd, int tty);
c906108c 6244
a14ed312 6245static void threadalive_test (char *cmd, int tty);
c906108c 6246
a14ed312 6247static void threadlist_test_cmd (char *cmd, int tty);
c906108c 6248
23860348 6249int get_and_display_threadinfo (threadref *ref);
c906108c 6250
a14ed312 6251static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 6252
23860348 6253static int thread_display_step (threadref *ref, void *context);
c906108c 6254
a14ed312 6255static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 6256
a14ed312 6257static void init_remote_threadtests (void);
c906108c 6258
23860348 6259#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
6260
6261static void
fba45db2 6262threadset_test_cmd (char *cmd, int tty)
c906108c
SS
6263{
6264 int sample_thread = SAMPLE_THREAD;
6265
a3f17187 6266 printf_filtered (_("Remote threadset test\n"));
79d7f229 6267 set_general_thread (sample_thread);
c906108c
SS
6268}
6269
6270
6271static void
fba45db2 6272threadalive_test (char *cmd, int tty)
c906108c
SS
6273{
6274 int sample_thread = SAMPLE_THREAD;
79d7f229
PA
6275 int pid = ptid_get_pid (inferior_ptid);
6276 ptid_t ptid = ptid_build (pid, 0, sample_thread);
c906108c 6277
79d7f229 6278 if (remote_thread_alive (ptid))
c906108c
SS
6279 printf_filtered ("PASS: Thread alive test\n");
6280 else
6281 printf_filtered ("FAIL: Thread alive test\n");
6282}
6283
23860348 6284void output_threadid (char *title, threadref *ref);
c906108c
SS
6285
6286void
fba45db2 6287output_threadid (char *title, threadref *ref)
c906108c
SS
6288{
6289 char hexid[20];
6290
23860348 6291 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
6292 hexid[16] = 0;
6293 printf_filtered ("%s %s\n", title, (&hexid[0]));
6294}
6295
6296static void
fba45db2 6297threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
6298{
6299 int startflag = 1;
6300 threadref nextthread;
6301 int done, result_count;
6302 threadref threadlist[3];
6303
6304 printf_filtered ("Remote Threadlist test\n");
6305 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
6306 &result_count, &threadlist[0]))
6307 printf_filtered ("FAIL: threadlist test\n");
6308 else
6309 {
6310 threadref *scan = threadlist;
6311 threadref *limit = scan + result_count;
6312
6313 while (scan < limit)
6314 output_threadid (" thread ", scan++);
6315 }
6316}
6317
6318void
fba45db2 6319display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
6320{
6321 output_threadid ("Threadid: ", &info->threadid);
6322 printf_filtered ("Name: %s\n ", info->shortname);
6323 printf_filtered ("State: %s\n", info->display);
6324 printf_filtered ("other: %s\n\n", info->more_display);
6325}
6326
6327int
fba45db2 6328get_and_display_threadinfo (threadref *ref)
c906108c
SS
6329{
6330 int result;
6331 int set;
6332 struct gdb_ext_thread_info threadinfo;
6333
6334 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
6335 | TAG_MOREDISPLAY | TAG_DISPLAY;
6336 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
6337 display_thread_info (&threadinfo);
6338 return result;
6339}
6340
6341static void
fba45db2 6342threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
6343{
6344 int athread = SAMPLE_THREAD;
6345 threadref thread;
6346 int set;
6347
6348 int_to_threadref (&thread, athread);
6349 printf_filtered ("Remote Threadinfo test\n");
6350 if (!get_and_display_threadinfo (&thread))
6351 printf_filtered ("FAIL cannot get thread info\n");
6352}
6353
6354static int
fba45db2 6355thread_display_step (threadref *ref, void *context)
c906108c
SS
6356{
6357 /* output_threadid(" threadstep ",ref); *//* simple test */
6358 return get_and_display_threadinfo (ref);
6359}
6360
6361static void
fba45db2 6362threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
6363{
6364 printf_filtered ("Remote Threadlist update test\n");
6365 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
6366}
6367
6368static void
6369init_remote_threadtests (void)
6370{
1bedd215
AC
6371 add_com ("tlist", class_obscure, threadlist_test_cmd, _("\
6372Fetch and print the remote list of thread identifiers, one pkt only"));
c906108c 6373 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 6374 _("Fetch and display info about one thread"));
c906108c 6375 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 6376 _("Test setting to a different thread"));
c906108c 6377 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 6378 _("Iterate through updating all remote thread info"));
c906108c 6379 add_com ("talive", class_obscure, threadalive_test,
1bedd215 6380 _(" Remote thread alive test "));
c906108c
SS
6381}
6382
6383#endif /* 0 */
6384
f3fb8c85
MS
6385/* Convert a thread ID to a string. Returns the string in a static
6386 buffer. */
6387
6388static char *
39f77062 6389remote_pid_to_str (ptid_t ptid)
f3fb8c85 6390{
79d7f229 6391 static char buf[64];
f3fb8c85 6392
79d7f229
PA
6393 if (ptid_equal (magic_null_ptid, ptid))
6394 {
6395 xsnprintf (buf, sizeof buf, "Thread <main>");
6396 return buf;
6397 }
6398 else if (ptid_get_tid (ptid) != 0)
6399 {
6400 xsnprintf (buf, sizeof buf, "Thread %ld",
6401 ptid_get_tid (ptid));
6402 return buf;
6403 }
6404
6405 return normal_pid_to_str (ptid);
f3fb8c85
MS
6406}
6407
38691318
KB
6408/* Get the address of the thread local variable in OBJFILE which is
6409 stored at OFFSET within the thread local storage for thread PTID. */
6410
6411static CORE_ADDR
6412remote_get_thread_local_address (ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
6413{
444abaca 6414 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
38691318
KB
6415 {
6416 struct remote_state *rs = get_remote_state ();
6d820c5c 6417 char *p = rs->buf;
571dd617 6418 enum packet_result result;
38691318
KB
6419
6420 strcpy (p, "qGetTLSAddr:");
6421 p += strlen (p);
79d7f229 6422 p += hexnumstr (p, ptid_get_tid (ptid));
38691318
KB
6423 *p++ = ',';
6424 p += hexnumstr (p, offset);
6425 *p++ = ',';
6426 p += hexnumstr (p, lm);
6427 *p++ = '\0';
6428
6d820c5c
DJ
6429 putpkt (rs->buf);
6430 getpkt (&rs->buf, &rs->buf_size, 0);
6431 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 6432 if (result == PACKET_OK)
38691318
KB
6433 {
6434 ULONGEST result;
6435
6d820c5c 6436 unpack_varlen_hex (rs->buf, &result);
38691318
KB
6437 return result;
6438 }
571dd617 6439 else if (result == PACKET_UNKNOWN)
109c3e39
AC
6440 throw_error (TLS_GENERIC_ERROR,
6441 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 6442 else
109c3e39
AC
6443 throw_error (TLS_GENERIC_ERROR,
6444 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
6445 }
6446 else
109c3e39
AC
6447 throw_error (TLS_GENERIC_ERROR,
6448 _("TLS not supported or disabled on this target"));
38691318
KB
6449 /* Not reached. */
6450 return 0;
6451}
6452
29709017
DJ
6453/* Support for inferring a target description based on the current
6454 architecture and the size of a 'g' packet. While the 'g' packet
6455 can have any size (since optional registers can be left off the
6456 end), some sizes are easily recognizable given knowledge of the
6457 approximate architecture. */
6458
6459struct remote_g_packet_guess
6460{
6461 int bytes;
6462 const struct target_desc *tdesc;
6463};
6464typedef struct remote_g_packet_guess remote_g_packet_guess_s;
6465DEF_VEC_O(remote_g_packet_guess_s);
6466
6467struct remote_g_packet_data
6468{
6469 VEC(remote_g_packet_guess_s) *guesses;
6470};
6471
6472static struct gdbarch_data *remote_g_packet_data_handle;
6473
6474static void *
6475remote_g_packet_data_init (struct obstack *obstack)
6476{
6477 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
6478}
6479
6480void
6481register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
6482 const struct target_desc *tdesc)
6483{
6484 struct remote_g_packet_data *data
6485 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
6486 struct remote_g_packet_guess new_guess, *guess;
6487 int ix;
6488
6489 gdb_assert (tdesc != NULL);
6490
6491 for (ix = 0;
6492 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
6493 ix++)
6494 if (guess->bytes == bytes)
6495 internal_error (__FILE__, __LINE__,
6496 "Duplicate g packet description added for size %d",
6497 bytes);
6498
6499 new_guess.bytes = bytes;
6500 new_guess.tdesc = tdesc;
6501 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
6502}
6503
6504static const struct target_desc *
6505remote_read_description (struct target_ops *target)
6506{
6507 struct remote_g_packet_data *data
6508 = gdbarch_data (current_gdbarch, remote_g_packet_data_handle);
6509
6510 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
6511 {
6512 struct remote_g_packet_guess *guess;
6513 int ix;
6514 int bytes = send_g_packet ();
6515
6516 for (ix = 0;
6517 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
6518 ix++)
6519 if (guess->bytes == bytes)
6520 return guess->tdesc;
6521
6522 /* We discard the g packet. A minor optimization would be to
6523 hold on to it, and fill the register cache once we have selected
6524 an architecture, but it's too tricky to do safely. */
6525 }
6526
6527 return NULL;
6528}
6529
a6b151f1
DJ
6530/* Remote file transfer support. This is host-initiated I/O, not
6531 target-initiated; for target-initiated, see remote-fileio.c. */
6532
6533/* If *LEFT is at least the length of STRING, copy STRING to
6534 *BUFFER, update *BUFFER to point to the new end of the buffer, and
6535 decrease *LEFT. Otherwise raise an error. */
6536
6537static void
6538remote_buffer_add_string (char **buffer, int *left, char *string)
6539{
6540 int len = strlen (string);
6541
6542 if (len > *left)
6543 error (_("Packet too long for target."));
6544
6545 memcpy (*buffer, string, len);
6546 *buffer += len;
6547 *left -= len;
6548
6549 /* NUL-terminate the buffer as a convenience, if there is
6550 room. */
6551 if (*left)
6552 **buffer = '\0';
6553}
6554
6555/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
6556 *BUFFER, update *BUFFER to point to the new end of the buffer, and
6557 decrease *LEFT. Otherwise raise an error. */
6558
6559static void
6560remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
6561 int len)
6562{
6563 if (2 * len > *left)
6564 error (_("Packet too long for target."));
6565
6566 bin2hex (bytes, *buffer, len);
6567 *buffer += 2 * len;
6568 *left -= 2 * len;
6569
6570 /* NUL-terminate the buffer as a convenience, if there is
6571 room. */
6572 if (*left)
6573 **buffer = '\0';
6574}
6575
6576/* If *LEFT is large enough, convert VALUE to hex and add it to
6577 *BUFFER, update *BUFFER to point to the new end of the buffer, and
6578 decrease *LEFT. Otherwise raise an error. */
6579
6580static void
6581remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
6582{
6583 int len = hexnumlen (value);
6584
6585 if (len > *left)
6586 error (_("Packet too long for target."));
6587
6588 hexnumstr (*buffer, value);
6589 *buffer += len;
6590 *left -= len;
6591
6592 /* NUL-terminate the buffer as a convenience, if there is
6593 room. */
6594 if (*left)
6595 **buffer = '\0';
6596}
6597
6598/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
6599 value, *REMOTE_ERRNO to the remote error number or zero if none
6600 was included, and *ATTACHMENT to point to the start of the annex
6601 if any. The length of the packet isn't needed here; there may
6602 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
6603
6604 Return 0 if the packet could be parsed, -1 if it could not. If
6605 -1 is returned, the other variables may not be initialized. */
6606
6607static int
6608remote_hostio_parse_result (char *buffer, int *retcode,
6609 int *remote_errno, char **attachment)
6610{
6611 char *p, *p2;
6612
6613 *remote_errno = 0;
6614 *attachment = NULL;
6615
6616 if (buffer[0] != 'F')
6617 return -1;
6618
6619 errno = 0;
6620 *retcode = strtol (&buffer[1], &p, 16);
6621 if (errno != 0 || p == &buffer[1])
6622 return -1;
6623
6624 /* Check for ",errno". */
6625 if (*p == ',')
6626 {
6627 errno = 0;
6628 *remote_errno = strtol (p + 1, &p2, 16);
6629 if (errno != 0 || p + 1 == p2)
6630 return -1;
6631 p = p2;
6632 }
6633
6634 /* Check for ";attachment". If there is no attachment, the
6635 packet should end here. */
6636 if (*p == ';')
6637 {
6638 *attachment = p + 1;
6639 return 0;
6640 }
6641 else if (*p == '\0')
6642 return 0;
6643 else
6644 return -1;
6645}
6646
6647/* Send a prepared I/O packet to the target and read its response.
6648 The prepared packet is in the global RS->BUF before this function
6649 is called, and the answer is there when we return.
6650
6651 COMMAND_BYTES is the length of the request to send, which may include
6652 binary data. WHICH_PACKET is the packet configuration to check
6653 before attempting a packet. If an error occurs, *REMOTE_ERRNO
6654 is set to the error number and -1 is returned. Otherwise the value
6655 returned by the function is returned.
6656
6657 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
6658 attachment is expected; an error will be reported if there's a
6659 mismatch. If one is found, *ATTACHMENT will be set to point into
6660 the packet buffer and *ATTACHMENT_LEN will be set to the
6661 attachment's length. */
6662
6663static int
6664remote_hostio_send_command (int command_bytes, int which_packet,
6665 int *remote_errno, char **attachment,
6666 int *attachment_len)
6667{
6668 struct remote_state *rs = get_remote_state ();
6669 int ret, bytes_read;
6670 char *attachment_tmp;
6671
6672 if (remote_protocol_packets[which_packet].support == PACKET_DISABLE)
6673 {
6674 *remote_errno = FILEIO_ENOSYS;
6675 return -1;
6676 }
6677
6678 putpkt_binary (rs->buf, command_bytes);
6679 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
6680
6681 /* If it timed out, something is wrong. Don't try to parse the
6682 buffer. */
6683 if (bytes_read < 0)
6684 {
6685 *remote_errno = FILEIO_EINVAL;
6686 return -1;
6687 }
6688
6689 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
6690 {
6691 case PACKET_ERROR:
6692 *remote_errno = FILEIO_EINVAL;
6693 return -1;
6694 case PACKET_UNKNOWN:
6695 *remote_errno = FILEIO_ENOSYS;
6696 return -1;
6697 case PACKET_OK:
6698 break;
6699 }
6700
6701 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
6702 &attachment_tmp))
6703 {
6704 *remote_errno = FILEIO_EINVAL;
6705 return -1;
6706 }
6707
6708 /* Make sure we saw an attachment if and only if we expected one. */
6709 if ((attachment_tmp == NULL && attachment != NULL)
6710 || (attachment_tmp != NULL && attachment == NULL))
6711 {
6712 *remote_errno = FILEIO_EINVAL;
6713 return -1;
6714 }
6715
6716 /* If an attachment was found, it must point into the packet buffer;
6717 work out how many bytes there were. */
6718 if (attachment_tmp != NULL)
6719 {
6720 *attachment = attachment_tmp;
6721 *attachment_len = bytes_read - (*attachment - rs->buf);
6722 }
6723
6724 return ret;
6725}
6726
6727/* Open FILENAME on the remote target, using FLAGS and MODE. Return a
6728 remote file descriptor, or -1 if an error occurs (and set
6729 *REMOTE_ERRNO). */
6730
6731static int
6732remote_hostio_open (const char *filename, int flags, int mode,
6733 int *remote_errno)
6734{
6735 struct remote_state *rs = get_remote_state ();
6736 char *p = rs->buf;
6737 int left = get_remote_packet_size () - 1;
6738
6739 remote_buffer_add_string (&p, &left, "vFile:open:");
6740
6741 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
6742 strlen (filename));
6743 remote_buffer_add_string (&p, &left, ",");
6744
6745 remote_buffer_add_int (&p, &left, flags);
6746 remote_buffer_add_string (&p, &left, ",");
6747
6748 remote_buffer_add_int (&p, &left, mode);
6749
6750 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
6751 remote_errno, NULL, NULL);
6752}
6753
6754/* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
6755 Return the number of bytes written, or -1 if an error occurs (and
6756 set *REMOTE_ERRNO). */
6757
6758static int
6759remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
6760 ULONGEST offset, int *remote_errno)
6761{
6762 struct remote_state *rs = get_remote_state ();
6763 char *p = rs->buf;
6764 int left = get_remote_packet_size ();
6765 int out_len;
6766
6767 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
6768
6769 remote_buffer_add_int (&p, &left, fd);
6770 remote_buffer_add_string (&p, &left, ",");
6771
6772 remote_buffer_add_int (&p, &left, offset);
6773 remote_buffer_add_string (&p, &left, ",");
6774
6775 p += remote_escape_output (write_buf, len, p, &out_len,
6776 get_remote_packet_size () - (p - rs->buf));
6777
6778 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
6779 remote_errno, NULL, NULL);
6780}
6781
6782/* Read up to LEN bytes FD on the remote target into READ_BUF
6783 Return the number of bytes read, or -1 if an error occurs (and
6784 set *REMOTE_ERRNO). */
6785
6786static int
6787remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
6788 ULONGEST offset, int *remote_errno)
6789{
6790 struct remote_state *rs = get_remote_state ();
6791 char *p = rs->buf;
6792 char *attachment;
6793 int left = get_remote_packet_size ();
6794 int ret, attachment_len;
6795 int read_len;
6796
6797 remote_buffer_add_string (&p, &left, "vFile:pread:");
6798
6799 remote_buffer_add_int (&p, &left, fd);
6800 remote_buffer_add_string (&p, &left, ",");
6801
6802 remote_buffer_add_int (&p, &left, len);
6803 remote_buffer_add_string (&p, &left, ",");
6804
6805 remote_buffer_add_int (&p, &left, offset);
6806
6807 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
6808 remote_errno, &attachment,
6809 &attachment_len);
6810
6811 if (ret < 0)
6812 return ret;
6813
6814 read_len = remote_unescape_input (attachment, attachment_len,
6815 read_buf, len);
6816 if (read_len != ret)
6817 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
6818
6819 return ret;
6820}
6821
6822/* Close FD on the remote target. Return 0, or -1 if an error occurs
6823 (and set *REMOTE_ERRNO). */
6824
6825static int
6826remote_hostio_close (int fd, int *remote_errno)
6827{
6828 struct remote_state *rs = get_remote_state ();
6829 char *p = rs->buf;
6830 int left = get_remote_packet_size () - 1;
6831
6832 remote_buffer_add_string (&p, &left, "vFile:close:");
6833
6834 remote_buffer_add_int (&p, &left, fd);
6835
6836 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
6837 remote_errno, NULL, NULL);
6838}
6839
6840/* Unlink FILENAME on the remote target. Return 0, or -1 if an error
6841 occurs (and set *REMOTE_ERRNO). */
6842
6843static int
6844remote_hostio_unlink (const char *filename, int *remote_errno)
6845{
6846 struct remote_state *rs = get_remote_state ();
6847 char *p = rs->buf;
6848 int left = get_remote_packet_size () - 1;
6849
6850 remote_buffer_add_string (&p, &left, "vFile:unlink:");
6851
6852 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
6853 strlen (filename));
6854
6855 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
6856 remote_errno, NULL, NULL);
6857}
6858
6859static int
6860remote_fileio_errno_to_host (int errnum)
6861{
6862 switch (errnum)
6863 {
6864 case FILEIO_EPERM:
6865 return EPERM;
6866 case FILEIO_ENOENT:
6867 return ENOENT;
6868 case FILEIO_EINTR:
6869 return EINTR;
6870 case FILEIO_EIO:
6871 return EIO;
6872 case FILEIO_EBADF:
6873 return EBADF;
6874 case FILEIO_EACCES:
6875 return EACCES;
6876 case FILEIO_EFAULT:
6877 return EFAULT;
6878 case FILEIO_EBUSY:
6879 return EBUSY;
6880 case FILEIO_EEXIST:
6881 return EEXIST;
6882 case FILEIO_ENODEV:
6883 return ENODEV;
6884 case FILEIO_ENOTDIR:
6885 return ENOTDIR;
6886 case FILEIO_EISDIR:
6887 return EISDIR;
6888 case FILEIO_EINVAL:
6889 return EINVAL;
6890 case FILEIO_ENFILE:
6891 return ENFILE;
6892 case FILEIO_EMFILE:
6893 return EMFILE;
6894 case FILEIO_EFBIG:
6895 return EFBIG;
6896 case FILEIO_ENOSPC:
6897 return ENOSPC;
6898 case FILEIO_ESPIPE:
6899 return ESPIPE;
6900 case FILEIO_EROFS:
6901 return EROFS;
6902 case FILEIO_ENOSYS:
6903 return ENOSYS;
6904 case FILEIO_ENAMETOOLONG:
6905 return ENAMETOOLONG;
6906 }
6907 return -1;
6908}
6909
6910static char *
6911remote_hostio_error (int errnum)
6912{
6913 int host_error = remote_fileio_errno_to_host (errnum);
6914
6915 if (host_error == -1)
6916 error (_("Unknown remote I/O error %d"), errnum);
6917 else
6918 error (_("Remote I/O error: %s"), safe_strerror (host_error));
6919}
6920
6921static void
6922fclose_cleanup (void *file)
6923{
6924 fclose (file);
6925}
6926
6927static void
6928remote_hostio_close_cleanup (void *opaque)
6929{
6930 int fd = *(int *) opaque;
6931 int remote_errno;
6932
6933 remote_hostio_close (fd, &remote_errno);
6934}
6935
6936void
6937remote_file_put (const char *local_file, const char *remote_file, int from_tty)
6938{
6939 struct cleanup *back_to, *close_cleanup;
6940 int retcode, fd, remote_errno, bytes, io_size;
6941 FILE *file;
6942 gdb_byte *buffer;
6943 int bytes_in_buffer;
6944 int saw_eof;
6945 ULONGEST offset;
6946
6947 if (!remote_desc)
6948 error (_("command can only be used with remote target"));
6949
6950 file = fopen (local_file, "rb");
6951 if (file == NULL)
6952 perror_with_name (local_file);
6953 back_to = make_cleanup (fclose_cleanup, file);
6954
6955 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
6956 | FILEIO_O_TRUNC),
6957 0700, &remote_errno);
6958 if (fd == -1)
6959 remote_hostio_error (remote_errno);
6960
6961 /* Send up to this many bytes at once. They won't all fit in the
6962 remote packet limit, so we'll transfer slightly fewer. */
6963 io_size = get_remote_packet_size ();
6964 buffer = xmalloc (io_size);
6965 make_cleanup (xfree, buffer);
6966
6967 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
6968
6969 bytes_in_buffer = 0;
6970 saw_eof = 0;
6971 offset = 0;
6972 while (bytes_in_buffer || !saw_eof)
6973 {
6974 if (!saw_eof)
6975 {
6976 bytes = fread (buffer + bytes_in_buffer, 1, io_size - bytes_in_buffer,
6977 file);
6978 if (bytes == 0)
6979 {
6980 if (ferror (file))
6981 error (_("Error reading %s."), local_file);
6982 else
6983 {
6984 /* EOF. Unless there is something still in the
6985 buffer from the last iteration, we are done. */
6986 saw_eof = 1;
6987 if (bytes_in_buffer == 0)
6988 break;
6989 }
6990 }
6991 }
6992 else
6993 bytes = 0;
6994
6995 bytes += bytes_in_buffer;
6996 bytes_in_buffer = 0;
6997
6998 retcode = remote_hostio_pwrite (fd, buffer, bytes, offset, &remote_errno);
6999
7000 if (retcode < 0)
7001 remote_hostio_error (remote_errno);
7002 else if (retcode == 0)
7003 error (_("Remote write of %d bytes returned 0!"), bytes);
7004 else if (retcode < bytes)
7005 {
7006 /* Short write. Save the rest of the read data for the next
7007 write. */
7008 bytes_in_buffer = bytes - retcode;
7009 memmove (buffer, buffer + retcode, bytes_in_buffer);
7010 }
7011
7012 offset += retcode;
7013 }
7014
7015 discard_cleanups (close_cleanup);
7016 if (remote_hostio_close (fd, &remote_errno))
7017 remote_hostio_error (remote_errno);
7018
7019 if (from_tty)
7020 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
7021 do_cleanups (back_to);
7022}
7023
7024void
7025remote_file_get (const char *remote_file, const char *local_file, int from_tty)
7026{
7027 struct cleanup *back_to, *close_cleanup;
7028 int retcode, fd, remote_errno, bytes, io_size;
7029 FILE *file;
7030 gdb_byte *buffer;
7031 ULONGEST offset;
7032
7033 if (!remote_desc)
7034 error (_("command can only be used with remote target"));
7035
7036 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
7037 if (fd == -1)
7038 remote_hostio_error (remote_errno);
7039
7040 file = fopen (local_file, "wb");
7041 if (file == NULL)
7042 perror_with_name (local_file);
7043 back_to = make_cleanup (fclose_cleanup, file);
7044
7045 /* Send up to this many bytes at once. They won't all fit in the
7046 remote packet limit, so we'll transfer slightly fewer. */
7047 io_size = get_remote_packet_size ();
7048 buffer = xmalloc (io_size);
7049 make_cleanup (xfree, buffer);
7050
7051 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
7052
7053 offset = 0;
7054 while (1)
7055 {
7056 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
7057 if (bytes == 0)
7058 /* Success, but no bytes, means end-of-file. */
7059 break;
7060 if (bytes == -1)
7061 remote_hostio_error (remote_errno);
7062
7063 offset += bytes;
7064
7065 bytes = fwrite (buffer, 1, bytes, file);
7066 if (bytes == 0)
7067 perror_with_name (local_file);
7068 }
7069
7070 discard_cleanups (close_cleanup);
7071 if (remote_hostio_close (fd, &remote_errno))
7072 remote_hostio_error (remote_errno);
7073
7074 if (from_tty)
7075 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
7076 do_cleanups (back_to);
7077}
7078
7079void
7080remote_file_delete (const char *remote_file, int from_tty)
7081{
7082 int retcode, remote_errno;
7083
7084 if (!remote_desc)
7085 error (_("command can only be used with remote target"));
7086
7087 retcode = remote_hostio_unlink (remote_file, &remote_errno);
7088 if (retcode == -1)
7089 remote_hostio_error (remote_errno);
7090
7091 if (from_tty)
7092 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
7093}
7094
7095static void
7096remote_put_command (char *args, int from_tty)
7097{
7098 struct cleanup *back_to;
7099 char **argv;
7100
7101 argv = buildargv (args);
7102 if (argv == NULL)
7103 nomem (0);
7104 back_to = make_cleanup_freeargv (argv);
7105 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
7106 error (_("Invalid parameters to remote put"));
7107
7108 remote_file_put (argv[0], argv[1], from_tty);
7109
7110 do_cleanups (back_to);
7111}
7112
7113static void
7114remote_get_command (char *args, int from_tty)
7115{
7116 struct cleanup *back_to;
7117 char **argv;
7118
7119 argv = buildargv (args);
7120 if (argv == NULL)
7121 nomem (0);
7122 back_to = make_cleanup_freeargv (argv);
7123 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
7124 error (_("Invalid parameters to remote get"));
7125
7126 remote_file_get (argv[0], argv[1], from_tty);
7127
7128 do_cleanups (back_to);
7129}
7130
7131static void
7132remote_delete_command (char *args, int from_tty)
7133{
7134 struct cleanup *back_to;
7135 char **argv;
7136
7137 argv = buildargv (args);
7138 if (argv == NULL)
7139 nomem (0);
7140 back_to = make_cleanup_freeargv (argv);
7141 if (argv[0] == NULL || argv[1] != NULL)
7142 error (_("Invalid parameters to remote delete"));
7143
7144 remote_file_delete (argv[0], from_tty);
7145
7146 do_cleanups (back_to);
7147}
7148
7149static void
7150remote_command (char *args, int from_tty)
7151{
7152 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
7153}
7154
c906108c 7155static void
fba45db2 7156init_remote_ops (void)
c906108c 7157{
c5aa993b 7158 remote_ops.to_shortname = "remote";
c906108c 7159 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 7160 remote_ops.to_doc =
c906108c 7161 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
7162Specify the serial device it is connected to\n\
7163(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
7164 remote_ops.to_open = remote_open;
7165 remote_ops.to_close = remote_close;
c906108c 7166 remote_ops.to_detach = remote_detach;
6ad8ae5c 7167 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 7168 remote_ops.to_resume = remote_resume;
c906108c
SS
7169 remote_ops.to_wait = remote_wait;
7170 remote_ops.to_fetch_registers = remote_fetch_registers;
7171 remote_ops.to_store_registers = remote_store_registers;
7172 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c8e73a31 7173 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
c5aa993b 7174 remote_ops.to_files_info = remote_files_info;
c906108c
SS
7175 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
7176 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
3c3bea1c
GS
7177 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
7178 remote_ops.to_stopped_data_address = remote_stopped_data_address;
7179 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
7180 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
7181 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
7182 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
7183 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b
JM
7184 remote_ops.to_kill = remote_kill;
7185 remote_ops.to_load = generic_load;
c906108c
SS
7186 remote_ops.to_mourn_inferior = remote_mourn;
7187 remote_ops.to_thread_alive = remote_thread_alive;
0f71a2f6 7188 remote_ops.to_find_new_threads = remote_threads_info;
0caabb7e 7189 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 7190 remote_ops.to_extra_thread_info = remote_threads_extra_info;
c906108c 7191 remote_ops.to_stop = remote_stop;
4b8a223f 7192 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 7193 remote_ops.to_rcmd = remote_rcmd;
49d03eab 7194 remote_ops.to_log_command = serial_log_command;
38691318 7195 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 7196 remote_ops.to_stratum = process_stratum;
c5aa993b
JM
7197 remote_ops.to_has_all_memory = 1;
7198 remote_ops.to_has_memory = 1;
7199 remote_ops.to_has_stack = 1;
7200 remote_ops.to_has_registers = 1;
7201 remote_ops.to_has_execution = 1;
7202 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
7203 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 7204 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
7205 remote_ops.to_flash_erase = remote_flash_erase;
7206 remote_ops.to_flash_done = remote_flash_done;
29709017 7207 remote_ops.to_read_description = remote_read_description;
08388c79 7208 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
7209 remote_ops.to_can_async_p = remote_can_async_p;
7210 remote_ops.to_is_async_p = remote_is_async_p;
7211 remote_ops.to_async = remote_async;
7212 remote_ops.to_async_mask = remote_async_mask;
7213 remote_ops.to_terminal_inferior = remote_terminal_inferior;
7214 remote_ops.to_terminal_ours = remote_terminal_ours;
c906108c
SS
7215}
7216
7217/* Set up the extended remote vector by making a copy of the standard
7218 remote vector and adding to it. */
7219
7220static void
fba45db2 7221init_extended_remote_ops (void)
c906108c
SS
7222{
7223 extended_remote_ops = remote_ops;
7224
0f71a2f6 7225 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 7226 extended_remote_ops.to_longname =
c906108c 7227 "Extended remote serial target in gdb-specific protocol";
c5aa993b 7228 extended_remote_ops.to_doc =
c906108c 7229 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
7230Specify the serial device it is connected to (e.g. /dev/ttya).";
7231 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
7232 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
7233 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
7234 extended_remote_ops.to_detach = extended_remote_detach;
7235 extended_remote_ops.to_attach = extended_remote_attach;
0f71a2f6
JM
7236}
7237
6426a772
JM
7238static int
7239remote_can_async_p (void)
7240{
c6ebd6cf 7241 if (!target_async_permitted)
75c99385
PA
7242 /* We only enable async when the user specifically asks for it. */
7243 return 0;
7244
23860348 7245 /* We're async whenever the serial device is. */
b84876c2 7246 return remote_async_mask_value && serial_can_async_p (remote_desc);
6426a772
JM
7247}
7248
7249static int
7250remote_is_async_p (void)
7251{
c6ebd6cf 7252 if (!target_async_permitted)
75c99385
PA
7253 /* We only enable async when the user specifically asks for it. */
7254 return 0;
7255
23860348 7256 /* We're async whenever the serial device is. */
b84876c2 7257 return remote_async_mask_value && serial_is_async_p (remote_desc);
6426a772
JM
7258}
7259
2acceee2
JM
7260/* Pass the SERIAL event on and up to the client. One day this code
7261 will be able to delay notifying the client of an event until the
23860348 7262 point where an entire packet has been received. */
2acceee2 7263
2bc416ba 7264static void (*async_client_callback) (enum inferior_event_type event_type,
23860348 7265 void *context);
2acceee2
JM
7266static void *async_client_context;
7267static serial_event_ftype remote_async_serial_handler;
7268
6426a772 7269static void
819cc324 7270remote_async_serial_handler (struct serial *scb, void *context)
6426a772 7271{
2acceee2
JM
7272 /* Don't propogate error information up to the client. Instead let
7273 the client find out about the error by querying the target. */
7274 async_client_callback (INF_REG_EVENT, async_client_context);
7275}
7276
7277static void
2bc416ba 7278remote_async (void (*callback) (enum inferior_event_type event_type,
23860348 7279 void *context), void *context)
2acceee2 7280{
b84876c2 7281 if (remote_async_mask_value == 0)
8e65ff28 7282 internal_error (__FILE__, __LINE__,
e2e0b3e5 7283 _("Calling remote_async when async is masked"));
ed9a39eb 7284
2acceee2
JM
7285 if (callback != NULL)
7286 {
2cd58942 7287 serial_async (remote_desc, remote_async_serial_handler, NULL);
2acceee2
JM
7288 async_client_callback = callback;
7289 async_client_context = context;
7290 }
7291 else
2cd58942 7292 serial_async (remote_desc, NULL, NULL);
6426a772
JM
7293}
7294
b84876c2
PA
7295static int
7296remote_async_mask (int new_mask)
7297{
7298 int curr_mask = remote_async_mask_value;
7299 remote_async_mask_value = new_mask;
7300 return curr_mask;
7301}
7302
5a2468f5 7303static void
c2d11a7d 7304set_remote_cmd (char *args, int from_tty)
5a2468f5 7305{
427c3a89 7306 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
5a2468f5
JM
7307}
7308
d471ea57
AC
7309static void
7310show_remote_cmd (char *args, int from_tty)
7311{
37a105a1 7312 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 7313 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
7314 struct cleanup *showlist_chain;
7315 struct cmd_list_element *list = remote_show_cmdlist;
7316
7317 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
7318 for (; list != NULL; list = list->next)
7319 if (strcmp (list->name, "Z-packet") == 0)
7320 continue;
427c3a89
DJ
7321 else if (list->type == not_set_cmd)
7322 /* Alias commands are exactly like the original, except they
7323 don't have the normal type. */
7324 continue;
7325 else
37a105a1
DJ
7326 {
7327 struct cleanup *option_chain
7328 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
7329 ui_out_field_string (uiout, "name", list->name);
7330 ui_out_text (uiout, ": ");
427c3a89
DJ
7331 if (list->type == show_cmd)
7332 do_setshow_command ((char *) NULL, from_tty, list);
7333 else
7334 cmd_func (list, NULL, from_tty);
37a105a1
DJ
7335 /* Close the tuple. */
7336 do_cleanups (option_chain);
7337 }
427c3a89
DJ
7338
7339 /* Close the tuple. */
7340 do_cleanups (showlist_chain);
d471ea57 7341}
5a2468f5 7342
0f71a2f6 7343
23860348 7344/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
7345static void
7346remote_new_objfile (struct objfile *objfile)
7347{
23860348 7348 if (remote_desc != 0) /* Have a remote connection. */
06d3b283 7349 remote_check_symbols (objfile);
dc8acb97
MS
7350}
7351
c906108c 7352void
fba45db2 7353_initialize_remote (void)
c906108c 7354{
ea9c271d
DJ
7355 struct remote_state *rs;
7356
0f71a2f6 7357 /* architecture specific data */
2bc416ba 7358 remote_gdbarch_data_handle =
23860348 7359 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
7360 remote_g_packet_data_handle =
7361 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 7362
ea9c271d
DJ
7363 /* Initialize the per-target state. At the moment there is only one
7364 of these, not one per target. Only one target is active at a
7365 time. The default buffer size is unimportant; it will be expanded
7366 whenever a larger buffer is needed. */
0b83947e 7367 rs = get_remote_state_raw ();
ea9c271d
DJ
7368 rs->buf_size = 400;
7369 rs->buf = xmalloc (rs->buf_size);
7370
c906108c
SS
7371 init_remote_ops ();
7372 add_target (&remote_ops);
7373
7374 init_extended_remote_ops ();
7375 add_target (&extended_remote_ops);
cce74817 7376
dc8acb97 7377 /* Hook into new objfile notification. */
06d3b283 7378 observer_attach_new_objfile (remote_new_objfile);
dc8acb97 7379
b803fb0f
DJ
7380 /* Set up signal handlers. */
7381 sigint_remote_token =
7382 create_async_signal_handler (async_remote_interrupt, NULL);
7383 sigint_remote_twice_token =
7384 create_async_signal_handler (inferior_event_handler_wrapper, NULL);
7385
c906108c
SS
7386#if 0
7387 init_remote_threadtests ();
7388#endif
7389
23860348 7390 /* set/show remote ... */
d471ea57 7391
1bedd215 7392 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
7393Remote protocol specific variables\n\
7394Configure various remote-protocol specific variables such as\n\
1bedd215 7395the packets being used"),
cff3e48b 7396 &remote_set_cmdlist, "set remote ",
23860348 7397 0 /* allow-unknown */, &setlist);
1bedd215 7398 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
7399Remote protocol specific variables\n\
7400Configure various remote-protocol specific variables such as\n\
1bedd215 7401the packets being used"),
cff3e48b 7402 &remote_show_cmdlist, "show remote ",
23860348 7403 0 /* allow-unknown */, &showlist);
5a2468f5 7404
1a966eab
AC
7405 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
7406Compare section data on target to the exec file.\n\
7407Argument is a single section name (default: all loaded sections)."),
c906108c
SS
7408 &cmdlist);
7409
1a966eab
AC
7410 add_cmd ("packet", class_maintenance, packet_command, _("\
7411Send an arbitrary packet to a remote target.\n\
c906108c
SS
7412 maintenance packet TEXT\n\
7413If GDB is talking to an inferior via the GDB serial protocol, then\n\
7414this command sends the string TEXT to the inferior, and displays the\n\
7415response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 7416terminating `#' character and checksum."),
c906108c
SS
7417 &maintenancelist);
7418
7915a72c
AC
7419 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
7420Set whether to send break if interrupted."), _("\
7421Show whether to send break if interrupted."), _("\
7422If set, a break, instead of a cntrl-c, is sent to the remote target."),
2c5b56ce 7423 NULL, NULL, /* FIXME: i18n: Whether to send break if interrupted is %s. */
e707bbc2 7424 &setlist, &showlist);
c906108c 7425
23860348 7426 /* Install commands for configuring memory read/write packets. */
11cf8741 7427
1a966eab
AC
7428 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
7429Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 7430 &setlist);
1a966eab
AC
7431 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
7432Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
7433 &showlist);
7434 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
7435 set_memory_write_packet_size, _("\
7436Set the maximum number of bytes per memory-write packet.\n\
7437Specify the number of bytes in a packet or 0 (zero) for the\n\
7438default packet size. The actual limit is further reduced\n\
7439dependent on the target. Specify ``fixed'' to disable the\n\
7440further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
7441 &remote_set_cmdlist);
7442 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
7443 set_memory_read_packet_size, _("\
7444Set the maximum number of bytes per memory-read packet.\n\
7445Specify the number of bytes in a packet or 0 (zero) for the\n\
7446default packet size. The actual limit is further reduced\n\
7447dependent on the target. Specify ``fixed'' to disable the\n\
7448further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
7449 &remote_set_cmdlist);
7450 add_cmd ("memory-write-packet-size", no_class,
7451 show_memory_write_packet_size,
1a966eab 7452 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
7453 &remote_show_cmdlist);
7454 add_cmd ("memory-read-packet-size", no_class,
7455 show_memory_read_packet_size,
1a966eab 7456 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 7457 &remote_show_cmdlist);
c906108c 7458
b3f42336 7459 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
7460 &remote_hw_watchpoint_limit, _("\
7461Set the maximum number of target hardware watchpoints."), _("\
7462Show the maximum number of target hardware watchpoints."), _("\
7463Specify a negative limit for unlimited."),
2c5b56ce 7464 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware watchpoints is %s. */
b3f42336
AC
7465 &remote_set_cmdlist, &remote_show_cmdlist);
7466 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
7467 &remote_hw_breakpoint_limit, _("\
7468Set the maximum number of target hardware breakpoints."), _("\
7469Show the maximum number of target hardware breakpoints."), _("\
7470Specify a negative limit for unlimited."),
2c5b56ce 7471 NULL, NULL, /* FIXME: i18n: The maximum number of target hardware breakpoints is %s. */
b3f42336 7472 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 7473
4d28ad1e
AC
7474 add_setshow_integer_cmd ("remoteaddresssize", class_obscure,
7475 &remote_address_size, _("\
7476Set the maximum size of the address (in bits) in a memory packet."), _("\
7477Show the maximum size of the address (in bits) in a memory packet."), NULL,
7478 NULL,
7479 NULL, /* FIXME: i18n: */
7480 &setlist, &showlist);
c906108c 7481
444abaca 7482 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 7483 "X", "binary-download", 1);
0f71a2f6 7484
444abaca 7485 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 7486 "vCont", "verbose-resume", 0);
506fb367 7487
89be2091
DJ
7488 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
7489 "QPassSignals", "pass-signals", 0);
7490
444abaca 7491 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 7492 "qSymbol", "symbol-lookup", 0);
dc8acb97 7493
444abaca 7494 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 7495 "P", "set-register", 1);
d471ea57 7496
444abaca 7497 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 7498 "p", "fetch-register", 1);
b96ec7ac 7499
444abaca 7500 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 7501 "Z0", "software-breakpoint", 0);
d471ea57 7502
444abaca 7503 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 7504 "Z1", "hardware-breakpoint", 0);
d471ea57 7505
444abaca 7506 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 7507 "Z2", "write-watchpoint", 0);
d471ea57 7508
444abaca 7509 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 7510 "Z3", "read-watchpoint", 0);
d471ea57 7511
444abaca 7512 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 7513 "Z4", "access-watchpoint", 0);
d471ea57 7514
0876f84a
DJ
7515 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
7516 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 7517
23181151
DJ
7518 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
7519 "qXfer:features:read", "target-features", 0);
7520
cfa9d6d9
DJ
7521 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
7522 "qXfer:libraries:read", "library-info", 0);
7523
fd79ecee
DJ
7524 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
7525 "qXfer:memory-map:read", "memory-map", 0);
7526
0e7f50da
UW
7527 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
7528 "qXfer:spu:read", "read-spu-object", 0);
7529
7530 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
7531 "qXfer:spu:write", "write-spu-object", 0);
7532
444abaca 7533 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 7534 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
7535 0);
7536
be2a5f71
DJ
7537 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
7538 "qSupported", "supported-packets", 0);
7539
08388c79
DE
7540 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
7541 "qSearch:memory", "search-memory", 0);
7542
a6b151f1
DJ
7543 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
7544 "vFile:open", "hostio-open", 0);
7545
7546 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
7547 "vFile:pread", "hostio-pread", 0);
7548
7549 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
7550 "vFile:pwrite", "hostio-pwrite", 0);
7551
7552 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
7553 "vFile:close", "hostio-close", 0);
7554
7555 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
7556 "vFile:unlink", "hostio-unlink", 0);
7557
2d717e4f
DJ
7558 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
7559 "vAttach", "attach", 0);
7560
7561 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
7562 "vRun", "run", 0);
7563
a6f3e723
SL
7564 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
7565 "QStartNoAckMode", "noack", 0);
7566
37a105a1
DJ
7567 /* Keep the old ``set remote Z-packet ...'' working. Each individual
7568 Z sub-packet has its own set and show commands, but users may
7569 have sets to this variable in their .gdbinit files (or in their
7570 documentation). */
e9e68a56 7571 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
7572 &remote_Z_packet_detect, _("\
7573Set use of remote protocol `Z' packets"), _("\
7574Show use of remote protocol `Z' packets "), _("\
3b64bf98 7575When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 7576packets."),
e9e68a56 7577 set_remote_protocol_Z_packet_cmd,
2c5b56ce 7578 show_remote_protocol_Z_packet_cmd, /* FIXME: i18n: Use of remote protocol `Z' packets is %s. */
e9e68a56 7579 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 7580
a6b151f1
DJ
7581 add_prefix_cmd ("remote", class_files, remote_command, _("\
7582Manipulate files on the remote system\n\
7583Transfer files to and from the remote target system."),
7584 &remote_cmdlist, "remote ",
7585 0 /* allow-unknown */, &cmdlist);
7586
7587 add_cmd ("put", class_files, remote_put_command,
7588 _("Copy a local file to the remote system."),
7589 &remote_cmdlist);
7590
7591 add_cmd ("get", class_files, remote_get_command,
7592 _("Copy a remote file to the local system."),
7593 &remote_cmdlist);
7594
7595 add_cmd ("delete", class_files, remote_delete_command,
7596 _("Delete a remote file."),
7597 &remote_cmdlist);
7598
2d717e4f
DJ
7599 remote_exec_file = xstrdup ("");
7600 add_setshow_string_noescape_cmd ("exec-file", class_files,
7601 &remote_exec_file, _("\
7602Set the remote pathname for \"run\""), _("\
7603Show the remote pathname for \"run\""), NULL, NULL, NULL,
7604 &remote_set_cmdlist, &remote_show_cmdlist);
7605
449092f6
CV
7606 /* Eventually initialize fileio. See fileio.c */
7607 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229
PA
7608
7609 /* Take advantage of the fact that the LWP field is not used, to tag
7610 special ptids with it set to != 0. */
7611 magic_null_ptid = ptid_build (0, 1, -1);
7612 not_sent_ptid = ptid_build (0, 1, -2);
7613 any_thread_ptid = ptid_build (0, 1, 0);
c906108c 7614}