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