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