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