]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
quit_force: Replace TRY_CATCH wrapper macros
[thirdparty/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
32d0add0 3 Copyright (C) 1988-2015 Free Software Foundation, Inc.
c906108c 4
c5aa993b
JM
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
c5aa993b
JM
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5aa993b 19
23860348 20/* See the GDB User Guide for details of the GDB remote protocol. */
c5aa993b 21
c906108c 22#include "defs.h"
c906108c
SS
23#include <ctype.h>
24#include <fcntl.h>
c906108c 25#include "inferior.h"
45741a9c 26#include "infrun.h"
c906108c
SS
27#include "bfd.h"
28#include "symfile.h"
29#include "target.h"
c5aa993b 30/*#include "terminal.h" */
c906108c
SS
31#include "gdbcmd.h"
32#include "objfiles.h"
33#include "gdb-stabs.h"
34#include "gdbthread.h"
c2c6d25f 35#include "remote.h"
722247f1 36#include "remote-notif.h"
4e052eda 37#include "regcache.h"
fd0407d6 38#include "value.h"
6867ae3e 39#include "observer.h"
a77053c2 40#include "solib.h"
37a105a1
DJ
41#include "cli/cli-decode.h"
42#include "cli/cli-setshow.h"
424163ea 43#include "target-descriptions.h"
a4453b7e 44#include "gdb_bfd.h"
614c279d 45#include "filestuff.h"
9c3d6531 46#include "rsp-low.h"
c906108c 47
9846de1b 48#include <sys/time.h>
c906108c 49
43ff13b4 50#include "event-loop.h"
c2c6d25f 51#include "event-top.h"
2acceee2 52#include "inf-loop.h"
43ff13b4 53
c906108c
SS
54#include <signal.h>
55#include "serial.h"
56
6240bebf
MS
57#include "gdbcore.h" /* for exec_bfd */
58
449092f6 59#include "remote-fileio.h"
a6b151f1 60#include "gdb/fileio.h"
53ce3c39 61#include <sys/stat.h>
dc146f7c 62#include "xml-support.h"
449092f6 63
fd79ecee
DJ
64#include "memory-map.h"
65
35b1e5cc
SS
66#include "tracepoint.h"
67#include "ax.h"
68#include "ax-gdb.h"
d1feda86 69#include "agent.h"
9accd112 70#include "btrace.h"
35b1e5cc 71
0df8b418 72/* Temp hacks for tracepoint encoding migration. */
35b1e5cc
SS
73static char *target_buf;
74static long target_buf_size;
35b1e5cc 75
6765f3e5
DJ
76/* The size to align memory write packets, when practical. The protocol
77 does not guarantee any alignment, and gdb will generate short
78 writes and unaligned writes, but even as a best-effort attempt this
79 can improve bulk transfers. For instance, if a write is misaligned
80 relative to the target's data bus, the stub may need to make an extra
81 round trip fetching data from the target. This doesn't make a
82 huge difference, but it's easy to do, so we try to be helpful.
83
84 The alignment chosen is arbitrary; usually data bus width is
85 important here, not the possibly larger cache line size. */
86enum { REMOTE_ALIGN_WRITES = 16 };
87
23860348 88/* Prototypes for local functions. */
934b9bac 89static void async_cleanup_sigint_signal_handler (void *dummy);
6d820c5c 90static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
74531fed 91static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
fee9eda9 92 int forever, int *is_notif);
6426a772 93
934b9bac
JK
94static void async_handle_remote_sigint (int);
95static void async_handle_remote_sigint_twice (int);
43ff13b4 96
a14ed312 97static void remote_files_info (struct target_ops *ignore);
c906108c 98
f32dbf8c
MM
99static void remote_prepare_to_store (struct target_ops *self,
100 struct regcache *regcache);
c906108c 101
014f9477
TT
102static void remote_open_1 (const char *, int, struct target_ops *,
103 int extended_p);
c906108c 104
de90e03d 105static void remote_close (struct target_ops *self);
c906108c 106
136d6dae 107static void remote_mourn (struct target_ops *ops);
c906108c 108
a14ed312 109static void extended_remote_restart (void);
c906108c 110
136d6dae 111static void extended_remote_mourn (struct target_ops *);
c906108c 112
a14ed312 113static void remote_mourn_1 (struct target_ops *);
c906108c 114
6d820c5c 115static void remote_send (char **buf, long *sizeof_buf_p);
c906108c 116
a14ed312 117static int readchar (int timeout);
c906108c 118
c33e31fd
PA
119static void remote_serial_write (const char *str, int len);
120
7d85a9c0 121static void remote_kill (struct target_ops *ops);
c906108c 122
6a109b6b 123static int remote_can_async_p (struct target_ops *);
75c99385 124
6a109b6b 125static int remote_is_async_p (struct target_ops *);
75c99385 126
6a109b6b
TT
127static void remote_async (struct target_ops *ops,
128 void (*callback) (enum inferior_event_type event_type,
129 void *context),
130 void *context);
75c99385 131
934b9bac 132static void sync_remote_interrupt_twice (int signo);
7a292a7a 133
a14ed312 134static void interrupt_query (void);
c906108c 135
79d7f229
PA
136static void set_general_thread (struct ptid ptid);
137static void set_continue_thread (struct ptid ptid);
c906108c 138
a14ed312 139static void get_offsets (void);
c906108c 140
6d820c5c
DJ
141static void skip_frame (void);
142
143static long read_frame (char **buf_p, long *sizeof_buf);
c906108c 144
a14ed312 145static int hexnumlen (ULONGEST num);
c906108c 146
a14ed312 147static void init_remote_ops (void);
c906108c 148
a14ed312 149static void init_extended_remote_ops (void);
c906108c 150
1eab8a48 151static void remote_stop (struct target_ops *self, ptid_t);
c906108c 152
a14ed312 153static int stubhex (int ch);
c906108c 154
a14ed312 155static int hexnumstr (char *, ULONGEST);
c906108c 156
a14ed312 157static int hexnumnstr (char *, ULONGEST, int);
2df3850c 158
a14ed312 159static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 160
baa336ce 161static void print_packet (const char *);
c906108c 162
a14ed312 163static void compare_sections_command (char *, int);
c906108c 164
a14ed312 165static void packet_command (char *, int);
c906108c 166
a14ed312 167static int stub_unpack_int (char *buff, int fieldlength);
c906108c 168
39f77062 169static ptid_t remote_current_thread (ptid_t oldptid);
c906108c 170
baa336ce 171static int putpkt_binary (const char *buf, int cnt);
c906108c 172
a14ed312 173static void check_binary_download (CORE_ADDR addr);
c906108c 174
5a2468f5 175struct packet_config;
5a2468f5 176
a14ed312 177static void show_packet_config_cmd (struct packet_config *config);
5a2468f5 178
bb572ddd
DJ
179static void show_remote_protocol_packet_cmd (struct ui_file *file,
180 int from_tty,
181 struct cmd_list_element *c,
182 const char *value);
183
82f73884
PA
184static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
185static ptid_t read_ptid (char *buf, char **obuf);
186
c378d69d 187static void remote_set_permissions (struct target_ops *self);
d914c394 188
d5551862 189struct remote_state;
8bd200f1
TT
190static int remote_get_trace_status (struct target_ops *self,
191 struct trace_status *ts);
d5551862 192
ab6617cc
TT
193static int remote_upload_tracepoints (struct target_ops *self,
194 struct uploaded_tp **utpp);
00bf0b85 195
181e3713
TT
196static int remote_upload_trace_state_variables (struct target_ops *self,
197 struct uploaded_tsv **utsvp);
00bf0b85 198
c8d104ad
PA
199static void remote_query_supported (void);
200
36d25514 201static void remote_check_symbols (void);
c8d104ad 202
a14ed312 203void _initialize_remote (void);
c906108c 204
74531fed 205struct stop_reply;
74531fed 206static void stop_reply_xfree (struct stop_reply *);
722247f1 207static void remote_parse_stop_reply (char *, struct stop_reply *);
74531fed 208static void push_stop_reply (struct stop_reply *);
bcc75809 209static void discard_pending_stop_replies_in_queue (struct remote_state *);
74531fed
PA
210static int peek_stop_reply (ptid_t ptid);
211
212static void remote_async_inferior_event_handler (gdb_client_data);
74531fed 213
e3594fd1 214static void remote_terminal_ours (struct target_ops *self);
d3fd5342 215
d962ef82
DJ
216static int remote_read_description_p (struct target_ops *target);
217
176a6961 218static void remote_console_output (char *msg);
dde08ee1 219
efcc2da7 220static int remote_supports_cond_breakpoints (struct target_ops *self);
b775012e 221
78eff0ec 222static int remote_can_run_breakpoint_commands (struct target_ops *self);
d3ce09f5 223
f4abbc16
MM
224static void remote_btrace_reset (void);
225
a6b151f1
DJ
226/* For "remote". */
227
228static struct cmd_list_element *remote_cmdlist;
229
bb572ddd
DJ
230/* For "set remote" and "show remote". */
231
232static struct cmd_list_element *remote_set_cmdlist;
233static struct cmd_list_element *remote_show_cmdlist;
234
d458bd84
PA
235/* Stub vCont actions support.
236
237 Each field is a boolean flag indicating whether the stub reports
238 support for the corresponding action. */
239
240struct vCont_action_support
241{
242 /* vCont;t */
243 int t;
c1e36e3e
PA
244
245 /* vCont;r */
246 int r;
d458bd84
PA
247};
248
c1e36e3e
PA
249/* Controls whether GDB is willing to use range stepping. */
250
251static int use_range_stepping = 1;
252
0d031856
TT
253#define OPAQUETHREADBYTES 8
254
255/* a 64 bit opaque identifier */
256typedef unsigned char threadref[OPAQUETHREADBYTES];
257
258/* About this many threadisds fit in a packet. */
259
260#define MAXTHREADLISTRESULTS 32
261
ea9c271d
DJ
262/* Description of the remote protocol state for the currently
263 connected target. This is per-target state, and independent of the
264 selected architecture. */
265
266struct remote_state
267{
268 /* A buffer to use for incoming packets, and its current size. The
269 buffer is grown dynamically for larger incoming packets.
270 Outgoing packets may also be constructed in this buffer.
271 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
272 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
273 packets. */
274 char *buf;
275 long buf_size;
be2a5f71 276
1e51243a
PA
277 /* True if we're going through initial connection setup (finding out
278 about the remote side's threads, relocating symbols, etc.). */
279 int starting_up;
280
be2a5f71
DJ
281 /* If we negotiated packet size explicitly (and thus can bypass
282 heuristics for the largest packet size that will not overflow
283 a buffer in the stub), this will be set to that packet size.
284 Otherwise zero, meaning to use the guessed size. */
285 long explicit_packet_size;
2d717e4f
DJ
286
287 /* remote_wait is normally called when the target is running and
288 waits for a stop reply packet. But sometimes we need to call it
289 when the target is already stopped. We can send a "?" packet
290 and have remote_wait read the response. Or, if we already have
291 the response, we can stash it in BUF and tell remote_wait to
292 skip calling getpkt. This flag is set when BUF contains a
293 stop reply packet and the target is not waiting. */
294 int cached_wait_status;
a6f3e723
SL
295
296 /* True, if in no ack mode. That is, neither GDB nor the stub will
297 expect acks from each other. The connection is assumed to be
298 reliable. */
299 int noack_mode;
82f73884
PA
300
301 /* True if we're connected in extended remote mode. */
302 int extended;
303
e24a49d8
PA
304 /* True if we resumed the target and we're waiting for the target to
305 stop. In the mean time, we can't start another command/query.
306 The remote server wouldn't be ready to process it, so we'd
307 timeout waiting for a reply that would never come and eventually
308 we'd close the connection. This can happen in asynchronous mode
309 because we allow GDB commands while the target is running. */
310 int waiting_for_stop_reply;
74531fed 311
d458bd84
PA
312 /* The status of the stub support for the various vCont actions. */
313 struct vCont_action_support supports_vCont;
782b2b07 314
3a29589a
DJ
315 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
316 responded to that. */
317 int ctrlc_pending_p;
5d93a237
TT
318
319 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
320 remote_open knows that we don't have a file open when the program
321 starts. */
322 struct serial *remote_desc;
47f8a51d
TT
323
324 /* These are the threads which we last sent to the remote system. The
325 TID member will be -1 for all or -2 for not sent yet. */
326 ptid_t general_thread;
327 ptid_t continue_thread;
262e1174
TT
328
329 /* This is the traceframe which we last selected on the remote system.
330 It will be -1 if no traceframe is selected. */
331 int remote_traceframe_number;
747dc59d
TT
332
333 char *last_pass_packet;
5e4a05c4
TT
334
335 /* The last QProgramSignals packet sent to the target. We bypass
336 sending a new program signals list down to the target if the new
337 packet is exactly the same as the last we sent. IOW, we only let
338 the target know about program signals list changes. */
339 char *last_program_signals_packet;
b73be471
TT
340
341 enum gdb_signal last_sent_signal;
280ceea3
TT
342
343 int last_sent_step;
8e88304f
TT
344
345 char *finished_object;
346 char *finished_annex;
347 ULONGEST finished_offset;
b80fafe3
TT
348
349 /* Should we try the 'ThreadInfo' query packet?
350
351 This variable (NOT available to the user: auto-detect only!)
352 determines whether GDB will use the new, simpler "ThreadInfo"
353 query or the older, more complex syntax for thread queries.
354 This is an auto-detect variable (set to true at each connect,
355 and set to false when the target fails to recognize it). */
356 int use_threadinfo_query;
357 int use_threadextra_query;
88b496c3
TT
358
359 void (*async_client_callback) (enum inferior_event_type event_type,
360 void *context);
361 void *async_client_context;
ee154bee
TT
362
363 /* This is set to the data address of the access causing the target
364 to stop for a watchpoint. */
365 CORE_ADDR remote_watch_data_address;
366
f7e6eed5
PA
367 /* Whether the target stopped for a breakpoint/watchpoint. */
368 enum target_stop_reason stop_reason;
0d031856
TT
369
370 threadref echo_nextthread;
371 threadref nextthread;
372 threadref resultthreadlist[MAXTHREADLISTRESULTS];
5965e028
YQ
373
374 /* The state of remote notification. */
375 struct remote_notif_state *notif_state;
f4abbc16
MM
376
377 /* The branch trace configuration. */
378 struct btrace_config btrace_config;
ea9c271d
DJ
379};
380
dc146f7c
VP
381/* Private data that we'll store in (struct thread_info)->private. */
382struct private_thread_info
383{
384 char *extra;
385 int core;
386};
387
388static void
389free_private_thread_info (struct private_thread_info *info)
390{
391 xfree (info->extra);
392 xfree (info);
393}
394
ea9c271d
DJ
395/* This data could be associated with a target, but we do not always
396 have access to the current target when we need it, so for now it is
397 static. This will be fine for as long as only one target is in use
398 at a time. */
cf792862 399static struct remote_state *remote_state;
ea9c271d
DJ
400
401static struct remote_state *
0b83947e 402get_remote_state_raw (void)
ea9c271d 403{
cf792862
TT
404 return remote_state;
405}
406
407/* Allocate a new struct remote_state with xmalloc, initialize it, and
408 return it. */
409
410static struct remote_state *
411new_remote_state (void)
412{
413 struct remote_state *result = XCNEW (struct remote_state);
414
415 /* The default buffer size is unimportant; it will be expanded
416 whenever a larger buffer is needed. */
417 result->buf_size = 400;
418 result->buf = xmalloc (result->buf_size);
262e1174 419 result->remote_traceframe_number = -1;
b73be471 420 result->last_sent_signal = GDB_SIGNAL_0;
cf792862
TT
421
422 return result;
ea9c271d
DJ
423}
424
425/* Description of the remote protocol for a given architecture. */
d01949b6 426
ad10f812
AC
427struct packet_reg
428{
429 long offset; /* Offset into G packet. */
430 long regnum; /* GDB's internal register number. */
431 LONGEST pnum; /* Remote protocol register number. */
b323314b 432 int in_g_packet; /* Always part of G packet. */
f5656ead 433 /* long size in bytes; == register_size (target_gdbarch (), regnum);
23860348 434 at present. */
f5656ead 435 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
c9f4d572 436 at present. */
ad10f812
AC
437};
438
ea9c271d 439struct remote_arch_state
d01949b6 440{
ad10f812
AC
441 /* Description of the remote protocol registers. */
442 long sizeof_g_packet;
b323314b
AC
443
444 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 445 (making an array gdbarch_num_regs in size). */
b323314b 446 struct packet_reg *regs;
ad10f812 447
d01949b6
AC
448 /* This is the size (in chars) of the first response to the ``g''
449 packet. It is used as a heuristic when determining the maximum
450 size of memory-read and memory-write packets. A target will
451 typically only reserve a buffer large enough to hold the ``g''
452 packet. The size does not include packet overhead (headers and
23860348 453 trailers). */
d01949b6
AC
454 long actual_register_packet_size;
455
456 /* This is the maximum size (in chars) of a non read/write packet.
23860348 457 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
458 long remote_packet_size;
459};
460
35b1e5cc
SS
461/* Utility: generate error from an incoming stub packet. */
462static void
463trace_error (char *buf)
464{
465 if (*buf++ != 'E')
466 return; /* not an error msg */
467 switch (*buf)
468 {
469 case '1': /* malformed packet error */
470 if (*++buf == '0') /* general case: */
471 error (_("remote.c: error in outgoing packet."));
472 else
473 error (_("remote.c: error in outgoing packet at field #%ld."),
474 strtol (buf, NULL, 16));
35b1e5cc
SS
475 default:
476 error (_("Target returns error code '%s'."), buf);
477 }
478}
479
480/* Utility: wait for reply from stub, while accepting "O" packets. */
481static char *
482remote_get_noisy_reply (char **buf_p,
483 long *sizeof_buf)
484{
485 do /* Loop on reply from remote stub. */
486 {
487 char *buf;
a744cf53 488
0df8b418 489 QUIT; /* Allow user to bail out with ^C. */
35b1e5cc
SS
490 getpkt (buf_p, sizeof_buf, 0);
491 buf = *buf_p;
ad91cd99 492 if (buf[0] == 'E')
35b1e5cc 493 trace_error (buf);
61012eef 494 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
495 {
496 ULONGEST ul;
497 CORE_ADDR from, to, org_to;
498 char *p, *pp;
499 int adjusted_size = 0;
500 volatile struct gdb_exception ex;
7556d4a4 501 int relocated = 0;
dde08ee1
PA
502
503 p = buf + strlen ("qRelocInsn:");
504 pp = unpack_varlen_hex (p, &ul);
505 if (*pp != ';')
cb91c06a 506 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
507 from = ul;
508
509 p = pp + 1;
a9cbf802 510 unpack_varlen_hex (p, &ul);
dde08ee1
PA
511 to = ul;
512
513 org_to = to;
514
515 TRY_CATCH (ex, RETURN_MASK_ALL)
516 {
f5656ead 517 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 518 relocated = 1;
dde08ee1 519 }
7556d4a4
PA
520 if (ex.reason < 0)
521 {
522 if (ex.error == MEMORY_ERROR)
523 {
524 /* Propagate memory errors silently back to the
525 target. The stub may have limited the range of
526 addresses we can write to, for example. */
527 }
528 else
529 {
530 /* Something unexpectedly bad happened. Be verbose
531 so we can tell what, and propagate the error back
532 to the stub, so it doesn't get stuck waiting for
533 a response. */
534 exception_fprintf (gdb_stderr, ex,
535 _("warning: relocating instruction: "));
536 }
537 putpkt ("E01");
538 }
539
540 if (relocated)
dde08ee1
PA
541 {
542 adjusted_size = to - org_to;
543
bba74b36 544 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
545 putpkt (buf);
546 }
dde08ee1 547 }
ad91cd99 548 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
549 remote_console_output (buf + 1); /* 'O' message from stub */
550 else
0df8b418 551 return buf; /* Here's the actual reply. */
35b1e5cc
SS
552 }
553 while (1);
554}
3c3bea1c 555
d01949b6
AC
556/* Handle for retreving the remote protocol data from gdbarch. */
557static struct gdbarch_data *remote_gdbarch_data_handle;
558
ea9c271d
DJ
559static struct remote_arch_state *
560get_remote_arch_state (void)
d01949b6 561{
f5656ead 562 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
d01949b6
AC
563}
564
0b83947e
DJ
565/* Fetch the global remote target state. */
566
567static struct remote_state *
568get_remote_state (void)
569{
570 /* Make sure that the remote architecture state has been
571 initialized, because doing so might reallocate rs->buf. Any
572 function which calls getpkt also needs to be mindful of changes
573 to rs->buf, but this call limits the number of places which run
574 into trouble. */
575 get_remote_arch_state ();
576
577 return get_remote_state_raw ();
578}
579
74ca34ce
DJ
580static int
581compare_pnums (const void *lhs_, const void *rhs_)
582{
583 const struct packet_reg * const *lhs = lhs_;
584 const struct packet_reg * const *rhs = rhs_;
585
586 if ((*lhs)->pnum < (*rhs)->pnum)
587 return -1;
588 else if ((*lhs)->pnum == (*rhs)->pnum)
589 return 0;
590 else
591 return 1;
592}
593
c21236dc
PA
594static int
595map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 596{
74ca34ce 597 int regnum, num_remote_regs, offset;
74ca34ce 598 struct packet_reg **remote_regs;
ea9c271d 599
4a22f64d 600 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 601 {
c21236dc 602 struct packet_reg *r = &regs[regnum];
baef701f 603
4a22f64d 604 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
605 /* Do not try to fetch zero-sized (placeholder) registers. */
606 r->pnum = -1;
607 else
608 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
609
b323314b 610 r->regnum = regnum;
74ca34ce
DJ
611 }
612
613 /* Define the g/G packet format as the contents of each register
614 with a remote protocol number, in order of ascending protocol
615 number. */
616
4a22f64d 617 remote_regs = alloca (gdbarch_num_regs (gdbarch)
c21236dc 618 * sizeof (struct packet_reg *));
f57d151a 619 for (num_remote_regs = 0, regnum = 0;
4a22f64d 620 regnum < gdbarch_num_regs (gdbarch);
f57d151a 621 regnum++)
c21236dc
PA
622 if (regs[regnum].pnum != -1)
623 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 624
74ca34ce
DJ
625 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
626 compare_pnums);
627
628 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
629 {
630 remote_regs[regnum]->in_g_packet = 1;
631 remote_regs[regnum]->offset = offset;
4a22f64d 632 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
633 }
634
c21236dc
PA
635 return offset;
636}
637
638/* Given the architecture described by GDBARCH, return the remote
639 protocol register's number and the register's offset in the g/G
640 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
641 If the target does not have a mapping for REGNUM, return false,
642 otherwise, return true. */
643
644int
645remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
646 int *pnum, int *poffset)
647{
648 int sizeof_g_packet;
649 struct packet_reg *regs;
650 struct cleanup *old_chain;
651
652 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
653
654 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
655 old_chain = make_cleanup (xfree, regs);
656
657 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
658
659 *pnum = regs[regnum].pnum;
660 *poffset = regs[regnum].offset;
661
662 do_cleanups (old_chain);
663
664 return *pnum != -1;
665}
666
667static void *
668init_remote_state (struct gdbarch *gdbarch)
669{
670 struct remote_state *rs = get_remote_state_raw ();
671 struct remote_arch_state *rsa;
672
673 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
674
675 /* Use the architecture to build a regnum<->pnum table, which will be
676 1:1 unless a feature set specifies otherwise. */
677 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
678 gdbarch_num_regs (gdbarch),
679 struct packet_reg);
680
74ca34ce
DJ
681 /* Record the maximum possible size of the g packet - it may turn out
682 to be smaller. */
c21236dc 683 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 684
0df8b418 685 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
686 remote stubs have a hardwired buffer size of 400 bytes
687 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
688 as the maximum packet-size to ensure that the packet and an extra
689 NUL character can always fit in the buffer. This stops GDB
690 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
691 already a full buffer (As of 1999-12-04 that was most stubs). */
692 rsa->remote_packet_size = 400 - 1;
d01949b6 693
ea9c271d
DJ
694 /* This one is filled in when a ``g'' packet is received. */
695 rsa->actual_register_packet_size = 0;
696
697 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
698 default, adjust the size accordingly. Remember that each byte is
699 encoded as two characters. 32 is the overhead for the packet
700 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 701 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 702 little. */
ea9c271d
DJ
703 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
704 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 705
ea9c271d
DJ
706 /* Make sure that the packet buffer is plenty big enough for
707 this architecture. */
708 if (rs->buf_size < rsa->remote_packet_size)
709 {
710 rs->buf_size = 2 * rsa->remote_packet_size;
7fca722e 711 rs->buf = xrealloc (rs->buf, rs->buf_size);
ea9c271d 712 }
6d820c5c 713
ea9c271d
DJ
714 return rsa;
715}
716
717/* Return the current allowed size of a remote packet. This is
718 inferred from the current architecture, and should be used to
719 limit the length of outgoing packets. */
720static long
721get_remote_packet_size (void)
722{
be2a5f71 723 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
724 struct remote_arch_state *rsa = get_remote_arch_state ();
725
be2a5f71
DJ
726 if (rs->explicit_packet_size)
727 return rs->explicit_packet_size;
728
ea9c271d 729 return rsa->remote_packet_size;
d01949b6
AC
730}
731
ad10f812 732static struct packet_reg *
ea9c271d 733packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 734{
f5656ead 735 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
b323314b
AC
736 return NULL;
737 else
ad10f812 738 {
ea9c271d 739 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 740
b323314b
AC
741 gdb_assert (r->regnum == regnum);
742 return r;
ad10f812 743 }
ad10f812
AC
744}
745
746static struct packet_reg *
ea9c271d 747packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 748{
b323314b 749 int i;
a744cf53 750
f5656ead 751 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
ad10f812 752 {
ea9c271d 753 struct packet_reg *r = &rsa->regs[i];
a744cf53 754
b323314b
AC
755 if (r->pnum == pnum)
756 return r;
ad10f812
AC
757 }
758 return NULL;
d01949b6
AC
759}
760
c906108c
SS
761static struct target_ops remote_ops;
762
763static struct target_ops extended_remote_ops;
764
6426a772
JM
765/* FIXME: cagney/1999-09-23: Even though getpkt was called with
766 ``forever'' still use the normal timeout mechanism. This is
767 currently used by the ASYNC code to guarentee that target reads
768 during the initial connect always time-out. Once getpkt has been
769 modified to return a timeout indication and, in turn
770 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 771 this can go away. */
6426a772
JM
772static int wait_forever_enabled_p = 1;
773
9a7071a8
JB
774/* Allow the user to specify what sequence to send to the remote
775 when he requests a program interruption: Although ^C is usually
776 what remote systems expect (this is the default, here), it is
777 sometimes preferable to send a break. On other systems such
778 as the Linux kernel, a break followed by g, which is Magic SysRq g
779 is required in order to interrupt the execution. */
780const char interrupt_sequence_control_c[] = "Ctrl-C";
781const char interrupt_sequence_break[] = "BREAK";
782const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 783static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
784 {
785 interrupt_sequence_control_c,
786 interrupt_sequence_break,
787 interrupt_sequence_break_g,
788 NULL
789 };
790static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
791
792static void
793show_interrupt_sequence (struct ui_file *file, int from_tty,
794 struct cmd_list_element *c,
795 const char *value)
796{
797 if (interrupt_sequence_mode == interrupt_sequence_control_c)
798 fprintf_filtered (file,
799 _("Send the ASCII ETX character (Ctrl-c) "
800 "to the remote target to interrupt the "
801 "execution of the program.\n"));
802 else if (interrupt_sequence_mode == interrupt_sequence_break)
803 fprintf_filtered (file,
804 _("send a break signal to the remote target "
805 "to interrupt the execution of the program.\n"));
806 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
807 fprintf_filtered (file,
808 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
809 "the remote target to interrupt the execution "
810 "of Linux kernel.\n"));
811 else
812 internal_error (__FILE__, __LINE__,
813 _("Invalid value for interrupt_sequence_mode: %s."),
814 interrupt_sequence_mode);
815}
6426a772 816
9a7071a8
JB
817/* This boolean variable specifies whether interrupt_sequence is sent
818 to the remote target when gdb connects to it.
819 This is mostly needed when you debug the Linux kernel: The Linux kernel
820 expects BREAK g which is Magic SysRq g for connecting gdb. */
821static int interrupt_on_connect = 0;
c906108c 822
9a7071a8
JB
823/* This variable is used to implement the "set/show remotebreak" commands.
824 Since these commands are now deprecated in favor of "set/show remote
825 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
826static int remote_break;
827
9a7071a8
JB
828static void
829set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
830{
831 if (remote_break)
832 interrupt_sequence_mode = interrupt_sequence_break;
833 else
834 interrupt_sequence_mode = interrupt_sequence_control_c;
835}
836
837static void
838show_remotebreak (struct ui_file *file, int from_tty,
839 struct cmd_list_element *c,
840 const char *value)
841{
842}
843
c906108c
SS
844/* This variable sets the number of bits in an address that are to be
845 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 846 leading zeros, the entire address would be sent. This variable
c906108c
SS
847 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
848 initial implementation of remote.c restricted the address sent in
849 memory packets to ``host::sizeof long'' bytes - (typically 32
850 bits). Consequently, for 64 bit targets, the upper 32 bits of an
851 address was never sent. Since fixing this bug may cause a break in
852 some remote targets this variable is principly provided to
23860348 853 facilitate backward compatibility. */
c906108c 854
883b9c6c 855static unsigned int remote_address_size;
c906108c 856
75c99385
PA
857/* Temporary to track who currently owns the terminal. See
858 remote_terminal_* for more details. */
6426a772
JM
859
860static int remote_async_terminal_ours_p;
861
2d717e4f
DJ
862/* The executable file to use for "run" on the remote side. */
863
864static char *remote_exec_file = "";
865
11cf8741 866\f
11cf8741 867/* User configurable variables for the number of characters in a
ea9c271d
DJ
868 memory read/write packet. MIN (rsa->remote_packet_size,
869 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 870 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
871 (speed up transfers). The variables ``preferred_*'' (the user
872 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 873 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
874
875struct memory_packet_config
876{
877 char *name;
878 long size;
879 int fixed_p;
880};
881
882/* Compute the current size of a read/write packet. Since this makes
883 use of ``actual_register_packet_size'' the computation is dynamic. */
884
885static long
886get_memory_packet_size (struct memory_packet_config *config)
887{
d01949b6 888 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
889 struct remote_arch_state *rsa = get_remote_arch_state ();
890
11cf8741
JM
891 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
892 law?) that some hosts don't cope very well with large alloca()
893 calls. Eventually the alloca() code will be replaced by calls to
894 xmalloc() and make_cleanups() allowing this restriction to either
23860348 895 be lifted or removed. */
11cf8741
JM
896#ifndef MAX_REMOTE_PACKET_SIZE
897#define MAX_REMOTE_PACKET_SIZE 16384
898#endif
3de11b2e 899 /* NOTE: 20 ensures we can write at least one byte. */
11cf8741 900#ifndef MIN_REMOTE_PACKET_SIZE
3de11b2e 901#define MIN_REMOTE_PACKET_SIZE 20
11cf8741
JM
902#endif
903 long what_they_get;
904 if (config->fixed_p)
905 {
906 if (config->size <= 0)
907 what_they_get = MAX_REMOTE_PACKET_SIZE;
908 else
909 what_they_get = config->size;
910 }
911 else
912 {
ea9c271d 913 what_they_get = get_remote_packet_size ();
23860348 914 /* Limit the packet to the size specified by the user. */
11cf8741
JM
915 if (config->size > 0
916 && what_they_get > config->size)
917 what_they_get = config->size;
be2a5f71
DJ
918
919 /* Limit it to the size of the targets ``g'' response unless we have
920 permission from the stub to use a larger packet size. */
921 if (rs->explicit_packet_size == 0
922 && rsa->actual_register_packet_size > 0
923 && what_they_get > rsa->actual_register_packet_size)
924 what_they_get = rsa->actual_register_packet_size;
11cf8741
JM
925 }
926 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
927 what_they_get = MAX_REMOTE_PACKET_SIZE;
928 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
929 what_they_get = MIN_REMOTE_PACKET_SIZE;
6d820c5c
DJ
930
931 /* Make sure there is room in the global buffer for this packet
932 (including its trailing NUL byte). */
933 if (rs->buf_size < what_they_get + 1)
934 {
935 rs->buf_size = 2 * what_they_get;
936 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
937 }
938
11cf8741
JM
939 return what_they_get;
940}
941
0df8b418 942/* Update the size of a read/write packet. If they user wants
23860348 943 something really big then do a sanity check. */
11cf8741
JM
944
945static void
946set_memory_packet_size (char *args, struct memory_packet_config *config)
947{
948 int fixed_p = config->fixed_p;
949 long size = config->size;
a744cf53 950
11cf8741 951 if (args == NULL)
8a3fe4f8 952 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
953 else if (strcmp (args, "hard") == 0
954 || strcmp (args, "fixed") == 0)
955 fixed_p = 1;
956 else if (strcmp (args, "soft") == 0
957 || strcmp (args, "limit") == 0)
958 fixed_p = 0;
959 else
960 {
961 char *end;
a744cf53 962
11cf8741
JM
963 size = strtoul (args, &end, 0);
964 if (args == end)
8a3fe4f8 965 error (_("Invalid %s (bad syntax)."), config->name);
11cf8741
JM
966#if 0
967 /* Instead of explicitly capping the size of a packet to
968 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
969 instead allowed to set the size to something arbitrarily
23860348 970 large. */
11cf8741 971 if (size > MAX_REMOTE_PACKET_SIZE)
8a3fe4f8 972 error (_("Invalid %s (too large)."), config->name);
11cf8741
JM
973#endif
974 }
23860348 975 /* Extra checks? */
11cf8741
JM
976 if (fixed_p && !config->fixed_p)
977 {
e2e0b3e5
AC
978 if (! query (_("The target may not be able to correctly handle a %s\n"
979 "of %ld bytes. Change the packet size? "),
11cf8741 980 config->name, size))
8a3fe4f8 981 error (_("Packet size not changed."));
11cf8741 982 }
23860348 983 /* Update the config. */
11cf8741
JM
984 config->fixed_p = fixed_p;
985 config->size = size;
986}
987
988static void
989show_memory_packet_size (struct memory_packet_config *config)
990{
a3f17187 991 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 992 if (config->fixed_p)
a3f17187 993 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
994 get_memory_packet_size (config));
995 else
a3f17187 996 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
997 get_memory_packet_size (config));
998}
999
1000static struct memory_packet_config memory_write_packet_config =
1001{
1002 "memory-write-packet-size",
1003};
1004
1005static void
1006set_memory_write_packet_size (char *args, int from_tty)
1007{
1008 set_memory_packet_size (args, &memory_write_packet_config);
1009}
1010
1011static void
1012show_memory_write_packet_size (char *args, int from_tty)
1013{
1014 show_memory_packet_size (&memory_write_packet_config);
1015}
1016
1017static long
1018get_memory_write_packet_size (void)
1019{
1020 return get_memory_packet_size (&memory_write_packet_config);
1021}
1022
1023static struct memory_packet_config memory_read_packet_config =
1024{
1025 "memory-read-packet-size",
1026};
1027
1028static void
1029set_memory_read_packet_size (char *args, int from_tty)
1030{
1031 set_memory_packet_size (args, &memory_read_packet_config);
1032}
1033
1034static void
1035show_memory_read_packet_size (char *args, int from_tty)
1036{
1037 show_memory_packet_size (&memory_read_packet_config);
1038}
1039
1040static long
1041get_memory_read_packet_size (void)
1042{
1043 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1044
11cf8741
JM
1045 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1046 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1047 increased beyond this. */
1048 if (size > get_remote_packet_size ())
1049 size = get_remote_packet_size ();
11cf8741
JM
1050 return size;
1051}
1052
11cf8741 1053\f
5a2468f5 1054/* Generic configuration support for packets the stub optionally
0df8b418 1055 supports. Allows the user to specify the use of the packet as well
23860348 1056 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1057
1058enum packet_support
1059 {
1060 PACKET_SUPPORT_UNKNOWN = 0,
1061 PACKET_ENABLE,
1062 PACKET_DISABLE
1063 };
1064
5a2468f5
JM
1065struct packet_config
1066 {
bb572ddd
DJ
1067 const char *name;
1068 const char *title;
4082afcc
PA
1069
1070 /* If auto, GDB auto-detects support for this packet or feature,
1071 either through qSupported, or by trying the packet and looking
1072 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1073 packet. If false, the packet is disabled. Configs that don't
1074 have an associated command always have this set to auto. */
7f19b9a2 1075 enum auto_boolean detect;
4082afcc
PA
1076
1077 /* Does the target support this packet? */
5a2468f5
JM
1078 enum packet_support support;
1079 };
1080
d471ea57 1081/* Analyze a packet's return value and update the packet config
23860348 1082 accordingly. */
d471ea57
AC
1083
1084enum packet_result
1085{
1086 PACKET_ERROR,
1087 PACKET_OK,
1088 PACKET_UNKNOWN
1089};
1090
4082afcc
PA
1091static enum packet_support packet_config_support (struct packet_config *config);
1092static enum packet_support packet_support (int packet);
5a2468f5
JM
1093
1094static void
fba45db2 1095show_packet_config_cmd (struct packet_config *config)
5a2468f5
JM
1096{
1097 char *support = "internal-error";
a744cf53 1098
4082afcc 1099 switch (packet_config_support (config))
5a2468f5
JM
1100 {
1101 case PACKET_ENABLE:
1102 support = "enabled";
1103 break;
1104 case PACKET_DISABLE:
1105 support = "disabled";
1106 break;
1107 case PACKET_SUPPORT_UNKNOWN:
1108 support = "unknown";
1109 break;
1110 }
1111 switch (config->detect)
1112 {
7f19b9a2 1113 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1114 printf_filtered (_("Support for the `%s' packet "
1115 "is auto-detected, currently %s.\n"),
37a105a1 1116 config->name, support);
5a2468f5 1117 break;
7f19b9a2
AC
1118 case AUTO_BOOLEAN_TRUE:
1119 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1120 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1121 config->name, support);
8e248173 1122 break;
5a2468f5
JM
1123 }
1124}
1125
1126static void
bb572ddd
DJ
1127add_packet_config_cmd (struct packet_config *config, const char *name,
1128 const char *title, int legacy)
d471ea57 1129{
5a2468f5
JM
1130 char *set_doc;
1131 char *show_doc;
d471ea57 1132 char *cmd_name;
3ed07be4 1133
5a2468f5
JM
1134 config->name = name;
1135 config->title = title;
b435e160
AC
1136 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1137 name, title);
3e43a32a
MS
1138 show_doc = xstrprintf ("Show current use of remote "
1139 "protocol `%s' (%s) packet",
b435e160 1140 name, title);
d471ea57 1141 /* set/show TITLE-packet {auto,on,off} */
b435e160 1142 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1143 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1144 &config->detect, set_doc,
1145 show_doc, NULL, /* help_doc */
4082afcc 1146 NULL,
bb572ddd
DJ
1147 show_remote_protocol_packet_cmd,
1148 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1149 /* The command code copies the documentation strings. */
1150 xfree (set_doc);
1151 xfree (show_doc);
23860348 1152 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1153 if (legacy)
1154 {
1155 char *legacy_name;
a744cf53 1156
b435e160 1157 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1158 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1159 &remote_set_cmdlist);
d471ea57 1160 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1161 &remote_show_cmdlist);
d471ea57 1162 }
5a2468f5
JM
1163}
1164
d471ea57 1165static enum packet_result
a76d924d 1166packet_check_result (const char *buf)
5a2468f5 1167{
d471ea57 1168 if (buf[0] != '\0')
5a2468f5 1169 {
d471ea57 1170 /* The stub recognized the packet request. Check that the
23860348 1171 operation succeeded. */
a76d924d
DJ
1172 if (buf[0] == 'E'
1173 && isxdigit (buf[1]) && isxdigit (buf[2])
1174 && buf[3] == '\0')
1175 /* "Enn" - definitly an error. */
1176 return PACKET_ERROR;
1177
1178 /* Always treat "E." as an error. This will be used for
1179 more verbose error messages, such as E.memtypes. */
1180 if (buf[0] == 'E' && buf[1] == '.')
1181 return PACKET_ERROR;
1182
1183 /* The packet may or may not be OK. Just assume it is. */
1184 return PACKET_OK;
1185 }
1186 else
1187 /* The stub does not support the packet. */
1188 return PACKET_UNKNOWN;
1189}
1190
1191static enum packet_result
1192packet_ok (const char *buf, struct packet_config *config)
1193{
1194 enum packet_result result;
1195
4082afcc
PA
1196 if (config->detect != AUTO_BOOLEAN_TRUE
1197 && config->support == PACKET_DISABLE)
1198 internal_error (__FILE__, __LINE__,
1199 _("packet_ok: attempt to use a disabled packet"));
1200
a76d924d
DJ
1201 result = packet_check_result (buf);
1202 switch (result)
1203 {
1204 case PACKET_OK:
1205 case PACKET_ERROR:
1206 /* The stub recognized the packet request. */
4082afcc 1207 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1208 {
d471ea57
AC
1209 if (remote_debug)
1210 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1211 "Packet %s (%s) is supported\n",
1212 config->name, config->title);
d471ea57 1213 config->support = PACKET_ENABLE;
d471ea57 1214 }
a76d924d
DJ
1215 break;
1216 case PACKET_UNKNOWN:
23860348 1217 /* The stub does not support the packet. */
4082afcc
PA
1218 if (config->detect == AUTO_BOOLEAN_AUTO
1219 && config->support == PACKET_ENABLE)
d471ea57 1220 {
4082afcc
PA
1221 /* If the stub previously indicated that the packet was
1222 supported then there is a protocol error. */
1223 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1224 config->name, config->title);
1225 }
1226 else if (config->detect == AUTO_BOOLEAN_TRUE)
1227 {
1228 /* The user set it wrong. */
1229 error (_("Enabled packet %s (%s) not recognized by stub"),
1230 config->name, config->title);
d471ea57 1231 }
4082afcc
PA
1232
1233 if (remote_debug)
1234 fprintf_unfiltered (gdb_stdlog,
1235 "Packet %s (%s) is NOT supported\n",
1236 config->name, config->title);
1237 config->support = PACKET_DISABLE;
a76d924d 1238 break;
5a2468f5 1239 }
a76d924d
DJ
1240
1241 return result;
5a2468f5
JM
1242}
1243
444abaca
DJ
1244enum {
1245 PACKET_vCont = 0,
1246 PACKET_X,
1247 PACKET_qSymbol,
1248 PACKET_P,
1249 PACKET_p,
1250 PACKET_Z0,
1251 PACKET_Z1,
1252 PACKET_Z2,
1253 PACKET_Z3,
1254 PACKET_Z4,
a6b151f1
DJ
1255 PACKET_vFile_open,
1256 PACKET_vFile_pread,
1257 PACKET_vFile_pwrite,
1258 PACKET_vFile_close,
1259 PACKET_vFile_unlink,
b9e7b9c3 1260 PACKET_vFile_readlink,
0876f84a 1261 PACKET_qXfer_auxv,
23181151 1262 PACKET_qXfer_features,
cfa9d6d9 1263 PACKET_qXfer_libraries,
2268b414 1264 PACKET_qXfer_libraries_svr4,
fd79ecee 1265 PACKET_qXfer_memory_map,
0e7f50da
UW
1266 PACKET_qXfer_spu_read,
1267 PACKET_qXfer_spu_write,
07e059b5 1268 PACKET_qXfer_osdata,
dc146f7c 1269 PACKET_qXfer_threads,
0fb4aa4b 1270 PACKET_qXfer_statictrace_read,
b3b9301e 1271 PACKET_qXfer_traceframe_info,
169081d0 1272 PACKET_qXfer_uib,
711e434b 1273 PACKET_qGetTIBAddr,
444abaca 1274 PACKET_qGetTLSAddr,
be2a5f71 1275 PACKET_qSupported,
bd3eecc3 1276 PACKET_qTStatus,
89be2091 1277 PACKET_QPassSignals,
9b224c5e 1278 PACKET_QProgramSignals,
936d2992 1279 PACKET_qCRC,
08388c79 1280 PACKET_qSearch_memory,
2d717e4f
DJ
1281 PACKET_vAttach,
1282 PACKET_vRun,
a6f3e723 1283 PACKET_QStartNoAckMode,
82f73884 1284 PACKET_vKill,
4aa995e1
PA
1285 PACKET_qXfer_siginfo_read,
1286 PACKET_qXfer_siginfo_write,
0b16c5cf 1287 PACKET_qAttached,
4082afcc
PA
1288
1289 /* Support for conditional tracepoints. */
782b2b07 1290 PACKET_ConditionalTracepoints,
4082afcc
PA
1291
1292 /* Support for target-side breakpoint conditions. */
3788aec7 1293 PACKET_ConditionalBreakpoints,
4082afcc
PA
1294
1295 /* Support for target-side breakpoint commands. */
d3ce09f5 1296 PACKET_BreakpointCommands,
4082afcc
PA
1297
1298 /* Support for fast tracepoints. */
7a697b8d 1299 PACKET_FastTracepoints,
4082afcc
PA
1300
1301 /* Support for static tracepoints. */
0fb4aa4b 1302 PACKET_StaticTracepoints,
4082afcc
PA
1303
1304 /* Support for installing tracepoints while a trace experiment is
1305 running. */
1e4d1764 1306 PACKET_InstallInTrace,
4082afcc 1307
40ab02ce
MS
1308 PACKET_bc,
1309 PACKET_bs,
409873ef 1310 PACKET_TracepointSource,
d914c394 1311 PACKET_QAllow,
78d85199 1312 PACKET_qXfer_fdpic,
03583c20 1313 PACKET_QDisableRandomization,
d1feda86 1314 PACKET_QAgent,
f6f899bf 1315 PACKET_QTBuffer_size,
9accd112
MM
1316 PACKET_Qbtrace_off,
1317 PACKET_Qbtrace_bts,
1318 PACKET_qXfer_btrace,
4082afcc
PA
1319
1320 /* Support for the QNonStop packet. */
1321 PACKET_QNonStop,
1322
1323 /* Support for multi-process extensions. */
1324 PACKET_multiprocess_feature,
1325
1326 /* Support for enabling and disabling tracepoints while a trace
1327 experiment is running. */
1328 PACKET_EnableDisableTracepoints_feature,
1329
1330 /* Support for collecting strings using the tracenz bytecode. */
1331 PACKET_tracenz_feature,
1332
1333 /* Support for continuing to run a trace experiment while GDB is
1334 disconnected. */
1335 PACKET_DisconnectedTracing_feature,
1336
1337 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1338 PACKET_augmented_libraries_svr4_read_feature,
1339
f4abbc16
MM
1340 /* Support for the qXfer:btrace-conf:read packet. */
1341 PACKET_qXfer_btrace_conf,
1342
d33501a5
MM
1343 /* Support for the Qbtrace-conf:bts:size packet. */
1344 PACKET_Qbtrace_conf_bts_size,
1345
f7e6eed5
PA
1346 /* Support for swbreak+ feature. */
1347 PACKET_swbreak_feature,
1348
1349 /* Support for hwbreak+ feature. */
1350 PACKET_hwbreak_feature,
1351
444abaca
DJ
1352 PACKET_MAX
1353};
506fb367 1354
444abaca 1355static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1356
f7e6eed5
PA
1357/* Returns the packet's corresponding "set remote foo-packet" command
1358 state. See struct packet_config for more details. */
1359
1360static enum auto_boolean
1361packet_set_cmd_state (int packet)
1362{
1363 return remote_protocol_packets[packet].detect;
1364}
1365
4082afcc
PA
1366/* Returns whether a given packet or feature is supported. This takes
1367 into account the state of the corresponding "set remote foo-packet"
1368 command, which may be used to bypass auto-detection. */
dc8acb97 1369
4082afcc
PA
1370static enum packet_support
1371packet_config_support (struct packet_config *config)
1372{
1373 switch (config->detect)
444abaca 1374 {
4082afcc
PA
1375 case AUTO_BOOLEAN_TRUE:
1376 return PACKET_ENABLE;
1377 case AUTO_BOOLEAN_FALSE:
1378 return PACKET_DISABLE;
1379 case AUTO_BOOLEAN_AUTO:
1380 return config->support;
1381 default:
1382 gdb_assert_not_reached (_("bad switch"));
444abaca 1383 }
4082afcc
PA
1384}
1385
1386/* Same as packet_config_support, but takes the packet's enum value as
1387 argument. */
1388
1389static enum packet_support
1390packet_support (int packet)
1391{
1392 struct packet_config *config = &remote_protocol_packets[packet];
1393
1394 return packet_config_support (config);
dc8acb97
MS
1395}
1396
5a2468f5 1397static void
444abaca
DJ
1398show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1399 struct cmd_list_element *c,
1400 const char *value)
5a2468f5 1401{
444abaca 1402 struct packet_config *packet;
5a2468f5 1403
444abaca
DJ
1404 for (packet = remote_protocol_packets;
1405 packet < &remote_protocol_packets[PACKET_MAX];
1406 packet++)
1407 {
1408 if (&packet->detect == c->var)
1409 {
1410 show_packet_config_cmd (packet);
1411 return;
1412 }
1413 }
9b20d036 1414 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1415 c->name);
5a2468f5
JM
1416}
1417
d471ea57
AC
1418/* Should we try one of the 'Z' requests? */
1419
1420enum Z_packet_type
1421{
1422 Z_PACKET_SOFTWARE_BP,
1423 Z_PACKET_HARDWARE_BP,
1424 Z_PACKET_WRITE_WP,
1425 Z_PACKET_READ_WP,
1426 Z_PACKET_ACCESS_WP,
1427 NR_Z_PACKET_TYPES
1428};
96baa820 1429
d471ea57 1430/* For compatibility with older distributions. Provide a ``set remote
23860348 1431 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1432
7f19b9a2 1433static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1434
1435static void
fba45db2
KB
1436set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1437 struct cmd_list_element *c)
96baa820 1438{
d471ea57 1439 int i;
a744cf53 1440
d471ea57 1441 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1442 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1443}
1444
1445static void
08546159
AC
1446show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1447 struct cmd_list_element *c,
1448 const char *value)
96baa820 1449{
d471ea57 1450 int i;
a744cf53 1451
d471ea57
AC
1452 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1453 {
444abaca 1454 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1455 }
96baa820
JM
1456}
1457
4082afcc
PA
1458/* Returns true if the multi-process extensions are in effect. */
1459
1460static int
1461remote_multi_process_p (struct remote_state *rs)
1462{
1463 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1464}
1465
23860348 1466/* Tokens for use by the asynchronous signal handlers for SIGINT. */
934b9bac
JK
1467static struct async_signal_handler *async_sigint_remote_twice_token;
1468static struct async_signal_handler *async_sigint_remote_token;
43ff13b4 1469
74531fed
PA
1470\f
1471/* Asynchronous signal handle registered as event loop source for
1472 when we have pending events ready to be passed to the core. */
1473
1474static struct async_event_handler *remote_async_inferior_event_token;
1475
c906108c
SS
1476\f
1477
79d7f229
PA
1478static ptid_t magic_null_ptid;
1479static ptid_t not_sent_ptid;
1480static ptid_t any_thread_ptid;
1481
0b16c5cf
PA
1482/* Find out if the stub attached to PID (and hence GDB should offer to
1483 detach instead of killing it when bailing out). */
1484
1485static int
1486remote_query_attached (int pid)
1487{
1488 struct remote_state *rs = get_remote_state ();
bba74b36 1489 size_t size = get_remote_packet_size ();
0b16c5cf 1490
4082afcc 1491 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1492 return 0;
1493
1494 if (remote_multi_process_p (rs))
bba74b36 1495 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1496 else
bba74b36 1497 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1498
1499 putpkt (rs->buf);
1500 getpkt (&rs->buf, &rs->buf_size, 0);
1501
1502 switch (packet_ok (rs->buf,
1554e9be 1503 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1504 {
1505 case PACKET_OK:
1506 if (strcmp (rs->buf, "1") == 0)
1507 return 1;
1508 break;
1509 case PACKET_ERROR:
1510 warning (_("Remote failure reply: %s"), rs->buf);
1511 break;
1512 case PACKET_UNKNOWN:
1513 break;
1514 }
1515
1516 return 0;
1517}
1518
49c62f2e
PA
1519/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1520 has been invented by GDB, instead of reported by the target. Since
1521 we can be connected to a remote system before before knowing about
1522 any inferior, mark the target with execution when we find the first
1523 inferior. If ATTACHED is 1, then we had just attached to this
1524 inferior. If it is 0, then we just created this inferior. If it
1525 is -1, then try querying the remote stub to find out if it had
1526 attached to the inferior or not. */
1941c569
PA
1527
1528static struct inferior *
49c62f2e 1529remote_add_inferior (int fake_pid_p, int pid, int attached)
1941c569 1530{
1941c569
PA
1531 struct inferior *inf;
1532
0b16c5cf
PA
1533 /* Check whether this process we're learning about is to be
1534 considered attached, or if is to be considered to have been
1535 spawned by the stub. */
1536 if (attached == -1)
1537 attached = remote_query_attached (pid);
1538
f5656ead 1539 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1540 {
1541 /* If the target shares code across all inferiors, then every
1542 attach adds a new inferior. */
1543 inf = add_inferior (pid);
1544
1545 /* ... and every inferior is bound to the same program space.
1546 However, each inferior may still have its own address
1547 space. */
1548 inf->aspace = maybe_new_address_space ();
1549 inf->pspace = current_program_space;
1550 }
1551 else
1552 {
1553 /* In the traditional debugging scenario, there's a 1-1 match
1554 between program/address spaces. We simply bind the inferior
1555 to the program space's address space. */
1556 inf = current_inferior ();
1557 inferior_appeared (inf, pid);
1558 }
1941c569 1559
0b16c5cf 1560 inf->attach_flag = attached;
49c62f2e 1561 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1562
1941c569
PA
1563 return inf;
1564}
1565
1566/* Add thread PTID to GDB's thread list. Tag it as executing/running
1567 according to RUNNING. */
1568
c906108c 1569static void
1941c569 1570remote_add_thread (ptid_t ptid, int running)
c906108c 1571{
b7ea362b
PA
1572 struct remote_state *rs = get_remote_state ();
1573
1574 /* GDB historically didn't pull threads in the initial connection
1575 setup. If the remote target doesn't even have a concept of
1576 threads (e.g., a bare-metal target), even if internally we
1577 consider that a single-threaded target, mentioning a new thread
1578 might be confusing to the user. Be silent then, preserving the
1579 age old behavior. */
1580 if (rs->starting_up)
1581 add_thread_silent (ptid);
1582 else
1583 add_thread (ptid);
1941c569
PA
1584
1585 set_executing (ptid, running);
1586 set_running (ptid, running);
1587}
1588
1589/* Come here when we learn about a thread id from the remote target.
1590 It may be the first time we hear about such thread, so take the
1591 opportunity to add it to GDB's thread list. In case this is the
1592 first time we're noticing its corresponding inferior, add it to
1593 GDB's inferior list as well. */
1594
1595static void
1596remote_notice_new_inferior (ptid_t currthread, int running)
1597{
c906108c
SS
1598 /* If this is a new thread, add it to GDB's thread list.
1599 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1600
1601 if (in_thread_list (currthread) && is_exited (currthread))
1602 {
1603 /* We're seeing an event on a thread id we knew had exited.
1604 This has to be a new thread reusing the old id. Add it. */
1941c569 1605 remote_add_thread (currthread, running);
82f73884
PA
1606 return;
1607 }
1608
79d7f229 1609 if (!in_thread_list (currthread))
c0a2216e 1610 {
1941c569 1611 struct inferior *inf = NULL;
bad34192 1612 int pid = ptid_get_pid (currthread);
1941c569 1613
bad34192
PA
1614 if (ptid_is_pid (inferior_ptid)
1615 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1616 {
1617 /* inferior_ptid has no thread member yet. This can happen
1618 with the vAttach -> remote_wait,"TAAthread:" path if the
1619 stub doesn't support qC. This is the first stop reported
1620 after an attach, so this is the main thread. Update the
1621 ptid in the thread list. */
bad34192
PA
1622 if (in_thread_list (pid_to_ptid (pid)))
1623 thread_change_ptid (inferior_ptid, currthread);
1624 else
1625 {
1626 remote_add_thread (currthread, running);
1627 inferior_ptid = currthread;
1628 }
dc146f7c 1629 return;
c0a2216e 1630 }
82f73884
PA
1631
1632 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1633 {
1634 /* inferior_ptid is not set yet. This can happen with the
1635 vRun -> remote_wait,"TAAthread:" path if the stub
1636 doesn't support qC. This is the first stop reported
1637 after an attach, so this is the main thread. Update the
1638 ptid in the thread list. */
dc146f7c 1639 thread_change_ptid (inferior_ptid, currthread);
82f73884 1640 return;
c0a2216e 1641 }
82f73884 1642
29c87f7f
PA
1643 /* When connecting to a target remote, or to a target
1644 extended-remote which already was debugging an inferior, we
1645 may not know about it yet. Add it before adding its child
1646 thread, so notifications are emitted in a sensible order. */
1647 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1648 {
1649 struct remote_state *rs = get_remote_state ();
1650 int fake_pid_p = !remote_multi_process_p (rs);
1651
1652 inf = remote_add_inferior (fake_pid_p,
1653 ptid_get_pid (currthread), -1);
1654 }
29c87f7f 1655
82f73884 1656 /* This is really a new thread. Add it. */
1941c569
PA
1657 remote_add_thread (currthread, running);
1658
1659 /* If we found a new inferior, let the common code do whatever
1660 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1661 breakpoints), unless we're just setting up an all-stop
1662 connection. */
1941c569 1663 if (inf != NULL)
b7ea362b
PA
1664 {
1665 struct remote_state *rs = get_remote_state ();
1666
1667 if (non_stop || !rs->starting_up)
1668 notice_new_inferior (currthread, running, 0);
1669 }
c0a2216e 1670 }
c906108c
SS
1671}
1672
dc146f7c
VP
1673/* Return the private thread data, creating it if necessary. */
1674
70221824 1675static struct private_thread_info *
dc146f7c
VP
1676demand_private_info (ptid_t ptid)
1677{
1678 struct thread_info *info = find_thread_ptid (ptid);
1679
1680 gdb_assert (info);
1681
fe978cb0 1682 if (!info->priv)
dc146f7c 1683 {
fe978cb0 1684 info->priv = xmalloc (sizeof (*(info->priv)));
dc146f7c 1685 info->private_dtor = free_private_thread_info;
fe978cb0
PA
1686 info->priv->core = -1;
1687 info->priv->extra = 0;
dc146f7c
VP
1688 }
1689
fe978cb0 1690 return info->priv;
dc146f7c
VP
1691}
1692
74531fed
PA
1693/* Call this function as a result of
1694 1) A halt indication (T packet) containing a thread id
1695 2) A direct query of currthread
0df8b418 1696 3) Successful execution of set thread */
74531fed
PA
1697
1698static void
47f8a51d 1699record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1700{
47f8a51d 1701 rs->general_thread = currthread;
74531fed
PA
1702}
1703
89be2091
DJ
1704/* If 'QPassSignals' is supported, tell the remote stub what signals
1705 it can simply pass through to the inferior without reporting. */
1706
1707static void
94bedb42
TT
1708remote_pass_signals (struct target_ops *self,
1709 int numsigs, unsigned char *pass_signals)
89be2091 1710{
4082afcc 1711 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
1712 {
1713 char *pass_packet, *p;
89be2091 1714 int count = 0, i;
747dc59d 1715 struct remote_state *rs = get_remote_state ();
89be2091
DJ
1716
1717 gdb_assert (numsigs < 256);
1718 for (i = 0; i < numsigs; i++)
1719 {
2455069d 1720 if (pass_signals[i])
89be2091
DJ
1721 count++;
1722 }
1723 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1724 strcpy (pass_packet, "QPassSignals:");
1725 p = pass_packet + strlen (pass_packet);
1726 for (i = 0; i < numsigs; i++)
1727 {
2455069d 1728 if (pass_signals[i])
89be2091
DJ
1729 {
1730 if (i >= 16)
1731 *p++ = tohex (i >> 4);
1732 *p++ = tohex (i & 15);
1733 if (count)
1734 *p++ = ';';
1735 else
1736 break;
1737 count--;
1738 }
1739 }
1740 *p = 0;
747dc59d 1741 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 1742 {
89be2091
DJ
1743 putpkt (pass_packet);
1744 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1745 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
1746 if (rs->last_pass_packet)
1747 xfree (rs->last_pass_packet);
1748 rs->last_pass_packet = pass_packet;
89be2091
DJ
1749 }
1750 else
1751 xfree (pass_packet);
1752 }
1753}
1754
9b224c5e
PA
1755/* If 'QProgramSignals' is supported, tell the remote stub what
1756 signals it should pass through to the inferior when detaching. */
1757
1758static void
daf5e9b6
TT
1759remote_program_signals (struct target_ops *self,
1760 int numsigs, unsigned char *signals)
9b224c5e 1761{
4082afcc 1762 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
1763 {
1764 char *packet, *p;
1765 int count = 0, i;
5e4a05c4 1766 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
1767
1768 gdb_assert (numsigs < 256);
1769 for (i = 0; i < numsigs; i++)
1770 {
1771 if (signals[i])
1772 count++;
1773 }
1774 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1775 strcpy (packet, "QProgramSignals:");
1776 p = packet + strlen (packet);
1777 for (i = 0; i < numsigs; i++)
1778 {
1779 if (signal_pass_state (i))
1780 {
1781 if (i >= 16)
1782 *p++ = tohex (i >> 4);
1783 *p++ = tohex (i & 15);
1784 if (count)
1785 *p++ = ';';
1786 else
1787 break;
1788 count--;
1789 }
1790 }
1791 *p = 0;
5e4a05c4
TT
1792 if (!rs->last_program_signals_packet
1793 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 1794 {
9b224c5e
PA
1795 putpkt (packet);
1796 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1797 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
1798 xfree (rs->last_program_signals_packet);
1799 rs->last_program_signals_packet = packet;
9b224c5e
PA
1800 }
1801 else
1802 xfree (packet);
1803 }
1804}
1805
79d7f229
PA
1806/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1807 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1808 thread. If GEN is set, set the general thread, if not, then set
1809 the step/continue thread. */
c906108c 1810static void
79d7f229 1811set_thread (struct ptid ptid, int gen)
c906108c 1812{
d01949b6 1813 struct remote_state *rs = get_remote_state ();
47f8a51d 1814 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 1815 char *buf = rs->buf;
79d7f229 1816 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 1817
79d7f229 1818 if (ptid_equal (state, ptid))
c906108c
SS
1819 return;
1820
79d7f229
PA
1821 *buf++ = 'H';
1822 *buf++ = gen ? 'g' : 'c';
1823 if (ptid_equal (ptid, magic_null_ptid))
1824 xsnprintf (buf, endbuf - buf, "0");
1825 else if (ptid_equal (ptid, any_thread_ptid))
1826 xsnprintf (buf, endbuf - buf, "0");
1827 else if (ptid_equal (ptid, minus_one_ptid))
1828 xsnprintf (buf, endbuf - buf, "-1");
1829 else
82f73884 1830 write_ptid (buf, endbuf, ptid);
79d7f229 1831 putpkt (rs->buf);
6d820c5c 1832 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 1833 if (gen)
47f8a51d 1834 rs->general_thread = ptid;
c906108c 1835 else
47f8a51d 1836 rs->continue_thread = ptid;
c906108c 1837}
79d7f229
PA
1838
1839static void
1840set_general_thread (struct ptid ptid)
1841{
1842 set_thread (ptid, 1);
1843}
1844
1845static void
1846set_continue_thread (struct ptid ptid)
1847{
1848 set_thread (ptid, 0);
1849}
1850
3c9c4b83
PA
1851/* Change the remote current process. Which thread within the process
1852 ends up selected isn't important, as long as it is the same process
1853 as what INFERIOR_PTID points to.
1854
1855 This comes from that fact that there is no explicit notion of
1856 "selected process" in the protocol. The selected process for
1857 general operations is the process the selected general thread
1858 belongs to. */
1859
1860static void
1861set_general_process (void)
1862{
1863 struct remote_state *rs = get_remote_state ();
1864
1865 /* If the remote can't handle multiple processes, don't bother. */
901f9912 1866 if (!rs->extended || !remote_multi_process_p (rs))
3c9c4b83
PA
1867 return;
1868
1869 /* We only need to change the remote current thread if it's pointing
1870 at some other process. */
47f8a51d 1871 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
1872 set_general_thread (inferior_ptid);
1873}
1874
c906108c 1875\f
7d1a114c
PA
1876/* Return nonzero if this is the main thread that we made up ourselves
1877 to model non-threaded targets as single-threaded. */
c906108c
SS
1878
1879static int
7d1a114c 1880remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 1881{
6d820c5c 1882 struct remote_state *rs = get_remote_state ();
82f73884 1883 char *p, *endp;
c906108c 1884
c0a2216e
PA
1885 if (ptid_equal (ptid, magic_null_ptid))
1886 /* The main thread is always alive. */
1887 return 1;
1888
ba348170 1889 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
1890 /* The main thread is always alive. This can happen after a
1891 vAttach, if the remote side doesn't support
1892 multi-threading. */
1893 return 1;
1894
7d1a114c
PA
1895 return 0;
1896}
1897
1898/* Return nonzero if the thread PTID is still alive on the remote
1899 system. */
1900
1901static int
1902remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1903{
1904 struct remote_state *rs = get_remote_state ();
1905 char *p, *endp;
1906
1907 /* Check if this is a thread that we made up ourselves to model
1908 non-threaded targets as single-threaded. */
1909 if (remote_thread_always_alive (ops, ptid))
1910 return 1;
1911
82f73884
PA
1912 p = rs->buf;
1913 endp = rs->buf + get_remote_packet_size ();
1914
1915 *p++ = 'T';
1916 write_ptid (p, endp, ptid);
1917
2e9f7625 1918 putpkt (rs->buf);
6d820c5c 1919 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 1920 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
1921}
1922
1923/* About these extended threadlist and threadinfo packets. They are
1924 variable length packets but, the fields within them are often fixed
1925 length. They are redundent enough to send over UDP as is the
1926 remote protocol in general. There is a matching unit test module
1927 in libstub. */
1928
23860348 1929/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 1930 libstub protocol encoding, and remote.c. It is not particularly
23860348 1931 changable. */
cce74817
JM
1932
1933/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 1934 Plan to fix this. */
cce74817 1935
23860348 1936typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 1937
9d1f7ab2 1938/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 1939 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
1940
1941struct gdb_ext_thread_info
c5aa993b 1942 {
23860348 1943 threadref threadid; /* External form of thread reference. */
2bc416ba 1944 int active; /* Has state interesting to GDB?
23860348 1945 regs, stack. */
2bc416ba 1946 char display[256]; /* Brief state display, name,
cedea757 1947 blocked/suspended. */
23860348 1948 char shortname[32]; /* To be used to name threads. */
2bc416ba 1949 char more_display[256]; /* Long info, statistics, queue depth,
23860348 1950 whatever. */
c5aa993b 1951 };
cce74817
JM
1952
1953/* The volume of remote transfers can be limited by submitting
1954 a mask containing bits specifying the desired information.
1955 Use a union of these values as the 'selection' parameter to
0df8b418 1956 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
1957
1958#define TAG_THREADID 1
1959#define TAG_EXISTS 2
1960#define TAG_DISPLAY 4
1961#define TAG_THREADNAME 8
c5aa993b 1962#define TAG_MOREDISPLAY 16
cce74817 1963
23860348 1964#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 1965
a14ed312 1966static char *unpack_nibble (char *buf, int *val);
cce74817 1967
a14ed312 1968static char *unpack_byte (char *buf, int *value);
cce74817 1969
a14ed312 1970static char *pack_int (char *buf, int value);
cce74817 1971
a14ed312 1972static char *unpack_int (char *buf, int *value);
cce74817 1973
a14ed312 1974static char *unpack_string (char *src, char *dest, int length);
cce74817 1975
23860348 1976static char *pack_threadid (char *pkt, threadref *id);
cce74817 1977
23860348 1978static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 1979
23860348 1980void int_to_threadref (threadref *id, int value);
cce74817 1981
23860348 1982static int threadref_to_int (threadref *ref);
cce74817 1983
23860348 1984static void copy_threadref (threadref *dest, threadref *src);
cce74817 1985
23860348 1986static int threadmatch (threadref *dest, threadref *src);
cce74817 1987
2bc416ba 1988static char *pack_threadinfo_request (char *pkt, int mode,
23860348 1989 threadref *id);
cce74817 1990
a14ed312 1991static int remote_unpack_thread_info_response (char *pkt,
23860348 1992 threadref *expectedref,
a14ed312
KB
1993 struct gdb_ext_thread_info
1994 *info);
cce74817
JM
1995
1996
2bc416ba 1997static int remote_get_threadinfo (threadref *threadid,
23860348 1998 int fieldset, /*TAG mask */
a14ed312 1999 struct gdb_ext_thread_info *info);
cce74817 2000
a14ed312
KB
2001static char *pack_threadlist_request (char *pkt, int startflag,
2002 int threadcount,
23860348 2003 threadref *nextthread);
cce74817 2004
a14ed312
KB
2005static int parse_threadlist_response (char *pkt,
2006 int result_limit,
23860348 2007 threadref *original_echo,
2bc416ba 2008 threadref *resultlist,
23860348 2009 int *doneflag);
cce74817 2010
a14ed312 2011static int remote_get_threadlist (int startflag,
23860348 2012 threadref *nextthread,
a14ed312
KB
2013 int result_limit,
2014 int *done,
2bc416ba 2015 int *result_count,
23860348 2016 threadref *threadlist);
cce74817 2017
23860348 2018typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2019
a14ed312
KB
2020static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2021 void *context, int looplimit);
cce74817 2022
23860348 2023static int remote_newthread_step (threadref *ref, void *context);
cce74817 2024
82f73884
PA
2025
2026/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2027 buffer we're allowed to write to. Returns
2028 BUF+CHARACTERS_WRITTEN. */
2029
2030static char *
2031write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2032{
2033 int pid, tid;
2034 struct remote_state *rs = get_remote_state ();
2035
2036 if (remote_multi_process_p (rs))
2037 {
2038 pid = ptid_get_pid (ptid);
2039 if (pid < 0)
2040 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2041 else
2042 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2043 }
ba348170 2044 tid = ptid_get_lwp (ptid);
82f73884
PA
2045 if (tid < 0)
2046 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2047 else
2048 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2049
2050 return buf;
2051}
2052
2053/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2054 passed the last parsed char. Returns null_ptid on error. */
2055
2056static ptid_t
2057read_ptid (char *buf, char **obuf)
2058{
2059 char *p = buf;
2060 char *pp;
2061 ULONGEST pid = 0, tid = 0;
82f73884
PA
2062
2063 if (*p == 'p')
2064 {
2065 /* Multi-process ptid. */
2066 pp = unpack_varlen_hex (p + 1, &pid);
2067 if (*pp != '.')
b37520b6 2068 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2069
2070 p = pp;
2071 pp = unpack_varlen_hex (p + 1, &tid);
2072 if (obuf)
2073 *obuf = pp;
ba348170 2074 return ptid_build (pid, tid, 0);
82f73884
PA
2075 }
2076
2077 /* No multi-process. Just a tid. */
2078 pp = unpack_varlen_hex (p, &tid);
2079
2080 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2081 what's in inferior_ptid, unless it's null at this point. If so,
2082 then since there's no way to know the pid of the reported
2083 threads, use the magic number. */
2084 if (ptid_equal (inferior_ptid, null_ptid))
2085 pid = ptid_get_pid (magic_null_ptid);
2086 else
2087 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2088
2089 if (obuf)
2090 *obuf = pp;
ba348170 2091 return ptid_build (pid, tid, 0);
82f73884
PA
2092}
2093
c906108c 2094static int
fba45db2 2095stubhex (int ch)
c906108c
SS
2096{
2097 if (ch >= 'a' && ch <= 'f')
2098 return ch - 'a' + 10;
2099 if (ch >= '0' && ch <= '9')
2100 return ch - '0';
2101 if (ch >= 'A' && ch <= 'F')
2102 return ch - 'A' + 10;
2103 return -1;
2104}
2105
2106static int
fba45db2 2107stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2108{
2109 int nibble;
2110 int retval = 0;
2111
2112 while (fieldlength)
2113 {
2114 nibble = stubhex (*buff++);
2115 retval |= nibble;
2116 fieldlength--;
2117 if (fieldlength)
2118 retval = retval << 4;
2119 }
2120 return retval;
2121}
2122
c906108c 2123static char *
fba45db2 2124unpack_nibble (char *buf, int *val)
c906108c 2125{
b7589f7d 2126 *val = fromhex (*buf++);
c906108c
SS
2127 return buf;
2128}
2129
c906108c 2130static char *
fba45db2 2131unpack_byte (char *buf, int *value)
c906108c
SS
2132{
2133 *value = stub_unpack_int (buf, 2);
2134 return buf + 2;
2135}
2136
2137static char *
fba45db2 2138pack_int (char *buf, int value)
c906108c
SS
2139{
2140 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2141 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2142 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2143 buf = pack_hex_byte (buf, (value & 0xff));
2144 return buf;
2145}
2146
2147static char *
fba45db2 2148unpack_int (char *buf, int *value)
c906108c
SS
2149{
2150 *value = stub_unpack_int (buf, 8);
2151 return buf + 8;
2152}
2153
23860348 2154#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2155static char *pack_string (char *pkt, char *string);
c906108c
SS
2156
2157static char *
fba45db2 2158pack_string (char *pkt, char *string)
c906108c
SS
2159{
2160 char ch;
2161 int len;
2162
2163 len = strlen (string);
2164 if (len > 200)
23860348 2165 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2166 pkt = pack_hex_byte (pkt, len);
2167 while (len-- > 0)
2168 {
2169 ch = *string++;
2170 if ((ch == '\0') || (ch == '#'))
23860348 2171 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2172 *pkt++ = ch;
2173 }
2174 return pkt;
2175}
2176#endif /* 0 (unused) */
2177
2178static char *
fba45db2 2179unpack_string (char *src, char *dest, int length)
c906108c
SS
2180{
2181 while (length--)
2182 *dest++ = *src++;
2183 *dest = '\0';
2184 return src;
2185}
2186
2187static char *
fba45db2 2188pack_threadid (char *pkt, threadref *id)
c906108c
SS
2189{
2190 char *limit;
2191 unsigned char *altid;
2192
2193 altid = (unsigned char *) id;
2194 limit = pkt + BUF_THREAD_ID_SIZE;
2195 while (pkt < limit)
2196 pkt = pack_hex_byte (pkt, *altid++);
2197 return pkt;
2198}
2199
2200
2201static char *
fba45db2 2202unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2203{
2204 char *altref;
2205 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2206 int x, y;
2207
2208 altref = (char *) id;
2209
2210 while (inbuf < limit)
2211 {
2212 x = stubhex (*inbuf++);
2213 y = stubhex (*inbuf++);
2214 *altref++ = (x << 4) | y;
2215 }
2216 return inbuf;
2217}
2218
2219/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2220 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2221 to use 64bit thread references internally. This is an adapter
2222 function. */
2223
2224void
fba45db2 2225int_to_threadref (threadref *id, int value)
c906108c
SS
2226{
2227 unsigned char *scan;
2228
2229 scan = (unsigned char *) id;
2230 {
2231 int i = 4;
2232 while (i--)
2233 *scan++ = 0;
2234 }
2235 *scan++ = (value >> 24) & 0xff;
2236 *scan++ = (value >> 16) & 0xff;
2237 *scan++ = (value >> 8) & 0xff;
2238 *scan++ = (value & 0xff);
2239}
2240
2241static int
fba45db2 2242threadref_to_int (threadref *ref)
c906108c
SS
2243{
2244 int i, value = 0;
2245 unsigned char *scan;
2246
cfd77fa1 2247 scan = *ref;
c906108c
SS
2248 scan += 4;
2249 i = 4;
2250 while (i-- > 0)
2251 value = (value << 8) | ((*scan++) & 0xff);
2252 return value;
2253}
2254
2255static void
fba45db2 2256copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2257{
2258 int i;
2259 unsigned char *csrc, *cdest;
2260
2261 csrc = (unsigned char *) src;
2262 cdest = (unsigned char *) dest;
2263 i = 8;
2264 while (i--)
2265 *cdest++ = *csrc++;
2266}
2267
2268static int
fba45db2 2269threadmatch (threadref *dest, threadref *src)
c906108c 2270{
23860348 2271 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2272#if 0
2273 unsigned char *srcp, *destp;
2274 int i, result;
2275 srcp = (char *) src;
2276 destp = (char *) dest;
2277
2278 result = 1;
2279 while (i-- > 0)
2280 result &= (*srcp++ == *destp++) ? 1 : 0;
2281 return result;
2282#endif
2283 return 1;
2284}
2285
2286/*
c5aa993b
JM
2287 threadid:1, # always request threadid
2288 context_exists:2,
2289 display:4,
2290 unique_name:8,
2291 more_display:16
2292 */
c906108c
SS
2293
2294/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2295
2296static char *
fba45db2 2297pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2298{
23860348
MS
2299 *pkt++ = 'q'; /* Info Query */
2300 *pkt++ = 'P'; /* process or thread info */
2301 pkt = pack_int (pkt, mode); /* mode */
c906108c 2302 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2303 *pkt = '\0'; /* terminate */
c906108c
SS
2304 return pkt;
2305}
2306
23860348 2307/* These values tag the fields in a thread info response packet. */
c906108c 2308/* Tagging the fields allows us to request specific fields and to
23860348 2309 add more fields as time goes by. */
c906108c 2310
23860348 2311#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2312#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2313 fetch registers and its stack? */
c5aa993b 2314#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2315#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2316#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2317 the process. */
c906108c
SS
2318
2319static int
fba45db2
KB
2320remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2321 struct gdb_ext_thread_info *info)
c906108c 2322{
d01949b6 2323 struct remote_state *rs = get_remote_state ();
c906108c 2324 int mask, length;
cfd77fa1 2325 int tag;
c906108c 2326 threadref ref;
6d820c5c 2327 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2328 int retval = 1;
2329
23860348 2330 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2331 info->active = 0;
2332 info->display[0] = '\0';
2333 info->shortname[0] = '\0';
2334 info->more_display[0] = '\0';
2335
23860348
MS
2336 /* Assume the characters indicating the packet type have been
2337 stripped. */
c906108c
SS
2338 pkt = unpack_int (pkt, &mask); /* arg mask */
2339 pkt = unpack_threadid (pkt, &ref);
2340
2341 if (mask == 0)
8a3fe4f8 2342 warning (_("Incomplete response to threadinfo request."));
c906108c 2343 if (!threadmatch (&ref, expectedref))
23860348 2344 { /* This is an answer to a different request. */
8a3fe4f8 2345 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2346 return 0;
2347 }
2348 copy_threadref (&info->threadid, &ref);
2349
23860348 2350 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2351
23860348
MS
2352 /* Packets are terminated with nulls. */
2353 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2354 {
2355 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2356 pkt = unpack_byte (pkt, &length); /* length */
2357 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2358 {
8a3fe4f8 2359 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2360 retval = 0;
2361 break;
2362 }
2363 if (tag == TAG_THREADID)
2364 {
2365 if (length != 16)
2366 {
8a3fe4f8 2367 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2368 retval = 0;
2369 break;
2370 }
2371 pkt = unpack_threadid (pkt, &ref);
2372 mask = mask & ~TAG_THREADID;
2373 continue;
2374 }
2375 if (tag == TAG_EXISTS)
2376 {
2377 info->active = stub_unpack_int (pkt, length);
2378 pkt += length;
2379 mask = mask & ~(TAG_EXISTS);
2380 if (length > 8)
2381 {
8a3fe4f8 2382 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2383 retval = 0;
2384 break;
2385 }
2386 continue;
2387 }
2388 if (tag == TAG_THREADNAME)
2389 {
2390 pkt = unpack_string (pkt, &info->shortname[0], length);
2391 mask = mask & ~TAG_THREADNAME;
2392 continue;
2393 }
2394 if (tag == TAG_DISPLAY)
2395 {
2396 pkt = unpack_string (pkt, &info->display[0], length);
2397 mask = mask & ~TAG_DISPLAY;
2398 continue;
2399 }
2400 if (tag == TAG_MOREDISPLAY)
2401 {
2402 pkt = unpack_string (pkt, &info->more_display[0], length);
2403 mask = mask & ~TAG_MOREDISPLAY;
2404 continue;
2405 }
8a3fe4f8 2406 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2407 break; /* Not a tag we know about. */
c906108c
SS
2408 }
2409 return retval;
2410}
2411
2412static int
fba45db2
KB
2413remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2414 struct gdb_ext_thread_info *info)
c906108c 2415{
d01949b6 2416 struct remote_state *rs = get_remote_state ();
c906108c 2417 int result;
c906108c 2418
2e9f7625
DJ
2419 pack_threadinfo_request (rs->buf, fieldset, threadid);
2420 putpkt (rs->buf);
6d820c5c 2421 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2422
2423 if (rs->buf[0] == '\0')
2424 return 0;
2425
2e9f7625 2426 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2427 threadid, info);
c906108c
SS
2428 return result;
2429}
2430
c906108c
SS
2431/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2432
2433static char *
fba45db2
KB
2434pack_threadlist_request (char *pkt, int startflag, int threadcount,
2435 threadref *nextthread)
c906108c
SS
2436{
2437 *pkt++ = 'q'; /* info query packet */
2438 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2439 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2440 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2441 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2442 *pkt = '\0';
2443 return pkt;
2444}
2445
2446/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2447
2448static int
fba45db2
KB
2449parse_threadlist_response (char *pkt, int result_limit,
2450 threadref *original_echo, threadref *resultlist,
2451 int *doneflag)
c906108c 2452{
d01949b6 2453 struct remote_state *rs = get_remote_state ();
c906108c
SS
2454 char *limit;
2455 int count, resultcount, done;
2456
2457 resultcount = 0;
2458 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2459 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2460 /* done parse past here */
c906108c
SS
2461 pkt = unpack_byte (pkt, &count); /* count field */
2462 pkt = unpack_nibble (pkt, &done);
2463 /* The first threadid is the argument threadid. */
2464 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2465 while ((count-- > 0) && (pkt < limit))
2466 {
2467 pkt = unpack_threadid (pkt, resultlist++);
2468 if (resultcount++ >= result_limit)
2469 break;
2470 }
2471 if (doneflag)
2472 *doneflag = done;
2473 return resultcount;
2474}
2475
6dc54d91
PA
2476/* Fetch the next batch of threads from the remote. Returns -1 if the
2477 qL packet is not supported, 0 on error and 1 on success. */
2478
c906108c 2479static int
fba45db2
KB
2480remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2481 int *done, int *result_count, threadref *threadlist)
c906108c 2482{
d01949b6 2483 struct remote_state *rs = get_remote_state ();
c906108c
SS
2484 int result = 1;
2485
23860348 2486 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2487 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2488 >= get_remote_packet_size ())
ea9c271d 2489 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2490
6d820c5c
DJ
2491 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2492 putpkt (rs->buf);
2493 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2494 if (*rs->buf == '\0')
6dc54d91
PA
2495 {
2496 /* Packet not supported. */
2497 return -1;
2498 }
2499
2500 *result_count =
2501 parse_threadlist_response (rs->buf + 2, result_limit,
2502 &rs->echo_nextthread, threadlist, done);
c906108c 2503
0d031856 2504 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2505 {
23860348
MS
2506 /* FIXME: This is a good reason to drop the packet. */
2507 /* Possably, there is a duplicate response. */
c906108c
SS
2508 /* Possabilities :
2509 retransmit immediatly - race conditions
2510 retransmit after timeout - yes
2511 exit
2512 wait for packet, then exit
2513 */
8a3fe4f8 2514 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2515 return 0; /* I choose simply exiting. */
c906108c
SS
2516 }
2517 if (*result_count <= 0)
2518 {
2519 if (*done != 1)
2520 {
8a3fe4f8 2521 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2522 result = 0;
2523 }
2524 return result; /* break; */
2525 }
2526 if (*result_count > result_limit)
2527 {
2528 *result_count = 0;
8a3fe4f8 2529 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2530 return 0;
2531 }
2532 return result;
2533}
2534
6dc54d91
PA
2535/* Fetch the list of remote threads, with the qL packet, and call
2536 STEPFUNCTION for each thread found. Stops iterating and returns 1
2537 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2538 STEPFUNCTION returns false. If the packet is not supported,
2539 returns -1. */
c906108c 2540
c906108c 2541static int
fba45db2
KB
2542remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2543 int looplimit)
c906108c 2544{
0d031856 2545 struct remote_state *rs = get_remote_state ();
c906108c
SS
2546 int done, i, result_count;
2547 int startflag = 1;
2548 int result = 1;
2549 int loopcount = 0;
c906108c
SS
2550
2551 done = 0;
2552 while (!done)
2553 {
2554 if (loopcount++ > looplimit)
2555 {
2556 result = 0;
8a3fe4f8 2557 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2558 break;
2559 }
6dc54d91
PA
2560 result = remote_get_threadlist (startflag, &rs->nextthread,
2561 MAXTHREADLISTRESULTS,
2562 &done, &result_count,
2563 rs->resultthreadlist);
2564 if (result <= 0)
2565 break;
23860348 2566 /* Clear for later iterations. */
c906108c
SS
2567 startflag = 0;
2568 /* Setup to resume next batch of thread references, set nextthread. */
2569 if (result_count >= 1)
0d031856
TT
2570 copy_threadref (&rs->nextthread,
2571 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2572 i = 0;
2573 while (result_count--)
6dc54d91
PA
2574 {
2575 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2576 {
2577 result = 0;
2578 break;
2579 }
2580 }
c906108c
SS
2581 }
2582 return result;
2583}
2584
6dc54d91
PA
2585/* A thread found on the remote target. */
2586
2587typedef struct thread_item
2588{
2589 /* The thread's PTID. */
2590 ptid_t ptid;
2591
2592 /* The thread's extra info. May be NULL. */
2593 char *extra;
2594
2595 /* The core the thread was running on. -1 if not known. */
2596 int core;
2597} thread_item_t;
2598DEF_VEC_O(thread_item_t);
2599
2600/* Context passed around to the various methods listing remote
2601 threads. As new threads are found, they're added to the ITEMS
2602 vector. */
2603
2604struct threads_listing_context
2605{
2606 /* The threads found on the remote target. */
2607 VEC (thread_item_t) *items;
2608};
2609
80134cf5
PA
2610/* Discard the contents of the constructed thread listing context. */
2611
2612static void
2613clear_threads_listing_context (void *p)
2614{
2615 struct threads_listing_context *context = p;
2616 int i;
2617 struct thread_item *item;
2618
2619 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2620 xfree (item->extra);
2621
2622 VEC_free (thread_item_t, context->items);
2623}
2624
c906108c 2625static int
6dc54d91 2626remote_newthread_step (threadref *ref, void *data)
c906108c 2627{
6dc54d91
PA
2628 struct threads_listing_context *context = data;
2629 struct thread_item item;
79d7f229 2630 int pid = ptid_get_pid (inferior_ptid);
39f77062 2631
6dc54d91
PA
2632 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2633 item.core = -1;
2634 item.extra = NULL;
2635
2636 VEC_safe_push (thread_item_t, context->items, &item);
2637
c906108c
SS
2638 return 1; /* continue iterator */
2639}
2640
2641#define CRAZY_MAX_THREADS 1000
2642
39f77062
KB
2643static ptid_t
2644remote_current_thread (ptid_t oldpid)
c906108c 2645{
d01949b6 2646 struct remote_state *rs = get_remote_state ();
c906108c
SS
2647
2648 putpkt ("qC");
6d820c5c 2649 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2650 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
82f73884 2651 return read_ptid (&rs->buf[2], NULL);
c906108c
SS
2652 else
2653 return oldpid;
2654}
2655
6dc54d91 2656/* List remote threads using the deprecated qL packet. */
cce74817 2657
6dc54d91
PA
2658static int
2659remote_get_threads_with_ql (struct target_ops *ops,
2660 struct threads_listing_context *context)
c906108c 2661{
6dc54d91
PA
2662 if (remote_threadlist_iterator (remote_newthread_step, context,
2663 CRAZY_MAX_THREADS) >= 0)
2664 return 1;
2665
2666 return 0;
c906108c
SS
2667}
2668
dc146f7c
VP
2669#if defined(HAVE_LIBEXPAT)
2670
dc146f7c
VP
2671static void
2672start_thread (struct gdb_xml_parser *parser,
2673 const struct gdb_xml_element *element,
2674 void *user_data, VEC(gdb_xml_value_s) *attributes)
2675{
6dc54d91 2676 struct threads_listing_context *data = user_data;
dc146f7c
VP
2677
2678 struct thread_item item;
2679 char *id;
3d2c1d41 2680 struct gdb_xml_value *attr;
dc146f7c 2681
3d2c1d41 2682 id = xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
2683 item.ptid = read_ptid (id, NULL);
2684
3d2c1d41
PA
2685 attr = xml_find_attribute (attributes, "core");
2686 if (attr != NULL)
2687 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
2688 else
2689 item.core = -1;
2690
2691 item.extra = 0;
2692
2693 VEC_safe_push (thread_item_t, data->items, &item);
2694}
2695
2696static void
2697end_thread (struct gdb_xml_parser *parser,
2698 const struct gdb_xml_element *element,
2699 void *user_data, const char *body_text)
2700{
6dc54d91 2701 struct threads_listing_context *data = user_data;
dc146f7c
VP
2702
2703 if (body_text && *body_text)
2ae2a0b7 2704 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
2705}
2706
2707const struct gdb_xml_attribute thread_attributes[] = {
2708 { "id", GDB_XML_AF_NONE, NULL, NULL },
2709 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2710 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2711};
2712
2713const struct gdb_xml_element thread_children[] = {
2714 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2715};
2716
2717const struct gdb_xml_element threads_children[] = {
2718 { "thread", thread_attributes, thread_children,
2719 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2720 start_thread, end_thread },
2721 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2722};
2723
2724const struct gdb_xml_element threads_elements[] = {
2725 { "threads", NULL, threads_children,
2726 GDB_XML_EF_NONE, NULL, NULL },
2727 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2728};
2729
2730#endif
2731
6dc54d91 2732/* List remote threads using qXfer:threads:read. */
9d1f7ab2 2733
6dc54d91
PA
2734static int
2735remote_get_threads_with_qxfer (struct target_ops *ops,
2736 struct threads_listing_context *context)
0f71a2f6 2737{
dc146f7c 2738#if defined(HAVE_LIBEXPAT)
4082afcc 2739 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 2740 {
6dc54d91 2741 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 2742 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 2743
6dc54d91 2744 if (xml != NULL && *xml != '\0')
dc146f7c 2745 {
6dc54d91
PA
2746 gdb_xml_parse_quick (_("threads"), "threads.dtd",
2747 threads_elements, xml, context);
dc146f7c
VP
2748 }
2749
2750 do_cleanups (back_to);
6dc54d91 2751 return 1;
dc146f7c
VP
2752 }
2753#endif
2754
6dc54d91
PA
2755 return 0;
2756}
2757
2758/* List remote threads using qfThreadInfo/qsThreadInfo. */
2759
2760static int
2761remote_get_threads_with_qthreadinfo (struct target_ops *ops,
2762 struct threads_listing_context *context)
2763{
2764 struct remote_state *rs = get_remote_state ();
2765
b80fafe3 2766 if (rs->use_threadinfo_query)
9d1f7ab2 2767 {
6dc54d91
PA
2768 char *bufp;
2769
9d1f7ab2 2770 putpkt ("qfThreadInfo");
6d820c5c 2771 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2772 bufp = rs->buf;
9d1f7ab2 2773 if (bufp[0] != '\0') /* q packet recognized */
802188a7 2774 {
9d1f7ab2
MS
2775 while (*bufp++ == 'm') /* reply contains one or more TID */
2776 {
2777 do
2778 {
6dc54d91
PA
2779 struct thread_item item;
2780
2781 item.ptid = read_ptid (bufp, &bufp);
2782 item.core = -1;
2783 item.extra = NULL;
2784
2785 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
2786 }
2787 while (*bufp++ == ','); /* comma-separated list */
2788 putpkt ("qsThreadInfo");
6d820c5c 2789 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 2790 bufp = rs->buf;
9d1f7ab2 2791 }
6dc54d91
PA
2792 return 1;
2793 }
2794 else
2795 {
2796 /* Packet not recognized. */
2797 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
2798 }
2799 }
2800
6dc54d91
PA
2801 return 0;
2802}
2803
e8032dde 2804/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
2805 targets. */
2806
2807static void
e8032dde 2808remote_update_thread_list (struct target_ops *ops)
6dc54d91
PA
2809{
2810 struct remote_state *rs = get_remote_state ();
2811 struct threads_listing_context context;
2812 struct cleanup *old_chain;
ab970af1 2813 int got_list = 0;
e8032dde 2814
6dc54d91
PA
2815 context.items = NULL;
2816 old_chain = make_cleanup (clear_threads_listing_context, &context);
2817
2818 /* We have a few different mechanisms to fetch the thread list. Try
2819 them all, starting with the most preferred one first, falling
2820 back to older methods. */
2821 if (remote_get_threads_with_qxfer (ops, &context)
2822 || remote_get_threads_with_qthreadinfo (ops, &context)
2823 || remote_get_threads_with_ql (ops, &context))
2824 {
2825 int i;
2826 struct thread_item *item;
ab970af1
PA
2827 struct thread_info *tp, *tmp;
2828
2829 got_list = 1;
2830
7d1a114c
PA
2831 if (VEC_empty (thread_item_t, context.items)
2832 && remote_thread_always_alive (ops, inferior_ptid))
2833 {
2834 /* Some targets don't really support threads, but still
2835 reply an (empty) thread list in response to the thread
2836 listing packets, instead of replying "packet not
2837 supported". Exit early so we don't delete the main
2838 thread. */
2839 do_cleanups (old_chain);
2840 return;
2841 }
2842
ab970af1
PA
2843 /* CONTEXT now holds the current thread list on the remote
2844 target end. Delete GDB-side threads no longer found on the
2845 target. */
2846 ALL_NON_EXITED_THREADS_SAFE (tp, tmp)
2847 {
2848 for (i = 0;
2849 VEC_iterate (thread_item_t, context.items, i, item);
2850 ++i)
2851 {
2852 if (ptid_equal (item->ptid, tp->ptid))
2853 break;
2854 }
2855
2856 if (i == VEC_length (thread_item_t, context.items))
2857 {
2858 /* Not found. */
2859 delete_thread (tp->ptid);
2860 }
2861 }
74531fed 2862
ab970af1 2863 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
2864 for (i = 0;
2865 VEC_iterate (thread_item_t, context.items, i, item);
2866 ++i)
2867 {
2868 if (!ptid_equal (item->ptid, null_ptid))
2869 {
2870 struct private_thread_info *info;
2871 /* In non-stop mode, we assume new found threads are
2872 running until proven otherwise with a stop reply. In
2873 all-stop, we can only get here if all threads are
2874 stopped. */
2875 int running = non_stop ? 1 : 0;
2876
2877 remote_notice_new_inferior (item->ptid, running);
2878
2879 info = demand_private_info (item->ptid);
2880 info->core = item->core;
2881 info->extra = item->extra;
2882 item->extra = NULL;
2883 }
2884 }
2885 }
2886
ab970af1
PA
2887 if (!got_list)
2888 {
2889 /* If no thread listing method is supported, then query whether
2890 each known thread is alive, one by one, with the T packet.
2891 If the target doesn't support threads at all, then this is a
2892 no-op. See remote_thread_alive. */
2893 prune_threads ();
2894 }
2895
6dc54d91 2896 do_cleanups (old_chain);
9d1f7ab2
MS
2897}
2898
802188a7 2899/*
9d1f7ab2
MS
2900 * Collect a descriptive string about the given thread.
2901 * The target may say anything it wants to about the thread
2902 * (typically info about its blocked / runnable state, name, etc.).
2903 * This string will appear in the info threads display.
802188a7 2904 *
9d1f7ab2
MS
2905 * Optional: targets are not required to implement this function.
2906 */
2907
2908static char *
c15906d8 2909remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 2910{
d01949b6 2911 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
2912 int result;
2913 int set;
2914 threadref id;
2915 struct gdb_ext_thread_info threadinfo;
23860348 2916 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
2917 int n = 0; /* position in display_buf */
2918
5d93a237 2919 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 2920 internal_error (__FILE__, __LINE__,
e2e0b3e5 2921 _("remote_threads_extra_info"));
9d1f7ab2 2922
60e569b9 2923 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 2924 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
2925 /* This is the main thread which was added by GDB. The remote
2926 server doesn't know about it. */
2927 return NULL;
2928
4082afcc 2929 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
2930 {
2931 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 2932
fe978cb0
PA
2933 if (info && info->priv)
2934 return info->priv->extra;
dc146f7c
VP
2935 else
2936 return NULL;
2937 }
2938
b80fafe3 2939 if (rs->use_threadextra_query)
9d1f7ab2 2940 {
82f73884
PA
2941 char *b = rs->buf;
2942 char *endb = rs->buf + get_remote_packet_size ();
2943
2944 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2945 b += strlen (b);
2946 write_ptid (b, endb, tp->ptid);
2947
2e9f7625 2948 putpkt (rs->buf);
6d820c5c 2949 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2950 if (rs->buf[0] != 0)
9d1f7ab2 2951 {
2e9f7625
DJ
2952 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2953 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 2954 display_buf [result] = '\0';
9d1f7ab2
MS
2955 return display_buf;
2956 }
0f71a2f6 2957 }
9d1f7ab2
MS
2958
2959 /* If the above query fails, fall back to the old method. */
b80fafe3 2960 rs->use_threadextra_query = 0;
9d1f7ab2
MS
2961 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2962 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 2963 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
2964 if (remote_get_threadinfo (&id, set, &threadinfo))
2965 if (threadinfo.active)
0f71a2f6 2966 {
9d1f7ab2 2967 if (*threadinfo.shortname)
2bc416ba 2968 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 2969 " Name: %s,", threadinfo.shortname);
9d1f7ab2 2970 if (*threadinfo.display)
2bc416ba 2971 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 2972 " State: %s,", threadinfo.display);
9d1f7ab2 2973 if (*threadinfo.more_display)
2bc416ba 2974 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 2975 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
2976
2977 if (n > 0)
c5aa993b 2978 {
23860348 2979 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
2980 if (',' == display_buf[n-1])
2981 display_buf[n-1] = ' ';
2982 return display_buf;
c5aa993b 2983 }
0f71a2f6 2984 }
9d1f7ab2 2985 return NULL;
0f71a2f6 2986}
c906108c 2987\f
c5aa993b 2988
0fb4aa4b 2989static int
61fc905d 2990remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
2991 struct static_tracepoint_marker *marker)
2992{
2993 struct remote_state *rs = get_remote_state ();
2994 char *p = rs->buf;
2995
bba74b36 2996 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
2997 p += strlen (p);
2998 p += hexnumstr (p, addr);
2999 putpkt (rs->buf);
3000 getpkt (&rs->buf, &rs->buf_size, 0);
3001 p = rs->buf;
3002
3003 if (*p == 'E')
3004 error (_("Remote failure reply: %s"), p);
3005
3006 if (*p++ == 'm')
3007 {
3008 parse_static_tracepoint_marker_definition (p, &p, marker);
3009 return 1;
3010 }
3011
3012 return 0;
3013}
3014
0fb4aa4b 3015static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3016remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3017 const char *strid)
0fb4aa4b
PA
3018{
3019 struct remote_state *rs = get_remote_state ();
3020 VEC(static_tracepoint_marker_p) *markers = NULL;
3021 struct static_tracepoint_marker *marker = NULL;
3022 struct cleanup *old_chain;
3023 char *p;
3024
3025 /* Ask for a first packet of static tracepoint marker
3026 definition. */
3027 putpkt ("qTfSTM");
3028 getpkt (&rs->buf, &rs->buf_size, 0);
3029 p = rs->buf;
3030 if (*p == 'E')
3031 error (_("Remote failure reply: %s"), p);
3032
3033 old_chain = make_cleanup (free_current_marker, &marker);
3034
3035 while (*p++ == 'm')
3036 {
3037 if (marker == NULL)
3038 marker = XCNEW (struct static_tracepoint_marker);
3039
3040 do
3041 {
3042 parse_static_tracepoint_marker_definition (p, &p, marker);
3043
3044 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3045 {
3046 VEC_safe_push (static_tracepoint_marker_p,
3047 markers, marker);
3048 marker = NULL;
3049 }
3050 else
3051 {
3052 release_static_tracepoint_marker (marker);
3053 memset (marker, 0, sizeof (*marker));
3054 }
3055 }
3056 while (*p++ == ','); /* comma-separated list */
3057 /* Ask for another packet of static tracepoint definition. */
3058 putpkt ("qTsSTM");
3059 getpkt (&rs->buf, &rs->buf_size, 0);
3060 p = rs->buf;
3061 }
3062
3063 do_cleanups (old_chain);
3064 return markers;
3065}
3066
3067\f
10760264
JB
3068/* Implement the to_get_ada_task_ptid function for the remote targets. */
3069
3070static ptid_t
1e6b91a4 3071remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3072{
ba348170 3073 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3074}
3075\f
3076
24b06219 3077/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3078
3079static void
fba45db2 3080extended_remote_restart (void)
c906108c 3081{
d01949b6 3082 struct remote_state *rs = get_remote_state ();
c906108c
SS
3083
3084 /* Send the restart command; for reasons I don't understand the
3085 remote side really expects a number after the "R". */
ea9c271d 3086 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3087 putpkt (rs->buf);
c906108c 3088
ad9a8f3f 3089 remote_fileio_reset ();
c906108c
SS
3090}
3091\f
3092/* Clean up connection to a remote debugger. */
3093
c906108c 3094static void
de90e03d 3095remote_close (struct target_ops *self)
c906108c 3096{
5d93a237
TT
3097 struct remote_state *rs = get_remote_state ();
3098
3099 if (rs->remote_desc == NULL)
d3fd5342
PA
3100 return; /* already closed */
3101
3102 /* Make sure we leave stdin registered in the event loop, and we
3103 don't leave the async SIGINT signal handler installed. */
e3594fd1 3104 remote_terminal_ours (self);
ce5ce7ed 3105
5d93a237
TT
3106 serial_close (rs->remote_desc);
3107 rs->remote_desc = NULL;
ce5ce7ed
PA
3108
3109 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3110 of all the inferiors and their threads we were controlling.
3111 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3112 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3113 inferior_ptid = null_ptid;
f67fd822 3114 discard_all_inferiors ();
ce5ce7ed 3115
f48ff2a7
YQ
3116 /* We are closing the remote target, so we should discard
3117 everything of this target. */
bcc75809 3118 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3119
3120 if (remote_async_inferior_event_token)
3121 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3122
5965e028 3123 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3124
3125 trace_reset_local_state ();
c906108c
SS
3126}
3127
23860348 3128/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3129
3130static void
fba45db2 3131get_offsets (void)
c906108c 3132{
d01949b6 3133 struct remote_state *rs = get_remote_state ();
2e9f7625 3134 char *buf;
085dd6e6 3135 char *ptr;
31d99776
DJ
3136 int lose, num_segments = 0, do_sections, do_segments;
3137 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3138 struct section_offsets *offs;
31d99776
DJ
3139 struct symfile_segment_data *data;
3140
3141 if (symfile_objfile == NULL)
3142 return;
c906108c
SS
3143
3144 putpkt ("qOffsets");
6d820c5c 3145 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3146 buf = rs->buf;
c906108c
SS
3147
3148 if (buf[0] == '\000')
3149 return; /* Return silently. Stub doesn't support
23860348 3150 this command. */
c906108c
SS
3151 if (buf[0] == 'E')
3152 {
8a3fe4f8 3153 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3154 return;
3155 }
3156
3157 /* Pick up each field in turn. This used to be done with scanf, but
3158 scanf will make trouble if CORE_ADDR size doesn't match
3159 conversion directives correctly. The following code will work
3160 with any size of CORE_ADDR. */
3161 text_addr = data_addr = bss_addr = 0;
3162 ptr = buf;
3163 lose = 0;
3164
61012eef 3165 if (startswith (ptr, "Text="))
c906108c
SS
3166 {
3167 ptr += 5;
3168 /* Don't use strtol, could lose on big values. */
3169 while (*ptr && *ptr != ';')
3170 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3171
61012eef 3172 if (startswith (ptr, ";Data="))
31d99776
DJ
3173 {
3174 ptr += 6;
3175 while (*ptr && *ptr != ';')
3176 data_addr = (data_addr << 4) + fromhex (*ptr++);
3177 }
3178 else
3179 lose = 1;
3180
61012eef 3181 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3182 {
3183 ptr += 5;
3184 while (*ptr && *ptr != ';')
3185 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3186
31d99776
DJ
3187 if (bss_addr != data_addr)
3188 warning (_("Target reported unsupported offsets: %s"), buf);
3189 }
3190 else
3191 lose = 1;
3192 }
61012eef 3193 else if (startswith (ptr, "TextSeg="))
c906108c 3194 {
31d99776
DJ
3195 ptr += 8;
3196 /* Don't use strtol, could lose on big values. */
c906108c 3197 while (*ptr && *ptr != ';')
31d99776
DJ
3198 text_addr = (text_addr << 4) + fromhex (*ptr++);
3199 num_segments = 1;
3200
61012eef 3201 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3202 {
3203 ptr += 9;
3204 while (*ptr && *ptr != ';')
3205 data_addr = (data_addr << 4) + fromhex (*ptr++);
3206 num_segments++;
3207 }
c906108c
SS
3208 }
3209 else
3210 lose = 1;
3211
3212 if (lose)
8a3fe4f8 3213 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3214 else if (*ptr != '\0')
3215 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3216
802188a7 3217 offs = ((struct section_offsets *)
a39a16c4 3218 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3219 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3220 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3221
31d99776
DJ
3222 data = get_symfile_segment_data (symfile_objfile->obfd);
3223 do_segments = (data != NULL);
3224 do_sections = num_segments == 0;
c906108c 3225
28c32713 3226 if (num_segments > 0)
31d99776 3227 {
31d99776
DJ
3228 segments[0] = text_addr;
3229 segments[1] = data_addr;
3230 }
28c32713
JB
3231 /* If we have two segments, we can still try to relocate everything
3232 by assuming that the .text and .data offsets apply to the whole
3233 text and data segments. Convert the offsets given in the packet
3234 to base addresses for symfile_map_offsets_to_segments. */
3235 else if (data && data->num_segments == 2)
3236 {
3237 segments[0] = data->segment_bases[0] + text_addr;
3238 segments[1] = data->segment_bases[1] + data_addr;
3239 num_segments = 2;
3240 }
8d385431
DJ
3241 /* If the object file has only one segment, assume that it is text
3242 rather than data; main programs with no writable data are rare,
3243 but programs with no code are useless. Of course the code might
3244 have ended up in the data segment... to detect that we would need
3245 the permissions here. */
3246 else if (data && data->num_segments == 1)
3247 {
3248 segments[0] = data->segment_bases[0] + text_addr;
3249 num_segments = 1;
3250 }
28c32713
JB
3251 /* There's no way to relocate by segment. */
3252 else
3253 do_segments = 0;
31d99776
DJ
3254
3255 if (do_segments)
3256 {
3257 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3258 offs, num_segments, segments);
3259
3260 if (ret == 0 && !do_sections)
3e43a32a
MS
3261 error (_("Can not handle qOffsets TextSeg "
3262 "response with this symbol file"));
31d99776
DJ
3263
3264 if (ret > 0)
3265 do_sections = 0;
3266 }
c906108c 3267
9ef895d6
DJ
3268 if (data)
3269 free_symfile_segment_data (data);
31d99776
DJ
3270
3271 if (do_sections)
3272 {
3273 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3274
3e43a32a
MS
3275 /* This is a temporary kludge to force data and bss to use the
3276 same offsets because that's what nlmconv does now. The real
3277 solution requires changes to the stub and remote.c that I
3278 don't have time to do right now. */
31d99776
DJ
3279
3280 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3281 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3282 }
c906108c
SS
3283
3284 objfile_relocate (symfile_objfile, offs);
3285}
3286
74531fed
PA
3287/* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3288 threads we know are stopped already. This is used during the
3289 initial remote connection in non-stop mode --- threads that are
3290 reported as already being stopped are left stopped. */
3291
3292static int
3293set_stop_requested_callback (struct thread_info *thread, void *data)
3294{
3295 /* If we have a stop reply for this thread, it must be stopped. */
3296 if (peek_stop_reply (thread->ptid))
3297 set_stop_requested (thread->ptid, 1);
3298
3299 return 0;
3300}
3301
9a7071a8
JB
3302/* Send interrupt_sequence to remote target. */
3303static void
eeae04df 3304send_interrupt_sequence (void)
9a7071a8 3305{
5d93a237
TT
3306 struct remote_state *rs = get_remote_state ();
3307
9a7071a8 3308 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3309 remote_serial_write ("\x03", 1);
9a7071a8 3310 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3311 serial_send_break (rs->remote_desc);
9a7071a8
JB
3312 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3313 {
5d93a237 3314 serial_send_break (rs->remote_desc);
c33e31fd 3315 remote_serial_write ("g", 1);
9a7071a8
JB
3316 }
3317 else
3318 internal_error (__FILE__, __LINE__,
3319 _("Invalid value for interrupt_sequence_mode: %s."),
3320 interrupt_sequence_mode);
3321}
3322
3405876a
PA
3323
3324/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3325 and extract the PTID. Returns NULL_PTID if not found. */
3326
3327static ptid_t
3328stop_reply_extract_thread (char *stop_reply)
3329{
3330 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3331 {
3332 char *p;
3333
3334 /* Txx r:val ; r:val (...) */
3335 p = &stop_reply[3];
3336
3337 /* Look for "register" named "thread". */
3338 while (*p != '\0')
3339 {
3340 char *p1;
3341
3342 p1 = strchr (p, ':');
3343 if (p1 == NULL)
3344 return null_ptid;
3345
3346 if (strncmp (p, "thread", p1 - p) == 0)
3347 return read_ptid (++p1, &p);
3348
3349 p1 = strchr (p, ';');
3350 if (p1 == NULL)
3351 return null_ptid;
3352 p1++;
3353
3354 p = p1;
3355 }
3356 }
3357
3358 return null_ptid;
3359}
3360
b7ea362b
PA
3361/* Determine the remote side's current thread. If we have a stop
3362 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3363 "thread" register we can extract the current thread from. If not,
3364 ask the remote which is the current thread with qC. The former
3365 method avoids a roundtrip. */
3366
3367static ptid_t
3368get_current_thread (char *wait_status)
3369{
3370 ptid_t ptid;
3371
3372 /* Note we don't use remote_parse_stop_reply as that makes use of
3373 the target architecture, which we haven't yet fully determined at
3374 this point. */
3375 if (wait_status != NULL)
3376 ptid = stop_reply_extract_thread (wait_status);
3377 if (ptid_equal (ptid, null_ptid))
3378 ptid = remote_current_thread (inferior_ptid);
3379
3380 return ptid;
3381}
3382
49c62f2e
PA
3383/* Query the remote target for which is the current thread/process,
3384 add it to our tables, and update INFERIOR_PTID. The caller is
3385 responsible for setting the state such that the remote end is ready
3405876a
PA
3386 to return the current thread.
3387
3388 This function is called after handling the '?' or 'vRun' packets,
3389 whose response is a stop reply from which we can also try
3390 extracting the thread. If the target doesn't support the explicit
3391 qC query, we infer the current thread from that stop reply, passed
3392 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3393
3394static void
3405876a 3395add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3396{
3397 struct remote_state *rs = get_remote_state ();
3398 int fake_pid_p = 0;
3405876a 3399 ptid_t ptid = null_ptid;
49c62f2e
PA
3400
3401 inferior_ptid = null_ptid;
3402
b7ea362b
PA
3403 /* Now, if we have thread information, update inferior_ptid. */
3404 ptid = get_current_thread (wait_status);
3405876a 3405
49c62f2e
PA
3406 if (!ptid_equal (ptid, null_ptid))
3407 {
3408 if (!remote_multi_process_p (rs))
3409 fake_pid_p = 1;
3410
3411 inferior_ptid = ptid;
3412 }
3413 else
3414 {
3415 /* Without this, some commands which require an active target
3416 (such as kill) won't work. This variable serves (at least)
3417 double duty as both the pid of the target process (if it has
3418 such), and as a flag indicating that a target is active. */
3419 inferior_ptid = magic_null_ptid;
3420 fake_pid_p = 1;
3421 }
3422
3423 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1);
3424
3425 /* Add the main thread. */
3426 add_thread_silent (inferior_ptid);
3427}
3428
9cbc821d 3429static void
04bd08de 3430remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 3431{
c8d104ad
PA
3432 struct remote_state *rs = get_remote_state ();
3433 struct packet_config *noack_config;
2d717e4f 3434 char *wait_status = NULL;
8621d6a9 3435
23860348 3436 immediate_quit++; /* Allow user to interrupt it. */
522002f9 3437 QUIT;
c906108c 3438
9a7071a8
JB
3439 if (interrupt_on_connect)
3440 send_interrupt_sequence ();
3441
57e12211 3442 /* Ack any packet which the remote side has already sent. */
5d93a237 3443 serial_write (rs->remote_desc, "+", 1);
57e12211 3444
1e51243a
PA
3445 /* Signal other parts that we're going through the initial setup,
3446 and so things may not be stable yet. */
3447 rs->starting_up = 1;
3448
c8d104ad
PA
3449 /* The first packet we send to the target is the optional "supported
3450 packets" request. If the target can answer this, it will tell us
3451 which later probes to skip. */
3452 remote_query_supported ();
3453
d914c394 3454 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 3455 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 3456 remote_set_permissions (target);
d914c394 3457
c8d104ad
PA
3458 /* Next, we possibly activate noack mode.
3459
3460 If the QStartNoAckMode packet configuration is set to AUTO,
3461 enable noack mode if the stub reported a wish for it with
3462 qSupported.
3463
3464 If set to TRUE, then enable noack mode even if the stub didn't
3465 report it in qSupported. If the stub doesn't reply OK, the
3466 session ends with an error.
3467
3468 If FALSE, then don't activate noack mode, regardless of what the
3469 stub claimed should be the default with qSupported. */
3470
3471 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 3472 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
3473 {
3474 putpkt ("QStartNoAckMode");
3475 getpkt (&rs->buf, &rs->buf_size, 0);
3476 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3477 rs->noack_mode = 1;
3478 }
3479
04bd08de 3480 if (extended_p)
5fe04517
PA
3481 {
3482 /* Tell the remote that we are using the extended protocol. */
3483 putpkt ("!");
3484 getpkt (&rs->buf, &rs->buf_size, 0);
3485 }
3486
9b224c5e
PA
3487 /* Let the target know which signals it is allowed to pass down to
3488 the program. */
3489 update_signals_program_target ();
3490
d962ef82
DJ
3491 /* Next, if the target can specify a description, read it. We do
3492 this before anything involving memory or registers. */
3493 target_find_description ();
3494
6c95b8df
PA
3495 /* Next, now that we know something about the target, update the
3496 address spaces in the program spaces. */
3497 update_address_spaces ();
3498
50c71eaf
PA
3499 /* On OSs where the list of libraries is global to all
3500 processes, we fetch them early. */
f5656ead 3501 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 3502 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 3503
74531fed
PA
3504 if (non_stop)
3505 {
4082afcc 3506 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
3507 error (_("Non-stop mode requested, but remote "
3508 "does not support non-stop"));
74531fed
PA
3509
3510 putpkt ("QNonStop:1");
3511 getpkt (&rs->buf, &rs->buf_size, 0);
3512
3513 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3514 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
3515
3516 /* Find about threads and processes the stub is already
3517 controlling. We default to adding them in the running state.
3518 The '?' query below will then tell us about which threads are
3519 stopped. */
e8032dde 3520 remote_update_thread_list (target);
74531fed 3521 }
4082afcc 3522 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
3523 {
3524 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 3525 Request it explicitly. */
74531fed
PA
3526 putpkt ("QNonStop:0");
3527 getpkt (&rs->buf, &rs->buf_size, 0);
3528
3529 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3530 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
3531 }
3532
a0743c90
YQ
3533 /* Upload TSVs regardless of whether the target is running or not. The
3534 remote stub, such as GDBserver, may have some predefined or builtin
3535 TSVs, even if the target is not running. */
8bd200f1 3536 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
3537 {
3538 struct uploaded_tsv *uploaded_tsvs = NULL;
3539
181e3713 3540 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
3541 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3542 }
3543
2d717e4f
DJ
3544 /* Check whether the target is running now. */
3545 putpkt ("?");
3546 getpkt (&rs->buf, &rs->buf_size, 0);
3547
74531fed 3548 if (!non_stop)
2d717e4f 3549 {
e714e1bf
UW
3550 ptid_t ptid;
3551 int fake_pid_p = 0;
3552 struct inferior *inf;
3553
74531fed 3554 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 3555 {
04bd08de 3556 if (!extended_p)
74531fed 3557 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
3558
3559 /* We're connected, but not running. Drop out before we
3560 call start_remote. */
e278ad5b 3561 rs->starting_up = 0;
c35b1492 3562 return;
2d717e4f
DJ
3563 }
3564 else
74531fed 3565 {
74531fed
PA
3566 /* Save the reply for later. */
3567 wait_status = alloca (strlen (rs->buf) + 1);
3568 strcpy (wait_status, rs->buf);
3569 }
3570
b7ea362b 3571 /* Fetch thread list. */
e8032dde 3572 target_update_thread_list ();
b7ea362b 3573
74531fed
PA
3574 /* Let the stub know that we want it to return the thread. */
3575 set_continue_thread (minus_one_ptid);
3576
b7ea362b
PA
3577 if (thread_count () == 0)
3578 {
3579 /* Target has no concept of threads at all. GDB treats
3580 non-threaded target as single-threaded; add a main
3581 thread. */
3582 add_current_inferior_and_thread (wait_status);
3583 }
3584 else
3585 {
3586 /* We have thread information; select the thread the target
3587 says should be current. If we're reconnecting to a
3588 multi-threaded program, this will ideally be the thread
3589 that last reported an event before GDB disconnected. */
3590 inferior_ptid = get_current_thread (wait_status);
3591 if (ptid_equal (inferior_ptid, null_ptid))
3592 {
3593 /* Odd... The target was able to list threads, but not
3594 tell us which thread was current (no "thread"
3595 register in T stop reply?). Just pick the first
3596 thread in the thread list then. */
3597 inferior_ptid = thread_list->ptid;
3598 }
3599 }
74531fed 3600
6e586cc5
YQ
3601 /* init_wait_for_inferior should be called before get_offsets in order
3602 to manage `inserted' flag in bp loc in a correct state.
3603 breakpoint_init_inferior, called from init_wait_for_inferior, set
3604 `inserted' flag to 0, while before breakpoint_re_set, called from
3605 start_remote, set `inserted' flag to 1. In the initialization of
3606 inferior, breakpoint_init_inferior should be called first, and then
3607 breakpoint_re_set can be called. If this order is broken, state of
3608 `inserted' flag is wrong, and cause some problems on breakpoint
3609 manipulation. */
3610 init_wait_for_inferior ();
3611
74531fed
PA
3612 get_offsets (); /* Get text, data & bss offsets. */
3613
d962ef82
DJ
3614 /* If we could not find a description using qXfer, and we know
3615 how to do it some other way, try again. This is not
3616 supported for non-stop; it could be, but it is tricky if
3617 there are no stopped threads when we connect. */
04bd08de 3618 if (remote_read_description_p (target)
f5656ead 3619 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
3620 {
3621 target_clear_description ();
3622 target_find_description ();
3623 }
3624
74531fed
PA
3625 /* Use the previously fetched status. */
3626 gdb_assert (wait_status != NULL);
3627 strcpy (rs->buf, wait_status);
3628 rs->cached_wait_status = 1;
3629
3630 immediate_quit--;
04bd08de 3631 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
3632 }
3633 else
3634 {
68c97600
PA
3635 /* Clear WFI global state. Do this before finding about new
3636 threads and inferiors, and setting the current inferior.
3637 Otherwise we would clear the proceed status of the current
3638 inferior when we want its stop_soon state to be preserved
3639 (see notice_new_inferior). */
3640 init_wait_for_inferior ();
3641
74531fed
PA
3642 /* In non-stop, we will either get an "OK", meaning that there
3643 are no stopped threads at this time; or, a regular stop
3644 reply. In the latter case, there may be more than one thread
3645 stopped --- we pull them all out using the vStopped
3646 mechanism. */
3647 if (strcmp (rs->buf, "OK") != 0)
3648 {
722247f1 3649 struct notif_client *notif = &notif_client_stop;
2d717e4f 3650
722247f1
YQ
3651 /* remote_notif_get_pending_replies acks this one, and gets
3652 the rest out. */
f48ff2a7 3653 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
3654 = remote_notif_parse (notif, rs->buf);
3655 remote_notif_get_pending_events (notif);
c906108c 3656
74531fed
PA
3657 /* Make sure that threads that were stopped remain
3658 stopped. */
3659 iterate_over_threads (set_stop_requested_callback, NULL);
3660 }
2d717e4f 3661
74531fed
PA
3662 if (target_can_async_p ())
3663 target_async (inferior_event_handler, 0);
c906108c 3664
74531fed
PA
3665 if (thread_count () == 0)
3666 {
04bd08de 3667 if (!extended_p)
74531fed 3668 error (_("The target is not running (try extended-remote?)"));
82f73884 3669
c35b1492
PA
3670 /* We're connected, but not running. Drop out before we
3671 call start_remote. */
e278ad5b 3672 rs->starting_up = 0;
c35b1492
PA
3673 return;
3674 }
74531fed
PA
3675
3676 /* Let the stub know that we want it to return the thread. */
c0a2216e 3677
74531fed
PA
3678 /* Force the stub to choose a thread. */
3679 set_general_thread (null_ptid);
c906108c 3680
74531fed
PA
3681 /* Query it. */
3682 inferior_ptid = remote_current_thread (minus_one_ptid);
3683 if (ptid_equal (inferior_ptid, minus_one_ptid))
3684 error (_("remote didn't report the current thread in non-stop mode"));
c906108c 3685
74531fed
PA
3686 get_offsets (); /* Get text, data & bss offsets. */
3687
3688 /* In non-stop mode, any cached wait status will be stored in
3689 the stop reply queue. */
3690 gdb_assert (wait_status == NULL);
f0223081 3691
2455069d 3692 /* Report all signals during attach/startup. */
94bedb42 3693 remote_pass_signals (target, 0, NULL);
74531fed 3694 }
c8d104ad 3695
c8d104ad
PA
3696 /* If we connected to a live target, do some additional setup. */
3697 if (target_has_execution)
3698 {
f4ccffad 3699 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 3700 remote_check_symbols ();
c8d104ad 3701 }
50c71eaf 3702
d5551862
SS
3703 /* Possibly the target has been engaged in a trace run started
3704 previously; find out where things are at. */
8bd200f1 3705 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 3706 {
00bf0b85 3707 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 3708
00bf0b85
SS
3709 if (current_trace_status ()->running)
3710 printf_filtered (_("Trace is already running on the target.\n"));
3711
ab6617cc 3712 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
3713
3714 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
3715 }
3716
1e51243a
PA
3717 /* The thread and inferior lists are now synchronized with the
3718 target, our symbols have been relocated, and we're merged the
3719 target's tracepoints with ours. We're done with basic start
3720 up. */
3721 rs->starting_up = 0;
3722
a25a5a45
PA
3723 /* Maybe breakpoints are global and need to be inserted now. */
3724 if (breakpoints_should_be_inserted_now ())
50c71eaf 3725 insert_breakpoints ();
c906108c
SS
3726}
3727
3728/* Open a connection to a remote debugger.
3729 NAME is the filename used for communication. */
3730
3731static void
014f9477 3732remote_open (const char *name, int from_tty)
c906108c 3733{
75c99385 3734 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
3735}
3736
c906108c
SS
3737/* Open a connection to a remote debugger using the extended
3738 remote gdb protocol. NAME is the filename used for communication. */
3739
3740static void
014f9477 3741extended_remote_open (const char *name, int from_tty)
c906108c 3742{
75c99385 3743 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
3744}
3745
ca4f7f8b
PA
3746/* Reset all packets back to "unknown support". Called when opening a
3747 new connection to a remote target. */
c906108c 3748
d471ea57 3749static void
ca4f7f8b 3750reset_all_packet_configs_support (void)
d471ea57
AC
3751{
3752 int i;
a744cf53 3753
444abaca 3754 for (i = 0; i < PACKET_MAX; i++)
4082afcc 3755 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
3756}
3757
ca4f7f8b
PA
3758/* Initialize all packet configs. */
3759
3760static void
3761init_all_packet_configs (void)
3762{
3763 int i;
3764
3765 for (i = 0; i < PACKET_MAX; i++)
3766 {
3767 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
3768 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3769 }
3770}
3771
23860348 3772/* Symbol look-up. */
dc8acb97
MS
3773
3774static void
36d25514 3775remote_check_symbols (void)
dc8acb97 3776{
d01949b6 3777 struct remote_state *rs = get_remote_state ();
dc8acb97 3778 char *msg, *reply, *tmp;
3b7344d5 3779 struct bound_minimal_symbol sym;
dc8acb97
MS
3780 int end;
3781
63154eca
PA
3782 /* The remote side has no concept of inferiors that aren't running
3783 yet, it only knows about running processes. If we're connected
3784 but our current inferior is not running, we should not invite the
3785 remote target to request symbol lookups related to its
3786 (unrelated) current process. */
3787 if (!target_has_execution)
3788 return;
3789
4082afcc 3790 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
3791 return;
3792
63154eca
PA
3793 /* Make sure the remote is pointing at the right process. Note
3794 there's no way to select "no process". */
3c9c4b83
PA
3795 set_general_process ();
3796
6d820c5c
DJ
3797 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3798 because we need both at the same time. */
ea9c271d 3799 msg = alloca (get_remote_packet_size ());
6d820c5c 3800
23860348 3801 /* Invite target to request symbol lookups. */
dc8acb97
MS
3802
3803 putpkt ("qSymbol::");
6d820c5c
DJ
3804 getpkt (&rs->buf, &rs->buf_size, 0);
3805 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2e9f7625 3806 reply = rs->buf;
dc8acb97 3807
61012eef 3808 while (startswith (reply, "qSymbol:"))
dc8acb97 3809 {
77e371c0
TT
3810 struct bound_minimal_symbol sym;
3811
dc8acb97 3812 tmp = &reply[8];
cfd77fa1 3813 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
3814 msg[end] = '\0';
3815 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 3816 if (sym.minsym == NULL)
ea9c271d 3817 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 3818 else
2bbe3cc1 3819 {
f5656ead 3820 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 3821 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
3822
3823 /* If this is a function address, return the start of code
3824 instead of any data function descriptor. */
f5656ead 3825 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
3826 sym_addr,
3827 &current_target);
3828
3829 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 3830 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
3831 }
3832
dc8acb97 3833 putpkt (msg);
6d820c5c 3834 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3835 reply = rs->buf;
dc8acb97
MS
3836 }
3837}
3838
9db8d71f 3839static struct serial *
baa336ce 3840remote_serial_open (const char *name)
9db8d71f
DJ
3841{
3842 static int udp_warning = 0;
3843
3844 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3845 of in ser-tcp.c, because it is the remote protocol assuming that the
3846 serial connection is reliable and not the serial connection promising
3847 to be. */
61012eef 3848 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 3849 {
3e43a32a
MS
3850 warning (_("The remote protocol may be unreliable over UDP.\n"
3851 "Some events may be lost, rendering further debugging "
3852 "impossible."));
9db8d71f
DJ
3853 udp_warning = 1;
3854 }
3855
3856 return serial_open (name);
3857}
3858
d914c394
SS
3859/* Inform the target of our permission settings. The permission flags
3860 work without this, but if the target knows the settings, it can do
3861 a couple things. First, it can add its own check, to catch cases
3862 that somehow manage to get by the permissions checks in target
3863 methods. Second, if the target is wired to disallow particular
3864 settings (for instance, a system in the field that is not set up to
3865 be able to stop at a breakpoint), it can object to any unavailable
3866 permissions. */
3867
3868void
c378d69d 3869remote_set_permissions (struct target_ops *self)
d914c394
SS
3870{
3871 struct remote_state *rs = get_remote_state ();
3872
bba74b36
YQ
3873 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3874 "WriteReg:%x;WriteMem:%x;"
3875 "InsertBreak:%x;InsertTrace:%x;"
3876 "InsertFastTrace:%x;Stop:%x",
3877 may_write_registers, may_write_memory,
3878 may_insert_breakpoints, may_insert_tracepoints,
3879 may_insert_fast_tracepoints, may_stop);
d914c394
SS
3880 putpkt (rs->buf);
3881 getpkt (&rs->buf, &rs->buf_size, 0);
3882
3883 /* If the target didn't like the packet, warn the user. Do not try
3884 to undo the user's settings, that would just be maddening. */
3885 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 3886 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
3887}
3888
be2a5f71
DJ
3889/* This type describes each known response to the qSupported
3890 packet. */
3891struct protocol_feature
3892{
3893 /* The name of this protocol feature. */
3894 const char *name;
3895
3896 /* The default for this protocol feature. */
3897 enum packet_support default_support;
3898
3899 /* The function to call when this feature is reported, or after
3900 qSupported processing if the feature is not supported.
3901 The first argument points to this structure. The second
3902 argument indicates whether the packet requested support be
3903 enabled, disabled, or probed (or the default, if this function
3904 is being called at the end of processing and this feature was
3905 not reported). The third argument may be NULL; if not NULL, it
3906 is a NUL-terminated string taken from the packet following
3907 this feature's name and an equals sign. */
3908 void (*func) (const struct protocol_feature *, enum packet_support,
3909 const char *);
3910
3911 /* The corresponding packet for this feature. Only used if
3912 FUNC is remote_supported_packet. */
3913 int packet;
3914};
3915
be2a5f71
DJ
3916static void
3917remote_supported_packet (const struct protocol_feature *feature,
3918 enum packet_support support,
3919 const char *argument)
3920{
3921 if (argument)
3922 {
3923 warning (_("Remote qSupported response supplied an unexpected value for"
3924 " \"%s\"."), feature->name);
3925 return;
3926 }
3927
4082afcc 3928 remote_protocol_packets[feature->packet].support = support;
be2a5f71 3929}
be2a5f71
DJ
3930
3931static void
3932remote_packet_size (const struct protocol_feature *feature,
3933 enum packet_support support, const char *value)
3934{
3935 struct remote_state *rs = get_remote_state ();
3936
3937 int packet_size;
3938 char *value_end;
3939
3940 if (support != PACKET_ENABLE)
3941 return;
3942
3943 if (value == NULL || *value == '\0')
3944 {
3945 warning (_("Remote target reported \"%s\" without a size."),
3946 feature->name);
3947 return;
3948 }
3949
3950 errno = 0;
3951 packet_size = strtol (value, &value_end, 16);
3952 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3953 {
3954 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3955 feature->name, value);
3956 return;
3957 }
3958
3959 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3960 {
3961 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3962 packet_size, MAX_REMOTE_PACKET_SIZE);
3963 packet_size = MAX_REMOTE_PACKET_SIZE;
3964 }
3965
3966 /* Record the new maximum packet size. */
3967 rs->explicit_packet_size = packet_size;
3968}
3969
dc473cfb 3970static const struct protocol_feature remote_protocol_features[] = {
0876f84a 3971 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 3972 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 3973 PACKET_qXfer_auxv },
23181151
DJ
3974 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3975 PACKET_qXfer_features },
cfa9d6d9
DJ
3976 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3977 PACKET_qXfer_libraries },
2268b414
JK
3978 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
3979 PACKET_qXfer_libraries_svr4 },
ced63ec0 3980 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 3981 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 3982 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 3983 PACKET_qXfer_memory_map },
4de6483e
UW
3984 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3985 PACKET_qXfer_spu_read },
3986 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3987 PACKET_qXfer_spu_write },
07e059b5
VP
3988 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3989 PACKET_qXfer_osdata },
dc146f7c
VP
3990 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
3991 PACKET_qXfer_threads },
b3b9301e
PA
3992 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
3993 PACKET_qXfer_traceframe_info },
89be2091
DJ
3994 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3995 PACKET_QPassSignals },
9b224c5e
PA
3996 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
3997 PACKET_QProgramSignals },
a6f3e723
SL
3998 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
3999 PACKET_QStartNoAckMode },
4082afcc
PA
4000 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4001 PACKET_multiprocess_feature },
4002 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4003 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4004 PACKET_qXfer_siginfo_read },
4005 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4006 PACKET_qXfer_siginfo_write },
4082afcc 4007 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4008 PACKET_ConditionalTracepoints },
4082afcc 4009 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4010 PACKET_ConditionalBreakpoints },
4082afcc 4011 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4012 PACKET_BreakpointCommands },
4082afcc 4013 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4014 PACKET_FastTracepoints },
4082afcc 4015 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4016 PACKET_StaticTracepoints },
4082afcc 4017 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4018 PACKET_InstallInTrace},
4082afcc
PA
4019 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4020 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4021 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4022 PACKET_bc },
4023 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4024 PACKET_bs },
409873ef
SS
4025 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4026 PACKET_TracepointSource },
d914c394
SS
4027 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4028 PACKET_QAllow },
4082afcc
PA
4029 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4030 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4031 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4032 PACKET_qXfer_fdpic },
169081d0
TG
4033 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4034 PACKET_qXfer_uib },
03583c20
UW
4035 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4036 PACKET_QDisableRandomization },
d1feda86 4037 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4038 { "QTBuffer:size", PACKET_DISABLE,
4039 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4040 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4041 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4042 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4043 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4044 PACKET_qXfer_btrace },
4045 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4046 PACKET_qXfer_btrace_conf },
4047 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4048 PACKET_Qbtrace_conf_bts_size },
4049 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4050 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature }
be2a5f71
DJ
4051};
4052
c8d5aac9
L
4053static char *remote_support_xml;
4054
4055/* Register string appended to "xmlRegisters=" in qSupported query. */
4056
4057void
6e39997a 4058register_remote_support_xml (const char *xml)
c8d5aac9
L
4059{
4060#if defined(HAVE_LIBEXPAT)
4061 if (remote_support_xml == NULL)
c4f7c687 4062 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4063 else
4064 {
4065 char *copy = xstrdup (remote_support_xml + 13);
4066 char *p = strtok (copy, ",");
4067
4068 do
4069 {
4070 if (strcmp (p, xml) == 0)
4071 {
4072 /* already there */
4073 xfree (copy);
4074 return;
4075 }
4076 }
4077 while ((p = strtok (NULL, ",")) != NULL);
4078 xfree (copy);
4079
94b0dee1
PA
4080 remote_support_xml = reconcat (remote_support_xml,
4081 remote_support_xml, ",", xml,
4082 (char *) NULL);
c8d5aac9
L
4083 }
4084#endif
4085}
4086
4087static char *
4088remote_query_supported_append (char *msg, const char *append)
4089{
4090 if (msg)
94b0dee1 4091 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4092 else
4093 return xstrdup (append);
4094}
4095
be2a5f71
DJ
4096static void
4097remote_query_supported (void)
4098{
4099 struct remote_state *rs = get_remote_state ();
4100 char *next;
4101 int i;
4102 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4103
4104 /* The packet support flags are handled differently for this packet
4105 than for most others. We treat an error, a disabled packet, and
4106 an empty response identically: any features which must be reported
4107 to be used will be automatically disabled. An empty buffer
4108 accomplishes this, since that is also the representation for a list
4109 containing no features. */
4110
4111 rs->buf[0] = 0;
4082afcc 4112 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4113 {
c8d5aac9 4114 char *q = NULL;
94b0dee1 4115 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4116
901f9912 4117 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4118
f7e6eed5
PA
4119 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4120 q = remote_query_supported_append (q, "swbreak+");
4121 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4122 q = remote_query_supported_append (q, "hwbreak+");
4123
c8d5aac9
L
4124 if (remote_support_xml)
4125 q = remote_query_supported_append (q, remote_support_xml);
4126
dde08ee1
PA
4127 q = remote_query_supported_append (q, "qRelocInsn+");
4128
4129 q = reconcat (q, "qSupported:", q, (char *) NULL);
4130 putpkt (q);
82f73884 4131
94b0dee1
PA
4132 do_cleanups (old_chain);
4133
be2a5f71
DJ
4134 getpkt (&rs->buf, &rs->buf_size, 0);
4135
4136 /* If an error occured, warn, but do not return - just reset the
4137 buffer to empty and go on to disable features. */
4138 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4139 == PACKET_ERROR)
4140 {
4141 warning (_("Remote failure reply: %s"), rs->buf);
4142 rs->buf[0] = 0;
4143 }
4144 }
4145
4146 memset (seen, 0, sizeof (seen));
4147
4148 next = rs->buf;
4149 while (*next)
4150 {
4151 enum packet_support is_supported;
4152 char *p, *end, *name_end, *value;
4153
4154 /* First separate out this item from the rest of the packet. If
4155 there's another item after this, we overwrite the separator
4156 (terminated strings are much easier to work with). */
4157 p = next;
4158 end = strchr (p, ';');
4159 if (end == NULL)
4160 {
4161 end = p + strlen (p);
4162 next = end;
4163 }
4164 else
4165 {
89be2091
DJ
4166 *end = '\0';
4167 next = end + 1;
4168
be2a5f71
DJ
4169 if (end == p)
4170 {
4171 warning (_("empty item in \"qSupported\" response"));
4172 continue;
4173 }
be2a5f71
DJ
4174 }
4175
4176 name_end = strchr (p, '=');
4177 if (name_end)
4178 {
4179 /* This is a name=value entry. */
4180 is_supported = PACKET_ENABLE;
4181 value = name_end + 1;
4182 *name_end = '\0';
4183 }
4184 else
4185 {
4186 value = NULL;
4187 switch (end[-1])
4188 {
4189 case '+':
4190 is_supported = PACKET_ENABLE;
4191 break;
4192
4193 case '-':
4194 is_supported = PACKET_DISABLE;
4195 break;
4196
4197 case '?':
4198 is_supported = PACKET_SUPPORT_UNKNOWN;
4199 break;
4200
4201 default:
3e43a32a
MS
4202 warning (_("unrecognized item \"%s\" "
4203 "in \"qSupported\" response"), p);
be2a5f71
DJ
4204 continue;
4205 }
4206 end[-1] = '\0';
4207 }
4208
4209 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4210 if (strcmp (remote_protocol_features[i].name, p) == 0)
4211 {
4212 const struct protocol_feature *feature;
4213
4214 seen[i] = 1;
4215 feature = &remote_protocol_features[i];
4216 feature->func (feature, is_supported, value);
4217 break;
4218 }
4219 }
4220
4221 /* If we increased the packet size, make sure to increase the global
4222 buffer size also. We delay this until after parsing the entire
4223 qSupported packet, because this is the same buffer we were
4224 parsing. */
4225 if (rs->buf_size < rs->explicit_packet_size)
4226 {
4227 rs->buf_size = rs->explicit_packet_size;
4228 rs->buf = xrealloc (rs->buf, rs->buf_size);
4229 }
4230
4231 /* Handle the defaults for unmentioned features. */
4232 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4233 if (!seen[i])
4234 {
4235 const struct protocol_feature *feature;
4236
4237 feature = &remote_protocol_features[i];
4238 feature->func (feature, feature->default_support, NULL);
4239 }
4240}
4241
78a095c3
JK
4242/* Remove any of the remote.c targets from target stack. Upper targets depend
4243 on it so remove them first. */
4244
4245static void
4246remote_unpush_target (void)
4247{
4248 pop_all_targets_above (process_stratum - 1);
4249}
be2a5f71 4250
c906108c 4251static void
014f9477 4252remote_open_1 (const char *name, int from_tty,
3e43a32a 4253 struct target_ops *target, int extended_p)
c906108c 4254{
d01949b6 4255 struct remote_state *rs = get_remote_state ();
a6f3e723 4256
c906108c 4257 if (name == 0)
8a3fe4f8 4258 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4259 "serial device is attached to the remote system\n"
8a3fe4f8 4260 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4261
23860348 4262 /* See FIXME above. */
c6ebd6cf 4263 if (!target_async_permitted)
92d1e331 4264 wait_forever_enabled_p = 1;
6426a772 4265
2d717e4f 4266 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4267 Ask this question first, before target_preopen has a chance to kill
4268 anything. */
5d93a237 4269 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4270 {
78a095c3
JK
4271 if (from_tty
4272 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4273 error (_("Still connected."));
4274 }
4275
78a095c3 4276 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4277 target_preopen (from_tty);
4278
89be2091 4279 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4280 xfree (rs->last_pass_packet);
4281 rs->last_pass_packet = NULL;
89be2091 4282
9b224c5e
PA
4283 /* Make sure we send the program signals list the next time we
4284 resume. */
5e4a05c4
TT
4285 xfree (rs->last_program_signals_packet);
4286 rs->last_program_signals_packet = NULL;
9b224c5e 4287
ad9a8f3f 4288 remote_fileio_reset ();
1dd41f16
NS
4289 reopen_exec_file ();
4290 reread_symbols ();
4291
5d93a237
TT
4292 rs->remote_desc = remote_serial_open (name);
4293 if (!rs->remote_desc)
c906108c
SS
4294 perror_with_name (name);
4295
4296 if (baud_rate != -1)
4297 {
5d93a237 4298 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4299 {
9b74d5d3
KB
4300 /* The requested speed could not be set. Error out to
4301 top level after closing remote_desc. Take care to
4302 set remote_desc to NULL to avoid closing remote_desc
4303 more than once. */
5d93a237
TT
4304 serial_close (rs->remote_desc);
4305 rs->remote_desc = NULL;
c906108c
SS
4306 perror_with_name (name);
4307 }
4308 }
4309
5d93a237 4310 serial_raw (rs->remote_desc);
c906108c
SS
4311
4312 /* If there is something sitting in the buffer we might take it as a
4313 response to a command, which would be bad. */
5d93a237 4314 serial_flush_input (rs->remote_desc);
c906108c
SS
4315
4316 if (from_tty)
4317 {
4318 puts_filtered ("Remote debugging using ");
4319 puts_filtered (name);
4320 puts_filtered ("\n");
4321 }
23860348 4322 push_target (target); /* Switch to using remote target now. */
c906108c 4323
74531fed
PA
4324 /* Register extra event sources in the event loop. */
4325 remote_async_inferior_event_token
4326 = create_async_event_handler (remote_async_inferior_event_handler,
4327 NULL);
5965e028 4328 rs->notif_state = remote_notif_state_allocate ();
74531fed 4329
be2a5f71
DJ
4330 /* Reset the target state; these things will be queried either by
4331 remote_query_supported or as they are needed. */
ca4f7f8b 4332 reset_all_packet_configs_support ();
74531fed 4333 rs->cached_wait_status = 0;
be2a5f71 4334 rs->explicit_packet_size = 0;
a6f3e723 4335 rs->noack_mode = 0;
82f73884 4336 rs->extended = extended_p;
e24a49d8 4337 rs->waiting_for_stop_reply = 0;
3a29589a 4338 rs->ctrlc_pending_p = 0;
802188a7 4339
47f8a51d
TT
4340 rs->general_thread = not_sent_ptid;
4341 rs->continue_thread = not_sent_ptid;
262e1174 4342 rs->remote_traceframe_number = -1;
c906108c 4343
9d1f7ab2 4344 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
4345 rs->use_threadinfo_query = 1;
4346 rs->use_threadextra_query = 1;
9d1f7ab2 4347
c6ebd6cf 4348 if (target_async_permitted)
92d1e331 4349 {
23860348 4350 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4351 remote_async_terminal_ours_p = 1;
4352
4353 /* FIXME: cagney/1999-09-23: During the initial connection it is
4354 assumed that the target is already ready and able to respond to
0df8b418 4355 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4356 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4357 around this. Eventually a mechanism that allows
92d1e331 4358 wait_for_inferior() to expect/get timeouts will be
23860348 4359 implemented. */
92d1e331
DJ
4360 wait_forever_enabled_p = 0;
4361 }
4362
23860348 4363 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4364 no_shared_libraries (NULL, 0);
f78f6cf1 4365
74531fed
PA
4366 /* Start afresh. */
4367 init_thread_list ();
4368
36918e70 4369 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4370 target (we'd otherwise be in an inconsistent state) and then
4371 propogate the error on up the exception chain. This ensures that
4372 the caller doesn't stumble along blindly assuming that the
4373 function succeeded. The CLI doesn't have this problem but other
4374 UI's, such as MI do.
36918e70
AC
4375
4376 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4377 this function should return an error indication letting the
ce2826aa 4378 caller restore the previous state. Unfortunately the command
36918e70
AC
4379 ``target remote'' is directly wired to this function making that
4380 impossible. On a positive note, the CLI side of this problem has
4381 been fixed - the function set_cmd_context() makes it possible for
4382 all the ``target ....'' commands to share a common callback
4383 function. See cli-dump.c. */
109c3e39 4384 {
04bd08de 4385 volatile struct gdb_exception ex;
2d717e4f 4386
04bd08de
TT
4387 TRY_CATCH (ex, RETURN_MASK_ALL)
4388 {
4389 remote_start_remote (from_tty, target, extended_p);
4390 }
109c3e39
AC
4391 if (ex.reason < 0)
4392 {
c8d104ad
PA
4393 /* Pop the partially set up target - unless something else did
4394 already before throwing the exception. */
5d93a237 4395 if (rs->remote_desc != NULL)
78a095c3 4396 remote_unpush_target ();
c6ebd6cf 4397 if (target_async_permitted)
109c3e39
AC
4398 wait_forever_enabled_p = 1;
4399 throw_exception (ex);
4400 }
4401 }
c906108c 4402
f4abbc16
MM
4403 remote_btrace_reset ();
4404
c6ebd6cf 4405 if (target_async_permitted)
92d1e331 4406 wait_forever_enabled_p = 1;
43ff13b4
JM
4407}
4408
c906108c
SS
4409/* This takes a program previously attached to and detaches it. After
4410 this is done, GDB can be used to debug some other program. We
4411 better not have left any breakpoints in the target program or it'll
4412 die when it hits one. */
4413
4414static void
52554a0e 4415remote_detach_1 (const char *args, int from_tty, int extended)
c906108c 4416{
82f73884 4417 int pid = ptid_get_pid (inferior_ptid);
d01949b6 4418 struct remote_state *rs = get_remote_state ();
c906108c
SS
4419
4420 if (args)
8a3fe4f8 4421 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 4422
2d717e4f
DJ
4423 if (!target_has_execution)
4424 error (_("No process to detach from."));
4425
7cee1e54
PA
4426 if (from_tty)
4427 {
4428 char *exec_file = get_exec_file (0);
4429 if (exec_file == NULL)
4430 exec_file = "";
4431 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4432 target_pid_to_str (pid_to_ptid (pid)));
4433 gdb_flush (gdb_stdout);
4434 }
4435
c906108c 4436 /* Tell the remote target to detach. */
82f73884 4437 if (remote_multi_process_p (rs))
bba74b36 4438 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
82f73884
PA
4439 else
4440 strcpy (rs->buf, "D");
4441
4ddda9b5
PA
4442 putpkt (rs->buf);
4443 getpkt (&rs->buf, &rs->buf_size, 0);
4444
82f73884
PA
4445 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4446 ;
4447 else if (rs->buf[0] == '\0')
4448 error (_("Remote doesn't know how to detach"));
4449 else
4ddda9b5 4450 error (_("Can't detach process."));
c906108c 4451
7cee1e54
PA
4452 if (from_tty && !extended)
4453 puts_filtered (_("Ending remote debugging.\n"));
82f73884 4454
82f73884 4455 target_mourn_inferior ();
2d717e4f
DJ
4456}
4457
4458static void
52554a0e 4459remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f
DJ
4460{
4461 remote_detach_1 (args, from_tty, 0);
4462}
4463
4464static void
52554a0e 4465extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f
DJ
4466{
4467 remote_detach_1 (args, from_tty, 1);
c906108c
SS
4468}
4469
6ad8ae5c
DJ
4470/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4471
43ff13b4 4472static void
fee354ee 4473remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 4474{
43ff13b4 4475 if (args)
2d717e4f 4476 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 4477
2d717e4f
DJ
4478 /* Make sure we unpush even the extended remote targets; mourn
4479 won't do it. So call remote_mourn_1 directly instead of
4480 target_mourn_inferior. */
4481 remote_mourn_1 (target);
4482
43ff13b4
JM
4483 if (from_tty)
4484 puts_filtered ("Ending remote debugging.\n");
4485}
4486
2d717e4f
DJ
4487/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4488 be chatty about it. */
4489
4490static void
c0939df1
TT
4491extended_remote_attach_1 (struct target_ops *target, const char *args,
4492 int from_tty)
2d717e4f
DJ
4493{
4494 struct remote_state *rs = get_remote_state ();
be86555c 4495 int pid;
96ef3384 4496 char *wait_status = NULL;
2d717e4f 4497
74164c56 4498 pid = parse_pid_to_attach (args);
2d717e4f 4499
74164c56
JK
4500 /* Remote PID can be freely equal to getpid, do not check it here the same
4501 way as in other targets. */
2d717e4f 4502
4082afcc 4503 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
4504 error (_("This target does not support attaching to a process"));
4505
7cee1e54
PA
4506 if (from_tty)
4507 {
4508 char *exec_file = get_exec_file (0);
4509
4510 if (exec_file)
4511 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4512 target_pid_to_str (pid_to_ptid (pid)));
4513 else
4514 printf_unfiltered (_("Attaching to %s\n"),
4515 target_pid_to_str (pid_to_ptid (pid)));
4516
4517 gdb_flush (gdb_stdout);
4518 }
4519
bba74b36 4520 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
4521 putpkt (rs->buf);
4522 getpkt (&rs->buf, &rs->buf_size, 0);
4523
4082afcc
PA
4524 switch (packet_ok (rs->buf,
4525 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 4526 {
4082afcc 4527 case PACKET_OK:
74531fed
PA
4528 if (!non_stop)
4529 {
4530 /* Save the reply for later. */
4531 wait_status = alloca (strlen (rs->buf) + 1);
4532 strcpy (wait_status, rs->buf);
4533 }
4534 else if (strcmp (rs->buf, "OK") != 0)
4535 error (_("Attaching to %s failed with: %s"),
4536 target_pid_to_str (pid_to_ptid (pid)),
4537 rs->buf);
4082afcc
PA
4538 break;
4539 case PACKET_UNKNOWN:
4540 error (_("This target does not support attaching to a process"));
4541 default:
4542 error (_("Attaching to %s failed"),
4543 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 4544 }
2d717e4f 4545
49c62f2e 4546 set_current_inferior (remote_add_inferior (0, pid, 1));
bad34192 4547
2d717e4f 4548 inferior_ptid = pid_to_ptid (pid);
79d7f229 4549
bad34192
PA
4550 if (non_stop)
4551 {
4552 struct thread_info *thread;
79d7f229 4553
bad34192 4554 /* Get list of threads. */
e8032dde 4555 remote_update_thread_list (target);
82f73884 4556
bad34192
PA
4557 thread = first_thread_of_process (pid);
4558 if (thread)
4559 inferior_ptid = thread->ptid;
4560 else
4561 inferior_ptid = pid_to_ptid (pid);
4562
4563 /* Invalidate our notion of the remote current thread. */
47f8a51d 4564 record_currthread (rs, minus_one_ptid);
bad34192 4565 }
74531fed 4566 else
bad34192
PA
4567 {
4568 /* Now, if we have thread information, update inferior_ptid. */
4569 inferior_ptid = remote_current_thread (inferior_ptid);
4570
4571 /* Add the main thread to the thread list. */
4572 add_thread_silent (inferior_ptid);
4573 }
c0a2216e 4574
96ef3384
UW
4575 /* Next, if the target can specify a description, read it. We do
4576 this before anything involving memory or registers. */
4577 target_find_description ();
4578
74531fed
PA
4579 if (!non_stop)
4580 {
4581 /* Use the previously fetched status. */
4582 gdb_assert (wait_status != NULL);
4583
4584 if (target_can_async_p ())
4585 {
722247f1
YQ
4586 struct notif_event *reply
4587 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 4588
722247f1 4589 push_stop_reply ((struct stop_reply *) reply);
74531fed
PA
4590
4591 target_async (inferior_event_handler, 0);
4592 }
4593 else
4594 {
4595 gdb_assert (wait_status != NULL);
4596 strcpy (rs->buf, wait_status);
4597 rs->cached_wait_status = 1;
4598 }
4599 }
4600 else
4601 gdb_assert (wait_status == NULL);
2d717e4f
DJ
4602}
4603
4604static void
c0939df1 4605extended_remote_attach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4606{
136d6dae 4607 extended_remote_attach_1 (ops, args, from_tty);
2d717e4f
DJ
4608}
4609
b9c1d481
AS
4610/* Implementation of the to_post_attach method. */
4611
4612static void
4613extended_remote_post_attach (struct target_ops *ops, int pid)
4614{
4615 /* In certain cases GDB might not have had the chance to start
4616 symbol lookup up until now. This could happen if the debugged
4617 binary is not using shared libraries, the vsyscall page is not
4618 present (on Linux) and the binary itself hadn't changed since the
4619 debugging process was started. */
4620 if (symfile_objfile != NULL)
4621 remote_check_symbols();
4622}
4623
c906108c 4624\f
506fb367
DJ
4625/* Check for the availability of vCont. This function should also check
4626 the response. */
c906108c
SS
4627
4628static void
6d820c5c 4629remote_vcont_probe (struct remote_state *rs)
c906108c 4630{
2e9f7625 4631 char *buf;
6d820c5c 4632
2e9f7625
DJ
4633 strcpy (rs->buf, "vCont?");
4634 putpkt (rs->buf);
6d820c5c 4635 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4636 buf = rs->buf;
c906108c 4637
506fb367 4638 /* Make sure that the features we assume are supported. */
61012eef 4639 if (startswith (buf, "vCont"))
506fb367
DJ
4640 {
4641 char *p = &buf[5];
4642 int support_s, support_S, support_c, support_C;
4643
4644 support_s = 0;
4645 support_S = 0;
4646 support_c = 0;
4647 support_C = 0;
d458bd84 4648 rs->supports_vCont.t = 0;
c1e36e3e 4649 rs->supports_vCont.r = 0;
506fb367
DJ
4650 while (p && *p == ';')
4651 {
4652 p++;
4653 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4654 support_s = 1;
4655 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4656 support_S = 1;
4657 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4658 support_c = 1;
4659 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4660 support_C = 1;
74531fed 4661 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 4662 rs->supports_vCont.t = 1;
c1e36e3e
PA
4663 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4664 rs->supports_vCont.r = 1;
506fb367
DJ
4665
4666 p = strchr (p, ';');
4667 }
c906108c 4668
506fb367
DJ
4669 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4670 BUF will make packet_ok disable the packet. */
4671 if (!support_s || !support_S || !support_c || !support_C)
4672 buf[0] = 0;
4673 }
c906108c 4674
444abaca 4675 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 4676}
c906108c 4677
0d8f58ca
PA
4678/* Helper function for building "vCont" resumptions. Write a
4679 resumption to P. ENDP points to one-passed-the-end of the buffer
4680 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4681 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4682 resumed thread should be single-stepped and/or signalled. If PTID
4683 equals minus_one_ptid, then all threads are resumed; if PTID
4684 represents a process, then all threads of the process are resumed;
4685 the thread to be stepped and/or signalled is given in the global
4686 INFERIOR_PTID. */
4687
4688static char *
4689append_resumption (char *p, char *endp,
2ea28649 4690 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
4691{
4692 struct remote_state *rs = get_remote_state ();
4693
a493e3e2 4694 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 4695 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
4696 else if (step
4697 /* GDB is willing to range step. */
4698 && use_range_stepping
4699 /* Target supports range stepping. */
4700 && rs->supports_vCont.r
4701 /* We don't currently support range stepping multiple
4702 threads with a wildcard (though the protocol allows it,
4703 so stubs shouldn't make an active effort to forbid
4704 it). */
4705 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4706 {
4707 struct thread_info *tp;
4708
4709 if (ptid_equal (ptid, minus_one_ptid))
4710 {
4711 /* If we don't know about the target thread's tid, then
4712 we're resuming magic_null_ptid (see caller). */
4713 tp = find_thread_ptid (magic_null_ptid);
4714 }
4715 else
4716 tp = find_thread_ptid (ptid);
4717 gdb_assert (tp != NULL);
4718
4719 if (tp->control.may_range_step)
4720 {
4721 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4722
4723 p += xsnprintf (p, endp - p, ";r%s,%s",
4724 phex_nz (tp->control.step_range_start,
4725 addr_size),
4726 phex_nz (tp->control.step_range_end,
4727 addr_size));
4728 }
4729 else
4730 p += xsnprintf (p, endp - p, ";s");
4731 }
0d8f58ca
PA
4732 else if (step)
4733 p += xsnprintf (p, endp - p, ";s");
a493e3e2 4734 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
4735 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4736 else
4737 p += xsnprintf (p, endp - p, ";c");
4738
4739 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4740 {
4741 ptid_t nptid;
4742
4743 /* All (-1) threads of process. */
ba348170 4744 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
4745
4746 p += xsnprintf (p, endp - p, ":");
4747 p = write_ptid (p, endp, nptid);
4748 }
4749 else if (!ptid_equal (ptid, minus_one_ptid))
4750 {
4751 p += xsnprintf (p, endp - p, ":");
4752 p = write_ptid (p, endp, ptid);
4753 }
4754
4755 return p;
4756}
4757
e5ef252a
PA
4758/* Append a vCont continue-with-signal action for threads that have a
4759 non-zero stop signal. */
4760
4761static char *
4762append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4763{
4764 struct thread_info *thread;
4765
034f788c 4766 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
4767 if (ptid_match (thread->ptid, ptid)
4768 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 4769 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
4770 {
4771 p = append_resumption (p, endp, thread->ptid,
4772 0, thread->suspend.stop_signal);
4773 thread->suspend.stop_signal = GDB_SIGNAL_0;
4774 }
4775
4776 return p;
4777}
4778
506fb367
DJ
4779/* Resume the remote inferior by using a "vCont" packet. The thread
4780 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
4781 resumed thread should be single-stepped and/or signalled. If PTID
4782 equals minus_one_ptid, then all threads are resumed; the thread to
4783 be stepped and/or signalled is given in the global INFERIOR_PTID.
4784 This function returns non-zero iff it resumes the inferior.
44eaed12 4785
506fb367
DJ
4786 This function issues a strict subset of all possible vCont commands at the
4787 moment. */
44eaed12 4788
506fb367 4789static int
2ea28649 4790remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
4791{
4792 struct remote_state *rs = get_remote_state ();
82f73884
PA
4793 char *p;
4794 char *endp;
44eaed12 4795
4082afcc 4796 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 4797 remote_vcont_probe (rs);
44eaed12 4798
4082afcc 4799 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 4800 return 0;
44eaed12 4801
82f73884
PA
4802 p = rs->buf;
4803 endp = rs->buf + get_remote_packet_size ();
4804
506fb367
DJ
4805 /* If we could generate a wider range of packets, we'd have to worry
4806 about overflowing BUF. Should there be a generic
4807 "multi-part-packet" packet? */
4808
0d8f58ca
PA
4809 p += xsnprintf (p, endp - p, "vCont");
4810
79d7f229 4811 if (ptid_equal (ptid, magic_null_ptid))
c906108c 4812 {
79d7f229
PA
4813 /* MAGIC_NULL_PTID means that we don't have any active threads,
4814 so we don't have any TID numbers the inferior will
4815 understand. Make sure to only send forms that do not specify
4816 a TID. */
a9cbf802 4817 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 4818 }
0d8f58ca 4819 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 4820 {
0d8f58ca
PA
4821 /* Resume all threads (of all processes, or of a single
4822 process), with preference for INFERIOR_PTID. This assumes
4823 inferior_ptid belongs to the set of all threads we are about
4824 to resume. */
a493e3e2 4825 if (step || siggnal != GDB_SIGNAL_0)
82f73884 4826 {
0d8f58ca
PA
4827 /* Step inferior_ptid, with or without signal. */
4828 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 4829 }
0d8f58ca 4830
e5ef252a
PA
4831 /* Also pass down any pending signaled resumption for other
4832 threads not the current. */
4833 p = append_pending_thread_resumptions (p, endp, ptid);
4834
0d8f58ca 4835 /* And continue others without a signal. */
a493e3e2 4836 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
4837 }
4838 else
506fb367
DJ
4839 {
4840 /* Scheduler locking; resume only PTID. */
a9cbf802 4841 append_resumption (p, endp, ptid, step, siggnal);
506fb367 4842 }
c906108c 4843
82f73884
PA
4844 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4845 putpkt (rs->buf);
506fb367 4846
74531fed
PA
4847 if (non_stop)
4848 {
4849 /* In non-stop, the stub replies to vCont with "OK". The stop
4850 reply will be reported asynchronously by means of a `%Stop'
4851 notification. */
4852 getpkt (&rs->buf, &rs->buf_size, 0);
4853 if (strcmp (rs->buf, "OK") != 0)
4854 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4855 }
4856
506fb367 4857 return 1;
c906108c 4858}
43ff13b4 4859
506fb367
DJ
4860/* Tell the remote machine to resume. */
4861
43ff13b4 4862static void
28439f5e 4863remote_resume (struct target_ops *ops,
2ea28649 4864 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 4865{
d01949b6 4866 struct remote_state *rs = get_remote_state ();
2e9f7625 4867 char *buf;
43ff13b4 4868
722247f1
YQ
4869 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
4870 (explained in remote-notif.c:handle_notification) so
4871 remote_notif_process is not called. We need find a place where
4872 it is safe to start a 'vNotif' sequence. It is good to do it
4873 before resuming inferior, because inferior was stopped and no RSP
4874 traffic at that moment. */
4875 if (!non_stop)
5965e028 4876 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 4877
b73be471 4878 rs->last_sent_signal = siggnal;
280ceea3 4879 rs->last_sent_step = step;
43ff13b4 4880
506fb367 4881 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
4882 /* No reverse support (yet) for vCont. */
4883 if (execution_direction != EXEC_REVERSE)
4884 if (remote_vcont_resume (ptid, step, siggnal))
4885 goto done;
506fb367 4886
79d7f229
PA
4887 /* All other supported resume packets do use Hc, so set the continue
4888 thread. */
4889 if (ptid_equal (ptid, minus_one_ptid))
4890 set_continue_thread (any_thread_ptid);
506fb367 4891 else
79d7f229 4892 set_continue_thread (ptid);
506fb367 4893
2e9f7625 4894 buf = rs->buf;
b2175913
MS
4895 if (execution_direction == EXEC_REVERSE)
4896 {
4897 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 4898 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 4899 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 4900 siggnal);
40ab02ce 4901
4082afcc 4902 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
40ab02ce 4903 error (_("Remote reverse-step not supported."));
4082afcc 4904 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
08c93ed9 4905 error (_("Remote reverse-continue not supported."));
40ab02ce 4906
b2175913
MS
4907 strcpy (buf, step ? "bs" : "bc");
4908 }
a493e3e2 4909 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
4910 {
4911 buf[0] = step ? 'S' : 'C';
c5aa993b 4912 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 4913 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
4914 buf[3] = '\0';
4915 }
4916 else
c5aa993b 4917 strcpy (buf, step ? "s" : "c");
506fb367 4918
44eaed12 4919 putpkt (buf);
43ff13b4 4920
75c99385 4921 done:
2acceee2 4922 /* We are about to start executing the inferior, let's register it
0df8b418
MS
4923 with the event loop. NOTE: this is the one place where all the
4924 execution commands end up. We could alternatively do this in each
23860348 4925 of the execution commands in infcmd.c. */
2acceee2
JM
4926 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4927 into infcmd.c in order to allow inferior function calls to work
23860348 4928 NOT asynchronously. */
362646f5 4929 if (target_can_async_p ())
2acceee2 4930 target_async (inferior_event_handler, 0);
e24a49d8
PA
4931
4932 /* We've just told the target to resume. The remote server will
4933 wait for the inferior to stop, and then send a stop reply. In
4934 the mean time, we can't start another command/query ourselves
74531fed
PA
4935 because the stub wouldn't be ready to process it. This applies
4936 only to the base all-stop protocol, however. In non-stop (which
4937 only supports vCont), the stub replies with an "OK", and is
4938 immediate able to process further serial input. */
4939 if (!non_stop)
4940 rs->waiting_for_stop_reply = 1;
43ff13b4 4941}
c906108c 4942\f
43ff13b4
JM
4943
4944/* Set up the signal handler for SIGINT, while the target is
23860348 4945 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 4946static void
934b9bac 4947async_initialize_sigint_signal_handler (void)
43ff13b4 4948{
934b9bac 4949 signal (SIGINT, async_handle_remote_sigint);
43ff13b4
JM
4950}
4951
23860348 4952/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 4953static void
934b9bac 4954async_handle_remote_sigint (int sig)
43ff13b4 4955{
934b9bac 4956 signal (sig, async_handle_remote_sigint_twice);
b2ee242b
PA
4957 /* Note we need to go through gdb_call_async_signal_handler in order
4958 to wake up the event loop on Windows. */
4959 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
43ff13b4
JM
4960}
4961
4962/* Signal handler for SIGINT, installed after SIGINT has already been
4963 sent once. It will take effect the second time that the user sends
23860348 4964 a ^C. */
43ff13b4 4965static void
934b9bac 4966async_handle_remote_sigint_twice (int sig)
43ff13b4 4967{
934b9bac 4968 signal (sig, async_handle_remote_sigint);
b2ee242b
PA
4969 /* See note in async_handle_remote_sigint. */
4970 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
43ff13b4
JM
4971}
4972
6426a772 4973/* Perform the real interruption of the target execution, in response
23860348 4974 to a ^C. */
c5aa993b 4975static void
fba45db2 4976async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
4977{
4978 if (remote_debug)
248fd3bf 4979 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
43ff13b4 4980
94cc34af 4981 target_stop (inferior_ptid);
43ff13b4
JM
4982}
4983
0df8b418 4984/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 4985 up on the target alltogether. */
47e1ce27 4986static void
fba45db2 4987async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 4988{
2df3850c 4989 if (remote_debug)
248fd3bf 4990 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
b803fb0f
DJ
4991
4992 interrupt_query ();
43ff13b4
JM
4993}
4994
4995/* Reinstall the usual SIGINT handlers, after the target has
23860348 4996 stopped. */
6426a772 4997static void
934b9bac 4998async_cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
4999{
5000 signal (SIGINT, handle_sigint);
43ff13b4
JM
5001}
5002
c906108c
SS
5003/* Send ^C to target to halt it. Target will respond, and send us a
5004 packet. */
507f3c78 5005static void (*ofunc) (int);
c906108c 5006
0df8b418
MS
5007/* The command line interface's stop routine. This function is installed
5008 as a signal handler for SIGINT. The first time a user requests a
5009 stop, we call remote_stop to send a break or ^C. If there is no
7a292a7a 5010 response from the target (it didn't stop when the user requested it),
23860348 5011 we ask the user if he'd like to detach from the target. */
c906108c 5012static void
934b9bac 5013sync_remote_interrupt (int signo)
c906108c 5014{
23860348 5015 /* If this doesn't work, try more severe steps. */
934b9bac 5016 signal (signo, sync_remote_interrupt_twice);
7a292a7a 5017
934b9bac 5018 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
7a292a7a
SS
5019}
5020
5021/* The user typed ^C twice. */
5022
5023static void
934b9bac 5024sync_remote_interrupt_twice (int signo)
7a292a7a
SS
5025{
5026 signal (signo, ofunc);
934b9bac
JK
5027 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5028 signal (signo, sync_remote_interrupt);
c906108c 5029}
7a292a7a 5030
74531fed
PA
5031/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5032 thread, all threads of a remote process, or all threads of all
5033 processes. */
5034
5035static void
5036remote_stop_ns (ptid_t ptid)
5037{
5038 struct remote_state *rs = get_remote_state ();
5039 char *p = rs->buf;
5040 char *endp = rs->buf + get_remote_packet_size ();
74531fed 5041
4082afcc 5042 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
5043 remote_vcont_probe (rs);
5044
d458bd84 5045 if (!rs->supports_vCont.t)
74531fed
PA
5046 error (_("Remote server does not support stopping threads"));
5047
f91d3df5
PA
5048 if (ptid_equal (ptid, minus_one_ptid)
5049 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5050 p += xsnprintf (p, endp - p, "vCont;t");
5051 else
5052 {
5053 ptid_t nptid;
5054
74531fed
PA
5055 p += xsnprintf (p, endp - p, "vCont;t:");
5056
5057 if (ptid_is_pid (ptid))
5058 /* All (-1) threads of process. */
ba348170 5059 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
5060 else
5061 {
5062 /* Small optimization: if we already have a stop reply for
5063 this thread, no use in telling the stub we want this
5064 stopped. */
5065 if (peek_stop_reply (ptid))
5066 return;
5067
5068 nptid = ptid;
5069 }
5070
a9cbf802 5071 write_ptid (p, endp, nptid);
74531fed
PA
5072 }
5073
5074 /* In non-stop, we get an immediate OK reply. The stop reply will
5075 come in asynchronously by notification. */
5076 putpkt (rs->buf);
5077 getpkt (&rs->buf, &rs->buf_size, 0);
5078 if (strcmp (rs->buf, "OK") != 0)
5079 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5080}
5081
5082/* All-stop version of target_stop. Sends a break or a ^C to stop the
5083 remote target. It is undefined which thread of which process
5084 reports the stop. */
5085
5086static void
5087remote_stop_as (ptid_t ptid)
5088{
5089 struct remote_state *rs = get_remote_state ();
5090
3a29589a
DJ
5091 rs->ctrlc_pending_p = 1;
5092
74531fed
PA
5093 /* If the inferior is stopped already, but the core didn't know
5094 about it yet, just ignore the request. The cached wait status
5095 will be collected in remote_wait. */
5096 if (rs->cached_wait_status)
5097 return;
5098
9a7071a8
JB
5099 /* Send interrupt_sequence to remote target. */
5100 send_interrupt_sequence ();
74531fed
PA
5101}
5102
0df8b418 5103/* This is the generic stop called via the target vector. When a target
7a292a7a 5104 interrupt is requested, either by the command line or the GUI, we
23860348 5105 will eventually end up here. */
74531fed 5106
c906108c 5107static void
1eab8a48 5108remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5109{
7a292a7a 5110 if (remote_debug)
0f71a2f6 5111 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5112
74531fed
PA
5113 if (non_stop)
5114 remote_stop_ns (ptid);
c906108c 5115 else
74531fed 5116 remote_stop_as (ptid);
c906108c
SS
5117}
5118
5119/* Ask the user what to do when an interrupt is received. */
5120
5121static void
fba45db2 5122interrupt_query (void)
c906108c
SS
5123{
5124 target_terminal_ours ();
5125
d9d41e78 5126 if (target_is_async_p ())
c906108c 5127 {
74531fed 5128 signal (SIGINT, handle_sigint);
039e3c22 5129 quit ();
c906108c 5130 }
74531fed
PA
5131 else
5132 {
9e2f0ad4
HZ
5133 if (query (_("Interrupted while waiting for the program.\n\
5134Give up (and stop debugging it)? ")))
74531fed 5135 {
78a095c3 5136 remote_unpush_target ();
039e3c22 5137 quit ();
74531fed
PA
5138 }
5139 }
c906108c
SS
5140
5141 target_terminal_inferior ();
5142}
5143
6426a772
JM
5144/* Enable/disable target terminal ownership. Most targets can use
5145 terminal groups to control terminal ownership. Remote targets are
5146 different in that explicit transfer of ownership to/from GDB/target
23860348 5147 is required. */
6426a772
JM
5148
5149static void
d2f640d4 5150remote_terminal_inferior (struct target_ops *self)
6426a772 5151{
c6ebd6cf 5152 if (!target_async_permitted)
75c99385
PA
5153 /* Nothing to do. */
5154 return;
5155
d9d2d8b6
PA
5156 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5157 idempotent. The event-loop GDB talking to an asynchronous target
5158 with a synchronous command calls this function from both
5159 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5160 transfer the terminal to the target when it shouldn't this guard
5161 can go away. */
6426a772
JM
5162 if (!remote_async_terminal_ours_p)
5163 return;
5164 delete_file_handler (input_fd);
5165 remote_async_terminal_ours_p = 0;
934b9bac 5166 async_initialize_sigint_signal_handler ();
6426a772
JM
5167 /* NOTE: At this point we could also register our selves as the
5168 recipient of all input. Any characters typed could then be
23860348 5169 passed on down to the target. */
6426a772
JM
5170}
5171
5172static void
e3594fd1 5173remote_terminal_ours (struct target_ops *self)
6426a772 5174{
c6ebd6cf 5175 if (!target_async_permitted)
75c99385
PA
5176 /* Nothing to do. */
5177 return;
5178
5179 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5180 if (remote_async_terminal_ours_p)
5181 return;
934b9bac 5182 async_cleanup_sigint_signal_handler (NULL);
6426a772
JM
5183 add_file_handler (input_fd, stdin_event_handler, 0);
5184 remote_async_terminal_ours_p = 1;
5185}
5186
176a6961 5187static void
917317f4 5188remote_console_output (char *msg)
c906108c
SS
5189{
5190 char *p;
5191
c5aa993b 5192 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5193 {
5194 char tb[2];
5195 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5196
c906108c
SS
5197 tb[0] = c;
5198 tb[1] = 0;
43ff13b4 5199 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5200 }
00db5b94
PA
5201 gdb_flush (gdb_stdtarg);
5202}
74531fed
PA
5203
5204typedef struct cached_reg
5205{
5206 int num;
5207 gdb_byte data[MAX_REGISTER_SIZE];
5208} cached_reg_t;
5209
5210DEF_VEC_O(cached_reg_t);
5211
722247f1 5212typedef struct stop_reply
74531fed 5213{
722247f1 5214 struct notif_event base;
74531fed 5215
722247f1 5216 /* The identifier of the thread about this event */
74531fed
PA
5217 ptid_t ptid;
5218
340e3c99 5219 /* The remote state this event is associated with. When the remote
bcc75809
YQ
5220 connection, represented by a remote_state object, is closed,
5221 all the associated stop_reply events should be released. */
5222 struct remote_state *rs;
5223
74531fed
PA
5224 struct target_waitstatus ws;
5225
15148d6a
PA
5226 /* Expedited registers. This makes remote debugging a bit more
5227 efficient for those targets that provide critical registers as
5228 part of their normal status mechanism (as another roundtrip to
5229 fetch them is avoided). */
74531fed
PA
5230 VEC(cached_reg_t) *regcache;
5231
f7e6eed5
PA
5232 enum target_stop_reason stop_reason;
5233
74531fed
PA
5234 CORE_ADDR watch_data_address;
5235
dc146f7c 5236 int core;
722247f1 5237} *stop_reply_p;
a744cf53 5238
722247f1
YQ
5239DECLARE_QUEUE_P (stop_reply_p);
5240DEFINE_QUEUE_P (stop_reply_p);
5241/* The list of already fetched and acknowledged stop events. This
5242 queue is used for notification Stop, and other notifications
5243 don't need queue for their events, because the notification events
5244 of Stop can't be consumed immediately, so that events should be
5245 queued first, and be consumed by remote_wait_{ns,as} one per
5246 time. Other notifications can consume their events immediately,
5247 so queue is not needed for them. */
5248static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
5249
5250static void
5251stop_reply_xfree (struct stop_reply *r)
5252{
f48ff2a7 5253 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
5254}
5255
722247f1
YQ
5256static void
5257remote_notif_stop_parse (struct notif_client *self, char *buf,
5258 struct notif_event *event)
5259{
5260 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5261}
5262
5263static void
5264remote_notif_stop_ack (struct notif_client *self, char *buf,
5265 struct notif_event *event)
5266{
5267 struct stop_reply *stop_reply = (struct stop_reply *) event;
5268
5269 /* acknowledge */
5270 putpkt ((char *) self->ack_command);
5271
5272 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5273 /* We got an unknown stop reply. */
5274 error (_("Unknown stop reply"));
5275
5276 push_stop_reply (stop_reply);
5277}
5278
5279static int
5280remote_notif_stop_can_get_pending_events (struct notif_client *self)
5281{
5282 /* We can't get pending events in remote_notif_process for
5283 notification stop, and we have to do this in remote_wait_ns
5284 instead. If we fetch all queued events from stub, remote stub
5285 may exit and we have no chance to process them back in
5286 remote_wait_ns. */
5287 mark_async_event_handler (remote_async_inferior_event_token);
5288 return 0;
5289}
5290
5291static void
5292stop_reply_dtr (struct notif_event *event)
5293{
5294 struct stop_reply *r = (struct stop_reply *) event;
5295
5296 VEC_free (cached_reg_t, r->regcache);
5297}
5298
5299static struct notif_event *
5300remote_notif_stop_alloc_reply (void)
5301{
5302 struct notif_event *r
70ba0933 5303 = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
5304
5305 r->dtr = stop_reply_dtr;
5306
5307 return r;
5308}
5309
5310/* A client of notification Stop. */
5311
5312struct notif_client notif_client_stop =
5313{
5314 "Stop",
5315 "vStopped",
5316 remote_notif_stop_parse,
5317 remote_notif_stop_ack,
5318 remote_notif_stop_can_get_pending_events,
5319 remote_notif_stop_alloc_reply,
f48ff2a7 5320 REMOTE_NOTIF_STOP,
722247f1
YQ
5321};
5322
5323/* A parameter to pass data in and out. */
5324
5325struct queue_iter_param
5326{
5327 void *input;
5328 struct stop_reply *output;
5329};
5330
f48ff2a7
YQ
5331/* Remove stop replies in the queue if its pid is equal to the given
5332 inferior's pid. */
722247f1
YQ
5333
5334static int
f48ff2a7
YQ
5335remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5336 QUEUE_ITER (stop_reply_p) *iter,
5337 stop_reply_p event,
5338 void *data)
722247f1
YQ
5339{
5340 struct queue_iter_param *param = data;
5341 struct inferior *inf = param->input;
5342
f48ff2a7 5343 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
5344 {
5345 stop_reply_xfree (event);
5346 QUEUE_remove_elem (stop_reply_p, q, iter);
5347 }
5348
5349 return 1;
5350}
5351
f48ff2a7 5352/* Discard all pending stop replies of inferior INF. */
c906108c 5353
74531fed 5354static void
5f4cf0bb 5355discard_pending_stop_replies (struct inferior *inf)
c906108c 5356{
722247f1
YQ
5357 int i;
5358 struct queue_iter_param param;
f48ff2a7
YQ
5359 struct stop_reply *reply;
5360 struct remote_state *rs = get_remote_state ();
5361 struct remote_notif_state *rns = rs->notif_state;
5362
5363 /* This function can be notified when an inferior exists. When the
5364 target is not remote, the notification state is NULL. */
5365 if (rs->remote_desc == NULL)
5366 return;
5367
5368 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 5369
74531fed 5370 /* Discard the in-flight notification. */
f48ff2a7 5371 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 5372 {
722247f1 5373 stop_reply_xfree (reply);
f48ff2a7 5374 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 5375 }
c906108c 5376
722247f1
YQ
5377 param.input = inf;
5378 param.output = NULL;
74531fed
PA
5379 /* Discard the stop replies we have already pulled with
5380 vStopped. */
722247f1 5381 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
5382 remove_stop_reply_for_inferior, &param);
5383}
5384
bcc75809
YQ
5385/* If its remote state is equal to the given remote state,
5386 remove EVENT from the stop reply queue. */
5387
5388static int
5389remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5390 QUEUE_ITER (stop_reply_p) *iter,
5391 stop_reply_p event,
5392 void *data)
5393{
5394 struct queue_iter_param *param = data;
5395 struct remote_state *rs = param->input;
5396
5397 if (event->rs == rs)
5398 {
5399 stop_reply_xfree (event);
5400 QUEUE_remove_elem (stop_reply_p, q, iter);
5401 }
5402
5403 return 1;
5404}
5405
5406/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
5407
5408static void
bcc75809 5409discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
5410{
5411 struct queue_iter_param param;
5412
bcc75809 5413 param.input = rs;
f48ff2a7
YQ
5414 param.output = NULL;
5415 /* Discard the stop replies we have already pulled with
5416 vStopped. */
5417 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 5418 remove_stop_reply_of_remote_state, &param);
722247f1 5419}
74531fed 5420
722247f1
YQ
5421/* A parameter to pass data in and out. */
5422
5423static int
5424remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5425 QUEUE_ITER (stop_reply_p) *iter,
5426 stop_reply_p event,
5427 void *data)
5428{
5429 struct queue_iter_param *param = data;
5430 ptid_t *ptid = param->input;
5431
5432 if (ptid_match (event->ptid, *ptid))
5433 {
5434 param->output = event;
5435 QUEUE_remove_elem (stop_reply_p, q, iter);
5436 return 0;
c8e38a49 5437 }
722247f1
YQ
5438
5439 return 1;
74531fed 5440}
43ff13b4 5441
722247f1
YQ
5442/* Remove the first reply in 'stop_reply_queue' which matches
5443 PTID. */
2e9f7625 5444
722247f1
YQ
5445static struct stop_reply *
5446remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 5447{
722247f1
YQ
5448 struct queue_iter_param param;
5449
5450 param.input = &ptid;
5451 param.output = NULL;
5452
5453 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5454 remote_notif_remove_once_on_match, &param);
5455 if (notif_debug)
5456 fprintf_unfiltered (gdb_stdlog,
5457 "notif: discard queued event: 'Stop' in %s\n",
5458 target_pid_to_str (ptid));
a744cf53 5459
722247f1 5460 return param.output;
74531fed 5461}
75c99385 5462
74531fed
PA
5463/* Look for a queued stop reply belonging to PTID. If one is found,
5464 remove it from the queue, and return it. Returns NULL if none is
5465 found. If there are still queued events left to process, tell the
5466 event loop to get back to target_wait soon. */
e24a49d8 5467
74531fed
PA
5468static struct stop_reply *
5469queued_stop_reply (ptid_t ptid)
5470{
722247f1 5471 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 5472
722247f1 5473 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
5474 /* There's still at least an event left. */
5475 mark_async_event_handler (remote_async_inferior_event_token);
5476
722247f1 5477 return r;
74531fed
PA
5478}
5479
5480/* Push a fully parsed stop reply in the stop reply queue. Since we
5481 know that we now have at least one queued event left to pass to the
5482 core side, tell the event loop to get back to target_wait soon. */
5483
5484static void
5485push_stop_reply (struct stop_reply *new_event)
5486{
722247f1 5487 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 5488
722247f1
YQ
5489 if (notif_debug)
5490 fprintf_unfiltered (gdb_stdlog,
5491 "notif: push 'Stop' %s to queue %d\n",
5492 target_pid_to_str (new_event->ptid),
5493 QUEUE_length (stop_reply_p,
5494 stop_reply_queue));
74531fed
PA
5495
5496 mark_async_event_handler (remote_async_inferior_event_token);
5497}
5498
722247f1
YQ
5499static int
5500stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5501 QUEUE_ITER (stop_reply_p) *iter,
5502 struct stop_reply *event,
5503 void *data)
5504{
5505 ptid_t *ptid = data;
5506
5507 return !(ptid_equal (*ptid, event->ptid)
5508 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5509}
5510
74531fed
PA
5511/* Returns true if we have a stop reply for PTID. */
5512
5513static int
5514peek_stop_reply (ptid_t ptid)
5515{
722247f1
YQ
5516 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5517 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
5518}
5519
1f10ba14
PA
5520/* Skip PACKET until the next semi-colon (or end of string). */
5521
5522static char *
5523skip_to_semicolon (char *p)
5524{
5525 while (*p != '\0' && *p != ';')
5526 p++;
5527 return p;
5528}
5529
74531fed
PA
5530/* Parse the stop reply in BUF. Either the function succeeds, and the
5531 result is stored in EVENT, or throws an error. */
5532
5533static void
5534remote_parse_stop_reply (char *buf, struct stop_reply *event)
5535{
5536 struct remote_arch_state *rsa = get_remote_arch_state ();
5537 ULONGEST addr;
5538 char *p;
5539
5540 event->ptid = null_ptid;
bcc75809 5541 event->rs = get_remote_state ();
74531fed
PA
5542 event->ws.kind = TARGET_WAITKIND_IGNORE;
5543 event->ws.value.integer = 0;
f7e6eed5 5544 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 5545 event->regcache = NULL;
dc146f7c 5546 event->core = -1;
74531fed
PA
5547
5548 switch (buf[0])
5549 {
5550 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
5551 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5552 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5553 ss = signal number
5554 n... = register number
5555 r... = register contents
5556 */
5557
5558 p = &buf[3]; /* after Txx */
5559 while (*p)
5560 {
5561 char *p1;
cea39f65 5562 int fieldsize;
43ff13b4 5563
1f10ba14
PA
5564 p1 = strchr (p, ':');
5565 if (p1 == NULL)
5566 error (_("Malformed packet(a) (missing colon): %s\n\
5567Packet: '%s'\n"),
5568 p, buf);
5569 if (p == p1)
5570 error (_("Malformed packet(a) (missing register number): %s\n\
5571Packet: '%s'\n"),
5572 p, buf);
3c3bea1c 5573
1f10ba14
PA
5574 /* Some "registers" are actually extended stop information.
5575 Note if you're adding a new entry here: GDB 7.9 and
5576 earlier assume that all register "numbers" that start
5577 with an hex digit are real register numbers. Make sure
5578 the server only sends such a packet if it knows the
5579 client understands it. */
c8e38a49 5580
1f10ba14
PA
5581 if (strncmp (p, "thread", p1 - p) == 0)
5582 event->ptid = read_ptid (++p1, &p);
5583 else if ((strncmp (p, "watch", p1 - p) == 0)
5584 || (strncmp (p, "rwatch", p1 - p) == 0)
5585 || (strncmp (p, "awatch", p1 - p) == 0))
cea39f65 5586 {
f7e6eed5 5587 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
5588 p = unpack_varlen_hex (++p1, &addr);
5589 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 5590 }
f7e6eed5
PA
5591 else if (strncmp (p, "swbreak", p1 - p) == 0)
5592 {
5593 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
5594
5595 /* Make sure the stub doesn't forget to indicate support
5596 with qSupported. */
5597 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
5598 error (_("Unexpected swbreak stop reason"));
5599
5600 /* The value part is documented as "must be empty",
5601 though we ignore it, in case we ever decide to make
5602 use of it in a backward compatible way. */
5603 p = skip_to_semicolon (p1 + 1);
5604 }
5605 else if (strncmp (p, "hwbreak", p1 - p) == 0)
5606 {
5607 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
5608
5609 /* Make sure the stub doesn't forget to indicate support
5610 with qSupported. */
5611 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
5612 error (_("Unexpected hwbreak stop reason"));
5613
5614 /* See above. */
5615 p = skip_to_semicolon (p1 + 1);
5616 }
1f10ba14 5617 else if (strncmp (p, "library", p1 - p) == 0)
cea39f65 5618 {
1f10ba14
PA
5619 event->ws.kind = TARGET_WAITKIND_LOADED;
5620 p = skip_to_semicolon (p1 + 1);
5621 }
5622 else if (strncmp (p, "replaylog", p1 - p) == 0)
5623 {
5624 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5625 /* p1 will indicate "begin" or "end", but it makes
5626 no difference for now, so ignore it. */
5627 p = skip_to_semicolon (p1 + 1);
5628 }
5629 else if (strncmp (p, "core", p1 - p) == 0)
5630 {
5631 ULONGEST c;
a744cf53 5632
1f10ba14
PA
5633 p = unpack_varlen_hex (++p1, &c);
5634 event->core = c;
cea39f65
MS
5635 }
5636 else
5637 {
1f10ba14
PA
5638 ULONGEST pnum;
5639 char *p_temp;
5640
5641 /* Maybe a real ``P'' register number. */
5642 p_temp = unpack_varlen_hex (p, &pnum);
5643 /* If the first invalid character is the colon, we got a
5644 register number. Otherwise, it's an unknown stop
5645 reason. */
5646 if (p_temp == p1)
5647 {
5648 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5649 cached_reg_t cached_reg;
43ff13b4 5650
1f10ba14
PA
5651 if (reg == NULL)
5652 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 5653Packet: '%s'\n"),
1f10ba14 5654 hex_string (pnum), p, buf);
c8e38a49 5655
1f10ba14 5656 cached_reg.num = reg->regnum;
4100683b 5657
1f10ba14
PA
5658 p = p1 + 1;
5659 fieldsize = hex2bin (p, cached_reg.data,
5660 register_size (target_gdbarch (),
5661 reg->regnum));
5662 p += 2 * fieldsize;
5663 if (fieldsize < register_size (target_gdbarch (),
5664 reg->regnum))
5665 warning (_("Remote reply is too short: %s"), buf);
74531fed 5666
1f10ba14
PA
5667 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5668 }
5669 else
5670 {
5671 /* Not a number. Silently skip unknown optional
5672 info. */
5673 p = skip_to_semicolon (p1 + 1);
5674 }
cea39f65 5675 }
c8e38a49 5676
cea39f65
MS
5677 if (*p != ';')
5678 error (_("Remote register badly formatted: %s\nhere: %s"),
5679 buf, p);
5680 ++p;
5681 }
5b5596ff
PA
5682
5683 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
5684 break;
5685
c8e38a49
PA
5686 /* fall through */
5687 case 'S': /* Old style status, just signal only. */
3a09da41
PA
5688 {
5689 int sig;
5690
5691 event->ws.kind = TARGET_WAITKIND_STOPPED;
5692 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
5693 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
5694 event->ws.value.sig = (enum gdb_signal) sig;
5695 else
5696 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5697 }
c8e38a49
PA
5698 break;
5699 case 'W': /* Target exited. */
5700 case 'X':
5701 {
5702 char *p;
5703 int pid;
5704 ULONGEST value;
82f73884 5705
c8e38a49
PA
5706 /* GDB used to accept only 2 hex chars here. Stubs should
5707 only send more if they detect GDB supports multi-process
5708 support. */
5709 p = unpack_varlen_hex (&buf[1], &value);
82f73884 5710
c8e38a49
PA
5711 if (buf[0] == 'W')
5712 {
5713 /* The remote process exited. */
74531fed
PA
5714 event->ws.kind = TARGET_WAITKIND_EXITED;
5715 event->ws.value.integer = value;
c8e38a49
PA
5716 }
5717 else
5718 {
5719 /* The remote process exited with a signal. */
74531fed 5720 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
5721 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
5722 event->ws.value.sig = (enum gdb_signal) value;
5723 else
5724 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 5725 }
82f73884 5726
c8e38a49
PA
5727 /* If no process is specified, assume inferior_ptid. */
5728 pid = ptid_get_pid (inferior_ptid);
5729 if (*p == '\0')
5730 ;
5731 else if (*p == ';')
5732 {
5733 p++;
5734
0b24eb2d 5735 if (*p == '\0')
82f73884 5736 ;
61012eef 5737 else if (startswith (p, "process:"))
82f73884 5738 {
c8e38a49 5739 ULONGEST upid;
a744cf53 5740
c8e38a49
PA
5741 p += sizeof ("process:") - 1;
5742 unpack_varlen_hex (p, &upid);
5743 pid = upid;
82f73884
PA
5744 }
5745 else
5746 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 5747 }
c8e38a49
PA
5748 else
5749 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
5750 event->ptid = pid_to_ptid (pid);
5751 }
5752 break;
5753 }
5754
5755 if (non_stop && ptid_equal (event->ptid, null_ptid))
5756 error (_("No process or thread specified in stop reply: %s"), buf);
5757}
5758
722247f1
YQ
5759/* When the stub wants to tell GDB about a new notification reply, it
5760 sends a notification (%Stop, for example). Those can come it at
5761 any time, hence, we have to make sure that any pending
5762 putpkt/getpkt sequence we're making is finished, before querying
5763 the stub for more events with the corresponding ack command
5764 (vStopped, for example). E.g., if we started a vStopped sequence
5765 immediately upon receiving the notification, something like this
5766 could happen:
74531fed
PA
5767
5768 1.1) --> Hg 1
5769 1.2) <-- OK
5770 1.3) --> g
5771 1.4) <-- %Stop
5772 1.5) --> vStopped
5773 1.6) <-- (registers reply to step #1.3)
5774
5775 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5776 query.
5777
796cb314 5778 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
5779 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5780 doing whatever we were doing:
5781
5782 2.1) --> Hg 1
5783 2.2) <-- OK
5784 2.3) --> g
5785 2.4) <-- %Stop
5786 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5787 2.5) <-- (registers reply to step #2.3)
5788
5789 Eventualy after step #2.5, we return to the event loop, which
5790 notices there's an event on the
5791 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5792 associated callback --- the function below. At this point, we're
5793 always safe to start a vStopped sequence. :
5794
5795 2.6) --> vStopped
5796 2.7) <-- T05 thread:2
5797 2.8) --> vStopped
5798 2.9) --> OK
5799*/
5800
722247f1
YQ
5801void
5802remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
5803{
5804 struct remote_state *rs = get_remote_state ();
74531fed 5805
f48ff2a7 5806 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 5807 {
722247f1
YQ
5808 if (notif_debug)
5809 fprintf_unfiltered (gdb_stdlog,
5810 "notif: process: '%s' ack pending event\n",
5811 nc->name);
74531fed 5812
722247f1 5813 /* acknowledge */
f48ff2a7
YQ
5814 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
5815 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
5816
5817 while (1)
5818 {
5819 getpkt (&rs->buf, &rs->buf_size, 0);
5820 if (strcmp (rs->buf, "OK") == 0)
5821 break;
5822 else
722247f1 5823 remote_notif_ack (nc, rs->buf);
74531fed
PA
5824 }
5825 }
722247f1
YQ
5826 else
5827 {
5828 if (notif_debug)
5829 fprintf_unfiltered (gdb_stdlog,
5830 "notif: process: '%s' no pending reply\n",
5831 nc->name);
5832 }
74531fed
PA
5833}
5834
74531fed
PA
5835/* Called when it is decided that STOP_REPLY holds the info of the
5836 event that is to be returned to the core. This function always
5837 destroys STOP_REPLY. */
5838
5839static ptid_t
5840process_stop_reply (struct stop_reply *stop_reply,
5841 struct target_waitstatus *status)
5842{
5843 ptid_t ptid;
5844
5845 *status = stop_reply->ws;
5846 ptid = stop_reply->ptid;
5847
5848 /* If no thread/process was reported by the stub, assume the current
5849 inferior. */
5850 if (ptid_equal (ptid, null_ptid))
5851 ptid = inferior_ptid;
5852
5f3563ea
PA
5853 if (status->kind != TARGET_WAITKIND_EXITED
5854 && status->kind != TARGET_WAITKIND_SIGNALLED)
74531fed 5855 {
ee154bee
TT
5856 struct remote_state *rs = get_remote_state ();
5857
5f3563ea
PA
5858 /* Expedited registers. */
5859 if (stop_reply->regcache)
5860 {
217f1f79 5861 struct regcache *regcache
f5656ead 5862 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
5863 cached_reg_t *reg;
5864 int ix;
5865
5866 for (ix = 0;
5867 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5868 ix++)
217f1f79 5869 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
5870 VEC_free (cached_reg_t, stop_reply->regcache);
5871 }
74531fed 5872
f7e6eed5 5873 rs->stop_reason = stop_reply->stop_reason;
ee154bee 5874 rs->remote_watch_data_address = stop_reply->watch_data_address;
1941c569
PA
5875
5876 remote_notice_new_inferior (ptid, 0);
dc146f7c 5877 demand_private_info (ptid)->core = stop_reply->core;
74531fed
PA
5878 }
5879
74531fed
PA
5880 stop_reply_xfree (stop_reply);
5881 return ptid;
5882}
5883
5884/* The non-stop mode version of target_wait. */
5885
5886static ptid_t
47608cb1 5887remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
5888{
5889 struct remote_state *rs = get_remote_state ();
74531fed
PA
5890 struct stop_reply *stop_reply;
5891 int ret;
fee9eda9 5892 int is_notif = 0;
74531fed
PA
5893
5894 /* If in non-stop mode, get out of getpkt even if a
5895 notification is received. */
5896
5897 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 5898 0 /* forever */, &is_notif);
74531fed
PA
5899 while (1)
5900 {
fee9eda9 5901 if (ret != -1 && !is_notif)
74531fed
PA
5902 switch (rs->buf[0])
5903 {
5904 case 'E': /* Error of some sort. */
5905 /* We're out of sync with the target now. Did it continue
5906 or not? We can't tell which thread it was in non-stop,
5907 so just ignore this. */
5908 warning (_("Remote failure reply: %s"), rs->buf);
5909 break;
5910 case 'O': /* Console output. */
5911 remote_console_output (rs->buf + 1);
5912 break;
5913 default:
5914 warning (_("Invalid remote reply: %s"), rs->buf);
5915 break;
5916 }
5917
5918 /* Acknowledge a pending stop reply that may have arrived in the
5919 mean time. */
f48ff2a7 5920 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 5921 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
5922
5923 /* If indeed we noticed a stop reply, we're done. */
5924 stop_reply = queued_stop_reply (ptid);
5925 if (stop_reply != NULL)
5926 return process_stop_reply (stop_reply, status);
5927
47608cb1 5928 /* Still no event. If we're just polling for an event, then
74531fed 5929 return to the event loop. */
47608cb1 5930 if (options & TARGET_WNOHANG)
74531fed
PA
5931 {
5932 status->kind = TARGET_WAITKIND_IGNORE;
5933 return minus_one_ptid;
5934 }
5935
47608cb1 5936 /* Otherwise do a blocking wait. */
74531fed 5937 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 5938 1 /* forever */, &is_notif);
74531fed
PA
5939 }
5940}
5941
5942/* Wait until the remote machine stops, then return, storing status in
5943 STATUS just as `wait' would. */
5944
5945static ptid_t
47608cb1 5946remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
5947{
5948 struct remote_state *rs = get_remote_state ();
74531fed 5949 ptid_t event_ptid = null_ptid;
cea39f65 5950 char *buf;
74531fed
PA
5951 struct stop_reply *stop_reply;
5952
47608cb1
PA
5953 again:
5954
74531fed
PA
5955 status->kind = TARGET_WAITKIND_IGNORE;
5956 status->value.integer = 0;
5957
5958 stop_reply = queued_stop_reply (ptid);
5959 if (stop_reply != NULL)
5960 return process_stop_reply (stop_reply, status);
5961
5962 if (rs->cached_wait_status)
5963 /* Use the cached wait status, but only once. */
5964 rs->cached_wait_status = 0;
5965 else
5966 {
5967 int ret;
722247f1 5968 int is_notif;
74531fed
PA
5969
5970 if (!target_is_async_p ())
5971 {
934b9bac 5972 ofunc = signal (SIGINT, sync_remote_interrupt);
74531fed
PA
5973 /* If the user hit C-c before this packet, or between packets,
5974 pretend that it was hit right here. */
522002f9 5975 if (check_quit_flag ())
74531fed 5976 {
522002f9 5977 clear_quit_flag ();
934b9bac 5978 sync_remote_interrupt (SIGINT);
74531fed
PA
5979 }
5980 }
5981
5982 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5983 _never_ wait for ever -> test on target_is_async_p().
5984 However, before we do that we need to ensure that the caller
5985 knows how to take the target into/out of async mode. */
722247f1
YQ
5986 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5987 wait_forever_enabled_p, &is_notif);
5988
5e1b953b
SDJ
5989 if (!target_is_async_p ())
5990 signal (SIGINT, ofunc);
5991
722247f1
YQ
5992 /* GDB gets a notification. Return to core as this event is
5993 not interesting. */
5994 if (ret != -1 && is_notif)
5995 return minus_one_ptid;
74531fed
PA
5996 }
5997
5998 buf = rs->buf;
5999
f7e6eed5 6000 rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed
PA
6001
6002 /* We got something. */
6003 rs->waiting_for_stop_reply = 0;
6004
3a29589a
DJ
6005 /* Assume that the target has acknowledged Ctrl-C unless we receive
6006 an 'F' or 'O' packet. */
6007 if (buf[0] != 'F' && buf[0] != 'O')
6008 rs->ctrlc_pending_p = 0;
6009
74531fed
PA
6010 switch (buf[0])
6011 {
6012 case 'E': /* Error of some sort. */
6013 /* We're out of sync with the target now. Did it continue or
6014 not? Not is more likely, so report a stop. */
6015 warning (_("Remote failure reply: %s"), buf);
6016 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 6017 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
6018 break;
6019 case 'F': /* File-I/O request. */
3a29589a
DJ
6020 remote_fileio_request (buf, rs->ctrlc_pending_p);
6021 rs->ctrlc_pending_p = 0;
74531fed
PA
6022 break;
6023 case 'T': case 'S': case 'X': case 'W':
6024 {
722247f1
YQ
6025 struct stop_reply *stop_reply
6026 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6027 rs->buf);
74531fed 6028
74531fed 6029 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
6030 break;
6031 }
6032 case 'O': /* Console output. */
6033 remote_console_output (buf + 1);
e24a49d8 6034
c8e38a49
PA
6035 /* The target didn't really stop; keep waiting. */
6036 rs->waiting_for_stop_reply = 1;
e24a49d8 6037
c8e38a49
PA
6038 break;
6039 case '\0':
b73be471 6040 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
6041 {
6042 /* Zero length reply means that we tried 'S' or 'C' and the
6043 remote system doesn't support it. */
6044 target_terminal_ours_for_output ();
6045 printf_filtered
6046 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
6047 gdb_signal_to_name (rs->last_sent_signal));
6048 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
6049 target_terminal_inferior ();
6050
280ceea3 6051 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49
PA
6052 putpkt ((char *) buf);
6053
6054 /* We just told the target to resume, so a stop reply is in
6055 order. */
e24a49d8 6056 rs->waiting_for_stop_reply = 1;
c8e38a49 6057 break;
43ff13b4 6058 }
c8e38a49
PA
6059 /* else fallthrough */
6060 default:
6061 warning (_("Invalid remote reply: %s"), buf);
6062 /* Keep waiting. */
6063 rs->waiting_for_stop_reply = 1;
6064 break;
43ff13b4 6065 }
c8e38a49 6066
c8e38a49 6067 if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
6068 {
6069 /* Nothing interesting happened. If we're doing a non-blocking
6070 poll, we're done. Otherwise, go back to waiting. */
6071 if (options & TARGET_WNOHANG)
6072 return minus_one_ptid;
6073 else
6074 goto again;
6075 }
74531fed
PA
6076 else if (status->kind != TARGET_WAITKIND_EXITED
6077 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
6078 {
6079 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 6080 record_currthread (rs, event_ptid);
82f73884
PA
6081 else
6082 event_ptid = inferior_ptid;
43ff13b4 6083 }
74531fed
PA
6084 else
6085 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 6086 record_currthread (rs, minus_one_ptid);
79d7f229 6087
82f73884 6088 return event_ptid;
43ff13b4
JM
6089}
6090
74531fed
PA
6091/* Wait until the remote machine stops, then return, storing status in
6092 STATUS just as `wait' would. */
6093
c8e38a49 6094static ptid_t
117de6a9 6095remote_wait (struct target_ops *ops,
47608cb1 6096 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
6097{
6098 ptid_t event_ptid;
6099
74531fed 6100 if (non_stop)
47608cb1 6101 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 6102 else
47608cb1 6103 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 6104
d9d41e78 6105 if (target_is_async_p ())
c8e38a49 6106 {
74531fed
PA
6107 /* If there are are events left in the queue tell the event loop
6108 to return here. */
722247f1 6109 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 6110 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 6111 }
c8e38a49
PA
6112
6113 return event_ptid;
6114}
6115
74ca34ce 6116/* Fetch a single register using a 'p' packet. */
c906108c 6117
b96ec7ac 6118static int
56be3814 6119fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
6120{
6121 struct remote_state *rs = get_remote_state ();
2e9f7625 6122 char *buf, *p;
b96ec7ac
AC
6123 char regp[MAX_REGISTER_SIZE];
6124 int i;
6125
4082afcc 6126 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
6127 return 0;
6128
6129 if (reg->pnum == -1)
6130 return 0;
6131
2e9f7625 6132 p = rs->buf;
fcad0fa4 6133 *p++ = 'p';
74ca34ce 6134 p += hexnumstr (p, reg->pnum);
fcad0fa4 6135 *p++ = '\0';
1f4437a4
MS
6136 putpkt (rs->buf);
6137 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 6138
2e9f7625
DJ
6139 buf = rs->buf;
6140
74ca34ce
DJ
6141 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6142 {
6143 case PACKET_OK:
6144 break;
6145 case PACKET_UNKNOWN:
6146 return 0;
6147 case PACKET_ERROR:
27a9c0bf
MS
6148 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6149 gdbarch_register_name (get_regcache_arch (regcache),
6150 reg->regnum),
6151 buf);
74ca34ce 6152 }
3f9a994c
JB
6153
6154 /* If this register is unfetchable, tell the regcache. */
6155 if (buf[0] == 'x')
8480adf2 6156 {
56be3814 6157 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 6158 return 1;
b96ec7ac 6159 }
b96ec7ac 6160
3f9a994c
JB
6161 /* Otherwise, parse and supply the value. */
6162 p = buf;
6163 i = 0;
6164 while (p[0] != 0)
6165 {
6166 if (p[1] == 0)
74ca34ce 6167 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
6168
6169 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6170 p += 2;
6171 }
56be3814 6172 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 6173 return 1;
b96ec7ac
AC
6174}
6175
74ca34ce
DJ
6176/* Fetch the registers included in the target's 'g' packet. */
6177
29709017
DJ
6178static int
6179send_g_packet (void)
c906108c 6180{
d01949b6 6181 struct remote_state *rs = get_remote_state ();
cea39f65 6182 int buf_len;
c906108c 6183
bba74b36 6184 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 6185 remote_send (&rs->buf, &rs->buf_size);
c906108c 6186
29709017
DJ
6187 /* We can get out of synch in various cases. If the first character
6188 in the buffer is not a hex character, assume that has happened
6189 and try to fetch another packet to read. */
6190 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6191 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6192 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6193 && rs->buf[0] != 'x') /* New: unavailable register value. */
6194 {
6195 if (remote_debug)
6196 fprintf_unfiltered (gdb_stdlog,
6197 "Bad register packet; fetching a new packet\n");
6198 getpkt (&rs->buf, &rs->buf_size, 0);
6199 }
6200
74ca34ce
DJ
6201 buf_len = strlen (rs->buf);
6202
6203 /* Sanity check the received packet. */
6204 if (buf_len % 2 != 0)
6205 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
6206
6207 return buf_len / 2;
6208}
6209
6210static void
56be3814 6211process_g_packet (struct regcache *regcache)
29709017 6212{
4a22f64d 6213 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
6214 struct remote_state *rs = get_remote_state ();
6215 struct remote_arch_state *rsa = get_remote_arch_state ();
6216 int i, buf_len;
6217 char *p;
6218 char *regs;
6219
6220 buf_len = strlen (rs->buf);
6221
6222 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
6223 if (buf_len > 2 * rsa->sizeof_g_packet)
6224 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6225
6226 /* Save the size of the packet sent to us by the target. It is used
6227 as a heuristic when determining the max size of packets that the
6228 target can safely receive. */
6229 if (rsa->actual_register_packet_size == 0)
6230 rsa->actual_register_packet_size = buf_len;
6231
6232 /* If this is smaller than we guessed the 'g' packet would be,
6233 update our records. A 'g' reply that doesn't include a register's
6234 value implies either that the register is not available, or that
6235 the 'p' packet must be used. */
6236 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 6237 {
74ca34ce
DJ
6238 rsa->sizeof_g_packet = buf_len / 2;
6239
4a22f64d 6240 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 6241 {
74ca34ce
DJ
6242 if (rsa->regs[i].pnum == -1)
6243 continue;
6244
6245 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6246 rsa->regs[i].in_g_packet = 0;
b96ec7ac 6247 else
74ca34ce 6248 rsa->regs[i].in_g_packet = 1;
b96ec7ac 6249 }
74ca34ce 6250 }
b323314b 6251
74ca34ce 6252 regs = alloca (rsa->sizeof_g_packet);
c906108c
SS
6253
6254 /* Unimplemented registers read as all bits zero. */
ea9c271d 6255 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 6256
c906108c
SS
6257 /* Reply describes registers byte by byte, each byte encoded as two
6258 hex characters. Suck them all up, then supply them to the
6259 register cacheing/storage mechanism. */
6260
74ca34ce 6261 p = rs->buf;
ea9c271d 6262 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 6263 {
74ca34ce
DJ
6264 if (p[0] == 0 || p[1] == 0)
6265 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6266 internal_error (__FILE__, __LINE__,
9b20d036 6267 _("unexpected end of 'g' packet reply"));
74ca34ce 6268
c906108c 6269 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 6270 regs[i] = 0; /* 'x' */
c906108c
SS
6271 else
6272 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6273 p += 2;
6274 }
6275
a744cf53
MS
6276 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6277 {
6278 struct packet_reg *r = &rsa->regs[i];
6279
6280 if (r->in_g_packet)
6281 {
6282 if (r->offset * 2 >= strlen (rs->buf))
6283 /* This shouldn't happen - we adjusted in_g_packet above. */
6284 internal_error (__FILE__, __LINE__,
9b20d036 6285 _("unexpected end of 'g' packet reply"));
a744cf53
MS
6286 else if (rs->buf[r->offset * 2] == 'x')
6287 {
6288 gdb_assert (r->offset * 2 < strlen (rs->buf));
6289 /* The register isn't available, mark it as such (at
6290 the same time setting the value to zero). */
6291 regcache_raw_supply (regcache, r->regnum, NULL);
6292 }
6293 else
6294 regcache_raw_supply (regcache, r->regnum,
6295 regs + r->offset);
6296 }
6297 }
c906108c
SS
6298}
6299
29709017 6300static void
56be3814 6301fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
6302{
6303 send_g_packet ();
56be3814 6304 process_g_packet (regcache);
29709017
DJ
6305}
6306
e6e4e701
PA
6307/* Make the remote selected traceframe match GDB's selected
6308 traceframe. */
6309
6310static void
6311set_remote_traceframe (void)
6312{
6313 int newnum;
262e1174 6314 struct remote_state *rs = get_remote_state ();
e6e4e701 6315
262e1174 6316 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
6317 return;
6318
6319 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 6320 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
6321
6322 newnum = target_trace_find (tfind_number,
6323 get_traceframe_number (), 0, 0, NULL);
6324
6325 /* Should not happen. If it does, all bets are off. */
6326 if (newnum != get_traceframe_number ())
6327 warning (_("could not set remote traceframe"));
6328}
6329
74ca34ce 6330static void
28439f5e
PA
6331remote_fetch_registers (struct target_ops *ops,
6332 struct regcache *regcache, int regnum)
74ca34ce 6333{
74ca34ce
DJ
6334 struct remote_arch_state *rsa = get_remote_arch_state ();
6335 int i;
6336
e6e4e701 6337 set_remote_traceframe ();
79d7f229 6338 set_general_thread (inferior_ptid);
74ca34ce
DJ
6339
6340 if (regnum >= 0)
6341 {
6342 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6343
74ca34ce
DJ
6344 gdb_assert (reg != NULL);
6345
6346 /* If this register might be in the 'g' packet, try that first -
6347 we are likely to read more than one register. If this is the
6348 first 'g' packet, we might be overly optimistic about its
6349 contents, so fall back to 'p'. */
6350 if (reg->in_g_packet)
6351 {
56be3814 6352 fetch_registers_using_g (regcache);
74ca34ce
DJ
6353 if (reg->in_g_packet)
6354 return;
6355 }
6356
56be3814 6357 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
6358 return;
6359
6360 /* This register is not available. */
56be3814 6361 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
6362
6363 return;
6364 }
6365
56be3814 6366 fetch_registers_using_g (regcache);
74ca34ce 6367
4a22f64d 6368 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6369 if (!rsa->regs[i].in_g_packet)
56be3814 6370 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
6371 {
6372 /* This register is not available. */
56be3814 6373 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
6374 }
6375}
6376
c906108c
SS
6377/* Prepare to store registers. Since we may send them all (using a
6378 'G' request), we have to read out the ones we don't want to change
6379 first. */
6380
c5aa993b 6381static void
f32dbf8c 6382remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 6383{
ea9c271d 6384 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 6385 int i;
cfd77fa1 6386 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 6387
c906108c 6388 /* Make sure the entire registers array is valid. */
4082afcc 6389 switch (packet_support (PACKET_P))
5a2468f5
JM
6390 {
6391 case PACKET_DISABLE:
6392 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 6393 /* Make sure all the necessary registers are cached. */
4a22f64d 6394 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 6395 if (rsa->regs[i].in_g_packet)
316f2060 6396 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
6397 break;
6398 case PACKET_ENABLE:
6399 break;
6400 }
6401}
6402
ad10f812 6403/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 6404 packet was not recognized. */
5a2468f5
JM
6405
6406static int
1f4437a4
MS
6407store_register_using_P (const struct regcache *regcache,
6408 struct packet_reg *reg)
5a2468f5 6409{
4a22f64d 6410 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 6411 struct remote_state *rs = get_remote_state ();
5a2468f5 6412 /* Try storing a single register. */
6d820c5c 6413 char *buf = rs->buf;
cfd77fa1 6414 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 6415 char *p;
5a2468f5 6416
4082afcc 6417 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
6418 return 0;
6419
6420 if (reg->pnum == -1)
6421 return 0;
6422
ea9c271d 6423 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 6424 p = buf + strlen (buf);
56be3814 6425 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 6426 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
6427 putpkt (rs->buf);
6428 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 6429
74ca34ce
DJ
6430 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6431 {
6432 case PACKET_OK:
6433 return 1;
6434 case PACKET_ERROR:
27a9c0bf
MS
6435 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6436 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
6437 case PACKET_UNKNOWN:
6438 return 0;
6439 default:
6440 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6441 }
c906108c
SS
6442}
6443
23860348
MS
6444/* Store register REGNUM, or all registers if REGNUM == -1, from the
6445 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
6446
6447static void
56be3814 6448store_registers_using_G (const struct regcache *regcache)
c906108c 6449{
d01949b6 6450 struct remote_state *rs = get_remote_state ();
ea9c271d 6451 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 6452 gdb_byte *regs;
c906108c
SS
6453 char *p;
6454
193cb69f
AC
6455 /* Extract all the registers in the regcache copying them into a
6456 local buffer. */
6457 {
b323314b 6458 int i;
a744cf53 6459
ea9c271d
DJ
6460 regs = alloca (rsa->sizeof_g_packet);
6461 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 6462 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 6463 {
ea9c271d 6464 struct packet_reg *r = &rsa->regs[i];
a744cf53 6465
b323314b 6466 if (r->in_g_packet)
56be3814 6467 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
6468 }
6469 }
c906108c
SS
6470
6471 /* Command describes registers byte by byte,
6472 each byte encoded as two hex characters. */
6d820c5c 6473 p = rs->buf;
193cb69f 6474 *p++ = 'G';
74ca34ce
DJ
6475 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6476 updated. */
6477 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
6478 putpkt (rs->buf);
6479 getpkt (&rs->buf, &rs->buf_size, 0);
6480 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
6481 error (_("Could not write registers; remote failure reply '%s'"),
6482 rs->buf);
c906108c 6483}
74ca34ce
DJ
6484
6485/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6486 of the register cache buffer. FIXME: ignores errors. */
6487
6488static void
28439f5e
PA
6489remote_store_registers (struct target_ops *ops,
6490 struct regcache *regcache, int regnum)
74ca34ce 6491{
74ca34ce
DJ
6492 struct remote_arch_state *rsa = get_remote_arch_state ();
6493 int i;
6494
e6e4e701 6495 set_remote_traceframe ();
79d7f229 6496 set_general_thread (inferior_ptid);
74ca34ce
DJ
6497
6498 if (regnum >= 0)
6499 {
6500 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6501
74ca34ce
DJ
6502 gdb_assert (reg != NULL);
6503
6504 /* Always prefer to store registers using the 'P' packet if
6505 possible; we often change only a small number of registers.
6506 Sometimes we change a larger number; we'd need help from a
6507 higher layer to know to use 'G'. */
56be3814 6508 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
6509 return;
6510
6511 /* For now, don't complain if we have no way to write the
6512 register. GDB loses track of unavailable registers too
6513 easily. Some day, this may be an error. We don't have
0df8b418 6514 any way to read the register, either... */
74ca34ce
DJ
6515 if (!reg->in_g_packet)
6516 return;
6517
56be3814 6518 store_registers_using_G (regcache);
74ca34ce
DJ
6519 return;
6520 }
6521
56be3814 6522 store_registers_using_G (regcache);
74ca34ce 6523
4a22f64d 6524 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6525 if (!rsa->regs[i].in_g_packet)
56be3814 6526 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
6527 /* See above for why we do not issue an error here. */
6528 continue;
6529}
c906108c
SS
6530\f
6531
6532/* Return the number of hex digits in num. */
6533
6534static int
fba45db2 6535hexnumlen (ULONGEST num)
c906108c
SS
6536{
6537 int i;
6538
6539 for (i = 0; num != 0; i++)
6540 num >>= 4;
6541
6542 return max (i, 1);
6543}
6544
2df3850c 6545/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
6546
6547static int
fba45db2 6548hexnumstr (char *buf, ULONGEST num)
c906108c 6549{
c906108c 6550 int len = hexnumlen (num);
a744cf53 6551
2df3850c
JM
6552 return hexnumnstr (buf, num, len);
6553}
6554
c906108c 6555
2df3850c 6556/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 6557
2df3850c 6558static int
fba45db2 6559hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
6560{
6561 int i;
6562
6563 buf[width] = '\0';
6564
6565 for (i = width - 1; i >= 0; i--)
c906108c 6566 {
c5aa993b 6567 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
6568 num >>= 4;
6569 }
6570
2df3850c 6571 return width;
c906108c
SS
6572}
6573
23860348 6574/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
6575
6576static CORE_ADDR
fba45db2 6577remote_address_masked (CORE_ADDR addr)
c906108c 6578{
883b9c6c 6579 unsigned int address_size = remote_address_size;
a744cf53 6580
911c95a5
UW
6581 /* If "remoteaddresssize" was not set, default to target address size. */
6582 if (!address_size)
f5656ead 6583 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
6584
6585 if (address_size > 0
6586 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
6587 {
6588 /* Only create a mask when that mask can safely be constructed
23860348 6589 in a ULONGEST variable. */
c906108c 6590 ULONGEST mask = 1;
a744cf53 6591
911c95a5 6592 mask = (mask << address_size) - 1;
c906108c
SS
6593 addr &= mask;
6594 }
6595 return addr;
6596}
6597
6598/* Determine whether the remote target supports binary downloading.
6599 This is accomplished by sending a no-op memory write of zero length
6600 to the target at the specified address. It does not suffice to send
23860348
MS
6601 the whole packet, since many stubs strip the eighth bit and
6602 subsequently compute a wrong checksum, which causes real havoc with
6603 remote_write_bytes.
7a292a7a 6604
96baa820 6605 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 6606 clean. In cases like this, the user should clear "remote
23860348 6607 X-packet". */
96baa820 6608
c906108c 6609static void
fba45db2 6610check_binary_download (CORE_ADDR addr)
c906108c 6611{
d01949b6 6612 struct remote_state *rs = get_remote_state ();
24b06219 6613
4082afcc 6614 switch (packet_support (PACKET_X))
c906108c 6615 {
96baa820
JM
6616 case PACKET_DISABLE:
6617 break;
6618 case PACKET_ENABLE:
6619 break;
6620 case PACKET_SUPPORT_UNKNOWN:
6621 {
96baa820 6622 char *p;
802188a7 6623
2e9f7625 6624 p = rs->buf;
96baa820
JM
6625 *p++ = 'X';
6626 p += hexnumstr (p, (ULONGEST) addr);
6627 *p++ = ',';
6628 p += hexnumstr (p, (ULONGEST) 0);
6629 *p++ = ':';
6630 *p = '\0';
802188a7 6631
2e9f7625 6632 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 6633 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 6634
2e9f7625 6635 if (rs->buf[0] == '\0')
96baa820
JM
6636 {
6637 if (remote_debug)
6638 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
6639 "binary downloading NOT "
6640 "supported by target\n");
444abaca 6641 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
6642 }
6643 else
6644 {
6645 if (remote_debug)
6646 fprintf_unfiltered (gdb_stdlog,
64b9b334 6647 "binary downloading supported by target\n");
444abaca 6648 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
6649 }
6650 break;
6651 }
c906108c
SS
6652 }
6653}
6654
6655/* Write memory data directly to the remote machine.
6656 This does not inform the data cache; the data cache uses this.
a76d924d 6657 HEADER is the starting part of the packet.
c906108c
SS
6658 MEMADDR is the address in the remote memory space.
6659 MYADDR is the address of the buffer in our space.
6660 LEN is the number of bytes.
a76d924d
DJ
6661 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6662 should send data as binary ('X'), or hex-encoded ('M').
6663
6664 The function creates packet of the form
6665 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6666
6667 where encoding of <DATA> is termined by PACKET_FORMAT.
6668
6669 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6670 are omitted.
6671
9b409511
YQ
6672 Return the transferred status, error or OK (an
6673 'enum target_xfer_status' value). Save the number of bytes
6674 transferred in *XFERED_LEN. Only transfer a single packet. */
c906108c 6675
9b409511 6676static enum target_xfer_status
a76d924d 6677remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
5d6df423 6678 const gdb_byte *myaddr, ULONGEST len,
9b409511
YQ
6679 ULONGEST *xfered_len, char packet_format,
6680 int use_length)
c906108c 6681{
6d820c5c 6682 struct remote_state *rs = get_remote_state ();
cfd77fa1 6683 char *p;
a76d924d
DJ
6684 char *plen = NULL;
6685 int plenlen = 0;
917317f4
JM
6686 int todo;
6687 int nr_bytes;
a257b5bb 6688 int payload_size;
6765f3e5 6689 int payload_length;
a76d924d
DJ
6690 int header_length;
6691
6692 if (packet_format != 'X' && packet_format != 'M')
6693 internal_error (__FILE__, __LINE__,
9b20d036 6694 _("remote_write_bytes_aux: bad packet format"));
c906108c 6695
5d6df423 6696 if (len == 0)
9b409511 6697 return TARGET_XFER_EOF;
b2182ed2 6698
3de11b2e 6699 payload_size = get_memory_write_packet_size ();
2bc416ba 6700
6d820c5c
DJ
6701 /* The packet buffer will be large enough for the payload;
6702 get_memory_packet_size ensures this. */
a76d924d 6703 rs->buf[0] = '\0';
c906108c 6704
a257b5bb 6705 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
6706 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6707
a76d924d
DJ
6708 payload_size -= strlen ("$,:#NN");
6709 if (!use_length)
0df8b418 6710 /* The comma won't be used. */
a76d924d
DJ
6711 payload_size += 1;
6712 header_length = strlen (header);
6713 payload_size -= header_length;
3de11b2e 6714 payload_size -= hexnumlen (memaddr);
c906108c 6715
a76d924d 6716 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 6717
a76d924d
DJ
6718 strcat (rs->buf, header);
6719 p = rs->buf + strlen (header);
6720
6721 /* Compute a best guess of the number of bytes actually transfered. */
6722 if (packet_format == 'X')
c906108c 6723 {
23860348 6724 /* Best guess at number of bytes that will fit. */
a257b5bb 6725 todo = min (len, payload_size);
a76d924d
DJ
6726 if (use_length)
6727 payload_size -= hexnumlen (todo);
3de11b2e 6728 todo = min (todo, payload_size);
a76d924d
DJ
6729 }
6730 else
6731 {
23860348 6732 /* Num bytes that will fit. */
a257b5bb 6733 todo = min (len, payload_size / 2);
a76d924d
DJ
6734 if (use_length)
6735 payload_size -= hexnumlen (todo);
3de11b2e 6736 todo = min (todo, payload_size / 2);
917317f4 6737 }
a76d924d 6738
3de11b2e
NS
6739 if (todo <= 0)
6740 internal_error (__FILE__, __LINE__,
405f8e94 6741 _("minimum packet size too small to write data"));
802188a7 6742
6765f3e5
DJ
6743 /* If we already need another packet, then try to align the end
6744 of this packet to a useful boundary. */
6745 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6746 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6747
a257b5bb 6748 /* Append "<memaddr>". */
917317f4
JM
6749 memaddr = remote_address_masked (memaddr);
6750 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 6751
a76d924d
DJ
6752 if (use_length)
6753 {
6754 /* Append ",". */
6755 *p++ = ',';
802188a7 6756
a76d924d
DJ
6757 /* Append <len>. Retain the location/size of <len>. It may need to
6758 be adjusted once the packet body has been created. */
6759 plen = p;
6760 plenlen = hexnumstr (p, (ULONGEST) todo);
6761 p += plenlen;
6762 }
a257b5bb
AC
6763
6764 /* Append ":". */
917317f4
JM
6765 *p++ = ':';
6766 *p = '\0';
802188a7 6767
a257b5bb 6768 /* Append the packet body. */
a76d924d 6769 if (packet_format == 'X')
917317f4 6770 {
917317f4
JM
6771 /* Binary mode. Send target system values byte by byte, in
6772 increasing byte addresses. Only escape certain critical
6773 characters. */
bc20a4af
PA
6774 payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
6775 &nr_bytes, payload_size);
6765f3e5
DJ
6776
6777 /* If not all TODO bytes fit, then we'll need another packet. Make
9b7194bc
DJ
6778 a second try to keep the end of the packet aligned. Don't do
6779 this if the packet is tiny. */
6780 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6765f3e5
DJ
6781 {
6782 int new_nr_bytes;
6783
6784 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6785 - memaddr);
6786 if (new_nr_bytes != nr_bytes)
6787 payload_length = remote_escape_output (myaddr, new_nr_bytes,
bc20a4af 6788 (gdb_byte *) p, &nr_bytes,
6765f3e5
DJ
6789 payload_size);
6790 }
6791
6792 p += payload_length;
a76d924d 6793 if (use_length && nr_bytes < todo)
c906108c 6794 {
802188a7 6795 /* Escape chars have filled up the buffer prematurely,
917317f4
JM
6796 and we have actually sent fewer bytes than planned.
6797 Fix-up the length field of the packet. Use the same
6798 number of characters as before. */
917317f4
JM
6799 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6800 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 6801 }
a76d924d
DJ
6802 }
6803 else
6804 {
917317f4
JM
6805 /* Normal mode: Send target system values byte by byte, in
6806 increasing byte addresses. Each byte is encoded as a two hex
6807 value. */
2644f393 6808 nr_bytes = bin2hex (myaddr, p, todo);
aa6c0017 6809 p += 2 * nr_bytes;
c906108c 6810 }
802188a7 6811
2e9f7625 6812 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 6813 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 6814
2e9f7625 6815 if (rs->buf[0] == 'E')
00d84524 6816 return TARGET_XFER_E_IO;
802188a7 6817
23860348
MS
6818 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6819 fewer bytes than we'd planned. */
9b409511
YQ
6820 *xfered_len = (ULONGEST) nr_bytes;
6821 return TARGET_XFER_OK;
c906108c
SS
6822}
6823
a76d924d
DJ
6824/* Write memory data directly to the remote machine.
6825 This does not inform the data cache; the data cache uses this.
6826 MEMADDR is the address in the remote memory space.
6827 MYADDR is the address of the buffer in our space.
6828 LEN is the number of bytes.
6829
9b409511
YQ
6830 Return the transferred status, error or OK (an
6831 'enum target_xfer_status' value). Save the number of bytes
6832 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 6833
9b409511
YQ
6834static enum target_xfer_status
6835remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
6836 ULONGEST *xfered_len)
a76d924d
DJ
6837{
6838 char *packet_format = 0;
6839
6840 /* Check whether the target supports binary download. */
6841 check_binary_download (memaddr);
6842
4082afcc 6843 switch (packet_support (PACKET_X))
a76d924d
DJ
6844 {
6845 case PACKET_ENABLE:
6846 packet_format = "X";
6847 break;
6848 case PACKET_DISABLE:
6849 packet_format = "M";
6850 break;
6851 case PACKET_SUPPORT_UNKNOWN:
6852 internal_error (__FILE__, __LINE__,
6853 _("remote_write_bytes: bad internal state"));
6854 default:
6855 internal_error (__FILE__, __LINE__, _("bad switch"));
6856 }
6857
6858 return remote_write_bytes_aux (packet_format,
9b409511
YQ
6859 memaddr, myaddr, len, xfered_len,
6860 packet_format[0], 1);
a76d924d
DJ
6861}
6862
9217e74e
YQ
6863/* Read memory data directly from the remote machine.
6864 This does not use the data cache; the data cache uses this.
6865 MEMADDR is the address in the remote memory space.
6866 MYADDR is the address of the buffer in our space.
6867 LEN is the number of bytes.
6868
6869 Return the transferred status, error or OK (an
6870 'enum target_xfer_status' value). Save the number of bytes
6871 transferred in *XFERED_LEN. */
6872
6873static enum target_xfer_status
6874remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len,
6875 ULONGEST *xfered_len)
6876{
6877 struct remote_state *rs = get_remote_state ();
6878 int max_buf_size; /* Max size of packet output buffer. */
6879 char *p;
6880 int todo;
6881 int i;
6882
6883 max_buf_size = get_memory_read_packet_size ();
6884 /* The packet buffer will be large enough for the payload;
6885 get_memory_packet_size ensures this. */
6886
6887 /* Number if bytes that will fit. */
6888 todo = min (len, max_buf_size / 2);
6889
6890 /* Construct "m"<memaddr>","<len>". */
6891 memaddr = remote_address_masked (memaddr);
6892 p = rs->buf;
6893 *p++ = 'm';
6894 p += hexnumstr (p, (ULONGEST) memaddr);
6895 *p++ = ',';
6896 p += hexnumstr (p, (ULONGEST) todo);
6897 *p = '\0';
6898 putpkt (rs->buf);
6899 getpkt (&rs->buf, &rs->buf_size, 0);
6900 if (rs->buf[0] == 'E'
6901 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6902 && rs->buf[3] == '\0')
6903 return TARGET_XFER_E_IO;
6904 /* Reply describes memory byte by byte, each byte encoded as two hex
6905 characters. */
6906 p = rs->buf;
6907 i = hex2bin (p, myaddr, todo);
6908 /* Return what we have. Let higher layers handle partial reads. */
6909 *xfered_len = (ULONGEST) i;
6910 return TARGET_XFER_OK;
6911}
6912
b55fbac4
YQ
6913/* Using the set of read-only target sections of remote, read live
6914 read-only memory.
8acf9577
YQ
6915
6916 For interface/parameters/return description see target.h,
6917 to_xfer_partial. */
6918
6919static enum target_xfer_status
b55fbac4
YQ
6920remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
6921 ULONGEST memaddr, ULONGEST len,
6922 ULONGEST *xfered_len)
8acf9577
YQ
6923{
6924 struct target_section *secp;
6925 struct target_section_table *table;
6926
6927 secp = target_section_by_addr (ops, memaddr);
6928 if (secp != NULL
6929 && (bfd_get_section_flags (secp->the_bfd_section->owner,
6930 secp->the_bfd_section)
6931 & SEC_READONLY))
6932 {
6933 struct target_section *p;
6934 ULONGEST memend = memaddr + len;
6935
6936 table = target_get_section_table (ops);
6937
6938 for (p = table->sections; p < table->sections_end; p++)
6939 {
6940 if (memaddr >= p->addr)
6941 {
6942 if (memend <= p->endaddr)
6943 {
6944 /* Entire transfer is within this section. */
b55fbac4
YQ
6945 return remote_read_bytes_1 (memaddr, readbuf, len,
6946 xfered_len);
8acf9577
YQ
6947 }
6948 else if (memaddr >= p->endaddr)
6949 {
6950 /* This section ends before the transfer starts. */
6951 continue;
6952 }
6953 else
6954 {
6955 /* This section overlaps the transfer. Just do half. */
6956 len = p->endaddr - memaddr;
b55fbac4
YQ
6957 return remote_read_bytes_1 (memaddr, readbuf, len,
6958 xfered_len);
8acf9577
YQ
6959 }
6960 }
6961 }
6962 }
6963
6964 return TARGET_XFER_EOF;
6965}
6966
9217e74e
YQ
6967/* Similar to remote_read_bytes_1, but it reads from the remote stub
6968 first if the requested memory is unavailable in traceframe.
6969 Otherwise, fall back to remote_read_bytes_1. */
c906108c 6970
9b409511 6971static enum target_xfer_status
8acf9577
YQ
6972remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
6973 gdb_byte *myaddr, ULONGEST len, ULONGEST *xfered_len)
c906108c 6974{
6b6aa828 6975 if (len == 0)
96c4f946 6976 return TARGET_XFER_EOF;
b2182ed2 6977
8acf9577
YQ
6978 if (get_traceframe_number () != -1)
6979 {
6980 VEC(mem_range_s) *available;
6981
6982 /* If we fail to get the set of available memory, then the
6983 target does not support querying traceframe info, and so we
6984 attempt reading from the traceframe anyway (assuming the
6985 target implements the old QTro packet then). */
6986 if (traceframe_available_memory (&available, memaddr, len))
6987 {
6988 struct cleanup *old_chain;
6989
6990 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
6991
6992 if (VEC_empty (mem_range_s, available)
6993 || VEC_index (mem_range_s, available, 0)->start != memaddr)
6994 {
6995 enum target_xfer_status res;
6996
6997 /* Don't read into the traceframe's available
6998 memory. */
6999 if (!VEC_empty (mem_range_s, available))
7000 {
7001 LONGEST oldlen = len;
7002
7003 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7004 gdb_assert (len <= oldlen);
7005 }
7006
7007 do_cleanups (old_chain);
7008
7009 /* This goes through the topmost target again. */
b55fbac4 7010 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8acf9577
YQ
7011 len, xfered_len);
7012 if (res == TARGET_XFER_OK)
7013 return TARGET_XFER_OK;
7014 else
7015 {
7016 /* No use trying further, we know some memory starting
7017 at MEMADDR isn't available. */
7018 *xfered_len = len;
7019 return TARGET_XFER_UNAVAILABLE;
7020 }
7021 }
7022
7023 /* Don't try to read more than how much is available, in
7024 case the target implements the deprecated QTro packet to
7025 cater for older GDBs (the target's knowledge of read-only
7026 sections may be outdated by now). */
7027 len = VEC_index (mem_range_s, available, 0)->length;
7028
7029 do_cleanups (old_chain);
7030 }
7031 }
7032
9217e74e 7033 return remote_read_bytes_1 (memaddr, myaddr, len, xfered_len);
c906108c 7034}
74531fed 7035
c906108c 7036\f
c906108c 7037
a76d924d
DJ
7038/* Sends a packet with content determined by the printf format string
7039 FORMAT and the remaining arguments, then gets the reply. Returns
7040 whether the packet was a success, a failure, or unknown. */
7041
77b64a49
PA
7042static enum packet_result remote_send_printf (const char *format, ...)
7043 ATTRIBUTE_PRINTF (1, 2);
7044
2c0b251b 7045static enum packet_result
a76d924d
DJ
7046remote_send_printf (const char *format, ...)
7047{
7048 struct remote_state *rs = get_remote_state ();
7049 int max_size = get_remote_packet_size ();
a76d924d 7050 va_list ap;
a744cf53 7051
a76d924d
DJ
7052 va_start (ap, format);
7053
7054 rs->buf[0] = '\0';
7055 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 7056 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
7057
7058 if (putpkt (rs->buf) < 0)
7059 error (_("Communication problem with target."));
7060
7061 rs->buf[0] = '\0';
7062 getpkt (&rs->buf, &rs->buf_size, 0);
7063
7064 return packet_check_result (rs->buf);
7065}
7066
7067static void
7068restore_remote_timeout (void *p)
7069{
7070 int value = *(int *)p;
a744cf53 7071
a76d924d
DJ
7072 remote_timeout = value;
7073}
7074
7075/* Flash writing can take quite some time. We'll set
7076 effectively infinite timeout for flash operations.
7077 In future, we'll need to decide on a better approach. */
7078static const int remote_flash_timeout = 1000;
7079
7080static void
7081remote_flash_erase (struct target_ops *ops,
7082 ULONGEST address, LONGEST length)
7083{
f5656ead 7084 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
7085 int saved_remote_timeout = remote_timeout;
7086 enum packet_result ret;
a76d924d
DJ
7087 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7088 &saved_remote_timeout);
a744cf53 7089
a76d924d
DJ
7090 remote_timeout = remote_flash_timeout;
7091
7092 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 7093 phex (address, addr_size),
a76d924d
DJ
7094 phex (length, 4));
7095 switch (ret)
7096 {
7097 case PACKET_UNKNOWN:
7098 error (_("Remote target does not support flash erase"));
7099 case PACKET_ERROR:
7100 error (_("Error erasing flash with vFlashErase packet"));
7101 default:
7102 break;
7103 }
7104
7105 do_cleanups (back_to);
7106}
7107
9b409511
YQ
7108static enum target_xfer_status
7109remote_flash_write (struct target_ops *ops, ULONGEST address,
7110 ULONGEST length, ULONGEST *xfered_len,
7111 const gdb_byte *data)
a76d924d
DJ
7112{
7113 int saved_remote_timeout = remote_timeout;
9b409511 7114 enum target_xfer_status ret;
a76d924d 7115 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 7116 &saved_remote_timeout);
a76d924d
DJ
7117
7118 remote_timeout = remote_flash_timeout;
9b409511
YQ
7119 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length,
7120 xfered_len,'X', 0);
a76d924d
DJ
7121 do_cleanups (back_to);
7122
7123 return ret;
7124}
7125
7126static void
7127remote_flash_done (struct target_ops *ops)
7128{
7129 int saved_remote_timeout = remote_timeout;
7130 int ret;
7131 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7132 &saved_remote_timeout);
7133
7134 remote_timeout = remote_flash_timeout;
7135 ret = remote_send_printf ("vFlashDone");
7136 do_cleanups (back_to);
7137
7138 switch (ret)
7139 {
7140 case PACKET_UNKNOWN:
7141 error (_("Remote target does not support vFlashDone"));
7142 case PACKET_ERROR:
7143 error (_("Error finishing flash operation"));
7144 default:
7145 break;
7146 }
7147}
7148
c906108c 7149static void
fba45db2 7150remote_files_info (struct target_ops *ignore)
c906108c
SS
7151{
7152 puts_filtered ("Debugging a target over a serial line.\n");
7153}
7154\f
7155/* Stuff for dealing with the packets which are part of this protocol.
7156 See comment at top of file for details. */
7157
1927e618
PA
7158/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7159 error to higher layers. Called when a serial error is detected.
7160 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
7161 the system error message for errno at function entry and final dot
7162 for output compatibility with throw_perror_with_name. */
1927e618
PA
7163
7164static void
7165unpush_and_perror (const char *string)
7166{
d6cb50a2 7167 int saved_errno = errno;
1927e618
PA
7168
7169 remote_unpush_target ();
d6cb50a2
JK
7170 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7171 safe_strerror (saved_errno));
1927e618
PA
7172}
7173
0876f84a 7174/* Read a single character from the remote end. */
c906108c
SS
7175
7176static int
fba45db2 7177readchar (int timeout)
c906108c
SS
7178{
7179 int ch;
5d93a237 7180 struct remote_state *rs = get_remote_state ();
c906108c 7181
5d93a237 7182 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 7183
2acceee2 7184 if (ch >= 0)
0876f84a 7185 return ch;
2acceee2
JM
7186
7187 switch ((enum serial_rc) ch)
c906108c
SS
7188 {
7189 case SERIAL_EOF:
78a095c3 7190 remote_unpush_target ();
598d3636 7191 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 7192 /* no return */
c906108c 7193 case SERIAL_ERROR:
1927e618
PA
7194 unpush_and_perror (_("Remote communication error. "
7195 "Target disconnected."));
2acceee2 7196 /* no return */
c906108c 7197 case SERIAL_TIMEOUT:
2acceee2 7198 break;
c906108c 7199 }
2acceee2 7200 return ch;
c906108c
SS
7201}
7202
c33e31fd
PA
7203/* Wrapper for serial_write that closes the target and throws if
7204 writing fails. */
7205
7206static void
7207remote_serial_write (const char *str, int len)
7208{
5d93a237
TT
7209 struct remote_state *rs = get_remote_state ();
7210
7211 if (serial_write (rs->remote_desc, str, len))
c33e31fd 7212 {
1927e618
PA
7213 unpush_and_perror (_("Remote communication error. "
7214 "Target disconnected."));
c33e31fd
PA
7215 }
7216}
7217
6d820c5c
DJ
7218/* Send the command in *BUF to the remote machine, and read the reply
7219 into *BUF. Report an error if we get an error reply. Resize
7220 *BUF using xrealloc if necessary to hold the result, and update
7221 *SIZEOF_BUF. */
c906108c
SS
7222
7223static void
6d820c5c
DJ
7224remote_send (char **buf,
7225 long *sizeof_buf)
c906108c 7226{
6d820c5c 7227 putpkt (*buf);
c2d11a7d 7228 getpkt (buf, sizeof_buf, 0);
c906108c 7229
6d820c5c
DJ
7230 if ((*buf)[0] == 'E')
7231 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
7232}
7233
6e5abd65
PA
7234/* Return a pointer to an xmalloc'ed string representing an escaped
7235 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7236 etc. The caller is responsible for releasing the returned
7237 memory. */
7238
7239static char *
7240escape_buffer (const char *buf, int n)
7241{
7242 struct cleanup *old_chain;
7243 struct ui_file *stb;
7244 char *str;
6e5abd65
PA
7245
7246 stb = mem_fileopen ();
7247 old_chain = make_cleanup_ui_file_delete (stb);
7248
6ef284bd 7249 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 7250 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
7251 do_cleanups (old_chain);
7252 return str;
7253}
7254
c906108c
SS
7255/* Display a null-terminated packet on stdout, for debugging, using C
7256 string notation. */
7257
7258static void
baa336ce 7259print_packet (const char *buf)
c906108c
SS
7260{
7261 puts_filtered ("\"");
43e526b9 7262 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
7263 puts_filtered ("\"");
7264}
7265
7266int
baa336ce 7267putpkt (const char *buf)
c906108c
SS
7268{
7269 return putpkt_binary (buf, strlen (buf));
7270}
7271
7272/* Send a packet to the remote machine, with error checking. The data
23860348 7273 of the packet is in BUF. The string in BUF can be at most
ea9c271d 7274 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
7275 and for a possible /0 if we are debugging (remote_debug) and want
7276 to print the sent packet as a string. */
c906108c
SS
7277
7278static int
baa336ce 7279putpkt_binary (const char *buf, int cnt)
c906108c 7280{
2d717e4f 7281 struct remote_state *rs = get_remote_state ();
c906108c
SS
7282 int i;
7283 unsigned char csum = 0;
11cf8741 7284 char *buf2 = alloca (cnt + 6);
085dd6e6 7285
c906108c
SS
7286 int ch;
7287 int tcount = 0;
7288 char *p;
dd61ec5c 7289 char *message;
c906108c 7290
e24a49d8
PA
7291 /* Catch cases like trying to read memory or listing threads while
7292 we're waiting for a stop reply. The remote server wouldn't be
7293 ready to handle this request, so we'd hang and timeout. We don't
7294 have to worry about this in synchronous mode, because in that
7295 case it's not possible to issue a command while the target is
74531fed
PA
7296 running. This is not a problem in non-stop mode, because in that
7297 case, the stub is always ready to process serial input. */
d9d41e78 7298 if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
9597b22a
DE
7299 {
7300 error (_("Cannot execute this command while the target is running.\n"
7301 "Use the \"interrupt\" command to stop the target\n"
7302 "and then try again."));
7303 }
e24a49d8 7304
2d717e4f
DJ
7305 /* We're sending out a new packet. Make sure we don't look at a
7306 stale cached response. */
7307 rs->cached_wait_status = 0;
7308
c906108c
SS
7309 /* Copy the packet into buffer BUF2, encapsulating it
7310 and giving it a checksum. */
7311
c906108c
SS
7312 p = buf2;
7313 *p++ = '$';
7314
7315 for (i = 0; i < cnt; i++)
7316 {
7317 csum += buf[i];
7318 *p++ = buf[i];
7319 }
7320 *p++ = '#';
7321 *p++ = tohex ((csum >> 4) & 0xf);
7322 *p++ = tohex (csum & 0xf);
7323
7324 /* Send it over and over until we get a positive ack. */
7325
7326 while (1)
7327 {
7328 int started_error_output = 0;
7329
7330 if (remote_debug)
7331 {
6e5abd65
PA
7332 struct cleanup *old_chain;
7333 char *str;
7334
c906108c 7335 *p = '\0';
6e5abd65
PA
7336 str = escape_buffer (buf2, p - buf2);
7337 old_chain = make_cleanup (xfree, str);
7338 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 7339 gdb_flush (gdb_stdlog);
6e5abd65 7340 do_cleanups (old_chain);
c906108c 7341 }
c33e31fd 7342 remote_serial_write (buf2, p - buf2);
c906108c 7343
a6f3e723
SL
7344 /* If this is a no acks version of the remote protocol, send the
7345 packet and move on. */
7346 if (rs->noack_mode)
7347 break;
7348
74531fed
PA
7349 /* Read until either a timeout occurs (-2) or '+' is read.
7350 Handle any notification that arrives in the mean time. */
c906108c
SS
7351 while (1)
7352 {
7353 ch = readchar (remote_timeout);
7354
c5aa993b 7355 if (remote_debug)
c906108c
SS
7356 {
7357 switch (ch)
7358 {
7359 case '+':
1216fa2c 7360 case '-':
c906108c
SS
7361 case SERIAL_TIMEOUT:
7362 case '$':
74531fed 7363 case '%':
c906108c
SS
7364 if (started_error_output)
7365 {
7366 putchar_unfiltered ('\n');
7367 started_error_output = 0;
7368 }
7369 }
7370 }
7371
7372 switch (ch)
7373 {
7374 case '+':
7375 if (remote_debug)
0f71a2f6 7376 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 7377 return 1;
1216fa2c
AC
7378 case '-':
7379 if (remote_debug)
7380 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 7381 /* FALLTHROUGH */
c906108c 7382 case SERIAL_TIMEOUT:
c5aa993b 7383 tcount++;
c906108c
SS
7384 if (tcount > 3)
7385 return 0;
23860348 7386 break; /* Retransmit buffer. */
c906108c
SS
7387 case '$':
7388 {
40e3f985 7389 if (remote_debug)
2bc416ba 7390 fprintf_unfiltered (gdb_stdlog,
23860348 7391 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
7392 /* It's probably an old response sent because an ACK
7393 was lost. Gobble up the packet and ack it so it
7394 doesn't get retransmitted when we resend this
7395 packet. */
6d820c5c 7396 skip_frame ();
c33e31fd 7397 remote_serial_write ("+", 1);
23860348 7398 continue; /* Now, go look for +. */
c906108c 7399 }
74531fed
PA
7400
7401 case '%':
7402 {
7403 int val;
7404
7405 /* If we got a notification, handle it, and go back to looking
7406 for an ack. */
7407 /* We've found the start of a notification. Now
7408 collect the data. */
7409 val = read_frame (&rs->buf, &rs->buf_size);
7410 if (val >= 0)
7411 {
7412 if (remote_debug)
7413 {
6e5abd65
PA
7414 struct cleanup *old_chain;
7415 char *str;
7416
7417 str = escape_buffer (rs->buf, val);
7418 old_chain = make_cleanup (xfree, str);
7419 fprintf_unfiltered (gdb_stdlog,
7420 " Notification received: %s\n",
7421 str);
7422 do_cleanups (old_chain);
74531fed 7423 }
5965e028 7424 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
7425 /* We're in sync now, rewait for the ack. */
7426 tcount = 0;
7427 }
7428 else
7429 {
7430 if (remote_debug)
7431 {
7432 if (!started_error_output)
7433 {
7434 started_error_output = 1;
7435 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7436 }
7437 fputc_unfiltered (ch & 0177, gdb_stdlog);
7438 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7439 }
7440 }
7441 continue;
7442 }
7443 /* fall-through */
c906108c
SS
7444 default:
7445 if (remote_debug)
7446 {
7447 if (!started_error_output)
7448 {
7449 started_error_output = 1;
0f71a2f6 7450 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 7451 }
0f71a2f6 7452 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
7453 }
7454 continue;
7455 }
23860348 7456 break; /* Here to retransmit. */
c906108c
SS
7457 }
7458
7459#if 0
7460 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
7461 able to get out next time we call QUIT, without anything as
7462 violent as interrupt_query. If we want to provide a way out of
7463 here without getting to the next QUIT, it should be based on
7464 hitting ^C twice as in remote_wait. */
c906108c
SS
7465 if (quit_flag)
7466 {
7467 quit_flag = 0;
7468 interrupt_query ();
7469 }
7470#endif
7471 }
a6f3e723 7472 return 0;
c906108c
SS
7473}
7474
6d820c5c
DJ
7475/* Come here after finding the start of a frame when we expected an
7476 ack. Do our best to discard the rest of this packet. */
7477
7478static void
7479skip_frame (void)
7480{
7481 int c;
7482
7483 while (1)
7484 {
7485 c = readchar (remote_timeout);
7486 switch (c)
7487 {
7488 case SERIAL_TIMEOUT:
7489 /* Nothing we can do. */
7490 return;
7491 case '#':
7492 /* Discard the two bytes of checksum and stop. */
7493 c = readchar (remote_timeout);
7494 if (c >= 0)
7495 c = readchar (remote_timeout);
7496
7497 return;
7498 case '*': /* Run length encoding. */
7499 /* Discard the repeat count. */
7500 c = readchar (remote_timeout);
7501 if (c < 0)
7502 return;
7503 break;
7504 default:
7505 /* A regular character. */
7506 break;
7507 }
7508 }
7509}
7510
c906108c 7511/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
7512 into *BUF, verifying the checksum, length, and handling run-length
7513 compression. NUL terminate the buffer. If there is not enough room,
7514 expand *BUF using xrealloc.
c906108c 7515
c2d11a7d
JM
7516 Returns -1 on error, number of characters in buffer (ignoring the
7517 trailing NULL) on success. (could be extended to return one of the
23860348 7518 SERIAL status indications). */
c2d11a7d
JM
7519
7520static long
6d820c5c
DJ
7521read_frame (char **buf_p,
7522 long *sizeof_buf)
c906108c
SS
7523{
7524 unsigned char csum;
c2d11a7d 7525 long bc;
c906108c 7526 int c;
6d820c5c 7527 char *buf = *buf_p;
a6f3e723 7528 struct remote_state *rs = get_remote_state ();
c906108c
SS
7529
7530 csum = 0;
c2d11a7d 7531 bc = 0;
c906108c
SS
7532
7533 while (1)
7534 {
7535 c = readchar (remote_timeout);
c906108c
SS
7536 switch (c)
7537 {
7538 case SERIAL_TIMEOUT:
7539 if (remote_debug)
0f71a2f6 7540 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 7541 return -1;
c906108c
SS
7542 case '$':
7543 if (remote_debug)
0f71a2f6
JM
7544 fputs_filtered ("Saw new packet start in middle of old one\n",
7545 gdb_stdlog);
23860348 7546 return -1; /* Start a new packet, count retries. */
c906108c
SS
7547 case '#':
7548 {
7549 unsigned char pktcsum;
e1b09194
AC
7550 int check_0 = 0;
7551 int check_1 = 0;
c906108c 7552
c2d11a7d 7553 buf[bc] = '\0';
c906108c 7554
e1b09194
AC
7555 check_0 = readchar (remote_timeout);
7556 if (check_0 >= 0)
7557 check_1 = readchar (remote_timeout);
802188a7 7558
e1b09194
AC
7559 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7560 {
7561 if (remote_debug)
2bc416ba 7562 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 7563 gdb_stdlog);
e1b09194
AC
7564 return -1;
7565 }
7566 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
7567 {
7568 if (remote_debug)
2bc416ba 7569 fputs_filtered ("Communication error in checksum\n",
23860348 7570 gdb_stdlog);
40e3f985
FN
7571 return -1;
7572 }
c906108c 7573
a6f3e723
SL
7574 /* Don't recompute the checksum; with no ack packets we
7575 don't have any way to indicate a packet retransmission
7576 is necessary. */
7577 if (rs->noack_mode)
7578 return bc;
7579
e1b09194 7580 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 7581 if (csum == pktcsum)
c2d11a7d 7582 return bc;
c906108c 7583
c5aa993b 7584 if (remote_debug)
c906108c 7585 {
6e5abd65
PA
7586 struct cleanup *old_chain;
7587 char *str;
7588
7589 str = escape_buffer (buf, bc);
7590 old_chain = make_cleanup (xfree, str);
7591 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7592 "Bad checksum, sentsum=0x%x, "
7593 "csum=0x%x, buf=%s\n",
6e5abd65
PA
7594 pktcsum, csum, str);
7595 do_cleanups (old_chain);
c906108c 7596 }
c2d11a7d 7597 /* Number of characters in buffer ignoring trailing
23860348 7598 NULL. */
c2d11a7d 7599 return -1;
c906108c 7600 }
23860348 7601 case '*': /* Run length encoding. */
c2c6d25f
JM
7602 {
7603 int repeat;
c906108c 7604
a744cf53 7605 csum += c;
b4501125
AC
7606 c = readchar (remote_timeout);
7607 csum += c;
23860348 7608 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 7609
23860348 7610 /* The character before ``*'' is repeated. */
c2d11a7d 7611
6d820c5c 7612 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 7613 {
6d820c5c
DJ
7614 if (bc + repeat - 1 >= *sizeof_buf - 1)
7615 {
7616 /* Make some more room in the buffer. */
7617 *sizeof_buf += repeat;
7618 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7619 buf = *buf_p;
7620 }
7621
c2d11a7d
JM
7622 memset (&buf[bc], buf[bc - 1], repeat);
7623 bc += repeat;
c2c6d25f
JM
7624 continue;
7625 }
7626
c2d11a7d 7627 buf[bc] = '\0';
6d820c5c 7628 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 7629 return -1;
c2c6d25f 7630 }
c906108c 7631 default:
6d820c5c 7632 if (bc >= *sizeof_buf - 1)
c906108c 7633 {
6d820c5c
DJ
7634 /* Make some more room in the buffer. */
7635 *sizeof_buf *= 2;
7636 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7637 buf = *buf_p;
c906108c
SS
7638 }
7639
6d820c5c
DJ
7640 buf[bc++] = c;
7641 csum += c;
7642 continue;
c906108c
SS
7643 }
7644 }
7645}
7646
7647/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
7648 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7649 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7650 rather than timing out; this is used (in synchronous mode) to wait
7651 for a target that is is executing user code to stop. */
d9fcf2fb
JM
7652/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7653 don't have to change all the calls to getpkt to deal with the
7654 return value, because at the moment I don't know what the right
23860348 7655 thing to do it for those. */
c906108c 7656void
6d820c5c
DJ
7657getpkt (char **buf,
7658 long *sizeof_buf,
c2d11a7d 7659 int forever)
d9fcf2fb
JM
7660{
7661 int timed_out;
7662
7663 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7664}
7665
7666
7667/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
7668 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7669 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7670 rather than timing out; this is used (in synchronous mode) to wait
7671 for a target that is is executing user code to stop. If FOREVER ==
7672 0, this function is allowed to time out gracefully and return an
74531fed
PA
7673 indication of this to the caller. Otherwise return the number of
7674 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
7675 enough reason to return to the caller. *IS_NOTIF is an output
7676 boolean that indicates whether *BUF holds a notification or not
7677 (a regular packet). */
74531fed 7678
3172dc30 7679static int
74531fed 7680getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 7681 int expecting_notif, int *is_notif)
c906108c 7682{
2d717e4f 7683 struct remote_state *rs = get_remote_state ();
c906108c
SS
7684 int c;
7685 int tries;
7686 int timeout;
df4b58fe 7687 int val = -1;
c906108c 7688
2d717e4f
DJ
7689 /* We're reading a new response. Make sure we don't look at a
7690 previously cached response. */
7691 rs->cached_wait_status = 0;
7692
6d820c5c 7693 strcpy (*buf, "timeout");
c906108c
SS
7694
7695 if (forever)
74531fed
PA
7696 timeout = watchdog > 0 ? watchdog : -1;
7697 else if (expecting_notif)
7698 timeout = 0; /* There should already be a char in the buffer. If
7699 not, bail out. */
c906108c
SS
7700 else
7701 timeout = remote_timeout;
7702
7703#define MAX_TRIES 3
7704
74531fed
PA
7705 /* Process any number of notifications, and then return when
7706 we get a packet. */
7707 for (;;)
c906108c 7708 {
d9c43928 7709 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
7710 times. */
7711 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 7712 {
74531fed
PA
7713 /* This can loop forever if the remote side sends us
7714 characters continuously, but if it pauses, we'll get
7715 SERIAL_TIMEOUT from readchar because of timeout. Then
7716 we'll count that as a retry.
7717
7718 Note that even when forever is set, we will only wait
7719 forever prior to the start of a packet. After that, we
7720 expect characters to arrive at a brisk pace. They should
7721 show up within remote_timeout intervals. */
7722 do
7723 c = readchar (timeout);
7724 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
7725
7726 if (c == SERIAL_TIMEOUT)
7727 {
74531fed
PA
7728 if (expecting_notif)
7729 return -1; /* Don't complain, it's normal to not get
7730 anything in this case. */
7731
23860348 7732 if (forever) /* Watchdog went off? Kill the target. */
c906108c 7733 {
2acceee2 7734 QUIT;
78a095c3 7735 remote_unpush_target ();
598d3636
JK
7736 throw_error (TARGET_CLOSE_ERROR,
7737 _("Watchdog timeout has expired. "
7738 "Target detached."));
c906108c 7739 }
c906108c 7740 if (remote_debug)
0f71a2f6 7741 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 7742 }
74531fed
PA
7743 else
7744 {
7745 /* We've found the start of a packet or notification.
7746 Now collect the data. */
7747 val = read_frame (buf, sizeof_buf);
7748 if (val >= 0)
7749 break;
7750 }
7751
c33e31fd 7752 remote_serial_write ("-", 1);
c906108c 7753 }
c906108c 7754
74531fed
PA
7755 if (tries > MAX_TRIES)
7756 {
7757 /* We have tried hard enough, and just can't receive the
7758 packet/notification. Give up. */
7759 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 7760
74531fed
PA
7761 /* Skip the ack char if we're in no-ack mode. */
7762 if (!rs->noack_mode)
c33e31fd 7763 remote_serial_write ("+", 1);
74531fed
PA
7764 return -1;
7765 }
c906108c 7766
74531fed
PA
7767 /* If we got an ordinary packet, return that to our caller. */
7768 if (c == '$')
c906108c
SS
7769 {
7770 if (remote_debug)
43e526b9 7771 {
6e5abd65
PA
7772 struct cleanup *old_chain;
7773 char *str;
7774
7775 str = escape_buffer (*buf, val);
7776 old_chain = make_cleanup (xfree, str);
7777 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7778 do_cleanups (old_chain);
43e526b9 7779 }
a6f3e723
SL
7780
7781 /* Skip the ack char if we're in no-ack mode. */
7782 if (!rs->noack_mode)
c33e31fd 7783 remote_serial_write ("+", 1);
fee9eda9
YQ
7784 if (is_notif != NULL)
7785 *is_notif = 0;
0876f84a 7786 return val;
c906108c
SS
7787 }
7788
74531fed
PA
7789 /* If we got a notification, handle it, and go back to looking
7790 for a packet. */
7791 else
7792 {
7793 gdb_assert (c == '%');
7794
7795 if (remote_debug)
7796 {
6e5abd65
PA
7797 struct cleanup *old_chain;
7798 char *str;
7799
7800 str = escape_buffer (*buf, val);
7801 old_chain = make_cleanup (xfree, str);
7802 fprintf_unfiltered (gdb_stdlog,
7803 " Notification received: %s\n",
7804 str);
7805 do_cleanups (old_chain);
74531fed 7806 }
fee9eda9
YQ
7807 if (is_notif != NULL)
7808 *is_notif = 1;
c906108c 7809
5965e028 7810 handle_notification (rs->notif_state, *buf);
c906108c 7811
74531fed 7812 /* Notifications require no acknowledgement. */
a6f3e723 7813
74531fed 7814 if (expecting_notif)
fee9eda9 7815 return val;
74531fed
PA
7816 }
7817 }
7818}
7819
7820static int
7821getpkt_sane (char **buf, long *sizeof_buf, int forever)
7822{
fee9eda9 7823 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
7824}
7825
7826static int
fee9eda9
YQ
7827getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
7828 int *is_notif)
74531fed 7829{
fee9eda9
YQ
7830 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
7831 is_notif);
c906108c 7832}
74531fed 7833
c906108c
SS
7834\f
7835static void
7d85a9c0 7836remote_kill (struct target_ops *ops)
43ff13b4 7837{
c90a6fb7 7838 volatile struct gdb_exception ex;
0fdf84ca
PA
7839
7840 /* Catch errors so the user can quit from gdb even when we
23860348 7841 aren't on speaking terms with the remote system. */
0fdf84ca
PA
7842 TRY_CATCH (ex, RETURN_MASK_ERROR)
7843 {
7844 putpkt ("k");
7845 }
7846 if (ex.reason < 0)
7847 {
7848 if (ex.error == TARGET_CLOSE_ERROR)
7849 {
7850 /* If we got an (EOF) error that caused the target
7851 to go away, then we're done, that's what we wanted.
7852 "k" is susceptible to cause a premature EOF, given
7853 that the remote server isn't actually required to
7854 reply to "k", and it can happen that it doesn't
7855 even get to reply ACK to the "k". */
7856 return;
7857 }
7858
7859 /* Otherwise, something went wrong. We didn't actually kill
7860 the target. Just propagate the exception, and let the
7861 user or higher layers decide what to do. */
7862 throw_exception (ex);
7863 }
43ff13b4 7864
0fdf84ca
PA
7865 /* We've killed the remote end, we get to mourn it. Since this is
7866 target remote, single-process, mourning the inferior also
7867 unpushes remote_ops. */
43ff13b4
JM
7868 target_mourn_inferior ();
7869}
7870
82f73884
PA
7871static int
7872remote_vkill (int pid, struct remote_state *rs)
7873{
4082afcc 7874 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
7875 return -1;
7876
7877 /* Tell the remote target to detach. */
bba74b36 7878 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
7879 putpkt (rs->buf);
7880 getpkt (&rs->buf, &rs->buf_size, 0);
7881
4082afcc
PA
7882 switch (packet_ok (rs->buf,
7883 &remote_protocol_packets[PACKET_vKill]))
7884 {
7885 case PACKET_OK:
7886 return 0;
7887 case PACKET_ERROR:
7888 return 1;
7889 case PACKET_UNKNOWN:
7890 return -1;
7891 default:
7892 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7893 }
82f73884
PA
7894}
7895
7896static void
7d85a9c0 7897extended_remote_kill (struct target_ops *ops)
82f73884
PA
7898{
7899 int res;
7900 int pid = ptid_get_pid (inferior_ptid);
7901 struct remote_state *rs = get_remote_state ();
7902
7903 res = remote_vkill (pid, rs);
901f9912 7904 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
82f73884
PA
7905 {
7906 /* Don't try 'k' on a multi-process aware stub -- it has no way
7907 to specify the pid. */
7908
7909 putpkt ("k");
7910#if 0
7911 getpkt (&rs->buf, &rs->buf_size, 0);
7912 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7913 res = 1;
7914#else
7915 /* Don't wait for it to die. I'm not really sure it matters whether
7916 we do or not. For the existing stubs, kill is a noop. */
7917 res = 0;
7918#endif
7919 }
7920
7921 if (res != 0)
7922 error (_("Can't kill process"));
7923
82f73884
PA
7924 target_mourn_inferior ();
7925}
7926
c906108c 7927static void
136d6dae 7928remote_mourn (struct target_ops *ops)
c906108c 7929{
136d6dae 7930 remote_mourn_1 (ops);
c906108c
SS
7931}
7932
c906108c
SS
7933/* Worker function for remote_mourn. */
7934static void
fba45db2 7935remote_mourn_1 (struct target_ops *target)
c906108c
SS
7936{
7937 unpush_target (target);
ce5ce7ed 7938
8a2492ee
PA
7939 /* remote_close takes care of doing most of the clean up. */
7940 generic_mourn_inferior ();
c906108c
SS
7941}
7942
2d717e4f
DJ
7943static void
7944extended_remote_mourn_1 (struct target_ops *target)
7945{
7946 struct remote_state *rs = get_remote_state ();
c906108c 7947
e24a49d8
PA
7948 /* In case we got here due to an error, but we're going to stay
7949 connected. */
7950 rs->waiting_for_stop_reply = 0;
7951
dc1981d7
PA
7952 /* If the current general thread belonged to the process we just
7953 detached from or has exited, the remote side current general
7954 thread becomes undefined. Considering a case like this:
7955
7956 - We just got here due to a detach.
7957 - The process that we're detaching from happens to immediately
7958 report a global breakpoint being hit in non-stop mode, in the
7959 same thread we had selected before.
7960 - GDB attaches to this process again.
7961 - This event happens to be the next event we handle.
7962
7963 GDB would consider that the current general thread didn't need to
7964 be set on the stub side (with Hg), since for all it knew,
7965 GENERAL_THREAD hadn't changed.
7966
7967 Notice that although in all-stop mode, the remote server always
7968 sets the current thread to the thread reporting the stop event,
7969 that doesn't happen in non-stop mode; in non-stop, the stub *must
7970 not* change the current thread when reporting a breakpoint hit,
7971 due to the decoupling of event reporting and event handling.
7972
7973 To keep things simple, we always invalidate our notion of the
7974 current thread. */
47f8a51d 7975 record_currthread (rs, minus_one_ptid);
dc1981d7 7976
2d717e4f
DJ
7977 /* Unlike "target remote", we do not want to unpush the target; then
7978 the next time the user says "run", we won't be connected. */
7979
48aa3c27
PA
7980 /* Call common code to mark the inferior as not running. */
7981 generic_mourn_inferior ();
7982
d729566a 7983 if (!have_inferiors ())
2d717e4f 7984 {
82f73884
PA
7985 if (!remote_multi_process_p (rs))
7986 {
7987 /* Check whether the target is running now - some remote stubs
7988 automatically restart after kill. */
7989 putpkt ("?");
7990 getpkt (&rs->buf, &rs->buf_size, 0);
7991
7992 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7993 {
3e43a32a
MS
7994 /* Assume that the target has been restarted. Set
7995 inferior_ptid so that bits of core GDB realizes
7996 there's something here, e.g., so that the user can
7997 say "kill" again. */
82f73884
PA
7998 inferior_ptid = magic_null_ptid;
7999 }
82f73884 8000 }
2d717e4f
DJ
8001 }
8002}
c906108c
SS
8003
8004static void
136d6dae 8005extended_remote_mourn (struct target_ops *ops)
c906108c 8006{
136d6dae 8007 extended_remote_mourn_1 (ops);
2d717e4f 8008}
c906108c 8009
03583c20 8010static int
2bfc0540 8011extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 8012{
4082afcc 8013 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
8014}
8015
8016static void
8017extended_remote_disable_randomization (int val)
8018{
8019 struct remote_state *rs = get_remote_state ();
8020 char *reply;
8021
bba74b36
YQ
8022 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8023 val);
03583c20
UW
8024 putpkt (rs->buf);
8025 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8026 if (*reply == '\0')
8027 error (_("Target does not support QDisableRandomization."));
8028 if (strcmp (reply, "OK") != 0)
8029 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8030}
8031
2d717e4f
DJ
8032static int
8033extended_remote_run (char *args)
8034{
8035 struct remote_state *rs = get_remote_state ();
2d717e4f 8036 int len;
c906108c 8037
2d717e4f
DJ
8038 /* If the user has disabled vRun support, or we have detected that
8039 support is not available, do not try it. */
4082afcc 8040 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 8041 return -1;
424163ea 8042
2d717e4f
DJ
8043 strcpy (rs->buf, "vRun;");
8044 len = strlen (rs->buf);
c906108c 8045
2d717e4f
DJ
8046 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8047 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
8048 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8049 strlen (remote_exec_file));
2d717e4f 8050
d1a41061 8051 gdb_assert (args != NULL);
2d717e4f
DJ
8052 if (*args)
8053 {
8054 struct cleanup *back_to;
8055 int i;
8056 char **argv;
8057
d1a41061 8058 argv = gdb_buildargv (args);
6e366df1 8059 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
8060 for (i = 0; argv[i] != NULL; i++)
8061 {
8062 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8063 error (_("Argument list too long for run packet"));
8064 rs->buf[len++] = ';';
9f1b45b0
TT
8065 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8066 strlen (argv[i]));
2d717e4f
DJ
8067 }
8068 do_cleanups (back_to);
8069 }
8070
8071 rs->buf[len++] = '\0';
8072
8073 putpkt (rs->buf);
8074 getpkt (&rs->buf, &rs->buf_size, 0);
8075
4082afcc 8076 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 8077 {
4082afcc 8078 case PACKET_OK:
3405876a 8079 /* We have a wait response. All is well. */
2d717e4f 8080 return 0;
4082afcc
PA
8081 case PACKET_UNKNOWN:
8082 return -1;
8083 case PACKET_ERROR:
2d717e4f
DJ
8084 if (remote_exec_file[0] == '\0')
8085 error (_("Running the default executable on the remote target failed; "
8086 "try \"set remote exec-file\"?"));
8087 else
8088 error (_("Running \"%s\" on the remote target failed"),
8089 remote_exec_file);
4082afcc
PA
8090 default:
8091 gdb_assert_not_reached (_("bad switch"));
2d717e4f 8092 }
c906108c
SS
8093}
8094
2d717e4f
DJ
8095/* In the extended protocol we want to be able to do things like
8096 "run" and have them basically work as expected. So we need
8097 a special create_inferior function. We support changing the
8098 executable file and the command line arguments, but not the
8099 environment. */
8100
43ff13b4 8101static void
77a19445
TT
8102extended_remote_create_inferior (struct target_ops *ops,
8103 char *exec_file, char *args,
8104 char **env, int from_tty)
43ff13b4 8105{
3405876a
PA
8106 int run_worked;
8107 char *stop_reply;
8108 struct remote_state *rs = get_remote_state ();
8109
43ff13b4 8110 /* If running asynchronously, register the target file descriptor
23860348 8111 with the event loop. */
75c99385 8112 if (target_can_async_p ())
2acceee2 8113 target_async (inferior_event_handler, 0);
43ff13b4 8114
03583c20 8115 /* Disable address space randomization if requested (and supported). */
2bfc0540 8116 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
8117 extended_remote_disable_randomization (disable_randomization);
8118
43ff13b4 8119 /* Now restart the remote server. */
3405876a
PA
8120 run_worked = extended_remote_run (args) != -1;
8121 if (!run_worked)
2d717e4f
DJ
8122 {
8123 /* vRun was not supported. Fail if we need it to do what the
8124 user requested. */
8125 if (remote_exec_file[0])
8126 error (_("Remote target does not support \"set remote exec-file\""));
8127 if (args[0])
8128 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 8129
2d717e4f
DJ
8130 /* Fall back to "R". */
8131 extended_remote_restart ();
8132 }
424163ea 8133
6c95b8df
PA
8134 if (!have_inferiors ())
8135 {
8136 /* Clean up from the last time we ran, before we mark the target
8137 running again. This will mark breakpoints uninserted, and
8138 get_offsets may insert breakpoints. */
8139 init_thread_list ();
8140 init_wait_for_inferior ();
8141 }
45280a52 8142
3405876a
PA
8143 /* vRun's success return is a stop reply. */
8144 stop_reply = run_worked ? rs->buf : NULL;
8145 add_current_inferior_and_thread (stop_reply);
c0a2216e 8146
2d717e4f
DJ
8147 /* Get updated offsets, if the stub uses qOffsets. */
8148 get_offsets ();
2d717e4f 8149}
c906108c 8150\f
c5aa993b 8151
b775012e
LM
8152/* Given a location's target info BP_TGT and the packet buffer BUF, output
8153 the list of conditions (in agent expression bytecode format), if any, the
8154 target needs to evaluate. The output is placed into the packet buffer
bba74b36 8155 started from BUF and ended at BUF_END. */
b775012e
LM
8156
8157static int
8158remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
8159 struct bp_target_info *bp_tgt, char *buf,
8160 char *buf_end)
b775012e
LM
8161{
8162 struct agent_expr *aexpr = NULL;
8163 int i, ix;
8164 char *pkt;
8165 char *buf_start = buf;
8166
8167 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8168 return 0;
8169
8170 buf += strlen (buf);
bba74b36 8171 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
8172 buf++;
8173
8174 /* Send conditions to the target and free the vector. */
8175 for (ix = 0;
8176 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8177 ix++)
8178 {
bba74b36 8179 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
8180 buf += strlen (buf);
8181 for (i = 0; i < aexpr->len; ++i)
8182 buf = pack_hex_byte (buf, aexpr->buf[i]);
8183 *buf = '\0';
8184 }
b775012e
LM
8185 return 0;
8186}
8187
d3ce09f5
SS
8188static void
8189remote_add_target_side_commands (struct gdbarch *gdbarch,
8190 struct bp_target_info *bp_tgt, char *buf)
8191{
8192 struct agent_expr *aexpr = NULL;
8193 int i, ix;
8194
8195 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8196 return;
8197
8198 buf += strlen (buf);
8199
8200 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8201 buf += strlen (buf);
8202
8203 /* Concatenate all the agent expressions that are commands into the
8204 cmds parameter. */
8205 for (ix = 0;
8206 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8207 ix++)
8208 {
8209 sprintf (buf, "X%x,", aexpr->len);
8210 buf += strlen (buf);
8211 for (i = 0; i < aexpr->len; ++i)
8212 buf = pack_hex_byte (buf, aexpr->buf[i]);
8213 *buf = '\0';
8214 }
d3ce09f5
SS
8215}
8216
8181d85f
DJ
8217/* Insert a breakpoint. On targets that have software breakpoint
8218 support, we ask the remote target to do the work; on targets
8219 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
8220
8221static int
3db08215
MM
8222remote_insert_breakpoint (struct target_ops *ops,
8223 struct gdbarch *gdbarch,
a6d9a66e 8224 struct bp_target_info *bp_tgt)
c906108c 8225{
d471ea57
AC
8226 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8227 If it succeeds, then set the support to PACKET_ENABLE. If it
8228 fails, and the user has explicitly requested the Z support then
23860348 8229 report an error, otherwise, mark it disabled and go on. */
802188a7 8230
4082afcc 8231 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 8232 {
0d5ed153 8233 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 8234 struct remote_state *rs;
bba74b36 8235 char *p, *endbuf;
7c0f6dcc 8236 int bpsize;
b775012e 8237 struct condition_list *cond = NULL;
4fff2411 8238
28439a30
PA
8239 /* Make sure the remote is pointing at the right process, if
8240 necessary. */
8241 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8242 set_general_process ();
8243
a1dcb23a 8244 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
8245
8246 rs = get_remote_state ();
8247 p = rs->buf;
bba74b36 8248 endbuf = rs->buf + get_remote_packet_size ();
802188a7 8249
96baa820
JM
8250 *(p++) = 'Z';
8251 *(p++) = '0';
8252 *(p++) = ',';
7c0f6dcc 8253 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 8254 p += hexnumstr (p, addr);
bba74b36 8255 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 8256
efcc2da7 8257 if (remote_supports_cond_breakpoints (ops))
bba74b36 8258 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8259
78eff0ec 8260 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
8261 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8262
6d820c5c
DJ
8263 putpkt (rs->buf);
8264 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8265
6d820c5c 8266 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 8267 {
d471ea57
AC
8268 case PACKET_ERROR:
8269 return -1;
8270 case PACKET_OK:
7c0f6dcc
JL
8271 bp_tgt->placed_address = addr;
8272 bp_tgt->placed_size = bpsize;
d471ea57
AC
8273 return 0;
8274 case PACKET_UNKNOWN:
8275 break;
96baa820
JM
8276 }
8277 }
c906108c 8278
0000e5cc
PA
8279 /* If this breakpoint has target-side commands but this stub doesn't
8280 support Z0 packets, throw error. */
8281 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8282 throw_error (NOT_SUPPORTED_ERROR, _("\
8283Target doesn't support breakpoints that have target side commands."));
8284
3db08215 8285 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8286}
8287
8288static int
3db08215
MM
8289remote_remove_breakpoint (struct target_ops *ops,
8290 struct gdbarch *gdbarch,
a6d9a66e 8291 struct bp_target_info *bp_tgt)
c906108c 8292{
8181d85f 8293 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 8294 struct remote_state *rs = get_remote_state ();
96baa820 8295
4082afcc 8296 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 8297 {
6d820c5c 8298 char *p = rs->buf;
bba74b36 8299 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 8300
28439a30
PA
8301 /* Make sure the remote is pointing at the right process, if
8302 necessary. */
8303 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8304 set_general_process ();
8305
96baa820
JM
8306 *(p++) = 'z';
8307 *(p++) = '0';
8308 *(p++) = ',';
8309
8181d85f
DJ
8310 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8311 p += hexnumstr (p, addr);
bba74b36 8312 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 8313
6d820c5c
DJ
8314 putpkt (rs->buf);
8315 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8316
6d820c5c 8317 return (rs->buf[0] == 'E');
96baa820
JM
8318 }
8319
3db08215 8320 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8321}
8322
d471ea57
AC
8323static int
8324watchpoint_to_Z_packet (int type)
8325{
8326 switch (type)
8327 {
8328 case hw_write:
bb858e6a 8329 return Z_PACKET_WRITE_WP;
d471ea57
AC
8330 break;
8331 case hw_read:
bb858e6a 8332 return Z_PACKET_READ_WP;
d471ea57
AC
8333 break;
8334 case hw_access:
bb858e6a 8335 return Z_PACKET_ACCESS_WP;
d471ea57
AC
8336 break;
8337 default:
8e65ff28 8338 internal_error (__FILE__, __LINE__,
e2e0b3e5 8339 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
8340 }
8341}
8342
3c3bea1c 8343static int
7bb99c53
TT
8344remote_insert_watchpoint (struct target_ops *self,
8345 CORE_ADDR addr, int len, int type,
0cf6dd15 8346 struct expression *cond)
96baa820 8347{
d01949b6 8348 struct remote_state *rs = get_remote_state ();
bba74b36 8349 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8350 char *p;
d471ea57 8351 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 8352
4082afcc 8353 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 8354 return 1;
802188a7 8355
28439a30
PA
8356 /* Make sure the remote is pointing at the right process, if
8357 necessary. */
8358 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8359 set_general_process ();
8360
bba74b36 8361 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 8362 p = strchr (rs->buf, '\0');
96baa820
JM
8363 addr = remote_address_masked (addr);
8364 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8365 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 8366
6d820c5c
DJ
8367 putpkt (rs->buf);
8368 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8369
6d820c5c 8370 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8371 {
8372 case PACKET_ERROR:
d471ea57 8373 return -1;
85d721b8
PA
8374 case PACKET_UNKNOWN:
8375 return 1;
d471ea57
AC
8376 case PACKET_OK:
8377 return 0;
8378 }
8e65ff28 8379 internal_error (__FILE__, __LINE__,
e2e0b3e5 8380 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
8381}
8382
283002cf
MR
8383static int
8384remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8385 CORE_ADDR start, int length)
8386{
8387 CORE_ADDR diff = remote_address_masked (addr - start);
8388
8389 return diff < length;
8390}
8391
d471ea57 8392
3c3bea1c 8393static int
11b5219a
TT
8394remote_remove_watchpoint (struct target_ops *self,
8395 CORE_ADDR addr, int len, int type,
0cf6dd15 8396 struct expression *cond)
96baa820 8397{
d01949b6 8398 struct remote_state *rs = get_remote_state ();
bba74b36 8399 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8400 char *p;
d471ea57
AC
8401 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8402
4082afcc 8403 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 8404 return -1;
802188a7 8405
28439a30
PA
8406 /* Make sure the remote is pointing at the right process, if
8407 necessary. */
8408 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8409 set_general_process ();
8410
bba74b36 8411 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 8412 p = strchr (rs->buf, '\0');
96baa820
JM
8413 addr = remote_address_masked (addr);
8414 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8415 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
8416 putpkt (rs->buf);
8417 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8418
6d820c5c 8419 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8420 {
8421 case PACKET_ERROR:
8422 case PACKET_UNKNOWN:
8423 return -1;
8424 case PACKET_OK:
8425 return 0;
8426 }
8e65ff28 8427 internal_error (__FILE__, __LINE__,
e2e0b3e5 8428 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
8429}
8430
3c3bea1c 8431
501eef12 8432int remote_hw_watchpoint_limit = -1;
480a3f21 8433int remote_hw_watchpoint_length_limit = -1;
501eef12 8434int remote_hw_breakpoint_limit = -1;
d471ea57 8435
480a3f21 8436static int
31568a15
TT
8437remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8438 CORE_ADDR addr, int len)
480a3f21
PW
8439{
8440 if (remote_hw_watchpoint_length_limit == 0)
8441 return 0;
8442 else if (remote_hw_watchpoint_length_limit < 0)
8443 return 1;
8444 else if (len <= remote_hw_watchpoint_length_limit)
8445 return 1;
8446 else
8447 return 0;
8448}
8449
b9362cc7 8450static int
5461485a
TT
8451remote_check_watch_resources (struct target_ops *self,
8452 int type, int cnt, int ot)
96baa820 8453{
3c3bea1c
GS
8454 if (type == bp_hardware_breakpoint)
8455 {
8456 if (remote_hw_breakpoint_limit == 0)
8457 return 0;
501eef12
AC
8458 else if (remote_hw_breakpoint_limit < 0)
8459 return 1;
3c3bea1c
GS
8460 else if (cnt <= remote_hw_breakpoint_limit)
8461 return 1;
8462 }
8463 else
8464 {
8465 if (remote_hw_watchpoint_limit == 0)
8466 return 0;
501eef12
AC
8467 else if (remote_hw_watchpoint_limit < 0)
8468 return 1;
3c3bea1c
GS
8469 else if (ot)
8470 return -1;
8471 else if (cnt <= remote_hw_watchpoint_limit)
8472 return 1;
8473 }
8474 return -1;
8475}
8476
f7e6eed5
PA
8477/* The to_stopped_by_sw_breakpoint method of target remote. */
8478
8479static int
8480remote_stopped_by_sw_breakpoint (struct target_ops *ops)
8481{
8482 struct remote_state *rs = get_remote_state ();
8483
8484 return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
8485}
8486
8487/* The to_supports_stopped_by_sw_breakpoint method of target
8488 remote. */
8489
8490static int
8491remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
8492{
8493 struct remote_state *rs = get_remote_state ();
8494
8495 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
8496}
8497
8498/* The to_stopped_by_hw_breakpoint method of target remote. */
8499
8500static int
8501remote_stopped_by_hw_breakpoint (struct target_ops *ops)
8502{
8503 struct remote_state *rs = get_remote_state ();
8504
8505 return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
8506}
8507
8508/* The to_supports_stopped_by_hw_breakpoint method of target
8509 remote. */
8510
8511static int
8512remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
8513{
8514 struct remote_state *rs = get_remote_state ();
8515
8516 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
8517}
8518
b9362cc7 8519static int
6a109b6b 8520remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 8521{
ee154bee
TT
8522 struct remote_state *rs = get_remote_state ();
8523
f7e6eed5 8524 return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
3c3bea1c
GS
8525}
8526
4aa7a7f5
JJ
8527static int
8528remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 8529{
ee154bee 8530 struct remote_state *rs = get_remote_state ();
4aa7a7f5 8531 int rc = 0;
a744cf53 8532
6a109b6b 8533 if (remote_stopped_by_watchpoint (target))
4aa7a7f5 8534 {
ee154bee 8535 *addr_p = rs->remote_watch_data_address;
4aa7a7f5
JJ
8536 rc = 1;
8537 }
8538
8539 return rc;
3c3bea1c
GS
8540}
8541
8542
8543static int
23a26771 8544remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 8545 struct bp_target_info *bp_tgt)
3c3bea1c 8546{
0d5ed153 8547 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 8548 struct remote_state *rs;
bba74b36 8549 char *p, *endbuf;
dd61ec5c 8550 char *message;
0d5ed153 8551 int bpsize;
802188a7 8552
c8189ed1 8553 /* The length field should be set to the size of a breakpoint
8181d85f 8554 instruction, even though we aren't inserting one ourselves. */
c8189ed1 8555
0d5ed153 8556 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 8557
4082afcc 8558 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 8559 return -1;
2bc416ba 8560
28439a30
PA
8561 /* Make sure the remote is pointing at the right process, if
8562 necessary. */
8563 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8564 set_general_process ();
8565
4fff2411
JZ
8566 rs = get_remote_state ();
8567 p = rs->buf;
bba74b36 8568 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 8569
96baa820
JM
8570 *(p++) = 'Z';
8571 *(p++) = '1';
8572 *(p++) = ',';
802188a7 8573
0d5ed153 8574 addr = remote_address_masked (addr);
96baa820 8575 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 8576 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 8577
efcc2da7 8578 if (remote_supports_cond_breakpoints (self))
bba74b36 8579 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8580
78eff0ec 8581 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
8582 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8583
6d820c5c
DJ
8584 putpkt (rs->buf);
8585 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8586
6d820c5c 8587 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
8588 {
8589 case PACKET_ERROR:
dd61ec5c
MW
8590 if (rs->buf[1] == '.')
8591 {
8592 message = strchr (rs->buf + 2, '.');
8593 if (message)
0316657e 8594 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
8595 }
8596 return -1;
d471ea57
AC
8597 case PACKET_UNKNOWN:
8598 return -1;
8599 case PACKET_OK:
0d5ed153
MR
8600 bp_tgt->placed_address = addr;
8601 bp_tgt->placed_size = bpsize;
d471ea57
AC
8602 return 0;
8603 }
8e65ff28 8604 internal_error (__FILE__, __LINE__,
e2e0b3e5 8605 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
8606}
8607
d471ea57 8608
802188a7 8609static int
a64dc96c 8610remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 8611 struct bp_target_info *bp_tgt)
96baa820 8612{
8181d85f 8613 CORE_ADDR addr;
d01949b6 8614 struct remote_state *rs = get_remote_state ();
6d820c5c 8615 char *p = rs->buf;
bba74b36 8616 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 8617
4082afcc 8618 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 8619 return -1;
802188a7 8620
28439a30
PA
8621 /* Make sure the remote is pointing at the right process, if
8622 necessary. */
8623 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8624 set_general_process ();
8625
96baa820
JM
8626 *(p++) = 'z';
8627 *(p++) = '1';
8628 *(p++) = ',';
802188a7 8629
8181d85f 8630 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 8631 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8632 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 8633
6d820c5c
DJ
8634 putpkt (rs->buf);
8635 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 8636
6d820c5c 8637 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
8638 {
8639 case PACKET_ERROR:
8640 case PACKET_UNKNOWN:
8641 return -1;
8642 case PACKET_OK:
8643 return 0;
8644 }
8e65ff28 8645 internal_error (__FILE__, __LINE__,
e2e0b3e5 8646 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 8647}
96baa820 8648
4a5e7a5b
PA
8649/* Verify memory using the "qCRC:" request. */
8650
8651static int
8652remote_verify_memory (struct target_ops *ops,
8653 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8654{
8655 struct remote_state *rs = get_remote_state ();
8656 unsigned long host_crc, target_crc;
8657 char *tmp;
8658
936d2992
PA
8659 /* It doesn't make sense to use qCRC if the remote target is
8660 connected but not running. */
8661 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
8662 {
8663 enum packet_result result;
28439a30 8664
936d2992
PA
8665 /* Make sure the remote is pointing at the right process. */
8666 set_general_process ();
4a5e7a5b 8667
936d2992
PA
8668 /* FIXME: assumes lma can fit into long. */
8669 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8670 (long) lma, (long) size);
8671 putpkt (rs->buf);
4a5e7a5b 8672
936d2992
PA
8673 /* Be clever; compute the host_crc before waiting for target
8674 reply. */
8675 host_crc = xcrc32 (data, size, 0xffffffff);
8676
8677 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 8678
936d2992
PA
8679 result = packet_ok (rs->buf,
8680 &remote_protocol_packets[PACKET_qCRC]);
8681 if (result == PACKET_ERROR)
8682 return -1;
8683 else if (result == PACKET_OK)
8684 {
8685 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8686 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 8687
936d2992
PA
8688 return (host_crc == target_crc);
8689 }
8690 }
4a5e7a5b 8691
936d2992 8692 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
8693}
8694
c906108c
SS
8695/* compare-sections command
8696
8697 With no arguments, compares each loadable section in the exec bfd
8698 with the same memory range on the target, and reports mismatches.
4a5e7a5b 8699 Useful for verifying the image on the target against the exec file. */
e514a9d6 8700
c906108c 8701static void
fba45db2 8702compare_sections_command (char *args, int from_tty)
c906108c
SS
8703{
8704 asection *s;
c906108c 8705 struct cleanup *old_chain;
948f8e3d 8706 gdb_byte *sectdata;
ce359b09 8707 const char *sectname;
c906108c
SS
8708 bfd_size_type size;
8709 bfd_vma lma;
8710 int matched = 0;
8711 int mismatched = 0;
4a5e7a5b 8712 int res;
95cf3b38 8713 int read_only = 0;
c906108c
SS
8714
8715 if (!exec_bfd)
8a3fe4f8 8716 error (_("command cannot be used without an exec file"));
c906108c 8717
28439a30
PA
8718 /* Make sure the remote is pointing at the right process. */
8719 set_general_process ();
8720
95cf3b38
DT
8721 if (args != NULL && strcmp (args, "-r") == 0)
8722 {
8723 read_only = 1;
8724 args = NULL;
8725 }
8726
c5aa993b 8727 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
8728 {
8729 if (!(s->flags & SEC_LOAD))
0df8b418 8730 continue; /* Skip non-loadable section. */
c906108c 8731
95cf3b38
DT
8732 if (read_only && (s->flags & SEC_READONLY) == 0)
8733 continue; /* Skip writeable sections */
8734
2c500098 8735 size = bfd_get_section_size (s);
c906108c 8736 if (size == 0)
0df8b418 8737 continue; /* Skip zero-length section. */
c906108c 8738
ce359b09 8739 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 8740 if (args && strcmp (args, sectname) != 0)
0df8b418 8741 continue; /* Not the section selected by user. */
c906108c 8742
0df8b418 8743 matched = 1; /* Do this section. */
c906108c 8744 lma = s->lma;
c906108c 8745
c906108c 8746 sectdata = xmalloc (size);
b8c9b27d 8747 old_chain = make_cleanup (xfree, sectdata);
c906108c 8748 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 8749
4a5e7a5b
PA
8750 res = target_verify_memory (sectdata, lma, size);
8751
8752 if (res == -1)
5af949e3 8753 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
8754 paddress (target_gdbarch (), lma),
8755 paddress (target_gdbarch (), lma + size));
c906108c 8756
5af949e3 8757 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
8758 paddress (target_gdbarch (), lma),
8759 paddress (target_gdbarch (), lma + size));
4a5e7a5b 8760 if (res)
c906108c
SS
8761 printf_filtered ("matched.\n");
8762 else
c5aa993b
JM
8763 {
8764 printf_filtered ("MIS-MATCHED!\n");
8765 mismatched++;
8766 }
c906108c
SS
8767
8768 do_cleanups (old_chain);
8769 }
8770 if (mismatched > 0)
936d2992 8771 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 8772the loaded file\n"));
c906108c 8773 if (args && !matched)
a3f17187 8774 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
8775}
8776
0e7f50da
UW
8777/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8778 into remote target. The number of bytes written to the remote
8779 target is returned, or -1 for error. */
8780
9b409511 8781static enum target_xfer_status
0e7f50da
UW
8782remote_write_qxfer (struct target_ops *ops, const char *object_name,
8783 const char *annex, const gdb_byte *writebuf,
9b409511 8784 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
8785 struct packet_config *packet)
8786{
8787 int i, buf_len;
8788 ULONGEST n;
0e7f50da
UW
8789 struct remote_state *rs = get_remote_state ();
8790 int max_size = get_memory_write_packet_size ();
8791
8792 if (packet->support == PACKET_DISABLE)
2ed4b548 8793 return TARGET_XFER_E_IO;
0e7f50da
UW
8794
8795 /* Insert header. */
8796 i = snprintf (rs->buf, max_size,
8797 "qXfer:%s:write:%s:%s:",
8798 object_name, annex ? annex : "",
8799 phex_nz (offset, sizeof offset));
8800 max_size -= (i + 1);
8801
8802 /* Escape as much data as fits into rs->buf. */
8803 buf_len = remote_escape_output
bc20a4af 8804 (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
8805
8806 if (putpkt_binary (rs->buf, i + buf_len) < 0
8807 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8808 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 8809 return TARGET_XFER_E_IO;
0e7f50da
UW
8810
8811 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
8812
8813 *xfered_len = n;
8814 return TARGET_XFER_OK;
0e7f50da
UW
8815}
8816
0876f84a
DJ
8817/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8818 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8819 number of bytes read is returned, or 0 for EOF, or -1 for error.
8820 The number of bytes read may be less than LEN without indicating an
8821 EOF. PACKET is checked and updated to indicate whether the remote
8822 target supports this object. */
8823
9b409511 8824static enum target_xfer_status
0876f84a
DJ
8825remote_read_qxfer (struct target_ops *ops, const char *object_name,
8826 const char *annex,
8827 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 8828 ULONGEST *xfered_len,
0876f84a
DJ
8829 struct packet_config *packet)
8830{
0876f84a 8831 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
8832 LONGEST i, n, packet_len;
8833
8834 if (packet->support == PACKET_DISABLE)
2ed4b548 8835 return TARGET_XFER_E_IO;
0876f84a
DJ
8836
8837 /* Check whether we've cached an end-of-object packet that matches
8838 this request. */
8e88304f 8839 if (rs->finished_object)
0876f84a 8840 {
8e88304f
TT
8841 if (strcmp (object_name, rs->finished_object) == 0
8842 && strcmp (annex ? annex : "", rs->finished_annex) == 0
8843 && offset == rs->finished_offset)
9b409511
YQ
8844 return TARGET_XFER_EOF;
8845
0876f84a
DJ
8846
8847 /* Otherwise, we're now reading something different. Discard
8848 the cache. */
8e88304f
TT
8849 xfree (rs->finished_object);
8850 xfree (rs->finished_annex);
8851 rs->finished_object = NULL;
8852 rs->finished_annex = NULL;
0876f84a
DJ
8853 }
8854
8855 /* Request only enough to fit in a single packet. The actual data
8856 may not, since we don't know how much of it will need to be escaped;
8857 the target is free to respond with slightly less data. We subtract
8858 five to account for the response type and the protocol frame. */
8859 n = min (get_remote_packet_size () - 5, len);
8860 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8861 object_name, annex ? annex : "",
8862 phex_nz (offset, sizeof offset),
8863 phex_nz (n, sizeof n));
8864 i = putpkt (rs->buf);
8865 if (i < 0)
2ed4b548 8866 return TARGET_XFER_E_IO;
0876f84a
DJ
8867
8868 rs->buf[0] = '\0';
8869 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8870 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 8871 return TARGET_XFER_E_IO;
0876f84a
DJ
8872
8873 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8874 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8875
8876 /* 'm' means there is (or at least might be) more data after this
8877 batch. That does not make sense unless there's at least one byte
8878 of data in this reply. */
8879 if (rs->buf[0] == 'm' && packet_len == 1)
8880 error (_("Remote qXfer reply contained no data."));
8881
8882 /* Got some data. */
bc20a4af
PA
8883 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
8884 packet_len - 1, readbuf, n);
0876f84a
DJ
8885
8886 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
8887 or possibly empty. If we have the final block of a non-empty
8888 object, record this fact to bypass a subsequent partial read. */
8889 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 8890 {
8e88304f
TT
8891 rs->finished_object = xstrdup (object_name);
8892 rs->finished_annex = xstrdup (annex ? annex : "");
8893 rs->finished_offset = offset + i;
0876f84a
DJ
8894 }
8895
9b409511
YQ
8896 if (i == 0)
8897 return TARGET_XFER_EOF;
8898 else
8899 {
8900 *xfered_len = i;
8901 return TARGET_XFER_OK;
8902 }
0876f84a
DJ
8903}
8904
9b409511 8905static enum target_xfer_status
4b8a223f 8906remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 8907 const char *annex, gdb_byte *readbuf,
9b409511
YQ
8908 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
8909 ULONGEST *xfered_len)
c906108c 8910{
82f73884 8911 struct remote_state *rs;
c906108c 8912 int i;
6d820c5c 8913 char *p2;
1e3ff5ad 8914 char query_type;
c906108c 8915
e6e4e701 8916 set_remote_traceframe ();
82f73884
PA
8917 set_general_thread (inferior_ptid);
8918
8919 rs = get_remote_state ();
8920
b2182ed2 8921 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
8922 if (object == TARGET_OBJECT_MEMORY)
8923 {
2d717e4f
DJ
8924 /* If the remote target is connected but not running, we should
8925 pass this request down to a lower stratum (e.g. the executable
8926 file). */
8927 if (!target_has_execution)
9b409511 8928 return TARGET_XFER_EOF;
2d717e4f 8929
21e3b9b9 8930 if (writebuf != NULL)
9b409511 8931 return remote_write_bytes (offset, writebuf, len, xfered_len);
21e3b9b9 8932 else
8acf9577 8933 return remote_read_bytes (ops, offset, readbuf, len, xfered_len);
21e3b9b9
DJ
8934 }
8935
0df8b418 8936 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
8937 if (object == TARGET_OBJECT_SPU)
8938 {
8939 if (readbuf)
8940 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
8941 xfered_len, &remote_protocol_packets
8942 [PACKET_qXfer_spu_read]);
0e7f50da
UW
8943 else
8944 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
8945 xfered_len, &remote_protocol_packets
8946 [PACKET_qXfer_spu_write]);
0e7f50da
UW
8947 }
8948
4aa995e1
PA
8949 /* Handle extra signal info using qxfer packets. */
8950 if (object == TARGET_OBJECT_SIGNAL_INFO)
8951 {
8952 if (readbuf)
8953 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 8954 xfered_len, &remote_protocol_packets
4aa995e1
PA
8955 [PACKET_qXfer_siginfo_read]);
8956 else
3e43a32a 8957 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 8958 writebuf, offset, len, xfered_len,
4aa995e1
PA
8959 &remote_protocol_packets
8960 [PACKET_qXfer_siginfo_write]);
8961 }
8962
0fb4aa4b
PA
8963 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8964 {
8965 if (readbuf)
3e43a32a 8966 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 8967 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
8968 &remote_protocol_packets
8969 [PACKET_qXfer_statictrace_read]);
8970 else
2ed4b548 8971 return TARGET_XFER_E_IO;
0fb4aa4b
PA
8972 }
8973
a76d924d
DJ
8974 /* Only handle flash writes. */
8975 if (writebuf != NULL)
8976 {
8977 LONGEST xfered;
8978
8979 switch (object)
8980 {
8981 case TARGET_OBJECT_FLASH:
9b409511
YQ
8982 return remote_flash_write (ops, offset, len, xfered_len,
8983 writebuf);
a76d924d
DJ
8984
8985 default:
2ed4b548 8986 return TARGET_XFER_E_IO;
a76d924d
DJ
8987 }
8988 }
4b8a223f 8989
1e3ff5ad
AC
8990 /* Map pre-existing objects onto letters. DO NOT do this for new
8991 objects!!! Instead specify new query packets. */
8992 switch (object)
c906108c 8993 {
1e3ff5ad
AC
8994 case TARGET_OBJECT_AVR:
8995 query_type = 'R';
8996 break;
802188a7
RM
8997
8998 case TARGET_OBJECT_AUXV:
0876f84a
DJ
8999 gdb_assert (annex == NULL);
9000 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 9001 xfered_len,
0876f84a 9002 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 9003
23181151
DJ
9004 case TARGET_OBJECT_AVAILABLE_FEATURES:
9005 return remote_read_qxfer
9b409511 9006 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
9007 &remote_protocol_packets[PACKET_qXfer_features]);
9008
cfa9d6d9
DJ
9009 case TARGET_OBJECT_LIBRARIES:
9010 return remote_read_qxfer
9b409511 9011 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
9012 &remote_protocol_packets[PACKET_qXfer_libraries]);
9013
2268b414
JK
9014 case TARGET_OBJECT_LIBRARIES_SVR4:
9015 return remote_read_qxfer
9b409511 9016 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
9017 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9018
fd79ecee
DJ
9019 case TARGET_OBJECT_MEMORY_MAP:
9020 gdb_assert (annex == NULL);
9021 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 9022 xfered_len,
fd79ecee
DJ
9023 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9024
07e059b5
VP
9025 case TARGET_OBJECT_OSDATA:
9026 /* Should only get here if we're connected. */
5d93a237 9027 gdb_assert (rs->remote_desc);
07e059b5 9028 return remote_read_qxfer
9b409511 9029 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
9030 &remote_protocol_packets[PACKET_qXfer_osdata]);
9031
dc146f7c
VP
9032 case TARGET_OBJECT_THREADS:
9033 gdb_assert (annex == NULL);
9034 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 9035 xfered_len,
dc146f7c
VP
9036 &remote_protocol_packets[PACKET_qXfer_threads]);
9037
b3b9301e
PA
9038 case TARGET_OBJECT_TRACEFRAME_INFO:
9039 gdb_assert (annex == NULL);
9040 return remote_read_qxfer
9b409511 9041 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 9042 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
9043
9044 case TARGET_OBJECT_FDPIC:
9045 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 9046 xfered_len,
78d85199 9047 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
9048
9049 case TARGET_OBJECT_OPENVMS_UIB:
9050 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 9051 xfered_len,
169081d0
TG
9052 &remote_protocol_packets[PACKET_qXfer_uib]);
9053
9accd112
MM
9054 case TARGET_OBJECT_BTRACE:
9055 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 9056 xfered_len,
9accd112
MM
9057 &remote_protocol_packets[PACKET_qXfer_btrace]);
9058
f4abbc16
MM
9059 case TARGET_OBJECT_BTRACE_CONF:
9060 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9061 len, xfered_len,
9062 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9063
1e3ff5ad 9064 default:
2ed4b548 9065 return TARGET_XFER_E_IO;
c906108c
SS
9066 }
9067
0df8b418 9068 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 9069 large enough let the caller deal with it. */
ea9c271d 9070 if (len < get_remote_packet_size ())
2ed4b548 9071 return TARGET_XFER_E_IO;
ea9c271d 9072 len = get_remote_packet_size ();
1e3ff5ad 9073
23860348 9074 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 9075 if (!rs->remote_desc)
8a3fe4f8 9076 error (_("remote query is only available after target open"));
c906108c 9077
1e3ff5ad 9078 gdb_assert (annex != NULL);
4b8a223f 9079 gdb_assert (readbuf != NULL);
c906108c 9080
6d820c5c 9081 p2 = rs->buf;
c906108c
SS
9082 *p2++ = 'q';
9083 *p2++ = query_type;
9084
23860348
MS
9085 /* We used one buffer char for the remote protocol q command and
9086 another for the query type. As the remote protocol encapsulation
9087 uses 4 chars plus one extra in case we are debugging
9088 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9089 string. */
c906108c 9090 i = 0;
ea9c271d 9091 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 9092 {
1e3ff5ad
AC
9093 /* Bad caller may have sent forbidden characters. */
9094 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9095 *p2++ = annex[i];
c906108c
SS
9096 i++;
9097 }
1e3ff5ad
AC
9098 *p2 = '\0';
9099 gdb_assert (annex[i] == '\0');
c906108c 9100
6d820c5c 9101 i = putpkt (rs->buf);
c5aa993b 9102 if (i < 0)
2ed4b548 9103 return TARGET_XFER_E_IO;
c906108c 9104
6d820c5c
DJ
9105 getpkt (&rs->buf, &rs->buf_size, 0);
9106 strcpy ((char *) readbuf, rs->buf);
c906108c 9107
9b409511
YQ
9108 *xfered_len = strlen ((char *) readbuf);
9109 return TARGET_XFER_OK;
c906108c
SS
9110}
9111
08388c79
DE
9112static int
9113remote_search_memory (struct target_ops* ops,
9114 CORE_ADDR start_addr, ULONGEST search_space_len,
9115 const gdb_byte *pattern, ULONGEST pattern_len,
9116 CORE_ADDR *found_addrp)
9117{
f5656ead 9118 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
9119 struct remote_state *rs = get_remote_state ();
9120 int max_size = get_memory_write_packet_size ();
9121 struct packet_config *packet =
9122 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
9123 /* Number of packet bytes used to encode the pattern;
9124 this could be more than PATTERN_LEN due to escape characters. */
08388c79 9125 int escaped_pattern_len;
0df8b418 9126 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
9127 int used_pattern_len;
9128 int i;
9129 int found;
9130 ULONGEST found_addr;
9131
9132 /* Don't go to the target if we don't have to.
9133 This is done before checking packet->support to avoid the possibility that
9134 a success for this edge case means the facility works in general. */
9135 if (pattern_len > search_space_len)
9136 return 0;
9137 if (pattern_len == 0)
9138 {
9139 *found_addrp = start_addr;
9140 return 1;
9141 }
9142
9143 /* If we already know the packet isn't supported, fall back to the simple
9144 way of searching memory. */
9145
4082afcc 9146 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
9147 {
9148 /* Target doesn't provided special support, fall back and use the
9149 standard support (copy memory and do the search here). */
9150 return simple_search_memory (ops, start_addr, search_space_len,
9151 pattern, pattern_len, found_addrp);
9152 }
9153
28439a30
PA
9154 /* Make sure the remote is pointing at the right process. */
9155 set_general_process ();
9156
08388c79
DE
9157 /* Insert header. */
9158 i = snprintf (rs->buf, max_size,
9159 "qSearch:memory:%s;%s;",
5af949e3 9160 phex_nz (start_addr, addr_size),
08388c79
DE
9161 phex_nz (search_space_len, sizeof (search_space_len)));
9162 max_size -= (i + 1);
9163
9164 /* Escape as much data as fits into rs->buf. */
9165 escaped_pattern_len =
bc20a4af 9166 remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
08388c79
DE
9167 &used_pattern_len, max_size);
9168
9169 /* Bail if the pattern is too large. */
9170 if (used_pattern_len != pattern_len)
9b20d036 9171 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
9172
9173 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9174 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9175 || packet_ok (rs->buf, packet) != PACKET_OK)
9176 {
9177 /* The request may not have worked because the command is not
9178 supported. If so, fall back to the simple way. */
9179 if (packet->support == PACKET_DISABLE)
9180 {
9181 return simple_search_memory (ops, start_addr, search_space_len,
9182 pattern, pattern_len, found_addrp);
9183 }
9184 return -1;
9185 }
9186
9187 if (rs->buf[0] == '0')
9188 found = 0;
9189 else if (rs->buf[0] == '1')
9190 {
9191 found = 1;
9192 if (rs->buf[1] != ',')
10e0fa18 9193 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9194 unpack_varlen_hex (rs->buf + 2, &found_addr);
9195 *found_addrp = found_addr;
9196 }
9197 else
10e0fa18 9198 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9199
9200 return found;
9201}
9202
96baa820 9203static void
a30bf1f1 9204remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 9205 struct ui_file *outbuf)
96baa820 9206{
d01949b6 9207 struct remote_state *rs = get_remote_state ();
2e9f7625 9208 char *p = rs->buf;
96baa820 9209
5d93a237 9210 if (!rs->remote_desc)
8a3fe4f8 9211 error (_("remote rcmd is only available after target open"));
96baa820 9212
23860348 9213 /* Send a NULL command across as an empty command. */
7be570e7
JM
9214 if (command == NULL)
9215 command = "";
9216
23860348 9217 /* The query prefix. */
2e9f7625
DJ
9218 strcpy (rs->buf, "qRcmd,");
9219 p = strchr (rs->buf, '\0');
96baa820 9220
3e43a32a
MS
9221 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9222 > get_remote_packet_size ())
8a3fe4f8 9223 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 9224
23860348 9225 /* Encode the actual command. */
a30bf1f1 9226 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 9227
6d820c5c 9228 if (putpkt (rs->buf) < 0)
8a3fe4f8 9229 error (_("Communication problem with target."));
96baa820
JM
9230
9231 /* get/display the response */
9232 while (1)
9233 {
2e9f7625
DJ
9234 char *buf;
9235
00bf0b85 9236 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 9237 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 9238 rs->buf[0] = '\0';
5b37825d
PW
9239 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9240 {
9241 /* Timeout. Continue to (try to) read responses.
9242 This is better than stopping with an error, assuming the stub
9243 is still executing the (long) monitor command.
9244 If needed, the user can interrupt gdb using C-c, obtaining
9245 an effect similar to stop on timeout. */
9246 continue;
9247 }
2e9f7625 9248 buf = rs->buf;
96baa820 9249 if (buf[0] == '\0')
8a3fe4f8 9250 error (_("Target does not support this command."));
96baa820
JM
9251 if (buf[0] == 'O' && buf[1] != 'K')
9252 {
23860348 9253 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
9254 continue;
9255 }
9256 if (strcmp (buf, "OK") == 0)
9257 break;
7be570e7
JM
9258 if (strlen (buf) == 3 && buf[0] == 'E'
9259 && isdigit (buf[1]) && isdigit (buf[2]))
9260 {
8a3fe4f8 9261 error (_("Protocol error with Rcmd"));
7be570e7 9262 }
96baa820
JM
9263 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9264 {
9265 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 9266
96baa820
JM
9267 fputc_unfiltered (c, outbuf);
9268 }
9269 break;
9270 }
9271}
9272
fd79ecee
DJ
9273static VEC(mem_region_s) *
9274remote_memory_map (struct target_ops *ops)
9275{
9276 VEC(mem_region_s) *result = NULL;
9277 char *text = target_read_stralloc (&current_target,
9278 TARGET_OBJECT_MEMORY_MAP, NULL);
9279
9280 if (text)
9281 {
9282 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 9283
fd79ecee
DJ
9284 result = parse_memory_map (text);
9285 do_cleanups (back_to);
9286 }
9287
9288 return result;
9289}
9290
c906108c 9291static void
fba45db2 9292packet_command (char *args, int from_tty)
c906108c 9293{
d01949b6 9294 struct remote_state *rs = get_remote_state ();
c906108c 9295
5d93a237 9296 if (!rs->remote_desc)
8a3fe4f8 9297 error (_("command can only be used with remote target"));
c906108c 9298
c5aa993b 9299 if (!args)
8a3fe4f8 9300 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
9301
9302 puts_filtered ("sending: ");
9303 print_packet (args);
9304 puts_filtered ("\n");
9305 putpkt (args);
9306
6d820c5c 9307 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 9308 puts_filtered ("received: ");
6d820c5c 9309 print_packet (rs->buf);
c906108c
SS
9310 puts_filtered ("\n");
9311}
9312
9313#if 0
23860348 9314/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 9315
a14ed312 9316static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 9317
a14ed312 9318static void threadset_test_cmd (char *cmd, int tty);
c906108c 9319
a14ed312 9320static void threadalive_test (char *cmd, int tty);
c906108c 9321
a14ed312 9322static void threadlist_test_cmd (char *cmd, int tty);
c906108c 9323
23860348 9324int get_and_display_threadinfo (threadref *ref);
c906108c 9325
a14ed312 9326static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 9327
23860348 9328static int thread_display_step (threadref *ref, void *context);
c906108c 9329
a14ed312 9330static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 9331
a14ed312 9332static void init_remote_threadtests (void);
c906108c 9333
23860348 9334#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
9335
9336static void
fba45db2 9337threadset_test_cmd (char *cmd, int tty)
c906108c
SS
9338{
9339 int sample_thread = SAMPLE_THREAD;
9340
a3f17187 9341 printf_filtered (_("Remote threadset test\n"));
79d7f229 9342 set_general_thread (sample_thread);
c906108c
SS
9343}
9344
9345
9346static void
fba45db2 9347threadalive_test (char *cmd, int tty)
c906108c
SS
9348{
9349 int sample_thread = SAMPLE_THREAD;
79d7f229 9350 int pid = ptid_get_pid (inferior_ptid);
ba348170 9351 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 9352
79d7f229 9353 if (remote_thread_alive (ptid))
c906108c
SS
9354 printf_filtered ("PASS: Thread alive test\n");
9355 else
9356 printf_filtered ("FAIL: Thread alive test\n");
9357}
9358
23860348 9359void output_threadid (char *title, threadref *ref);
c906108c
SS
9360
9361void
fba45db2 9362output_threadid (char *title, threadref *ref)
c906108c
SS
9363{
9364 char hexid[20];
9365
23860348 9366 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
9367 hexid[16] = 0;
9368 printf_filtered ("%s %s\n", title, (&hexid[0]));
9369}
9370
9371static void
fba45db2 9372threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
9373{
9374 int startflag = 1;
9375 threadref nextthread;
9376 int done, result_count;
9377 threadref threadlist[3];
9378
9379 printf_filtered ("Remote Threadlist test\n");
9380 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9381 &result_count, &threadlist[0]))
9382 printf_filtered ("FAIL: threadlist test\n");
9383 else
9384 {
9385 threadref *scan = threadlist;
9386 threadref *limit = scan + result_count;
9387
9388 while (scan < limit)
9389 output_threadid (" thread ", scan++);
9390 }
9391}
9392
9393void
fba45db2 9394display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
9395{
9396 output_threadid ("Threadid: ", &info->threadid);
9397 printf_filtered ("Name: %s\n ", info->shortname);
9398 printf_filtered ("State: %s\n", info->display);
9399 printf_filtered ("other: %s\n\n", info->more_display);
9400}
9401
9402int
fba45db2 9403get_and_display_threadinfo (threadref *ref)
c906108c
SS
9404{
9405 int result;
9406 int set;
9407 struct gdb_ext_thread_info threadinfo;
9408
9409 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9410 | TAG_MOREDISPLAY | TAG_DISPLAY;
9411 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9412 display_thread_info (&threadinfo);
9413 return result;
9414}
9415
9416static void
fba45db2 9417threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
9418{
9419 int athread = SAMPLE_THREAD;
9420 threadref thread;
9421 int set;
9422
9423 int_to_threadref (&thread, athread);
9424 printf_filtered ("Remote Threadinfo test\n");
9425 if (!get_and_display_threadinfo (&thread))
9426 printf_filtered ("FAIL cannot get thread info\n");
9427}
9428
9429static int
fba45db2 9430thread_display_step (threadref *ref, void *context)
c906108c
SS
9431{
9432 /* output_threadid(" threadstep ",ref); *//* simple test */
9433 return get_and_display_threadinfo (ref);
9434}
9435
9436static void
fba45db2 9437threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
9438{
9439 printf_filtered ("Remote Threadlist update test\n");
9440 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9441}
9442
9443static void
9444init_remote_threadtests (void)
9445{
3e43a32a
MS
9446 add_com ("tlist", class_obscure, threadlist_test_cmd,
9447 _("Fetch and print the remote list of "
9448 "thread identifiers, one pkt only"));
c906108c 9449 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 9450 _("Fetch and display info about one thread"));
c906108c 9451 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 9452 _("Test setting to a different thread"));
c906108c 9453 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 9454 _("Iterate through updating all remote thread info"));
c906108c 9455 add_com ("talive", class_obscure, threadalive_test,
1bedd215 9456 _(" Remote thread alive test "));
c906108c
SS
9457}
9458
9459#endif /* 0 */
9460
f3fb8c85
MS
9461/* Convert a thread ID to a string. Returns the string in a static
9462 buffer. */
9463
9464static char *
117de6a9 9465remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 9466{
79d7f229 9467 static char buf[64];
82f73884 9468 struct remote_state *rs = get_remote_state ();
f3fb8c85 9469
7cee1e54
PA
9470 if (ptid_equal (ptid, null_ptid))
9471 return normal_pid_to_str (ptid);
9472 else if (ptid_is_pid (ptid))
ecd0ada5
PA
9473 {
9474 /* Printing an inferior target id. */
9475
9476 /* When multi-process extensions are off, there's no way in the
9477 remote protocol to know the remote process id, if there's any
9478 at all. There's one exception --- when we're connected with
9479 target extended-remote, and we manually attached to a process
9480 with "attach PID". We don't record anywhere a flag that
9481 allows us to distinguish that case from the case of
9482 connecting with extended-remote and the stub already being
9483 attached to a process, and reporting yes to qAttached, hence
9484 no smart special casing here. */
9485 if (!remote_multi_process_p (rs))
9486 {
9487 xsnprintf (buf, sizeof buf, "Remote target");
9488 return buf;
9489 }
9490
9491 return normal_pid_to_str (ptid);
82f73884 9492 }
ecd0ada5 9493 else
79d7f229 9494 {
ecd0ada5
PA
9495 if (ptid_equal (magic_null_ptid, ptid))
9496 xsnprintf (buf, sizeof buf, "Thread <main>");
901f9912 9497 else if (rs->extended && remote_multi_process_p (rs))
ecd0ada5 9498 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
ba348170 9499 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
9500 else
9501 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 9502 ptid_get_lwp (ptid));
79d7f229
PA
9503 return buf;
9504 }
f3fb8c85
MS
9505}
9506
38691318
KB
9507/* Get the address of the thread local variable in OBJFILE which is
9508 stored at OFFSET within the thread local storage for thread PTID. */
9509
9510static CORE_ADDR
117de6a9
PA
9511remote_get_thread_local_address (struct target_ops *ops,
9512 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 9513{
4082afcc 9514 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
9515 {
9516 struct remote_state *rs = get_remote_state ();
6d820c5c 9517 char *p = rs->buf;
82f73884 9518 char *endp = rs->buf + get_remote_packet_size ();
571dd617 9519 enum packet_result result;
38691318
KB
9520
9521 strcpy (p, "qGetTLSAddr:");
9522 p += strlen (p);
82f73884 9523 p = write_ptid (p, endp, ptid);
38691318
KB
9524 *p++ = ',';
9525 p += hexnumstr (p, offset);
9526 *p++ = ',';
9527 p += hexnumstr (p, lm);
9528 *p++ = '\0';
9529
6d820c5c
DJ
9530 putpkt (rs->buf);
9531 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
9532 result = packet_ok (rs->buf,
9533 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 9534 if (result == PACKET_OK)
38691318
KB
9535 {
9536 ULONGEST result;
9537
6d820c5c 9538 unpack_varlen_hex (rs->buf, &result);
38691318
KB
9539 return result;
9540 }
571dd617 9541 else if (result == PACKET_UNKNOWN)
109c3e39
AC
9542 throw_error (TLS_GENERIC_ERROR,
9543 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 9544 else
109c3e39
AC
9545 throw_error (TLS_GENERIC_ERROR,
9546 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
9547 }
9548 else
109c3e39
AC
9549 throw_error (TLS_GENERIC_ERROR,
9550 _("TLS not supported or disabled on this target"));
38691318
KB
9551 /* Not reached. */
9552 return 0;
9553}
9554
711e434b
PM
9555/* Provide thread local base, i.e. Thread Information Block address.
9556 Returns 1 if ptid is found and thread_local_base is non zero. */
9557
70221824 9558static int
bd7ae0f5 9559remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 9560{
4082afcc 9561 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
9562 {
9563 struct remote_state *rs = get_remote_state ();
9564 char *p = rs->buf;
9565 char *endp = rs->buf + get_remote_packet_size ();
9566 enum packet_result result;
9567
9568 strcpy (p, "qGetTIBAddr:");
9569 p += strlen (p);
9570 p = write_ptid (p, endp, ptid);
9571 *p++ = '\0';
9572
9573 putpkt (rs->buf);
9574 getpkt (&rs->buf, &rs->buf_size, 0);
9575 result = packet_ok (rs->buf,
9576 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9577 if (result == PACKET_OK)
9578 {
9579 ULONGEST result;
9580
9581 unpack_varlen_hex (rs->buf, &result);
9582 if (addr)
9583 *addr = (CORE_ADDR) result;
9584 return 1;
9585 }
9586 else if (result == PACKET_UNKNOWN)
9587 error (_("Remote target doesn't support qGetTIBAddr packet"));
9588 else
9589 error (_("Remote target failed to process qGetTIBAddr request"));
9590 }
9591 else
9592 error (_("qGetTIBAddr not supported or disabled on this target"));
9593 /* Not reached. */
9594 return 0;
9595}
9596
29709017
DJ
9597/* Support for inferring a target description based on the current
9598 architecture and the size of a 'g' packet. While the 'g' packet
9599 can have any size (since optional registers can be left off the
9600 end), some sizes are easily recognizable given knowledge of the
9601 approximate architecture. */
9602
9603struct remote_g_packet_guess
9604{
9605 int bytes;
9606 const struct target_desc *tdesc;
9607};
9608typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9609DEF_VEC_O(remote_g_packet_guess_s);
9610
9611struct remote_g_packet_data
9612{
9613 VEC(remote_g_packet_guess_s) *guesses;
9614};
9615
9616static struct gdbarch_data *remote_g_packet_data_handle;
9617
9618static void *
9619remote_g_packet_data_init (struct obstack *obstack)
9620{
9621 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9622}
9623
9624void
9625register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9626 const struct target_desc *tdesc)
9627{
9628 struct remote_g_packet_data *data
9629 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9630 struct remote_g_packet_guess new_guess, *guess;
9631 int ix;
9632
9633 gdb_assert (tdesc != NULL);
9634
9635 for (ix = 0;
9636 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9637 ix++)
9638 if (guess->bytes == bytes)
9639 internal_error (__FILE__, __LINE__,
9b20d036 9640 _("Duplicate g packet description added for size %d"),
29709017
DJ
9641 bytes);
9642
9643 new_guess.bytes = bytes;
9644 new_guess.tdesc = tdesc;
9645 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9646}
9647
d962ef82
DJ
9648/* Return 1 if remote_read_description would do anything on this target
9649 and architecture, 0 otherwise. */
9650
9651static int
9652remote_read_description_p (struct target_ops *target)
9653{
9654 struct remote_g_packet_data *data
f5656ead 9655 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
d962ef82
DJ
9656
9657 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9658 return 1;
9659
9660 return 0;
9661}
9662
29709017
DJ
9663static const struct target_desc *
9664remote_read_description (struct target_ops *target)
9665{
9666 struct remote_g_packet_data *data
f5656ead 9667 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
29709017 9668
d962ef82
DJ
9669 /* Do not try this during initial connection, when we do not know
9670 whether there is a running but stopped thread. */
9671 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 9672 return target->beneath->to_read_description (target->beneath);
d962ef82 9673
29709017
DJ
9674 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9675 {
9676 struct remote_g_packet_guess *guess;
9677 int ix;
9678 int bytes = send_g_packet ();
9679
9680 for (ix = 0;
9681 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9682 ix++)
9683 if (guess->bytes == bytes)
9684 return guess->tdesc;
9685
9686 /* We discard the g packet. A minor optimization would be to
9687 hold on to it, and fill the register cache once we have selected
9688 an architecture, but it's too tricky to do safely. */
9689 }
9690
2117c711 9691 return target->beneath->to_read_description (target->beneath);
29709017
DJ
9692}
9693
a6b151f1
DJ
9694/* Remote file transfer support. This is host-initiated I/O, not
9695 target-initiated; for target-initiated, see remote-fileio.c. */
9696
9697/* If *LEFT is at least the length of STRING, copy STRING to
9698 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9699 decrease *LEFT. Otherwise raise an error. */
9700
9701static void
9702remote_buffer_add_string (char **buffer, int *left, char *string)
9703{
9704 int len = strlen (string);
9705
9706 if (len > *left)
9707 error (_("Packet too long for target."));
9708
9709 memcpy (*buffer, string, len);
9710 *buffer += len;
9711 *left -= len;
9712
9713 /* NUL-terminate the buffer as a convenience, if there is
9714 room. */
9715 if (*left)
9716 **buffer = '\0';
9717}
9718
9719/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9720 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9721 decrease *LEFT. Otherwise raise an error. */
9722
9723static void
9724remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9725 int len)
9726{
9727 if (2 * len > *left)
9728 error (_("Packet too long for target."));
9729
9730 bin2hex (bytes, *buffer, len);
9731 *buffer += 2 * len;
9732 *left -= 2 * len;
9733
9734 /* NUL-terminate the buffer as a convenience, if there is
9735 room. */
9736 if (*left)
9737 **buffer = '\0';
9738}
9739
9740/* If *LEFT is large enough, convert VALUE to hex and add it to
9741 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9742 decrease *LEFT. Otherwise raise an error. */
9743
9744static void
9745remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9746{
9747 int len = hexnumlen (value);
9748
9749 if (len > *left)
9750 error (_("Packet too long for target."));
9751
9752 hexnumstr (*buffer, value);
9753 *buffer += len;
9754 *left -= len;
9755
9756 /* NUL-terminate the buffer as a convenience, if there is
9757 room. */
9758 if (*left)
9759 **buffer = '\0';
9760}
9761
9762/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9763 value, *REMOTE_ERRNO to the remote error number or zero if none
9764 was included, and *ATTACHMENT to point to the start of the annex
9765 if any. The length of the packet isn't needed here; there may
9766 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9767
9768 Return 0 if the packet could be parsed, -1 if it could not. If
9769 -1 is returned, the other variables may not be initialized. */
9770
9771static int
9772remote_hostio_parse_result (char *buffer, int *retcode,
9773 int *remote_errno, char **attachment)
9774{
9775 char *p, *p2;
9776
9777 *remote_errno = 0;
9778 *attachment = NULL;
9779
9780 if (buffer[0] != 'F')
9781 return -1;
9782
9783 errno = 0;
9784 *retcode = strtol (&buffer[1], &p, 16);
9785 if (errno != 0 || p == &buffer[1])
9786 return -1;
9787
9788 /* Check for ",errno". */
9789 if (*p == ',')
9790 {
9791 errno = 0;
9792 *remote_errno = strtol (p + 1, &p2, 16);
9793 if (errno != 0 || p + 1 == p2)
9794 return -1;
9795 p = p2;
9796 }
9797
9798 /* Check for ";attachment". If there is no attachment, the
9799 packet should end here. */
9800 if (*p == ';')
9801 {
9802 *attachment = p + 1;
9803 return 0;
9804 }
9805 else if (*p == '\0')
9806 return 0;
9807 else
9808 return -1;
9809}
9810
9811/* Send a prepared I/O packet to the target and read its response.
9812 The prepared packet is in the global RS->BUF before this function
9813 is called, and the answer is there when we return.
9814
9815 COMMAND_BYTES is the length of the request to send, which may include
9816 binary data. WHICH_PACKET is the packet configuration to check
9817 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9818 is set to the error number and -1 is returned. Otherwise the value
9819 returned by the function is returned.
9820
9821 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9822 attachment is expected; an error will be reported if there's a
9823 mismatch. If one is found, *ATTACHMENT will be set to point into
9824 the packet buffer and *ATTACHMENT_LEN will be set to the
9825 attachment's length. */
9826
9827static int
9828remote_hostio_send_command (int command_bytes, int which_packet,
9829 int *remote_errno, char **attachment,
9830 int *attachment_len)
9831{
9832 struct remote_state *rs = get_remote_state ();
9833 int ret, bytes_read;
9834 char *attachment_tmp;
9835
5d93a237 9836 if (!rs->remote_desc
4082afcc 9837 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
9838 {
9839 *remote_errno = FILEIO_ENOSYS;
9840 return -1;
9841 }
9842
9843 putpkt_binary (rs->buf, command_bytes);
9844 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9845
9846 /* If it timed out, something is wrong. Don't try to parse the
9847 buffer. */
9848 if (bytes_read < 0)
9849 {
9850 *remote_errno = FILEIO_EINVAL;
9851 return -1;
9852 }
9853
9854 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9855 {
9856 case PACKET_ERROR:
9857 *remote_errno = FILEIO_EINVAL;
9858 return -1;
9859 case PACKET_UNKNOWN:
9860 *remote_errno = FILEIO_ENOSYS;
9861 return -1;
9862 case PACKET_OK:
9863 break;
9864 }
9865
9866 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9867 &attachment_tmp))
9868 {
9869 *remote_errno = FILEIO_EINVAL;
9870 return -1;
9871 }
9872
9873 /* Make sure we saw an attachment if and only if we expected one. */
9874 if ((attachment_tmp == NULL && attachment != NULL)
9875 || (attachment_tmp != NULL && attachment == NULL))
9876 {
9877 *remote_errno = FILEIO_EINVAL;
9878 return -1;
9879 }
9880
9881 /* If an attachment was found, it must point into the packet buffer;
9882 work out how many bytes there were. */
9883 if (attachment_tmp != NULL)
9884 {
9885 *attachment = attachment_tmp;
9886 *attachment_len = bytes_read - (*attachment - rs->buf);
9887 }
9888
9889 return ret;
9890}
9891
9892/* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9893 remote file descriptor, or -1 if an error occurs (and set
9894 *REMOTE_ERRNO). */
9895
9896static int
cd897586
TT
9897remote_hostio_open (struct target_ops *self,
9898 const char *filename, int flags, int mode,
a6b151f1
DJ
9899 int *remote_errno)
9900{
9901 struct remote_state *rs = get_remote_state ();
9902 char *p = rs->buf;
9903 int left = get_remote_packet_size () - 1;
9904
9905 remote_buffer_add_string (&p, &left, "vFile:open:");
9906
9907 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9908 strlen (filename));
9909 remote_buffer_add_string (&p, &left, ",");
9910
9911 remote_buffer_add_int (&p, &left, flags);
9912 remote_buffer_add_string (&p, &left, ",");
9913
9914 remote_buffer_add_int (&p, &left, mode);
9915
9916 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9917 remote_errno, NULL, NULL);
9918}
9919
9920/* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9921 Return the number of bytes written, or -1 if an error occurs (and
9922 set *REMOTE_ERRNO). */
9923
9924static int
0d866f62
TT
9925remote_hostio_pwrite (struct target_ops *self,
9926 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
9927 ULONGEST offset, int *remote_errno)
9928{
9929 struct remote_state *rs = get_remote_state ();
9930 char *p = rs->buf;
9931 int left = get_remote_packet_size ();
9932 int out_len;
9933
9934 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9935
9936 remote_buffer_add_int (&p, &left, fd);
9937 remote_buffer_add_string (&p, &left, ",");
9938
9939 remote_buffer_add_int (&p, &left, offset);
9940 remote_buffer_add_string (&p, &left, ",");
9941
bc20a4af 9942 p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
a6b151f1
DJ
9943 get_remote_packet_size () - (p - rs->buf));
9944
9945 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9946 remote_errno, NULL, NULL);
9947}
9948
9949/* Read up to LEN bytes FD on the remote target into READ_BUF
9950 Return the number of bytes read, or -1 if an error occurs (and
9951 set *REMOTE_ERRNO). */
9952
9953static int
a3be983c
TT
9954remote_hostio_pread (struct target_ops *self,
9955 int fd, gdb_byte *read_buf, int len,
a6b151f1
DJ
9956 ULONGEST offset, int *remote_errno)
9957{
9958 struct remote_state *rs = get_remote_state ();
9959 char *p = rs->buf;
9960 char *attachment;
9961 int left = get_remote_packet_size ();
9962 int ret, attachment_len;
9963 int read_len;
9964
9965 remote_buffer_add_string (&p, &left, "vFile:pread:");
9966
9967 remote_buffer_add_int (&p, &left, fd);
9968 remote_buffer_add_string (&p, &left, ",");
9969
9970 remote_buffer_add_int (&p, &left, len);
9971 remote_buffer_add_string (&p, &left, ",");
9972
9973 remote_buffer_add_int (&p, &left, offset);
9974
9975 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9976 remote_errno, &attachment,
9977 &attachment_len);
9978
9979 if (ret < 0)
9980 return ret;
9981
bc20a4af 9982 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
9983 read_buf, len);
9984 if (read_len != ret)
9985 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9986
9987 return ret;
9988}
9989
9990/* Close FD on the remote target. Return 0, or -1 if an error occurs
9991 (and set *REMOTE_ERRNO). */
9992
9993static int
df39ea25 9994remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
9995{
9996 struct remote_state *rs = get_remote_state ();
9997 char *p = rs->buf;
9998 int left = get_remote_packet_size () - 1;
9999
10000 remote_buffer_add_string (&p, &left, "vFile:close:");
10001
10002 remote_buffer_add_int (&p, &left, fd);
10003
10004 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
10005 remote_errno, NULL, NULL);
10006}
10007
10008/* Unlink FILENAME on the remote target. Return 0, or -1 if an error
10009 occurs (and set *REMOTE_ERRNO). */
10010
10011static int
dbbca37d
TT
10012remote_hostio_unlink (struct target_ops *self,
10013 const char *filename, int *remote_errno)
a6b151f1
DJ
10014{
10015 struct remote_state *rs = get_remote_state ();
10016 char *p = rs->buf;
10017 int left = get_remote_packet_size () - 1;
10018
10019 remote_buffer_add_string (&p, &left, "vFile:unlink:");
10020
10021 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10022 strlen (filename));
10023
10024 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10025 remote_errno, NULL, NULL);
10026}
10027
b9e7b9c3
UW
10028/* Read value of symbolic link FILENAME on the remote target. Return
10029 a null-terminated string allocated via xmalloc, or NULL if an error
10030 occurs (and set *REMOTE_ERRNO). */
10031
10032static char *
fab5aa7c
TT
10033remote_hostio_readlink (struct target_ops *self,
10034 const char *filename, int *remote_errno)
b9e7b9c3
UW
10035{
10036 struct remote_state *rs = get_remote_state ();
10037 char *p = rs->buf;
10038 char *attachment;
10039 int left = get_remote_packet_size ();
10040 int len, attachment_len;
10041 int read_len;
10042 char *ret;
10043
10044 remote_buffer_add_string (&p, &left, "vFile:readlink:");
10045
10046 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10047 strlen (filename));
10048
10049 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10050 remote_errno, &attachment,
10051 &attachment_len);
10052
10053 if (len < 0)
10054 return NULL;
10055
10056 ret = xmalloc (len + 1);
10057
bc20a4af
PA
10058 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10059 (gdb_byte *) ret, len);
b9e7b9c3
UW
10060 if (read_len != len)
10061 error (_("Readlink returned %d, but %d bytes."), len, read_len);
10062
10063 ret[len] = '\0';
10064 return ret;
10065}
10066
a6b151f1
DJ
10067static int
10068remote_fileio_errno_to_host (int errnum)
10069{
10070 switch (errnum)
10071 {
10072 case FILEIO_EPERM:
10073 return EPERM;
10074 case FILEIO_ENOENT:
10075 return ENOENT;
10076 case FILEIO_EINTR:
10077 return EINTR;
10078 case FILEIO_EIO:
10079 return EIO;
10080 case FILEIO_EBADF:
10081 return EBADF;
10082 case FILEIO_EACCES:
10083 return EACCES;
10084 case FILEIO_EFAULT:
10085 return EFAULT;
10086 case FILEIO_EBUSY:
10087 return EBUSY;
10088 case FILEIO_EEXIST:
10089 return EEXIST;
10090 case FILEIO_ENODEV:
10091 return ENODEV;
10092 case FILEIO_ENOTDIR:
10093 return ENOTDIR;
10094 case FILEIO_EISDIR:
10095 return EISDIR;
10096 case FILEIO_EINVAL:
10097 return EINVAL;
10098 case FILEIO_ENFILE:
10099 return ENFILE;
10100 case FILEIO_EMFILE:
10101 return EMFILE;
10102 case FILEIO_EFBIG:
10103 return EFBIG;
10104 case FILEIO_ENOSPC:
10105 return ENOSPC;
10106 case FILEIO_ESPIPE:
10107 return ESPIPE;
10108 case FILEIO_EROFS:
10109 return EROFS;
10110 case FILEIO_ENOSYS:
10111 return ENOSYS;
10112 case FILEIO_ENAMETOOLONG:
10113 return ENAMETOOLONG;
10114 }
10115 return -1;
10116}
10117
10118static char *
10119remote_hostio_error (int errnum)
10120{
10121 int host_error = remote_fileio_errno_to_host (errnum);
10122
10123 if (host_error == -1)
10124 error (_("Unknown remote I/O error %d"), errnum);
10125 else
10126 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10127}
10128
a6b151f1
DJ
10129static void
10130remote_hostio_close_cleanup (void *opaque)
10131{
10132 int fd = *(int *) opaque;
10133 int remote_errno;
10134
df39ea25 10135 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
10136}
10137
f1838a98
UW
10138
10139static void *
10140remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
10141{
10142 const char *filename = bfd_get_filename (abfd);
10143 int fd, remote_errno;
10144 int *stream;
10145
10146 gdb_assert (remote_filename_p (filename));
10147
cd897586
TT
10148 fd = remote_hostio_open (find_target_at (process_stratum),
10149 filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
f1838a98
UW
10150 if (fd == -1)
10151 {
10152 errno = remote_fileio_errno_to_host (remote_errno);
10153 bfd_set_error (bfd_error_system_call);
10154 return NULL;
10155 }
10156
10157 stream = xmalloc (sizeof (int));
10158 *stream = fd;
10159 return stream;
10160}
10161
10162static int
10163remote_bfd_iovec_close (struct bfd *abfd, void *stream)
10164{
10165 int fd = *(int *)stream;
10166 int remote_errno;
10167
10168 xfree (stream);
10169
10170 /* Ignore errors on close; these may happen if the remote
10171 connection was already torn down. */
df39ea25 10172 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
f1838a98 10173
39ed5604
JK
10174 /* Zero means success. */
10175 return 0;
f1838a98
UW
10176}
10177
10178static file_ptr
10179remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
10180 file_ptr nbytes, file_ptr offset)
10181{
10182 int fd = *(int *)stream;
10183 int remote_errno;
10184 file_ptr pos, bytes;
10185
10186 pos = 0;
10187 while (nbytes > pos)
10188 {
a3be983c
TT
10189 bytes = remote_hostio_pread (find_target_at (process_stratum),
10190 fd, (gdb_byte *) buf + pos, nbytes - pos,
f1838a98
UW
10191 offset + pos, &remote_errno);
10192 if (bytes == 0)
10193 /* Success, but no bytes, means end-of-file. */
10194 break;
10195 if (bytes == -1)
10196 {
10197 errno = remote_fileio_errno_to_host (remote_errno);
10198 bfd_set_error (bfd_error_system_call);
10199 return -1;
10200 }
10201
10202 pos += bytes;
10203 }
10204
10205 return pos;
10206}
10207
10208static int
10209remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
10210{
10211 /* FIXME: We should probably implement remote_hostio_stat. */
10212 sb->st_size = INT_MAX;
10213 return 0;
10214}
10215
10216int
10217remote_filename_p (const char *filename)
10218{
61012eef 10219 return startswith (filename, REMOTE_SYSROOT_PREFIX);
f1838a98
UW
10220}
10221
10222bfd *
10223remote_bfd_open (const char *remote_file, const char *target)
10224{
64c31149
TT
10225 bfd *abfd = gdb_bfd_openr_iovec (remote_file, target,
10226 remote_bfd_iovec_open, NULL,
10227 remote_bfd_iovec_pread,
10228 remote_bfd_iovec_close,
10229 remote_bfd_iovec_stat);
10230
a4453b7e 10231 return abfd;
f1838a98
UW
10232}
10233
a6b151f1
DJ
10234void
10235remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10236{
10237 struct cleanup *back_to, *close_cleanup;
10238 int retcode, fd, remote_errno, bytes, io_size;
10239 FILE *file;
10240 gdb_byte *buffer;
10241 int bytes_in_buffer;
10242 int saw_eof;
10243 ULONGEST offset;
5d93a237 10244 struct remote_state *rs = get_remote_state ();
a6b151f1 10245
5d93a237 10246 if (!rs->remote_desc)
a6b151f1
DJ
10247 error (_("command can only be used with remote target"));
10248
614c279d 10249 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
10250 if (file == NULL)
10251 perror_with_name (local_file);
7c8a8b04 10252 back_to = make_cleanup_fclose (file);
a6b151f1 10253
cd897586
TT
10254 fd = remote_hostio_open (find_target_at (process_stratum),
10255 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1
DJ
10256 | FILEIO_O_TRUNC),
10257 0700, &remote_errno);
10258 if (fd == -1)
10259 remote_hostio_error (remote_errno);
10260
10261 /* Send up to this many bytes at once. They won't all fit in the
10262 remote packet limit, so we'll transfer slightly fewer. */
10263 io_size = get_remote_packet_size ();
10264 buffer = xmalloc (io_size);
10265 make_cleanup (xfree, buffer);
10266
10267 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10268
10269 bytes_in_buffer = 0;
10270 saw_eof = 0;
10271 offset = 0;
10272 while (bytes_in_buffer || !saw_eof)
10273 {
10274 if (!saw_eof)
10275 {
3e43a32a
MS
10276 bytes = fread (buffer + bytes_in_buffer, 1,
10277 io_size - bytes_in_buffer,
a6b151f1
DJ
10278 file);
10279 if (bytes == 0)
10280 {
10281 if (ferror (file))
10282 error (_("Error reading %s."), local_file);
10283 else
10284 {
10285 /* EOF. Unless there is something still in the
10286 buffer from the last iteration, we are done. */
10287 saw_eof = 1;
10288 if (bytes_in_buffer == 0)
10289 break;
10290 }
10291 }
10292 }
10293 else
10294 bytes = 0;
10295
10296 bytes += bytes_in_buffer;
10297 bytes_in_buffer = 0;
10298
0d866f62
TT
10299 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
10300 fd, buffer, bytes,
3e43a32a 10301 offset, &remote_errno);
a6b151f1
DJ
10302
10303 if (retcode < 0)
10304 remote_hostio_error (remote_errno);
10305 else if (retcode == 0)
10306 error (_("Remote write of %d bytes returned 0!"), bytes);
10307 else if (retcode < bytes)
10308 {
10309 /* Short write. Save the rest of the read data for the next
10310 write. */
10311 bytes_in_buffer = bytes - retcode;
10312 memmove (buffer, buffer + retcode, bytes_in_buffer);
10313 }
10314
10315 offset += retcode;
10316 }
10317
10318 discard_cleanups (close_cleanup);
df39ea25 10319 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
10320 remote_hostio_error (remote_errno);
10321
10322 if (from_tty)
10323 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10324 do_cleanups (back_to);
10325}
10326
10327void
10328remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10329{
10330 struct cleanup *back_to, *close_cleanup;
cea39f65 10331 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
10332 FILE *file;
10333 gdb_byte *buffer;
10334 ULONGEST offset;
5d93a237 10335 struct remote_state *rs = get_remote_state ();
a6b151f1 10336
5d93a237 10337 if (!rs->remote_desc)
a6b151f1
DJ
10338 error (_("command can only be used with remote target"));
10339
cd897586
TT
10340 fd = remote_hostio_open (find_target_at (process_stratum),
10341 remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
a6b151f1
DJ
10342 if (fd == -1)
10343 remote_hostio_error (remote_errno);
10344
614c279d 10345 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
10346 if (file == NULL)
10347 perror_with_name (local_file);
7c8a8b04 10348 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
10349
10350 /* Send up to this many bytes at once. They won't all fit in the
10351 remote packet limit, so we'll transfer slightly fewer. */
10352 io_size = get_remote_packet_size ();
10353 buffer = xmalloc (io_size);
10354 make_cleanup (xfree, buffer);
10355
10356 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10357
10358 offset = 0;
10359 while (1)
10360 {
a3be983c
TT
10361 bytes = remote_hostio_pread (find_target_at (process_stratum),
10362 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
10363 if (bytes == 0)
10364 /* Success, but no bytes, means end-of-file. */
10365 break;
10366 if (bytes == -1)
10367 remote_hostio_error (remote_errno);
10368
10369 offset += bytes;
10370
10371 bytes = fwrite (buffer, 1, bytes, file);
10372 if (bytes == 0)
10373 perror_with_name (local_file);
10374 }
10375
10376 discard_cleanups (close_cleanup);
df39ea25 10377 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
10378 remote_hostio_error (remote_errno);
10379
10380 if (from_tty)
10381 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10382 do_cleanups (back_to);
10383}
10384
10385void
10386remote_file_delete (const char *remote_file, int from_tty)
10387{
10388 int retcode, remote_errno;
5d93a237 10389 struct remote_state *rs = get_remote_state ();
a6b151f1 10390
5d93a237 10391 if (!rs->remote_desc)
a6b151f1
DJ
10392 error (_("command can only be used with remote target"));
10393
dbbca37d
TT
10394 retcode = remote_hostio_unlink (find_target_at (process_stratum),
10395 remote_file, &remote_errno);
a6b151f1
DJ
10396 if (retcode == -1)
10397 remote_hostio_error (remote_errno);
10398
10399 if (from_tty)
10400 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10401}
10402
10403static void
10404remote_put_command (char *args, int from_tty)
10405{
10406 struct cleanup *back_to;
10407 char **argv;
10408
d1a41061
PP
10409 if (args == NULL)
10410 error_no_arg (_("file to put"));
10411
10412 argv = gdb_buildargv (args);
a6b151f1
DJ
10413 back_to = make_cleanup_freeargv (argv);
10414 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10415 error (_("Invalid parameters to remote put"));
10416
10417 remote_file_put (argv[0], argv[1], from_tty);
10418
10419 do_cleanups (back_to);
10420}
10421
10422static void
10423remote_get_command (char *args, int from_tty)
10424{
10425 struct cleanup *back_to;
10426 char **argv;
10427
d1a41061
PP
10428 if (args == NULL)
10429 error_no_arg (_("file to get"));
10430
10431 argv = gdb_buildargv (args);
a6b151f1
DJ
10432 back_to = make_cleanup_freeargv (argv);
10433 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10434 error (_("Invalid parameters to remote get"));
10435
10436 remote_file_get (argv[0], argv[1], from_tty);
10437
10438 do_cleanups (back_to);
10439}
10440
10441static void
10442remote_delete_command (char *args, int from_tty)
10443{
10444 struct cleanup *back_to;
10445 char **argv;
10446
d1a41061
PP
10447 if (args == NULL)
10448 error_no_arg (_("file to delete"));
10449
10450 argv = gdb_buildargv (args);
a6b151f1
DJ
10451 back_to = make_cleanup_freeargv (argv);
10452 if (argv[0] == NULL || argv[1] != NULL)
10453 error (_("Invalid parameters to remote delete"));
10454
10455 remote_file_delete (argv[0], from_tty);
10456
10457 do_cleanups (back_to);
10458}
10459
10460static void
10461remote_command (char *args, int from_tty)
10462{
635c7e8a 10463 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
10464}
10465
b2175913 10466static int
19db3e69 10467remote_can_execute_reverse (struct target_ops *self)
b2175913 10468{
4082afcc
PA
10469 if (packet_support (PACKET_bs) == PACKET_ENABLE
10470 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
10471 return 1;
10472 else
10473 return 0;
b2175913
MS
10474}
10475
74531fed 10476static int
2a9a2795 10477remote_supports_non_stop (struct target_ops *self)
74531fed
PA
10478{
10479 return 1;
10480}
10481
03583c20 10482static int
2bfc0540 10483remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
10484{
10485 /* Only supported in extended mode. */
10486 return 0;
10487}
10488
8a305172 10489static int
86ce2668 10490remote_supports_multi_process (struct target_ops *self)
8a305172
PA
10491{
10492 struct remote_state *rs = get_remote_state ();
a744cf53 10493
901f9912
UW
10494 /* Only extended-remote handles being attached to multiple
10495 processes, even though plain remote can use the multi-process
10496 thread id extensions, so that GDB knows the target process's
10497 PID. */
10498 return rs->extended && remote_multi_process_p (rs);
8a305172
PA
10499}
10500
70221824 10501static int
782b2b07
SS
10502remote_supports_cond_tracepoints (void)
10503{
4082afcc 10504 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
10505}
10506
3788aec7 10507static int
efcc2da7 10508remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 10509{
4082afcc 10510 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
10511}
10512
70221824 10513static int
7a697b8d
SS
10514remote_supports_fast_tracepoints (void)
10515{
4082afcc 10516 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
10517}
10518
0fb4aa4b
PA
10519static int
10520remote_supports_static_tracepoints (void)
10521{
4082afcc 10522 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
10523}
10524
1e4d1764
YQ
10525static int
10526remote_supports_install_in_trace (void)
10527{
4082afcc 10528 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
10529}
10530
d248b706 10531static int
7d178d6a 10532remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 10533{
4082afcc
PA
10534 return (packet_support (PACKET_EnableDisableTracepoints_feature)
10535 == PACKET_ENABLE);
d248b706
KY
10536}
10537
3065dfb6 10538static int
6de37a3a 10539remote_supports_string_tracing (struct target_ops *self)
3065dfb6 10540{
4082afcc 10541 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
10542}
10543
d3ce09f5 10544static int
78eff0ec 10545remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 10546{
4082afcc 10547 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
10548}
10549
35b1e5cc 10550static void
ecae04e1 10551remote_trace_init (struct target_ops *self)
35b1e5cc
SS
10552{
10553 putpkt ("QTinit");
10554 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 10555 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
10556 error (_("Target does not support this command."));
10557}
10558
10559static void free_actions_list (char **actions_list);
10560static void free_actions_list_cleanup_wrapper (void *);
10561static void
10562free_actions_list_cleanup_wrapper (void *al)
10563{
10564 free_actions_list (al);
10565}
10566
10567static void
10568free_actions_list (char **actions_list)
10569{
10570 int ndx;
10571
10572 if (actions_list == 0)
10573 return;
10574
10575 for (ndx = 0; actions_list[ndx]; ndx++)
10576 xfree (actions_list[ndx]);
10577
10578 xfree (actions_list);
10579}
10580
409873ef
SS
10581/* Recursive routine to walk through command list including loops, and
10582 download packets for each command. */
10583
10584static void
10585remote_download_command_source (int num, ULONGEST addr,
10586 struct command_line *cmds)
10587{
10588 struct remote_state *rs = get_remote_state ();
10589 struct command_line *cmd;
10590
10591 for (cmd = cmds; cmd; cmd = cmd->next)
10592 {
0df8b418 10593 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
10594 strcpy (rs->buf, "QTDPsrc:");
10595 encode_source_string (num, addr, "cmd", cmd->line,
10596 rs->buf + strlen (rs->buf),
10597 rs->buf_size - strlen (rs->buf));
10598 putpkt (rs->buf);
10599 remote_get_noisy_reply (&target_buf, &target_buf_size);
10600 if (strcmp (target_buf, "OK"))
10601 warning (_("Target does not support source download."));
10602
10603 if (cmd->control_type == while_control
10604 || cmd->control_type == while_stepping_control)
10605 {
10606 remote_download_command_source (num, addr, *cmd->body_list);
10607
0df8b418 10608 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
10609 strcpy (rs->buf, "QTDPsrc:");
10610 encode_source_string (num, addr, "cmd", "end",
10611 rs->buf + strlen (rs->buf),
10612 rs->buf_size - strlen (rs->buf));
10613 putpkt (rs->buf);
10614 remote_get_noisy_reply (&target_buf, &target_buf_size);
10615 if (strcmp (target_buf, "OK"))
10616 warning (_("Target does not support source download."));
10617 }
10618 }
10619}
10620
35b1e5cc 10621static void
548f7808 10622remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 10623{
bba74b36 10624#define BUF_SIZE 2048
e8ba3115 10625
35b1e5cc 10626 CORE_ADDR tpaddr;
409873ef 10627 char addrbuf[40];
bba74b36 10628 char buf[BUF_SIZE];
35b1e5cc
SS
10629 char **tdp_actions;
10630 char **stepping_actions;
10631 int ndx;
10632 struct cleanup *old_chain = NULL;
10633 struct agent_expr *aexpr;
10634 struct cleanup *aexpr_chain = NULL;
10635 char *pkt;
e8ba3115 10636 struct breakpoint *b = loc->owner;
d9b3f62e 10637 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 10638
dc673c81 10639 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
10640 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10641 tdp_actions);
10642 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10643 stepping_actions);
10644
10645 tpaddr = loc->address;
10646 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
10647 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10648 addrbuf, /* address */
10649 (b->enable_state == bp_enabled ? 'E' : 'D'),
10650 t->step_count, t->pass_count);
e8ba3115
YQ
10651 /* Fast tracepoints are mostly handled by the target, but we can
10652 tell the target how big of an instruction block should be moved
10653 around. */
10654 if (b->type == bp_fast_tracepoint)
10655 {
10656 /* Only test for support at download time; we may not know
10657 target capabilities at definition time. */
10658 if (remote_supports_fast_tracepoints ())
35b1e5cc 10659 {
e8ba3115 10660 int isize;
35b1e5cc 10661
f5656ead 10662 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
e8ba3115 10663 tpaddr, &isize, NULL))
bba74b36
YQ
10664 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10665 isize);
35b1e5cc 10666 else
e8ba3115
YQ
10667 /* If it passed validation at definition but fails now,
10668 something is very wrong. */
10669 internal_error (__FILE__, __LINE__,
10670 _("Fast tracepoint not "
10671 "valid during download"));
35b1e5cc 10672 }
e8ba3115
YQ
10673 else
10674 /* Fast tracepoints are functionally identical to regular
10675 tracepoints, so don't take lack of support as a reason to
10676 give up on the trace run. */
10677 warning (_("Target does not support fast tracepoints, "
10678 "downloading %d as regular tracepoint"), b->number);
10679 }
10680 else if (b->type == bp_static_tracepoint)
10681 {
10682 /* Only test for support at download time; we may not know
10683 target capabilities at definition time. */
10684 if (remote_supports_static_tracepoints ())
0fb4aa4b 10685 {
e8ba3115 10686 struct static_tracepoint_marker marker;
0fb4aa4b 10687
e8ba3115
YQ
10688 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10689 strcat (buf, ":S");
0fb4aa4b 10690 else
e8ba3115 10691 error (_("Static tracepoint not valid during download"));
0fb4aa4b 10692 }
e8ba3115
YQ
10693 else
10694 /* Fast tracepoints are functionally identical to regular
10695 tracepoints, so don't take lack of support as a reason
10696 to give up on the trace run. */
10697 error (_("Target does not support static tracepoints"));
10698 }
10699 /* If the tracepoint has a conditional, make it into an agent
10700 expression and append to the definition. */
10701 if (loc->cond)
10702 {
10703 /* Only test support at download time, we may not know target
10704 capabilities at definition time. */
10705 if (remote_supports_cond_tracepoints ())
35b1e5cc 10706 {
e8ba3115
YQ
10707 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10708 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
10709 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10710 aexpr->len);
e8ba3115
YQ
10711 pkt = buf + strlen (buf);
10712 for (ndx = 0; ndx < aexpr->len; ++ndx)
10713 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10714 *pkt = '\0';
10715 do_cleanups (aexpr_chain);
35b1e5cc 10716 }
e8ba3115
YQ
10717 else
10718 warning (_("Target does not support conditional tracepoints, "
10719 "ignoring tp %d cond"), b->number);
10720 }
35b1e5cc 10721
d9b3f62e 10722 if (b->commands || *default_collect)
e8ba3115
YQ
10723 strcat (buf, "-");
10724 putpkt (buf);
10725 remote_get_noisy_reply (&target_buf, &target_buf_size);
10726 if (strcmp (target_buf, "OK"))
10727 error (_("Target does not support tracepoints."));
35b1e5cc 10728
e8ba3115
YQ
10729 /* do_single_steps (t); */
10730 if (tdp_actions)
10731 {
10732 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 10733 {
e8ba3115 10734 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
10735 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10736 b->number, addrbuf, /* address */
10737 tdp_actions[ndx],
10738 ((tdp_actions[ndx + 1] || stepping_actions)
10739 ? '-' : 0));
e8ba3115
YQ
10740 putpkt (buf);
10741 remote_get_noisy_reply (&target_buf,
10742 &target_buf_size);
10743 if (strcmp (target_buf, "OK"))
10744 error (_("Error on target while setting tracepoints."));
35b1e5cc 10745 }
e8ba3115
YQ
10746 }
10747 if (stepping_actions)
10748 {
10749 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 10750 {
e8ba3115 10751 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
10752 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10753 b->number, addrbuf, /* address */
10754 ((ndx == 0) ? "S" : ""),
10755 stepping_actions[ndx],
10756 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
10757 putpkt (buf);
10758 remote_get_noisy_reply (&target_buf,
10759 &target_buf_size);
10760 if (strcmp (target_buf, "OK"))
10761 error (_("Error on target while setting tracepoints."));
35b1e5cc 10762 }
e8ba3115 10763 }
409873ef 10764
4082afcc 10765 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115
YQ
10766 {
10767 if (b->addr_string)
409873ef 10768 {
e8ba3115
YQ
10769 strcpy (buf, "QTDPsrc:");
10770 encode_source_string (b->number, loc->address,
10771 "at", b->addr_string, buf + strlen (buf),
10772 2048 - strlen (buf));
409873ef 10773
e8ba3115
YQ
10774 putpkt (buf);
10775 remote_get_noisy_reply (&target_buf, &target_buf_size);
10776 if (strcmp (target_buf, "OK"))
10777 warning (_("Target does not support source download."));
409873ef 10778 }
e8ba3115
YQ
10779 if (b->cond_string)
10780 {
10781 strcpy (buf, "QTDPsrc:");
10782 encode_source_string (b->number, loc->address,
10783 "cond", b->cond_string, buf + strlen (buf),
10784 2048 - strlen (buf));
10785 putpkt (buf);
10786 remote_get_noisy_reply (&target_buf, &target_buf_size);
10787 if (strcmp (target_buf, "OK"))
10788 warning (_("Target does not support source download."));
10789 }
10790 remote_download_command_source (b->number, loc->address,
10791 breakpoint_commands (b));
35b1e5cc 10792 }
e8ba3115
YQ
10793
10794 do_cleanups (old_chain);
35b1e5cc
SS
10795}
10796
1e4d1764 10797static int
a52a8357 10798remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 10799{
1e51243a
PA
10800 struct remote_state *rs = get_remote_state ();
10801 struct trace_status *ts;
10802 int status;
10803
10804 /* Don't try to install tracepoints until we've relocated our
10805 symbols, and fetched and merged the target's tracepoint list with
10806 ours. */
10807 if (rs->starting_up)
10808 return 0;
10809
10810 ts = current_trace_status ();
8bd200f1 10811 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
10812
10813 if (status == -1 || !ts->running_known || !ts->running)
10814 return 0;
10815
10816 /* If we are in a tracing experiment, but remote stub doesn't support
10817 installing tracepoint in trace, we have to return. */
10818 if (!remote_supports_install_in_trace ())
10819 return 0;
10820
10821 return 1;
10822}
10823
10824
35b1e5cc 10825static void
559d2b81
TT
10826remote_download_trace_state_variable (struct target_ops *self,
10827 struct trace_state_variable *tsv)
35b1e5cc
SS
10828{
10829 struct remote_state *rs = get_remote_state ();
00bf0b85 10830 char *p;
35b1e5cc 10831
bba74b36
YQ
10832 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10833 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10834 tsv->builtin);
00bf0b85
SS
10835 p = rs->buf + strlen (rs->buf);
10836 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10837 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 10838 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 10839 *p++ = '\0';
35b1e5cc
SS
10840 putpkt (rs->buf);
10841 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
10842 if (*target_buf == '\0')
10843 error (_("Target does not support this command."));
10844 if (strcmp (target_buf, "OK") != 0)
10845 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
10846}
10847
d248b706 10848static void
46670d57
TT
10849remote_enable_tracepoint (struct target_ops *self,
10850 struct bp_location *location)
d248b706
KY
10851{
10852 struct remote_state *rs = get_remote_state ();
10853 char addr_buf[40];
10854
10855 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
10856 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10857 location->owner->number, addr_buf);
d248b706
KY
10858 putpkt (rs->buf);
10859 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10860 if (*rs->buf == '\0')
10861 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10862 if (strcmp (rs->buf, "OK") != 0)
10863 error (_("Error on target while enabling tracepoint."));
10864}
10865
10866static void
780b049c
TT
10867remote_disable_tracepoint (struct target_ops *self,
10868 struct bp_location *location)
d248b706
KY
10869{
10870 struct remote_state *rs = get_remote_state ();
10871 char addr_buf[40];
10872
10873 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
10874 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10875 location->owner->number, addr_buf);
d248b706
KY
10876 putpkt (rs->buf);
10877 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10878 if (*rs->buf == '\0')
10879 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10880 if (strcmp (rs->buf, "OK") != 0)
10881 error (_("Error on target while disabling tracepoint."));
10882}
10883
35b1e5cc 10884static void
583f9a86 10885remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
10886{
10887 asection *s;
81b9b86e 10888 bfd *abfd = NULL;
35b1e5cc 10889 bfd_size_type size;
608bcef2 10890 bfd_vma vma;
35b1e5cc 10891 int anysecs = 0;
c2fa21f1 10892 int offset = 0;
35b1e5cc
SS
10893
10894 if (!exec_bfd)
10895 return; /* No information to give. */
10896
10897 strcpy (target_buf, "QTro");
9779ab84 10898 offset = strlen (target_buf);
35b1e5cc
SS
10899 for (s = exec_bfd->sections; s; s = s->next)
10900 {
10901 char tmp1[40], tmp2[40];
c2fa21f1 10902 int sec_length;
35b1e5cc
SS
10903
10904 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 10905 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
10906 (s->flags & SEC_READONLY) == 0)
10907 continue;
10908
10909 anysecs = 1;
81b9b86e 10910 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 10911 size = bfd_get_section_size (s);
608bcef2
HZ
10912 sprintf_vma (tmp1, vma);
10913 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
10914 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10915 if (offset + sec_length + 1 > target_buf_size)
10916 {
4082afcc 10917 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 10918 warning (_("\
c2fa21f1
HZ
10919Too many sections for read-only sections definition packet."));
10920 break;
10921 }
bba74b36
YQ
10922 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10923 tmp1, tmp2);
c2fa21f1 10924 offset += sec_length;
35b1e5cc
SS
10925 }
10926 if (anysecs)
10927 {
10928 putpkt (target_buf);
10929 getpkt (&target_buf, &target_buf_size, 0);
10930 }
10931}
10932
10933static void
e2d1aae3 10934remote_trace_start (struct target_ops *self)
35b1e5cc
SS
10935{
10936 putpkt ("QTStart");
10937 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
10938 if (*target_buf == '\0')
10939 error (_("Target does not support this command."));
10940 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
10941 error (_("Bogus reply from target: %s"), target_buf);
10942}
10943
10944static int
8bd200f1 10945remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 10946{
953b98d1 10947 /* Initialize it just to avoid a GCC false warning. */
f652de6f 10948 char *p = NULL;
0df8b418 10949 /* FIXME we need to get register block size some other way. */
00bf0b85 10950 extern int trace_regblock_size;
67f41397 10951 volatile struct gdb_exception ex;
bd3eecc3
PA
10952 enum packet_result result;
10953
4082afcc 10954 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 10955 return -1;
a744cf53 10956
00bf0b85
SS
10957 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10958
049dc89b
JK
10959 putpkt ("qTStatus");
10960
67f41397
JK
10961 TRY_CATCH (ex, RETURN_MASK_ERROR)
10962 {
10963 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10964 }
10965 if (ex.reason < 0)
10966 {
598d3636
JK
10967 if (ex.error != TARGET_CLOSE_ERROR)
10968 {
10969 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10970 return -1;
10971 }
10972 throw_exception (ex);
67f41397 10973 }
00bf0b85 10974
bd3eecc3
PA
10975 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
10976
00bf0b85 10977 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 10978 if (result == PACKET_UNKNOWN)
00bf0b85 10979 return -1;
35b1e5cc 10980
00bf0b85 10981 /* We're working with a live target. */
f5911ea1 10982 ts->filename = NULL;
00bf0b85 10983
00bf0b85 10984 if (*p++ != 'T')
35b1e5cc
SS
10985 error (_("Bogus trace status reply from target: %s"), target_buf);
10986
84cebc4a
YQ
10987 /* Function 'parse_trace_status' sets default value of each field of
10988 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
10989 parse_trace_status (p, ts);
10990
10991 return ts->running;
35b1e5cc
SS
10992}
10993
70221824 10994static void
db90e85c 10995remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
10996 struct uploaded_tp *utp)
10997{
10998 struct remote_state *rs = get_remote_state ();
f196051f
SS
10999 char *reply;
11000 struct bp_location *loc;
11001 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 11002 size_t size = get_remote_packet_size ();
f196051f
SS
11003
11004 if (tp)
11005 {
11006 tp->base.hit_count = 0;
11007 tp->traceframe_usage = 0;
11008 for (loc = tp->base.loc; loc; loc = loc->next)
11009 {
11010 /* If the tracepoint was never downloaded, don't go asking for
11011 any status. */
11012 if (tp->number_on_target == 0)
11013 continue;
bba74b36
YQ
11014 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
11015 phex_nz (loc->address, 0));
f196051f
SS
11016 putpkt (rs->buf);
11017 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11018 if (reply && *reply)
11019 {
11020 if (*reply == 'V')
11021 parse_tracepoint_status (reply + 1, bp, utp);
11022 }
11023 }
11024 }
11025 else if (utp)
11026 {
11027 utp->hit_count = 0;
11028 utp->traceframe_usage = 0;
bba74b36
YQ
11029 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
11030 phex_nz (utp->addr, 0));
f196051f
SS
11031 putpkt (rs->buf);
11032 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11033 if (reply && *reply)
11034 {
11035 if (*reply == 'V')
11036 parse_tracepoint_status (reply + 1, bp, utp);
11037 }
11038 }
11039}
11040
35b1e5cc 11041static void
74499f1b 11042remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
11043{
11044 putpkt ("QTStop");
11045 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11046 if (*target_buf == '\0')
11047 error (_("Target does not support this command."));
11048 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11049 error (_("Bogus reply from target: %s"), target_buf);
11050}
11051
11052static int
bd4c6793
TT
11053remote_trace_find (struct target_ops *self,
11054 enum trace_find_type type, int num,
cc5925ad 11055 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
11056 int *tpp)
11057{
11058 struct remote_state *rs = get_remote_state ();
bba74b36 11059 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
11060 char *p, *reply;
11061 int target_frameno = -1, target_tracept = -1;
11062
e6e4e701
PA
11063 /* Lookups other than by absolute frame number depend on the current
11064 trace selected, so make sure it is correct on the remote end
11065 first. */
11066 if (type != tfind_number)
11067 set_remote_traceframe ();
11068
35b1e5cc
SS
11069 p = rs->buf;
11070 strcpy (p, "QTFrame:");
11071 p = strchr (p, '\0');
11072 switch (type)
11073 {
11074 case tfind_number:
bba74b36 11075 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
11076 break;
11077 case tfind_pc:
bba74b36 11078 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
11079 break;
11080 case tfind_tp:
bba74b36 11081 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
11082 break;
11083 case tfind_range:
bba74b36
YQ
11084 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11085 phex_nz (addr2, 0));
35b1e5cc
SS
11086 break;
11087 case tfind_outside:
bba74b36
YQ
11088 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11089 phex_nz (addr2, 0));
35b1e5cc
SS
11090 break;
11091 default:
9b20d036 11092 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
11093 }
11094
11095 putpkt (rs->buf);
2f65bcb7 11096 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
11097 if (*reply == '\0')
11098 error (_("Target does not support this command."));
35b1e5cc
SS
11099
11100 while (reply && *reply)
11101 switch (*reply)
11102 {
11103 case 'F':
f197e0f1
VP
11104 p = ++reply;
11105 target_frameno = (int) strtol (p, &reply, 16);
11106 if (reply == p)
11107 error (_("Unable to parse trace frame number"));
e6e4e701
PA
11108 /* Don't update our remote traceframe number cache on failure
11109 to select a remote traceframe. */
f197e0f1
VP
11110 if (target_frameno == -1)
11111 return -1;
35b1e5cc
SS
11112 break;
11113 case 'T':
f197e0f1
VP
11114 p = ++reply;
11115 target_tracept = (int) strtol (p, &reply, 16);
11116 if (reply == p)
11117 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
11118 break;
11119 case 'O': /* "OK"? */
11120 if (reply[1] == 'K' && reply[2] == '\0')
11121 reply += 2;
11122 else
11123 error (_("Bogus reply from target: %s"), reply);
11124 break;
11125 default:
11126 error (_("Bogus reply from target: %s"), reply);
11127 }
11128 if (tpp)
11129 *tpp = target_tracept;
e6e4e701 11130
262e1174 11131 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
11132 return target_frameno;
11133}
11134
11135static int
4011015b
TT
11136remote_get_trace_state_variable_value (struct target_ops *self,
11137 int tsvnum, LONGEST *val)
35b1e5cc
SS
11138{
11139 struct remote_state *rs = get_remote_state ();
11140 char *reply;
11141 ULONGEST uval;
11142
e6e4e701
PA
11143 set_remote_traceframe ();
11144
bba74b36 11145 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
11146 putpkt (rs->buf);
11147 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11148 if (reply && *reply)
11149 {
11150 if (*reply == 'V')
11151 {
11152 unpack_varlen_hex (reply + 1, &uval);
11153 *val = (LONGEST) uval;
11154 return 1;
11155 }
11156 }
11157 return 0;
11158}
11159
00bf0b85 11160static int
dc3decaf 11161remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
11162{
11163 struct remote_state *rs = get_remote_state ();
11164 char *p, *reply;
11165
11166 p = rs->buf;
11167 strcpy (p, "QTSave:");
11168 p += strlen (p);
11169 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11170 error (_("Remote file name too long for trace save packet"));
9f1b45b0 11171 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
11172 *p++ = '\0';
11173 putpkt (rs->buf);
ad91cd99 11174 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 11175 if (*reply == '\0')
ad91cd99
PA
11176 error (_("Target does not support this command."));
11177 if (strcmp (reply, "OK") != 0)
11178 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
11179 return 0;
11180}
11181
11182/* This is basically a memory transfer, but needs to be its own packet
11183 because we don't know how the target actually organizes its trace
11184 memory, plus we want to be able to ask for as much as possible, but
11185 not be unhappy if we don't get as much as we ask for. */
11186
11187static LONGEST
88ee6f45
TT
11188remote_get_raw_trace_data (struct target_ops *self,
11189 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
11190{
11191 struct remote_state *rs = get_remote_state ();
11192 char *reply;
11193 char *p;
11194 int rslt;
11195
11196 p = rs->buf;
11197 strcpy (p, "qTBuffer:");
11198 p += strlen (p);
11199 p += hexnumstr (p, offset);
11200 *p++ = ',';
11201 p += hexnumstr (p, len);
11202 *p++ = '\0';
11203
11204 putpkt (rs->buf);
11205 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11206 if (reply && *reply)
11207 {
11208 /* 'l' by itself means we're at the end of the buffer and
11209 there is nothing more to get. */
11210 if (*reply == 'l')
11211 return 0;
11212
11213 /* Convert the reply into binary. Limit the number of bytes to
11214 convert according to our passed-in buffer size, rather than
11215 what was returned in the packet; if the target is
11216 unexpectedly generous and gives us a bigger reply than we
11217 asked for, we don't want to crash. */
11218 rslt = hex2bin (target_buf, buf, len);
11219 return rslt;
11220 }
11221
11222 /* Something went wrong, flag as an error. */
11223 return -1;
11224}
11225
35b1e5cc 11226static void
37b25738 11227remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
11228{
11229 struct remote_state *rs = get_remote_state ();
11230
4082afcc 11231 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 11232 {
ad91cd99
PA
11233 char *reply;
11234
bba74b36 11235 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 11236 putpkt (rs->buf);
ad91cd99
PA
11237 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11238 if (*reply == '\0')
33da3f1c 11239 error (_("Target does not support this command."));
ad91cd99
PA
11240 if (strcmp (reply, "OK") != 0)
11241 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
11242 }
11243 else if (val)
11244 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
11245}
11246
dc146f7c
VP
11247static int
11248remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11249{
11250 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 11251
fe978cb0
PA
11252 if (info && info->priv)
11253 return info->priv->core;
dc146f7c
VP
11254 return -1;
11255}
11256
4daf5ac0 11257static void
736d5b1f 11258remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
11259{
11260 struct remote_state *rs = get_remote_state ();
ad91cd99 11261 char *reply;
4daf5ac0 11262
bba74b36 11263 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 11264 putpkt (rs->buf);
ad91cd99
PA
11265 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11266 if (*reply == '\0')
4daf5ac0 11267 error (_("Target does not support this command."));
ad91cd99
PA
11268 if (strcmp (reply, "OK") != 0)
11269 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
11270}
11271
b3b9301e 11272static struct traceframe_info *
a893e81f 11273remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
11274{
11275 char *text;
11276
11277 text = target_read_stralloc (&current_target,
11278 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11279 if (text != NULL)
11280 {
11281 struct traceframe_info *info;
11282 struct cleanup *back_to = make_cleanup (xfree, text);
11283
11284 info = parse_traceframe_info (text);
11285 do_cleanups (back_to);
11286 return info;
11287 }
11288
11289 return NULL;
11290}
11291
405f8e94
SS
11292/* Handle the qTMinFTPILen packet. Returns the minimum length of
11293 instruction on which a fast tracepoint may be placed. Returns -1
11294 if the packet is not supported, and 0 if the minimum instruction
11295 length is unknown. */
11296
11297static int
0e67620a 11298remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
11299{
11300 struct remote_state *rs = get_remote_state ();
11301 char *reply;
11302
e886a173
PA
11303 /* If we're not debugging a process yet, the IPA can't be
11304 loaded. */
11305 if (!target_has_execution)
11306 return 0;
11307
11308 /* Make sure the remote is pointing at the right process. */
11309 set_general_process ();
11310
bba74b36 11311 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
11312 putpkt (rs->buf);
11313 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11314 if (*reply == '\0')
11315 return -1;
11316 else
11317 {
11318 ULONGEST min_insn_len;
11319
11320 unpack_varlen_hex (reply, &min_insn_len);
11321
11322 return (int) min_insn_len;
11323 }
11324}
11325
f6f899bf 11326static void
4da384be 11327remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 11328{
4082afcc 11329 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
11330 {
11331 struct remote_state *rs = get_remote_state ();
11332 char *buf = rs->buf;
11333 char *endbuf = rs->buf + get_remote_packet_size ();
11334 enum packet_result result;
11335
11336 gdb_assert (val >= 0 || val == -1);
11337 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11338 /* Send -1 as literal "-1" to avoid host size dependency. */
11339 if (val < 0)
11340 {
11341 *buf++ = '-';
11342 buf += hexnumstr (buf, (ULONGEST) -val);
11343 }
11344 else
11345 buf += hexnumstr (buf, (ULONGEST) val);
11346
11347 putpkt (rs->buf);
11348 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11349 result = packet_ok (rs->buf,
11350 &remote_protocol_packets[PACKET_QTBuffer_size]);
11351
11352 if (result != PACKET_OK)
11353 warning (_("Bogus reply from target: %s"), rs->buf);
11354 }
11355}
11356
f196051f 11357static int
d9e68a2c
TT
11358remote_set_trace_notes (struct target_ops *self,
11359 const char *user, const char *notes,
ca623f82 11360 const char *stop_notes)
f196051f
SS
11361{
11362 struct remote_state *rs = get_remote_state ();
11363 char *reply;
11364 char *buf = rs->buf;
11365 char *endbuf = rs->buf + get_remote_packet_size ();
11366 int nbytes;
11367
11368 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11369 if (user)
11370 {
11371 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 11372 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
11373 buf += 2 * nbytes;
11374 *buf++ = ';';
11375 }
11376 if (notes)
11377 {
11378 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 11379 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
11380 buf += 2 * nbytes;
11381 *buf++ = ';';
11382 }
11383 if (stop_notes)
11384 {
11385 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 11386 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
11387 buf += 2 * nbytes;
11388 *buf++ = ';';
11389 }
11390 /* Ensure the buffer is terminated. */
11391 *buf = '\0';
11392
11393 putpkt (rs->buf);
11394 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11395 if (*reply == '\0')
11396 return 0;
11397
11398 if (strcmp (reply, "OK") != 0)
11399 error (_("Bogus reply from target: %s"), reply);
11400
11401 return 1;
11402}
11403
d1feda86 11404static int
2c152180 11405remote_use_agent (struct target_ops *self, int use)
d1feda86 11406{
4082afcc 11407 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
11408 {
11409 struct remote_state *rs = get_remote_state ();
11410
11411 /* If the stub supports QAgent. */
bba74b36 11412 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
11413 putpkt (rs->buf);
11414 getpkt (&rs->buf, &rs->buf_size, 0);
11415
11416 if (strcmp (rs->buf, "OK") == 0)
11417 {
11418 use_agent = use;
11419 return 1;
11420 }
11421 }
11422
11423 return 0;
11424}
11425
11426static int
fe38f897 11427remote_can_use_agent (struct target_ops *self)
d1feda86 11428{
4082afcc 11429 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
11430}
11431
9accd112
MM
11432struct btrace_target_info
11433{
11434 /* The ptid of the traced thread. */
11435 ptid_t ptid;
f4abbc16
MM
11436
11437 /* The obtained branch trace configuration. */
11438 struct btrace_config conf;
9accd112
MM
11439};
11440
f4abbc16
MM
11441/* Reset our idea of our target's btrace configuration. */
11442
11443static void
11444remote_btrace_reset (void)
11445{
11446 struct remote_state *rs = get_remote_state ();
11447
11448 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
11449}
11450
9accd112
MM
11451/* Check whether the target supports branch tracing. */
11452
11453static int
043c3577 11454remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 11455{
4082afcc 11456 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 11457 return 0;
4082afcc 11458 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
11459 return 0;
11460
043c3577
MM
11461 switch (format)
11462 {
11463 case BTRACE_FORMAT_NONE:
11464 return 0;
11465
11466 case BTRACE_FORMAT_BTS:
11467 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
11468 }
11469
11470 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
11471}
11472
f4abbc16
MM
11473/* Synchronize the configuration with the target. */
11474
11475static void
11476btrace_sync_conf (const struct btrace_config *conf)
11477{
d33501a5
MM
11478 struct packet_config *packet;
11479 struct remote_state *rs;
11480 char *buf, *pos, *endbuf;
11481
11482 rs = get_remote_state ();
11483 buf = rs->buf;
11484 endbuf = buf + get_remote_packet_size ();
11485
11486 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
11487 if (packet_config_support (packet) == PACKET_ENABLE
11488 && conf->bts.size != rs->btrace_config.bts.size)
11489 {
11490 pos = buf;
11491 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
11492 conf->bts.size);
11493
11494 putpkt (buf);
11495 getpkt (&buf, &rs->buf_size, 0);
11496
11497 if (packet_ok (buf, packet) == PACKET_ERROR)
11498 {
11499 if (buf[0] == 'E' && buf[1] == '.')
11500 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
11501 else
11502 error (_("Failed to configure the BTS buffer size."));
11503 }
11504
11505 rs->btrace_config.bts.size = conf->bts.size;
11506 }
f4abbc16
MM
11507}
11508
11509/* Read the current thread's btrace configuration from the target and
11510 store it into CONF. */
11511
11512static void
11513btrace_read_config (struct btrace_config *conf)
11514{
11515 char *xml;
11516
11517 xml = target_read_stralloc (&current_target,
11518 TARGET_OBJECT_BTRACE_CONF, "");
11519 if (xml != NULL)
11520 {
11521 struct cleanup *cleanup;
11522
11523 cleanup = make_cleanup (xfree, xml);
11524 parse_xml_btrace_conf (conf, xml);
11525 do_cleanups (cleanup);
11526 }
11527}
11528
9accd112
MM
11529/* Enable branch tracing. */
11530
11531static struct btrace_target_info *
f4abbc16
MM
11532remote_enable_btrace (struct target_ops *self, ptid_t ptid,
11533 const struct btrace_config *conf)
9accd112
MM
11534{
11535 struct btrace_target_info *tinfo = NULL;
11536 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11537 struct remote_state *rs = get_remote_state ();
11538 char *buf = rs->buf;
11539 char *endbuf = rs->buf + get_remote_packet_size ();
f4abbc16 11540 volatile struct gdb_exception err;
9accd112 11541
4082afcc 11542 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
11543 error (_("Target does not support branch tracing."));
11544
f4abbc16
MM
11545 btrace_sync_conf (conf);
11546
9accd112
MM
11547 set_general_thread (ptid);
11548
11549 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11550 putpkt (rs->buf);
11551 getpkt (&rs->buf, &rs->buf_size, 0);
11552
11553 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11554 {
11555 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11556 error (_("Could not enable branch tracing for %s: %s"),
11557 target_pid_to_str (ptid), rs->buf + 2);
11558 else
11559 error (_("Could not enable branch tracing for %s."),
11560 target_pid_to_str (ptid));
11561 }
11562
11563 tinfo = xzalloc (sizeof (*tinfo));
11564 tinfo->ptid = ptid;
11565
f4abbc16
MM
11566 /* If we fail to read the configuration, we lose some information, but the
11567 tracing itself is not impacted. */
11568 TRY_CATCH (err, RETURN_MASK_ERROR)
11569 btrace_read_config (&tinfo->conf);
11570
11571 if (err.message != NULL)
11572 warning ("%s", err.message);
11573
9accd112
MM
11574 return tinfo;
11575}
11576
11577/* Disable branch tracing. */
11578
11579static void
25e95349
TT
11580remote_disable_btrace (struct target_ops *self,
11581 struct btrace_target_info *tinfo)
9accd112
MM
11582{
11583 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11584 struct remote_state *rs = get_remote_state ();
11585 char *buf = rs->buf;
11586 char *endbuf = rs->buf + get_remote_packet_size ();
11587
4082afcc 11588 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
11589 error (_("Target does not support branch tracing."));
11590
11591 set_general_thread (tinfo->ptid);
11592
11593 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11594 putpkt (rs->buf);
11595 getpkt (&rs->buf, &rs->buf_size, 0);
11596
11597 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11598 {
11599 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11600 error (_("Could not disable branch tracing for %s: %s"),
11601 target_pid_to_str (tinfo->ptid), rs->buf + 2);
11602 else
11603 error (_("Could not disable branch tracing for %s."),
11604 target_pid_to_str (tinfo->ptid));
11605 }
11606
11607 xfree (tinfo);
11608}
11609
11610/* Teardown branch tracing. */
11611
11612static void
1777056d
TT
11613remote_teardown_btrace (struct target_ops *self,
11614 struct btrace_target_info *tinfo)
9accd112
MM
11615{
11616 /* We must not talk to the target during teardown. */
11617 xfree (tinfo);
11618}
11619
11620/* Read the branch trace. */
11621
969c39fb 11622static enum btrace_error
39c49f83 11623remote_read_btrace (struct target_ops *self,
734b0e4b 11624 struct btrace_data *btrace,
969c39fb 11625 struct btrace_target_info *tinfo,
9accd112
MM
11626 enum btrace_read_type type)
11627{
11628 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11629 struct remote_state *rs = get_remote_state ();
969c39fb 11630 struct cleanup *cleanup;
9accd112
MM
11631 const char *annex;
11632 char *xml;
11633
4082afcc 11634 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
11635 error (_("Target does not support branch tracing."));
11636
11637#if !defined(HAVE_LIBEXPAT)
11638 error (_("Cannot process branch tracing result. XML parsing not supported."));
11639#endif
11640
11641 switch (type)
11642 {
864089d2 11643 case BTRACE_READ_ALL:
9accd112
MM
11644 annex = "all";
11645 break;
864089d2 11646 case BTRACE_READ_NEW:
9accd112
MM
11647 annex = "new";
11648 break;
969c39fb
MM
11649 case BTRACE_READ_DELTA:
11650 annex = "delta";
11651 break;
9accd112
MM
11652 default:
11653 internal_error (__FILE__, __LINE__,
11654 _("Bad branch tracing read type: %u."),
11655 (unsigned int) type);
11656 }
11657
11658 xml = target_read_stralloc (&current_target,
11659 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
11660 if (xml == NULL)
11661 return BTRACE_ERR_UNKNOWN;
9accd112 11662
969c39fb 11663 cleanup = make_cleanup (xfree, xml);
734b0e4b 11664 parse_xml_btrace (btrace, xml);
969c39fb 11665 do_cleanups (cleanup);
9accd112 11666
969c39fb 11667 return BTRACE_ERR_NONE;
9accd112
MM
11668}
11669
f4abbc16
MM
11670static const struct btrace_config *
11671remote_btrace_conf (struct target_ops *self,
11672 const struct btrace_target_info *tinfo)
11673{
11674 return &tinfo->conf;
11675}
11676
ced63ec0 11677static int
5436ff03 11678remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 11679{
4082afcc
PA
11680 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
11681 == PACKET_ENABLE);
ced63ec0
GB
11682}
11683
9dd130a0
TT
11684/* Implementation of to_load. */
11685
11686static void
9cbe5fff 11687remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
11688{
11689 generic_load (name, from_tty);
11690}
11691
c906108c 11692static void
fba45db2 11693init_remote_ops (void)
c906108c 11694{
c5aa993b 11695 remote_ops.to_shortname = "remote";
c906108c 11696 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 11697 remote_ops.to_doc =
c906108c 11698 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
11699Specify the serial device it is connected to\n\
11700(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
11701 remote_ops.to_open = remote_open;
11702 remote_ops.to_close = remote_close;
c906108c 11703 remote_ops.to_detach = remote_detach;
6ad8ae5c 11704 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 11705 remote_ops.to_resume = remote_resume;
c906108c
SS
11706 remote_ops.to_wait = remote_wait;
11707 remote_ops.to_fetch_registers = remote_fetch_registers;
11708 remote_ops.to_store_registers = remote_store_registers;
11709 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 11710 remote_ops.to_files_info = remote_files_info;
c906108c
SS
11711 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11712 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
11713 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
11714 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
11715 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
11716 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
11717 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11718 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
11719 remote_ops.to_watchpoint_addr_within_range =
11720 remote_watchpoint_addr_within_range;
3c3bea1c
GS
11721 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11722 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11723 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
11724 remote_ops.to_region_ok_for_hw_watchpoint
11725 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
11726 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11727 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 11728 remote_ops.to_kill = remote_kill;
9dd130a0 11729 remote_ops.to_load = remote_load;
c906108c 11730 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 11731 remote_ops.to_pass_signals = remote_pass_signals;
9b224c5e 11732 remote_ops.to_program_signals = remote_program_signals;
c906108c 11733 remote_ops.to_thread_alive = remote_thread_alive;
e8032dde 11734 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 11735 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 11736 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 11737 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 11738 remote_ops.to_stop = remote_stop;
4b8a223f 11739 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 11740 remote_ops.to_rcmd = remote_rcmd;
49d03eab 11741 remote_ops.to_log_command = serial_log_command;
38691318 11742 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 11743 remote_ops.to_stratum = process_stratum;
c35b1492
PA
11744 remote_ops.to_has_all_memory = default_child_has_all_memory;
11745 remote_ops.to_has_memory = default_child_has_memory;
11746 remote_ops.to_has_stack = default_child_has_stack;
11747 remote_ops.to_has_registers = default_child_has_registers;
11748 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 11749 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 11750 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 11751 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 11752 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
11753 remote_ops.to_flash_erase = remote_flash_erase;
11754 remote_ops.to_flash_done = remote_flash_done;
29709017 11755 remote_ops.to_read_description = remote_read_description;
08388c79 11756 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
11757 remote_ops.to_can_async_p = remote_can_async_p;
11758 remote_ops.to_is_async_p = remote_is_async_p;
11759 remote_ops.to_async = remote_async;
75c99385
PA
11760 remote_ops.to_terminal_inferior = remote_terminal_inferior;
11761 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 11762 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 11763 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
11764 remote_ops.to_supports_disable_randomization
11765 = remote_supports_disable_randomization;
7313baad
UW
11766 remote_ops.to_fileio_open = remote_hostio_open;
11767 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11768 remote_ops.to_fileio_pread = remote_hostio_pread;
11769 remote_ops.to_fileio_close = remote_hostio_close;
11770 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 11771 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 11772 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 11773 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 11774 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 11775 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
11776 remote_ops.to_trace_init = remote_trace_init;
11777 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 11778 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
11779 remote_ops.to_download_trace_state_variable
11780 = remote_download_trace_state_variable;
d248b706
KY
11781 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11782 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
11783 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11784 remote_ops.to_trace_start = remote_trace_start;
11785 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 11786 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
11787 remote_ops.to_trace_stop = remote_trace_stop;
11788 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
11789 remote_ops.to_get_trace_state_variable_value
11790 = remote_get_trace_state_variable_value;
00bf0b85
SS
11791 remote_ops.to_save_trace_data = remote_save_trace_data;
11792 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
11793 remote_ops.to_upload_trace_state_variables
11794 = remote_upload_trace_state_variables;
00bf0b85 11795 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 11796 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 11797 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 11798 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 11799 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 11800 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 11801 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 11802 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 11803 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 11804 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
11805 remote_ops.to_static_tracepoint_marker_at
11806 = remote_static_tracepoint_marker_at;
11807 remote_ops.to_static_tracepoint_markers_by_strid
11808 = remote_static_tracepoint_markers_by_strid;
b3b9301e 11809 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
11810 remote_ops.to_use_agent = remote_use_agent;
11811 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
11812 remote_ops.to_supports_btrace = remote_supports_btrace;
11813 remote_ops.to_enable_btrace = remote_enable_btrace;
11814 remote_ops.to_disable_btrace = remote_disable_btrace;
11815 remote_ops.to_teardown_btrace = remote_teardown_btrace;
11816 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 11817 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
11818 remote_ops.to_augmented_libraries_svr4_read =
11819 remote_augmented_libraries_svr4_read;
c906108c
SS
11820}
11821
11822/* Set up the extended remote vector by making a copy of the standard
11823 remote vector and adding to it. */
11824
11825static void
fba45db2 11826init_extended_remote_ops (void)
c906108c
SS
11827{
11828 extended_remote_ops = remote_ops;
11829
0f71a2f6 11830 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 11831 extended_remote_ops.to_longname =
c906108c 11832 "Extended remote serial target in gdb-specific protocol";
c5aa993b 11833 extended_remote_ops.to_doc =
c906108c 11834 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
11835Specify the serial device it is connected to (e.g. /dev/ttya).";
11836 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
11837 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11838 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
11839 extended_remote_ops.to_detach = extended_remote_detach;
11840 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 11841 extended_remote_ops.to_post_attach = extended_remote_post_attach;
82f73884 11842 extended_remote_ops.to_kill = extended_remote_kill;
03583c20
UW
11843 extended_remote_ops.to_supports_disable_randomization
11844 = extended_remote_supports_disable_randomization;
0f71a2f6
JM
11845}
11846
6426a772 11847static int
6a109b6b 11848remote_can_async_p (struct target_ops *ops)
6426a772 11849{
5d93a237
TT
11850 struct remote_state *rs = get_remote_state ();
11851
c6ebd6cf 11852 if (!target_async_permitted)
75c99385
PA
11853 /* We only enable async when the user specifically asks for it. */
11854 return 0;
11855
23860348 11856 /* We're async whenever the serial device is. */
5d93a237 11857 return serial_can_async_p (rs->remote_desc);
6426a772
JM
11858}
11859
11860static int
6a109b6b 11861remote_is_async_p (struct target_ops *ops)
6426a772 11862{
5d93a237
TT
11863 struct remote_state *rs = get_remote_state ();
11864
c6ebd6cf 11865 if (!target_async_permitted)
75c99385
PA
11866 /* We only enable async when the user specifically asks for it. */
11867 return 0;
11868
23860348 11869 /* We're async whenever the serial device is. */
5d93a237 11870 return serial_is_async_p (rs->remote_desc);
6426a772
JM
11871}
11872
2acceee2
JM
11873/* Pass the SERIAL event on and up to the client. One day this code
11874 will be able to delay notifying the client of an event until the
23860348 11875 point where an entire packet has been received. */
2acceee2 11876
2acceee2
JM
11877static serial_event_ftype remote_async_serial_handler;
11878
6426a772 11879static void
819cc324 11880remote_async_serial_handler (struct serial *scb, void *context)
6426a772 11881{
88b496c3
TT
11882 struct remote_state *rs = context;
11883
2acceee2
JM
11884 /* Don't propogate error information up to the client. Instead let
11885 the client find out about the error by querying the target. */
88b496c3 11886 rs->async_client_callback (INF_REG_EVENT, rs->async_client_context);
2acceee2
JM
11887}
11888
74531fed
PA
11889static void
11890remote_async_inferior_event_handler (gdb_client_data data)
11891{
11892 inferior_event_handler (INF_REG_EVENT, NULL);
11893}
11894
2acceee2 11895static void
6a109b6b
TT
11896remote_async (struct target_ops *ops,
11897 void (*callback) (enum inferior_event_type event_type,
11898 void *context),
11899 void *context)
2acceee2 11900{
5d93a237
TT
11901 struct remote_state *rs = get_remote_state ();
11902
2acceee2
JM
11903 if (callback != NULL)
11904 {
88b496c3
TT
11905 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
11906 rs->async_client_callback = callback;
11907 rs->async_client_context = context;
b7d2e916
PA
11908
11909 /* If there are pending events in the stop reply queue tell the
11910 event loop to process them. */
11911 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
11912 mark_async_event_handler (remote_async_inferior_event_token);
2acceee2
JM
11913 }
11914 else
b7d2e916
PA
11915 {
11916 serial_async (rs->remote_desc, NULL, NULL);
11917 clear_async_event_handler (remote_async_inferior_event_token);
11918 }
6426a772
JM
11919}
11920
5a2468f5 11921static void
c2d11a7d 11922set_remote_cmd (char *args, int from_tty)
5a2468f5 11923{
635c7e8a 11924 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
11925}
11926
d471ea57
AC
11927static void
11928show_remote_cmd (char *args, int from_tty)
11929{
37a105a1 11930 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 11931 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
11932 struct cleanup *showlist_chain;
11933 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 11934 struct ui_out *uiout = current_uiout;
37a105a1
DJ
11935
11936 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
11937 for (; list != NULL; list = list->next)
11938 if (strcmp (list->name, "Z-packet") == 0)
11939 continue;
427c3a89
DJ
11940 else if (list->type == not_set_cmd)
11941 /* Alias commands are exactly like the original, except they
11942 don't have the normal type. */
11943 continue;
11944 else
37a105a1
DJ
11945 {
11946 struct cleanup *option_chain
11947 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 11948
37a105a1
DJ
11949 ui_out_field_string (uiout, "name", list->name);
11950 ui_out_text (uiout, ": ");
427c3a89 11951 if (list->type == show_cmd)
5b9afe8a 11952 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
11953 else
11954 cmd_func (list, NULL, from_tty);
37a105a1
DJ
11955 /* Close the tuple. */
11956 do_cleanups (option_chain);
11957 }
427c3a89
DJ
11958
11959 /* Close the tuple. */
11960 do_cleanups (showlist_chain);
d471ea57 11961}
5a2468f5 11962
0f71a2f6 11963
23860348 11964/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
11965static void
11966remote_new_objfile (struct objfile *objfile)
11967{
5d93a237
TT
11968 struct remote_state *rs = get_remote_state ();
11969
11970 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 11971 remote_check_symbols ();
dc8acb97
MS
11972}
11973
00bf0b85
SS
11974/* Pull all the tracepoints defined on the target and create local
11975 data structures representing them. We don't want to create real
11976 tracepoints yet, we don't want to mess up the user's existing
11977 collection. */
11978
11979static int
ab6617cc 11980remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 11981{
00bf0b85
SS
11982 struct remote_state *rs = get_remote_state ();
11983 char *p;
d5551862 11984
00bf0b85
SS
11985 /* Ask for a first packet of tracepoint definition. */
11986 putpkt ("qTfP");
11987 getpkt (&rs->buf, &rs->buf_size, 0);
11988 p = rs->buf;
11989 while (*p && *p != 'l')
d5551862 11990 {
00bf0b85
SS
11991 parse_tracepoint_definition (p, utpp);
11992 /* Ask for another packet of tracepoint definition. */
11993 putpkt ("qTsP");
11994 getpkt (&rs->buf, &rs->buf_size, 0);
11995 p = rs->buf;
d5551862 11996 }
00bf0b85 11997 return 0;
d5551862
SS
11998}
11999
00bf0b85 12000static int
181e3713
TT
12001remote_upload_trace_state_variables (struct target_ops *self,
12002 struct uploaded_tsv **utsvp)
d5551862 12003{
00bf0b85 12004 struct remote_state *rs = get_remote_state ();
d5551862 12005 char *p;
d5551862 12006
00bf0b85
SS
12007 /* Ask for a first packet of variable definition. */
12008 putpkt ("qTfV");
d5551862
SS
12009 getpkt (&rs->buf, &rs->buf_size, 0);
12010 p = rs->buf;
00bf0b85 12011 while (*p && *p != 'l')
d5551862 12012 {
00bf0b85
SS
12013 parse_tsv_definition (p, utsvp);
12014 /* Ask for another packet of variable definition. */
12015 putpkt ("qTsV");
d5551862
SS
12016 getpkt (&rs->buf, &rs->buf_size, 0);
12017 p = rs->buf;
12018 }
00bf0b85 12019 return 0;
d5551862
SS
12020}
12021
c1e36e3e
PA
12022/* The "set/show range-stepping" show hook. */
12023
12024static void
12025show_range_stepping (struct ui_file *file, int from_tty,
12026 struct cmd_list_element *c,
12027 const char *value)
12028{
12029 fprintf_filtered (file,
12030 _("Debugger's willingness to use range stepping "
12031 "is %s.\n"), value);
12032}
12033
12034/* The "set/show range-stepping" set hook. */
12035
12036static void
12037set_range_stepping (char *ignore_args, int from_tty,
12038 struct cmd_list_element *c)
12039{
5d93a237
TT
12040 struct remote_state *rs = get_remote_state ();
12041
c1e36e3e
PA
12042 /* Whene enabling, check whether range stepping is actually
12043 supported by the target, and warn if not. */
12044 if (use_range_stepping)
12045 {
5d93a237 12046 if (rs->remote_desc != NULL)
c1e36e3e 12047 {
4082afcc 12048 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
12049 remote_vcont_probe (rs);
12050
4082afcc 12051 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
12052 && rs->supports_vCont.r)
12053 return;
12054 }
12055
12056 warning (_("Range stepping is not supported by the current target"));
12057 }
12058}
12059
c906108c 12060void
fba45db2 12061_initialize_remote (void)
c906108c 12062{
ea9c271d 12063 struct remote_state *rs;
9a7071a8 12064 struct cmd_list_element *cmd;
6f937416 12065 const char *cmd_name;
ea9c271d 12066
0f71a2f6 12067 /* architecture specific data */
2bc416ba 12068 remote_gdbarch_data_handle =
23860348 12069 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
12070 remote_g_packet_data_handle =
12071 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 12072
ea9c271d
DJ
12073 /* Initialize the per-target state. At the moment there is only one
12074 of these, not one per target. Only one target is active at a
cf792862
TT
12075 time. */
12076 remote_state = new_remote_state ();
ea9c271d 12077
c906108c
SS
12078 init_remote_ops ();
12079 add_target (&remote_ops);
12080
12081 init_extended_remote_ops ();
12082 add_target (&extended_remote_ops);
cce74817 12083
dc8acb97 12084 /* Hook into new objfile notification. */
06d3b283 12085 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
12086 /* We're no longer interested in notification events of an inferior
12087 when it exits. */
12088 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 12089
b803fb0f 12090 /* Set up signal handlers. */
934b9bac 12091 async_sigint_remote_token =
b803fb0f 12092 create_async_signal_handler (async_remote_interrupt, NULL);
934b9bac 12093 async_sigint_remote_twice_token =
6d549500 12094 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 12095
c906108c
SS
12096#if 0
12097 init_remote_threadtests ();
12098#endif
12099
722247f1 12100 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 12101 /* set/show remote ... */
d471ea57 12102
1bedd215 12103 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
12104Remote protocol specific variables\n\
12105Configure various remote-protocol specific variables such as\n\
1bedd215 12106the packets being used"),
cff3e48b 12107 &remote_set_cmdlist, "set remote ",
23860348 12108 0 /* allow-unknown */, &setlist);
1bedd215 12109 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
12110Remote protocol specific variables\n\
12111Configure various remote-protocol specific variables such as\n\
1bedd215 12112the packets being used"),
cff3e48b 12113 &remote_show_cmdlist, "show remote ",
23860348 12114 0 /* allow-unknown */, &showlist);
5a2468f5 12115
1a966eab
AC
12116 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
12117Compare section data on target to the exec file.\n\
95cf3b38
DT
12118Argument is a single section name (default: all loaded sections).\n\
12119To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
12120 &cmdlist);
12121
1a966eab
AC
12122 add_cmd ("packet", class_maintenance, packet_command, _("\
12123Send an arbitrary packet to a remote target.\n\
c906108c
SS
12124 maintenance packet TEXT\n\
12125If GDB is talking to an inferior via the GDB serial protocol, then\n\
12126this command sends the string TEXT to the inferior, and displays the\n\
12127response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 12128terminating `#' character and checksum."),
c906108c
SS
12129 &maintenancelist);
12130
7915a72c
AC
12131 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
12132Set whether to send break if interrupted."), _("\
12133Show whether to send break if interrupted."), _("\
12134If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 12135 set_remotebreak, show_remotebreak,
e707bbc2 12136 &setlist, &showlist);
9a7071a8
JB
12137 cmd_name = "remotebreak";
12138 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
12139 deprecate_cmd (cmd, "set remote interrupt-sequence");
12140 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
12141 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
12142 deprecate_cmd (cmd, "show remote interrupt-sequence");
12143
12144 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
12145 interrupt_sequence_modes, &interrupt_sequence_mode,
12146 _("\
9a7071a8
JB
12147Set interrupt sequence to remote target."), _("\
12148Show interrupt sequence to remote target."), _("\
12149Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
12150 NULL, show_interrupt_sequence,
12151 &remote_set_cmdlist,
12152 &remote_show_cmdlist);
12153
12154 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
12155 &interrupt_on_connect, _("\
12156Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12157Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12158If set, interrupt sequence is sent to remote target."),
12159 NULL, NULL,
12160 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 12161
23860348 12162 /* Install commands for configuring memory read/write packets. */
11cf8741 12163
1a966eab
AC
12164 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
12165Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 12166 &setlist);
1a966eab
AC
12167 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
12168Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
12169 &showlist);
12170 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
12171 set_memory_write_packet_size, _("\
12172Set the maximum number of bytes per memory-write packet.\n\
12173Specify the number of bytes in a packet or 0 (zero) for the\n\
12174default packet size. The actual limit is further reduced\n\
12175dependent on the target. Specify ``fixed'' to disable the\n\
12176further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
12177 &remote_set_cmdlist);
12178 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
12179 set_memory_read_packet_size, _("\
12180Set the maximum number of bytes per memory-read packet.\n\
12181Specify the number of bytes in a packet or 0 (zero) for the\n\
12182default packet size. The actual limit is further reduced\n\
12183dependent on the target. Specify ``fixed'' to disable the\n\
12184further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
12185 &remote_set_cmdlist);
12186 add_cmd ("memory-write-packet-size", no_class,
12187 show_memory_write_packet_size,
1a966eab 12188 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
12189 &remote_show_cmdlist);
12190 add_cmd ("memory-read-packet-size", no_class,
12191 show_memory_read_packet_size,
1a966eab 12192 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 12193 &remote_show_cmdlist);
c906108c 12194
b3f42336 12195 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
12196 &remote_hw_watchpoint_limit, _("\
12197Set the maximum number of target hardware watchpoints."), _("\
12198Show the maximum number of target hardware watchpoints."), _("\
12199Specify a negative limit for unlimited."),
3e43a32a
MS
12200 NULL, NULL, /* FIXME: i18n: The maximum
12201 number of target hardware
12202 watchpoints is %s. */
b3f42336 12203 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
12204 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
12205 &remote_hw_watchpoint_length_limit, _("\
12206Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
12207Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
12208Specify a negative limit for unlimited."),
12209 NULL, NULL, /* FIXME: i18n: The maximum
12210 length (in bytes) of a target
12211 hardware watchpoint is %s. */
12212 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 12213 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
12214 &remote_hw_breakpoint_limit, _("\
12215Set the maximum number of target hardware breakpoints."), _("\
12216Show the maximum number of target hardware breakpoints."), _("\
12217Specify a negative limit for unlimited."),
3e43a32a
MS
12218 NULL, NULL, /* FIXME: i18n: The maximum
12219 number of target hardware
12220 breakpoints is %s. */
b3f42336 12221 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 12222
1b493192
PA
12223 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
12224 &remote_address_size, _("\
4d28ad1e
AC
12225Set the maximum size of the address (in bits) in a memory packet."), _("\
12226Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
12227 NULL,
12228 NULL, /* FIXME: i18n: */
12229 &setlist, &showlist);
c906108c 12230
ca4f7f8b
PA
12231 init_all_packet_configs ();
12232
444abaca 12233 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 12234 "X", "binary-download", 1);
0f71a2f6 12235
444abaca 12236 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 12237 "vCont", "verbose-resume", 0);
506fb367 12238
89be2091
DJ
12239 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
12240 "QPassSignals", "pass-signals", 0);
12241
9b224c5e
PA
12242 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
12243 "QProgramSignals", "program-signals", 0);
12244
444abaca 12245 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 12246 "qSymbol", "symbol-lookup", 0);
dc8acb97 12247
444abaca 12248 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 12249 "P", "set-register", 1);
d471ea57 12250
444abaca 12251 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 12252 "p", "fetch-register", 1);
b96ec7ac 12253
444abaca 12254 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 12255 "Z0", "software-breakpoint", 0);
d471ea57 12256
444abaca 12257 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 12258 "Z1", "hardware-breakpoint", 0);
d471ea57 12259
444abaca 12260 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 12261 "Z2", "write-watchpoint", 0);
d471ea57 12262
444abaca 12263 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 12264 "Z3", "read-watchpoint", 0);
d471ea57 12265
444abaca 12266 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 12267 "Z4", "access-watchpoint", 0);
d471ea57 12268
0876f84a
DJ
12269 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
12270 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 12271
23181151
DJ
12272 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
12273 "qXfer:features:read", "target-features", 0);
12274
cfa9d6d9
DJ
12275 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
12276 "qXfer:libraries:read", "library-info", 0);
12277
2268b414
JK
12278 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12279 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12280
fd79ecee
DJ
12281 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12282 "qXfer:memory-map:read", "memory-map", 0);
12283
0e7f50da
UW
12284 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12285 "qXfer:spu:read", "read-spu-object", 0);
12286
12287 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12288 "qXfer:spu:write", "write-spu-object", 0);
12289
07e059b5
VP
12290 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12291 "qXfer:osdata:read", "osdata", 0);
12292
dc146f7c
VP
12293 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12294 "qXfer:threads:read", "threads", 0);
12295
4aa995e1
PA
12296 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12297 "qXfer:siginfo:read", "read-siginfo-object", 0);
12298
12299 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12300 "qXfer:siginfo:write", "write-siginfo-object", 0);
12301
b3b9301e
PA
12302 add_packet_config_cmd
12303 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 12304 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 12305
169081d0
TG
12306 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12307 "qXfer:uib:read", "unwind-info-block", 0);
12308
444abaca 12309 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 12310 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
12311 0);
12312
711e434b
PM
12313 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12314 "qGetTIBAddr", "get-thread-information-block-address",
12315 0);
12316
40ab02ce
MS
12317 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12318 "bc", "reverse-continue", 0);
12319
12320 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12321 "bs", "reverse-step", 0);
12322
be2a5f71
DJ
12323 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12324 "qSupported", "supported-packets", 0);
12325
08388c79
DE
12326 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12327 "qSearch:memory", "search-memory", 0);
12328
bd3eecc3
PA
12329 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12330 "qTStatus", "trace-status", 0);
12331
a6b151f1
DJ
12332 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12333 "vFile:open", "hostio-open", 0);
12334
12335 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12336 "vFile:pread", "hostio-pread", 0);
12337
12338 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12339 "vFile:pwrite", "hostio-pwrite", 0);
12340
12341 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12342 "vFile:close", "hostio-close", 0);
12343
12344 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12345 "vFile:unlink", "hostio-unlink", 0);
12346
b9e7b9c3
UW
12347 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12348 "vFile:readlink", "hostio-readlink", 0);
12349
2d717e4f
DJ
12350 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12351 "vAttach", "attach", 0);
12352
12353 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12354 "vRun", "run", 0);
12355
a6f3e723
SL
12356 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12357 "QStartNoAckMode", "noack", 0);
12358
82f73884
PA
12359 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12360 "vKill", "kill", 0);
12361
0b16c5cf
PA
12362 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12363 "qAttached", "query-attached", 0);
12364
782b2b07 12365 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
12366 "ConditionalTracepoints",
12367 "conditional-tracepoints", 0);
3788aec7
LM
12368
12369 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12370 "ConditionalBreakpoints",
12371 "conditional-breakpoints", 0);
12372
d3ce09f5
SS
12373 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12374 "BreakpointCommands",
12375 "breakpoint-commands", 0);
12376
7a697b8d
SS
12377 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12378 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 12379
409873ef
SS
12380 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12381 "TracepointSource", "TracepointSource", 0);
12382
d914c394
SS
12383 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12384 "QAllow", "allow", 0);
12385
0fb4aa4b
PA
12386 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12387 "StaticTracepoints", "static-tracepoints", 0);
12388
1e4d1764
YQ
12389 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12390 "InstallInTrace", "install-in-trace", 0);
12391
0fb4aa4b
PA
12392 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12393 "qXfer:statictrace:read", "read-sdata-object", 0);
12394
78d85199
YQ
12395 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12396 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12397
03583c20
UW
12398 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12399 "QDisableRandomization", "disable-randomization", 0);
12400
d1feda86
YQ
12401 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12402 "QAgent", "agent", 0);
12403
f6f899bf
HAQ
12404 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12405 "QTBuffer:size", "trace-buffer-size", 0);
12406
9accd112
MM
12407 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12408 "Qbtrace:off", "disable-btrace", 0);
12409
12410 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12411 "Qbtrace:bts", "enable-btrace", 0);
12412
12413 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12414 "qXfer:btrace", "read-btrace", 0);
12415
f4abbc16
MM
12416 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
12417 "qXfer:btrace-conf", "read-btrace-conf", 0);
12418
d33501a5
MM
12419 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
12420 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
12421
f7e6eed5
PA
12422 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
12423 "swbreak-feature", "swbreak-feature", 0);
12424
12425 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
12426 "hwbreak-feature", "hwbreak-feature", 0);
12427
ca4f7f8b
PA
12428 /* Assert that we've registered commands for all packet configs. */
12429 {
12430 int i;
12431
12432 for (i = 0; i < PACKET_MAX; i++)
12433 {
12434 /* Ideally all configs would have a command associated. Some
12435 still don't though. */
12436 int excepted;
12437
12438 switch (i)
12439 {
12440 case PACKET_QNonStop:
12441 case PACKET_multiprocess_feature:
12442 case PACKET_EnableDisableTracepoints_feature:
12443 case PACKET_tracenz_feature:
12444 case PACKET_DisconnectedTracing_feature:
12445 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
12446 case PACKET_qCRC:
12447 /* Additions to this list need to be well justified:
12448 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
12449 excepted = 1;
12450 break;
12451 default:
12452 excepted = 0;
12453 break;
12454 }
12455
12456 /* This catches both forgetting to add a config command, and
12457 forgetting to remove a packet from the exception list. */
12458 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
12459 }
12460 }
12461
37a105a1
DJ
12462 /* Keep the old ``set remote Z-packet ...'' working. Each individual
12463 Z sub-packet has its own set and show commands, but users may
12464 have sets to this variable in their .gdbinit files (or in their
12465 documentation). */
e9e68a56 12466 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
12467 &remote_Z_packet_detect, _("\
12468Set use of remote protocol `Z' packets"), _("\
12469Show use of remote protocol `Z' packets "), _("\
3b64bf98 12470When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 12471packets."),
e9e68a56 12472 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
12473 show_remote_protocol_Z_packet_cmd,
12474 /* FIXME: i18n: Use of remote protocol
12475 `Z' packets is %s. */
e9e68a56 12476 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 12477
a6b151f1
DJ
12478 add_prefix_cmd ("remote", class_files, remote_command, _("\
12479Manipulate files on the remote system\n\
12480Transfer files to and from the remote target system."),
12481 &remote_cmdlist, "remote ",
12482 0 /* allow-unknown */, &cmdlist);
12483
12484 add_cmd ("put", class_files, remote_put_command,
12485 _("Copy a local file to the remote system."),
12486 &remote_cmdlist);
12487
12488 add_cmd ("get", class_files, remote_get_command,
12489 _("Copy a remote file to the local system."),
12490 &remote_cmdlist);
12491
12492 add_cmd ("delete", class_files, remote_delete_command,
12493 _("Delete a remote file."),
12494 &remote_cmdlist);
12495
2d717e4f
DJ
12496 remote_exec_file = xstrdup ("");
12497 add_setshow_string_noescape_cmd ("exec-file", class_files,
12498 &remote_exec_file, _("\
12499Set the remote pathname for \"run\""), _("\
12500Show the remote pathname for \"run\""), NULL, NULL, NULL,
12501 &remote_set_cmdlist, &remote_show_cmdlist);
12502
c1e36e3e
PA
12503 add_setshow_boolean_cmd ("range-stepping", class_run,
12504 &use_range_stepping, _("\
12505Enable or disable range stepping."), _("\
12506Show whether target-assisted range stepping is enabled."), _("\
12507If on, and the target supports it, when stepping a source line, GDB\n\
12508tells the target to step the corresponding range of addresses itself instead\n\
12509of issuing multiple single-steps. This speeds up source level\n\
12510stepping. If off, GDB always issues single-steps, even if range\n\
12511stepping is supported by the target. The default is on."),
12512 set_range_stepping,
12513 show_range_stepping,
12514 &setlist,
12515 &showlist);
12516
449092f6
CV
12517 /* Eventually initialize fileio. See fileio.c */
12518 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 12519
ba348170 12520 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 12521 special ptids with it set to != 0. */
ba348170
PA
12522 magic_null_ptid = ptid_build (42000, -1, 1);
12523 not_sent_ptid = ptid_build (42000, -2, 1);
12524 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
12525
12526 target_buf_size = 2048;
12527 target_buf = xmalloc (target_buf_size);
c906108c 12528}
10760264 12529