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