Explicit locations: introduce new struct event_location-based API
[deliverable/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"
6b940e6a 47#include "disasm.h"
c906108c 48
9846de1b 49#include <sys/time.h>
c906108c 50
43ff13b4 51#include "event-loop.h"
c2c6d25f 52#include "event-top.h"
2acceee2 53#include "inf-loop.h"
43ff13b4 54
c906108c
SS
55#include <signal.h>
56#include "serial.h"
57
6240bebf
MS
58#include "gdbcore.h" /* for exec_bfd */
59
449092f6 60#include "remote-fileio.h"
a6b151f1 61#include "gdb/fileio.h"
53ce3c39 62#include <sys/stat.h>
dc146f7c 63#include "xml-support.h"
449092f6 64
fd79ecee
DJ
65#include "memory-map.h"
66
35b1e5cc
SS
67#include "tracepoint.h"
68#include "ax.h"
69#include "ax-gdb.h"
d1feda86 70#include "agent.h"
9accd112 71#include "btrace.h"
35b1e5cc 72
0df8b418 73/* Temp hacks for tracepoint encoding migration. */
35b1e5cc
SS
74static char *target_buf;
75static long target_buf_size;
35b1e5cc 76
6765f3e5
DJ
77/* The size to align memory write packets, when practical. The protocol
78 does not guarantee any alignment, and gdb will generate short
79 writes and unaligned writes, but even as a best-effort attempt this
80 can improve bulk transfers. For instance, if a write is misaligned
81 relative to the target's data bus, the stub may need to make an extra
82 round trip fetching data from the target. This doesn't make a
83 huge difference, but it's easy to do, so we try to be helpful.
84
85 The alignment chosen is arbitrary; usually data bus width is
86 important here, not the possibly larger cache line size. */
87enum { REMOTE_ALIGN_WRITES = 16 };
88
23860348 89/* Prototypes for local functions. */
934b9bac 90static void async_cleanup_sigint_signal_handler (void *dummy);
6d820c5c 91static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
74531fed 92static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
fee9eda9 93 int forever, int *is_notif);
6426a772 94
934b9bac
JK
95static void async_handle_remote_sigint (int);
96static void async_handle_remote_sigint_twice (int);
43ff13b4 97
a14ed312 98static void remote_files_info (struct target_ops *ignore);
c906108c 99
f32dbf8c
MM
100static void remote_prepare_to_store (struct target_ops *self,
101 struct regcache *regcache);
c906108c 102
014f9477
TT
103static void remote_open_1 (const char *, int, struct target_ops *,
104 int extended_p);
c906108c 105
de90e03d 106static void remote_close (struct target_ops *self);
c906108c 107
cbb8991c
DB
108struct remote_state;
109
110static int remote_vkill (int pid, struct remote_state *rs);
111
136d6dae 112static void remote_mourn (struct target_ops *ops);
c906108c 113
a14ed312 114static void extended_remote_restart (void);
c906108c 115
136d6dae 116static void extended_remote_mourn (struct target_ops *);
c906108c 117
6d820c5c 118static void remote_send (char **buf, long *sizeof_buf_p);
c906108c 119
a14ed312 120static int readchar (int timeout);
c906108c 121
c33e31fd
PA
122static void remote_serial_write (const char *str, int len);
123
7d85a9c0 124static void remote_kill (struct target_ops *ops);
c906108c 125
6a109b6b 126static int remote_can_async_p (struct target_ops *);
75c99385 127
6a109b6b 128static int remote_is_async_p (struct target_ops *);
75c99385 129
6a3753b3 130static void remote_async (struct target_ops *ops, int enable);
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
8bd200f1
TT
189static int remote_get_trace_status (struct target_ops *self,
190 struct trace_status *ts);
d5551862 191
ab6617cc
TT
192static int remote_upload_tracepoints (struct target_ops *self,
193 struct uploaded_tp **utpp);
00bf0b85 194
181e3713
TT
195static int remote_upload_trace_state_variables (struct target_ops *self,
196 struct uploaded_tsv **utsvp);
00bf0b85 197
c8d104ad
PA
198static void remote_query_supported (void);
199
36d25514 200static void remote_check_symbols (void);
c8d104ad 201
a14ed312 202void _initialize_remote (void);
c906108c 203
74531fed 204struct stop_reply;
74531fed 205static void stop_reply_xfree (struct stop_reply *);
722247f1 206static void remote_parse_stop_reply (char *, struct stop_reply *);
74531fed 207static void push_stop_reply (struct stop_reply *);
bcc75809 208static void discard_pending_stop_replies_in_queue (struct remote_state *);
74531fed
PA
209static int peek_stop_reply (ptid_t ptid);
210
cbb8991c
DB
211struct threads_listing_context;
212static void remove_new_fork_children (struct threads_listing_context *);
213
74531fed 214static void remote_async_inferior_event_handler (gdb_client_data);
74531fed 215
e3594fd1 216static void remote_terminal_ours (struct target_ops *self);
d3fd5342 217
d962ef82
DJ
218static int remote_read_description_p (struct target_ops *target);
219
176a6961 220static void remote_console_output (char *msg);
dde08ee1 221
efcc2da7 222static int remote_supports_cond_breakpoints (struct target_ops *self);
b775012e 223
78eff0ec 224static int remote_can_run_breakpoint_commands (struct target_ops *self);
d3ce09f5 225
f4abbc16
MM
226static void remote_btrace_reset (void);
227
a6b151f1
DJ
228/* For "remote". */
229
230static struct cmd_list_element *remote_cmdlist;
231
bb572ddd
DJ
232/* For "set remote" and "show remote". */
233
234static struct cmd_list_element *remote_set_cmdlist;
235static struct cmd_list_element *remote_show_cmdlist;
236
d458bd84
PA
237/* Stub vCont actions support.
238
239 Each field is a boolean flag indicating whether the stub reports
240 support for the corresponding action. */
241
242struct vCont_action_support
243{
244 /* vCont;t */
245 int t;
c1e36e3e
PA
246
247 /* vCont;r */
248 int r;
d458bd84
PA
249};
250
c1e36e3e
PA
251/* Controls whether GDB is willing to use range stepping. */
252
253static int use_range_stepping = 1;
254
0d031856
TT
255#define OPAQUETHREADBYTES 8
256
257/* a 64 bit opaque identifier */
258typedef unsigned char threadref[OPAQUETHREADBYTES];
259
260/* About this many threadisds fit in a packet. */
261
262#define MAXTHREADLISTRESULTS 32
263
ea9c271d
DJ
264/* Description of the remote protocol state for the currently
265 connected target. This is per-target state, and independent of the
266 selected architecture. */
267
268struct remote_state
269{
270 /* A buffer to use for incoming packets, and its current size. The
271 buffer is grown dynamically for larger incoming packets.
272 Outgoing packets may also be constructed in this buffer.
273 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
274 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
275 packets. */
276 char *buf;
277 long buf_size;
be2a5f71 278
1e51243a
PA
279 /* True if we're going through initial connection setup (finding out
280 about the remote side's threads, relocating symbols, etc.). */
281 int starting_up;
282
be2a5f71
DJ
283 /* If we negotiated packet size explicitly (and thus can bypass
284 heuristics for the largest packet size that will not overflow
285 a buffer in the stub), this will be set to that packet size.
286 Otherwise zero, meaning to use the guessed size. */
287 long explicit_packet_size;
2d717e4f
DJ
288
289 /* remote_wait is normally called when the target is running and
290 waits for a stop reply packet. But sometimes we need to call it
291 when the target is already stopped. We can send a "?" packet
292 and have remote_wait read the response. Or, if we already have
293 the response, we can stash it in BUF and tell remote_wait to
294 skip calling getpkt. This flag is set when BUF contains a
295 stop reply packet and the target is not waiting. */
296 int cached_wait_status;
a6f3e723
SL
297
298 /* True, if in no ack mode. That is, neither GDB nor the stub will
299 expect acks from each other. The connection is assumed to be
300 reliable. */
301 int noack_mode;
82f73884
PA
302
303 /* True if we're connected in extended remote mode. */
304 int extended;
305
e24a49d8
PA
306 /* True if we resumed the target and we're waiting for the target to
307 stop. In the mean time, we can't start another command/query.
308 The remote server wouldn't be ready to process it, so we'd
309 timeout waiting for a reply that would never come and eventually
310 we'd close the connection. This can happen in asynchronous mode
311 because we allow GDB commands while the target is running. */
312 int waiting_for_stop_reply;
74531fed 313
d458bd84
PA
314 /* The status of the stub support for the various vCont actions. */
315 struct vCont_action_support supports_vCont;
782b2b07 316
3a29589a
DJ
317 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
318 responded to that. */
319 int ctrlc_pending_p;
5d93a237
TT
320
321 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
322 remote_open knows that we don't have a file open when the program
323 starts. */
324 struct serial *remote_desc;
47f8a51d
TT
325
326 /* These are the threads which we last sent to the remote system. The
327 TID member will be -1 for all or -2 for not sent yet. */
328 ptid_t general_thread;
329 ptid_t continue_thread;
262e1174
TT
330
331 /* This is the traceframe which we last selected on the remote system.
332 It will be -1 if no traceframe is selected. */
333 int remote_traceframe_number;
747dc59d
TT
334
335 char *last_pass_packet;
5e4a05c4
TT
336
337 /* The last QProgramSignals packet sent to the target. We bypass
338 sending a new program signals list down to the target if the new
339 packet is exactly the same as the last we sent. IOW, we only let
340 the target know about program signals list changes. */
341 char *last_program_signals_packet;
b73be471
TT
342
343 enum gdb_signal last_sent_signal;
280ceea3
TT
344
345 int last_sent_step;
8e88304f
TT
346
347 char *finished_object;
348 char *finished_annex;
349 ULONGEST finished_offset;
b80fafe3
TT
350
351 /* Should we try the 'ThreadInfo' query packet?
352
353 This variable (NOT available to the user: auto-detect only!)
354 determines whether GDB will use the new, simpler "ThreadInfo"
355 query or the older, more complex syntax for thread queries.
356 This is an auto-detect variable (set to true at each connect,
357 and set to false when the target fails to recognize it). */
358 int use_threadinfo_query;
359 int use_threadextra_query;
88b496c3 360
ee154bee
TT
361 /* This is set to the data address of the access causing the target
362 to stop for a watchpoint. */
363 CORE_ADDR remote_watch_data_address;
364
f7e6eed5
PA
365 /* Whether the target stopped for a breakpoint/watchpoint. */
366 enum target_stop_reason stop_reason;
0d031856
TT
367
368 threadref echo_nextthread;
369 threadref nextthread;
370 threadref resultthreadlist[MAXTHREADLISTRESULTS];
5965e028
YQ
371
372 /* The state of remote notification. */
373 struct remote_notif_state *notif_state;
f4abbc16
MM
374
375 /* The branch trace configuration. */
376 struct btrace_config btrace_config;
15a201c8
GB
377
378 /* The argument to the last "vFile:setfs:" packet we sent, used
379 to avoid sending repeated unnecessary "vFile:setfs:" packets.
380 Initialized to -1 to indicate that no "vFile:setfs:" packet
381 has yet been sent. */
382 int fs_pid;
ea9c271d
DJ
383};
384
dc146f7c
VP
385/* Private data that we'll store in (struct thread_info)->private. */
386struct private_thread_info
387{
388 char *extra;
389 int core;
390};
391
392static void
393free_private_thread_info (struct private_thread_info *info)
394{
395 xfree (info->extra);
396 xfree (info);
397}
398
ea9c271d
DJ
399/* This data could be associated with a target, but we do not always
400 have access to the current target when we need it, so for now it is
401 static. This will be fine for as long as only one target is in use
402 at a time. */
cf792862 403static struct remote_state *remote_state;
ea9c271d
DJ
404
405static struct remote_state *
0b83947e 406get_remote_state_raw (void)
ea9c271d 407{
cf792862
TT
408 return remote_state;
409}
410
411/* Allocate a new struct remote_state with xmalloc, initialize it, and
412 return it. */
413
414static struct remote_state *
415new_remote_state (void)
416{
417 struct remote_state *result = XCNEW (struct remote_state);
418
419 /* The default buffer size is unimportant; it will be expanded
420 whenever a larger buffer is needed. */
421 result->buf_size = 400;
422 result->buf = xmalloc (result->buf_size);
262e1174 423 result->remote_traceframe_number = -1;
b73be471 424 result->last_sent_signal = GDB_SIGNAL_0;
15a201c8 425 result->fs_pid = -1;
cf792862
TT
426
427 return result;
ea9c271d
DJ
428}
429
430/* Description of the remote protocol for a given architecture. */
d01949b6 431
ad10f812
AC
432struct packet_reg
433{
434 long offset; /* Offset into G packet. */
435 long regnum; /* GDB's internal register number. */
436 LONGEST pnum; /* Remote protocol register number. */
b323314b 437 int in_g_packet; /* Always part of G packet. */
f5656ead 438 /* long size in bytes; == register_size (target_gdbarch (), regnum);
23860348 439 at present. */
f5656ead 440 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
c9f4d572 441 at present. */
ad10f812
AC
442};
443
ea9c271d 444struct remote_arch_state
d01949b6 445{
ad10f812
AC
446 /* Description of the remote protocol registers. */
447 long sizeof_g_packet;
b323314b
AC
448
449 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 450 (making an array gdbarch_num_regs in size). */
b323314b 451 struct packet_reg *regs;
ad10f812 452
d01949b6
AC
453 /* This is the size (in chars) of the first response to the ``g''
454 packet. It is used as a heuristic when determining the maximum
455 size of memory-read and memory-write packets. A target will
456 typically only reserve a buffer large enough to hold the ``g''
457 packet. The size does not include packet overhead (headers and
23860348 458 trailers). */
d01949b6
AC
459 long actual_register_packet_size;
460
461 /* This is the maximum size (in chars) of a non read/write packet.
23860348 462 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
463 long remote_packet_size;
464};
465
35b1e5cc
SS
466/* Utility: generate error from an incoming stub packet. */
467static void
468trace_error (char *buf)
469{
470 if (*buf++ != 'E')
471 return; /* not an error msg */
472 switch (*buf)
473 {
474 case '1': /* malformed packet error */
475 if (*++buf == '0') /* general case: */
476 error (_("remote.c: error in outgoing packet."));
477 else
478 error (_("remote.c: error in outgoing packet at field #%ld."),
479 strtol (buf, NULL, 16));
35b1e5cc
SS
480 default:
481 error (_("Target returns error code '%s'."), buf);
482 }
483}
484
485/* Utility: wait for reply from stub, while accepting "O" packets. */
486static char *
487remote_get_noisy_reply (char **buf_p,
488 long *sizeof_buf)
489{
490 do /* Loop on reply from remote stub. */
491 {
492 char *buf;
a744cf53 493
0df8b418 494 QUIT; /* Allow user to bail out with ^C. */
35b1e5cc
SS
495 getpkt (buf_p, sizeof_buf, 0);
496 buf = *buf_p;
ad91cd99 497 if (buf[0] == 'E')
35b1e5cc 498 trace_error (buf);
61012eef 499 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
500 {
501 ULONGEST ul;
502 CORE_ADDR from, to, org_to;
503 char *p, *pp;
504 int adjusted_size = 0;
7556d4a4 505 int relocated = 0;
dde08ee1
PA
506
507 p = buf + strlen ("qRelocInsn:");
508 pp = unpack_varlen_hex (p, &ul);
509 if (*pp != ';')
cb91c06a 510 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
511 from = ul;
512
513 p = pp + 1;
a9cbf802 514 unpack_varlen_hex (p, &ul);
dde08ee1
PA
515 to = ul;
516
517 org_to = to;
518
492d29ea 519 TRY
dde08ee1 520 {
f5656ead 521 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 522 relocated = 1;
dde08ee1 523 }
492d29ea 524 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
525 {
526 if (ex.error == MEMORY_ERROR)
527 {
528 /* Propagate memory errors silently back to the
529 target. The stub may have limited the range of
530 addresses we can write to, for example. */
531 }
532 else
533 {
534 /* Something unexpectedly bad happened. Be verbose
535 so we can tell what, and propagate the error back
536 to the stub, so it doesn't get stuck waiting for
537 a response. */
538 exception_fprintf (gdb_stderr, ex,
539 _("warning: relocating instruction: "));
540 }
541 putpkt ("E01");
542 }
492d29ea 543 END_CATCH
7556d4a4
PA
544
545 if (relocated)
dde08ee1
PA
546 {
547 adjusted_size = to - org_to;
548
bba74b36 549 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
550 putpkt (buf);
551 }
dde08ee1 552 }
ad91cd99 553 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
554 remote_console_output (buf + 1); /* 'O' message from stub */
555 else
0df8b418 556 return buf; /* Here's the actual reply. */
35b1e5cc
SS
557 }
558 while (1);
559}
3c3bea1c 560
d01949b6
AC
561/* Handle for retreving the remote protocol data from gdbarch. */
562static struct gdbarch_data *remote_gdbarch_data_handle;
563
ea9c271d
DJ
564static struct remote_arch_state *
565get_remote_arch_state (void)
d01949b6 566{
f5656ead 567 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
d01949b6
AC
568}
569
0b83947e
DJ
570/* Fetch the global remote target state. */
571
572static struct remote_state *
573get_remote_state (void)
574{
575 /* Make sure that the remote architecture state has been
576 initialized, because doing so might reallocate rs->buf. Any
577 function which calls getpkt also needs to be mindful of changes
578 to rs->buf, but this call limits the number of places which run
579 into trouble. */
580 get_remote_arch_state ();
581
582 return get_remote_state_raw ();
583}
584
74ca34ce
DJ
585static int
586compare_pnums (const void *lhs_, const void *rhs_)
587{
588 const struct packet_reg * const *lhs = lhs_;
589 const struct packet_reg * const *rhs = rhs_;
590
591 if ((*lhs)->pnum < (*rhs)->pnum)
592 return -1;
593 else if ((*lhs)->pnum == (*rhs)->pnum)
594 return 0;
595 else
596 return 1;
597}
598
c21236dc
PA
599static int
600map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 601{
74ca34ce 602 int regnum, num_remote_regs, offset;
74ca34ce 603 struct packet_reg **remote_regs;
ea9c271d 604
4a22f64d 605 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 606 {
c21236dc 607 struct packet_reg *r = &regs[regnum];
baef701f 608
4a22f64d 609 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
610 /* Do not try to fetch zero-sized (placeholder) registers. */
611 r->pnum = -1;
612 else
613 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
614
b323314b 615 r->regnum = regnum;
74ca34ce
DJ
616 }
617
618 /* Define the g/G packet format as the contents of each register
619 with a remote protocol number, in order of ascending protocol
620 number. */
621
4a22f64d 622 remote_regs = alloca (gdbarch_num_regs (gdbarch)
c21236dc 623 * sizeof (struct packet_reg *));
f57d151a 624 for (num_remote_regs = 0, regnum = 0;
4a22f64d 625 regnum < gdbarch_num_regs (gdbarch);
f57d151a 626 regnum++)
c21236dc
PA
627 if (regs[regnum].pnum != -1)
628 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 629
74ca34ce
DJ
630 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
631 compare_pnums);
632
633 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
634 {
635 remote_regs[regnum]->in_g_packet = 1;
636 remote_regs[regnum]->offset = offset;
4a22f64d 637 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
638 }
639
c21236dc
PA
640 return offset;
641}
642
643/* Given the architecture described by GDBARCH, return the remote
644 protocol register's number and the register's offset in the g/G
645 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
646 If the target does not have a mapping for REGNUM, return false,
647 otherwise, return true. */
648
649int
650remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
651 int *pnum, int *poffset)
652{
653 int sizeof_g_packet;
654 struct packet_reg *regs;
655 struct cleanup *old_chain;
656
657 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
658
659 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
660 old_chain = make_cleanup (xfree, regs);
661
662 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
663
664 *pnum = regs[regnum].pnum;
665 *poffset = regs[regnum].offset;
666
667 do_cleanups (old_chain);
668
669 return *pnum != -1;
670}
671
672static void *
673init_remote_state (struct gdbarch *gdbarch)
674{
675 struct remote_state *rs = get_remote_state_raw ();
676 struct remote_arch_state *rsa;
677
678 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
679
680 /* Use the architecture to build a regnum<->pnum table, which will be
681 1:1 unless a feature set specifies otherwise. */
682 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
683 gdbarch_num_regs (gdbarch),
684 struct packet_reg);
685
74ca34ce
DJ
686 /* Record the maximum possible size of the g packet - it may turn out
687 to be smaller. */
c21236dc 688 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 689
0df8b418 690 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
691 remote stubs have a hardwired buffer size of 400 bytes
692 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
693 as the maximum packet-size to ensure that the packet and an extra
694 NUL character can always fit in the buffer. This stops GDB
695 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
696 already a full buffer (As of 1999-12-04 that was most stubs). */
697 rsa->remote_packet_size = 400 - 1;
d01949b6 698
ea9c271d
DJ
699 /* This one is filled in when a ``g'' packet is received. */
700 rsa->actual_register_packet_size = 0;
701
702 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
703 default, adjust the size accordingly. Remember that each byte is
704 encoded as two characters. 32 is the overhead for the packet
705 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 706 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 707 little. */
ea9c271d
DJ
708 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
709 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 710
ea9c271d
DJ
711 /* Make sure that the packet buffer is plenty big enough for
712 this architecture. */
713 if (rs->buf_size < rsa->remote_packet_size)
714 {
715 rs->buf_size = 2 * rsa->remote_packet_size;
7fca722e 716 rs->buf = xrealloc (rs->buf, rs->buf_size);
ea9c271d 717 }
6d820c5c 718
ea9c271d
DJ
719 return rsa;
720}
721
722/* Return the current allowed size of a remote packet. This is
723 inferred from the current architecture, and should be used to
724 limit the length of outgoing packets. */
725static long
726get_remote_packet_size (void)
727{
be2a5f71 728 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
729 struct remote_arch_state *rsa = get_remote_arch_state ();
730
be2a5f71
DJ
731 if (rs->explicit_packet_size)
732 return rs->explicit_packet_size;
733
ea9c271d 734 return rsa->remote_packet_size;
d01949b6
AC
735}
736
ad10f812 737static struct packet_reg *
ea9c271d 738packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 739{
f5656ead 740 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
b323314b
AC
741 return NULL;
742 else
ad10f812 743 {
ea9c271d 744 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 745
b323314b
AC
746 gdb_assert (r->regnum == regnum);
747 return r;
ad10f812 748 }
ad10f812
AC
749}
750
751static struct packet_reg *
ea9c271d 752packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 753{
b323314b 754 int i;
a744cf53 755
f5656ead 756 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
ad10f812 757 {
ea9c271d 758 struct packet_reg *r = &rsa->regs[i];
a744cf53 759
b323314b
AC
760 if (r->pnum == pnum)
761 return r;
ad10f812
AC
762 }
763 return NULL;
d01949b6
AC
764}
765
c906108c
SS
766static struct target_ops remote_ops;
767
768static struct target_ops extended_remote_ops;
769
6426a772
JM
770/* FIXME: cagney/1999-09-23: Even though getpkt was called with
771 ``forever'' still use the normal timeout mechanism. This is
772 currently used by the ASYNC code to guarentee that target reads
773 during the initial connect always time-out. Once getpkt has been
774 modified to return a timeout indication and, in turn
775 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 776 this can go away. */
6426a772
JM
777static int wait_forever_enabled_p = 1;
778
9a7071a8
JB
779/* Allow the user to specify what sequence to send to the remote
780 when he requests a program interruption: Although ^C is usually
781 what remote systems expect (this is the default, here), it is
782 sometimes preferable to send a break. On other systems such
783 as the Linux kernel, a break followed by g, which is Magic SysRq g
784 is required in order to interrupt the execution. */
785const char interrupt_sequence_control_c[] = "Ctrl-C";
786const char interrupt_sequence_break[] = "BREAK";
787const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 788static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
789 {
790 interrupt_sequence_control_c,
791 interrupt_sequence_break,
792 interrupt_sequence_break_g,
793 NULL
794 };
795static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
796
797static void
798show_interrupt_sequence (struct ui_file *file, int from_tty,
799 struct cmd_list_element *c,
800 const char *value)
801{
802 if (interrupt_sequence_mode == interrupt_sequence_control_c)
803 fprintf_filtered (file,
804 _("Send the ASCII ETX character (Ctrl-c) "
805 "to the remote target to interrupt the "
806 "execution of the program.\n"));
807 else if (interrupt_sequence_mode == interrupt_sequence_break)
808 fprintf_filtered (file,
809 _("send a break signal to the remote target "
810 "to interrupt the execution of the program.\n"));
811 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
812 fprintf_filtered (file,
813 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
814 "the remote target to interrupt the execution "
815 "of Linux kernel.\n"));
816 else
817 internal_error (__FILE__, __LINE__,
818 _("Invalid value for interrupt_sequence_mode: %s."),
819 interrupt_sequence_mode);
820}
6426a772 821
9a7071a8
JB
822/* This boolean variable specifies whether interrupt_sequence is sent
823 to the remote target when gdb connects to it.
824 This is mostly needed when you debug the Linux kernel: The Linux kernel
825 expects BREAK g which is Magic SysRq g for connecting gdb. */
826static int interrupt_on_connect = 0;
c906108c 827
9a7071a8
JB
828/* This variable is used to implement the "set/show remotebreak" commands.
829 Since these commands are now deprecated in favor of "set/show remote
830 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
831static int remote_break;
832
9a7071a8
JB
833static void
834set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
835{
836 if (remote_break)
837 interrupt_sequence_mode = interrupt_sequence_break;
838 else
839 interrupt_sequence_mode = interrupt_sequence_control_c;
840}
841
842static void
843show_remotebreak (struct ui_file *file, int from_tty,
844 struct cmd_list_element *c,
845 const char *value)
846{
847}
848
c906108c
SS
849/* This variable sets the number of bits in an address that are to be
850 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 851 leading zeros, the entire address would be sent. This variable
c906108c
SS
852 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
853 initial implementation of remote.c restricted the address sent in
854 memory packets to ``host::sizeof long'' bytes - (typically 32
855 bits). Consequently, for 64 bit targets, the upper 32 bits of an
856 address was never sent. Since fixing this bug may cause a break in
857 some remote targets this variable is principly provided to
23860348 858 facilitate backward compatibility. */
c906108c 859
883b9c6c 860static unsigned int remote_address_size;
c906108c 861
75c99385
PA
862/* Temporary to track who currently owns the terminal. See
863 remote_terminal_* for more details. */
6426a772
JM
864
865static int remote_async_terminal_ours_p;
866
2d717e4f
DJ
867/* The executable file to use for "run" on the remote side. */
868
869static char *remote_exec_file = "";
870
11cf8741 871\f
11cf8741 872/* User configurable variables for the number of characters in a
ea9c271d
DJ
873 memory read/write packet. MIN (rsa->remote_packet_size,
874 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 875 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
876 (speed up transfers). The variables ``preferred_*'' (the user
877 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 878 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
879
880struct memory_packet_config
881{
882 char *name;
883 long size;
884 int fixed_p;
885};
886
887/* Compute the current size of a read/write packet. Since this makes
888 use of ``actual_register_packet_size'' the computation is dynamic. */
889
890static long
891get_memory_packet_size (struct memory_packet_config *config)
892{
d01949b6 893 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
894 struct remote_arch_state *rsa = get_remote_arch_state ();
895
11cf8741
JM
896 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
897 law?) that some hosts don't cope very well with large alloca()
898 calls. Eventually the alloca() code will be replaced by calls to
899 xmalloc() and make_cleanups() allowing this restriction to either
23860348 900 be lifted or removed. */
11cf8741
JM
901#ifndef MAX_REMOTE_PACKET_SIZE
902#define MAX_REMOTE_PACKET_SIZE 16384
903#endif
3de11b2e 904 /* NOTE: 20 ensures we can write at least one byte. */
11cf8741 905#ifndef MIN_REMOTE_PACKET_SIZE
3de11b2e 906#define MIN_REMOTE_PACKET_SIZE 20
11cf8741
JM
907#endif
908 long what_they_get;
909 if (config->fixed_p)
910 {
911 if (config->size <= 0)
912 what_they_get = MAX_REMOTE_PACKET_SIZE;
913 else
914 what_they_get = config->size;
915 }
916 else
917 {
ea9c271d 918 what_they_get = get_remote_packet_size ();
23860348 919 /* Limit the packet to the size specified by the user. */
11cf8741
JM
920 if (config->size > 0
921 && what_they_get > config->size)
922 what_they_get = config->size;
be2a5f71
DJ
923
924 /* Limit it to the size of the targets ``g'' response unless we have
925 permission from the stub to use a larger packet size. */
926 if (rs->explicit_packet_size == 0
927 && rsa->actual_register_packet_size > 0
928 && what_they_get > rsa->actual_register_packet_size)
929 what_they_get = rsa->actual_register_packet_size;
11cf8741
JM
930 }
931 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
932 what_they_get = MAX_REMOTE_PACKET_SIZE;
933 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
934 what_they_get = MIN_REMOTE_PACKET_SIZE;
6d820c5c
DJ
935
936 /* Make sure there is room in the global buffer for this packet
937 (including its trailing NUL byte). */
938 if (rs->buf_size < what_they_get + 1)
939 {
940 rs->buf_size = 2 * what_they_get;
941 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
942 }
943
11cf8741
JM
944 return what_they_get;
945}
946
0df8b418 947/* Update the size of a read/write packet. If they user wants
23860348 948 something really big then do a sanity check. */
11cf8741
JM
949
950static void
951set_memory_packet_size (char *args, struct memory_packet_config *config)
952{
953 int fixed_p = config->fixed_p;
954 long size = config->size;
a744cf53 955
11cf8741 956 if (args == NULL)
8a3fe4f8 957 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
958 else if (strcmp (args, "hard") == 0
959 || strcmp (args, "fixed") == 0)
960 fixed_p = 1;
961 else if (strcmp (args, "soft") == 0
962 || strcmp (args, "limit") == 0)
963 fixed_p = 0;
964 else
965 {
966 char *end;
a744cf53 967
11cf8741
JM
968 size = strtoul (args, &end, 0);
969 if (args == end)
8a3fe4f8 970 error (_("Invalid %s (bad syntax)."), config->name);
11cf8741
JM
971#if 0
972 /* Instead of explicitly capping the size of a packet to
973 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
974 instead allowed to set the size to something arbitrarily
23860348 975 large. */
11cf8741 976 if (size > MAX_REMOTE_PACKET_SIZE)
8a3fe4f8 977 error (_("Invalid %s (too large)."), config->name);
11cf8741
JM
978#endif
979 }
23860348 980 /* Extra checks? */
11cf8741
JM
981 if (fixed_p && !config->fixed_p)
982 {
e2e0b3e5
AC
983 if (! query (_("The target may not be able to correctly handle a %s\n"
984 "of %ld bytes. Change the packet size? "),
11cf8741 985 config->name, size))
8a3fe4f8 986 error (_("Packet size not changed."));
11cf8741 987 }
23860348 988 /* Update the config. */
11cf8741
JM
989 config->fixed_p = fixed_p;
990 config->size = size;
991}
992
993static void
994show_memory_packet_size (struct memory_packet_config *config)
995{
a3f17187 996 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 997 if (config->fixed_p)
a3f17187 998 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
999 get_memory_packet_size (config));
1000 else
a3f17187 1001 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
1002 get_memory_packet_size (config));
1003}
1004
1005static struct memory_packet_config memory_write_packet_config =
1006{
1007 "memory-write-packet-size",
1008};
1009
1010static void
1011set_memory_write_packet_size (char *args, int from_tty)
1012{
1013 set_memory_packet_size (args, &memory_write_packet_config);
1014}
1015
1016static void
1017show_memory_write_packet_size (char *args, int from_tty)
1018{
1019 show_memory_packet_size (&memory_write_packet_config);
1020}
1021
1022static long
1023get_memory_write_packet_size (void)
1024{
1025 return get_memory_packet_size (&memory_write_packet_config);
1026}
1027
1028static struct memory_packet_config memory_read_packet_config =
1029{
1030 "memory-read-packet-size",
1031};
1032
1033static void
1034set_memory_read_packet_size (char *args, int from_tty)
1035{
1036 set_memory_packet_size (args, &memory_read_packet_config);
1037}
1038
1039static void
1040show_memory_read_packet_size (char *args, int from_tty)
1041{
1042 show_memory_packet_size (&memory_read_packet_config);
1043}
1044
1045static long
1046get_memory_read_packet_size (void)
1047{
1048 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1049
11cf8741
JM
1050 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1051 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1052 increased beyond this. */
1053 if (size > get_remote_packet_size ())
1054 size = get_remote_packet_size ();
11cf8741
JM
1055 return size;
1056}
1057
11cf8741 1058\f
5a2468f5 1059/* Generic configuration support for packets the stub optionally
0df8b418 1060 supports. Allows the user to specify the use of the packet as well
23860348 1061 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1062
1063enum packet_support
1064 {
1065 PACKET_SUPPORT_UNKNOWN = 0,
1066 PACKET_ENABLE,
1067 PACKET_DISABLE
1068 };
1069
5a2468f5
JM
1070struct packet_config
1071 {
bb572ddd
DJ
1072 const char *name;
1073 const char *title;
4082afcc
PA
1074
1075 /* If auto, GDB auto-detects support for this packet or feature,
1076 either through qSupported, or by trying the packet and looking
1077 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1078 packet. If false, the packet is disabled. Configs that don't
1079 have an associated command always have this set to auto. */
7f19b9a2 1080 enum auto_boolean detect;
4082afcc
PA
1081
1082 /* Does the target support this packet? */
5a2468f5
JM
1083 enum packet_support support;
1084 };
1085
d471ea57 1086/* Analyze a packet's return value and update the packet config
23860348 1087 accordingly. */
d471ea57
AC
1088
1089enum packet_result
1090{
1091 PACKET_ERROR,
1092 PACKET_OK,
1093 PACKET_UNKNOWN
1094};
1095
4082afcc
PA
1096static enum packet_support packet_config_support (struct packet_config *config);
1097static enum packet_support packet_support (int packet);
5a2468f5
JM
1098
1099static void
fba45db2 1100show_packet_config_cmd (struct packet_config *config)
5a2468f5
JM
1101{
1102 char *support = "internal-error";
a744cf53 1103
4082afcc 1104 switch (packet_config_support (config))
5a2468f5
JM
1105 {
1106 case PACKET_ENABLE:
1107 support = "enabled";
1108 break;
1109 case PACKET_DISABLE:
1110 support = "disabled";
1111 break;
1112 case PACKET_SUPPORT_UNKNOWN:
1113 support = "unknown";
1114 break;
1115 }
1116 switch (config->detect)
1117 {
7f19b9a2 1118 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1119 printf_filtered (_("Support for the `%s' packet "
1120 "is auto-detected, currently %s.\n"),
37a105a1 1121 config->name, support);
5a2468f5 1122 break;
7f19b9a2
AC
1123 case AUTO_BOOLEAN_TRUE:
1124 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1125 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1126 config->name, support);
8e248173 1127 break;
5a2468f5
JM
1128 }
1129}
1130
1131static void
bb572ddd
DJ
1132add_packet_config_cmd (struct packet_config *config, const char *name,
1133 const char *title, int legacy)
d471ea57 1134{
5a2468f5
JM
1135 char *set_doc;
1136 char *show_doc;
d471ea57 1137 char *cmd_name;
3ed07be4 1138
5a2468f5
JM
1139 config->name = name;
1140 config->title = title;
b435e160
AC
1141 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1142 name, title);
3e43a32a
MS
1143 show_doc = xstrprintf ("Show current use of remote "
1144 "protocol `%s' (%s) packet",
b435e160 1145 name, title);
d471ea57 1146 /* set/show TITLE-packet {auto,on,off} */
b435e160 1147 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1148 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1149 &config->detect, set_doc,
1150 show_doc, NULL, /* help_doc */
4082afcc 1151 NULL,
bb572ddd
DJ
1152 show_remote_protocol_packet_cmd,
1153 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1154 /* The command code copies the documentation strings. */
1155 xfree (set_doc);
1156 xfree (show_doc);
23860348 1157 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1158 if (legacy)
1159 {
1160 char *legacy_name;
a744cf53 1161
b435e160 1162 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1163 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1164 &remote_set_cmdlist);
d471ea57 1165 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1166 &remote_show_cmdlist);
d471ea57 1167 }
5a2468f5
JM
1168}
1169
d471ea57 1170static enum packet_result
a76d924d 1171packet_check_result (const char *buf)
5a2468f5 1172{
d471ea57 1173 if (buf[0] != '\0')
5a2468f5 1174 {
d471ea57 1175 /* The stub recognized the packet request. Check that the
23860348 1176 operation succeeded. */
a76d924d
DJ
1177 if (buf[0] == 'E'
1178 && isxdigit (buf[1]) && isxdigit (buf[2])
1179 && buf[3] == '\0')
1180 /* "Enn" - definitly an error. */
1181 return PACKET_ERROR;
1182
1183 /* Always treat "E." as an error. This will be used for
1184 more verbose error messages, such as E.memtypes. */
1185 if (buf[0] == 'E' && buf[1] == '.')
1186 return PACKET_ERROR;
1187
1188 /* The packet may or may not be OK. Just assume it is. */
1189 return PACKET_OK;
1190 }
1191 else
1192 /* The stub does not support the packet. */
1193 return PACKET_UNKNOWN;
1194}
1195
1196static enum packet_result
1197packet_ok (const char *buf, struct packet_config *config)
1198{
1199 enum packet_result result;
1200
4082afcc
PA
1201 if (config->detect != AUTO_BOOLEAN_TRUE
1202 && config->support == PACKET_DISABLE)
1203 internal_error (__FILE__, __LINE__,
1204 _("packet_ok: attempt to use a disabled packet"));
1205
a76d924d
DJ
1206 result = packet_check_result (buf);
1207 switch (result)
1208 {
1209 case PACKET_OK:
1210 case PACKET_ERROR:
1211 /* The stub recognized the packet request. */
4082afcc 1212 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1213 {
d471ea57
AC
1214 if (remote_debug)
1215 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1216 "Packet %s (%s) is supported\n",
1217 config->name, config->title);
d471ea57 1218 config->support = PACKET_ENABLE;
d471ea57 1219 }
a76d924d
DJ
1220 break;
1221 case PACKET_UNKNOWN:
23860348 1222 /* The stub does not support the packet. */
4082afcc
PA
1223 if (config->detect == AUTO_BOOLEAN_AUTO
1224 && config->support == PACKET_ENABLE)
d471ea57 1225 {
4082afcc
PA
1226 /* If the stub previously indicated that the packet was
1227 supported then there is a protocol error. */
1228 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1229 config->name, config->title);
1230 }
1231 else if (config->detect == AUTO_BOOLEAN_TRUE)
1232 {
1233 /* The user set it wrong. */
1234 error (_("Enabled packet %s (%s) not recognized by stub"),
1235 config->name, config->title);
d471ea57 1236 }
4082afcc
PA
1237
1238 if (remote_debug)
1239 fprintf_unfiltered (gdb_stdlog,
1240 "Packet %s (%s) is NOT supported\n",
1241 config->name, config->title);
1242 config->support = PACKET_DISABLE;
a76d924d 1243 break;
5a2468f5 1244 }
a76d924d
DJ
1245
1246 return result;
5a2468f5
JM
1247}
1248
444abaca
DJ
1249enum {
1250 PACKET_vCont = 0,
1251 PACKET_X,
1252 PACKET_qSymbol,
1253 PACKET_P,
1254 PACKET_p,
1255 PACKET_Z0,
1256 PACKET_Z1,
1257 PACKET_Z2,
1258 PACKET_Z3,
1259 PACKET_Z4,
15a201c8 1260 PACKET_vFile_setfs,
a6b151f1
DJ
1261 PACKET_vFile_open,
1262 PACKET_vFile_pread,
1263 PACKET_vFile_pwrite,
1264 PACKET_vFile_close,
1265 PACKET_vFile_unlink,
b9e7b9c3 1266 PACKET_vFile_readlink,
0a93529c 1267 PACKET_vFile_fstat,
0876f84a 1268 PACKET_qXfer_auxv,
23181151 1269 PACKET_qXfer_features,
c78fa86a 1270 PACKET_qXfer_exec_file,
cfa9d6d9 1271 PACKET_qXfer_libraries,
2268b414 1272 PACKET_qXfer_libraries_svr4,
fd79ecee 1273 PACKET_qXfer_memory_map,
0e7f50da
UW
1274 PACKET_qXfer_spu_read,
1275 PACKET_qXfer_spu_write,
07e059b5 1276 PACKET_qXfer_osdata,
dc146f7c 1277 PACKET_qXfer_threads,
0fb4aa4b 1278 PACKET_qXfer_statictrace_read,
b3b9301e 1279 PACKET_qXfer_traceframe_info,
169081d0 1280 PACKET_qXfer_uib,
711e434b 1281 PACKET_qGetTIBAddr,
444abaca 1282 PACKET_qGetTLSAddr,
be2a5f71 1283 PACKET_qSupported,
bd3eecc3 1284 PACKET_qTStatus,
89be2091 1285 PACKET_QPassSignals,
9b224c5e 1286 PACKET_QProgramSignals,
936d2992 1287 PACKET_qCRC,
08388c79 1288 PACKET_qSearch_memory,
2d717e4f
DJ
1289 PACKET_vAttach,
1290 PACKET_vRun,
a6f3e723 1291 PACKET_QStartNoAckMode,
82f73884 1292 PACKET_vKill,
4aa995e1
PA
1293 PACKET_qXfer_siginfo_read,
1294 PACKET_qXfer_siginfo_write,
0b16c5cf 1295 PACKET_qAttached,
4082afcc
PA
1296
1297 /* Support for conditional tracepoints. */
782b2b07 1298 PACKET_ConditionalTracepoints,
4082afcc
PA
1299
1300 /* Support for target-side breakpoint conditions. */
3788aec7 1301 PACKET_ConditionalBreakpoints,
4082afcc
PA
1302
1303 /* Support for target-side breakpoint commands. */
d3ce09f5 1304 PACKET_BreakpointCommands,
4082afcc
PA
1305
1306 /* Support for fast tracepoints. */
7a697b8d 1307 PACKET_FastTracepoints,
4082afcc
PA
1308
1309 /* Support for static tracepoints. */
0fb4aa4b 1310 PACKET_StaticTracepoints,
4082afcc
PA
1311
1312 /* Support for installing tracepoints while a trace experiment is
1313 running. */
1e4d1764 1314 PACKET_InstallInTrace,
4082afcc 1315
40ab02ce
MS
1316 PACKET_bc,
1317 PACKET_bs,
409873ef 1318 PACKET_TracepointSource,
d914c394 1319 PACKET_QAllow,
78d85199 1320 PACKET_qXfer_fdpic,
03583c20 1321 PACKET_QDisableRandomization,
d1feda86 1322 PACKET_QAgent,
f6f899bf 1323 PACKET_QTBuffer_size,
9accd112
MM
1324 PACKET_Qbtrace_off,
1325 PACKET_Qbtrace_bts,
b20a6524 1326 PACKET_Qbtrace_pt,
9accd112 1327 PACKET_qXfer_btrace,
4082afcc
PA
1328
1329 /* Support for the QNonStop packet. */
1330 PACKET_QNonStop,
1331
1332 /* Support for multi-process extensions. */
1333 PACKET_multiprocess_feature,
1334
1335 /* Support for enabling and disabling tracepoints while a trace
1336 experiment is running. */
1337 PACKET_EnableDisableTracepoints_feature,
1338
1339 /* Support for collecting strings using the tracenz bytecode. */
1340 PACKET_tracenz_feature,
1341
1342 /* Support for continuing to run a trace experiment while GDB is
1343 disconnected. */
1344 PACKET_DisconnectedTracing_feature,
1345
1346 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1347 PACKET_augmented_libraries_svr4_read_feature,
1348
f4abbc16
MM
1349 /* Support for the qXfer:btrace-conf:read packet. */
1350 PACKET_qXfer_btrace_conf,
1351
d33501a5
MM
1352 /* Support for the Qbtrace-conf:bts:size packet. */
1353 PACKET_Qbtrace_conf_bts_size,
1354
f7e6eed5
PA
1355 /* Support for swbreak+ feature. */
1356 PACKET_swbreak_feature,
1357
1358 /* Support for hwbreak+ feature. */
1359 PACKET_hwbreak_feature,
1360
89245bc0
DB
1361 /* Support for fork events. */
1362 PACKET_fork_event_feature,
1363
1364 /* Support for vfork events. */
1365 PACKET_vfork_event_feature,
1366
b20a6524
MM
1367 /* Support for the Qbtrace-conf:pt:size packet. */
1368 PACKET_Qbtrace_conf_pt_size,
1369
444abaca
DJ
1370 PACKET_MAX
1371};
506fb367 1372
444abaca 1373static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1374
f7e6eed5
PA
1375/* Returns the packet's corresponding "set remote foo-packet" command
1376 state. See struct packet_config for more details. */
1377
1378static enum auto_boolean
1379packet_set_cmd_state (int packet)
1380{
1381 return remote_protocol_packets[packet].detect;
1382}
1383
4082afcc
PA
1384/* Returns whether a given packet or feature is supported. This takes
1385 into account the state of the corresponding "set remote foo-packet"
1386 command, which may be used to bypass auto-detection. */
dc8acb97 1387
4082afcc
PA
1388static enum packet_support
1389packet_config_support (struct packet_config *config)
1390{
1391 switch (config->detect)
444abaca 1392 {
4082afcc
PA
1393 case AUTO_BOOLEAN_TRUE:
1394 return PACKET_ENABLE;
1395 case AUTO_BOOLEAN_FALSE:
1396 return PACKET_DISABLE;
1397 case AUTO_BOOLEAN_AUTO:
1398 return config->support;
1399 default:
1400 gdb_assert_not_reached (_("bad switch"));
444abaca 1401 }
4082afcc
PA
1402}
1403
1404/* Same as packet_config_support, but takes the packet's enum value as
1405 argument. */
1406
1407static enum packet_support
1408packet_support (int packet)
1409{
1410 struct packet_config *config = &remote_protocol_packets[packet];
1411
1412 return packet_config_support (config);
dc8acb97
MS
1413}
1414
5a2468f5 1415static void
444abaca
DJ
1416show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1417 struct cmd_list_element *c,
1418 const char *value)
5a2468f5 1419{
444abaca 1420 struct packet_config *packet;
5a2468f5 1421
444abaca
DJ
1422 for (packet = remote_protocol_packets;
1423 packet < &remote_protocol_packets[PACKET_MAX];
1424 packet++)
1425 {
1426 if (&packet->detect == c->var)
1427 {
1428 show_packet_config_cmd (packet);
1429 return;
1430 }
1431 }
9b20d036 1432 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1433 c->name);
5a2468f5
JM
1434}
1435
d471ea57
AC
1436/* Should we try one of the 'Z' requests? */
1437
1438enum Z_packet_type
1439{
1440 Z_PACKET_SOFTWARE_BP,
1441 Z_PACKET_HARDWARE_BP,
1442 Z_PACKET_WRITE_WP,
1443 Z_PACKET_READ_WP,
1444 Z_PACKET_ACCESS_WP,
1445 NR_Z_PACKET_TYPES
1446};
96baa820 1447
d471ea57 1448/* For compatibility with older distributions. Provide a ``set remote
23860348 1449 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1450
7f19b9a2 1451static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1452
1453static void
fba45db2
KB
1454set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1455 struct cmd_list_element *c)
96baa820 1456{
d471ea57 1457 int i;
a744cf53 1458
d471ea57 1459 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1460 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1461}
1462
1463static void
08546159
AC
1464show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1465 struct cmd_list_element *c,
1466 const char *value)
96baa820 1467{
d471ea57 1468 int i;
a744cf53 1469
d471ea57
AC
1470 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1471 {
444abaca 1472 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1473 }
96baa820
JM
1474}
1475
4082afcc
PA
1476/* Returns true if the multi-process extensions are in effect. */
1477
1478static int
1479remote_multi_process_p (struct remote_state *rs)
1480{
1481 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1482}
1483
de0d863e
DB
1484/* Returns true if fork events are supported. */
1485
1486static int
1487remote_fork_event_p (struct remote_state *rs)
1488{
1489 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1490}
1491
c269dbdb
DB
1492/* Returns true if vfork events are supported. */
1493
1494static int
1495remote_vfork_event_p (struct remote_state *rs)
1496{
1497 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1498}
1499
cbb8991c
DB
1500/* Insert fork catchpoint target routine. If fork events are enabled
1501 then return success, nothing more to do. */
1502
1503static int
1504remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1505{
1506 struct remote_state *rs = get_remote_state ();
1507
1508 return !remote_fork_event_p (rs);
1509}
1510
1511/* Remove fork catchpoint target routine. Nothing to do, just
1512 return success. */
1513
1514static int
1515remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1516{
1517 return 0;
1518}
1519
1520/* Insert vfork catchpoint target routine. If vfork events are enabled
1521 then return success, nothing more to do. */
1522
1523static int
1524remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1525{
1526 struct remote_state *rs = get_remote_state ();
1527
1528 return !remote_vfork_event_p (rs);
1529}
1530
1531/* Remove vfork catchpoint target routine. Nothing to do, just
1532 return success. */
1533
1534static int
1535remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1536{
1537 return 0;
1538}
1539
23860348 1540/* Tokens for use by the asynchronous signal handlers for SIGINT. */
934b9bac
JK
1541static struct async_signal_handler *async_sigint_remote_twice_token;
1542static struct async_signal_handler *async_sigint_remote_token;
43ff13b4 1543
74531fed
PA
1544\f
1545/* Asynchronous signal handle registered as event loop source for
1546 when we have pending events ready to be passed to the core. */
1547
1548static struct async_event_handler *remote_async_inferior_event_token;
1549
c906108c
SS
1550\f
1551
79d7f229
PA
1552static ptid_t magic_null_ptid;
1553static ptid_t not_sent_ptid;
1554static ptid_t any_thread_ptid;
1555
0b16c5cf
PA
1556/* Find out if the stub attached to PID (and hence GDB should offer to
1557 detach instead of killing it when bailing out). */
1558
1559static int
1560remote_query_attached (int pid)
1561{
1562 struct remote_state *rs = get_remote_state ();
bba74b36 1563 size_t size = get_remote_packet_size ();
0b16c5cf 1564
4082afcc 1565 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1566 return 0;
1567
1568 if (remote_multi_process_p (rs))
bba74b36 1569 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1570 else
bba74b36 1571 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1572
1573 putpkt (rs->buf);
1574 getpkt (&rs->buf, &rs->buf_size, 0);
1575
1576 switch (packet_ok (rs->buf,
1554e9be 1577 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1578 {
1579 case PACKET_OK:
1580 if (strcmp (rs->buf, "1") == 0)
1581 return 1;
1582 break;
1583 case PACKET_ERROR:
1584 warning (_("Remote failure reply: %s"), rs->buf);
1585 break;
1586 case PACKET_UNKNOWN:
1587 break;
1588 }
1589
1590 return 0;
1591}
1592
49c62f2e
PA
1593/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1594 has been invented by GDB, instead of reported by the target. Since
1595 we can be connected to a remote system before before knowing about
1596 any inferior, mark the target with execution when we find the first
1597 inferior. If ATTACHED is 1, then we had just attached to this
1598 inferior. If it is 0, then we just created this inferior. If it
1599 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
1600 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1601 attempt to open this inferior's executable as the main executable
1602 if no main executable is open already. */
1941c569
PA
1603
1604static struct inferior *
1b6e6f5c
GB
1605remote_add_inferior (int fake_pid_p, int pid, int attached,
1606 int try_open_exec)
1941c569 1607{
1941c569
PA
1608 struct inferior *inf;
1609
0b16c5cf
PA
1610 /* Check whether this process we're learning about is to be
1611 considered attached, or if is to be considered to have been
1612 spawned by the stub. */
1613 if (attached == -1)
1614 attached = remote_query_attached (pid);
1615
f5656ead 1616 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1617 {
1618 /* If the target shares code across all inferiors, then every
1619 attach adds a new inferior. */
1620 inf = add_inferior (pid);
1621
1622 /* ... and every inferior is bound to the same program space.
1623 However, each inferior may still have its own address
1624 space. */
1625 inf->aspace = maybe_new_address_space ();
1626 inf->pspace = current_program_space;
1627 }
1628 else
1629 {
1630 /* In the traditional debugging scenario, there's a 1-1 match
1631 between program/address spaces. We simply bind the inferior
1632 to the program space's address space. */
1633 inf = current_inferior ();
1634 inferior_appeared (inf, pid);
1635 }
1941c569 1636
0b16c5cf 1637 inf->attach_flag = attached;
49c62f2e 1638 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1639
1b6e6f5c
GB
1640 /* If no main executable is currently open then attempt to
1641 open the file that was executed to create this inferior. */
835205d0 1642 if (try_open_exec && get_exec_file (0) == NULL)
1b6e6f5c
GB
1643 exec_file_locate_attach (pid, 1);
1644
1941c569
PA
1645 return inf;
1646}
1647
1648/* Add thread PTID to GDB's thread list. Tag it as executing/running
1649 according to RUNNING. */
1650
c906108c 1651static void
1941c569 1652remote_add_thread (ptid_t ptid, int running)
c906108c 1653{
b7ea362b
PA
1654 struct remote_state *rs = get_remote_state ();
1655
1656 /* GDB historically didn't pull threads in the initial connection
1657 setup. If the remote target doesn't even have a concept of
1658 threads (e.g., a bare-metal target), even if internally we
1659 consider that a single-threaded target, mentioning a new thread
1660 might be confusing to the user. Be silent then, preserving the
1661 age old behavior. */
1662 if (rs->starting_up)
1663 add_thread_silent (ptid);
1664 else
1665 add_thread (ptid);
1941c569
PA
1666
1667 set_executing (ptid, running);
1668 set_running (ptid, running);
1669}
1670
1671/* Come here when we learn about a thread id from the remote target.
1672 It may be the first time we hear about such thread, so take the
1673 opportunity to add it to GDB's thread list. In case this is the
1674 first time we're noticing its corresponding inferior, add it to
1675 GDB's inferior list as well. */
1676
1677static void
1678remote_notice_new_inferior (ptid_t currthread, int running)
1679{
c906108c
SS
1680 /* If this is a new thread, add it to GDB's thread list.
1681 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1682
1683 if (in_thread_list (currthread) && is_exited (currthread))
1684 {
1685 /* We're seeing an event on a thread id we knew had exited.
1686 This has to be a new thread reusing the old id. Add it. */
1941c569 1687 remote_add_thread (currthread, running);
82f73884
PA
1688 return;
1689 }
1690
79d7f229 1691 if (!in_thread_list (currthread))
c0a2216e 1692 {
1941c569 1693 struct inferior *inf = NULL;
bad34192 1694 int pid = ptid_get_pid (currthread);
1941c569 1695
bad34192
PA
1696 if (ptid_is_pid (inferior_ptid)
1697 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1698 {
1699 /* inferior_ptid has no thread member yet. This can happen
1700 with the vAttach -> remote_wait,"TAAthread:" path if the
1701 stub doesn't support qC. This is the first stop reported
1702 after an attach, so this is the main thread. Update the
1703 ptid in the thread list. */
bad34192
PA
1704 if (in_thread_list (pid_to_ptid (pid)))
1705 thread_change_ptid (inferior_ptid, currthread);
1706 else
1707 {
1708 remote_add_thread (currthread, running);
1709 inferior_ptid = currthread;
1710 }
dc146f7c 1711 return;
c0a2216e 1712 }
82f73884
PA
1713
1714 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1715 {
1716 /* inferior_ptid is not set yet. This can happen with the
1717 vRun -> remote_wait,"TAAthread:" path if the stub
1718 doesn't support qC. This is the first stop reported
1719 after an attach, so this is the main thread. Update the
1720 ptid in the thread list. */
dc146f7c 1721 thread_change_ptid (inferior_ptid, currthread);
82f73884 1722 return;
c0a2216e 1723 }
82f73884 1724
29c87f7f
PA
1725 /* When connecting to a target remote, or to a target
1726 extended-remote which already was debugging an inferior, we
1727 may not know about it yet. Add it before adding its child
1728 thread, so notifications are emitted in a sensible order. */
1729 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1730 {
1731 struct remote_state *rs = get_remote_state ();
1732 int fake_pid_p = !remote_multi_process_p (rs);
1733
1734 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 1735 ptid_get_pid (currthread), -1, 1);
49c62f2e 1736 }
29c87f7f 1737
82f73884 1738 /* This is really a new thread. Add it. */
1941c569
PA
1739 remote_add_thread (currthread, running);
1740
1741 /* If we found a new inferior, let the common code do whatever
1742 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1743 breakpoints), unless we're just setting up an all-stop
1744 connection. */
1941c569 1745 if (inf != NULL)
b7ea362b
PA
1746 {
1747 struct remote_state *rs = get_remote_state ();
1748
1749 if (non_stop || !rs->starting_up)
1750 notice_new_inferior (currthread, running, 0);
1751 }
c0a2216e 1752 }
c906108c
SS
1753}
1754
dc146f7c
VP
1755/* Return the private thread data, creating it if necessary. */
1756
70221824 1757static struct private_thread_info *
dc146f7c
VP
1758demand_private_info (ptid_t ptid)
1759{
1760 struct thread_info *info = find_thread_ptid (ptid);
1761
1762 gdb_assert (info);
1763
fe978cb0 1764 if (!info->priv)
dc146f7c 1765 {
fe978cb0 1766 info->priv = xmalloc (sizeof (*(info->priv)));
dc146f7c 1767 info->private_dtor = free_private_thread_info;
fe978cb0
PA
1768 info->priv->core = -1;
1769 info->priv->extra = 0;
dc146f7c
VP
1770 }
1771
fe978cb0 1772 return info->priv;
dc146f7c
VP
1773}
1774
74531fed
PA
1775/* Call this function as a result of
1776 1) A halt indication (T packet) containing a thread id
1777 2) A direct query of currthread
0df8b418 1778 3) Successful execution of set thread */
74531fed
PA
1779
1780static void
47f8a51d 1781record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1782{
47f8a51d 1783 rs->general_thread = currthread;
74531fed
PA
1784}
1785
89be2091
DJ
1786/* If 'QPassSignals' is supported, tell the remote stub what signals
1787 it can simply pass through to the inferior without reporting. */
1788
1789static void
94bedb42
TT
1790remote_pass_signals (struct target_ops *self,
1791 int numsigs, unsigned char *pass_signals)
89be2091 1792{
4082afcc 1793 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
1794 {
1795 char *pass_packet, *p;
89be2091 1796 int count = 0, i;
747dc59d 1797 struct remote_state *rs = get_remote_state ();
89be2091
DJ
1798
1799 gdb_assert (numsigs < 256);
1800 for (i = 0; i < numsigs; i++)
1801 {
2455069d 1802 if (pass_signals[i])
89be2091
DJ
1803 count++;
1804 }
1805 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1806 strcpy (pass_packet, "QPassSignals:");
1807 p = pass_packet + strlen (pass_packet);
1808 for (i = 0; i < numsigs; i++)
1809 {
2455069d 1810 if (pass_signals[i])
89be2091
DJ
1811 {
1812 if (i >= 16)
1813 *p++ = tohex (i >> 4);
1814 *p++ = tohex (i & 15);
1815 if (count)
1816 *p++ = ';';
1817 else
1818 break;
1819 count--;
1820 }
1821 }
1822 *p = 0;
747dc59d 1823 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 1824 {
89be2091
DJ
1825 putpkt (pass_packet);
1826 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1827 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
1828 if (rs->last_pass_packet)
1829 xfree (rs->last_pass_packet);
1830 rs->last_pass_packet = pass_packet;
89be2091
DJ
1831 }
1832 else
1833 xfree (pass_packet);
1834 }
1835}
1836
9b224c5e
PA
1837/* If 'QProgramSignals' is supported, tell the remote stub what
1838 signals it should pass through to the inferior when detaching. */
1839
1840static void
daf5e9b6
TT
1841remote_program_signals (struct target_ops *self,
1842 int numsigs, unsigned char *signals)
9b224c5e 1843{
4082afcc 1844 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
1845 {
1846 char *packet, *p;
1847 int count = 0, i;
5e4a05c4 1848 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
1849
1850 gdb_assert (numsigs < 256);
1851 for (i = 0; i < numsigs; i++)
1852 {
1853 if (signals[i])
1854 count++;
1855 }
1856 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1857 strcpy (packet, "QProgramSignals:");
1858 p = packet + strlen (packet);
1859 for (i = 0; i < numsigs; i++)
1860 {
1861 if (signal_pass_state (i))
1862 {
1863 if (i >= 16)
1864 *p++ = tohex (i >> 4);
1865 *p++ = tohex (i & 15);
1866 if (count)
1867 *p++ = ';';
1868 else
1869 break;
1870 count--;
1871 }
1872 }
1873 *p = 0;
5e4a05c4
TT
1874 if (!rs->last_program_signals_packet
1875 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 1876 {
9b224c5e
PA
1877 putpkt (packet);
1878 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1879 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
1880 xfree (rs->last_program_signals_packet);
1881 rs->last_program_signals_packet = packet;
9b224c5e
PA
1882 }
1883 else
1884 xfree (packet);
1885 }
1886}
1887
79d7f229
PA
1888/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1889 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1890 thread. If GEN is set, set the general thread, if not, then set
1891 the step/continue thread. */
c906108c 1892static void
79d7f229 1893set_thread (struct ptid ptid, int gen)
c906108c 1894{
d01949b6 1895 struct remote_state *rs = get_remote_state ();
47f8a51d 1896 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 1897 char *buf = rs->buf;
79d7f229 1898 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 1899
79d7f229 1900 if (ptid_equal (state, ptid))
c906108c
SS
1901 return;
1902
79d7f229
PA
1903 *buf++ = 'H';
1904 *buf++ = gen ? 'g' : 'c';
1905 if (ptid_equal (ptid, magic_null_ptid))
1906 xsnprintf (buf, endbuf - buf, "0");
1907 else if (ptid_equal (ptid, any_thread_ptid))
1908 xsnprintf (buf, endbuf - buf, "0");
1909 else if (ptid_equal (ptid, minus_one_ptid))
1910 xsnprintf (buf, endbuf - buf, "-1");
1911 else
82f73884 1912 write_ptid (buf, endbuf, ptid);
79d7f229 1913 putpkt (rs->buf);
6d820c5c 1914 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 1915 if (gen)
47f8a51d 1916 rs->general_thread = ptid;
c906108c 1917 else
47f8a51d 1918 rs->continue_thread = ptid;
c906108c 1919}
79d7f229
PA
1920
1921static void
1922set_general_thread (struct ptid ptid)
1923{
1924 set_thread (ptid, 1);
1925}
1926
1927static void
1928set_continue_thread (struct ptid ptid)
1929{
1930 set_thread (ptid, 0);
1931}
1932
3c9c4b83
PA
1933/* Change the remote current process. Which thread within the process
1934 ends up selected isn't important, as long as it is the same process
1935 as what INFERIOR_PTID points to.
1936
1937 This comes from that fact that there is no explicit notion of
1938 "selected process" in the protocol. The selected process for
1939 general operations is the process the selected general thread
1940 belongs to. */
1941
1942static void
1943set_general_process (void)
1944{
1945 struct remote_state *rs = get_remote_state ();
1946
1947 /* If the remote can't handle multiple processes, don't bother. */
901f9912 1948 if (!rs->extended || !remote_multi_process_p (rs))
3c9c4b83
PA
1949 return;
1950
1951 /* We only need to change the remote current thread if it's pointing
1952 at some other process. */
47f8a51d 1953 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
1954 set_general_thread (inferior_ptid);
1955}
1956
c906108c 1957\f
7d1a114c
PA
1958/* Return nonzero if this is the main thread that we made up ourselves
1959 to model non-threaded targets as single-threaded. */
c906108c
SS
1960
1961static int
7d1a114c 1962remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 1963{
6d820c5c 1964 struct remote_state *rs = get_remote_state ();
82f73884 1965 char *p, *endp;
c906108c 1966
c0a2216e
PA
1967 if (ptid_equal (ptid, magic_null_ptid))
1968 /* The main thread is always alive. */
1969 return 1;
1970
ba348170 1971 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
1972 /* The main thread is always alive. This can happen after a
1973 vAttach, if the remote side doesn't support
1974 multi-threading. */
1975 return 1;
1976
7d1a114c
PA
1977 return 0;
1978}
1979
1980/* Return nonzero if the thread PTID is still alive on the remote
1981 system. */
1982
1983static int
1984remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1985{
1986 struct remote_state *rs = get_remote_state ();
1987 char *p, *endp;
1988
1989 /* Check if this is a thread that we made up ourselves to model
1990 non-threaded targets as single-threaded. */
1991 if (remote_thread_always_alive (ops, ptid))
1992 return 1;
1993
82f73884
PA
1994 p = rs->buf;
1995 endp = rs->buf + get_remote_packet_size ();
1996
1997 *p++ = 'T';
1998 write_ptid (p, endp, ptid);
1999
2e9f7625 2000 putpkt (rs->buf);
6d820c5c 2001 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2002 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2003}
2004
2005/* About these extended threadlist and threadinfo packets. They are
2006 variable length packets but, the fields within them are often fixed
2007 length. They are redundent enough to send over UDP as is the
2008 remote protocol in general. There is a matching unit test module
2009 in libstub. */
2010
23860348 2011/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2012 libstub protocol encoding, and remote.c. It is not particularly
23860348 2013 changable. */
cce74817
JM
2014
2015/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2016 Plan to fix this. */
cce74817 2017
23860348 2018typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2019
9d1f7ab2 2020/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2021 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2022
2023struct gdb_ext_thread_info
c5aa993b 2024 {
23860348 2025 threadref threadid; /* External form of thread reference. */
2bc416ba 2026 int active; /* Has state interesting to GDB?
23860348 2027 regs, stack. */
2bc416ba 2028 char display[256]; /* Brief state display, name,
cedea757 2029 blocked/suspended. */
23860348 2030 char shortname[32]; /* To be used to name threads. */
2bc416ba 2031 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2032 whatever. */
c5aa993b 2033 };
cce74817
JM
2034
2035/* The volume of remote transfers can be limited by submitting
2036 a mask containing bits specifying the desired information.
2037 Use a union of these values as the 'selection' parameter to
0df8b418 2038 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2039
2040#define TAG_THREADID 1
2041#define TAG_EXISTS 2
2042#define TAG_DISPLAY 4
2043#define TAG_THREADNAME 8
c5aa993b 2044#define TAG_MOREDISPLAY 16
cce74817 2045
23860348 2046#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2047
a14ed312 2048static char *unpack_nibble (char *buf, int *val);
cce74817 2049
a14ed312 2050static char *unpack_byte (char *buf, int *value);
cce74817 2051
a14ed312 2052static char *pack_int (char *buf, int value);
cce74817 2053
a14ed312 2054static char *unpack_int (char *buf, int *value);
cce74817 2055
a14ed312 2056static char *unpack_string (char *src, char *dest, int length);
cce74817 2057
23860348 2058static char *pack_threadid (char *pkt, threadref *id);
cce74817 2059
23860348 2060static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2061
23860348 2062void int_to_threadref (threadref *id, int value);
cce74817 2063
23860348 2064static int threadref_to_int (threadref *ref);
cce74817 2065
23860348 2066static void copy_threadref (threadref *dest, threadref *src);
cce74817 2067
23860348 2068static int threadmatch (threadref *dest, threadref *src);
cce74817 2069
2bc416ba 2070static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2071 threadref *id);
cce74817 2072
a14ed312 2073static int remote_unpack_thread_info_response (char *pkt,
23860348 2074 threadref *expectedref,
a14ed312
KB
2075 struct gdb_ext_thread_info
2076 *info);
cce74817
JM
2077
2078
2bc416ba 2079static int remote_get_threadinfo (threadref *threadid,
23860348 2080 int fieldset, /*TAG mask */
a14ed312 2081 struct gdb_ext_thread_info *info);
cce74817 2082
a14ed312
KB
2083static char *pack_threadlist_request (char *pkt, int startflag,
2084 int threadcount,
23860348 2085 threadref *nextthread);
cce74817 2086
a14ed312
KB
2087static int parse_threadlist_response (char *pkt,
2088 int result_limit,
23860348 2089 threadref *original_echo,
2bc416ba 2090 threadref *resultlist,
23860348 2091 int *doneflag);
cce74817 2092
a14ed312 2093static int remote_get_threadlist (int startflag,
23860348 2094 threadref *nextthread,
a14ed312
KB
2095 int result_limit,
2096 int *done,
2bc416ba 2097 int *result_count,
23860348 2098 threadref *threadlist);
cce74817 2099
23860348 2100typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2101
a14ed312
KB
2102static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2103 void *context, int looplimit);
cce74817 2104
23860348 2105static int remote_newthread_step (threadref *ref, void *context);
cce74817 2106
82f73884
PA
2107
2108/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2109 buffer we're allowed to write to. Returns
2110 BUF+CHARACTERS_WRITTEN. */
2111
2112static char *
2113write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2114{
2115 int pid, tid;
2116 struct remote_state *rs = get_remote_state ();
2117
2118 if (remote_multi_process_p (rs))
2119 {
2120 pid = ptid_get_pid (ptid);
2121 if (pid < 0)
2122 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2123 else
2124 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2125 }
ba348170 2126 tid = ptid_get_lwp (ptid);
82f73884
PA
2127 if (tid < 0)
2128 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2129 else
2130 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2131
2132 return buf;
2133}
2134
2135/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2136 passed the last parsed char. Returns null_ptid on error. */
2137
2138static ptid_t
2139read_ptid (char *buf, char **obuf)
2140{
2141 char *p = buf;
2142 char *pp;
2143 ULONGEST pid = 0, tid = 0;
82f73884
PA
2144
2145 if (*p == 'p')
2146 {
2147 /* Multi-process ptid. */
2148 pp = unpack_varlen_hex (p + 1, &pid);
2149 if (*pp != '.')
b37520b6 2150 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2151
2152 p = pp;
2153 pp = unpack_varlen_hex (p + 1, &tid);
2154 if (obuf)
2155 *obuf = pp;
ba348170 2156 return ptid_build (pid, tid, 0);
82f73884
PA
2157 }
2158
2159 /* No multi-process. Just a tid. */
2160 pp = unpack_varlen_hex (p, &tid);
2161
c9f35b34
KB
2162 /* Return null_ptid when no thread id is found. */
2163 if (p == pp)
2164 {
2165 if (obuf)
2166 *obuf = pp;
2167 return null_ptid;
2168 }
2169
82f73884 2170 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2171 what's in inferior_ptid, unless it's null at this point. If so,
2172 then since there's no way to know the pid of the reported
2173 threads, use the magic number. */
2174 if (ptid_equal (inferior_ptid, null_ptid))
2175 pid = ptid_get_pid (magic_null_ptid);
2176 else
2177 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2178
2179 if (obuf)
2180 *obuf = pp;
ba348170 2181 return ptid_build (pid, tid, 0);
82f73884
PA
2182}
2183
c906108c 2184static int
fba45db2 2185stubhex (int ch)
c906108c
SS
2186{
2187 if (ch >= 'a' && ch <= 'f')
2188 return ch - 'a' + 10;
2189 if (ch >= '0' && ch <= '9')
2190 return ch - '0';
2191 if (ch >= 'A' && ch <= 'F')
2192 return ch - 'A' + 10;
2193 return -1;
2194}
2195
2196static int
fba45db2 2197stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2198{
2199 int nibble;
2200 int retval = 0;
2201
2202 while (fieldlength)
2203 {
2204 nibble = stubhex (*buff++);
2205 retval |= nibble;
2206 fieldlength--;
2207 if (fieldlength)
2208 retval = retval << 4;
2209 }
2210 return retval;
2211}
2212
c906108c 2213static char *
fba45db2 2214unpack_nibble (char *buf, int *val)
c906108c 2215{
b7589f7d 2216 *val = fromhex (*buf++);
c906108c
SS
2217 return buf;
2218}
2219
c906108c 2220static char *
fba45db2 2221unpack_byte (char *buf, int *value)
c906108c
SS
2222{
2223 *value = stub_unpack_int (buf, 2);
2224 return buf + 2;
2225}
2226
2227static char *
fba45db2 2228pack_int (char *buf, int value)
c906108c
SS
2229{
2230 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2231 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2232 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2233 buf = pack_hex_byte (buf, (value & 0xff));
2234 return buf;
2235}
2236
2237static char *
fba45db2 2238unpack_int (char *buf, int *value)
c906108c
SS
2239{
2240 *value = stub_unpack_int (buf, 8);
2241 return buf + 8;
2242}
2243
23860348 2244#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2245static char *pack_string (char *pkt, char *string);
c906108c
SS
2246
2247static char *
fba45db2 2248pack_string (char *pkt, char *string)
c906108c
SS
2249{
2250 char ch;
2251 int len;
2252
2253 len = strlen (string);
2254 if (len > 200)
23860348 2255 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2256 pkt = pack_hex_byte (pkt, len);
2257 while (len-- > 0)
2258 {
2259 ch = *string++;
2260 if ((ch == '\0') || (ch == '#'))
23860348 2261 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2262 *pkt++ = ch;
2263 }
2264 return pkt;
2265}
2266#endif /* 0 (unused) */
2267
2268static char *
fba45db2 2269unpack_string (char *src, char *dest, int length)
c906108c
SS
2270{
2271 while (length--)
2272 *dest++ = *src++;
2273 *dest = '\0';
2274 return src;
2275}
2276
2277static char *
fba45db2 2278pack_threadid (char *pkt, threadref *id)
c906108c
SS
2279{
2280 char *limit;
2281 unsigned char *altid;
2282
2283 altid = (unsigned char *) id;
2284 limit = pkt + BUF_THREAD_ID_SIZE;
2285 while (pkt < limit)
2286 pkt = pack_hex_byte (pkt, *altid++);
2287 return pkt;
2288}
2289
2290
2291static char *
fba45db2 2292unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2293{
2294 char *altref;
2295 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2296 int x, y;
2297
2298 altref = (char *) id;
2299
2300 while (inbuf < limit)
2301 {
2302 x = stubhex (*inbuf++);
2303 y = stubhex (*inbuf++);
2304 *altref++ = (x << 4) | y;
2305 }
2306 return inbuf;
2307}
2308
2309/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2310 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2311 to use 64bit thread references internally. This is an adapter
2312 function. */
2313
2314void
fba45db2 2315int_to_threadref (threadref *id, int value)
c906108c
SS
2316{
2317 unsigned char *scan;
2318
2319 scan = (unsigned char *) id;
2320 {
2321 int i = 4;
2322 while (i--)
2323 *scan++ = 0;
2324 }
2325 *scan++ = (value >> 24) & 0xff;
2326 *scan++ = (value >> 16) & 0xff;
2327 *scan++ = (value >> 8) & 0xff;
2328 *scan++ = (value & 0xff);
2329}
2330
2331static int
fba45db2 2332threadref_to_int (threadref *ref)
c906108c
SS
2333{
2334 int i, value = 0;
2335 unsigned char *scan;
2336
cfd77fa1 2337 scan = *ref;
c906108c
SS
2338 scan += 4;
2339 i = 4;
2340 while (i-- > 0)
2341 value = (value << 8) | ((*scan++) & 0xff);
2342 return value;
2343}
2344
2345static void
fba45db2 2346copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2347{
2348 int i;
2349 unsigned char *csrc, *cdest;
2350
2351 csrc = (unsigned char *) src;
2352 cdest = (unsigned char *) dest;
2353 i = 8;
2354 while (i--)
2355 *cdest++ = *csrc++;
2356}
2357
2358static int
fba45db2 2359threadmatch (threadref *dest, threadref *src)
c906108c 2360{
23860348 2361 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2362#if 0
2363 unsigned char *srcp, *destp;
2364 int i, result;
2365 srcp = (char *) src;
2366 destp = (char *) dest;
2367
2368 result = 1;
2369 while (i-- > 0)
2370 result &= (*srcp++ == *destp++) ? 1 : 0;
2371 return result;
2372#endif
2373 return 1;
2374}
2375
2376/*
c5aa993b
JM
2377 threadid:1, # always request threadid
2378 context_exists:2,
2379 display:4,
2380 unique_name:8,
2381 more_display:16
2382 */
c906108c
SS
2383
2384/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2385
2386static char *
fba45db2 2387pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2388{
23860348
MS
2389 *pkt++ = 'q'; /* Info Query */
2390 *pkt++ = 'P'; /* process or thread info */
2391 pkt = pack_int (pkt, mode); /* mode */
c906108c 2392 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2393 *pkt = '\0'; /* terminate */
c906108c
SS
2394 return pkt;
2395}
2396
23860348 2397/* These values tag the fields in a thread info response packet. */
c906108c 2398/* Tagging the fields allows us to request specific fields and to
23860348 2399 add more fields as time goes by. */
c906108c 2400
23860348 2401#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2402#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2403 fetch registers and its stack? */
c5aa993b 2404#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2405#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2406#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2407 the process. */
c906108c
SS
2408
2409static int
fba45db2
KB
2410remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2411 struct gdb_ext_thread_info *info)
c906108c 2412{
d01949b6 2413 struct remote_state *rs = get_remote_state ();
c906108c 2414 int mask, length;
cfd77fa1 2415 int tag;
c906108c 2416 threadref ref;
6d820c5c 2417 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2418 int retval = 1;
2419
23860348 2420 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2421 info->active = 0;
2422 info->display[0] = '\0';
2423 info->shortname[0] = '\0';
2424 info->more_display[0] = '\0';
2425
23860348
MS
2426 /* Assume the characters indicating the packet type have been
2427 stripped. */
c906108c
SS
2428 pkt = unpack_int (pkt, &mask); /* arg mask */
2429 pkt = unpack_threadid (pkt, &ref);
2430
2431 if (mask == 0)
8a3fe4f8 2432 warning (_("Incomplete response to threadinfo request."));
c906108c 2433 if (!threadmatch (&ref, expectedref))
23860348 2434 { /* This is an answer to a different request. */
8a3fe4f8 2435 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2436 return 0;
2437 }
2438 copy_threadref (&info->threadid, &ref);
2439
23860348 2440 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2441
23860348
MS
2442 /* Packets are terminated with nulls. */
2443 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2444 {
2445 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2446 pkt = unpack_byte (pkt, &length); /* length */
2447 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2448 {
8a3fe4f8 2449 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2450 retval = 0;
2451 break;
2452 }
2453 if (tag == TAG_THREADID)
2454 {
2455 if (length != 16)
2456 {
8a3fe4f8 2457 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2458 retval = 0;
2459 break;
2460 }
2461 pkt = unpack_threadid (pkt, &ref);
2462 mask = mask & ~TAG_THREADID;
2463 continue;
2464 }
2465 if (tag == TAG_EXISTS)
2466 {
2467 info->active = stub_unpack_int (pkt, length);
2468 pkt += length;
2469 mask = mask & ~(TAG_EXISTS);
2470 if (length > 8)
2471 {
8a3fe4f8 2472 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2473 retval = 0;
2474 break;
2475 }
2476 continue;
2477 }
2478 if (tag == TAG_THREADNAME)
2479 {
2480 pkt = unpack_string (pkt, &info->shortname[0], length);
2481 mask = mask & ~TAG_THREADNAME;
2482 continue;
2483 }
2484 if (tag == TAG_DISPLAY)
2485 {
2486 pkt = unpack_string (pkt, &info->display[0], length);
2487 mask = mask & ~TAG_DISPLAY;
2488 continue;
2489 }
2490 if (tag == TAG_MOREDISPLAY)
2491 {
2492 pkt = unpack_string (pkt, &info->more_display[0], length);
2493 mask = mask & ~TAG_MOREDISPLAY;
2494 continue;
2495 }
8a3fe4f8 2496 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2497 break; /* Not a tag we know about. */
c906108c
SS
2498 }
2499 return retval;
2500}
2501
2502static int
fba45db2
KB
2503remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2504 struct gdb_ext_thread_info *info)
c906108c 2505{
d01949b6 2506 struct remote_state *rs = get_remote_state ();
c906108c 2507 int result;
c906108c 2508
2e9f7625
DJ
2509 pack_threadinfo_request (rs->buf, fieldset, threadid);
2510 putpkt (rs->buf);
6d820c5c 2511 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2512
2513 if (rs->buf[0] == '\0')
2514 return 0;
2515
2e9f7625 2516 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2517 threadid, info);
c906108c
SS
2518 return result;
2519}
2520
c906108c
SS
2521/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2522
2523static char *
fba45db2
KB
2524pack_threadlist_request (char *pkt, int startflag, int threadcount,
2525 threadref *nextthread)
c906108c
SS
2526{
2527 *pkt++ = 'q'; /* info query packet */
2528 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2529 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2530 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2531 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2532 *pkt = '\0';
2533 return pkt;
2534}
2535
2536/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2537
2538static int
fba45db2
KB
2539parse_threadlist_response (char *pkt, int result_limit,
2540 threadref *original_echo, threadref *resultlist,
2541 int *doneflag)
c906108c 2542{
d01949b6 2543 struct remote_state *rs = get_remote_state ();
c906108c
SS
2544 char *limit;
2545 int count, resultcount, done;
2546
2547 resultcount = 0;
2548 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2549 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2550 /* done parse past here */
c906108c
SS
2551 pkt = unpack_byte (pkt, &count); /* count field */
2552 pkt = unpack_nibble (pkt, &done);
2553 /* The first threadid is the argument threadid. */
2554 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2555 while ((count-- > 0) && (pkt < limit))
2556 {
2557 pkt = unpack_threadid (pkt, resultlist++);
2558 if (resultcount++ >= result_limit)
2559 break;
2560 }
2561 if (doneflag)
2562 *doneflag = done;
2563 return resultcount;
2564}
2565
6dc54d91
PA
2566/* Fetch the next batch of threads from the remote. Returns -1 if the
2567 qL packet is not supported, 0 on error and 1 on success. */
2568
c906108c 2569static int
fba45db2
KB
2570remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2571 int *done, int *result_count, threadref *threadlist)
c906108c 2572{
d01949b6 2573 struct remote_state *rs = get_remote_state ();
c906108c
SS
2574 int result = 1;
2575
23860348 2576 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2577 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2578 >= get_remote_packet_size ())
ea9c271d 2579 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2580
6d820c5c
DJ
2581 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2582 putpkt (rs->buf);
2583 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2584 if (*rs->buf == '\0')
6dc54d91
PA
2585 {
2586 /* Packet not supported. */
2587 return -1;
2588 }
2589
2590 *result_count =
2591 parse_threadlist_response (rs->buf + 2, result_limit,
2592 &rs->echo_nextthread, threadlist, done);
c906108c 2593
0d031856 2594 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2595 {
23860348
MS
2596 /* FIXME: This is a good reason to drop the packet. */
2597 /* Possably, there is a duplicate response. */
c906108c
SS
2598 /* Possabilities :
2599 retransmit immediatly - race conditions
2600 retransmit after timeout - yes
2601 exit
2602 wait for packet, then exit
2603 */
8a3fe4f8 2604 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2605 return 0; /* I choose simply exiting. */
c906108c
SS
2606 }
2607 if (*result_count <= 0)
2608 {
2609 if (*done != 1)
2610 {
8a3fe4f8 2611 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2612 result = 0;
2613 }
2614 return result; /* break; */
2615 }
2616 if (*result_count > result_limit)
2617 {
2618 *result_count = 0;
8a3fe4f8 2619 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2620 return 0;
2621 }
2622 return result;
2623}
2624
6dc54d91
PA
2625/* Fetch the list of remote threads, with the qL packet, and call
2626 STEPFUNCTION for each thread found. Stops iterating and returns 1
2627 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2628 STEPFUNCTION returns false. If the packet is not supported,
2629 returns -1. */
c906108c 2630
c906108c 2631static int
fba45db2
KB
2632remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2633 int looplimit)
c906108c 2634{
0d031856 2635 struct remote_state *rs = get_remote_state ();
c906108c
SS
2636 int done, i, result_count;
2637 int startflag = 1;
2638 int result = 1;
2639 int loopcount = 0;
c906108c
SS
2640
2641 done = 0;
2642 while (!done)
2643 {
2644 if (loopcount++ > looplimit)
2645 {
2646 result = 0;
8a3fe4f8 2647 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2648 break;
2649 }
6dc54d91
PA
2650 result = remote_get_threadlist (startflag, &rs->nextthread,
2651 MAXTHREADLISTRESULTS,
2652 &done, &result_count,
2653 rs->resultthreadlist);
2654 if (result <= 0)
2655 break;
23860348 2656 /* Clear for later iterations. */
c906108c
SS
2657 startflag = 0;
2658 /* Setup to resume next batch of thread references, set nextthread. */
2659 if (result_count >= 1)
0d031856
TT
2660 copy_threadref (&rs->nextthread,
2661 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2662 i = 0;
2663 while (result_count--)
6dc54d91
PA
2664 {
2665 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2666 {
2667 result = 0;
2668 break;
2669 }
2670 }
c906108c
SS
2671 }
2672 return result;
2673}
2674
6dc54d91
PA
2675/* A thread found on the remote target. */
2676
2677typedef struct thread_item
2678{
2679 /* The thread's PTID. */
2680 ptid_t ptid;
2681
2682 /* The thread's extra info. May be NULL. */
2683 char *extra;
2684
2685 /* The core the thread was running on. -1 if not known. */
2686 int core;
2687} thread_item_t;
2688DEF_VEC_O(thread_item_t);
2689
2690/* Context passed around to the various methods listing remote
2691 threads. As new threads are found, they're added to the ITEMS
2692 vector. */
2693
2694struct threads_listing_context
2695{
2696 /* The threads found on the remote target. */
2697 VEC (thread_item_t) *items;
2698};
2699
80134cf5
PA
2700/* Discard the contents of the constructed thread listing context. */
2701
2702static void
2703clear_threads_listing_context (void *p)
2704{
2705 struct threads_listing_context *context = p;
2706 int i;
2707 struct thread_item *item;
2708
2709 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2710 xfree (item->extra);
2711
2712 VEC_free (thread_item_t, context->items);
2713}
2714
cbb8991c
DB
2715/* Remove the thread specified as the related_pid field of WS
2716 from the CONTEXT list. */
2717
2718static void
2719threads_listing_context_remove (struct target_waitstatus *ws,
2720 struct threads_listing_context *context)
2721{
2722 struct thread_item *item;
2723 int i;
2724 ptid_t child_ptid = ws->value.related_pid;
2725
2726 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2727 {
2728 if (ptid_equal (item->ptid, child_ptid))
2729 {
2730 VEC_ordered_remove (thread_item_t, context->items, i);
2731 break;
2732 }
2733 }
2734}
2735
c906108c 2736static int
6dc54d91 2737remote_newthread_step (threadref *ref, void *data)
c906108c 2738{
6dc54d91
PA
2739 struct threads_listing_context *context = data;
2740 struct thread_item item;
79d7f229 2741 int pid = ptid_get_pid (inferior_ptid);
39f77062 2742
6dc54d91
PA
2743 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2744 item.core = -1;
2745 item.extra = NULL;
2746
2747 VEC_safe_push (thread_item_t, context->items, &item);
2748
c906108c
SS
2749 return 1; /* continue iterator */
2750}
2751
2752#define CRAZY_MAX_THREADS 1000
2753
39f77062
KB
2754static ptid_t
2755remote_current_thread (ptid_t oldpid)
c906108c 2756{
d01949b6 2757 struct remote_state *rs = get_remote_state ();
c906108c
SS
2758
2759 putpkt ("qC");
6d820c5c 2760 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2761 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34
KB
2762 {
2763 char *obuf;
2764 ptid_t result;
2765
2766 result = read_ptid (&rs->buf[2], &obuf);
2767 if (*obuf != '\0' && remote_debug)
2768 fprintf_unfiltered (gdb_stdlog,
2769 "warning: garbage in qC reply\n");
2770
2771 return result;
2772 }
c906108c
SS
2773 else
2774 return oldpid;
2775}
2776
6dc54d91 2777/* List remote threads using the deprecated qL packet. */
cce74817 2778
6dc54d91
PA
2779static int
2780remote_get_threads_with_ql (struct target_ops *ops,
2781 struct threads_listing_context *context)
c906108c 2782{
6dc54d91
PA
2783 if (remote_threadlist_iterator (remote_newthread_step, context,
2784 CRAZY_MAX_THREADS) >= 0)
2785 return 1;
2786
2787 return 0;
c906108c
SS
2788}
2789
dc146f7c
VP
2790#if defined(HAVE_LIBEXPAT)
2791
dc146f7c
VP
2792static void
2793start_thread (struct gdb_xml_parser *parser,
2794 const struct gdb_xml_element *element,
2795 void *user_data, VEC(gdb_xml_value_s) *attributes)
2796{
6dc54d91 2797 struct threads_listing_context *data = user_data;
dc146f7c
VP
2798
2799 struct thread_item item;
2800 char *id;
3d2c1d41 2801 struct gdb_xml_value *attr;
dc146f7c 2802
3d2c1d41 2803 id = xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
2804 item.ptid = read_ptid (id, NULL);
2805
3d2c1d41
PA
2806 attr = xml_find_attribute (attributes, "core");
2807 if (attr != NULL)
2808 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
2809 else
2810 item.core = -1;
2811
2812 item.extra = 0;
2813
2814 VEC_safe_push (thread_item_t, data->items, &item);
2815}
2816
2817static void
2818end_thread (struct gdb_xml_parser *parser,
2819 const struct gdb_xml_element *element,
2820 void *user_data, const char *body_text)
2821{
6dc54d91 2822 struct threads_listing_context *data = user_data;
dc146f7c
VP
2823
2824 if (body_text && *body_text)
2ae2a0b7 2825 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
2826}
2827
2828const struct gdb_xml_attribute thread_attributes[] = {
2829 { "id", GDB_XML_AF_NONE, NULL, NULL },
2830 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2831 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2832};
2833
2834const struct gdb_xml_element thread_children[] = {
2835 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2836};
2837
2838const struct gdb_xml_element threads_children[] = {
2839 { "thread", thread_attributes, thread_children,
2840 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2841 start_thread, end_thread },
2842 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2843};
2844
2845const struct gdb_xml_element threads_elements[] = {
2846 { "threads", NULL, threads_children,
2847 GDB_XML_EF_NONE, NULL, NULL },
2848 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2849};
2850
2851#endif
2852
6dc54d91 2853/* List remote threads using qXfer:threads:read. */
9d1f7ab2 2854
6dc54d91
PA
2855static int
2856remote_get_threads_with_qxfer (struct target_ops *ops,
2857 struct threads_listing_context *context)
0f71a2f6 2858{
dc146f7c 2859#if defined(HAVE_LIBEXPAT)
4082afcc 2860 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 2861 {
6dc54d91 2862 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 2863 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 2864
6dc54d91 2865 if (xml != NULL && *xml != '\0')
dc146f7c 2866 {
6dc54d91
PA
2867 gdb_xml_parse_quick (_("threads"), "threads.dtd",
2868 threads_elements, xml, context);
dc146f7c
VP
2869 }
2870
2871 do_cleanups (back_to);
6dc54d91 2872 return 1;
dc146f7c
VP
2873 }
2874#endif
2875
6dc54d91
PA
2876 return 0;
2877}
2878
2879/* List remote threads using qfThreadInfo/qsThreadInfo. */
2880
2881static int
2882remote_get_threads_with_qthreadinfo (struct target_ops *ops,
2883 struct threads_listing_context *context)
2884{
2885 struct remote_state *rs = get_remote_state ();
2886
b80fafe3 2887 if (rs->use_threadinfo_query)
9d1f7ab2 2888 {
6dc54d91
PA
2889 char *bufp;
2890
9d1f7ab2 2891 putpkt ("qfThreadInfo");
6d820c5c 2892 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2893 bufp = rs->buf;
9d1f7ab2 2894 if (bufp[0] != '\0') /* q packet recognized */
802188a7 2895 {
9d1f7ab2
MS
2896 while (*bufp++ == 'm') /* reply contains one or more TID */
2897 {
2898 do
2899 {
6dc54d91
PA
2900 struct thread_item item;
2901
2902 item.ptid = read_ptid (bufp, &bufp);
2903 item.core = -1;
2904 item.extra = NULL;
2905
2906 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
2907 }
2908 while (*bufp++ == ','); /* comma-separated list */
2909 putpkt ("qsThreadInfo");
6d820c5c 2910 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 2911 bufp = rs->buf;
9d1f7ab2 2912 }
6dc54d91
PA
2913 return 1;
2914 }
2915 else
2916 {
2917 /* Packet not recognized. */
2918 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
2919 }
2920 }
2921
6dc54d91
PA
2922 return 0;
2923}
2924
e8032dde 2925/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
2926 targets. */
2927
2928static void
e8032dde 2929remote_update_thread_list (struct target_ops *ops)
6dc54d91
PA
2930{
2931 struct remote_state *rs = get_remote_state ();
2932 struct threads_listing_context context;
2933 struct cleanup *old_chain;
ab970af1 2934 int got_list = 0;
e8032dde 2935
6dc54d91
PA
2936 context.items = NULL;
2937 old_chain = make_cleanup (clear_threads_listing_context, &context);
2938
2939 /* We have a few different mechanisms to fetch the thread list. Try
2940 them all, starting with the most preferred one first, falling
2941 back to older methods. */
2942 if (remote_get_threads_with_qxfer (ops, &context)
2943 || remote_get_threads_with_qthreadinfo (ops, &context)
2944 || remote_get_threads_with_ql (ops, &context))
2945 {
2946 int i;
2947 struct thread_item *item;
ab970af1
PA
2948 struct thread_info *tp, *tmp;
2949
2950 got_list = 1;
2951
7d1a114c
PA
2952 if (VEC_empty (thread_item_t, context.items)
2953 && remote_thread_always_alive (ops, inferior_ptid))
2954 {
2955 /* Some targets don't really support threads, but still
2956 reply an (empty) thread list in response to the thread
2957 listing packets, instead of replying "packet not
2958 supported". Exit early so we don't delete the main
2959 thread. */
2960 do_cleanups (old_chain);
2961 return;
2962 }
2963
ab970af1
PA
2964 /* CONTEXT now holds the current thread list on the remote
2965 target end. Delete GDB-side threads no longer found on the
2966 target. */
8a06aea7 2967 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 2968 {
ab970af1
PA
2969 for (i = 0;
2970 VEC_iterate (thread_item_t, context.items, i, item);
2971 ++i)
2972 {
2973 if (ptid_equal (item->ptid, tp->ptid))
2974 break;
2975 }
2976
2977 if (i == VEC_length (thread_item_t, context.items))
2978 {
2979 /* Not found. */
2980 delete_thread (tp->ptid);
2981 }
cbb8991c
DB
2982 }
2983
2984 /* Remove any unreported fork child threads from CONTEXT so
2985 that we don't interfere with follow fork, which is where
2986 creation of such threads is handled. */
2987 remove_new_fork_children (&context);
74531fed 2988
ab970af1 2989 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
2990 for (i = 0;
2991 VEC_iterate (thread_item_t, context.items, i, item);
2992 ++i)
2993 {
2994 if (!ptid_equal (item->ptid, null_ptid))
2995 {
2996 struct private_thread_info *info;
2997 /* In non-stop mode, we assume new found threads are
2998 running until proven otherwise with a stop reply. In
2999 all-stop, we can only get here if all threads are
3000 stopped. */
3001 int running = non_stop ? 1 : 0;
3002
3003 remote_notice_new_inferior (item->ptid, running);
3004
3005 info = demand_private_info (item->ptid);
3006 info->core = item->core;
3007 info->extra = item->extra;
3008 item->extra = NULL;
3009 }
3010 }
3011 }
3012
ab970af1
PA
3013 if (!got_list)
3014 {
3015 /* If no thread listing method is supported, then query whether
3016 each known thread is alive, one by one, with the T packet.
3017 If the target doesn't support threads at all, then this is a
3018 no-op. See remote_thread_alive. */
3019 prune_threads ();
3020 }
3021
6dc54d91 3022 do_cleanups (old_chain);
9d1f7ab2
MS
3023}
3024
802188a7 3025/*
9d1f7ab2
MS
3026 * Collect a descriptive string about the given thread.
3027 * The target may say anything it wants to about the thread
3028 * (typically info about its blocked / runnable state, name, etc.).
3029 * This string will appear in the info threads display.
802188a7 3030 *
9d1f7ab2
MS
3031 * Optional: targets are not required to implement this function.
3032 */
3033
3034static char *
c15906d8 3035remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 3036{
d01949b6 3037 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3038 int result;
3039 int set;
3040 threadref id;
3041 struct gdb_ext_thread_info threadinfo;
23860348 3042 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3043 int n = 0; /* position in display_buf */
3044
5d93a237 3045 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3046 internal_error (__FILE__, __LINE__,
e2e0b3e5 3047 _("remote_threads_extra_info"));
9d1f7ab2 3048
60e569b9 3049 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3050 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3051 /* This is the main thread which was added by GDB. The remote
3052 server doesn't know about it. */
3053 return NULL;
3054
4082afcc 3055 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3056 {
3057 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3058
fe978cb0
PA
3059 if (info && info->priv)
3060 return info->priv->extra;
dc146f7c
VP
3061 else
3062 return NULL;
3063 }
3064
b80fafe3 3065 if (rs->use_threadextra_query)
9d1f7ab2 3066 {
82f73884
PA
3067 char *b = rs->buf;
3068 char *endb = rs->buf + get_remote_packet_size ();
3069
3070 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3071 b += strlen (b);
3072 write_ptid (b, endb, tp->ptid);
3073
2e9f7625 3074 putpkt (rs->buf);
6d820c5c 3075 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3076 if (rs->buf[0] != 0)
9d1f7ab2 3077 {
2e9f7625
DJ
3078 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3079 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3080 display_buf [result] = '\0';
9d1f7ab2
MS
3081 return display_buf;
3082 }
0f71a2f6 3083 }
9d1f7ab2
MS
3084
3085 /* If the above query fails, fall back to the old method. */
b80fafe3 3086 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3087 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3088 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3089 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3090 if (remote_get_threadinfo (&id, set, &threadinfo))
3091 if (threadinfo.active)
0f71a2f6 3092 {
9d1f7ab2 3093 if (*threadinfo.shortname)
2bc416ba 3094 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3095 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3096 if (*threadinfo.display)
2bc416ba 3097 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3098 " State: %s,", threadinfo.display);
9d1f7ab2 3099 if (*threadinfo.more_display)
2bc416ba 3100 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3101 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3102
3103 if (n > 0)
c5aa993b 3104 {
23860348 3105 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3106 if (',' == display_buf[n-1])
3107 display_buf[n-1] = ' ';
3108 return display_buf;
c5aa993b 3109 }
0f71a2f6 3110 }
9d1f7ab2 3111 return NULL;
0f71a2f6 3112}
c906108c 3113\f
c5aa993b 3114
0fb4aa4b 3115static int
61fc905d 3116remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
3117 struct static_tracepoint_marker *marker)
3118{
3119 struct remote_state *rs = get_remote_state ();
3120 char *p = rs->buf;
3121
bba74b36 3122 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3123 p += strlen (p);
3124 p += hexnumstr (p, addr);
3125 putpkt (rs->buf);
3126 getpkt (&rs->buf, &rs->buf_size, 0);
3127 p = rs->buf;
3128
3129 if (*p == 'E')
3130 error (_("Remote failure reply: %s"), p);
3131
3132 if (*p++ == 'm')
3133 {
3134 parse_static_tracepoint_marker_definition (p, &p, marker);
3135 return 1;
3136 }
3137
3138 return 0;
3139}
3140
0fb4aa4b 3141static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3142remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3143 const char *strid)
0fb4aa4b
PA
3144{
3145 struct remote_state *rs = get_remote_state ();
3146 VEC(static_tracepoint_marker_p) *markers = NULL;
3147 struct static_tracepoint_marker *marker = NULL;
3148 struct cleanup *old_chain;
3149 char *p;
3150
3151 /* Ask for a first packet of static tracepoint marker
3152 definition. */
3153 putpkt ("qTfSTM");
3154 getpkt (&rs->buf, &rs->buf_size, 0);
3155 p = rs->buf;
3156 if (*p == 'E')
3157 error (_("Remote failure reply: %s"), p);
3158
3159 old_chain = make_cleanup (free_current_marker, &marker);
3160
3161 while (*p++ == 'm')
3162 {
3163 if (marker == NULL)
3164 marker = XCNEW (struct static_tracepoint_marker);
3165
3166 do
3167 {
3168 parse_static_tracepoint_marker_definition (p, &p, marker);
3169
3170 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3171 {
3172 VEC_safe_push (static_tracepoint_marker_p,
3173 markers, marker);
3174 marker = NULL;
3175 }
3176 else
3177 {
3178 release_static_tracepoint_marker (marker);
3179 memset (marker, 0, sizeof (*marker));
3180 }
3181 }
3182 while (*p++ == ','); /* comma-separated list */
3183 /* Ask for another packet of static tracepoint definition. */
3184 putpkt ("qTsSTM");
3185 getpkt (&rs->buf, &rs->buf_size, 0);
3186 p = rs->buf;
3187 }
3188
3189 do_cleanups (old_chain);
3190 return markers;
3191}
3192
3193\f
10760264
JB
3194/* Implement the to_get_ada_task_ptid function for the remote targets. */
3195
3196static ptid_t
1e6b91a4 3197remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3198{
ba348170 3199 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3200}
3201\f
3202
24b06219 3203/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3204
3205static void
fba45db2 3206extended_remote_restart (void)
c906108c 3207{
d01949b6 3208 struct remote_state *rs = get_remote_state ();
c906108c
SS
3209
3210 /* Send the restart command; for reasons I don't understand the
3211 remote side really expects a number after the "R". */
ea9c271d 3212 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3213 putpkt (rs->buf);
c906108c 3214
ad9a8f3f 3215 remote_fileio_reset ();
c906108c
SS
3216}
3217\f
3218/* Clean up connection to a remote debugger. */
3219
c906108c 3220static void
de90e03d 3221remote_close (struct target_ops *self)
c906108c 3222{
5d93a237
TT
3223 struct remote_state *rs = get_remote_state ();
3224
3225 if (rs->remote_desc == NULL)
d3fd5342
PA
3226 return; /* already closed */
3227
3228 /* Make sure we leave stdin registered in the event loop, and we
3229 don't leave the async SIGINT signal handler installed. */
e3594fd1 3230 remote_terminal_ours (self);
ce5ce7ed 3231
5d93a237
TT
3232 serial_close (rs->remote_desc);
3233 rs->remote_desc = NULL;
ce5ce7ed
PA
3234
3235 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3236 of all the inferiors and their threads we were controlling.
3237 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3238 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3239 inferior_ptid = null_ptid;
f67fd822 3240 discard_all_inferiors ();
ce5ce7ed 3241
f48ff2a7
YQ
3242 /* We are closing the remote target, so we should discard
3243 everything of this target. */
bcc75809 3244 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3245
3246 if (remote_async_inferior_event_token)
3247 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3248
5965e028 3249 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3250
3251 trace_reset_local_state ();
c906108c
SS
3252}
3253
23860348 3254/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3255
3256static void
fba45db2 3257get_offsets (void)
c906108c 3258{
d01949b6 3259 struct remote_state *rs = get_remote_state ();
2e9f7625 3260 char *buf;
085dd6e6 3261 char *ptr;
31d99776
DJ
3262 int lose, num_segments = 0, do_sections, do_segments;
3263 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3264 struct section_offsets *offs;
31d99776
DJ
3265 struct symfile_segment_data *data;
3266
3267 if (symfile_objfile == NULL)
3268 return;
c906108c
SS
3269
3270 putpkt ("qOffsets");
6d820c5c 3271 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3272 buf = rs->buf;
c906108c
SS
3273
3274 if (buf[0] == '\000')
3275 return; /* Return silently. Stub doesn't support
23860348 3276 this command. */
c906108c
SS
3277 if (buf[0] == 'E')
3278 {
8a3fe4f8 3279 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3280 return;
3281 }
3282
3283 /* Pick up each field in turn. This used to be done with scanf, but
3284 scanf will make trouble if CORE_ADDR size doesn't match
3285 conversion directives correctly. The following code will work
3286 with any size of CORE_ADDR. */
3287 text_addr = data_addr = bss_addr = 0;
3288 ptr = buf;
3289 lose = 0;
3290
61012eef 3291 if (startswith (ptr, "Text="))
c906108c
SS
3292 {
3293 ptr += 5;
3294 /* Don't use strtol, could lose on big values. */
3295 while (*ptr && *ptr != ';')
3296 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3297
61012eef 3298 if (startswith (ptr, ";Data="))
31d99776
DJ
3299 {
3300 ptr += 6;
3301 while (*ptr && *ptr != ';')
3302 data_addr = (data_addr << 4) + fromhex (*ptr++);
3303 }
3304 else
3305 lose = 1;
3306
61012eef 3307 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3308 {
3309 ptr += 5;
3310 while (*ptr && *ptr != ';')
3311 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3312
31d99776
DJ
3313 if (bss_addr != data_addr)
3314 warning (_("Target reported unsupported offsets: %s"), buf);
3315 }
3316 else
3317 lose = 1;
3318 }
61012eef 3319 else if (startswith (ptr, "TextSeg="))
c906108c 3320 {
31d99776
DJ
3321 ptr += 8;
3322 /* Don't use strtol, could lose on big values. */
c906108c 3323 while (*ptr && *ptr != ';')
31d99776
DJ
3324 text_addr = (text_addr << 4) + fromhex (*ptr++);
3325 num_segments = 1;
3326
61012eef 3327 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3328 {
3329 ptr += 9;
3330 while (*ptr && *ptr != ';')
3331 data_addr = (data_addr << 4) + fromhex (*ptr++);
3332 num_segments++;
3333 }
c906108c
SS
3334 }
3335 else
3336 lose = 1;
3337
3338 if (lose)
8a3fe4f8 3339 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3340 else if (*ptr != '\0')
3341 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3342
802188a7 3343 offs = ((struct section_offsets *)
a39a16c4 3344 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3345 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3346 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3347
31d99776
DJ
3348 data = get_symfile_segment_data (symfile_objfile->obfd);
3349 do_segments = (data != NULL);
3350 do_sections = num_segments == 0;
c906108c 3351
28c32713 3352 if (num_segments > 0)
31d99776 3353 {
31d99776
DJ
3354 segments[0] = text_addr;
3355 segments[1] = data_addr;
3356 }
28c32713
JB
3357 /* If we have two segments, we can still try to relocate everything
3358 by assuming that the .text and .data offsets apply to the whole
3359 text and data segments. Convert the offsets given in the packet
3360 to base addresses for symfile_map_offsets_to_segments. */
3361 else if (data && data->num_segments == 2)
3362 {
3363 segments[0] = data->segment_bases[0] + text_addr;
3364 segments[1] = data->segment_bases[1] + data_addr;
3365 num_segments = 2;
3366 }
8d385431
DJ
3367 /* If the object file has only one segment, assume that it is text
3368 rather than data; main programs with no writable data are rare,
3369 but programs with no code are useless. Of course the code might
3370 have ended up in the data segment... to detect that we would need
3371 the permissions here. */
3372 else if (data && data->num_segments == 1)
3373 {
3374 segments[0] = data->segment_bases[0] + text_addr;
3375 num_segments = 1;
3376 }
28c32713
JB
3377 /* There's no way to relocate by segment. */
3378 else
3379 do_segments = 0;
31d99776
DJ
3380
3381 if (do_segments)
3382 {
3383 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3384 offs, num_segments, segments);
3385
3386 if (ret == 0 && !do_sections)
3e43a32a
MS
3387 error (_("Can not handle qOffsets TextSeg "
3388 "response with this symbol file"));
31d99776
DJ
3389
3390 if (ret > 0)
3391 do_sections = 0;
3392 }
c906108c 3393
9ef895d6
DJ
3394 if (data)
3395 free_symfile_segment_data (data);
31d99776
DJ
3396
3397 if (do_sections)
3398 {
3399 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3400
3e43a32a
MS
3401 /* This is a temporary kludge to force data and bss to use the
3402 same offsets because that's what nlmconv does now. The real
3403 solution requires changes to the stub and remote.c that I
3404 don't have time to do right now. */
31d99776
DJ
3405
3406 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3407 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3408 }
c906108c
SS
3409
3410 objfile_relocate (symfile_objfile, offs);
3411}
3412
74531fed
PA
3413/* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3414 threads we know are stopped already. This is used during the
3415 initial remote connection in non-stop mode --- threads that are
3416 reported as already being stopped are left stopped. */
3417
3418static int
3419set_stop_requested_callback (struct thread_info *thread, void *data)
3420{
3421 /* If we have a stop reply for this thread, it must be stopped. */
3422 if (peek_stop_reply (thread->ptid))
3423 set_stop_requested (thread->ptid, 1);
3424
3425 return 0;
3426}
3427
9a7071a8
JB
3428/* Send interrupt_sequence to remote target. */
3429static void
eeae04df 3430send_interrupt_sequence (void)
9a7071a8 3431{
5d93a237
TT
3432 struct remote_state *rs = get_remote_state ();
3433
9a7071a8 3434 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3435 remote_serial_write ("\x03", 1);
9a7071a8 3436 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3437 serial_send_break (rs->remote_desc);
9a7071a8
JB
3438 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3439 {
5d93a237 3440 serial_send_break (rs->remote_desc);
c33e31fd 3441 remote_serial_write ("g", 1);
9a7071a8
JB
3442 }
3443 else
3444 internal_error (__FILE__, __LINE__,
3445 _("Invalid value for interrupt_sequence_mode: %s."),
3446 interrupt_sequence_mode);
3447}
3448
3405876a
PA
3449
3450/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3451 and extract the PTID. Returns NULL_PTID if not found. */
3452
3453static ptid_t
3454stop_reply_extract_thread (char *stop_reply)
3455{
3456 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3457 {
3458 char *p;
3459
3460 /* Txx r:val ; r:val (...) */
3461 p = &stop_reply[3];
3462
3463 /* Look for "register" named "thread". */
3464 while (*p != '\0')
3465 {
3466 char *p1;
3467
3468 p1 = strchr (p, ':');
3469 if (p1 == NULL)
3470 return null_ptid;
3471
3472 if (strncmp (p, "thread", p1 - p) == 0)
3473 return read_ptid (++p1, &p);
3474
3475 p1 = strchr (p, ';');
3476 if (p1 == NULL)
3477 return null_ptid;
3478 p1++;
3479
3480 p = p1;
3481 }
3482 }
3483
3484 return null_ptid;
3485}
3486
b7ea362b
PA
3487/* Determine the remote side's current thread. If we have a stop
3488 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3489 "thread" register we can extract the current thread from. If not,
3490 ask the remote which is the current thread with qC. The former
3491 method avoids a roundtrip. */
3492
3493static ptid_t
3494get_current_thread (char *wait_status)
3495{
6a49a997 3496 ptid_t ptid = null_ptid;
b7ea362b
PA
3497
3498 /* Note we don't use remote_parse_stop_reply as that makes use of
3499 the target architecture, which we haven't yet fully determined at
3500 this point. */
3501 if (wait_status != NULL)
3502 ptid = stop_reply_extract_thread (wait_status);
3503 if (ptid_equal (ptid, null_ptid))
3504 ptid = remote_current_thread (inferior_ptid);
3505
3506 return ptid;
3507}
3508
49c62f2e
PA
3509/* Query the remote target for which is the current thread/process,
3510 add it to our tables, and update INFERIOR_PTID. The caller is
3511 responsible for setting the state such that the remote end is ready
3405876a
PA
3512 to return the current thread.
3513
3514 This function is called after handling the '?' or 'vRun' packets,
3515 whose response is a stop reply from which we can also try
3516 extracting the thread. If the target doesn't support the explicit
3517 qC query, we infer the current thread from that stop reply, passed
3518 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3519
3520static void
3405876a 3521add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3522{
3523 struct remote_state *rs = get_remote_state ();
3524 int fake_pid_p = 0;
6a49a997 3525 ptid_t ptid;
49c62f2e
PA
3526
3527 inferior_ptid = null_ptid;
3528
b7ea362b
PA
3529 /* Now, if we have thread information, update inferior_ptid. */
3530 ptid = get_current_thread (wait_status);
3405876a 3531
49c62f2e
PA
3532 if (!ptid_equal (ptid, null_ptid))
3533 {
3534 if (!remote_multi_process_p (rs))
3535 fake_pid_p = 1;
3536
3537 inferior_ptid = ptid;
3538 }
3539 else
3540 {
3541 /* Without this, some commands which require an active target
3542 (such as kill) won't work. This variable serves (at least)
3543 double duty as both the pid of the target process (if it has
3544 such), and as a flag indicating that a target is active. */
3545 inferior_ptid = magic_null_ptid;
3546 fake_pid_p = 1;
3547 }
3548
1b6e6f5c 3549 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
49c62f2e
PA
3550
3551 /* Add the main thread. */
3552 add_thread_silent (inferior_ptid);
3553}
3554
9cbc821d 3555static void
04bd08de 3556remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 3557{
c8d104ad
PA
3558 struct remote_state *rs = get_remote_state ();
3559 struct packet_config *noack_config;
2d717e4f 3560 char *wait_status = NULL;
8621d6a9 3561
23860348 3562 immediate_quit++; /* Allow user to interrupt it. */
522002f9 3563 QUIT;
c906108c 3564
9a7071a8
JB
3565 if (interrupt_on_connect)
3566 send_interrupt_sequence ();
3567
57e12211 3568 /* Ack any packet which the remote side has already sent. */
5d93a237 3569 serial_write (rs->remote_desc, "+", 1);
57e12211 3570
1e51243a
PA
3571 /* Signal other parts that we're going through the initial setup,
3572 and so things may not be stable yet. */
3573 rs->starting_up = 1;
3574
c8d104ad
PA
3575 /* The first packet we send to the target is the optional "supported
3576 packets" request. If the target can answer this, it will tell us
3577 which later probes to skip. */
3578 remote_query_supported ();
3579
d914c394 3580 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 3581 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 3582 remote_set_permissions (target);
d914c394 3583
c8d104ad
PA
3584 /* Next, we possibly activate noack mode.
3585
3586 If the QStartNoAckMode packet configuration is set to AUTO,
3587 enable noack mode if the stub reported a wish for it with
3588 qSupported.
3589
3590 If set to TRUE, then enable noack mode even if the stub didn't
3591 report it in qSupported. If the stub doesn't reply OK, the
3592 session ends with an error.
3593
3594 If FALSE, then don't activate noack mode, regardless of what the
3595 stub claimed should be the default with qSupported. */
3596
3597 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 3598 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
3599 {
3600 putpkt ("QStartNoAckMode");
3601 getpkt (&rs->buf, &rs->buf_size, 0);
3602 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3603 rs->noack_mode = 1;
3604 }
3605
04bd08de 3606 if (extended_p)
5fe04517
PA
3607 {
3608 /* Tell the remote that we are using the extended protocol. */
3609 putpkt ("!");
3610 getpkt (&rs->buf, &rs->buf_size, 0);
3611 }
3612
9b224c5e
PA
3613 /* Let the target know which signals it is allowed to pass down to
3614 the program. */
3615 update_signals_program_target ();
3616
d962ef82
DJ
3617 /* Next, if the target can specify a description, read it. We do
3618 this before anything involving memory or registers. */
3619 target_find_description ();
3620
6c95b8df
PA
3621 /* Next, now that we know something about the target, update the
3622 address spaces in the program spaces. */
3623 update_address_spaces ();
3624
50c71eaf
PA
3625 /* On OSs where the list of libraries is global to all
3626 processes, we fetch them early. */
f5656ead 3627 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 3628 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 3629
74531fed
PA
3630 if (non_stop)
3631 {
4082afcc 3632 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
3633 error (_("Non-stop mode requested, but remote "
3634 "does not support non-stop"));
74531fed
PA
3635
3636 putpkt ("QNonStop:1");
3637 getpkt (&rs->buf, &rs->buf_size, 0);
3638
3639 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3640 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
3641
3642 /* Find about threads and processes the stub is already
3643 controlling. We default to adding them in the running state.
3644 The '?' query below will then tell us about which threads are
3645 stopped. */
e8032dde 3646 remote_update_thread_list (target);
74531fed 3647 }
4082afcc 3648 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
3649 {
3650 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 3651 Request it explicitly. */
74531fed
PA
3652 putpkt ("QNonStop:0");
3653 getpkt (&rs->buf, &rs->buf_size, 0);
3654
3655 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3656 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
3657 }
3658
a0743c90
YQ
3659 /* Upload TSVs regardless of whether the target is running or not. The
3660 remote stub, such as GDBserver, may have some predefined or builtin
3661 TSVs, even if the target is not running. */
8bd200f1 3662 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
3663 {
3664 struct uploaded_tsv *uploaded_tsvs = NULL;
3665
181e3713 3666 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
3667 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3668 }
3669
2d717e4f
DJ
3670 /* Check whether the target is running now. */
3671 putpkt ("?");
3672 getpkt (&rs->buf, &rs->buf_size, 0);
3673
74531fed 3674 if (!non_stop)
2d717e4f 3675 {
e714e1bf
UW
3676 ptid_t ptid;
3677 int fake_pid_p = 0;
3678 struct inferior *inf;
3679
74531fed 3680 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 3681 {
04bd08de 3682 if (!extended_p)
74531fed 3683 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
3684
3685 /* We're connected, but not running. Drop out before we
3686 call start_remote. */
e278ad5b 3687 rs->starting_up = 0;
c35b1492 3688 return;
2d717e4f
DJ
3689 }
3690 else
74531fed 3691 {
74531fed
PA
3692 /* Save the reply for later. */
3693 wait_status = alloca (strlen (rs->buf) + 1);
3694 strcpy (wait_status, rs->buf);
3695 }
3696
b7ea362b 3697 /* Fetch thread list. */
e8032dde 3698 target_update_thread_list ();
b7ea362b 3699
74531fed
PA
3700 /* Let the stub know that we want it to return the thread. */
3701 set_continue_thread (minus_one_ptid);
3702
b7ea362b
PA
3703 if (thread_count () == 0)
3704 {
3705 /* Target has no concept of threads at all. GDB treats
3706 non-threaded target as single-threaded; add a main
3707 thread. */
3708 add_current_inferior_and_thread (wait_status);
3709 }
3710 else
3711 {
3712 /* We have thread information; select the thread the target
3713 says should be current. If we're reconnecting to a
3714 multi-threaded program, this will ideally be the thread
3715 that last reported an event before GDB disconnected. */
3716 inferior_ptid = get_current_thread (wait_status);
3717 if (ptid_equal (inferior_ptid, null_ptid))
3718 {
3719 /* Odd... The target was able to list threads, but not
3720 tell us which thread was current (no "thread"
3721 register in T stop reply?). Just pick the first
3722 thread in the thread list then. */
c9f35b34
KB
3723
3724 if (remote_debug)
3725 fprintf_unfiltered (gdb_stdlog,
3726 "warning: couldn't determine remote "
3727 "current thread; picking first in list.\n");
3728
b7ea362b
PA
3729 inferior_ptid = thread_list->ptid;
3730 }
3731 }
74531fed 3732
6e586cc5
YQ
3733 /* init_wait_for_inferior should be called before get_offsets in order
3734 to manage `inserted' flag in bp loc in a correct state.
3735 breakpoint_init_inferior, called from init_wait_for_inferior, set
3736 `inserted' flag to 0, while before breakpoint_re_set, called from
3737 start_remote, set `inserted' flag to 1. In the initialization of
3738 inferior, breakpoint_init_inferior should be called first, and then
3739 breakpoint_re_set can be called. If this order is broken, state of
3740 `inserted' flag is wrong, and cause some problems on breakpoint
3741 manipulation. */
3742 init_wait_for_inferior ();
3743
74531fed
PA
3744 get_offsets (); /* Get text, data & bss offsets. */
3745
d962ef82
DJ
3746 /* If we could not find a description using qXfer, and we know
3747 how to do it some other way, try again. This is not
3748 supported for non-stop; it could be, but it is tricky if
3749 there are no stopped threads when we connect. */
04bd08de 3750 if (remote_read_description_p (target)
f5656ead 3751 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
3752 {
3753 target_clear_description ();
3754 target_find_description ();
3755 }
3756
74531fed
PA
3757 /* Use the previously fetched status. */
3758 gdb_assert (wait_status != NULL);
3759 strcpy (rs->buf, wait_status);
3760 rs->cached_wait_status = 1;
3761
3762 immediate_quit--;
04bd08de 3763 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
3764 }
3765 else
3766 {
68c97600
PA
3767 /* Clear WFI global state. Do this before finding about new
3768 threads and inferiors, and setting the current inferior.
3769 Otherwise we would clear the proceed status of the current
3770 inferior when we want its stop_soon state to be preserved
3771 (see notice_new_inferior). */
3772 init_wait_for_inferior ();
3773
74531fed
PA
3774 /* In non-stop, we will either get an "OK", meaning that there
3775 are no stopped threads at this time; or, a regular stop
3776 reply. In the latter case, there may be more than one thread
3777 stopped --- we pull them all out using the vStopped
3778 mechanism. */
3779 if (strcmp (rs->buf, "OK") != 0)
3780 {
722247f1 3781 struct notif_client *notif = &notif_client_stop;
2d717e4f 3782
722247f1
YQ
3783 /* remote_notif_get_pending_replies acks this one, and gets
3784 the rest out. */
f48ff2a7 3785 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
3786 = remote_notif_parse (notif, rs->buf);
3787 remote_notif_get_pending_events (notif);
c906108c 3788
74531fed
PA
3789 /* Make sure that threads that were stopped remain
3790 stopped. */
3791 iterate_over_threads (set_stop_requested_callback, NULL);
3792 }
2d717e4f 3793
74531fed 3794 if (target_can_async_p ())
6a3753b3 3795 target_async (1);
c906108c 3796
74531fed
PA
3797 if (thread_count () == 0)
3798 {
04bd08de 3799 if (!extended_p)
74531fed 3800 error (_("The target is not running (try extended-remote?)"));
82f73884 3801
c35b1492
PA
3802 /* We're connected, but not running. Drop out before we
3803 call start_remote. */
e278ad5b 3804 rs->starting_up = 0;
c35b1492
PA
3805 return;
3806 }
74531fed
PA
3807
3808 /* Let the stub know that we want it to return the thread. */
c0a2216e 3809
74531fed
PA
3810 /* Force the stub to choose a thread. */
3811 set_general_thread (null_ptid);
c906108c 3812
74531fed
PA
3813 /* Query it. */
3814 inferior_ptid = remote_current_thread (minus_one_ptid);
3815 if (ptid_equal (inferior_ptid, minus_one_ptid))
3816 error (_("remote didn't report the current thread in non-stop mode"));
c906108c 3817
74531fed
PA
3818 get_offsets (); /* Get text, data & bss offsets. */
3819
3820 /* In non-stop mode, any cached wait status will be stored in
3821 the stop reply queue. */
3822 gdb_assert (wait_status == NULL);
f0223081 3823
2455069d 3824 /* Report all signals during attach/startup. */
94bedb42 3825 remote_pass_signals (target, 0, NULL);
74531fed 3826 }
c8d104ad 3827
c8d104ad
PA
3828 /* If we connected to a live target, do some additional setup. */
3829 if (target_has_execution)
3830 {
f4ccffad 3831 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 3832 remote_check_symbols ();
c8d104ad 3833 }
50c71eaf 3834
d5551862
SS
3835 /* Possibly the target has been engaged in a trace run started
3836 previously; find out where things are at. */
8bd200f1 3837 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 3838 {
00bf0b85 3839 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 3840
00bf0b85
SS
3841 if (current_trace_status ()->running)
3842 printf_filtered (_("Trace is already running on the target.\n"));
3843
ab6617cc 3844 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
3845
3846 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
3847 }
3848
1e51243a
PA
3849 /* The thread and inferior lists are now synchronized with the
3850 target, our symbols have been relocated, and we're merged the
3851 target's tracepoints with ours. We're done with basic start
3852 up. */
3853 rs->starting_up = 0;
3854
a25a5a45
PA
3855 /* Maybe breakpoints are global and need to be inserted now. */
3856 if (breakpoints_should_be_inserted_now ())
50c71eaf 3857 insert_breakpoints ();
c906108c
SS
3858}
3859
3860/* Open a connection to a remote debugger.
3861 NAME is the filename used for communication. */
3862
3863static void
014f9477 3864remote_open (const char *name, int from_tty)
c906108c 3865{
75c99385 3866 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
3867}
3868
c906108c
SS
3869/* Open a connection to a remote debugger using the extended
3870 remote gdb protocol. NAME is the filename used for communication. */
3871
3872static void
014f9477 3873extended_remote_open (const char *name, int from_tty)
c906108c 3874{
75c99385 3875 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
3876}
3877
ca4f7f8b
PA
3878/* Reset all packets back to "unknown support". Called when opening a
3879 new connection to a remote target. */
c906108c 3880
d471ea57 3881static void
ca4f7f8b 3882reset_all_packet_configs_support (void)
d471ea57
AC
3883{
3884 int i;
a744cf53 3885
444abaca 3886 for (i = 0; i < PACKET_MAX; i++)
4082afcc 3887 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
3888}
3889
ca4f7f8b
PA
3890/* Initialize all packet configs. */
3891
3892static void
3893init_all_packet_configs (void)
3894{
3895 int i;
3896
3897 for (i = 0; i < PACKET_MAX; i++)
3898 {
3899 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
3900 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3901 }
3902}
3903
23860348 3904/* Symbol look-up. */
dc8acb97
MS
3905
3906static void
36d25514 3907remote_check_symbols (void)
dc8acb97 3908{
d01949b6 3909 struct remote_state *rs = get_remote_state ();
dc8acb97 3910 char *msg, *reply, *tmp;
3b7344d5 3911 struct bound_minimal_symbol sym;
dc8acb97
MS
3912 int end;
3913
63154eca
PA
3914 /* The remote side has no concept of inferiors that aren't running
3915 yet, it only knows about running processes. If we're connected
3916 but our current inferior is not running, we should not invite the
3917 remote target to request symbol lookups related to its
3918 (unrelated) current process. */
3919 if (!target_has_execution)
3920 return;
3921
4082afcc 3922 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
3923 return;
3924
63154eca
PA
3925 /* Make sure the remote is pointing at the right process. Note
3926 there's no way to select "no process". */
3c9c4b83
PA
3927 set_general_process ();
3928
6d820c5c
DJ
3929 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3930 because we need both at the same time. */
ea9c271d 3931 msg = alloca (get_remote_packet_size ());
6d820c5c 3932
23860348 3933 /* Invite target to request symbol lookups. */
dc8acb97
MS
3934
3935 putpkt ("qSymbol::");
6d820c5c
DJ
3936 getpkt (&rs->buf, &rs->buf_size, 0);
3937 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2e9f7625 3938 reply = rs->buf;
dc8acb97 3939
61012eef 3940 while (startswith (reply, "qSymbol:"))
dc8acb97 3941 {
77e371c0
TT
3942 struct bound_minimal_symbol sym;
3943
dc8acb97 3944 tmp = &reply[8];
cfd77fa1 3945 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
3946 msg[end] = '\0';
3947 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 3948 if (sym.minsym == NULL)
ea9c271d 3949 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 3950 else
2bbe3cc1 3951 {
f5656ead 3952 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 3953 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
3954
3955 /* If this is a function address, return the start of code
3956 instead of any data function descriptor. */
f5656ead 3957 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
3958 sym_addr,
3959 &current_target);
3960
3961 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 3962 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
3963 }
3964
dc8acb97 3965 putpkt (msg);
6d820c5c 3966 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3967 reply = rs->buf;
dc8acb97
MS
3968 }
3969}
3970
9db8d71f 3971static struct serial *
baa336ce 3972remote_serial_open (const char *name)
9db8d71f
DJ
3973{
3974 static int udp_warning = 0;
3975
3976 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3977 of in ser-tcp.c, because it is the remote protocol assuming that the
3978 serial connection is reliable and not the serial connection promising
3979 to be. */
61012eef 3980 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 3981 {
3e43a32a
MS
3982 warning (_("The remote protocol may be unreliable over UDP.\n"
3983 "Some events may be lost, rendering further debugging "
3984 "impossible."));
9db8d71f
DJ
3985 udp_warning = 1;
3986 }
3987
3988 return serial_open (name);
3989}
3990
d914c394
SS
3991/* Inform the target of our permission settings. The permission flags
3992 work without this, but if the target knows the settings, it can do
3993 a couple things. First, it can add its own check, to catch cases
3994 that somehow manage to get by the permissions checks in target
3995 methods. Second, if the target is wired to disallow particular
3996 settings (for instance, a system in the field that is not set up to
3997 be able to stop at a breakpoint), it can object to any unavailable
3998 permissions. */
3999
4000void
c378d69d 4001remote_set_permissions (struct target_ops *self)
d914c394
SS
4002{
4003 struct remote_state *rs = get_remote_state ();
4004
bba74b36
YQ
4005 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4006 "WriteReg:%x;WriteMem:%x;"
4007 "InsertBreak:%x;InsertTrace:%x;"
4008 "InsertFastTrace:%x;Stop:%x",
4009 may_write_registers, may_write_memory,
4010 may_insert_breakpoints, may_insert_tracepoints,
4011 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4012 putpkt (rs->buf);
4013 getpkt (&rs->buf, &rs->buf_size, 0);
4014
4015 /* If the target didn't like the packet, warn the user. Do not try
4016 to undo the user's settings, that would just be maddening. */
4017 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4018 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4019}
4020
be2a5f71
DJ
4021/* This type describes each known response to the qSupported
4022 packet. */
4023struct protocol_feature
4024{
4025 /* The name of this protocol feature. */
4026 const char *name;
4027
4028 /* The default for this protocol feature. */
4029 enum packet_support default_support;
4030
4031 /* The function to call when this feature is reported, or after
4032 qSupported processing if the feature is not supported.
4033 The first argument points to this structure. The second
4034 argument indicates whether the packet requested support be
4035 enabled, disabled, or probed (or the default, if this function
4036 is being called at the end of processing and this feature was
4037 not reported). The third argument may be NULL; if not NULL, it
4038 is a NUL-terminated string taken from the packet following
4039 this feature's name and an equals sign. */
4040 void (*func) (const struct protocol_feature *, enum packet_support,
4041 const char *);
4042
4043 /* The corresponding packet for this feature. Only used if
4044 FUNC is remote_supported_packet. */
4045 int packet;
4046};
4047
be2a5f71
DJ
4048static void
4049remote_supported_packet (const struct protocol_feature *feature,
4050 enum packet_support support,
4051 const char *argument)
4052{
4053 if (argument)
4054 {
4055 warning (_("Remote qSupported response supplied an unexpected value for"
4056 " \"%s\"."), feature->name);
4057 return;
4058 }
4059
4082afcc 4060 remote_protocol_packets[feature->packet].support = support;
be2a5f71 4061}
be2a5f71
DJ
4062
4063static void
4064remote_packet_size (const struct protocol_feature *feature,
4065 enum packet_support support, const char *value)
4066{
4067 struct remote_state *rs = get_remote_state ();
4068
4069 int packet_size;
4070 char *value_end;
4071
4072 if (support != PACKET_ENABLE)
4073 return;
4074
4075 if (value == NULL || *value == '\0')
4076 {
4077 warning (_("Remote target reported \"%s\" without a size."),
4078 feature->name);
4079 return;
4080 }
4081
4082 errno = 0;
4083 packet_size = strtol (value, &value_end, 16);
4084 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4085 {
4086 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4087 feature->name, value);
4088 return;
4089 }
4090
4091 if (packet_size > MAX_REMOTE_PACKET_SIZE)
4092 {
4093 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
4094 packet_size, MAX_REMOTE_PACKET_SIZE);
4095 packet_size = MAX_REMOTE_PACKET_SIZE;
4096 }
4097
4098 /* Record the new maximum packet size. */
4099 rs->explicit_packet_size = packet_size;
4100}
4101
dc473cfb 4102static const struct protocol_feature remote_protocol_features[] = {
0876f84a 4103 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 4104 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 4105 PACKET_qXfer_auxv },
c78fa86a
GB
4106 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4107 PACKET_qXfer_exec_file },
23181151
DJ
4108 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4109 PACKET_qXfer_features },
cfa9d6d9
DJ
4110 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4111 PACKET_qXfer_libraries },
2268b414
JK
4112 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4113 PACKET_qXfer_libraries_svr4 },
ced63ec0 4114 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 4115 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 4116 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 4117 PACKET_qXfer_memory_map },
4de6483e
UW
4118 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4119 PACKET_qXfer_spu_read },
4120 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4121 PACKET_qXfer_spu_write },
07e059b5
VP
4122 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4123 PACKET_qXfer_osdata },
dc146f7c
VP
4124 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4125 PACKET_qXfer_threads },
b3b9301e
PA
4126 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4127 PACKET_qXfer_traceframe_info },
89be2091
DJ
4128 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4129 PACKET_QPassSignals },
9b224c5e
PA
4130 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4131 PACKET_QProgramSignals },
a6f3e723
SL
4132 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4133 PACKET_QStartNoAckMode },
4082afcc
PA
4134 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4135 PACKET_multiprocess_feature },
4136 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4137 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4138 PACKET_qXfer_siginfo_read },
4139 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4140 PACKET_qXfer_siginfo_write },
4082afcc 4141 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4142 PACKET_ConditionalTracepoints },
4082afcc 4143 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4144 PACKET_ConditionalBreakpoints },
4082afcc 4145 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4146 PACKET_BreakpointCommands },
4082afcc 4147 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4148 PACKET_FastTracepoints },
4082afcc 4149 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4150 PACKET_StaticTracepoints },
4082afcc 4151 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4152 PACKET_InstallInTrace},
4082afcc
PA
4153 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4154 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4155 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4156 PACKET_bc },
4157 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4158 PACKET_bs },
409873ef
SS
4159 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4160 PACKET_TracepointSource },
d914c394
SS
4161 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4162 PACKET_QAllow },
4082afcc
PA
4163 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4164 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4165 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4166 PACKET_qXfer_fdpic },
169081d0
TG
4167 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4168 PACKET_qXfer_uib },
03583c20
UW
4169 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4170 PACKET_QDisableRandomization },
d1feda86 4171 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4172 { "QTBuffer:size", PACKET_DISABLE,
4173 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4174 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4175 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4176 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 4177 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 4178 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4179 PACKET_qXfer_btrace },
4180 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4181 PACKET_qXfer_btrace_conf },
4182 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4183 PACKET_Qbtrace_conf_bts_size },
4184 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4185 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
4186 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4187 PACKET_fork_event_feature },
4188 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4189 PACKET_vfork_event_feature },
b20a6524
MM
4190 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4191 PACKET_Qbtrace_conf_pt_size }
be2a5f71
DJ
4192};
4193
c8d5aac9
L
4194static char *remote_support_xml;
4195
4196/* Register string appended to "xmlRegisters=" in qSupported query. */
4197
4198void
6e39997a 4199register_remote_support_xml (const char *xml)
c8d5aac9
L
4200{
4201#if defined(HAVE_LIBEXPAT)
4202 if (remote_support_xml == NULL)
c4f7c687 4203 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4204 else
4205 {
4206 char *copy = xstrdup (remote_support_xml + 13);
4207 char *p = strtok (copy, ",");
4208
4209 do
4210 {
4211 if (strcmp (p, xml) == 0)
4212 {
4213 /* already there */
4214 xfree (copy);
4215 return;
4216 }
4217 }
4218 while ((p = strtok (NULL, ",")) != NULL);
4219 xfree (copy);
4220
94b0dee1
PA
4221 remote_support_xml = reconcat (remote_support_xml,
4222 remote_support_xml, ",", xml,
4223 (char *) NULL);
c8d5aac9
L
4224 }
4225#endif
4226}
4227
4228static char *
4229remote_query_supported_append (char *msg, const char *append)
4230{
4231 if (msg)
94b0dee1 4232 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4233 else
4234 return xstrdup (append);
4235}
4236
be2a5f71
DJ
4237static void
4238remote_query_supported (void)
4239{
4240 struct remote_state *rs = get_remote_state ();
4241 char *next;
4242 int i;
4243 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4244
4245 /* The packet support flags are handled differently for this packet
4246 than for most others. We treat an error, a disabled packet, and
4247 an empty response identically: any features which must be reported
4248 to be used will be automatically disabled. An empty buffer
4249 accomplishes this, since that is also the representation for a list
4250 containing no features. */
4251
4252 rs->buf[0] = 0;
4082afcc 4253 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4254 {
c8d5aac9 4255 char *q = NULL;
94b0dee1 4256 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4257
901f9912 4258 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4259
f7e6eed5
PA
4260 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4261 q = remote_query_supported_append (q, "swbreak+");
4262 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4263 q = remote_query_supported_append (q, "hwbreak+");
4264
c8d5aac9
L
4265 if (remote_support_xml)
4266 q = remote_query_supported_append (q, remote_support_xml);
4267
dde08ee1
PA
4268 q = remote_query_supported_append (q, "qRelocInsn+");
4269
89245bc0
DB
4270 if (rs->extended)
4271 {
4272 if (packet_set_cmd_state (PACKET_fork_event_feature)
4273 != AUTO_BOOLEAN_FALSE)
4274 q = remote_query_supported_append (q, "fork-events+");
4275 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4276 != AUTO_BOOLEAN_FALSE)
4277 q = remote_query_supported_append (q, "vfork-events+");
4278 }
4279
dde08ee1
PA
4280 q = reconcat (q, "qSupported:", q, (char *) NULL);
4281 putpkt (q);
82f73884 4282
94b0dee1
PA
4283 do_cleanups (old_chain);
4284
be2a5f71
DJ
4285 getpkt (&rs->buf, &rs->buf_size, 0);
4286
4287 /* If an error occured, warn, but do not return - just reset the
4288 buffer to empty and go on to disable features. */
4289 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4290 == PACKET_ERROR)
4291 {
4292 warning (_("Remote failure reply: %s"), rs->buf);
4293 rs->buf[0] = 0;
4294 }
4295 }
4296
4297 memset (seen, 0, sizeof (seen));
4298
4299 next = rs->buf;
4300 while (*next)
4301 {
4302 enum packet_support is_supported;
4303 char *p, *end, *name_end, *value;
4304
4305 /* First separate out this item from the rest of the packet. If
4306 there's another item after this, we overwrite the separator
4307 (terminated strings are much easier to work with). */
4308 p = next;
4309 end = strchr (p, ';');
4310 if (end == NULL)
4311 {
4312 end = p + strlen (p);
4313 next = end;
4314 }
4315 else
4316 {
89be2091
DJ
4317 *end = '\0';
4318 next = end + 1;
4319
be2a5f71
DJ
4320 if (end == p)
4321 {
4322 warning (_("empty item in \"qSupported\" response"));
4323 continue;
4324 }
be2a5f71
DJ
4325 }
4326
4327 name_end = strchr (p, '=');
4328 if (name_end)
4329 {
4330 /* This is a name=value entry. */
4331 is_supported = PACKET_ENABLE;
4332 value = name_end + 1;
4333 *name_end = '\0';
4334 }
4335 else
4336 {
4337 value = NULL;
4338 switch (end[-1])
4339 {
4340 case '+':
4341 is_supported = PACKET_ENABLE;
4342 break;
4343
4344 case '-':
4345 is_supported = PACKET_DISABLE;
4346 break;
4347
4348 case '?':
4349 is_supported = PACKET_SUPPORT_UNKNOWN;
4350 break;
4351
4352 default:
3e43a32a
MS
4353 warning (_("unrecognized item \"%s\" "
4354 "in \"qSupported\" response"), p);
be2a5f71
DJ
4355 continue;
4356 }
4357 end[-1] = '\0';
4358 }
4359
4360 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4361 if (strcmp (remote_protocol_features[i].name, p) == 0)
4362 {
4363 const struct protocol_feature *feature;
4364
4365 seen[i] = 1;
4366 feature = &remote_protocol_features[i];
4367 feature->func (feature, is_supported, value);
4368 break;
4369 }
4370 }
4371
4372 /* If we increased the packet size, make sure to increase the global
4373 buffer size also. We delay this until after parsing the entire
4374 qSupported packet, because this is the same buffer we were
4375 parsing. */
4376 if (rs->buf_size < rs->explicit_packet_size)
4377 {
4378 rs->buf_size = rs->explicit_packet_size;
4379 rs->buf = xrealloc (rs->buf, rs->buf_size);
4380 }
4381
4382 /* Handle the defaults for unmentioned features. */
4383 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4384 if (!seen[i])
4385 {
4386 const struct protocol_feature *feature;
4387
4388 feature = &remote_protocol_features[i];
4389 feature->func (feature, feature->default_support, NULL);
4390 }
4391}
4392
78a095c3
JK
4393/* Remove any of the remote.c targets from target stack. Upper targets depend
4394 on it so remove them first. */
4395
4396static void
4397remote_unpush_target (void)
4398{
4399 pop_all_targets_above (process_stratum - 1);
4400}
be2a5f71 4401
c906108c 4402static void
014f9477 4403remote_open_1 (const char *name, int from_tty,
3e43a32a 4404 struct target_ops *target, int extended_p)
c906108c 4405{
d01949b6 4406 struct remote_state *rs = get_remote_state ();
a6f3e723 4407
c906108c 4408 if (name == 0)
8a3fe4f8 4409 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4410 "serial device is attached to the remote system\n"
8a3fe4f8 4411 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4412
23860348 4413 /* See FIXME above. */
c6ebd6cf 4414 if (!target_async_permitted)
92d1e331 4415 wait_forever_enabled_p = 1;
6426a772 4416
2d717e4f 4417 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4418 Ask this question first, before target_preopen has a chance to kill
4419 anything. */
5d93a237 4420 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4421 {
78a095c3
JK
4422 if (from_tty
4423 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4424 error (_("Still connected."));
4425 }
4426
78a095c3 4427 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4428 target_preopen (from_tty);
4429
89be2091 4430 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4431 xfree (rs->last_pass_packet);
4432 rs->last_pass_packet = NULL;
89be2091 4433
9b224c5e
PA
4434 /* Make sure we send the program signals list the next time we
4435 resume. */
5e4a05c4
TT
4436 xfree (rs->last_program_signals_packet);
4437 rs->last_program_signals_packet = NULL;
9b224c5e 4438
ad9a8f3f 4439 remote_fileio_reset ();
1dd41f16
NS
4440 reopen_exec_file ();
4441 reread_symbols ();
4442
5d93a237
TT
4443 rs->remote_desc = remote_serial_open (name);
4444 if (!rs->remote_desc)
c906108c
SS
4445 perror_with_name (name);
4446
4447 if (baud_rate != -1)
4448 {
5d93a237 4449 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4450 {
9b74d5d3
KB
4451 /* The requested speed could not be set. Error out to
4452 top level after closing remote_desc. Take care to
4453 set remote_desc to NULL to avoid closing remote_desc
4454 more than once. */
5d93a237
TT
4455 serial_close (rs->remote_desc);
4456 rs->remote_desc = NULL;
c906108c
SS
4457 perror_with_name (name);
4458 }
4459 }
4460
236af5e3 4461 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 4462 serial_raw (rs->remote_desc);
c906108c
SS
4463
4464 /* If there is something sitting in the buffer we might take it as a
4465 response to a command, which would be bad. */
5d93a237 4466 serial_flush_input (rs->remote_desc);
c906108c
SS
4467
4468 if (from_tty)
4469 {
4470 puts_filtered ("Remote debugging using ");
4471 puts_filtered (name);
4472 puts_filtered ("\n");
4473 }
23860348 4474 push_target (target); /* Switch to using remote target now. */
c906108c 4475
74531fed
PA
4476 /* Register extra event sources in the event loop. */
4477 remote_async_inferior_event_token
4478 = create_async_event_handler (remote_async_inferior_event_handler,
4479 NULL);
5965e028 4480 rs->notif_state = remote_notif_state_allocate ();
74531fed 4481
be2a5f71
DJ
4482 /* Reset the target state; these things will be queried either by
4483 remote_query_supported or as they are needed. */
ca4f7f8b 4484 reset_all_packet_configs_support ();
74531fed 4485 rs->cached_wait_status = 0;
be2a5f71 4486 rs->explicit_packet_size = 0;
a6f3e723 4487 rs->noack_mode = 0;
82f73884 4488 rs->extended = extended_p;
e24a49d8 4489 rs->waiting_for_stop_reply = 0;
3a29589a 4490 rs->ctrlc_pending_p = 0;
802188a7 4491
47f8a51d
TT
4492 rs->general_thread = not_sent_ptid;
4493 rs->continue_thread = not_sent_ptid;
262e1174 4494 rs->remote_traceframe_number = -1;
c906108c 4495
9d1f7ab2 4496 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
4497 rs->use_threadinfo_query = 1;
4498 rs->use_threadextra_query = 1;
9d1f7ab2 4499
c6ebd6cf 4500 if (target_async_permitted)
92d1e331 4501 {
23860348 4502 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4503 remote_async_terminal_ours_p = 1;
4504
4505 /* FIXME: cagney/1999-09-23: During the initial connection it is
4506 assumed that the target is already ready and able to respond to
0df8b418 4507 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4508 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4509 around this. Eventually a mechanism that allows
92d1e331 4510 wait_for_inferior() to expect/get timeouts will be
23860348 4511 implemented. */
92d1e331
DJ
4512 wait_forever_enabled_p = 0;
4513 }
4514
23860348 4515 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4516 no_shared_libraries (NULL, 0);
f78f6cf1 4517
74531fed
PA
4518 /* Start afresh. */
4519 init_thread_list ();
4520
36918e70 4521 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4522 target (we'd otherwise be in an inconsistent state) and then
4523 propogate the error on up the exception chain. This ensures that
4524 the caller doesn't stumble along blindly assuming that the
4525 function succeeded. The CLI doesn't have this problem but other
4526 UI's, such as MI do.
36918e70
AC
4527
4528 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4529 this function should return an error indication letting the
ce2826aa 4530 caller restore the previous state. Unfortunately the command
36918e70
AC
4531 ``target remote'' is directly wired to this function making that
4532 impossible. On a positive note, the CLI side of this problem has
4533 been fixed - the function set_cmd_context() makes it possible for
4534 all the ``target ....'' commands to share a common callback
4535 function. See cli-dump.c. */
109c3e39 4536 {
2d717e4f 4537
492d29ea 4538 TRY
04bd08de
TT
4539 {
4540 remote_start_remote (from_tty, target, extended_p);
4541 }
492d29ea 4542 CATCH (ex, RETURN_MASK_ALL)
109c3e39 4543 {
c8d104ad
PA
4544 /* Pop the partially set up target - unless something else did
4545 already before throwing the exception. */
5d93a237 4546 if (rs->remote_desc != NULL)
78a095c3 4547 remote_unpush_target ();
c6ebd6cf 4548 if (target_async_permitted)
109c3e39
AC
4549 wait_forever_enabled_p = 1;
4550 throw_exception (ex);
4551 }
492d29ea 4552 END_CATCH
109c3e39 4553 }
c906108c 4554
f4abbc16
MM
4555 remote_btrace_reset ();
4556
c6ebd6cf 4557 if (target_async_permitted)
92d1e331 4558 wait_forever_enabled_p = 1;
43ff13b4
JM
4559}
4560
de0d863e
DB
4561/* Detach the specified process. */
4562
4563static void
4564remote_detach_pid (int pid)
4565{
4566 struct remote_state *rs = get_remote_state ();
4567
4568 if (remote_multi_process_p (rs))
4569 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4570 else
4571 strcpy (rs->buf, "D");
4572
4573 putpkt (rs->buf);
4574 getpkt (&rs->buf, &rs->buf_size, 0);
4575
4576 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4577 ;
4578 else if (rs->buf[0] == '\0')
4579 error (_("Remote doesn't know how to detach"));
4580 else
4581 error (_("Can't detach process."));
4582}
4583
4584/* This detaches a program to which we previously attached, using
4585 inferior_ptid to identify the process. After this is done, GDB
4586 can be used to debug some other program. We better not have left
4587 any breakpoints in the target program or it'll die when it hits
4588 one. */
c906108c
SS
4589
4590static void
de0d863e 4591remote_detach_1 (const char *args, int from_tty)
c906108c 4592{
82f73884 4593 int pid = ptid_get_pid (inferior_ptid);
d01949b6 4594 struct remote_state *rs = get_remote_state ();
de0d863e
DB
4595 struct thread_info *tp = find_thread_ptid (inferior_ptid);
4596 int is_fork_parent;
c906108c
SS
4597
4598 if (args)
8a3fe4f8 4599 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 4600
2d717e4f
DJ
4601 if (!target_has_execution)
4602 error (_("No process to detach from."));
4603
7cee1e54
PA
4604 if (from_tty)
4605 {
4606 char *exec_file = get_exec_file (0);
4607 if (exec_file == NULL)
4608 exec_file = "";
4609 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4610 target_pid_to_str (pid_to_ptid (pid)));
4611 gdb_flush (gdb_stdout);
4612 }
4613
c906108c 4614 /* Tell the remote target to detach. */
de0d863e 4615 remote_detach_pid (pid);
82f73884 4616
de0d863e 4617 if (from_tty && !rs->extended)
7cee1e54 4618 puts_filtered (_("Ending remote debugging.\n"));
82f73884 4619
de0d863e
DB
4620 /* Check to see if we are detaching a fork parent. Note that if we
4621 are detaching a fork child, tp == NULL. */
4622 is_fork_parent = (tp != NULL
4623 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4624
4625 /* If doing detach-on-fork, we don't mourn, because that will delete
4626 breakpoints that should be available for the followed inferior. */
4627 if (!is_fork_parent)
4628 target_mourn_inferior ();
4629 else
4630 {
4631 inferior_ptid = null_ptid;
4632 detach_inferior (pid);
4633 }
2d717e4f
DJ
4634}
4635
4636static void
52554a0e 4637remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4638{
de0d863e 4639 remote_detach_1 (args, from_tty);
2d717e4f
DJ
4640}
4641
4642static void
52554a0e 4643extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4644{
de0d863e
DB
4645 remote_detach_1 (args, from_tty);
4646}
4647
4648/* Target follow-fork function for remote targets. On entry, and
4649 at return, the current inferior is the fork parent.
4650
4651 Note that although this is currently only used for extended-remote,
4652 it is named remote_follow_fork in anticipation of using it for the
4653 remote target as well. */
4654
4655static int
4656remote_follow_fork (struct target_ops *ops, int follow_child,
4657 int detach_fork)
4658{
4659 struct remote_state *rs = get_remote_state ();
c269dbdb 4660 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 4661
c269dbdb
DB
4662 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
4663 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
4664 {
4665 /* When following the parent and detaching the child, we detach
4666 the child here. For the case of following the child and
4667 detaching the parent, the detach is done in the target-
4668 independent follow fork code in infrun.c. We can't use
4669 target_detach when detaching an unfollowed child because
4670 the client side doesn't know anything about the child. */
4671 if (detach_fork && !follow_child)
4672 {
4673 /* Detach the fork child. */
4674 ptid_t child_ptid;
4675 pid_t child_pid;
4676
4677 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
4678 child_pid = ptid_get_pid (child_ptid);
4679
4680 remote_detach_pid (child_pid);
4681 detach_inferior (child_pid);
4682 }
4683 }
4684 return 0;
c906108c
SS
4685}
4686
6ad8ae5c
DJ
4687/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4688
43ff13b4 4689static void
fee354ee 4690remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 4691{
43ff13b4 4692 if (args)
2d717e4f 4693 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 4694
2d717e4f 4695 /* Make sure we unpush even the extended remote targets; mourn
20f796c9 4696 won't do it. So call remote_mourn directly instead of
2d717e4f 4697 target_mourn_inferior. */
20f796c9 4698 remote_mourn (target);
2d717e4f 4699
43ff13b4
JM
4700 if (from_tty)
4701 puts_filtered ("Ending remote debugging.\n");
4702}
4703
2d717e4f
DJ
4704/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4705 be chatty about it. */
4706
4707static void
20f796c9
GB
4708extended_remote_attach (struct target_ops *target, const char *args,
4709 int from_tty)
2d717e4f
DJ
4710{
4711 struct remote_state *rs = get_remote_state ();
be86555c 4712 int pid;
96ef3384 4713 char *wait_status = NULL;
2d717e4f 4714
74164c56 4715 pid = parse_pid_to_attach (args);
2d717e4f 4716
74164c56
JK
4717 /* Remote PID can be freely equal to getpid, do not check it here the same
4718 way as in other targets. */
2d717e4f 4719
4082afcc 4720 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
4721 error (_("This target does not support attaching to a process"));
4722
7cee1e54
PA
4723 if (from_tty)
4724 {
4725 char *exec_file = get_exec_file (0);
4726
4727 if (exec_file)
4728 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4729 target_pid_to_str (pid_to_ptid (pid)));
4730 else
4731 printf_unfiltered (_("Attaching to %s\n"),
4732 target_pid_to_str (pid_to_ptid (pid)));
4733
4734 gdb_flush (gdb_stdout);
4735 }
4736
bba74b36 4737 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
4738 putpkt (rs->buf);
4739 getpkt (&rs->buf, &rs->buf_size, 0);
4740
4082afcc
PA
4741 switch (packet_ok (rs->buf,
4742 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 4743 {
4082afcc 4744 case PACKET_OK:
74531fed
PA
4745 if (!non_stop)
4746 {
4747 /* Save the reply for later. */
4748 wait_status = alloca (strlen (rs->buf) + 1);
4749 strcpy (wait_status, rs->buf);
4750 }
4751 else if (strcmp (rs->buf, "OK") != 0)
4752 error (_("Attaching to %s failed with: %s"),
4753 target_pid_to_str (pid_to_ptid (pid)),
4754 rs->buf);
4082afcc
PA
4755 break;
4756 case PACKET_UNKNOWN:
4757 error (_("This target does not support attaching to a process"));
4758 default:
4759 error (_("Attaching to %s failed"),
4760 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 4761 }
2d717e4f 4762
1b6e6f5c 4763 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 4764
2d717e4f 4765 inferior_ptid = pid_to_ptid (pid);
79d7f229 4766
bad34192
PA
4767 if (non_stop)
4768 {
4769 struct thread_info *thread;
79d7f229 4770
bad34192 4771 /* Get list of threads. */
e8032dde 4772 remote_update_thread_list (target);
82f73884 4773
bad34192
PA
4774 thread = first_thread_of_process (pid);
4775 if (thread)
4776 inferior_ptid = thread->ptid;
4777 else
4778 inferior_ptid = pid_to_ptid (pid);
4779
4780 /* Invalidate our notion of the remote current thread. */
47f8a51d 4781 record_currthread (rs, minus_one_ptid);
bad34192 4782 }
74531fed 4783 else
bad34192
PA
4784 {
4785 /* Now, if we have thread information, update inferior_ptid. */
4786 inferior_ptid = remote_current_thread (inferior_ptid);
4787
4788 /* Add the main thread to the thread list. */
4789 add_thread_silent (inferior_ptid);
4790 }
c0a2216e 4791
96ef3384
UW
4792 /* Next, if the target can specify a description, read it. We do
4793 this before anything involving memory or registers. */
4794 target_find_description ();
4795
74531fed
PA
4796 if (!non_stop)
4797 {
4798 /* Use the previously fetched status. */
4799 gdb_assert (wait_status != NULL);
4800
4801 if (target_can_async_p ())
4802 {
722247f1
YQ
4803 struct notif_event *reply
4804 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 4805
722247f1 4806 push_stop_reply ((struct stop_reply *) reply);
74531fed 4807
6a3753b3 4808 target_async (1);
74531fed
PA
4809 }
4810 else
4811 {
4812 gdb_assert (wait_status != NULL);
4813 strcpy (rs->buf, wait_status);
4814 rs->cached_wait_status = 1;
4815 }
4816 }
4817 else
4818 gdb_assert (wait_status == NULL);
2d717e4f
DJ
4819}
4820
b9c1d481
AS
4821/* Implementation of the to_post_attach method. */
4822
4823static void
4824extended_remote_post_attach (struct target_ops *ops, int pid)
4825{
4826 /* In certain cases GDB might not have had the chance to start
4827 symbol lookup up until now. This could happen if the debugged
4828 binary is not using shared libraries, the vsyscall page is not
4829 present (on Linux) and the binary itself hadn't changed since the
4830 debugging process was started. */
4831 if (symfile_objfile != NULL)
4832 remote_check_symbols();
4833}
4834
c906108c 4835\f
506fb367
DJ
4836/* Check for the availability of vCont. This function should also check
4837 the response. */
c906108c
SS
4838
4839static void
6d820c5c 4840remote_vcont_probe (struct remote_state *rs)
c906108c 4841{
2e9f7625 4842 char *buf;
6d820c5c 4843
2e9f7625
DJ
4844 strcpy (rs->buf, "vCont?");
4845 putpkt (rs->buf);
6d820c5c 4846 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4847 buf = rs->buf;
c906108c 4848
506fb367 4849 /* Make sure that the features we assume are supported. */
61012eef 4850 if (startswith (buf, "vCont"))
506fb367
DJ
4851 {
4852 char *p = &buf[5];
4853 int support_s, support_S, support_c, support_C;
4854
4855 support_s = 0;
4856 support_S = 0;
4857 support_c = 0;
4858 support_C = 0;
d458bd84 4859 rs->supports_vCont.t = 0;
c1e36e3e 4860 rs->supports_vCont.r = 0;
506fb367
DJ
4861 while (p && *p == ';')
4862 {
4863 p++;
4864 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4865 support_s = 1;
4866 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4867 support_S = 1;
4868 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4869 support_c = 1;
4870 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4871 support_C = 1;
74531fed 4872 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 4873 rs->supports_vCont.t = 1;
c1e36e3e
PA
4874 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4875 rs->supports_vCont.r = 1;
506fb367
DJ
4876
4877 p = strchr (p, ';');
4878 }
c906108c 4879
506fb367
DJ
4880 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4881 BUF will make packet_ok disable the packet. */
4882 if (!support_s || !support_S || !support_c || !support_C)
4883 buf[0] = 0;
4884 }
c906108c 4885
444abaca 4886 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 4887}
c906108c 4888
0d8f58ca
PA
4889/* Helper function for building "vCont" resumptions. Write a
4890 resumption to P. ENDP points to one-passed-the-end of the buffer
4891 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4892 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4893 resumed thread should be single-stepped and/or signalled. If PTID
4894 equals minus_one_ptid, then all threads are resumed; if PTID
4895 represents a process, then all threads of the process are resumed;
4896 the thread to be stepped and/or signalled is given in the global
4897 INFERIOR_PTID. */
4898
4899static char *
4900append_resumption (char *p, char *endp,
2ea28649 4901 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
4902{
4903 struct remote_state *rs = get_remote_state ();
4904
a493e3e2 4905 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 4906 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
4907 else if (step
4908 /* GDB is willing to range step. */
4909 && use_range_stepping
4910 /* Target supports range stepping. */
4911 && rs->supports_vCont.r
4912 /* We don't currently support range stepping multiple
4913 threads with a wildcard (though the protocol allows it,
4914 so stubs shouldn't make an active effort to forbid
4915 it). */
4916 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4917 {
4918 struct thread_info *tp;
4919
4920 if (ptid_equal (ptid, minus_one_ptid))
4921 {
4922 /* If we don't know about the target thread's tid, then
4923 we're resuming magic_null_ptid (see caller). */
4924 tp = find_thread_ptid (magic_null_ptid);
4925 }
4926 else
4927 tp = find_thread_ptid (ptid);
4928 gdb_assert (tp != NULL);
4929
4930 if (tp->control.may_range_step)
4931 {
4932 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4933
4934 p += xsnprintf (p, endp - p, ";r%s,%s",
4935 phex_nz (tp->control.step_range_start,
4936 addr_size),
4937 phex_nz (tp->control.step_range_end,
4938 addr_size));
4939 }
4940 else
4941 p += xsnprintf (p, endp - p, ";s");
4942 }
0d8f58ca
PA
4943 else if (step)
4944 p += xsnprintf (p, endp - p, ";s");
a493e3e2 4945 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
4946 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4947 else
4948 p += xsnprintf (p, endp - p, ";c");
4949
4950 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4951 {
4952 ptid_t nptid;
4953
4954 /* All (-1) threads of process. */
ba348170 4955 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
4956
4957 p += xsnprintf (p, endp - p, ":");
4958 p = write_ptid (p, endp, nptid);
4959 }
4960 else if (!ptid_equal (ptid, minus_one_ptid))
4961 {
4962 p += xsnprintf (p, endp - p, ":");
4963 p = write_ptid (p, endp, ptid);
4964 }
4965
4966 return p;
4967}
4968
e5ef252a
PA
4969/* Append a vCont continue-with-signal action for threads that have a
4970 non-zero stop signal. */
4971
4972static char *
4973append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4974{
4975 struct thread_info *thread;
4976
034f788c 4977 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
4978 if (ptid_match (thread->ptid, ptid)
4979 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 4980 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
4981 {
4982 p = append_resumption (p, endp, thread->ptid,
4983 0, thread->suspend.stop_signal);
4984 thread->suspend.stop_signal = GDB_SIGNAL_0;
4985 }
4986
4987 return p;
4988}
4989
506fb367
DJ
4990/* Resume the remote inferior by using a "vCont" packet. The thread
4991 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
4992 resumed thread should be single-stepped and/or signalled. If PTID
4993 equals minus_one_ptid, then all threads are resumed; the thread to
4994 be stepped and/or signalled is given in the global INFERIOR_PTID.
4995 This function returns non-zero iff it resumes the inferior.
44eaed12 4996
506fb367
DJ
4997 This function issues a strict subset of all possible vCont commands at the
4998 moment. */
44eaed12 4999
506fb367 5000static int
2ea28649 5001remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5002{
5003 struct remote_state *rs = get_remote_state ();
82f73884
PA
5004 char *p;
5005 char *endp;
44eaed12 5006
4082afcc 5007 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5008 remote_vcont_probe (rs);
44eaed12 5009
4082afcc 5010 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5011 return 0;
44eaed12 5012
82f73884
PA
5013 p = rs->buf;
5014 endp = rs->buf + get_remote_packet_size ();
5015
506fb367
DJ
5016 /* If we could generate a wider range of packets, we'd have to worry
5017 about overflowing BUF. Should there be a generic
5018 "multi-part-packet" packet? */
5019
0d8f58ca
PA
5020 p += xsnprintf (p, endp - p, "vCont");
5021
79d7f229 5022 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5023 {
79d7f229
PA
5024 /* MAGIC_NULL_PTID means that we don't have any active threads,
5025 so we don't have any TID numbers the inferior will
5026 understand. Make sure to only send forms that do not specify
5027 a TID. */
a9cbf802 5028 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5029 }
0d8f58ca 5030 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5031 {
0d8f58ca
PA
5032 /* Resume all threads (of all processes, or of a single
5033 process), with preference for INFERIOR_PTID. This assumes
5034 inferior_ptid belongs to the set of all threads we are about
5035 to resume. */
a493e3e2 5036 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5037 {
0d8f58ca
PA
5038 /* Step inferior_ptid, with or without signal. */
5039 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5040 }
0d8f58ca 5041
e5ef252a
PA
5042 /* Also pass down any pending signaled resumption for other
5043 threads not the current. */
5044 p = append_pending_thread_resumptions (p, endp, ptid);
5045
0d8f58ca 5046 /* And continue others without a signal. */
a493e3e2 5047 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5048 }
5049 else
506fb367
DJ
5050 {
5051 /* Scheduler locking; resume only PTID. */
a9cbf802 5052 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5053 }
c906108c 5054
82f73884
PA
5055 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5056 putpkt (rs->buf);
506fb367 5057
74531fed
PA
5058 if (non_stop)
5059 {
5060 /* In non-stop, the stub replies to vCont with "OK". The stop
5061 reply will be reported asynchronously by means of a `%Stop'
5062 notification. */
5063 getpkt (&rs->buf, &rs->buf_size, 0);
5064 if (strcmp (rs->buf, "OK") != 0)
5065 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5066 }
5067
506fb367 5068 return 1;
c906108c 5069}
43ff13b4 5070
506fb367
DJ
5071/* Tell the remote machine to resume. */
5072
43ff13b4 5073static void
28439f5e 5074remote_resume (struct target_ops *ops,
2ea28649 5075 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5076{
d01949b6 5077 struct remote_state *rs = get_remote_state ();
2e9f7625 5078 char *buf;
43ff13b4 5079
722247f1
YQ
5080 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5081 (explained in remote-notif.c:handle_notification) so
5082 remote_notif_process is not called. We need find a place where
5083 it is safe to start a 'vNotif' sequence. It is good to do it
5084 before resuming inferior, because inferior was stopped and no RSP
5085 traffic at that moment. */
5086 if (!non_stop)
5965e028 5087 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 5088
b73be471 5089 rs->last_sent_signal = siggnal;
280ceea3 5090 rs->last_sent_step = step;
43ff13b4 5091
506fb367 5092 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
5093 /* No reverse support (yet) for vCont. */
5094 if (execution_direction != EXEC_REVERSE)
5095 if (remote_vcont_resume (ptid, step, siggnal))
5096 goto done;
506fb367 5097
79d7f229
PA
5098 /* All other supported resume packets do use Hc, so set the continue
5099 thread. */
5100 if (ptid_equal (ptid, minus_one_ptid))
5101 set_continue_thread (any_thread_ptid);
506fb367 5102 else
79d7f229 5103 set_continue_thread (ptid);
506fb367 5104
2e9f7625 5105 buf = rs->buf;
b2175913
MS
5106 if (execution_direction == EXEC_REVERSE)
5107 {
5108 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 5109 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 5110 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 5111 siggnal);
40ab02ce 5112
4082afcc 5113 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
40ab02ce 5114 error (_("Remote reverse-step not supported."));
4082afcc 5115 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
08c93ed9 5116 error (_("Remote reverse-continue not supported."));
40ab02ce 5117
b2175913
MS
5118 strcpy (buf, step ? "bs" : "bc");
5119 }
a493e3e2 5120 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
5121 {
5122 buf[0] = step ? 'S' : 'C';
c5aa993b 5123 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 5124 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
5125 buf[3] = '\0';
5126 }
5127 else
c5aa993b 5128 strcpy (buf, step ? "s" : "c");
506fb367 5129
44eaed12 5130 putpkt (buf);
43ff13b4 5131
75c99385 5132 done:
2acceee2 5133 /* We are about to start executing the inferior, let's register it
0df8b418
MS
5134 with the event loop. NOTE: this is the one place where all the
5135 execution commands end up. We could alternatively do this in each
23860348 5136 of the execution commands in infcmd.c. */
2acceee2
JM
5137 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5138 into infcmd.c in order to allow inferior function calls to work
23860348 5139 NOT asynchronously. */
362646f5 5140 if (target_can_async_p ())
6a3753b3 5141 target_async (1);
e24a49d8
PA
5142
5143 /* We've just told the target to resume. The remote server will
5144 wait for the inferior to stop, and then send a stop reply. In
5145 the mean time, we can't start another command/query ourselves
74531fed
PA
5146 because the stub wouldn't be ready to process it. This applies
5147 only to the base all-stop protocol, however. In non-stop (which
5148 only supports vCont), the stub replies with an "OK", and is
5149 immediate able to process further serial input. */
5150 if (!non_stop)
5151 rs->waiting_for_stop_reply = 1;
43ff13b4 5152}
c906108c 5153\f
43ff13b4
JM
5154
5155/* Set up the signal handler for SIGINT, while the target is
23860348 5156 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 5157static void
934b9bac 5158async_initialize_sigint_signal_handler (void)
43ff13b4 5159{
934b9bac 5160 signal (SIGINT, async_handle_remote_sigint);
43ff13b4
JM
5161}
5162
23860348 5163/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 5164static void
934b9bac 5165async_handle_remote_sigint (int sig)
43ff13b4 5166{
934b9bac 5167 signal (sig, async_handle_remote_sigint_twice);
b2ee242b
PA
5168 /* Note we need to go through gdb_call_async_signal_handler in order
5169 to wake up the event loop on Windows. */
5170 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
43ff13b4
JM
5171}
5172
5173/* Signal handler for SIGINT, installed after SIGINT has already been
5174 sent once. It will take effect the second time that the user sends
23860348 5175 a ^C. */
43ff13b4 5176static void
934b9bac 5177async_handle_remote_sigint_twice (int sig)
43ff13b4 5178{
934b9bac 5179 signal (sig, async_handle_remote_sigint);
b2ee242b
PA
5180 /* See note in async_handle_remote_sigint. */
5181 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
43ff13b4
JM
5182}
5183
6426a772 5184/* Perform the real interruption of the target execution, in response
23860348 5185 to a ^C. */
c5aa993b 5186static void
fba45db2 5187async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
5188{
5189 if (remote_debug)
248fd3bf 5190 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
43ff13b4 5191
94cc34af 5192 target_stop (inferior_ptid);
43ff13b4
JM
5193}
5194
0df8b418 5195/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 5196 up on the target alltogether. */
47e1ce27 5197static void
fba45db2 5198async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 5199{
2df3850c 5200 if (remote_debug)
248fd3bf 5201 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
b803fb0f
DJ
5202
5203 interrupt_query ();
43ff13b4
JM
5204}
5205
5206/* Reinstall the usual SIGINT handlers, after the target has
23860348 5207 stopped. */
6426a772 5208static void
934b9bac 5209async_cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
5210{
5211 signal (SIGINT, handle_sigint);
43ff13b4
JM
5212}
5213
c906108c
SS
5214/* Send ^C to target to halt it. Target will respond, and send us a
5215 packet. */
507f3c78 5216static void (*ofunc) (int);
c906108c 5217
bfedc46a
PA
5218/* The command line interface's interrupt routine. This function is installed
5219 as a signal handler for SIGINT. The first time a user requests an
5220 interrupt, we call remote_interrupt to send a break or ^C. If there is no
7a292a7a 5221 response from the target (it didn't stop when the user requested it),
23860348 5222 we ask the user if he'd like to detach from the target. */
bfedc46a 5223
c906108c 5224static void
934b9bac 5225sync_remote_interrupt (int signo)
c906108c 5226{
23860348 5227 /* If this doesn't work, try more severe steps. */
934b9bac 5228 signal (signo, sync_remote_interrupt_twice);
7a292a7a 5229
934b9bac 5230 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
7a292a7a
SS
5231}
5232
5233/* The user typed ^C twice. */
5234
5235static void
934b9bac 5236sync_remote_interrupt_twice (int signo)
7a292a7a
SS
5237{
5238 signal (signo, ofunc);
934b9bac
JK
5239 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5240 signal (signo, sync_remote_interrupt);
c906108c 5241}
7a292a7a 5242
74531fed
PA
5243/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5244 thread, all threads of a remote process, or all threads of all
5245 processes. */
5246
5247static void
5248remote_stop_ns (ptid_t ptid)
5249{
5250 struct remote_state *rs = get_remote_state ();
5251 char *p = rs->buf;
5252 char *endp = rs->buf + get_remote_packet_size ();
74531fed 5253
4082afcc 5254 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
5255 remote_vcont_probe (rs);
5256
d458bd84 5257 if (!rs->supports_vCont.t)
74531fed
PA
5258 error (_("Remote server does not support stopping threads"));
5259
f91d3df5
PA
5260 if (ptid_equal (ptid, minus_one_ptid)
5261 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5262 p += xsnprintf (p, endp - p, "vCont;t");
5263 else
5264 {
5265 ptid_t nptid;
5266
74531fed
PA
5267 p += xsnprintf (p, endp - p, "vCont;t:");
5268
5269 if (ptid_is_pid (ptid))
5270 /* All (-1) threads of process. */
ba348170 5271 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
5272 else
5273 {
5274 /* Small optimization: if we already have a stop reply for
5275 this thread, no use in telling the stub we want this
5276 stopped. */
5277 if (peek_stop_reply (ptid))
5278 return;
5279
5280 nptid = ptid;
5281 }
5282
a9cbf802 5283 write_ptid (p, endp, nptid);
74531fed
PA
5284 }
5285
5286 /* In non-stop, we get an immediate OK reply. The stop reply will
5287 come in asynchronously by notification. */
5288 putpkt (rs->buf);
5289 getpkt (&rs->buf, &rs->buf_size, 0);
5290 if (strcmp (rs->buf, "OK") != 0)
5291 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5292}
5293
bfedc46a
PA
5294/* All-stop version of target_interrupt. Sends a break or a ^C to
5295 interrupt the remote target. It is undefined which thread of which
5296 process reports the interrupt. */
74531fed
PA
5297
5298static void
bfedc46a 5299remote_interrupt_as (ptid_t ptid)
74531fed
PA
5300{
5301 struct remote_state *rs = get_remote_state ();
5302
3a29589a
DJ
5303 rs->ctrlc_pending_p = 1;
5304
74531fed
PA
5305 /* If the inferior is stopped already, but the core didn't know
5306 about it yet, just ignore the request. The cached wait status
5307 will be collected in remote_wait. */
5308 if (rs->cached_wait_status)
5309 return;
5310
9a7071a8
JB
5311 /* Send interrupt_sequence to remote target. */
5312 send_interrupt_sequence ();
74531fed
PA
5313}
5314
bfedc46a 5315/* Implement the to_stop function for the remote targets. */
74531fed 5316
c906108c 5317static void
1eab8a48 5318remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5319{
7a292a7a 5320 if (remote_debug)
0f71a2f6 5321 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5322
74531fed
PA
5323 if (non_stop)
5324 remote_stop_ns (ptid);
c906108c 5325 else
bfedc46a
PA
5326 {
5327 /* We don't currently have a way to transparently pause the
5328 remote target in all-stop mode. Interrupt it instead. */
5329 remote_interrupt_as (ptid);
5330 }
5331}
5332
5333/* Implement the to_interrupt function for the remote targets. */
5334
5335static void
5336remote_interrupt (struct target_ops *self, ptid_t ptid)
5337{
5338 if (remote_debug)
5339 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5340
5341 if (non_stop)
5342 {
5343 /* We don't currently have a way to ^C the remote target in
5344 non-stop mode. Stop it (with no signal) instead. */
5345 remote_stop_ns (ptid);
5346 }
5347 else
5348 remote_interrupt_as (ptid);
c906108c
SS
5349}
5350
5351/* Ask the user what to do when an interrupt is received. */
5352
5353static void
fba45db2 5354interrupt_query (void)
c906108c
SS
5355{
5356 target_terminal_ours ();
5357
d9d41e78 5358 if (target_is_async_p ())
c906108c 5359 {
74531fed 5360 signal (SIGINT, handle_sigint);
039e3c22 5361 quit ();
c906108c 5362 }
74531fed
PA
5363 else
5364 {
9e2f0ad4
HZ
5365 if (query (_("Interrupted while waiting for the program.\n\
5366Give up (and stop debugging it)? ")))
74531fed 5367 {
78a095c3 5368 remote_unpush_target ();
039e3c22 5369 quit ();
74531fed
PA
5370 }
5371 }
c906108c
SS
5372
5373 target_terminal_inferior ();
5374}
5375
6426a772
JM
5376/* Enable/disable target terminal ownership. Most targets can use
5377 terminal groups to control terminal ownership. Remote targets are
5378 different in that explicit transfer of ownership to/from GDB/target
23860348 5379 is required. */
6426a772
JM
5380
5381static void
d2f640d4 5382remote_terminal_inferior (struct target_ops *self)
6426a772 5383{
c6ebd6cf 5384 if (!target_async_permitted)
75c99385
PA
5385 /* Nothing to do. */
5386 return;
5387
d9d2d8b6
PA
5388 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5389 idempotent. The event-loop GDB talking to an asynchronous target
5390 with a synchronous command calls this function from both
5391 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5392 transfer the terminal to the target when it shouldn't this guard
5393 can go away. */
6426a772
JM
5394 if (!remote_async_terminal_ours_p)
5395 return;
5396 delete_file_handler (input_fd);
5397 remote_async_terminal_ours_p = 0;
934b9bac 5398 async_initialize_sigint_signal_handler ();
6426a772
JM
5399 /* NOTE: At this point we could also register our selves as the
5400 recipient of all input. Any characters typed could then be
23860348 5401 passed on down to the target. */
6426a772
JM
5402}
5403
5404static void
e3594fd1 5405remote_terminal_ours (struct target_ops *self)
6426a772 5406{
c6ebd6cf 5407 if (!target_async_permitted)
75c99385
PA
5408 /* Nothing to do. */
5409 return;
5410
5411 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5412 if (remote_async_terminal_ours_p)
5413 return;
934b9bac 5414 async_cleanup_sigint_signal_handler (NULL);
6426a772
JM
5415 add_file_handler (input_fd, stdin_event_handler, 0);
5416 remote_async_terminal_ours_p = 1;
5417}
5418
176a6961 5419static void
917317f4 5420remote_console_output (char *msg)
c906108c
SS
5421{
5422 char *p;
5423
c5aa993b 5424 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5425 {
5426 char tb[2];
5427 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5428
c906108c
SS
5429 tb[0] = c;
5430 tb[1] = 0;
43ff13b4 5431 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5432 }
00db5b94
PA
5433 gdb_flush (gdb_stdtarg);
5434}
74531fed
PA
5435
5436typedef struct cached_reg
5437{
5438 int num;
5439 gdb_byte data[MAX_REGISTER_SIZE];
5440} cached_reg_t;
5441
5442DEF_VEC_O(cached_reg_t);
5443
722247f1 5444typedef struct stop_reply
74531fed 5445{
722247f1 5446 struct notif_event base;
74531fed 5447
722247f1 5448 /* The identifier of the thread about this event */
74531fed
PA
5449 ptid_t ptid;
5450
340e3c99 5451 /* The remote state this event is associated with. When the remote
bcc75809
YQ
5452 connection, represented by a remote_state object, is closed,
5453 all the associated stop_reply events should be released. */
5454 struct remote_state *rs;
5455
74531fed
PA
5456 struct target_waitstatus ws;
5457
15148d6a
PA
5458 /* Expedited registers. This makes remote debugging a bit more
5459 efficient for those targets that provide critical registers as
5460 part of their normal status mechanism (as another roundtrip to
5461 fetch them is avoided). */
74531fed
PA
5462 VEC(cached_reg_t) *regcache;
5463
f7e6eed5
PA
5464 enum target_stop_reason stop_reason;
5465
74531fed
PA
5466 CORE_ADDR watch_data_address;
5467
dc146f7c 5468 int core;
722247f1 5469} *stop_reply_p;
a744cf53 5470
722247f1
YQ
5471DECLARE_QUEUE_P (stop_reply_p);
5472DEFINE_QUEUE_P (stop_reply_p);
5473/* The list of already fetched and acknowledged stop events. This
5474 queue is used for notification Stop, and other notifications
5475 don't need queue for their events, because the notification events
5476 of Stop can't be consumed immediately, so that events should be
5477 queued first, and be consumed by remote_wait_{ns,as} one per
5478 time. Other notifications can consume their events immediately,
5479 so queue is not needed for them. */
5480static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
5481
5482static void
5483stop_reply_xfree (struct stop_reply *r)
5484{
f48ff2a7 5485 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
5486}
5487
722247f1
YQ
5488static void
5489remote_notif_stop_parse (struct notif_client *self, char *buf,
5490 struct notif_event *event)
5491{
5492 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5493}
5494
5495static void
5496remote_notif_stop_ack (struct notif_client *self, char *buf,
5497 struct notif_event *event)
5498{
5499 struct stop_reply *stop_reply = (struct stop_reply *) event;
5500
5501 /* acknowledge */
5502 putpkt ((char *) self->ack_command);
5503
5504 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5505 /* We got an unknown stop reply. */
5506 error (_("Unknown stop reply"));
5507
5508 push_stop_reply (stop_reply);
5509}
5510
5511static int
5512remote_notif_stop_can_get_pending_events (struct notif_client *self)
5513{
5514 /* We can't get pending events in remote_notif_process for
5515 notification stop, and we have to do this in remote_wait_ns
5516 instead. If we fetch all queued events from stub, remote stub
5517 may exit and we have no chance to process them back in
5518 remote_wait_ns. */
5519 mark_async_event_handler (remote_async_inferior_event_token);
5520 return 0;
5521}
5522
5523static void
5524stop_reply_dtr (struct notif_event *event)
5525{
5526 struct stop_reply *r = (struct stop_reply *) event;
5527
5528 VEC_free (cached_reg_t, r->regcache);
5529}
5530
5531static struct notif_event *
5532remote_notif_stop_alloc_reply (void)
5533{
5534 struct notif_event *r
70ba0933 5535 = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
5536
5537 r->dtr = stop_reply_dtr;
5538
5539 return r;
5540}
5541
5542/* A client of notification Stop. */
5543
5544struct notif_client notif_client_stop =
5545{
5546 "Stop",
5547 "vStopped",
5548 remote_notif_stop_parse,
5549 remote_notif_stop_ack,
5550 remote_notif_stop_can_get_pending_events,
5551 remote_notif_stop_alloc_reply,
f48ff2a7 5552 REMOTE_NOTIF_STOP,
722247f1
YQ
5553};
5554
5555/* A parameter to pass data in and out. */
5556
5557struct queue_iter_param
5558{
5559 void *input;
5560 struct stop_reply *output;
5561};
5562
cbb8991c
DB
5563/* Determine if THREAD is a pending fork parent thread. ARG contains
5564 the pid of the process that owns the threads we want to check, or
5565 -1 if we want to check all threads. */
5566
5567static int
5568is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
5569 ptid_t thread_ptid)
5570{
5571 if (ws->kind == TARGET_WAITKIND_FORKED
5572 || ws->kind == TARGET_WAITKIND_VFORKED)
5573 {
5574 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
5575 return 1;
5576 }
5577
5578 return 0;
5579}
5580
5581/* Check whether EVENT is a fork event, and if it is, remove the
5582 fork child from the context list passed in DATA. */
5583
5584static int
5585remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
5586 QUEUE_ITER (stop_reply_p) *iter,
5587 stop_reply_p event,
5588 void *data)
5589{
5590 struct queue_iter_param *param = data;
5591 struct threads_listing_context *context = param->input;
5592
5593 if (event->ws.kind == TARGET_WAITKIND_FORKED
5594 || event->ws.kind == TARGET_WAITKIND_VFORKED)
5595 {
5596 threads_listing_context_remove (&event->ws, context);
5597 }
5598
5599 return 1;
5600}
5601
5602/* If CONTEXT contains any fork child threads that have not been
5603 reported yet, remove them from the CONTEXT list. If such a
5604 thread exists it is because we are stopped at a fork catchpoint
5605 and have not yet called follow_fork, which will set up the
5606 host-side data structures for the new process. */
5607
5608static void
5609remove_new_fork_children (struct threads_listing_context *context)
5610{
5611 struct thread_info * thread;
5612 int pid = -1;
5613 struct notif_client *notif = &notif_client_stop;
5614 struct queue_iter_param param;
5615
5616 /* For any threads stopped at a fork event, remove the corresponding
5617 fork child threads from the CONTEXT list. */
5618 ALL_NON_EXITED_THREADS (thread)
5619 {
5620 struct target_waitstatus *ws = &thread->pending_follow;
5621
5622 if (is_pending_fork_parent (ws, pid, thread->ptid))
5623 {
5624 threads_listing_context_remove (ws, context);
5625 }
5626 }
5627
5628 /* Check for any pending fork events (not reported or processed yet)
5629 in process PID and remove those fork child threads from the
5630 CONTEXT list as well. */
5631 remote_notif_get_pending_events (notif);
5632 param.input = context;
5633 param.output = NULL;
5634 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5635 remove_child_of_pending_fork, &param);
5636}
5637
f48ff2a7
YQ
5638/* Remove stop replies in the queue if its pid is equal to the given
5639 inferior's pid. */
722247f1
YQ
5640
5641static int
f48ff2a7
YQ
5642remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5643 QUEUE_ITER (stop_reply_p) *iter,
5644 stop_reply_p event,
5645 void *data)
722247f1
YQ
5646{
5647 struct queue_iter_param *param = data;
5648 struct inferior *inf = param->input;
5649
f48ff2a7 5650 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
5651 {
5652 stop_reply_xfree (event);
5653 QUEUE_remove_elem (stop_reply_p, q, iter);
5654 }
5655
5656 return 1;
5657}
5658
f48ff2a7 5659/* Discard all pending stop replies of inferior INF. */
c906108c 5660
74531fed 5661static void
5f4cf0bb 5662discard_pending_stop_replies (struct inferior *inf)
c906108c 5663{
722247f1
YQ
5664 int i;
5665 struct queue_iter_param param;
f48ff2a7
YQ
5666 struct stop_reply *reply;
5667 struct remote_state *rs = get_remote_state ();
5668 struct remote_notif_state *rns = rs->notif_state;
5669
5670 /* This function can be notified when an inferior exists. When the
5671 target is not remote, the notification state is NULL. */
5672 if (rs->remote_desc == NULL)
5673 return;
5674
5675 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 5676
74531fed 5677 /* Discard the in-flight notification. */
f48ff2a7 5678 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 5679 {
722247f1 5680 stop_reply_xfree (reply);
f48ff2a7 5681 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 5682 }
c906108c 5683
722247f1
YQ
5684 param.input = inf;
5685 param.output = NULL;
74531fed
PA
5686 /* Discard the stop replies we have already pulled with
5687 vStopped. */
722247f1 5688 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
5689 remove_stop_reply_for_inferior, &param);
5690}
5691
bcc75809
YQ
5692/* If its remote state is equal to the given remote state,
5693 remove EVENT from the stop reply queue. */
5694
5695static int
5696remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5697 QUEUE_ITER (stop_reply_p) *iter,
5698 stop_reply_p event,
5699 void *data)
5700{
5701 struct queue_iter_param *param = data;
5702 struct remote_state *rs = param->input;
5703
5704 if (event->rs == rs)
5705 {
5706 stop_reply_xfree (event);
5707 QUEUE_remove_elem (stop_reply_p, q, iter);
5708 }
5709
5710 return 1;
5711}
5712
5713/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
5714
5715static void
bcc75809 5716discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
5717{
5718 struct queue_iter_param param;
5719
bcc75809 5720 param.input = rs;
f48ff2a7
YQ
5721 param.output = NULL;
5722 /* Discard the stop replies we have already pulled with
5723 vStopped. */
5724 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 5725 remove_stop_reply_of_remote_state, &param);
722247f1 5726}
74531fed 5727
722247f1
YQ
5728/* A parameter to pass data in and out. */
5729
5730static int
5731remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5732 QUEUE_ITER (stop_reply_p) *iter,
5733 stop_reply_p event,
5734 void *data)
5735{
5736 struct queue_iter_param *param = data;
5737 ptid_t *ptid = param->input;
5738
5739 if (ptid_match (event->ptid, *ptid))
5740 {
5741 param->output = event;
5742 QUEUE_remove_elem (stop_reply_p, q, iter);
5743 return 0;
c8e38a49 5744 }
722247f1
YQ
5745
5746 return 1;
74531fed 5747}
43ff13b4 5748
722247f1
YQ
5749/* Remove the first reply in 'stop_reply_queue' which matches
5750 PTID. */
2e9f7625 5751
722247f1
YQ
5752static struct stop_reply *
5753remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 5754{
722247f1
YQ
5755 struct queue_iter_param param;
5756
5757 param.input = &ptid;
5758 param.output = NULL;
5759
5760 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5761 remote_notif_remove_once_on_match, &param);
5762 if (notif_debug)
5763 fprintf_unfiltered (gdb_stdlog,
5764 "notif: discard queued event: 'Stop' in %s\n",
5765 target_pid_to_str (ptid));
a744cf53 5766
722247f1 5767 return param.output;
74531fed 5768}
75c99385 5769
74531fed
PA
5770/* Look for a queued stop reply belonging to PTID. If one is found,
5771 remove it from the queue, and return it. Returns NULL if none is
5772 found. If there are still queued events left to process, tell the
5773 event loop to get back to target_wait soon. */
e24a49d8 5774
74531fed
PA
5775static struct stop_reply *
5776queued_stop_reply (ptid_t ptid)
5777{
722247f1 5778 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 5779
722247f1 5780 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
5781 /* There's still at least an event left. */
5782 mark_async_event_handler (remote_async_inferior_event_token);
5783
722247f1 5784 return r;
74531fed
PA
5785}
5786
5787/* Push a fully parsed stop reply in the stop reply queue. Since we
5788 know that we now have at least one queued event left to pass to the
5789 core side, tell the event loop to get back to target_wait soon. */
5790
5791static void
5792push_stop_reply (struct stop_reply *new_event)
5793{
722247f1 5794 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 5795
722247f1
YQ
5796 if (notif_debug)
5797 fprintf_unfiltered (gdb_stdlog,
5798 "notif: push 'Stop' %s to queue %d\n",
5799 target_pid_to_str (new_event->ptid),
5800 QUEUE_length (stop_reply_p,
5801 stop_reply_queue));
74531fed
PA
5802
5803 mark_async_event_handler (remote_async_inferior_event_token);
5804}
5805
722247f1
YQ
5806static int
5807stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5808 QUEUE_ITER (stop_reply_p) *iter,
5809 struct stop_reply *event,
5810 void *data)
5811{
5812 ptid_t *ptid = data;
5813
5814 return !(ptid_equal (*ptid, event->ptid)
5815 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5816}
5817
74531fed
PA
5818/* Returns true if we have a stop reply for PTID. */
5819
5820static int
5821peek_stop_reply (ptid_t ptid)
5822{
722247f1
YQ
5823 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5824 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
5825}
5826
1f10ba14
PA
5827/* Skip PACKET until the next semi-colon (or end of string). */
5828
5829static char *
5830skip_to_semicolon (char *p)
5831{
5832 while (*p != '\0' && *p != ';')
5833 p++;
5834 return p;
5835}
5836
74531fed
PA
5837/* Parse the stop reply in BUF. Either the function succeeds, and the
5838 result is stored in EVENT, or throws an error. */
5839
5840static void
5841remote_parse_stop_reply (char *buf, struct stop_reply *event)
5842{
5843 struct remote_arch_state *rsa = get_remote_arch_state ();
5844 ULONGEST addr;
5845 char *p;
5846
5847 event->ptid = null_ptid;
bcc75809 5848 event->rs = get_remote_state ();
74531fed
PA
5849 event->ws.kind = TARGET_WAITKIND_IGNORE;
5850 event->ws.value.integer = 0;
f7e6eed5 5851 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 5852 event->regcache = NULL;
dc146f7c 5853 event->core = -1;
74531fed
PA
5854
5855 switch (buf[0])
5856 {
5857 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
5858 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5859 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5860 ss = signal number
5861 n... = register number
5862 r... = register contents
5863 */
5864
5865 p = &buf[3]; /* after Txx */
5866 while (*p)
5867 {
5868 char *p1;
cea39f65 5869 int fieldsize;
43ff13b4 5870
1f10ba14
PA
5871 p1 = strchr (p, ':');
5872 if (p1 == NULL)
5873 error (_("Malformed packet(a) (missing colon): %s\n\
5874Packet: '%s'\n"),
5875 p, buf);
5876 if (p == p1)
5877 error (_("Malformed packet(a) (missing register number): %s\n\
5878Packet: '%s'\n"),
5879 p, buf);
3c3bea1c 5880
1f10ba14
PA
5881 /* Some "registers" are actually extended stop information.
5882 Note if you're adding a new entry here: GDB 7.9 and
5883 earlier assume that all register "numbers" that start
5884 with an hex digit are real register numbers. Make sure
5885 the server only sends such a packet if it knows the
5886 client understands it. */
c8e38a49 5887
1f10ba14
PA
5888 if (strncmp (p, "thread", p1 - p) == 0)
5889 event->ptid = read_ptid (++p1, &p);
5890 else if ((strncmp (p, "watch", p1 - p) == 0)
5891 || (strncmp (p, "rwatch", p1 - p) == 0)
5892 || (strncmp (p, "awatch", p1 - p) == 0))
cea39f65 5893 {
f7e6eed5 5894 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
5895 p = unpack_varlen_hex (++p1, &addr);
5896 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 5897 }
f7e6eed5
PA
5898 else if (strncmp (p, "swbreak", p1 - p) == 0)
5899 {
5900 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
5901
5902 /* Make sure the stub doesn't forget to indicate support
5903 with qSupported. */
5904 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
5905 error (_("Unexpected swbreak stop reason"));
5906
5907 /* The value part is documented as "must be empty",
5908 though we ignore it, in case we ever decide to make
5909 use of it in a backward compatible way. */
5910 p = skip_to_semicolon (p1 + 1);
5911 }
5912 else if (strncmp (p, "hwbreak", p1 - p) == 0)
5913 {
5914 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
5915
5916 /* Make sure the stub doesn't forget to indicate support
5917 with qSupported. */
5918 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
5919 error (_("Unexpected hwbreak stop reason"));
5920
5921 /* See above. */
5922 p = skip_to_semicolon (p1 + 1);
5923 }
1f10ba14 5924 else if (strncmp (p, "library", p1 - p) == 0)
cea39f65 5925 {
1f10ba14
PA
5926 event->ws.kind = TARGET_WAITKIND_LOADED;
5927 p = skip_to_semicolon (p1 + 1);
5928 }
5929 else if (strncmp (p, "replaylog", p1 - p) == 0)
5930 {
5931 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5932 /* p1 will indicate "begin" or "end", but it makes
5933 no difference for now, so ignore it. */
5934 p = skip_to_semicolon (p1 + 1);
5935 }
5936 else if (strncmp (p, "core", p1 - p) == 0)
5937 {
5938 ULONGEST c;
a744cf53 5939
1f10ba14
PA
5940 p = unpack_varlen_hex (++p1, &c);
5941 event->core = c;
cea39f65 5942 }
de0d863e
DB
5943 else if (strncmp (p, "fork", p1 - p) == 0)
5944 {
5945 event->ws.value.related_pid = read_ptid (++p1, &p);
5946 event->ws.kind = TARGET_WAITKIND_FORKED;
5947 }
c269dbdb
DB
5948 else if (strncmp (p, "vfork", p1 - p) == 0)
5949 {
5950 event->ws.value.related_pid = read_ptid (++p1, &p);
5951 event->ws.kind = TARGET_WAITKIND_VFORKED;
5952 }
5953 else if (strncmp (p, "vforkdone", p1 - p) == 0)
5954 {
5955 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
5956 p = skip_to_semicolon (p1 + 1);
5957 }
cea39f65
MS
5958 else
5959 {
1f10ba14
PA
5960 ULONGEST pnum;
5961 char *p_temp;
5962
5963 /* Maybe a real ``P'' register number. */
5964 p_temp = unpack_varlen_hex (p, &pnum);
5965 /* If the first invalid character is the colon, we got a
5966 register number. Otherwise, it's an unknown stop
5967 reason. */
5968 if (p_temp == p1)
5969 {
5970 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5971 cached_reg_t cached_reg;
43ff13b4 5972
1f10ba14
PA
5973 if (reg == NULL)
5974 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 5975Packet: '%s'\n"),
1f10ba14 5976 hex_string (pnum), p, buf);
c8e38a49 5977
1f10ba14 5978 cached_reg.num = reg->regnum;
4100683b 5979
1f10ba14
PA
5980 p = p1 + 1;
5981 fieldsize = hex2bin (p, cached_reg.data,
5982 register_size (target_gdbarch (),
5983 reg->regnum));
5984 p += 2 * fieldsize;
5985 if (fieldsize < register_size (target_gdbarch (),
5986 reg->regnum))
5987 warning (_("Remote reply is too short: %s"), buf);
74531fed 5988
1f10ba14
PA
5989 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5990 }
5991 else
5992 {
5993 /* Not a number. Silently skip unknown optional
5994 info. */
5995 p = skip_to_semicolon (p1 + 1);
5996 }
cea39f65 5997 }
c8e38a49 5998
cea39f65
MS
5999 if (*p != ';')
6000 error (_("Remote register badly formatted: %s\nhere: %s"),
6001 buf, p);
6002 ++p;
6003 }
5b5596ff
PA
6004
6005 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6006 break;
6007
c8e38a49
PA
6008 /* fall through */
6009 case 'S': /* Old style status, just signal only. */
3a09da41
PA
6010 {
6011 int sig;
6012
6013 event->ws.kind = TARGET_WAITKIND_STOPPED;
6014 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6015 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6016 event->ws.value.sig = (enum gdb_signal) sig;
6017 else
6018 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6019 }
c8e38a49
PA
6020 break;
6021 case 'W': /* Target exited. */
6022 case 'X':
6023 {
6024 char *p;
6025 int pid;
6026 ULONGEST value;
82f73884 6027
c8e38a49
PA
6028 /* GDB used to accept only 2 hex chars here. Stubs should
6029 only send more if they detect GDB supports multi-process
6030 support. */
6031 p = unpack_varlen_hex (&buf[1], &value);
82f73884 6032
c8e38a49
PA
6033 if (buf[0] == 'W')
6034 {
6035 /* The remote process exited. */
74531fed
PA
6036 event->ws.kind = TARGET_WAITKIND_EXITED;
6037 event->ws.value.integer = value;
c8e38a49
PA
6038 }
6039 else
6040 {
6041 /* The remote process exited with a signal. */
74531fed 6042 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
6043 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6044 event->ws.value.sig = (enum gdb_signal) value;
6045 else
6046 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 6047 }
82f73884 6048
c8e38a49
PA
6049 /* If no process is specified, assume inferior_ptid. */
6050 pid = ptid_get_pid (inferior_ptid);
6051 if (*p == '\0')
6052 ;
6053 else if (*p == ';')
6054 {
6055 p++;
6056
0b24eb2d 6057 if (*p == '\0')
82f73884 6058 ;
61012eef 6059 else if (startswith (p, "process:"))
82f73884 6060 {
c8e38a49 6061 ULONGEST upid;
a744cf53 6062
c8e38a49
PA
6063 p += sizeof ("process:") - 1;
6064 unpack_varlen_hex (p, &upid);
6065 pid = upid;
82f73884
PA
6066 }
6067 else
6068 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 6069 }
c8e38a49
PA
6070 else
6071 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
6072 event->ptid = pid_to_ptid (pid);
6073 }
6074 break;
6075 }
6076
6077 if (non_stop && ptid_equal (event->ptid, null_ptid))
6078 error (_("No process or thread specified in stop reply: %s"), buf);
6079}
6080
722247f1
YQ
6081/* When the stub wants to tell GDB about a new notification reply, it
6082 sends a notification (%Stop, for example). Those can come it at
6083 any time, hence, we have to make sure that any pending
6084 putpkt/getpkt sequence we're making is finished, before querying
6085 the stub for more events with the corresponding ack command
6086 (vStopped, for example). E.g., if we started a vStopped sequence
6087 immediately upon receiving the notification, something like this
6088 could happen:
74531fed
PA
6089
6090 1.1) --> Hg 1
6091 1.2) <-- OK
6092 1.3) --> g
6093 1.4) <-- %Stop
6094 1.5) --> vStopped
6095 1.6) <-- (registers reply to step #1.3)
6096
6097 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6098 query.
6099
796cb314 6100 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
6101 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6102 doing whatever we were doing:
6103
6104 2.1) --> Hg 1
6105 2.2) <-- OK
6106 2.3) --> g
6107 2.4) <-- %Stop
6108 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6109 2.5) <-- (registers reply to step #2.3)
6110
6111 Eventualy after step #2.5, we return to the event loop, which
6112 notices there's an event on the
6113 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6114 associated callback --- the function below. At this point, we're
6115 always safe to start a vStopped sequence. :
6116
6117 2.6) --> vStopped
6118 2.7) <-- T05 thread:2
6119 2.8) --> vStopped
6120 2.9) --> OK
6121*/
6122
722247f1
YQ
6123void
6124remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
6125{
6126 struct remote_state *rs = get_remote_state ();
74531fed 6127
f48ff2a7 6128 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 6129 {
722247f1
YQ
6130 if (notif_debug)
6131 fprintf_unfiltered (gdb_stdlog,
6132 "notif: process: '%s' ack pending event\n",
6133 nc->name);
74531fed 6134
722247f1 6135 /* acknowledge */
f48ff2a7
YQ
6136 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6137 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
6138
6139 while (1)
6140 {
6141 getpkt (&rs->buf, &rs->buf_size, 0);
6142 if (strcmp (rs->buf, "OK") == 0)
6143 break;
6144 else
722247f1 6145 remote_notif_ack (nc, rs->buf);
74531fed
PA
6146 }
6147 }
722247f1
YQ
6148 else
6149 {
6150 if (notif_debug)
6151 fprintf_unfiltered (gdb_stdlog,
6152 "notif: process: '%s' no pending reply\n",
6153 nc->name);
6154 }
74531fed
PA
6155}
6156
74531fed
PA
6157/* Called when it is decided that STOP_REPLY holds the info of the
6158 event that is to be returned to the core. This function always
6159 destroys STOP_REPLY. */
6160
6161static ptid_t
6162process_stop_reply (struct stop_reply *stop_reply,
6163 struct target_waitstatus *status)
6164{
6165 ptid_t ptid;
6166
6167 *status = stop_reply->ws;
6168 ptid = stop_reply->ptid;
6169
6170 /* If no thread/process was reported by the stub, assume the current
6171 inferior. */
6172 if (ptid_equal (ptid, null_ptid))
6173 ptid = inferior_ptid;
6174
5f3563ea
PA
6175 if (status->kind != TARGET_WAITKIND_EXITED
6176 && status->kind != TARGET_WAITKIND_SIGNALLED)
74531fed 6177 {
ee154bee
TT
6178 struct remote_state *rs = get_remote_state ();
6179
5f3563ea
PA
6180 /* Expedited registers. */
6181 if (stop_reply->regcache)
6182 {
217f1f79 6183 struct regcache *regcache
f5656ead 6184 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
6185 cached_reg_t *reg;
6186 int ix;
6187
6188 for (ix = 0;
6189 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6190 ix++)
217f1f79 6191 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
6192 VEC_free (cached_reg_t, stop_reply->regcache);
6193 }
74531fed 6194
f7e6eed5 6195 rs->stop_reason = stop_reply->stop_reason;
ee154bee 6196 rs->remote_watch_data_address = stop_reply->watch_data_address;
1941c569
PA
6197
6198 remote_notice_new_inferior (ptid, 0);
dc146f7c 6199 demand_private_info (ptid)->core = stop_reply->core;
74531fed
PA
6200 }
6201
74531fed
PA
6202 stop_reply_xfree (stop_reply);
6203 return ptid;
6204}
6205
6206/* The non-stop mode version of target_wait. */
6207
6208static ptid_t
47608cb1 6209remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6210{
6211 struct remote_state *rs = get_remote_state ();
74531fed
PA
6212 struct stop_reply *stop_reply;
6213 int ret;
fee9eda9 6214 int is_notif = 0;
74531fed
PA
6215
6216 /* If in non-stop mode, get out of getpkt even if a
6217 notification is received. */
6218
6219 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6220 0 /* forever */, &is_notif);
74531fed
PA
6221 while (1)
6222 {
fee9eda9 6223 if (ret != -1 && !is_notif)
74531fed
PA
6224 switch (rs->buf[0])
6225 {
6226 case 'E': /* Error of some sort. */
6227 /* We're out of sync with the target now. Did it continue
6228 or not? We can't tell which thread it was in non-stop,
6229 so just ignore this. */
6230 warning (_("Remote failure reply: %s"), rs->buf);
6231 break;
6232 case 'O': /* Console output. */
6233 remote_console_output (rs->buf + 1);
6234 break;
6235 default:
6236 warning (_("Invalid remote reply: %s"), rs->buf);
6237 break;
6238 }
6239
6240 /* Acknowledge a pending stop reply that may have arrived in the
6241 mean time. */
f48ff2a7 6242 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 6243 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
6244
6245 /* If indeed we noticed a stop reply, we're done. */
6246 stop_reply = queued_stop_reply (ptid);
6247 if (stop_reply != NULL)
6248 return process_stop_reply (stop_reply, status);
6249
47608cb1 6250 /* Still no event. If we're just polling for an event, then
74531fed 6251 return to the event loop. */
47608cb1 6252 if (options & TARGET_WNOHANG)
74531fed
PA
6253 {
6254 status->kind = TARGET_WAITKIND_IGNORE;
6255 return minus_one_ptid;
6256 }
6257
47608cb1 6258 /* Otherwise do a blocking wait. */
74531fed 6259 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6260 1 /* forever */, &is_notif);
74531fed
PA
6261 }
6262}
6263
6264/* Wait until the remote machine stops, then return, storing status in
6265 STATUS just as `wait' would. */
6266
6267static ptid_t
47608cb1 6268remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6269{
6270 struct remote_state *rs = get_remote_state ();
74531fed 6271 ptid_t event_ptid = null_ptid;
cea39f65 6272 char *buf;
74531fed
PA
6273 struct stop_reply *stop_reply;
6274
47608cb1
PA
6275 again:
6276
74531fed
PA
6277 status->kind = TARGET_WAITKIND_IGNORE;
6278 status->value.integer = 0;
6279
6280 stop_reply = queued_stop_reply (ptid);
6281 if (stop_reply != NULL)
6282 return process_stop_reply (stop_reply, status);
6283
6284 if (rs->cached_wait_status)
6285 /* Use the cached wait status, but only once. */
6286 rs->cached_wait_status = 0;
6287 else
6288 {
6289 int ret;
722247f1 6290 int is_notif;
567420d1
PA
6291 int forever = ((options & TARGET_WNOHANG) == 0
6292 && wait_forever_enabled_p);
6293
6294 if (!rs->waiting_for_stop_reply)
6295 {
6296 status->kind = TARGET_WAITKIND_NO_RESUMED;
6297 return minus_one_ptid;
6298 }
74531fed
PA
6299
6300 if (!target_is_async_p ())
6301 {
934b9bac 6302 ofunc = signal (SIGINT, sync_remote_interrupt);
74531fed
PA
6303 /* If the user hit C-c before this packet, or between packets,
6304 pretend that it was hit right here. */
522002f9 6305 if (check_quit_flag ())
74531fed 6306 {
522002f9 6307 clear_quit_flag ();
934b9bac 6308 sync_remote_interrupt (SIGINT);
74531fed
PA
6309 }
6310 }
6311
6312 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6313 _never_ wait for ever -> test on target_is_async_p().
6314 However, before we do that we need to ensure that the caller
6315 knows how to take the target into/out of async mode. */
722247f1 6316 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 6317 forever, &is_notif);
722247f1 6318
5e1b953b
SDJ
6319 if (!target_is_async_p ())
6320 signal (SIGINT, ofunc);
6321
722247f1
YQ
6322 /* GDB gets a notification. Return to core as this event is
6323 not interesting. */
6324 if (ret != -1 && is_notif)
6325 return minus_one_ptid;
567420d1
PA
6326
6327 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6328 return minus_one_ptid;
74531fed
PA
6329 }
6330
6331 buf = rs->buf;
6332
f7e6eed5 6333 rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed
PA
6334
6335 /* We got something. */
6336 rs->waiting_for_stop_reply = 0;
6337
3a29589a
DJ
6338 /* Assume that the target has acknowledged Ctrl-C unless we receive
6339 an 'F' or 'O' packet. */
6340 if (buf[0] != 'F' && buf[0] != 'O')
6341 rs->ctrlc_pending_p = 0;
6342
74531fed
PA
6343 switch (buf[0])
6344 {
6345 case 'E': /* Error of some sort. */
6346 /* We're out of sync with the target now. Did it continue or
6347 not? Not is more likely, so report a stop. */
6348 warning (_("Remote failure reply: %s"), buf);
6349 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 6350 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
6351 break;
6352 case 'F': /* File-I/O request. */
3a29589a
DJ
6353 remote_fileio_request (buf, rs->ctrlc_pending_p);
6354 rs->ctrlc_pending_p = 0;
74531fed
PA
6355 break;
6356 case 'T': case 'S': case 'X': case 'W':
6357 {
722247f1
YQ
6358 struct stop_reply *stop_reply
6359 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6360 rs->buf);
74531fed 6361
74531fed 6362 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
6363 break;
6364 }
6365 case 'O': /* Console output. */
6366 remote_console_output (buf + 1);
e24a49d8 6367
c8e38a49
PA
6368 /* The target didn't really stop; keep waiting. */
6369 rs->waiting_for_stop_reply = 1;
e24a49d8 6370
c8e38a49
PA
6371 break;
6372 case '\0':
b73be471 6373 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
6374 {
6375 /* Zero length reply means that we tried 'S' or 'C' and the
6376 remote system doesn't support it. */
6377 target_terminal_ours_for_output ();
6378 printf_filtered
6379 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
6380 gdb_signal_to_name (rs->last_sent_signal));
6381 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
6382 target_terminal_inferior ();
6383
280ceea3 6384 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49
PA
6385 putpkt ((char *) buf);
6386
6387 /* We just told the target to resume, so a stop reply is in
6388 order. */
e24a49d8 6389 rs->waiting_for_stop_reply = 1;
c8e38a49 6390 break;
43ff13b4 6391 }
c8e38a49
PA
6392 /* else fallthrough */
6393 default:
6394 warning (_("Invalid remote reply: %s"), buf);
6395 /* Keep waiting. */
6396 rs->waiting_for_stop_reply = 1;
6397 break;
43ff13b4 6398 }
c8e38a49 6399
c8e38a49 6400 if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
6401 {
6402 /* Nothing interesting happened. If we're doing a non-blocking
6403 poll, we're done. Otherwise, go back to waiting. */
6404 if (options & TARGET_WNOHANG)
6405 return minus_one_ptid;
6406 else
6407 goto again;
6408 }
74531fed
PA
6409 else if (status->kind != TARGET_WAITKIND_EXITED
6410 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
6411 {
6412 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 6413 record_currthread (rs, event_ptid);
82f73884
PA
6414 else
6415 event_ptid = inferior_ptid;
43ff13b4 6416 }
74531fed
PA
6417 else
6418 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 6419 record_currthread (rs, minus_one_ptid);
79d7f229 6420
82f73884 6421 return event_ptid;
43ff13b4
JM
6422}
6423
74531fed
PA
6424/* Wait until the remote machine stops, then return, storing status in
6425 STATUS just as `wait' would. */
6426
c8e38a49 6427static ptid_t
117de6a9 6428remote_wait (struct target_ops *ops,
47608cb1 6429 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
6430{
6431 ptid_t event_ptid;
6432
74531fed 6433 if (non_stop)
47608cb1 6434 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 6435 else
47608cb1 6436 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 6437
d9d41e78 6438 if (target_is_async_p ())
c8e38a49 6439 {
74531fed
PA
6440 /* If there are are events left in the queue tell the event loop
6441 to return here. */
722247f1 6442 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 6443 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 6444 }
c8e38a49
PA
6445
6446 return event_ptid;
6447}
6448
74ca34ce 6449/* Fetch a single register using a 'p' packet. */
c906108c 6450
b96ec7ac 6451static int
56be3814 6452fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
6453{
6454 struct remote_state *rs = get_remote_state ();
2e9f7625 6455 char *buf, *p;
b96ec7ac
AC
6456 char regp[MAX_REGISTER_SIZE];
6457 int i;
6458
4082afcc 6459 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
6460 return 0;
6461
6462 if (reg->pnum == -1)
6463 return 0;
6464
2e9f7625 6465 p = rs->buf;
fcad0fa4 6466 *p++ = 'p';
74ca34ce 6467 p += hexnumstr (p, reg->pnum);
fcad0fa4 6468 *p++ = '\0';
1f4437a4
MS
6469 putpkt (rs->buf);
6470 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 6471
2e9f7625
DJ
6472 buf = rs->buf;
6473
74ca34ce
DJ
6474 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6475 {
6476 case PACKET_OK:
6477 break;
6478 case PACKET_UNKNOWN:
6479 return 0;
6480 case PACKET_ERROR:
27a9c0bf
MS
6481 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6482 gdbarch_register_name (get_regcache_arch (regcache),
6483 reg->regnum),
6484 buf);
74ca34ce 6485 }
3f9a994c
JB
6486
6487 /* If this register is unfetchable, tell the regcache. */
6488 if (buf[0] == 'x')
8480adf2 6489 {
56be3814 6490 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 6491 return 1;
b96ec7ac 6492 }
b96ec7ac 6493
3f9a994c
JB
6494 /* Otherwise, parse and supply the value. */
6495 p = buf;
6496 i = 0;
6497 while (p[0] != 0)
6498 {
6499 if (p[1] == 0)
74ca34ce 6500 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
6501
6502 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6503 p += 2;
6504 }
56be3814 6505 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 6506 return 1;
b96ec7ac
AC
6507}
6508
74ca34ce
DJ
6509/* Fetch the registers included in the target's 'g' packet. */
6510
29709017
DJ
6511static int
6512send_g_packet (void)
c906108c 6513{
d01949b6 6514 struct remote_state *rs = get_remote_state ();
cea39f65 6515 int buf_len;
c906108c 6516
bba74b36 6517 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 6518 remote_send (&rs->buf, &rs->buf_size);
c906108c 6519
29709017
DJ
6520 /* We can get out of synch in various cases. If the first character
6521 in the buffer is not a hex character, assume that has happened
6522 and try to fetch another packet to read. */
6523 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6524 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6525 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6526 && rs->buf[0] != 'x') /* New: unavailable register value. */
6527 {
6528 if (remote_debug)
6529 fprintf_unfiltered (gdb_stdlog,
6530 "Bad register packet; fetching a new packet\n");
6531 getpkt (&rs->buf, &rs->buf_size, 0);
6532 }
6533
74ca34ce
DJ
6534 buf_len = strlen (rs->buf);
6535
6536 /* Sanity check the received packet. */
6537 if (buf_len % 2 != 0)
6538 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
6539
6540 return buf_len / 2;
6541}
6542
6543static void
56be3814 6544process_g_packet (struct regcache *regcache)
29709017 6545{
4a22f64d 6546 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
6547 struct remote_state *rs = get_remote_state ();
6548 struct remote_arch_state *rsa = get_remote_arch_state ();
6549 int i, buf_len;
6550 char *p;
6551 char *regs;
6552
6553 buf_len = strlen (rs->buf);
6554
6555 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
6556 if (buf_len > 2 * rsa->sizeof_g_packet)
6557 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6558
6559 /* Save the size of the packet sent to us by the target. It is used
6560 as a heuristic when determining the max size of packets that the
6561 target can safely receive. */
6562 if (rsa->actual_register_packet_size == 0)
6563 rsa->actual_register_packet_size = buf_len;
6564
6565 /* If this is smaller than we guessed the 'g' packet would be,
6566 update our records. A 'g' reply that doesn't include a register's
6567 value implies either that the register is not available, or that
6568 the 'p' packet must be used. */
6569 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 6570 {
74ca34ce
DJ
6571 rsa->sizeof_g_packet = buf_len / 2;
6572
4a22f64d 6573 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 6574 {
74ca34ce
DJ
6575 if (rsa->regs[i].pnum == -1)
6576 continue;
6577
6578 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6579 rsa->regs[i].in_g_packet = 0;
b96ec7ac 6580 else
74ca34ce 6581 rsa->regs[i].in_g_packet = 1;
b96ec7ac 6582 }
74ca34ce 6583 }
b323314b 6584
74ca34ce 6585 regs = alloca (rsa->sizeof_g_packet);
c906108c
SS
6586
6587 /* Unimplemented registers read as all bits zero. */
ea9c271d 6588 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 6589
c906108c
SS
6590 /* Reply describes registers byte by byte, each byte encoded as two
6591 hex characters. Suck them all up, then supply them to the
6592 register cacheing/storage mechanism. */
6593
74ca34ce 6594 p = rs->buf;
ea9c271d 6595 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 6596 {
74ca34ce
DJ
6597 if (p[0] == 0 || p[1] == 0)
6598 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6599 internal_error (__FILE__, __LINE__,
9b20d036 6600 _("unexpected end of 'g' packet reply"));
74ca34ce 6601
c906108c 6602 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 6603 regs[i] = 0; /* 'x' */
c906108c
SS
6604 else
6605 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6606 p += 2;
6607 }
6608
a744cf53
MS
6609 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6610 {
6611 struct packet_reg *r = &rsa->regs[i];
6612
6613 if (r->in_g_packet)
6614 {
6615 if (r->offset * 2 >= strlen (rs->buf))
6616 /* This shouldn't happen - we adjusted in_g_packet above. */
6617 internal_error (__FILE__, __LINE__,
9b20d036 6618 _("unexpected end of 'g' packet reply"));
a744cf53
MS
6619 else if (rs->buf[r->offset * 2] == 'x')
6620 {
6621 gdb_assert (r->offset * 2 < strlen (rs->buf));
6622 /* The register isn't available, mark it as such (at
6623 the same time setting the value to zero). */
6624 regcache_raw_supply (regcache, r->regnum, NULL);
6625 }
6626 else
6627 regcache_raw_supply (regcache, r->regnum,
6628 regs + r->offset);
6629 }
6630 }
c906108c
SS
6631}
6632
29709017 6633static void
56be3814 6634fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
6635{
6636 send_g_packet ();
56be3814 6637 process_g_packet (regcache);
29709017
DJ
6638}
6639
e6e4e701
PA
6640/* Make the remote selected traceframe match GDB's selected
6641 traceframe. */
6642
6643static void
6644set_remote_traceframe (void)
6645{
6646 int newnum;
262e1174 6647 struct remote_state *rs = get_remote_state ();
e6e4e701 6648
262e1174 6649 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
6650 return;
6651
6652 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 6653 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
6654
6655 newnum = target_trace_find (tfind_number,
6656 get_traceframe_number (), 0, 0, NULL);
6657
6658 /* Should not happen. If it does, all bets are off. */
6659 if (newnum != get_traceframe_number ())
6660 warning (_("could not set remote traceframe"));
6661}
6662
74ca34ce 6663static void
28439f5e
PA
6664remote_fetch_registers (struct target_ops *ops,
6665 struct regcache *regcache, int regnum)
74ca34ce 6666{
74ca34ce
DJ
6667 struct remote_arch_state *rsa = get_remote_arch_state ();
6668 int i;
6669
e6e4e701 6670 set_remote_traceframe ();
79d7f229 6671 set_general_thread (inferior_ptid);
74ca34ce
DJ
6672
6673 if (regnum >= 0)
6674 {
6675 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6676
74ca34ce
DJ
6677 gdb_assert (reg != NULL);
6678
6679 /* If this register might be in the 'g' packet, try that first -
6680 we are likely to read more than one register. If this is the
6681 first 'g' packet, we might be overly optimistic about its
6682 contents, so fall back to 'p'. */
6683 if (reg->in_g_packet)
6684 {
56be3814 6685 fetch_registers_using_g (regcache);
74ca34ce
DJ
6686 if (reg->in_g_packet)
6687 return;
6688 }
6689
56be3814 6690 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
6691 return;
6692
6693 /* This register is not available. */
56be3814 6694 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
6695
6696 return;
6697 }
6698
56be3814 6699 fetch_registers_using_g (regcache);
74ca34ce 6700
4a22f64d 6701 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6702 if (!rsa->regs[i].in_g_packet)
56be3814 6703 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
6704 {
6705 /* This register is not available. */
56be3814 6706 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
6707 }
6708}
6709
c906108c
SS
6710/* Prepare to store registers. Since we may send them all (using a
6711 'G' request), we have to read out the ones we don't want to change
6712 first. */
6713
c5aa993b 6714static void
f32dbf8c 6715remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 6716{
ea9c271d 6717 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 6718 int i;
cfd77fa1 6719 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 6720
c906108c 6721 /* Make sure the entire registers array is valid. */
4082afcc 6722 switch (packet_support (PACKET_P))
5a2468f5
JM
6723 {
6724 case PACKET_DISABLE:
6725 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 6726 /* Make sure all the necessary registers are cached. */
4a22f64d 6727 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 6728 if (rsa->regs[i].in_g_packet)
316f2060 6729 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
6730 break;
6731 case PACKET_ENABLE:
6732 break;
6733 }
6734}
6735
ad10f812 6736/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 6737 packet was not recognized. */
5a2468f5
JM
6738
6739static int
1f4437a4
MS
6740store_register_using_P (const struct regcache *regcache,
6741 struct packet_reg *reg)
5a2468f5 6742{
4a22f64d 6743 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 6744 struct remote_state *rs = get_remote_state ();
5a2468f5 6745 /* Try storing a single register. */
6d820c5c 6746 char *buf = rs->buf;
cfd77fa1 6747 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 6748 char *p;
5a2468f5 6749
4082afcc 6750 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
6751 return 0;
6752
6753 if (reg->pnum == -1)
6754 return 0;
6755
ea9c271d 6756 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 6757 p = buf + strlen (buf);
56be3814 6758 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 6759 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
6760 putpkt (rs->buf);
6761 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 6762
74ca34ce
DJ
6763 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6764 {
6765 case PACKET_OK:
6766 return 1;
6767 case PACKET_ERROR:
27a9c0bf
MS
6768 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6769 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
6770 case PACKET_UNKNOWN:
6771 return 0;
6772 default:
6773 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6774 }
c906108c
SS
6775}
6776
23860348
MS
6777/* Store register REGNUM, or all registers if REGNUM == -1, from the
6778 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
6779
6780static void
56be3814 6781store_registers_using_G (const struct regcache *regcache)
c906108c 6782{
d01949b6 6783 struct remote_state *rs = get_remote_state ();
ea9c271d 6784 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 6785 gdb_byte *regs;
c906108c
SS
6786 char *p;
6787
193cb69f
AC
6788 /* Extract all the registers in the regcache copying them into a
6789 local buffer. */
6790 {
b323314b 6791 int i;
a744cf53 6792
ea9c271d
DJ
6793 regs = alloca (rsa->sizeof_g_packet);
6794 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 6795 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 6796 {
ea9c271d 6797 struct packet_reg *r = &rsa->regs[i];
a744cf53 6798
b323314b 6799 if (r->in_g_packet)
56be3814 6800 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
6801 }
6802 }
c906108c
SS
6803
6804 /* Command describes registers byte by byte,
6805 each byte encoded as two hex characters. */
6d820c5c 6806 p = rs->buf;
193cb69f 6807 *p++ = 'G';
74ca34ce
DJ
6808 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6809 updated. */
6810 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
6811 putpkt (rs->buf);
6812 getpkt (&rs->buf, &rs->buf_size, 0);
6813 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
6814 error (_("Could not write registers; remote failure reply '%s'"),
6815 rs->buf);
c906108c 6816}
74ca34ce
DJ
6817
6818/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6819 of the register cache buffer. FIXME: ignores errors. */
6820
6821static void
28439f5e
PA
6822remote_store_registers (struct target_ops *ops,
6823 struct regcache *regcache, int regnum)
74ca34ce 6824{
74ca34ce
DJ
6825 struct remote_arch_state *rsa = get_remote_arch_state ();
6826 int i;
6827
e6e4e701 6828 set_remote_traceframe ();
79d7f229 6829 set_general_thread (inferior_ptid);
74ca34ce
DJ
6830
6831 if (regnum >= 0)
6832 {
6833 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6834
74ca34ce
DJ
6835 gdb_assert (reg != NULL);
6836
6837 /* Always prefer to store registers using the 'P' packet if
6838 possible; we often change only a small number of registers.
6839 Sometimes we change a larger number; we'd need help from a
6840 higher layer to know to use 'G'. */
56be3814 6841 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
6842 return;
6843
6844 /* For now, don't complain if we have no way to write the
6845 register. GDB loses track of unavailable registers too
6846 easily. Some day, this may be an error. We don't have
0df8b418 6847 any way to read the register, either... */
74ca34ce
DJ
6848 if (!reg->in_g_packet)
6849 return;
6850
56be3814 6851 store_registers_using_G (regcache);
74ca34ce
DJ
6852 return;
6853 }
6854
56be3814 6855 store_registers_using_G (regcache);
74ca34ce 6856
4a22f64d 6857 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6858 if (!rsa->regs[i].in_g_packet)
56be3814 6859 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
6860 /* See above for why we do not issue an error here. */
6861 continue;
6862}
c906108c
SS
6863\f
6864
6865/* Return the number of hex digits in num. */
6866
6867static int
fba45db2 6868hexnumlen (ULONGEST num)
c906108c
SS
6869{
6870 int i;
6871
6872 for (i = 0; num != 0; i++)
6873 num >>= 4;
6874
6875 return max (i, 1);
6876}
6877
2df3850c 6878/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
6879
6880static int
fba45db2 6881hexnumstr (char *buf, ULONGEST num)
c906108c 6882{
c906108c 6883 int len = hexnumlen (num);
a744cf53 6884
2df3850c
JM
6885 return hexnumnstr (buf, num, len);
6886}
6887
c906108c 6888
2df3850c 6889/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 6890
2df3850c 6891static int
fba45db2 6892hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
6893{
6894 int i;
6895
6896 buf[width] = '\0';
6897
6898 for (i = width - 1; i >= 0; i--)
c906108c 6899 {
c5aa993b 6900 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
6901 num >>= 4;
6902 }
6903
2df3850c 6904 return width;
c906108c
SS
6905}
6906
23860348 6907/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
6908
6909static CORE_ADDR
fba45db2 6910remote_address_masked (CORE_ADDR addr)
c906108c 6911{
883b9c6c 6912 unsigned int address_size = remote_address_size;
a744cf53 6913
911c95a5
UW
6914 /* If "remoteaddresssize" was not set, default to target address size. */
6915 if (!address_size)
f5656ead 6916 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
6917
6918 if (address_size > 0
6919 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
6920 {
6921 /* Only create a mask when that mask can safely be constructed
23860348 6922 in a ULONGEST variable. */
c906108c 6923 ULONGEST mask = 1;
a744cf53 6924
911c95a5 6925 mask = (mask << address_size) - 1;
c906108c
SS
6926 addr &= mask;
6927 }
6928 return addr;
6929}
6930
6931/* Determine whether the remote target supports binary downloading.
6932 This is accomplished by sending a no-op memory write of zero length
6933 to the target at the specified address. It does not suffice to send
23860348
MS
6934 the whole packet, since many stubs strip the eighth bit and
6935 subsequently compute a wrong checksum, which causes real havoc with
6936 remote_write_bytes.
7a292a7a 6937
96baa820 6938 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 6939 clean. In cases like this, the user should clear "remote
23860348 6940 X-packet". */
96baa820 6941
c906108c 6942static void
fba45db2 6943check_binary_download (CORE_ADDR addr)
c906108c 6944{
d01949b6 6945 struct remote_state *rs = get_remote_state ();
24b06219 6946
4082afcc 6947 switch (packet_support (PACKET_X))
c906108c 6948 {
96baa820
JM
6949 case PACKET_DISABLE:
6950 break;
6951 case PACKET_ENABLE:
6952 break;
6953 case PACKET_SUPPORT_UNKNOWN:
6954 {
96baa820 6955 char *p;
802188a7 6956
2e9f7625 6957 p = rs->buf;
96baa820
JM
6958 *p++ = 'X';
6959 p += hexnumstr (p, (ULONGEST) addr);
6960 *p++ = ',';
6961 p += hexnumstr (p, (ULONGEST) 0);
6962 *p++ = ':';
6963 *p = '\0';
802188a7 6964
2e9f7625 6965 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 6966 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 6967
2e9f7625 6968 if (rs->buf[0] == '\0')
96baa820
JM
6969 {
6970 if (remote_debug)
6971 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
6972 "binary downloading NOT "
6973 "supported by target\n");
444abaca 6974 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
6975 }
6976 else
6977 {
6978 if (remote_debug)
6979 fprintf_unfiltered (gdb_stdlog,
64b9b334 6980 "binary downloading supported by target\n");
444abaca 6981 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
6982 }
6983 break;
6984 }
c906108c
SS
6985 }
6986}
6987
124e13d9
SM
6988/* Helper function to resize the payload in order to try to get a good
6989 alignment. We try to write an amount of data such that the next write will
6990 start on an address aligned on REMOTE_ALIGN_WRITES. */
6991
6992static int
6993align_for_efficient_write (int todo, CORE_ADDR memaddr)
6994{
6995 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6996}
6997
c906108c
SS
6998/* Write memory data directly to the remote machine.
6999 This does not inform the data cache; the data cache uses this.
a76d924d 7000 HEADER is the starting part of the packet.
c906108c
SS
7001 MEMADDR is the address in the remote memory space.
7002 MYADDR is the address of the buffer in our space.
124e13d9
SM
7003 LEN_UNITS is the number of addressable units to write.
7004 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
7005 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7006 should send data as binary ('X'), or hex-encoded ('M').
7007
7008 The function creates packet of the form
7009 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7010
124e13d9 7011 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
7012
7013 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7014 are omitted.
7015
9b409511 7016 Return the transferred status, error or OK (an
124e13d9
SM
7017 'enum target_xfer_status' value). Save the number of addressable units
7018 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7019
7020 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7021 exchange between gdb and the stub could look like (?? in place of the
7022 checksum):
7023
7024 -> $m1000,4#??
7025 <- aaaabbbbccccdddd
7026
7027 -> $M1000,3:eeeeffffeeee#??
7028 <- OK
7029
7030 -> $m1000,4#??
7031 <- eeeeffffeeeedddd */
c906108c 7032
9b409511 7033static enum target_xfer_status
a76d924d 7034remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
7035 const gdb_byte *myaddr, ULONGEST len_units,
7036 int unit_size, ULONGEST *xfered_len_units,
7037 char packet_format, int use_length)
c906108c 7038{
6d820c5c 7039 struct remote_state *rs = get_remote_state ();
cfd77fa1 7040 char *p;
a76d924d
DJ
7041 char *plen = NULL;
7042 int plenlen = 0;
124e13d9
SM
7043 int todo_units;
7044 int units_written;
7045 int payload_capacity_bytes;
7046 int payload_length_bytes;
a76d924d
DJ
7047
7048 if (packet_format != 'X' && packet_format != 'M')
7049 internal_error (__FILE__, __LINE__,
9b20d036 7050 _("remote_write_bytes_aux: bad packet format"));
c906108c 7051
124e13d9 7052 if (len_units == 0)
9b409511 7053 return TARGET_XFER_EOF;
b2182ed2 7054
124e13d9 7055 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 7056
6d820c5c
DJ
7057 /* The packet buffer will be large enough for the payload;
7058 get_memory_packet_size ensures this. */
a76d924d 7059 rs->buf[0] = '\0';
c906108c 7060
a257b5bb 7061 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
7062 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7063
124e13d9 7064 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 7065 if (!use_length)
0df8b418 7066 /* The comma won't be used. */
124e13d9
SM
7067 payload_capacity_bytes += 1;
7068 payload_capacity_bytes -= strlen (header);
7069 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 7070
a76d924d 7071 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 7072
a76d924d
DJ
7073 strcat (rs->buf, header);
7074 p = rs->buf + strlen (header);
7075
7076 /* Compute a best guess of the number of bytes actually transfered. */
7077 if (packet_format == 'X')
c906108c 7078 {
23860348 7079 /* Best guess at number of bytes that will fit. */
124e13d9 7080 todo_units = min (len_units, payload_capacity_bytes / unit_size);
a76d924d 7081 if (use_length)
124e13d9
SM
7082 payload_capacity_bytes -= hexnumlen (todo_units);
7083 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
7084 }
7085 else
7086 {
124e13d9
SM
7087 /* Number of bytes that will fit. */
7088 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
a76d924d 7089 if (use_length)
124e13d9
SM
7090 payload_capacity_bytes -= hexnumlen (todo_units);
7091 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
917317f4 7092 }
a76d924d 7093
124e13d9 7094 if (todo_units <= 0)
3de11b2e 7095 internal_error (__FILE__, __LINE__,
405f8e94 7096 _("minimum packet size too small to write data"));
802188a7 7097
6765f3e5
DJ
7098 /* If we already need another packet, then try to align the end
7099 of this packet to a useful boundary. */
124e13d9
SM
7100 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7101 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 7102
a257b5bb 7103 /* Append "<memaddr>". */
917317f4
JM
7104 memaddr = remote_address_masked (memaddr);
7105 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 7106
a76d924d
DJ
7107 if (use_length)
7108 {
7109 /* Append ",". */
7110 *p++ = ',';
802188a7 7111
124e13d9
SM
7112 /* Append the length and retain its location and size. It may need to be
7113 adjusted once the packet body has been created. */
a76d924d 7114 plen = p;
124e13d9 7115 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
7116 p += plenlen;
7117 }
a257b5bb
AC
7118
7119 /* Append ":". */
917317f4
JM
7120 *p++ = ':';
7121 *p = '\0';
802188a7 7122
a257b5bb 7123 /* Append the packet body. */
a76d924d 7124 if (packet_format == 'X')
917317f4 7125 {
917317f4
JM
7126 /* Binary mode. Send target system values byte by byte, in
7127 increasing byte addresses. Only escape certain critical
7128 characters. */
124e13d9
SM
7129 payload_length_bytes =
7130 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7131 &units_written, payload_capacity_bytes);
6765f3e5 7132
124e13d9 7133 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
7134 a second try to keep the end of the packet aligned. Don't do
7135 this if the packet is tiny. */
124e13d9 7136 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 7137 {
124e13d9
SM
7138 int new_todo_units;
7139
7140 new_todo_units = align_for_efficient_write (units_written, memaddr);
7141
7142 if (new_todo_units != units_written)
7143 payload_length_bytes =
7144 remote_escape_output (myaddr, new_todo_units, unit_size,
7145 (gdb_byte *) p, &units_written,
7146 payload_capacity_bytes);
6765f3e5
DJ
7147 }
7148
124e13d9
SM
7149 p += payload_length_bytes;
7150 if (use_length && units_written < todo_units)
c906108c 7151 {
802188a7 7152 /* Escape chars have filled up the buffer prematurely,
124e13d9 7153 and we have actually sent fewer units than planned.
917317f4
JM
7154 Fix-up the length field of the packet. Use the same
7155 number of characters as before. */
124e13d9
SM
7156 plen += hexnumnstr (plen, (ULONGEST) units_written,
7157 plenlen);
917317f4 7158 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 7159 }
a76d924d
DJ
7160 }
7161 else
7162 {
917317f4
JM
7163 /* Normal mode: Send target system values byte by byte, in
7164 increasing byte addresses. Each byte is encoded as a two hex
7165 value. */
124e13d9
SM
7166 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7167 units_written = todo_units;
c906108c 7168 }
802188a7 7169
2e9f7625 7170 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7171 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 7172
2e9f7625 7173 if (rs->buf[0] == 'E')
00d84524 7174 return TARGET_XFER_E_IO;
802188a7 7175
124e13d9
SM
7176 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7177 send fewer units than we'd planned. */
7178 *xfered_len_units = (ULONGEST) units_written;
9b409511 7179 return TARGET_XFER_OK;
c906108c
SS
7180}
7181
a76d924d
DJ
7182/* Write memory data directly to the remote machine.
7183 This does not inform the data cache; the data cache uses this.
7184 MEMADDR is the address in the remote memory space.
7185 MYADDR is the address of the buffer in our space.
7186 LEN is the number of bytes.
7187
9b409511
YQ
7188 Return the transferred status, error or OK (an
7189 'enum target_xfer_status' value). Save the number of bytes
7190 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 7191
9b409511
YQ
7192static enum target_xfer_status
7193remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 7194 int unit_size, ULONGEST *xfered_len)
a76d924d
DJ
7195{
7196 char *packet_format = 0;
7197
7198 /* Check whether the target supports binary download. */
7199 check_binary_download (memaddr);
7200
4082afcc 7201 switch (packet_support (PACKET_X))
a76d924d
DJ
7202 {
7203 case PACKET_ENABLE:
7204 packet_format = "X";
7205 break;
7206 case PACKET_DISABLE:
7207 packet_format = "M";
7208 break;
7209 case PACKET_SUPPORT_UNKNOWN:
7210 internal_error (__FILE__, __LINE__,
7211 _("remote_write_bytes: bad internal state"));
7212 default:
7213 internal_error (__FILE__, __LINE__, _("bad switch"));
7214 }
7215
7216 return remote_write_bytes_aux (packet_format,
124e13d9 7217 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 7218 packet_format[0], 1);
a76d924d
DJ
7219}
7220
9217e74e
YQ
7221/* Read memory data directly from the remote machine.
7222 This does not use the data cache; the data cache uses this.
7223 MEMADDR is the address in the remote memory space.
7224 MYADDR is the address of the buffer in our space.
124e13d9
SM
7225 LEN_UNITS is the number of addressable memory units to read..
7226 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
7227
7228 Return the transferred status, error or OK (an
7229 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
7230 transferred in *XFERED_LEN_UNITS.
7231
7232 See the comment of remote_write_bytes_aux for an example of
7233 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
7234
7235static enum target_xfer_status
124e13d9
SM
7236remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7237 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
7238{
7239 struct remote_state *rs = get_remote_state ();
124e13d9 7240 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 7241 char *p;
124e13d9
SM
7242 int todo_units;
7243 int decoded_bytes;
9217e74e 7244
124e13d9 7245 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
7246 /* The packet buffer will be large enough for the payload;
7247 get_memory_packet_size ensures this. */
7248
124e13d9
SM
7249 /* Number of units that will fit. */
7250 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
7251
7252 /* Construct "m"<memaddr>","<len>". */
7253 memaddr = remote_address_masked (memaddr);
7254 p = rs->buf;
7255 *p++ = 'm';
7256 p += hexnumstr (p, (ULONGEST) memaddr);
7257 *p++ = ',';
124e13d9 7258 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
7259 *p = '\0';
7260 putpkt (rs->buf);
7261 getpkt (&rs->buf, &rs->buf_size, 0);
7262 if (rs->buf[0] == 'E'
7263 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7264 && rs->buf[3] == '\0')
7265 return TARGET_XFER_E_IO;
7266 /* Reply describes memory byte by byte, each byte encoded as two hex
7267 characters. */
7268 p = rs->buf;
124e13d9 7269 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 7270 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 7271 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9217e74e
YQ
7272 return TARGET_XFER_OK;
7273}
7274
b55fbac4
YQ
7275/* Using the set of read-only target sections of remote, read live
7276 read-only memory.
8acf9577
YQ
7277
7278 For interface/parameters/return description see target.h,
7279 to_xfer_partial. */
7280
7281static enum target_xfer_status
b55fbac4
YQ
7282remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7283 ULONGEST memaddr, ULONGEST len,
124e13d9 7284 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
7285{
7286 struct target_section *secp;
7287 struct target_section_table *table;
7288
7289 secp = target_section_by_addr (ops, memaddr);
7290 if (secp != NULL
7291 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7292 secp->the_bfd_section)
7293 & SEC_READONLY))
7294 {
7295 struct target_section *p;
7296 ULONGEST memend = memaddr + len;
7297
7298 table = target_get_section_table (ops);
7299
7300 for (p = table->sections; p < table->sections_end; p++)
7301 {
7302 if (memaddr >= p->addr)
7303 {
7304 if (memend <= p->endaddr)
7305 {
7306 /* Entire transfer is within this section. */
124e13d9 7307 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7308 xfered_len);
8acf9577
YQ
7309 }
7310 else if (memaddr >= p->endaddr)
7311 {
7312 /* This section ends before the transfer starts. */
7313 continue;
7314 }
7315 else
7316 {
7317 /* This section overlaps the transfer. Just do half. */
7318 len = p->endaddr - memaddr;
124e13d9 7319 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7320 xfered_len);
8acf9577
YQ
7321 }
7322 }
7323 }
7324 }
7325
7326 return TARGET_XFER_EOF;
7327}
7328
9217e74e
YQ
7329/* Similar to remote_read_bytes_1, but it reads from the remote stub
7330 first if the requested memory is unavailable in traceframe.
7331 Otherwise, fall back to remote_read_bytes_1. */
c906108c 7332
9b409511 7333static enum target_xfer_status
8acf9577 7334remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
7335 gdb_byte *myaddr, ULONGEST len, int unit_size,
7336 ULONGEST *xfered_len)
c906108c 7337{
6b6aa828 7338 if (len == 0)
96c4f946 7339 return TARGET_XFER_EOF;
b2182ed2 7340
8acf9577
YQ
7341 if (get_traceframe_number () != -1)
7342 {
7343 VEC(mem_range_s) *available;
7344
7345 /* If we fail to get the set of available memory, then the
7346 target does not support querying traceframe info, and so we
7347 attempt reading from the traceframe anyway (assuming the
7348 target implements the old QTro packet then). */
7349 if (traceframe_available_memory (&available, memaddr, len))
7350 {
7351 struct cleanup *old_chain;
7352
7353 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7354
7355 if (VEC_empty (mem_range_s, available)
7356 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7357 {
7358 enum target_xfer_status res;
7359
7360 /* Don't read into the traceframe's available
7361 memory. */
7362 if (!VEC_empty (mem_range_s, available))
7363 {
7364 LONGEST oldlen = len;
7365
7366 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7367 gdb_assert (len <= oldlen);
7368 }
7369
7370 do_cleanups (old_chain);
7371
7372 /* This goes through the topmost target again. */
b55fbac4 7373 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 7374 len, unit_size, xfered_len);
8acf9577
YQ
7375 if (res == TARGET_XFER_OK)
7376 return TARGET_XFER_OK;
7377 else
7378 {
7379 /* No use trying further, we know some memory starting
7380 at MEMADDR isn't available. */
7381 *xfered_len = len;
7382 return TARGET_XFER_UNAVAILABLE;
7383 }
7384 }
7385
7386 /* Don't try to read more than how much is available, in
7387 case the target implements the deprecated QTro packet to
7388 cater for older GDBs (the target's knowledge of read-only
7389 sections may be outdated by now). */
7390 len = VEC_index (mem_range_s, available, 0)->length;
7391
7392 do_cleanups (old_chain);
7393 }
7394 }
7395
124e13d9 7396 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 7397}
74531fed 7398
c906108c 7399\f
c906108c 7400
a76d924d
DJ
7401/* Sends a packet with content determined by the printf format string
7402 FORMAT and the remaining arguments, then gets the reply. Returns
7403 whether the packet was a success, a failure, or unknown. */
7404
77b64a49
PA
7405static enum packet_result remote_send_printf (const char *format, ...)
7406 ATTRIBUTE_PRINTF (1, 2);
7407
2c0b251b 7408static enum packet_result
a76d924d
DJ
7409remote_send_printf (const char *format, ...)
7410{
7411 struct remote_state *rs = get_remote_state ();
7412 int max_size = get_remote_packet_size ();
a76d924d 7413 va_list ap;
a744cf53 7414
a76d924d
DJ
7415 va_start (ap, format);
7416
7417 rs->buf[0] = '\0';
7418 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 7419 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
7420
7421 if (putpkt (rs->buf) < 0)
7422 error (_("Communication problem with target."));
7423
7424 rs->buf[0] = '\0';
7425 getpkt (&rs->buf, &rs->buf_size, 0);
7426
7427 return packet_check_result (rs->buf);
7428}
7429
7430static void
7431restore_remote_timeout (void *p)
7432{
7433 int value = *(int *)p;
a744cf53 7434
a76d924d
DJ
7435 remote_timeout = value;
7436}
7437
7438/* Flash writing can take quite some time. We'll set
7439 effectively infinite timeout for flash operations.
7440 In future, we'll need to decide on a better approach. */
7441static const int remote_flash_timeout = 1000;
7442
7443static void
7444remote_flash_erase (struct target_ops *ops,
7445 ULONGEST address, LONGEST length)
7446{
f5656ead 7447 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
7448 int saved_remote_timeout = remote_timeout;
7449 enum packet_result ret;
a76d924d
DJ
7450 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7451 &saved_remote_timeout);
a744cf53 7452
a76d924d
DJ
7453 remote_timeout = remote_flash_timeout;
7454
7455 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 7456 phex (address, addr_size),
a76d924d
DJ
7457 phex (length, 4));
7458 switch (ret)
7459 {
7460 case PACKET_UNKNOWN:
7461 error (_("Remote target does not support flash erase"));
7462 case PACKET_ERROR:
7463 error (_("Error erasing flash with vFlashErase packet"));
7464 default:
7465 break;
7466 }
7467
7468 do_cleanups (back_to);
7469}
7470
9b409511
YQ
7471static enum target_xfer_status
7472remote_flash_write (struct target_ops *ops, ULONGEST address,
7473 ULONGEST length, ULONGEST *xfered_len,
7474 const gdb_byte *data)
a76d924d
DJ
7475{
7476 int saved_remote_timeout = remote_timeout;
9b409511 7477 enum target_xfer_status ret;
a76d924d 7478 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 7479 &saved_remote_timeout);
a76d924d
DJ
7480
7481 remote_timeout = remote_flash_timeout;
124e13d9 7482 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9b409511 7483 xfered_len,'X', 0);
a76d924d
DJ
7484 do_cleanups (back_to);
7485
7486 return ret;
7487}
7488
7489static void
7490remote_flash_done (struct target_ops *ops)
7491{
7492 int saved_remote_timeout = remote_timeout;
7493 int ret;
7494 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7495 &saved_remote_timeout);
7496
7497 remote_timeout = remote_flash_timeout;
7498 ret = remote_send_printf ("vFlashDone");
7499 do_cleanups (back_to);
7500
7501 switch (ret)
7502 {
7503 case PACKET_UNKNOWN:
7504 error (_("Remote target does not support vFlashDone"));
7505 case PACKET_ERROR:
7506 error (_("Error finishing flash operation"));
7507 default:
7508 break;
7509 }
7510}
7511
c906108c 7512static void
fba45db2 7513remote_files_info (struct target_ops *ignore)
c906108c
SS
7514{
7515 puts_filtered ("Debugging a target over a serial line.\n");
7516}
7517\f
7518/* Stuff for dealing with the packets which are part of this protocol.
7519 See comment at top of file for details. */
7520
1927e618
PA
7521/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7522 error to higher layers. Called when a serial error is detected.
7523 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
7524 the system error message for errno at function entry and final dot
7525 for output compatibility with throw_perror_with_name. */
1927e618
PA
7526
7527static void
7528unpush_and_perror (const char *string)
7529{
d6cb50a2 7530 int saved_errno = errno;
1927e618
PA
7531
7532 remote_unpush_target ();
d6cb50a2
JK
7533 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7534 safe_strerror (saved_errno));
1927e618
PA
7535}
7536
0876f84a 7537/* Read a single character from the remote end. */
c906108c
SS
7538
7539static int
fba45db2 7540readchar (int timeout)
c906108c
SS
7541{
7542 int ch;
5d93a237 7543 struct remote_state *rs = get_remote_state ();
c906108c 7544
5d93a237 7545 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 7546
2acceee2 7547 if (ch >= 0)
0876f84a 7548 return ch;
2acceee2
JM
7549
7550 switch ((enum serial_rc) ch)
c906108c
SS
7551 {
7552 case SERIAL_EOF:
78a095c3 7553 remote_unpush_target ();
598d3636 7554 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 7555 /* no return */
c906108c 7556 case SERIAL_ERROR:
1927e618
PA
7557 unpush_and_perror (_("Remote communication error. "
7558 "Target disconnected."));
2acceee2 7559 /* no return */
c906108c 7560 case SERIAL_TIMEOUT:
2acceee2 7561 break;
c906108c 7562 }
2acceee2 7563 return ch;
c906108c
SS
7564}
7565
c33e31fd
PA
7566/* Wrapper for serial_write that closes the target and throws if
7567 writing fails. */
7568
7569static void
7570remote_serial_write (const char *str, int len)
7571{
5d93a237
TT
7572 struct remote_state *rs = get_remote_state ();
7573
7574 if (serial_write (rs->remote_desc, str, len))
c33e31fd 7575 {
1927e618
PA
7576 unpush_and_perror (_("Remote communication error. "
7577 "Target disconnected."));
c33e31fd
PA
7578 }
7579}
7580
6d820c5c
DJ
7581/* Send the command in *BUF to the remote machine, and read the reply
7582 into *BUF. Report an error if we get an error reply. Resize
7583 *BUF using xrealloc if necessary to hold the result, and update
7584 *SIZEOF_BUF. */
c906108c
SS
7585
7586static void
6d820c5c
DJ
7587remote_send (char **buf,
7588 long *sizeof_buf)
c906108c 7589{
6d820c5c 7590 putpkt (*buf);
c2d11a7d 7591 getpkt (buf, sizeof_buf, 0);
c906108c 7592
6d820c5c
DJ
7593 if ((*buf)[0] == 'E')
7594 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
7595}
7596
6e5abd65
PA
7597/* Return a pointer to an xmalloc'ed string representing an escaped
7598 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7599 etc. The caller is responsible for releasing the returned
7600 memory. */
7601
7602static char *
7603escape_buffer (const char *buf, int n)
7604{
7605 struct cleanup *old_chain;
7606 struct ui_file *stb;
7607 char *str;
6e5abd65
PA
7608
7609 stb = mem_fileopen ();
7610 old_chain = make_cleanup_ui_file_delete (stb);
7611
6ef284bd 7612 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 7613 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
7614 do_cleanups (old_chain);
7615 return str;
7616}
7617
c906108c
SS
7618/* Display a null-terminated packet on stdout, for debugging, using C
7619 string notation. */
7620
7621static void
baa336ce 7622print_packet (const char *buf)
c906108c
SS
7623{
7624 puts_filtered ("\"");
43e526b9 7625 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
7626 puts_filtered ("\"");
7627}
7628
7629int
baa336ce 7630putpkt (const char *buf)
c906108c
SS
7631{
7632 return putpkt_binary (buf, strlen (buf));
7633}
7634
7635/* Send a packet to the remote machine, with error checking. The data
23860348 7636 of the packet is in BUF. The string in BUF can be at most
ea9c271d 7637 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
7638 and for a possible /0 if we are debugging (remote_debug) and want
7639 to print the sent packet as a string. */
c906108c
SS
7640
7641static int
baa336ce 7642putpkt_binary (const char *buf, int cnt)
c906108c 7643{
2d717e4f 7644 struct remote_state *rs = get_remote_state ();
c906108c
SS
7645 int i;
7646 unsigned char csum = 0;
11cf8741 7647 char *buf2 = alloca (cnt + 6);
085dd6e6 7648
c906108c
SS
7649 int ch;
7650 int tcount = 0;
7651 char *p;
dd61ec5c 7652 char *message;
c906108c 7653
e24a49d8
PA
7654 /* Catch cases like trying to read memory or listing threads while
7655 we're waiting for a stop reply. The remote server wouldn't be
7656 ready to handle this request, so we'd hang and timeout. We don't
7657 have to worry about this in synchronous mode, because in that
7658 case it's not possible to issue a command while the target is
74531fed
PA
7659 running. This is not a problem in non-stop mode, because in that
7660 case, the stub is always ready to process serial input. */
d9d41e78 7661 if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
9597b22a
DE
7662 {
7663 error (_("Cannot execute this command while the target is running.\n"
7664 "Use the \"interrupt\" command to stop the target\n"
7665 "and then try again."));
7666 }
e24a49d8 7667
2d717e4f
DJ
7668 /* We're sending out a new packet. Make sure we don't look at a
7669 stale cached response. */
7670 rs->cached_wait_status = 0;
7671
c906108c
SS
7672 /* Copy the packet into buffer BUF2, encapsulating it
7673 and giving it a checksum. */
7674
c906108c
SS
7675 p = buf2;
7676 *p++ = '$';
7677
7678 for (i = 0; i < cnt; i++)
7679 {
7680 csum += buf[i];
7681 *p++ = buf[i];
7682 }
7683 *p++ = '#';
7684 *p++ = tohex ((csum >> 4) & 0xf);
7685 *p++ = tohex (csum & 0xf);
7686
7687 /* Send it over and over until we get a positive ack. */
7688
7689 while (1)
7690 {
7691 int started_error_output = 0;
7692
7693 if (remote_debug)
7694 {
6e5abd65
PA
7695 struct cleanup *old_chain;
7696 char *str;
7697
c906108c 7698 *p = '\0';
6e5abd65
PA
7699 str = escape_buffer (buf2, p - buf2);
7700 old_chain = make_cleanup (xfree, str);
7701 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 7702 gdb_flush (gdb_stdlog);
6e5abd65 7703 do_cleanups (old_chain);
c906108c 7704 }
c33e31fd 7705 remote_serial_write (buf2, p - buf2);
c906108c 7706
a6f3e723
SL
7707 /* If this is a no acks version of the remote protocol, send the
7708 packet and move on. */
7709 if (rs->noack_mode)
7710 break;
7711
74531fed
PA
7712 /* Read until either a timeout occurs (-2) or '+' is read.
7713 Handle any notification that arrives in the mean time. */
c906108c
SS
7714 while (1)
7715 {
7716 ch = readchar (remote_timeout);
7717
c5aa993b 7718 if (remote_debug)
c906108c
SS
7719 {
7720 switch (ch)
7721 {
7722 case '+':
1216fa2c 7723 case '-':
c906108c
SS
7724 case SERIAL_TIMEOUT:
7725 case '$':
74531fed 7726 case '%':
c906108c
SS
7727 if (started_error_output)
7728 {
7729 putchar_unfiltered ('\n');
7730 started_error_output = 0;
7731 }
7732 }
7733 }
7734
7735 switch (ch)
7736 {
7737 case '+':
7738 if (remote_debug)
0f71a2f6 7739 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 7740 return 1;
1216fa2c
AC
7741 case '-':
7742 if (remote_debug)
7743 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 7744 /* FALLTHROUGH */
c906108c 7745 case SERIAL_TIMEOUT:
c5aa993b 7746 tcount++;
c906108c
SS
7747 if (tcount > 3)
7748 return 0;
23860348 7749 break; /* Retransmit buffer. */
c906108c
SS
7750 case '$':
7751 {
40e3f985 7752 if (remote_debug)
2bc416ba 7753 fprintf_unfiltered (gdb_stdlog,
23860348 7754 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
7755 /* It's probably an old response sent because an ACK
7756 was lost. Gobble up the packet and ack it so it
7757 doesn't get retransmitted when we resend this
7758 packet. */
6d820c5c 7759 skip_frame ();
c33e31fd 7760 remote_serial_write ("+", 1);
23860348 7761 continue; /* Now, go look for +. */
c906108c 7762 }
74531fed
PA
7763
7764 case '%':
7765 {
7766 int val;
7767
7768 /* If we got a notification, handle it, and go back to looking
7769 for an ack. */
7770 /* We've found the start of a notification. Now
7771 collect the data. */
7772 val = read_frame (&rs->buf, &rs->buf_size);
7773 if (val >= 0)
7774 {
7775 if (remote_debug)
7776 {
6e5abd65
PA
7777 struct cleanup *old_chain;
7778 char *str;
7779
7780 str = escape_buffer (rs->buf, val);
7781 old_chain = make_cleanup (xfree, str);
7782 fprintf_unfiltered (gdb_stdlog,
7783 " Notification received: %s\n",
7784 str);
7785 do_cleanups (old_chain);
74531fed 7786 }
5965e028 7787 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
7788 /* We're in sync now, rewait for the ack. */
7789 tcount = 0;
7790 }
7791 else
7792 {
7793 if (remote_debug)
7794 {
7795 if (!started_error_output)
7796 {
7797 started_error_output = 1;
7798 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7799 }
7800 fputc_unfiltered (ch & 0177, gdb_stdlog);
7801 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7802 }
7803 }
7804 continue;
7805 }
7806 /* fall-through */
c906108c
SS
7807 default:
7808 if (remote_debug)
7809 {
7810 if (!started_error_output)
7811 {
7812 started_error_output = 1;
0f71a2f6 7813 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 7814 }
0f71a2f6 7815 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
7816 }
7817 continue;
7818 }
23860348 7819 break; /* Here to retransmit. */
c906108c
SS
7820 }
7821
7822#if 0
7823 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
7824 able to get out next time we call QUIT, without anything as
7825 violent as interrupt_query. If we want to provide a way out of
7826 here without getting to the next QUIT, it should be based on
7827 hitting ^C twice as in remote_wait. */
c906108c
SS
7828 if (quit_flag)
7829 {
7830 quit_flag = 0;
7831 interrupt_query ();
7832 }
7833#endif
7834 }
a6f3e723 7835 return 0;
c906108c
SS
7836}
7837
6d820c5c
DJ
7838/* Come here after finding the start of a frame when we expected an
7839 ack. Do our best to discard the rest of this packet. */
7840
7841static void
7842skip_frame (void)
7843{
7844 int c;
7845
7846 while (1)
7847 {
7848 c = readchar (remote_timeout);
7849 switch (c)
7850 {
7851 case SERIAL_TIMEOUT:
7852 /* Nothing we can do. */
7853 return;
7854 case '#':
7855 /* Discard the two bytes of checksum and stop. */
7856 c = readchar (remote_timeout);
7857 if (c >= 0)
7858 c = readchar (remote_timeout);
7859
7860 return;
7861 case '*': /* Run length encoding. */
7862 /* Discard the repeat count. */
7863 c = readchar (remote_timeout);
7864 if (c < 0)
7865 return;
7866 break;
7867 default:
7868 /* A regular character. */
7869 break;
7870 }
7871 }
7872}
7873
c906108c 7874/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
7875 into *BUF, verifying the checksum, length, and handling run-length
7876 compression. NUL terminate the buffer. If there is not enough room,
7877 expand *BUF using xrealloc.
c906108c 7878
c2d11a7d
JM
7879 Returns -1 on error, number of characters in buffer (ignoring the
7880 trailing NULL) on success. (could be extended to return one of the
23860348 7881 SERIAL status indications). */
c2d11a7d
JM
7882
7883static long
6d820c5c
DJ
7884read_frame (char **buf_p,
7885 long *sizeof_buf)
c906108c
SS
7886{
7887 unsigned char csum;
c2d11a7d 7888 long bc;
c906108c 7889 int c;
6d820c5c 7890 char *buf = *buf_p;
a6f3e723 7891 struct remote_state *rs = get_remote_state ();
c906108c
SS
7892
7893 csum = 0;
c2d11a7d 7894 bc = 0;
c906108c
SS
7895
7896 while (1)
7897 {
7898 c = readchar (remote_timeout);
c906108c
SS
7899 switch (c)
7900 {
7901 case SERIAL_TIMEOUT:
7902 if (remote_debug)
0f71a2f6 7903 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 7904 return -1;
c906108c
SS
7905 case '$':
7906 if (remote_debug)
0f71a2f6
JM
7907 fputs_filtered ("Saw new packet start in middle of old one\n",
7908 gdb_stdlog);
23860348 7909 return -1; /* Start a new packet, count retries. */
c906108c
SS
7910 case '#':
7911 {
7912 unsigned char pktcsum;
e1b09194
AC
7913 int check_0 = 0;
7914 int check_1 = 0;
c906108c 7915
c2d11a7d 7916 buf[bc] = '\0';
c906108c 7917
e1b09194
AC
7918 check_0 = readchar (remote_timeout);
7919 if (check_0 >= 0)
7920 check_1 = readchar (remote_timeout);
802188a7 7921
e1b09194
AC
7922 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7923 {
7924 if (remote_debug)
2bc416ba 7925 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 7926 gdb_stdlog);
e1b09194
AC
7927 return -1;
7928 }
7929 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
7930 {
7931 if (remote_debug)
2bc416ba 7932 fputs_filtered ("Communication error in checksum\n",
23860348 7933 gdb_stdlog);
40e3f985
FN
7934 return -1;
7935 }
c906108c 7936
a6f3e723
SL
7937 /* Don't recompute the checksum; with no ack packets we
7938 don't have any way to indicate a packet retransmission
7939 is necessary. */
7940 if (rs->noack_mode)
7941 return bc;
7942
e1b09194 7943 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 7944 if (csum == pktcsum)
c2d11a7d 7945 return bc;
c906108c 7946
c5aa993b 7947 if (remote_debug)
c906108c 7948 {
6e5abd65
PA
7949 struct cleanup *old_chain;
7950 char *str;
7951
7952 str = escape_buffer (buf, bc);
7953 old_chain = make_cleanup (xfree, str);
7954 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7955 "Bad checksum, sentsum=0x%x, "
7956 "csum=0x%x, buf=%s\n",
6e5abd65
PA
7957 pktcsum, csum, str);
7958 do_cleanups (old_chain);
c906108c 7959 }
c2d11a7d 7960 /* Number of characters in buffer ignoring trailing
23860348 7961 NULL. */
c2d11a7d 7962 return -1;
c906108c 7963 }
23860348 7964 case '*': /* Run length encoding. */
c2c6d25f
JM
7965 {
7966 int repeat;
c906108c 7967
a744cf53 7968 csum += c;
b4501125
AC
7969 c = readchar (remote_timeout);
7970 csum += c;
23860348 7971 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 7972
23860348 7973 /* The character before ``*'' is repeated. */
c2d11a7d 7974
6d820c5c 7975 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 7976 {
6d820c5c
DJ
7977 if (bc + repeat - 1 >= *sizeof_buf - 1)
7978 {
7979 /* Make some more room in the buffer. */
7980 *sizeof_buf += repeat;
7981 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7982 buf = *buf_p;
7983 }
7984
c2d11a7d
JM
7985 memset (&buf[bc], buf[bc - 1], repeat);
7986 bc += repeat;
c2c6d25f
JM
7987 continue;
7988 }
7989
c2d11a7d 7990 buf[bc] = '\0';
6d820c5c 7991 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 7992 return -1;
c2c6d25f 7993 }
c906108c 7994 default:
6d820c5c 7995 if (bc >= *sizeof_buf - 1)
c906108c 7996 {
6d820c5c
DJ
7997 /* Make some more room in the buffer. */
7998 *sizeof_buf *= 2;
7999 *buf_p = xrealloc (*buf_p, *sizeof_buf);
8000 buf = *buf_p;
c906108c
SS
8001 }
8002
6d820c5c
DJ
8003 buf[bc++] = c;
8004 csum += c;
8005 continue;
c906108c
SS
8006 }
8007 }
8008}
8009
8010/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8011 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8012 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8013 rather than timing out; this is used (in synchronous mode) to wait
8014 for a target that is is executing user code to stop. */
d9fcf2fb
JM
8015/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8016 don't have to change all the calls to getpkt to deal with the
8017 return value, because at the moment I don't know what the right
23860348 8018 thing to do it for those. */
c906108c 8019void
6d820c5c
DJ
8020getpkt (char **buf,
8021 long *sizeof_buf,
c2d11a7d 8022 int forever)
d9fcf2fb
JM
8023{
8024 int timed_out;
8025
8026 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8027}
8028
8029
8030/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8031 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8032 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8033 rather than timing out; this is used (in synchronous mode) to wait
8034 for a target that is is executing user code to stop. If FOREVER ==
8035 0, this function is allowed to time out gracefully and return an
74531fed
PA
8036 indication of this to the caller. Otherwise return the number of
8037 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
8038 enough reason to return to the caller. *IS_NOTIF is an output
8039 boolean that indicates whether *BUF holds a notification or not
8040 (a regular packet). */
74531fed 8041
3172dc30 8042static int
74531fed 8043getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 8044 int expecting_notif, int *is_notif)
c906108c 8045{
2d717e4f 8046 struct remote_state *rs = get_remote_state ();
c906108c
SS
8047 int c;
8048 int tries;
8049 int timeout;
df4b58fe 8050 int val = -1;
c906108c 8051
2d717e4f
DJ
8052 /* We're reading a new response. Make sure we don't look at a
8053 previously cached response. */
8054 rs->cached_wait_status = 0;
8055
6d820c5c 8056 strcpy (*buf, "timeout");
c906108c
SS
8057
8058 if (forever)
74531fed
PA
8059 timeout = watchdog > 0 ? watchdog : -1;
8060 else if (expecting_notif)
8061 timeout = 0; /* There should already be a char in the buffer. If
8062 not, bail out. */
c906108c
SS
8063 else
8064 timeout = remote_timeout;
8065
8066#define MAX_TRIES 3
8067
74531fed
PA
8068 /* Process any number of notifications, and then return when
8069 we get a packet. */
8070 for (;;)
c906108c 8071 {
d9c43928 8072 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
8073 times. */
8074 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 8075 {
74531fed
PA
8076 /* This can loop forever if the remote side sends us
8077 characters continuously, but if it pauses, we'll get
8078 SERIAL_TIMEOUT from readchar because of timeout. Then
8079 we'll count that as a retry.
8080
8081 Note that even when forever is set, we will only wait
8082 forever prior to the start of a packet. After that, we
8083 expect characters to arrive at a brisk pace. They should
8084 show up within remote_timeout intervals. */
8085 do
8086 c = readchar (timeout);
8087 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
8088
8089 if (c == SERIAL_TIMEOUT)
8090 {
74531fed
PA
8091 if (expecting_notif)
8092 return -1; /* Don't complain, it's normal to not get
8093 anything in this case. */
8094
23860348 8095 if (forever) /* Watchdog went off? Kill the target. */
c906108c 8096 {
2acceee2 8097 QUIT;
78a095c3 8098 remote_unpush_target ();
598d3636
JK
8099 throw_error (TARGET_CLOSE_ERROR,
8100 _("Watchdog timeout has expired. "
8101 "Target detached."));
c906108c 8102 }
c906108c 8103 if (remote_debug)
0f71a2f6 8104 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 8105 }
74531fed
PA
8106 else
8107 {
8108 /* We've found the start of a packet or notification.
8109 Now collect the data. */
8110 val = read_frame (buf, sizeof_buf);
8111 if (val >= 0)
8112 break;
8113 }
8114
c33e31fd 8115 remote_serial_write ("-", 1);
c906108c 8116 }
c906108c 8117
74531fed
PA
8118 if (tries > MAX_TRIES)
8119 {
8120 /* We have tried hard enough, and just can't receive the
8121 packet/notification. Give up. */
8122 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 8123
74531fed
PA
8124 /* Skip the ack char if we're in no-ack mode. */
8125 if (!rs->noack_mode)
c33e31fd 8126 remote_serial_write ("+", 1);
74531fed
PA
8127 return -1;
8128 }
c906108c 8129
74531fed
PA
8130 /* If we got an ordinary packet, return that to our caller. */
8131 if (c == '$')
c906108c
SS
8132 {
8133 if (remote_debug)
43e526b9 8134 {
6e5abd65
PA
8135 struct cleanup *old_chain;
8136 char *str;
8137
8138 str = escape_buffer (*buf, val);
8139 old_chain = make_cleanup (xfree, str);
8140 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8141 do_cleanups (old_chain);
43e526b9 8142 }
a6f3e723
SL
8143
8144 /* Skip the ack char if we're in no-ack mode. */
8145 if (!rs->noack_mode)
c33e31fd 8146 remote_serial_write ("+", 1);
fee9eda9
YQ
8147 if (is_notif != NULL)
8148 *is_notif = 0;
0876f84a 8149 return val;
c906108c
SS
8150 }
8151
74531fed
PA
8152 /* If we got a notification, handle it, and go back to looking
8153 for a packet. */
8154 else
8155 {
8156 gdb_assert (c == '%');
8157
8158 if (remote_debug)
8159 {
6e5abd65
PA
8160 struct cleanup *old_chain;
8161 char *str;
8162
8163 str = escape_buffer (*buf, val);
8164 old_chain = make_cleanup (xfree, str);
8165 fprintf_unfiltered (gdb_stdlog,
8166 " Notification received: %s\n",
8167 str);
8168 do_cleanups (old_chain);
74531fed 8169 }
fee9eda9
YQ
8170 if (is_notif != NULL)
8171 *is_notif = 1;
c906108c 8172
5965e028 8173 handle_notification (rs->notif_state, *buf);
c906108c 8174
74531fed 8175 /* Notifications require no acknowledgement. */
a6f3e723 8176
74531fed 8177 if (expecting_notif)
fee9eda9 8178 return val;
74531fed
PA
8179 }
8180 }
8181}
8182
8183static int
8184getpkt_sane (char **buf, long *sizeof_buf, int forever)
8185{
fee9eda9 8186 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
8187}
8188
8189static int
fee9eda9
YQ
8190getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8191 int *is_notif)
74531fed 8192{
fee9eda9
YQ
8193 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8194 is_notif);
c906108c 8195}
74531fed 8196
cbb8991c
DB
8197/* Check whether EVENT is a fork event for the process specified
8198 by the pid passed in DATA, and if it is, kill the fork child. */
8199
8200static int
8201kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8202 QUEUE_ITER (stop_reply_p) *iter,
8203 stop_reply_p event,
8204 void *data)
8205{
8206 struct queue_iter_param *param = data;
8207 int parent_pid = *(int *) param->input;
8208
8209 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8210 {
8211 struct remote_state *rs = get_remote_state ();
8212 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8213 int res;
8214
8215 res = remote_vkill (child_pid, rs);
8216 if (res != 0)
8217 error (_("Can't kill fork child process %d"), child_pid);
8218 }
8219
8220 return 1;
8221}
8222
8223/* Kill any new fork children of process PID that haven't been
8224 processed by follow_fork. */
8225
8226static void
8227kill_new_fork_children (int pid, struct remote_state *rs)
8228{
8229 struct thread_info *thread;
8230 struct notif_client *notif = &notif_client_stop;
8231 struct queue_iter_param param;
8232
8233 /* Kill the fork child threads of any threads in process PID
8234 that are stopped at a fork event. */
8235 ALL_NON_EXITED_THREADS (thread)
8236 {
8237 struct target_waitstatus *ws = &thread->pending_follow;
8238
8239 if (is_pending_fork_parent (ws, pid, thread->ptid))
8240 {
8241 struct remote_state *rs = get_remote_state ();
8242 int child_pid = ptid_get_pid (ws->value.related_pid);
8243 int res;
8244
8245 res = remote_vkill (child_pid, rs);
8246 if (res != 0)
8247 error (_("Can't kill fork child process %d"), child_pid);
8248 }
8249 }
8250
8251 /* Check for any pending fork events (not reported or processed yet)
8252 in process PID and kill those fork child threads as well. */
8253 remote_notif_get_pending_events (notif);
8254 param.input = &pid;
8255 param.output = NULL;
8256 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8257 kill_child_of_pending_fork, &param);
8258}
8259
c906108c
SS
8260\f
8261static void
7d85a9c0 8262remote_kill (struct target_ops *ops)
43ff13b4 8263{
0fdf84ca
PA
8264
8265 /* Catch errors so the user can quit from gdb even when we
23860348 8266 aren't on speaking terms with the remote system. */
492d29ea 8267 TRY
0fdf84ca
PA
8268 {
8269 putpkt ("k");
8270 }
492d29ea 8271 CATCH (ex, RETURN_MASK_ERROR)
0fdf84ca
PA
8272 {
8273 if (ex.error == TARGET_CLOSE_ERROR)
8274 {
8275 /* If we got an (EOF) error that caused the target
8276 to go away, then we're done, that's what we wanted.
8277 "k" is susceptible to cause a premature EOF, given
8278 that the remote server isn't actually required to
8279 reply to "k", and it can happen that it doesn't
8280 even get to reply ACK to the "k". */
8281 return;
8282 }
8283
8284 /* Otherwise, something went wrong. We didn't actually kill
8285 the target. Just propagate the exception, and let the
8286 user or higher layers decide what to do. */
8287 throw_exception (ex);
8288 }
492d29ea 8289 END_CATCH
43ff13b4 8290
0fdf84ca
PA
8291 /* We've killed the remote end, we get to mourn it. Since this is
8292 target remote, single-process, mourning the inferior also
8293 unpushes remote_ops. */
43ff13b4
JM
8294 target_mourn_inferior ();
8295}
8296
82f73884
PA
8297static int
8298remote_vkill (int pid, struct remote_state *rs)
8299{
4082afcc 8300 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
8301 return -1;
8302
8303 /* Tell the remote target to detach. */
bba74b36 8304 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
8305 putpkt (rs->buf);
8306 getpkt (&rs->buf, &rs->buf_size, 0);
8307
4082afcc
PA
8308 switch (packet_ok (rs->buf,
8309 &remote_protocol_packets[PACKET_vKill]))
8310 {
8311 case PACKET_OK:
8312 return 0;
8313 case PACKET_ERROR:
8314 return 1;
8315 case PACKET_UNKNOWN:
8316 return -1;
8317 default:
8318 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8319 }
82f73884
PA
8320}
8321
8322static void
7d85a9c0 8323extended_remote_kill (struct target_ops *ops)
82f73884
PA
8324{
8325 int res;
8326 int pid = ptid_get_pid (inferior_ptid);
8327 struct remote_state *rs = get_remote_state ();
8328
cbb8991c
DB
8329 /* If we're stopped while forking and we haven't followed yet, kill the
8330 child task. We need to do this before killing the parent task
8331 because if this is a vfork then the parent will be sleeping. */
8332 kill_new_fork_children (pid, rs);
8333
82f73884 8334 res = remote_vkill (pid, rs);
901f9912 8335 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
82f73884
PA
8336 {
8337 /* Don't try 'k' on a multi-process aware stub -- it has no way
8338 to specify the pid. */
8339
8340 putpkt ("k");
8341#if 0
8342 getpkt (&rs->buf, &rs->buf_size, 0);
8343 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8344 res = 1;
8345#else
8346 /* Don't wait for it to die. I'm not really sure it matters whether
8347 we do or not. For the existing stubs, kill is a noop. */
8348 res = 0;
8349#endif
8350 }
8351
8352 if (res != 0)
8353 error (_("Can't kill process"));
8354
82f73884
PA
8355 target_mourn_inferior ();
8356}
8357
c906108c 8358static void
20f796c9 8359remote_mourn (struct target_ops *target)
c906108c
SS
8360{
8361 unpush_target (target);
ce5ce7ed 8362
8a2492ee
PA
8363 /* remote_close takes care of doing most of the clean up. */
8364 generic_mourn_inferior ();
c906108c
SS
8365}
8366
2d717e4f 8367static void
20f796c9 8368extended_remote_mourn (struct target_ops *target)
2d717e4f
DJ
8369{
8370 struct remote_state *rs = get_remote_state ();
c906108c 8371
e24a49d8
PA
8372 /* In case we got here due to an error, but we're going to stay
8373 connected. */
8374 rs->waiting_for_stop_reply = 0;
8375
dc1981d7
PA
8376 /* If the current general thread belonged to the process we just
8377 detached from or has exited, the remote side current general
8378 thread becomes undefined. Considering a case like this:
8379
8380 - We just got here due to a detach.
8381 - The process that we're detaching from happens to immediately
8382 report a global breakpoint being hit in non-stop mode, in the
8383 same thread we had selected before.
8384 - GDB attaches to this process again.
8385 - This event happens to be the next event we handle.
8386
8387 GDB would consider that the current general thread didn't need to
8388 be set on the stub side (with Hg), since for all it knew,
8389 GENERAL_THREAD hadn't changed.
8390
8391 Notice that although in all-stop mode, the remote server always
8392 sets the current thread to the thread reporting the stop event,
8393 that doesn't happen in non-stop mode; in non-stop, the stub *must
8394 not* change the current thread when reporting a breakpoint hit,
8395 due to the decoupling of event reporting and event handling.
8396
8397 To keep things simple, we always invalidate our notion of the
8398 current thread. */
47f8a51d 8399 record_currthread (rs, minus_one_ptid);
dc1981d7 8400
2d717e4f
DJ
8401 /* Unlike "target remote", we do not want to unpush the target; then
8402 the next time the user says "run", we won't be connected. */
8403
48aa3c27
PA
8404 /* Call common code to mark the inferior as not running. */
8405 generic_mourn_inferior ();
8406
d729566a 8407 if (!have_inferiors ())
2d717e4f 8408 {
82f73884
PA
8409 if (!remote_multi_process_p (rs))
8410 {
8411 /* Check whether the target is running now - some remote stubs
8412 automatically restart after kill. */
8413 putpkt ("?");
8414 getpkt (&rs->buf, &rs->buf_size, 0);
8415
8416 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8417 {
3e43a32a
MS
8418 /* Assume that the target has been restarted. Set
8419 inferior_ptid so that bits of core GDB realizes
8420 there's something here, e.g., so that the user can
8421 say "kill" again. */
82f73884
PA
8422 inferior_ptid = magic_null_ptid;
8423 }
82f73884 8424 }
2d717e4f
DJ
8425 }
8426}
c906108c 8427
03583c20 8428static int
2bfc0540 8429extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 8430{
4082afcc 8431 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
8432}
8433
8434static void
8435extended_remote_disable_randomization (int val)
8436{
8437 struct remote_state *rs = get_remote_state ();
8438 char *reply;
8439
bba74b36
YQ
8440 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8441 val);
03583c20
UW
8442 putpkt (rs->buf);
8443 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8444 if (*reply == '\0')
8445 error (_("Target does not support QDisableRandomization."));
8446 if (strcmp (reply, "OK") != 0)
8447 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8448}
8449
2d717e4f
DJ
8450static int
8451extended_remote_run (char *args)
8452{
8453 struct remote_state *rs = get_remote_state ();
2d717e4f 8454 int len;
c906108c 8455
2d717e4f
DJ
8456 /* If the user has disabled vRun support, or we have detected that
8457 support is not available, do not try it. */
4082afcc 8458 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 8459 return -1;
424163ea 8460
2d717e4f
DJ
8461 strcpy (rs->buf, "vRun;");
8462 len = strlen (rs->buf);
c906108c 8463
2d717e4f
DJ
8464 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8465 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
8466 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8467 strlen (remote_exec_file));
2d717e4f 8468
d1a41061 8469 gdb_assert (args != NULL);
2d717e4f
DJ
8470 if (*args)
8471 {
8472 struct cleanup *back_to;
8473 int i;
8474 char **argv;
8475
d1a41061 8476 argv = gdb_buildargv (args);
6e366df1 8477 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
8478 for (i = 0; argv[i] != NULL; i++)
8479 {
8480 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8481 error (_("Argument list too long for run packet"));
8482 rs->buf[len++] = ';';
9f1b45b0
TT
8483 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8484 strlen (argv[i]));
2d717e4f
DJ
8485 }
8486 do_cleanups (back_to);
8487 }
8488
8489 rs->buf[len++] = '\0';
8490
8491 putpkt (rs->buf);
8492 getpkt (&rs->buf, &rs->buf_size, 0);
8493
4082afcc 8494 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 8495 {
4082afcc 8496 case PACKET_OK:
3405876a 8497 /* We have a wait response. All is well. */
2d717e4f 8498 return 0;
4082afcc
PA
8499 case PACKET_UNKNOWN:
8500 return -1;
8501 case PACKET_ERROR:
2d717e4f
DJ
8502 if (remote_exec_file[0] == '\0')
8503 error (_("Running the default executable on the remote target failed; "
8504 "try \"set remote exec-file\"?"));
8505 else
8506 error (_("Running \"%s\" on the remote target failed"),
8507 remote_exec_file);
4082afcc
PA
8508 default:
8509 gdb_assert_not_reached (_("bad switch"));
2d717e4f 8510 }
c906108c
SS
8511}
8512
2d717e4f
DJ
8513/* In the extended protocol we want to be able to do things like
8514 "run" and have them basically work as expected. So we need
8515 a special create_inferior function. We support changing the
8516 executable file and the command line arguments, but not the
8517 environment. */
8518
43ff13b4 8519static void
77a19445
TT
8520extended_remote_create_inferior (struct target_ops *ops,
8521 char *exec_file, char *args,
8522 char **env, int from_tty)
43ff13b4 8523{
3405876a
PA
8524 int run_worked;
8525 char *stop_reply;
8526 struct remote_state *rs = get_remote_state ();
8527
43ff13b4 8528 /* If running asynchronously, register the target file descriptor
23860348 8529 with the event loop. */
75c99385 8530 if (target_can_async_p ())
6a3753b3 8531 target_async (1);
43ff13b4 8532
03583c20 8533 /* Disable address space randomization if requested (and supported). */
2bfc0540 8534 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
8535 extended_remote_disable_randomization (disable_randomization);
8536
43ff13b4 8537 /* Now restart the remote server. */
3405876a
PA
8538 run_worked = extended_remote_run (args) != -1;
8539 if (!run_worked)
2d717e4f
DJ
8540 {
8541 /* vRun was not supported. Fail if we need it to do what the
8542 user requested. */
8543 if (remote_exec_file[0])
8544 error (_("Remote target does not support \"set remote exec-file\""));
8545 if (args[0])
8546 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 8547
2d717e4f
DJ
8548 /* Fall back to "R". */
8549 extended_remote_restart ();
8550 }
424163ea 8551
6c95b8df
PA
8552 if (!have_inferiors ())
8553 {
8554 /* Clean up from the last time we ran, before we mark the target
8555 running again. This will mark breakpoints uninserted, and
8556 get_offsets may insert breakpoints. */
8557 init_thread_list ();
8558 init_wait_for_inferior ();
8559 }
45280a52 8560
3405876a
PA
8561 /* vRun's success return is a stop reply. */
8562 stop_reply = run_worked ? rs->buf : NULL;
8563 add_current_inferior_and_thread (stop_reply);
c0a2216e 8564
2d717e4f
DJ
8565 /* Get updated offsets, if the stub uses qOffsets. */
8566 get_offsets ();
2d717e4f 8567}
c906108c 8568\f
c5aa993b 8569
b775012e
LM
8570/* Given a location's target info BP_TGT and the packet buffer BUF, output
8571 the list of conditions (in agent expression bytecode format), if any, the
8572 target needs to evaluate. The output is placed into the packet buffer
bba74b36 8573 started from BUF and ended at BUF_END. */
b775012e
LM
8574
8575static int
8576remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
8577 struct bp_target_info *bp_tgt, char *buf,
8578 char *buf_end)
b775012e
LM
8579{
8580 struct agent_expr *aexpr = NULL;
8581 int i, ix;
8582 char *pkt;
8583 char *buf_start = buf;
8584
8585 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8586 return 0;
8587
8588 buf += strlen (buf);
bba74b36 8589 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
8590 buf++;
8591
8592 /* Send conditions to the target and free the vector. */
8593 for (ix = 0;
8594 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8595 ix++)
8596 {
bba74b36 8597 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
8598 buf += strlen (buf);
8599 for (i = 0; i < aexpr->len; ++i)
8600 buf = pack_hex_byte (buf, aexpr->buf[i]);
8601 *buf = '\0';
8602 }
b775012e
LM
8603 return 0;
8604}
8605
d3ce09f5
SS
8606static void
8607remote_add_target_side_commands (struct gdbarch *gdbarch,
8608 struct bp_target_info *bp_tgt, char *buf)
8609{
8610 struct agent_expr *aexpr = NULL;
8611 int i, ix;
8612
8613 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8614 return;
8615
8616 buf += strlen (buf);
8617
8618 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8619 buf += strlen (buf);
8620
8621 /* Concatenate all the agent expressions that are commands into the
8622 cmds parameter. */
8623 for (ix = 0;
8624 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8625 ix++)
8626 {
8627 sprintf (buf, "X%x,", aexpr->len);
8628 buf += strlen (buf);
8629 for (i = 0; i < aexpr->len; ++i)
8630 buf = pack_hex_byte (buf, aexpr->buf[i]);
8631 *buf = '\0';
8632 }
d3ce09f5
SS
8633}
8634
8181d85f
DJ
8635/* Insert a breakpoint. On targets that have software breakpoint
8636 support, we ask the remote target to do the work; on targets
8637 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
8638
8639static int
3db08215
MM
8640remote_insert_breakpoint (struct target_ops *ops,
8641 struct gdbarch *gdbarch,
a6d9a66e 8642 struct bp_target_info *bp_tgt)
c906108c 8643{
d471ea57
AC
8644 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8645 If it succeeds, then set the support to PACKET_ENABLE. If it
8646 fails, and the user has explicitly requested the Z support then
23860348 8647 report an error, otherwise, mark it disabled and go on. */
802188a7 8648
4082afcc 8649 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 8650 {
0d5ed153 8651 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 8652 struct remote_state *rs;
bba74b36 8653 char *p, *endbuf;
7c0f6dcc 8654 int bpsize;
b775012e 8655 struct condition_list *cond = NULL;
4fff2411 8656
28439a30
PA
8657 /* Make sure the remote is pointing at the right process, if
8658 necessary. */
8659 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8660 set_general_process ();
8661
a1dcb23a 8662 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
8663
8664 rs = get_remote_state ();
8665 p = rs->buf;
bba74b36 8666 endbuf = rs->buf + get_remote_packet_size ();
802188a7 8667
96baa820
JM
8668 *(p++) = 'Z';
8669 *(p++) = '0';
8670 *(p++) = ',';
7c0f6dcc 8671 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 8672 p += hexnumstr (p, addr);
bba74b36 8673 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 8674
efcc2da7 8675 if (remote_supports_cond_breakpoints (ops))
bba74b36 8676 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8677
78eff0ec 8678 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
8679 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8680
6d820c5c
DJ
8681 putpkt (rs->buf);
8682 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8683
6d820c5c 8684 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 8685 {
d471ea57
AC
8686 case PACKET_ERROR:
8687 return -1;
8688 case PACKET_OK:
7c0f6dcc
JL
8689 bp_tgt->placed_address = addr;
8690 bp_tgt->placed_size = bpsize;
d471ea57
AC
8691 return 0;
8692 case PACKET_UNKNOWN:
8693 break;
96baa820
JM
8694 }
8695 }
c906108c 8696
0000e5cc
PA
8697 /* If this breakpoint has target-side commands but this stub doesn't
8698 support Z0 packets, throw error. */
8699 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8700 throw_error (NOT_SUPPORTED_ERROR, _("\
8701Target doesn't support breakpoints that have target side commands."));
8702
3db08215 8703 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8704}
8705
8706static int
3db08215
MM
8707remote_remove_breakpoint (struct target_ops *ops,
8708 struct gdbarch *gdbarch,
a6d9a66e 8709 struct bp_target_info *bp_tgt)
c906108c 8710{
8181d85f 8711 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 8712 struct remote_state *rs = get_remote_state ();
96baa820 8713
4082afcc 8714 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 8715 {
6d820c5c 8716 char *p = rs->buf;
bba74b36 8717 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 8718
28439a30
PA
8719 /* Make sure the remote is pointing at the right process, if
8720 necessary. */
8721 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8722 set_general_process ();
8723
96baa820
JM
8724 *(p++) = 'z';
8725 *(p++) = '0';
8726 *(p++) = ',';
8727
8181d85f
DJ
8728 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8729 p += hexnumstr (p, addr);
bba74b36 8730 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 8731
6d820c5c
DJ
8732 putpkt (rs->buf);
8733 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8734
6d820c5c 8735 return (rs->buf[0] == 'E');
96baa820
JM
8736 }
8737
3db08215 8738 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8739}
8740
f486487f 8741static enum Z_packet_type
d471ea57
AC
8742watchpoint_to_Z_packet (int type)
8743{
8744 switch (type)
8745 {
8746 case hw_write:
bb858e6a 8747 return Z_PACKET_WRITE_WP;
d471ea57
AC
8748 break;
8749 case hw_read:
bb858e6a 8750 return Z_PACKET_READ_WP;
d471ea57
AC
8751 break;
8752 case hw_access:
bb858e6a 8753 return Z_PACKET_ACCESS_WP;
d471ea57
AC
8754 break;
8755 default:
8e65ff28 8756 internal_error (__FILE__, __LINE__,
e2e0b3e5 8757 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
8758 }
8759}
8760
3c3bea1c 8761static int
f486487f
SM
8762remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
8763 enum target_hw_bp_type type, struct expression *cond)
96baa820 8764{
d01949b6 8765 struct remote_state *rs = get_remote_state ();
bba74b36 8766 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8767 char *p;
d471ea57 8768 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 8769
4082afcc 8770 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 8771 return 1;
802188a7 8772
28439a30
PA
8773 /* Make sure the remote is pointing at the right process, if
8774 necessary. */
8775 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8776 set_general_process ();
8777
bba74b36 8778 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 8779 p = strchr (rs->buf, '\0');
96baa820
JM
8780 addr = remote_address_masked (addr);
8781 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8782 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 8783
6d820c5c
DJ
8784 putpkt (rs->buf);
8785 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8786
6d820c5c 8787 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8788 {
8789 case PACKET_ERROR:
d471ea57 8790 return -1;
85d721b8
PA
8791 case PACKET_UNKNOWN:
8792 return 1;
d471ea57
AC
8793 case PACKET_OK:
8794 return 0;
8795 }
8e65ff28 8796 internal_error (__FILE__, __LINE__,
e2e0b3e5 8797 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
8798}
8799
283002cf
MR
8800static int
8801remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8802 CORE_ADDR start, int length)
8803{
8804 CORE_ADDR diff = remote_address_masked (addr - start);
8805
8806 return diff < length;
8807}
8808
d471ea57 8809
3c3bea1c 8810static int
f486487f
SM
8811remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
8812 enum target_hw_bp_type type, struct expression *cond)
96baa820 8813{
d01949b6 8814 struct remote_state *rs = get_remote_state ();
bba74b36 8815 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8816 char *p;
d471ea57
AC
8817 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8818
4082afcc 8819 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 8820 return -1;
802188a7 8821
28439a30
PA
8822 /* Make sure the remote is pointing at the right process, if
8823 necessary. */
8824 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8825 set_general_process ();
8826
bba74b36 8827 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 8828 p = strchr (rs->buf, '\0');
96baa820
JM
8829 addr = remote_address_masked (addr);
8830 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8831 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
8832 putpkt (rs->buf);
8833 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8834
6d820c5c 8835 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8836 {
8837 case PACKET_ERROR:
8838 case PACKET_UNKNOWN:
8839 return -1;
8840 case PACKET_OK:
8841 return 0;
8842 }
8e65ff28 8843 internal_error (__FILE__, __LINE__,
e2e0b3e5 8844 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
8845}
8846
3c3bea1c 8847
501eef12 8848int remote_hw_watchpoint_limit = -1;
480a3f21 8849int remote_hw_watchpoint_length_limit = -1;
501eef12 8850int remote_hw_breakpoint_limit = -1;
d471ea57 8851
480a3f21 8852static int
31568a15
TT
8853remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8854 CORE_ADDR addr, int len)
480a3f21
PW
8855{
8856 if (remote_hw_watchpoint_length_limit == 0)
8857 return 0;
8858 else if (remote_hw_watchpoint_length_limit < 0)
8859 return 1;
8860 else if (len <= remote_hw_watchpoint_length_limit)
8861 return 1;
8862 else
8863 return 0;
8864}
8865
b9362cc7 8866static int
5461485a 8867remote_check_watch_resources (struct target_ops *self,
f486487f 8868 enum bptype type, int cnt, int ot)
96baa820 8869{
3c3bea1c
GS
8870 if (type == bp_hardware_breakpoint)
8871 {
8872 if (remote_hw_breakpoint_limit == 0)
8873 return 0;
501eef12
AC
8874 else if (remote_hw_breakpoint_limit < 0)
8875 return 1;
3c3bea1c
GS
8876 else if (cnt <= remote_hw_breakpoint_limit)
8877 return 1;
8878 }
8879 else
8880 {
8881 if (remote_hw_watchpoint_limit == 0)
8882 return 0;
501eef12
AC
8883 else if (remote_hw_watchpoint_limit < 0)
8884 return 1;
3c3bea1c
GS
8885 else if (ot)
8886 return -1;
8887 else if (cnt <= remote_hw_watchpoint_limit)
8888 return 1;
8889 }
8890 return -1;
8891}
8892
f7e6eed5
PA
8893/* The to_stopped_by_sw_breakpoint method of target remote. */
8894
8895static int
8896remote_stopped_by_sw_breakpoint (struct target_ops *ops)
8897{
8898 struct remote_state *rs = get_remote_state ();
8899
8900 return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
8901}
8902
8903/* The to_supports_stopped_by_sw_breakpoint method of target
8904 remote. */
8905
8906static int
8907remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
8908{
8909 struct remote_state *rs = get_remote_state ();
8910
8911 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
8912}
8913
8914/* The to_stopped_by_hw_breakpoint method of target remote. */
8915
8916static int
8917remote_stopped_by_hw_breakpoint (struct target_ops *ops)
8918{
8919 struct remote_state *rs = get_remote_state ();
8920
8921 return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
8922}
8923
8924/* The to_supports_stopped_by_hw_breakpoint method of target
8925 remote. */
8926
8927static int
8928remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
8929{
8930 struct remote_state *rs = get_remote_state ();
8931
8932 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
8933}
8934
b9362cc7 8935static int
6a109b6b 8936remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 8937{
ee154bee
TT
8938 struct remote_state *rs = get_remote_state ();
8939
f7e6eed5 8940 return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
3c3bea1c
GS
8941}
8942
4aa7a7f5
JJ
8943static int
8944remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 8945{
ee154bee 8946 struct remote_state *rs = get_remote_state ();
4aa7a7f5 8947 int rc = 0;
a744cf53 8948
6a109b6b 8949 if (remote_stopped_by_watchpoint (target))
4aa7a7f5 8950 {
ee154bee 8951 *addr_p = rs->remote_watch_data_address;
4aa7a7f5
JJ
8952 rc = 1;
8953 }
8954
8955 return rc;
3c3bea1c
GS
8956}
8957
8958
8959static int
23a26771 8960remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 8961 struct bp_target_info *bp_tgt)
3c3bea1c 8962{
0d5ed153 8963 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 8964 struct remote_state *rs;
bba74b36 8965 char *p, *endbuf;
dd61ec5c 8966 char *message;
0d5ed153 8967 int bpsize;
802188a7 8968
c8189ed1 8969 /* The length field should be set to the size of a breakpoint
8181d85f 8970 instruction, even though we aren't inserting one ourselves. */
c8189ed1 8971
0d5ed153 8972 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 8973
4082afcc 8974 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 8975 return -1;
2bc416ba 8976
28439a30
PA
8977 /* Make sure the remote is pointing at the right process, if
8978 necessary. */
8979 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8980 set_general_process ();
8981
4fff2411
JZ
8982 rs = get_remote_state ();
8983 p = rs->buf;
bba74b36 8984 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 8985
96baa820
JM
8986 *(p++) = 'Z';
8987 *(p++) = '1';
8988 *(p++) = ',';
802188a7 8989
0d5ed153 8990 addr = remote_address_masked (addr);
96baa820 8991 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 8992 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 8993
efcc2da7 8994 if (remote_supports_cond_breakpoints (self))
bba74b36 8995 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8996
78eff0ec 8997 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
8998 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8999
6d820c5c
DJ
9000 putpkt (rs->buf);
9001 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9002
6d820c5c 9003 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9004 {
9005 case PACKET_ERROR:
dd61ec5c
MW
9006 if (rs->buf[1] == '.')
9007 {
9008 message = strchr (rs->buf + 2, '.');
9009 if (message)
0316657e 9010 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
9011 }
9012 return -1;
d471ea57
AC
9013 case PACKET_UNKNOWN:
9014 return -1;
9015 case PACKET_OK:
0d5ed153
MR
9016 bp_tgt->placed_address = addr;
9017 bp_tgt->placed_size = bpsize;
d471ea57
AC
9018 return 0;
9019 }
8e65ff28 9020 internal_error (__FILE__, __LINE__,
e2e0b3e5 9021 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
9022}
9023
d471ea57 9024
802188a7 9025static int
a64dc96c 9026remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9027 struct bp_target_info *bp_tgt)
96baa820 9028{
8181d85f 9029 CORE_ADDR addr;
d01949b6 9030 struct remote_state *rs = get_remote_state ();
6d820c5c 9031 char *p = rs->buf;
bba74b36 9032 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 9033
4082afcc 9034 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9035 return -1;
802188a7 9036
28439a30
PA
9037 /* Make sure the remote is pointing at the right process, if
9038 necessary. */
9039 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9040 set_general_process ();
9041
96baa820
JM
9042 *(p++) = 'z';
9043 *(p++) = '1';
9044 *(p++) = ',';
802188a7 9045
8181d85f 9046 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 9047 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9048 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 9049
6d820c5c
DJ
9050 putpkt (rs->buf);
9051 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 9052
6d820c5c 9053 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9054 {
9055 case PACKET_ERROR:
9056 case PACKET_UNKNOWN:
9057 return -1;
9058 case PACKET_OK:
9059 return 0;
9060 }
8e65ff28 9061 internal_error (__FILE__, __LINE__,
e2e0b3e5 9062 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 9063}
96baa820 9064
4a5e7a5b
PA
9065/* Verify memory using the "qCRC:" request. */
9066
9067static int
9068remote_verify_memory (struct target_ops *ops,
9069 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9070{
9071 struct remote_state *rs = get_remote_state ();
9072 unsigned long host_crc, target_crc;
9073 char *tmp;
9074
936d2992
PA
9075 /* It doesn't make sense to use qCRC if the remote target is
9076 connected but not running. */
9077 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9078 {
9079 enum packet_result result;
28439a30 9080
936d2992
PA
9081 /* Make sure the remote is pointing at the right process. */
9082 set_general_process ();
4a5e7a5b 9083
936d2992
PA
9084 /* FIXME: assumes lma can fit into long. */
9085 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9086 (long) lma, (long) size);
9087 putpkt (rs->buf);
4a5e7a5b 9088
936d2992
PA
9089 /* Be clever; compute the host_crc before waiting for target
9090 reply. */
9091 host_crc = xcrc32 (data, size, 0xffffffff);
9092
9093 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 9094
936d2992
PA
9095 result = packet_ok (rs->buf,
9096 &remote_protocol_packets[PACKET_qCRC]);
9097 if (result == PACKET_ERROR)
9098 return -1;
9099 else if (result == PACKET_OK)
9100 {
9101 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9102 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 9103
936d2992
PA
9104 return (host_crc == target_crc);
9105 }
9106 }
4a5e7a5b 9107
936d2992 9108 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
9109}
9110
c906108c
SS
9111/* compare-sections command
9112
9113 With no arguments, compares each loadable section in the exec bfd
9114 with the same memory range on the target, and reports mismatches.
4a5e7a5b 9115 Useful for verifying the image on the target against the exec file. */
e514a9d6 9116
c906108c 9117static void
fba45db2 9118compare_sections_command (char *args, int from_tty)
c906108c
SS
9119{
9120 asection *s;
c906108c 9121 struct cleanup *old_chain;
948f8e3d 9122 gdb_byte *sectdata;
ce359b09 9123 const char *sectname;
c906108c
SS
9124 bfd_size_type size;
9125 bfd_vma lma;
9126 int matched = 0;
9127 int mismatched = 0;
4a5e7a5b 9128 int res;
95cf3b38 9129 int read_only = 0;
c906108c
SS
9130
9131 if (!exec_bfd)
8a3fe4f8 9132 error (_("command cannot be used without an exec file"));
c906108c 9133
28439a30
PA
9134 /* Make sure the remote is pointing at the right process. */
9135 set_general_process ();
9136
95cf3b38
DT
9137 if (args != NULL && strcmp (args, "-r") == 0)
9138 {
9139 read_only = 1;
9140 args = NULL;
9141 }
9142
c5aa993b 9143 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
9144 {
9145 if (!(s->flags & SEC_LOAD))
0df8b418 9146 continue; /* Skip non-loadable section. */
c906108c 9147
95cf3b38
DT
9148 if (read_only && (s->flags & SEC_READONLY) == 0)
9149 continue; /* Skip writeable sections */
9150
2c500098 9151 size = bfd_get_section_size (s);
c906108c 9152 if (size == 0)
0df8b418 9153 continue; /* Skip zero-length section. */
c906108c 9154
ce359b09 9155 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 9156 if (args && strcmp (args, sectname) != 0)
0df8b418 9157 continue; /* Not the section selected by user. */
c906108c 9158
0df8b418 9159 matched = 1; /* Do this section. */
c906108c 9160 lma = s->lma;
c906108c 9161
c906108c 9162 sectdata = xmalloc (size);
b8c9b27d 9163 old_chain = make_cleanup (xfree, sectdata);
c906108c 9164 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 9165
4a5e7a5b
PA
9166 res = target_verify_memory (sectdata, lma, size);
9167
9168 if (res == -1)
5af949e3 9169 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
9170 paddress (target_gdbarch (), lma),
9171 paddress (target_gdbarch (), lma + size));
c906108c 9172
5af949e3 9173 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
9174 paddress (target_gdbarch (), lma),
9175 paddress (target_gdbarch (), lma + size));
4a5e7a5b 9176 if (res)
c906108c
SS
9177 printf_filtered ("matched.\n");
9178 else
c5aa993b
JM
9179 {
9180 printf_filtered ("MIS-MATCHED!\n");
9181 mismatched++;
9182 }
c906108c
SS
9183
9184 do_cleanups (old_chain);
9185 }
9186 if (mismatched > 0)
936d2992 9187 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 9188the loaded file\n"));
c906108c 9189 if (args && !matched)
a3f17187 9190 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
9191}
9192
0e7f50da
UW
9193/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9194 into remote target. The number of bytes written to the remote
9195 target is returned, or -1 for error. */
9196
9b409511 9197static enum target_xfer_status
0e7f50da
UW
9198remote_write_qxfer (struct target_ops *ops, const char *object_name,
9199 const char *annex, const gdb_byte *writebuf,
9b409511 9200 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
9201 struct packet_config *packet)
9202{
9203 int i, buf_len;
9204 ULONGEST n;
0e7f50da
UW
9205 struct remote_state *rs = get_remote_state ();
9206 int max_size = get_memory_write_packet_size ();
9207
9208 if (packet->support == PACKET_DISABLE)
2ed4b548 9209 return TARGET_XFER_E_IO;
0e7f50da
UW
9210
9211 /* Insert header. */
9212 i = snprintf (rs->buf, max_size,
9213 "qXfer:%s:write:%s:%s:",
9214 object_name, annex ? annex : "",
9215 phex_nz (offset, sizeof offset));
9216 max_size -= (i + 1);
9217
9218 /* Escape as much data as fits into rs->buf. */
9219 buf_len = remote_escape_output
124e13d9 9220 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
9221
9222 if (putpkt_binary (rs->buf, i + buf_len) < 0
9223 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9224 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9225 return TARGET_XFER_E_IO;
0e7f50da
UW
9226
9227 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
9228
9229 *xfered_len = n;
9230 return TARGET_XFER_OK;
0e7f50da
UW
9231}
9232
0876f84a
DJ
9233/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9234 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9235 number of bytes read is returned, or 0 for EOF, or -1 for error.
9236 The number of bytes read may be less than LEN without indicating an
9237 EOF. PACKET is checked and updated to indicate whether the remote
9238 target supports this object. */
9239
9b409511 9240static enum target_xfer_status
0876f84a
DJ
9241remote_read_qxfer (struct target_ops *ops, const char *object_name,
9242 const char *annex,
9243 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 9244 ULONGEST *xfered_len,
0876f84a
DJ
9245 struct packet_config *packet)
9246{
0876f84a 9247 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
9248 LONGEST i, n, packet_len;
9249
9250 if (packet->support == PACKET_DISABLE)
2ed4b548 9251 return TARGET_XFER_E_IO;
0876f84a
DJ
9252
9253 /* Check whether we've cached an end-of-object packet that matches
9254 this request. */
8e88304f 9255 if (rs->finished_object)
0876f84a 9256 {
8e88304f
TT
9257 if (strcmp (object_name, rs->finished_object) == 0
9258 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9259 && offset == rs->finished_offset)
9b409511
YQ
9260 return TARGET_XFER_EOF;
9261
0876f84a
DJ
9262
9263 /* Otherwise, we're now reading something different. Discard
9264 the cache. */
8e88304f
TT
9265 xfree (rs->finished_object);
9266 xfree (rs->finished_annex);
9267 rs->finished_object = NULL;
9268 rs->finished_annex = NULL;
0876f84a
DJ
9269 }
9270
9271 /* Request only enough to fit in a single packet. The actual data
9272 may not, since we don't know how much of it will need to be escaped;
9273 the target is free to respond with slightly less data. We subtract
9274 five to account for the response type and the protocol frame. */
9275 n = min (get_remote_packet_size () - 5, len);
9276 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9277 object_name, annex ? annex : "",
9278 phex_nz (offset, sizeof offset),
9279 phex_nz (n, sizeof n));
9280 i = putpkt (rs->buf);
9281 if (i < 0)
2ed4b548 9282 return TARGET_XFER_E_IO;
0876f84a
DJ
9283
9284 rs->buf[0] = '\0';
9285 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9286 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9287 return TARGET_XFER_E_IO;
0876f84a
DJ
9288
9289 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9290 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9291
9292 /* 'm' means there is (or at least might be) more data after this
9293 batch. That does not make sense unless there's at least one byte
9294 of data in this reply. */
9295 if (rs->buf[0] == 'm' && packet_len == 1)
9296 error (_("Remote qXfer reply contained no data."));
9297
9298 /* Got some data. */
bc20a4af
PA
9299 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9300 packet_len - 1, readbuf, n);
0876f84a
DJ
9301
9302 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
9303 or possibly empty. If we have the final block of a non-empty
9304 object, record this fact to bypass a subsequent partial read. */
9305 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 9306 {
8e88304f
TT
9307 rs->finished_object = xstrdup (object_name);
9308 rs->finished_annex = xstrdup (annex ? annex : "");
9309 rs->finished_offset = offset + i;
0876f84a
DJ
9310 }
9311
9b409511
YQ
9312 if (i == 0)
9313 return TARGET_XFER_EOF;
9314 else
9315 {
9316 *xfered_len = i;
9317 return TARGET_XFER_OK;
9318 }
0876f84a
DJ
9319}
9320
9b409511 9321static enum target_xfer_status
4b8a223f 9322remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 9323 const char *annex, gdb_byte *readbuf,
9b409511
YQ
9324 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9325 ULONGEST *xfered_len)
c906108c 9326{
82f73884 9327 struct remote_state *rs;
c906108c 9328 int i;
6d820c5c 9329 char *p2;
1e3ff5ad 9330 char query_type;
124e13d9 9331 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 9332
e6e4e701 9333 set_remote_traceframe ();
82f73884
PA
9334 set_general_thread (inferior_ptid);
9335
9336 rs = get_remote_state ();
9337
b2182ed2 9338 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
9339 if (object == TARGET_OBJECT_MEMORY)
9340 {
2d717e4f
DJ
9341 /* If the remote target is connected but not running, we should
9342 pass this request down to a lower stratum (e.g. the executable
9343 file). */
9344 if (!target_has_execution)
9b409511 9345 return TARGET_XFER_EOF;
2d717e4f 9346
21e3b9b9 9347 if (writebuf != NULL)
124e13d9
SM
9348 return remote_write_bytes (offset, writebuf, len, unit_size,
9349 xfered_len);
21e3b9b9 9350 else
124e13d9
SM
9351 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9352 xfered_len);
21e3b9b9
DJ
9353 }
9354
0df8b418 9355 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
9356 if (object == TARGET_OBJECT_SPU)
9357 {
9358 if (readbuf)
9359 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
9360 xfered_len, &remote_protocol_packets
9361 [PACKET_qXfer_spu_read]);
0e7f50da
UW
9362 else
9363 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
9364 xfered_len, &remote_protocol_packets
9365 [PACKET_qXfer_spu_write]);
0e7f50da
UW
9366 }
9367
4aa995e1
PA
9368 /* Handle extra signal info using qxfer packets. */
9369 if (object == TARGET_OBJECT_SIGNAL_INFO)
9370 {
9371 if (readbuf)
9372 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 9373 xfered_len, &remote_protocol_packets
4aa995e1
PA
9374 [PACKET_qXfer_siginfo_read]);
9375 else
3e43a32a 9376 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 9377 writebuf, offset, len, xfered_len,
4aa995e1
PA
9378 &remote_protocol_packets
9379 [PACKET_qXfer_siginfo_write]);
9380 }
9381
0fb4aa4b
PA
9382 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9383 {
9384 if (readbuf)
3e43a32a 9385 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 9386 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
9387 &remote_protocol_packets
9388 [PACKET_qXfer_statictrace_read]);
9389 else
2ed4b548 9390 return TARGET_XFER_E_IO;
0fb4aa4b
PA
9391 }
9392
a76d924d
DJ
9393 /* Only handle flash writes. */
9394 if (writebuf != NULL)
9395 {
9396 LONGEST xfered;
9397
9398 switch (object)
9399 {
9400 case TARGET_OBJECT_FLASH:
9b409511
YQ
9401 return remote_flash_write (ops, offset, len, xfered_len,
9402 writebuf);
a76d924d
DJ
9403
9404 default:
2ed4b548 9405 return TARGET_XFER_E_IO;
a76d924d
DJ
9406 }
9407 }
4b8a223f 9408
1e3ff5ad
AC
9409 /* Map pre-existing objects onto letters. DO NOT do this for new
9410 objects!!! Instead specify new query packets. */
9411 switch (object)
c906108c 9412 {
1e3ff5ad
AC
9413 case TARGET_OBJECT_AVR:
9414 query_type = 'R';
9415 break;
802188a7
RM
9416
9417 case TARGET_OBJECT_AUXV:
0876f84a
DJ
9418 gdb_assert (annex == NULL);
9419 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 9420 xfered_len,
0876f84a 9421 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 9422
23181151
DJ
9423 case TARGET_OBJECT_AVAILABLE_FEATURES:
9424 return remote_read_qxfer
9b409511 9425 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
9426 &remote_protocol_packets[PACKET_qXfer_features]);
9427
cfa9d6d9
DJ
9428 case TARGET_OBJECT_LIBRARIES:
9429 return remote_read_qxfer
9b409511 9430 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
9431 &remote_protocol_packets[PACKET_qXfer_libraries]);
9432
2268b414
JK
9433 case TARGET_OBJECT_LIBRARIES_SVR4:
9434 return remote_read_qxfer
9b409511 9435 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
9436 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9437
fd79ecee
DJ
9438 case TARGET_OBJECT_MEMORY_MAP:
9439 gdb_assert (annex == NULL);
9440 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 9441 xfered_len,
fd79ecee
DJ
9442 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9443
07e059b5
VP
9444 case TARGET_OBJECT_OSDATA:
9445 /* Should only get here if we're connected. */
5d93a237 9446 gdb_assert (rs->remote_desc);
07e059b5 9447 return remote_read_qxfer
9b409511 9448 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
9449 &remote_protocol_packets[PACKET_qXfer_osdata]);
9450
dc146f7c
VP
9451 case TARGET_OBJECT_THREADS:
9452 gdb_assert (annex == NULL);
9453 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 9454 xfered_len,
dc146f7c
VP
9455 &remote_protocol_packets[PACKET_qXfer_threads]);
9456
b3b9301e
PA
9457 case TARGET_OBJECT_TRACEFRAME_INFO:
9458 gdb_assert (annex == NULL);
9459 return remote_read_qxfer
9b409511 9460 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 9461 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
9462
9463 case TARGET_OBJECT_FDPIC:
9464 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 9465 xfered_len,
78d85199 9466 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
9467
9468 case TARGET_OBJECT_OPENVMS_UIB:
9469 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 9470 xfered_len,
169081d0
TG
9471 &remote_protocol_packets[PACKET_qXfer_uib]);
9472
9accd112
MM
9473 case TARGET_OBJECT_BTRACE:
9474 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 9475 xfered_len,
9accd112
MM
9476 &remote_protocol_packets[PACKET_qXfer_btrace]);
9477
f4abbc16
MM
9478 case TARGET_OBJECT_BTRACE_CONF:
9479 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9480 len, xfered_len,
9481 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9482
c78fa86a
GB
9483 case TARGET_OBJECT_EXEC_FILE:
9484 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9485 len, xfered_len,
9486 &remote_protocol_packets[PACKET_qXfer_exec_file]);
9487
1e3ff5ad 9488 default:
2ed4b548 9489 return TARGET_XFER_E_IO;
c906108c
SS
9490 }
9491
0df8b418 9492 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 9493 large enough let the caller deal with it. */
ea9c271d 9494 if (len < get_remote_packet_size ())
2ed4b548 9495 return TARGET_XFER_E_IO;
ea9c271d 9496 len = get_remote_packet_size ();
1e3ff5ad 9497
23860348 9498 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 9499 if (!rs->remote_desc)
8a3fe4f8 9500 error (_("remote query is only available after target open"));
c906108c 9501
1e3ff5ad 9502 gdb_assert (annex != NULL);
4b8a223f 9503 gdb_assert (readbuf != NULL);
c906108c 9504
6d820c5c 9505 p2 = rs->buf;
c906108c
SS
9506 *p2++ = 'q';
9507 *p2++ = query_type;
9508
23860348
MS
9509 /* We used one buffer char for the remote protocol q command and
9510 another for the query type. As the remote protocol encapsulation
9511 uses 4 chars plus one extra in case we are debugging
9512 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9513 string. */
c906108c 9514 i = 0;
ea9c271d 9515 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 9516 {
1e3ff5ad
AC
9517 /* Bad caller may have sent forbidden characters. */
9518 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9519 *p2++ = annex[i];
c906108c
SS
9520 i++;
9521 }
1e3ff5ad
AC
9522 *p2 = '\0';
9523 gdb_assert (annex[i] == '\0');
c906108c 9524
6d820c5c 9525 i = putpkt (rs->buf);
c5aa993b 9526 if (i < 0)
2ed4b548 9527 return TARGET_XFER_E_IO;
c906108c 9528
6d820c5c
DJ
9529 getpkt (&rs->buf, &rs->buf_size, 0);
9530 strcpy ((char *) readbuf, rs->buf);
c906108c 9531
9b409511
YQ
9532 *xfered_len = strlen ((char *) readbuf);
9533 return TARGET_XFER_OK;
c906108c
SS
9534}
9535
08388c79
DE
9536static int
9537remote_search_memory (struct target_ops* ops,
9538 CORE_ADDR start_addr, ULONGEST search_space_len,
9539 const gdb_byte *pattern, ULONGEST pattern_len,
9540 CORE_ADDR *found_addrp)
9541{
f5656ead 9542 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
9543 struct remote_state *rs = get_remote_state ();
9544 int max_size = get_memory_write_packet_size ();
9545 struct packet_config *packet =
9546 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
9547 /* Number of packet bytes used to encode the pattern;
9548 this could be more than PATTERN_LEN due to escape characters. */
08388c79 9549 int escaped_pattern_len;
0df8b418 9550 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
9551 int used_pattern_len;
9552 int i;
9553 int found;
9554 ULONGEST found_addr;
9555
9556 /* Don't go to the target if we don't have to.
9557 This is done before checking packet->support to avoid the possibility that
9558 a success for this edge case means the facility works in general. */
9559 if (pattern_len > search_space_len)
9560 return 0;
9561 if (pattern_len == 0)
9562 {
9563 *found_addrp = start_addr;
9564 return 1;
9565 }
9566
9567 /* If we already know the packet isn't supported, fall back to the simple
9568 way of searching memory. */
9569
4082afcc 9570 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
9571 {
9572 /* Target doesn't provided special support, fall back and use the
9573 standard support (copy memory and do the search here). */
9574 return simple_search_memory (ops, start_addr, search_space_len,
9575 pattern, pattern_len, found_addrp);
9576 }
9577
28439a30
PA
9578 /* Make sure the remote is pointing at the right process. */
9579 set_general_process ();
9580
08388c79
DE
9581 /* Insert header. */
9582 i = snprintf (rs->buf, max_size,
9583 "qSearch:memory:%s;%s;",
5af949e3 9584 phex_nz (start_addr, addr_size),
08388c79
DE
9585 phex_nz (search_space_len, sizeof (search_space_len)));
9586 max_size -= (i + 1);
9587
9588 /* Escape as much data as fits into rs->buf. */
9589 escaped_pattern_len =
124e13d9 9590 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
9591 &used_pattern_len, max_size);
9592
9593 /* Bail if the pattern is too large. */
9594 if (used_pattern_len != pattern_len)
9b20d036 9595 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
9596
9597 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9598 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9599 || packet_ok (rs->buf, packet) != PACKET_OK)
9600 {
9601 /* The request may not have worked because the command is not
9602 supported. If so, fall back to the simple way. */
9603 if (packet->support == PACKET_DISABLE)
9604 {
9605 return simple_search_memory (ops, start_addr, search_space_len,
9606 pattern, pattern_len, found_addrp);
9607 }
9608 return -1;
9609 }
9610
9611 if (rs->buf[0] == '0')
9612 found = 0;
9613 else if (rs->buf[0] == '1')
9614 {
9615 found = 1;
9616 if (rs->buf[1] != ',')
10e0fa18 9617 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9618 unpack_varlen_hex (rs->buf + 2, &found_addr);
9619 *found_addrp = found_addr;
9620 }
9621 else
10e0fa18 9622 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9623
9624 return found;
9625}
9626
96baa820 9627static void
a30bf1f1 9628remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 9629 struct ui_file *outbuf)
96baa820 9630{
d01949b6 9631 struct remote_state *rs = get_remote_state ();
2e9f7625 9632 char *p = rs->buf;
96baa820 9633
5d93a237 9634 if (!rs->remote_desc)
8a3fe4f8 9635 error (_("remote rcmd is only available after target open"));
96baa820 9636
23860348 9637 /* Send a NULL command across as an empty command. */
7be570e7
JM
9638 if (command == NULL)
9639 command = "";
9640
23860348 9641 /* The query prefix. */
2e9f7625
DJ
9642 strcpy (rs->buf, "qRcmd,");
9643 p = strchr (rs->buf, '\0');
96baa820 9644
3e43a32a
MS
9645 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9646 > get_remote_packet_size ())
8a3fe4f8 9647 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 9648
23860348 9649 /* Encode the actual command. */
a30bf1f1 9650 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 9651
6d820c5c 9652 if (putpkt (rs->buf) < 0)
8a3fe4f8 9653 error (_("Communication problem with target."));
96baa820
JM
9654
9655 /* get/display the response */
9656 while (1)
9657 {
2e9f7625
DJ
9658 char *buf;
9659
00bf0b85 9660 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 9661 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 9662 rs->buf[0] = '\0';
5b37825d
PW
9663 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9664 {
9665 /* Timeout. Continue to (try to) read responses.
9666 This is better than stopping with an error, assuming the stub
9667 is still executing the (long) monitor command.
9668 If needed, the user can interrupt gdb using C-c, obtaining
9669 an effect similar to stop on timeout. */
9670 continue;
9671 }
2e9f7625 9672 buf = rs->buf;
96baa820 9673 if (buf[0] == '\0')
8a3fe4f8 9674 error (_("Target does not support this command."));
96baa820
JM
9675 if (buf[0] == 'O' && buf[1] != 'K')
9676 {
23860348 9677 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
9678 continue;
9679 }
9680 if (strcmp (buf, "OK") == 0)
9681 break;
7be570e7
JM
9682 if (strlen (buf) == 3 && buf[0] == 'E'
9683 && isdigit (buf[1]) && isdigit (buf[2]))
9684 {
8a3fe4f8 9685 error (_("Protocol error with Rcmd"));
7be570e7 9686 }
96baa820
JM
9687 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9688 {
9689 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 9690
96baa820
JM
9691 fputc_unfiltered (c, outbuf);
9692 }
9693 break;
9694 }
9695}
9696
fd79ecee
DJ
9697static VEC(mem_region_s) *
9698remote_memory_map (struct target_ops *ops)
9699{
9700 VEC(mem_region_s) *result = NULL;
9701 char *text = target_read_stralloc (&current_target,
9702 TARGET_OBJECT_MEMORY_MAP, NULL);
9703
9704 if (text)
9705 {
9706 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 9707
fd79ecee
DJ
9708 result = parse_memory_map (text);
9709 do_cleanups (back_to);
9710 }
9711
9712 return result;
9713}
9714
c906108c 9715static void
fba45db2 9716packet_command (char *args, int from_tty)
c906108c 9717{
d01949b6 9718 struct remote_state *rs = get_remote_state ();
c906108c 9719
5d93a237 9720 if (!rs->remote_desc)
8a3fe4f8 9721 error (_("command can only be used with remote target"));
c906108c 9722
c5aa993b 9723 if (!args)
8a3fe4f8 9724 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
9725
9726 puts_filtered ("sending: ");
9727 print_packet (args);
9728 puts_filtered ("\n");
9729 putpkt (args);
9730
6d820c5c 9731 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 9732 puts_filtered ("received: ");
6d820c5c 9733 print_packet (rs->buf);
c906108c
SS
9734 puts_filtered ("\n");
9735}
9736
9737#if 0
23860348 9738/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 9739
a14ed312 9740static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 9741
a14ed312 9742static void threadset_test_cmd (char *cmd, int tty);
c906108c 9743
a14ed312 9744static void threadalive_test (char *cmd, int tty);
c906108c 9745
a14ed312 9746static void threadlist_test_cmd (char *cmd, int tty);
c906108c 9747
23860348 9748int get_and_display_threadinfo (threadref *ref);
c906108c 9749
a14ed312 9750static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 9751
23860348 9752static int thread_display_step (threadref *ref, void *context);
c906108c 9753
a14ed312 9754static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 9755
a14ed312 9756static void init_remote_threadtests (void);
c906108c 9757
23860348 9758#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
9759
9760static void
fba45db2 9761threadset_test_cmd (char *cmd, int tty)
c906108c
SS
9762{
9763 int sample_thread = SAMPLE_THREAD;
9764
a3f17187 9765 printf_filtered (_("Remote threadset test\n"));
79d7f229 9766 set_general_thread (sample_thread);
c906108c
SS
9767}
9768
9769
9770static void
fba45db2 9771threadalive_test (char *cmd, int tty)
c906108c
SS
9772{
9773 int sample_thread = SAMPLE_THREAD;
79d7f229 9774 int pid = ptid_get_pid (inferior_ptid);
ba348170 9775 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 9776
79d7f229 9777 if (remote_thread_alive (ptid))
c906108c
SS
9778 printf_filtered ("PASS: Thread alive test\n");
9779 else
9780 printf_filtered ("FAIL: Thread alive test\n");
9781}
9782
23860348 9783void output_threadid (char *title, threadref *ref);
c906108c
SS
9784
9785void
fba45db2 9786output_threadid (char *title, threadref *ref)
c906108c
SS
9787{
9788 char hexid[20];
9789
23860348 9790 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
9791 hexid[16] = 0;
9792 printf_filtered ("%s %s\n", title, (&hexid[0]));
9793}
9794
9795static void
fba45db2 9796threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
9797{
9798 int startflag = 1;
9799 threadref nextthread;
9800 int done, result_count;
9801 threadref threadlist[3];
9802
9803 printf_filtered ("Remote Threadlist test\n");
9804 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9805 &result_count, &threadlist[0]))
9806 printf_filtered ("FAIL: threadlist test\n");
9807 else
9808 {
9809 threadref *scan = threadlist;
9810 threadref *limit = scan + result_count;
9811
9812 while (scan < limit)
9813 output_threadid (" thread ", scan++);
9814 }
9815}
9816
9817void
fba45db2 9818display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
9819{
9820 output_threadid ("Threadid: ", &info->threadid);
9821 printf_filtered ("Name: %s\n ", info->shortname);
9822 printf_filtered ("State: %s\n", info->display);
9823 printf_filtered ("other: %s\n\n", info->more_display);
9824}
9825
9826int
fba45db2 9827get_and_display_threadinfo (threadref *ref)
c906108c
SS
9828{
9829 int result;
9830 int set;
9831 struct gdb_ext_thread_info threadinfo;
9832
9833 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9834 | TAG_MOREDISPLAY | TAG_DISPLAY;
9835 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9836 display_thread_info (&threadinfo);
9837 return result;
9838}
9839
9840static void
fba45db2 9841threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
9842{
9843 int athread = SAMPLE_THREAD;
9844 threadref thread;
9845 int set;
9846
9847 int_to_threadref (&thread, athread);
9848 printf_filtered ("Remote Threadinfo test\n");
9849 if (!get_and_display_threadinfo (&thread))
9850 printf_filtered ("FAIL cannot get thread info\n");
9851}
9852
9853static int
fba45db2 9854thread_display_step (threadref *ref, void *context)
c906108c
SS
9855{
9856 /* output_threadid(" threadstep ",ref); *//* simple test */
9857 return get_and_display_threadinfo (ref);
9858}
9859
9860static void
fba45db2 9861threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
9862{
9863 printf_filtered ("Remote Threadlist update test\n");
9864 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9865}
9866
9867static void
9868init_remote_threadtests (void)
9869{
3e43a32a
MS
9870 add_com ("tlist", class_obscure, threadlist_test_cmd,
9871 _("Fetch and print the remote list of "
9872 "thread identifiers, one pkt only"));
c906108c 9873 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 9874 _("Fetch and display info about one thread"));
c906108c 9875 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 9876 _("Test setting to a different thread"));
c906108c 9877 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 9878 _("Iterate through updating all remote thread info"));
c906108c 9879 add_com ("talive", class_obscure, threadalive_test,
1bedd215 9880 _(" Remote thread alive test "));
c906108c
SS
9881}
9882
9883#endif /* 0 */
9884
f3fb8c85
MS
9885/* Convert a thread ID to a string. Returns the string in a static
9886 buffer. */
9887
9888static char *
117de6a9 9889remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 9890{
79d7f229 9891 static char buf[64];
82f73884 9892 struct remote_state *rs = get_remote_state ();
f3fb8c85 9893
7cee1e54
PA
9894 if (ptid_equal (ptid, null_ptid))
9895 return normal_pid_to_str (ptid);
9896 else if (ptid_is_pid (ptid))
ecd0ada5
PA
9897 {
9898 /* Printing an inferior target id. */
9899
9900 /* When multi-process extensions are off, there's no way in the
9901 remote protocol to know the remote process id, if there's any
9902 at all. There's one exception --- when we're connected with
9903 target extended-remote, and we manually attached to a process
9904 with "attach PID". We don't record anywhere a flag that
9905 allows us to distinguish that case from the case of
9906 connecting with extended-remote and the stub already being
9907 attached to a process, and reporting yes to qAttached, hence
9908 no smart special casing here. */
9909 if (!remote_multi_process_p (rs))
9910 {
9911 xsnprintf (buf, sizeof buf, "Remote target");
9912 return buf;
9913 }
9914
9915 return normal_pid_to_str (ptid);
82f73884 9916 }
ecd0ada5 9917 else
79d7f229 9918 {
ecd0ada5
PA
9919 if (ptid_equal (magic_null_ptid, ptid))
9920 xsnprintf (buf, sizeof buf, "Thread <main>");
901f9912 9921 else if (rs->extended && remote_multi_process_p (rs))
de0d863e
DB
9922 if (ptid_get_lwp (ptid) == 0)
9923 return normal_pid_to_str (ptid);
9924 else
9925 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
9926 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
9927 else
9928 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 9929 ptid_get_lwp (ptid));
79d7f229
PA
9930 return buf;
9931 }
f3fb8c85
MS
9932}
9933
38691318
KB
9934/* Get the address of the thread local variable in OBJFILE which is
9935 stored at OFFSET within the thread local storage for thread PTID. */
9936
9937static CORE_ADDR
117de6a9
PA
9938remote_get_thread_local_address (struct target_ops *ops,
9939 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 9940{
4082afcc 9941 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
9942 {
9943 struct remote_state *rs = get_remote_state ();
6d820c5c 9944 char *p = rs->buf;
82f73884 9945 char *endp = rs->buf + get_remote_packet_size ();
571dd617 9946 enum packet_result result;
38691318
KB
9947
9948 strcpy (p, "qGetTLSAddr:");
9949 p += strlen (p);
82f73884 9950 p = write_ptid (p, endp, ptid);
38691318
KB
9951 *p++ = ',';
9952 p += hexnumstr (p, offset);
9953 *p++ = ',';
9954 p += hexnumstr (p, lm);
9955 *p++ = '\0';
9956
6d820c5c
DJ
9957 putpkt (rs->buf);
9958 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
9959 result = packet_ok (rs->buf,
9960 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 9961 if (result == PACKET_OK)
38691318
KB
9962 {
9963 ULONGEST result;
9964
6d820c5c 9965 unpack_varlen_hex (rs->buf, &result);
38691318
KB
9966 return result;
9967 }
571dd617 9968 else if (result == PACKET_UNKNOWN)
109c3e39
AC
9969 throw_error (TLS_GENERIC_ERROR,
9970 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 9971 else
109c3e39
AC
9972 throw_error (TLS_GENERIC_ERROR,
9973 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
9974 }
9975 else
109c3e39
AC
9976 throw_error (TLS_GENERIC_ERROR,
9977 _("TLS not supported or disabled on this target"));
38691318
KB
9978 /* Not reached. */
9979 return 0;
9980}
9981
711e434b
PM
9982/* Provide thread local base, i.e. Thread Information Block address.
9983 Returns 1 if ptid is found and thread_local_base is non zero. */
9984
70221824 9985static int
bd7ae0f5 9986remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 9987{
4082afcc 9988 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
9989 {
9990 struct remote_state *rs = get_remote_state ();
9991 char *p = rs->buf;
9992 char *endp = rs->buf + get_remote_packet_size ();
9993 enum packet_result result;
9994
9995 strcpy (p, "qGetTIBAddr:");
9996 p += strlen (p);
9997 p = write_ptid (p, endp, ptid);
9998 *p++ = '\0';
9999
10000 putpkt (rs->buf);
10001 getpkt (&rs->buf, &rs->buf_size, 0);
10002 result = packet_ok (rs->buf,
10003 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10004 if (result == PACKET_OK)
10005 {
10006 ULONGEST result;
10007
10008 unpack_varlen_hex (rs->buf, &result);
10009 if (addr)
10010 *addr = (CORE_ADDR) result;
10011 return 1;
10012 }
10013 else if (result == PACKET_UNKNOWN)
10014 error (_("Remote target doesn't support qGetTIBAddr packet"));
10015 else
10016 error (_("Remote target failed to process qGetTIBAddr request"));
10017 }
10018 else
10019 error (_("qGetTIBAddr not supported or disabled on this target"));
10020 /* Not reached. */
10021 return 0;
10022}
10023
29709017
DJ
10024/* Support for inferring a target description based on the current
10025 architecture and the size of a 'g' packet. While the 'g' packet
10026 can have any size (since optional registers can be left off the
10027 end), some sizes are easily recognizable given knowledge of the
10028 approximate architecture. */
10029
10030struct remote_g_packet_guess
10031{
10032 int bytes;
10033 const struct target_desc *tdesc;
10034};
10035typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10036DEF_VEC_O(remote_g_packet_guess_s);
10037
10038struct remote_g_packet_data
10039{
10040 VEC(remote_g_packet_guess_s) *guesses;
10041};
10042
10043static struct gdbarch_data *remote_g_packet_data_handle;
10044
10045static void *
10046remote_g_packet_data_init (struct obstack *obstack)
10047{
10048 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10049}
10050
10051void
10052register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10053 const struct target_desc *tdesc)
10054{
10055 struct remote_g_packet_data *data
10056 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
10057 struct remote_g_packet_guess new_guess, *guess;
10058 int ix;
10059
10060 gdb_assert (tdesc != NULL);
10061
10062 for (ix = 0;
10063 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10064 ix++)
10065 if (guess->bytes == bytes)
10066 internal_error (__FILE__, __LINE__,
9b20d036 10067 _("Duplicate g packet description added for size %d"),
29709017
DJ
10068 bytes);
10069
10070 new_guess.bytes = bytes;
10071 new_guess.tdesc = tdesc;
10072 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10073}
10074
d962ef82
DJ
10075/* Return 1 if remote_read_description would do anything on this target
10076 and architecture, 0 otherwise. */
10077
10078static int
10079remote_read_description_p (struct target_ops *target)
10080{
10081 struct remote_g_packet_data *data
f5656ead 10082 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
d962ef82
DJ
10083
10084 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10085 return 1;
10086
10087 return 0;
10088}
10089
29709017
DJ
10090static const struct target_desc *
10091remote_read_description (struct target_ops *target)
10092{
10093 struct remote_g_packet_data *data
f5656ead 10094 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
29709017 10095
d962ef82
DJ
10096 /* Do not try this during initial connection, when we do not know
10097 whether there is a running but stopped thread. */
10098 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 10099 return target->beneath->to_read_description (target->beneath);
d962ef82 10100
29709017
DJ
10101 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10102 {
10103 struct remote_g_packet_guess *guess;
10104 int ix;
10105 int bytes = send_g_packet ();
10106
10107 for (ix = 0;
10108 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10109 ix++)
10110 if (guess->bytes == bytes)
10111 return guess->tdesc;
10112
10113 /* We discard the g packet. A minor optimization would be to
10114 hold on to it, and fill the register cache once we have selected
10115 an architecture, but it's too tricky to do safely. */
10116 }
10117
2117c711 10118 return target->beneath->to_read_description (target->beneath);
29709017
DJ
10119}
10120
a6b151f1
DJ
10121/* Remote file transfer support. This is host-initiated I/O, not
10122 target-initiated; for target-initiated, see remote-fileio.c. */
10123
10124/* If *LEFT is at least the length of STRING, copy STRING to
10125 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10126 decrease *LEFT. Otherwise raise an error. */
10127
10128static void
10129remote_buffer_add_string (char **buffer, int *left, char *string)
10130{
10131 int len = strlen (string);
10132
10133 if (len > *left)
10134 error (_("Packet too long for target."));
10135
10136 memcpy (*buffer, string, len);
10137 *buffer += len;
10138 *left -= len;
10139
10140 /* NUL-terminate the buffer as a convenience, if there is
10141 room. */
10142 if (*left)
10143 **buffer = '\0';
10144}
10145
10146/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10147 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10148 decrease *LEFT. Otherwise raise an error. */
10149
10150static void
10151remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10152 int len)
10153{
10154 if (2 * len > *left)
10155 error (_("Packet too long for target."));
10156
10157 bin2hex (bytes, *buffer, len);
10158 *buffer += 2 * len;
10159 *left -= 2 * len;
10160
10161 /* NUL-terminate the buffer as a convenience, if there is
10162 room. */
10163 if (*left)
10164 **buffer = '\0';
10165}
10166
10167/* If *LEFT is large enough, convert VALUE to hex and add it to
10168 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10169 decrease *LEFT. Otherwise raise an error. */
10170
10171static void
10172remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10173{
10174 int len = hexnumlen (value);
10175
10176 if (len > *left)
10177 error (_("Packet too long for target."));
10178
10179 hexnumstr (*buffer, value);
10180 *buffer += len;
10181 *left -= len;
10182
10183 /* NUL-terminate the buffer as a convenience, if there is
10184 room. */
10185 if (*left)
10186 **buffer = '\0';
10187}
10188
10189/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10190 value, *REMOTE_ERRNO to the remote error number or zero if none
10191 was included, and *ATTACHMENT to point to the start of the annex
10192 if any. The length of the packet isn't needed here; there may
10193 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10194
10195 Return 0 if the packet could be parsed, -1 if it could not. If
10196 -1 is returned, the other variables may not be initialized. */
10197
10198static int
10199remote_hostio_parse_result (char *buffer, int *retcode,
10200 int *remote_errno, char **attachment)
10201{
10202 char *p, *p2;
10203
10204 *remote_errno = 0;
10205 *attachment = NULL;
10206
10207 if (buffer[0] != 'F')
10208 return -1;
10209
10210 errno = 0;
10211 *retcode = strtol (&buffer[1], &p, 16);
10212 if (errno != 0 || p == &buffer[1])
10213 return -1;
10214
10215 /* Check for ",errno". */
10216 if (*p == ',')
10217 {
10218 errno = 0;
10219 *remote_errno = strtol (p + 1, &p2, 16);
10220 if (errno != 0 || p + 1 == p2)
10221 return -1;
10222 p = p2;
10223 }
10224
10225 /* Check for ";attachment". If there is no attachment, the
10226 packet should end here. */
10227 if (*p == ';')
10228 {
10229 *attachment = p + 1;
10230 return 0;
10231 }
10232 else if (*p == '\0')
10233 return 0;
10234 else
10235 return -1;
10236}
10237
10238/* Send a prepared I/O packet to the target and read its response.
10239 The prepared packet is in the global RS->BUF before this function
10240 is called, and the answer is there when we return.
10241
10242 COMMAND_BYTES is the length of the request to send, which may include
10243 binary data. WHICH_PACKET is the packet configuration to check
10244 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10245 is set to the error number and -1 is returned. Otherwise the value
10246 returned by the function is returned.
10247
10248 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10249 attachment is expected; an error will be reported if there's a
10250 mismatch. If one is found, *ATTACHMENT will be set to point into
10251 the packet buffer and *ATTACHMENT_LEN will be set to the
10252 attachment's length. */
10253
10254static int
10255remote_hostio_send_command (int command_bytes, int which_packet,
10256 int *remote_errno, char **attachment,
10257 int *attachment_len)
10258{
10259 struct remote_state *rs = get_remote_state ();
10260 int ret, bytes_read;
10261 char *attachment_tmp;
10262
5d93a237 10263 if (!rs->remote_desc
4082afcc 10264 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
10265 {
10266 *remote_errno = FILEIO_ENOSYS;
10267 return -1;
10268 }
10269
10270 putpkt_binary (rs->buf, command_bytes);
10271 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10272
10273 /* If it timed out, something is wrong. Don't try to parse the
10274 buffer. */
10275 if (bytes_read < 0)
10276 {
10277 *remote_errno = FILEIO_EINVAL;
10278 return -1;
10279 }
10280
10281 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10282 {
10283 case PACKET_ERROR:
10284 *remote_errno = FILEIO_EINVAL;
10285 return -1;
10286 case PACKET_UNKNOWN:
10287 *remote_errno = FILEIO_ENOSYS;
10288 return -1;
10289 case PACKET_OK:
10290 break;
10291 }
10292
10293 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10294 &attachment_tmp))
10295 {
10296 *remote_errno = FILEIO_EINVAL;
10297 return -1;
10298 }
10299
10300 /* Make sure we saw an attachment if and only if we expected one. */
10301 if ((attachment_tmp == NULL && attachment != NULL)
10302 || (attachment_tmp != NULL && attachment == NULL))
10303 {
10304 *remote_errno = FILEIO_EINVAL;
10305 return -1;
10306 }
10307
10308 /* If an attachment was found, it must point into the packet buffer;
10309 work out how many bytes there were. */
10310 if (attachment_tmp != NULL)
10311 {
10312 *attachment = attachment_tmp;
10313 *attachment_len = bytes_read - (*attachment - rs->buf);
10314 }
10315
10316 return ret;
10317}
10318
15a201c8
GB
10319/* Set the filesystem remote_hostio functions that take FILENAME
10320 arguments will use. Return 0 on success, or -1 if an error
10321 occurs (and set *REMOTE_ERRNO). */
10322
10323static int
10324remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10325{
10326 struct remote_state *rs = get_remote_state ();
10327 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10328 char *p = rs->buf;
10329 int left = get_remote_packet_size () - 1;
10330 char arg[9];
10331 int ret;
10332
10333 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10334 return 0;
10335
10336 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10337 return 0;
10338
10339 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10340
10341 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10342 remote_buffer_add_string (&p, &left, arg);
10343
10344 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10345 remote_errno, NULL, NULL);
10346
10347 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10348 return 0;
10349
10350 if (ret == 0)
10351 rs->fs_pid = required_pid;
10352
10353 return ret;
10354}
10355
12e2a5fd 10356/* Implementation of to_fileio_open. */
a6b151f1
DJ
10357
10358static int
cd897586 10359remote_hostio_open (struct target_ops *self,
07c138c8
GB
10360 struct inferior *inf, const char *filename,
10361 int flags, int mode, int *remote_errno)
a6b151f1
DJ
10362{
10363 struct remote_state *rs = get_remote_state ();
10364 char *p = rs->buf;
10365 int left = get_remote_packet_size () - 1;
10366
15a201c8
GB
10367 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10368 return -1;
10369
a6b151f1
DJ
10370 remote_buffer_add_string (&p, &left, "vFile:open:");
10371
10372 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10373 strlen (filename));
10374 remote_buffer_add_string (&p, &left, ",");
10375
10376 remote_buffer_add_int (&p, &left, flags);
10377 remote_buffer_add_string (&p, &left, ",");
10378
10379 remote_buffer_add_int (&p, &left, mode);
10380
10381 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10382 remote_errno, NULL, NULL);
10383}
10384
12e2a5fd 10385/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
10386
10387static int
0d866f62
TT
10388remote_hostio_pwrite (struct target_ops *self,
10389 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
10390 ULONGEST offset, int *remote_errno)
10391{
10392 struct remote_state *rs = get_remote_state ();
10393 char *p = rs->buf;
10394 int left = get_remote_packet_size ();
10395 int out_len;
10396
10397 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10398
10399 remote_buffer_add_int (&p, &left, fd);
10400 remote_buffer_add_string (&p, &left, ",");
10401
10402 remote_buffer_add_int (&p, &left, offset);
10403 remote_buffer_add_string (&p, &left, ",");
10404
124e13d9 10405 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
10406 get_remote_packet_size () - (p - rs->buf));
10407
10408 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10409 remote_errno, NULL, NULL);
10410}
10411
12e2a5fd 10412/* Implementation of to_fileio_pread. */
a6b151f1
DJ
10413
10414static int
a3be983c
TT
10415remote_hostio_pread (struct target_ops *self,
10416 int fd, gdb_byte *read_buf, int len,
a6b151f1
DJ
10417 ULONGEST offset, int *remote_errno)
10418{
10419 struct remote_state *rs = get_remote_state ();
10420 char *p = rs->buf;
10421 char *attachment;
10422 int left = get_remote_packet_size ();
10423 int ret, attachment_len;
10424 int read_len;
10425
10426 remote_buffer_add_string (&p, &left, "vFile:pread:");
10427
10428 remote_buffer_add_int (&p, &left, fd);
10429 remote_buffer_add_string (&p, &left, ",");
10430
10431 remote_buffer_add_int (&p, &left, len);
10432 remote_buffer_add_string (&p, &left, ",");
10433
10434 remote_buffer_add_int (&p, &left, offset);
10435
10436 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
10437 remote_errno, &attachment,
10438 &attachment_len);
10439
10440 if (ret < 0)
10441 return ret;
10442
bc20a4af 10443 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
10444 read_buf, len);
10445 if (read_len != ret)
10446 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
10447
10448 return ret;
10449}
10450
12e2a5fd 10451/* Implementation of to_fileio_close. */
a6b151f1
DJ
10452
10453static int
df39ea25 10454remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
10455{
10456 struct remote_state *rs = get_remote_state ();
10457 char *p = rs->buf;
10458 int left = get_remote_packet_size () - 1;
10459
10460 remote_buffer_add_string (&p, &left, "vFile:close:");
10461
10462 remote_buffer_add_int (&p, &left, fd);
10463
10464 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
10465 remote_errno, NULL, NULL);
10466}
10467
12e2a5fd 10468/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
10469
10470static int
dbbca37d 10471remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
10472 struct inferior *inf, const char *filename,
10473 int *remote_errno)
a6b151f1
DJ
10474{
10475 struct remote_state *rs = get_remote_state ();
10476 char *p = rs->buf;
10477 int left = get_remote_packet_size () - 1;
10478
15a201c8
GB
10479 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10480 return -1;
10481
a6b151f1
DJ
10482 remote_buffer_add_string (&p, &left, "vFile:unlink:");
10483
10484 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10485 strlen (filename));
10486
10487 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10488 remote_errno, NULL, NULL);
10489}
10490
12e2a5fd 10491/* Implementation of to_fileio_readlink. */
b9e7b9c3
UW
10492
10493static char *
fab5aa7c 10494remote_hostio_readlink (struct target_ops *self,
07c138c8
GB
10495 struct inferior *inf, const char *filename,
10496 int *remote_errno)
b9e7b9c3
UW
10497{
10498 struct remote_state *rs = get_remote_state ();
10499 char *p = rs->buf;
10500 char *attachment;
10501 int left = get_remote_packet_size ();
10502 int len, attachment_len;
10503 int read_len;
10504 char *ret;
10505
15a201c8
GB
10506 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10507 return NULL;
10508
b9e7b9c3
UW
10509 remote_buffer_add_string (&p, &left, "vFile:readlink:");
10510
10511 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10512 strlen (filename));
10513
10514 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10515 remote_errno, &attachment,
10516 &attachment_len);
10517
10518 if (len < 0)
10519 return NULL;
10520
10521 ret = xmalloc (len + 1);
10522
bc20a4af
PA
10523 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10524 (gdb_byte *) ret, len);
b9e7b9c3
UW
10525 if (read_len != len)
10526 error (_("Readlink returned %d, but %d bytes."), len, read_len);
10527
10528 ret[len] = '\0';
10529 return ret;
10530}
10531
12e2a5fd 10532/* Implementation of to_fileio_fstat. */
0a93529c
GB
10533
10534static int
10535remote_hostio_fstat (struct target_ops *self,
10536 int fd, struct stat *st,
10537 int *remote_errno)
10538{
10539 struct remote_state *rs = get_remote_state ();
10540 char *p = rs->buf;
10541 int left = get_remote_packet_size ();
10542 int attachment_len, ret;
10543 char *attachment;
10544 struct fio_stat fst;
10545 int read_len;
10546
464b0089
GB
10547 remote_buffer_add_string (&p, &left, "vFile:fstat:");
10548
10549 remote_buffer_add_int (&p, &left, fd);
10550
10551 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
10552 remote_errno, &attachment,
10553 &attachment_len);
10554 if (ret < 0)
0a93529c 10555 {
464b0089
GB
10556 if (*remote_errno != FILEIO_ENOSYS)
10557 return ret;
10558
0a93529c
GB
10559 /* Strictly we should return -1, ENOSYS here, but when
10560 "set sysroot remote:" was implemented in August 2008
10561 BFD's need for a stat function was sidestepped with
10562 this hack. This was not remedied until March 2015
10563 so we retain the previous behavior to avoid breaking
10564 compatibility.
10565
10566 Note that the memset is a March 2015 addition; older
10567 GDBs set st_size *and nothing else* so the structure
10568 would have garbage in all other fields. This might
10569 break something but retaining the previous behavior
10570 here would be just too wrong. */
10571
10572 memset (st, 0, sizeof (struct stat));
10573 st->st_size = INT_MAX;
10574 return 0;
10575 }
10576
0a93529c
GB
10577 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10578 (gdb_byte *) &fst, sizeof (fst));
10579
10580 if (read_len != ret)
10581 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
10582
10583 if (read_len != sizeof (fst))
10584 error (_("vFile:fstat returned %d bytes, but expecting %d."),
10585 read_len, (int) sizeof (fst));
10586
10587 remote_fileio_to_host_stat (&fst, st);
10588
10589 return 0;
10590}
10591
12e2a5fd 10592/* Implementation of to_filesystem_is_local. */
e3dd7556
GB
10593
10594static int
10595remote_filesystem_is_local (struct target_ops *self)
10596{
10597 /* Valgrind GDB presents itself as a remote target but works
10598 on the local filesystem: it does not implement remote get
10599 and users are not expected to set a sysroot. To handle
10600 this case we treat the remote filesystem as local if the
10601 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
10602 does not support vFile:open. */
a3be80c3 10603 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
10604 {
10605 enum packet_support ps = packet_support (PACKET_vFile_open);
10606
10607 if (ps == PACKET_SUPPORT_UNKNOWN)
10608 {
10609 int fd, remote_errno;
10610
10611 /* Try opening a file to probe support. The supplied
10612 filename is irrelevant, we only care about whether
10613 the stub recognizes the packet or not. */
07c138c8 10614 fd = remote_hostio_open (self, NULL, "just probing",
e3dd7556
GB
10615 FILEIO_O_RDONLY, 0700,
10616 &remote_errno);
10617
10618 if (fd >= 0)
10619 remote_hostio_close (self, fd, &remote_errno);
10620
10621 ps = packet_support (PACKET_vFile_open);
10622 }
10623
10624 if (ps == PACKET_DISABLE)
10625 {
10626 static int warning_issued = 0;
10627
10628 if (!warning_issued)
10629 {
10630 warning (_("remote target does not support file"
10631 " transfer, attempting to access files"
10632 " from local filesystem."));
10633 warning_issued = 1;
10634 }
10635
10636 return 1;
10637 }
10638 }
10639
10640 return 0;
10641}
10642
a6b151f1
DJ
10643static int
10644remote_fileio_errno_to_host (int errnum)
10645{
10646 switch (errnum)
10647 {
10648 case FILEIO_EPERM:
10649 return EPERM;
10650 case FILEIO_ENOENT:
10651 return ENOENT;
10652 case FILEIO_EINTR:
10653 return EINTR;
10654 case FILEIO_EIO:
10655 return EIO;
10656 case FILEIO_EBADF:
10657 return EBADF;
10658 case FILEIO_EACCES:
10659 return EACCES;
10660 case FILEIO_EFAULT:
10661 return EFAULT;
10662 case FILEIO_EBUSY:
10663 return EBUSY;
10664 case FILEIO_EEXIST:
10665 return EEXIST;
10666 case FILEIO_ENODEV:
10667 return ENODEV;
10668 case FILEIO_ENOTDIR:
10669 return ENOTDIR;
10670 case FILEIO_EISDIR:
10671 return EISDIR;
10672 case FILEIO_EINVAL:
10673 return EINVAL;
10674 case FILEIO_ENFILE:
10675 return ENFILE;
10676 case FILEIO_EMFILE:
10677 return EMFILE;
10678 case FILEIO_EFBIG:
10679 return EFBIG;
10680 case FILEIO_ENOSPC:
10681 return ENOSPC;
10682 case FILEIO_ESPIPE:
10683 return ESPIPE;
10684 case FILEIO_EROFS:
10685 return EROFS;
10686 case FILEIO_ENOSYS:
10687 return ENOSYS;
10688 case FILEIO_ENAMETOOLONG:
10689 return ENAMETOOLONG;
10690 }
10691 return -1;
10692}
10693
10694static char *
10695remote_hostio_error (int errnum)
10696{
10697 int host_error = remote_fileio_errno_to_host (errnum);
10698
10699 if (host_error == -1)
10700 error (_("Unknown remote I/O error %d"), errnum);
10701 else
10702 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10703}
10704
a6b151f1
DJ
10705static void
10706remote_hostio_close_cleanup (void *opaque)
10707{
10708 int fd = *(int *) opaque;
10709 int remote_errno;
10710
df39ea25 10711 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
10712}
10713
10714void
10715remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10716{
10717 struct cleanup *back_to, *close_cleanup;
10718 int retcode, fd, remote_errno, bytes, io_size;
10719 FILE *file;
10720 gdb_byte *buffer;
10721 int bytes_in_buffer;
10722 int saw_eof;
10723 ULONGEST offset;
5d93a237 10724 struct remote_state *rs = get_remote_state ();
a6b151f1 10725
5d93a237 10726 if (!rs->remote_desc)
a6b151f1
DJ
10727 error (_("command can only be used with remote target"));
10728
614c279d 10729 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
10730 if (file == NULL)
10731 perror_with_name (local_file);
7c8a8b04 10732 back_to = make_cleanup_fclose (file);
a6b151f1 10733
07c138c8 10734 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 10735 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1
DJ
10736 | FILEIO_O_TRUNC),
10737 0700, &remote_errno);
10738 if (fd == -1)
10739 remote_hostio_error (remote_errno);
10740
10741 /* Send up to this many bytes at once. They won't all fit in the
10742 remote packet limit, so we'll transfer slightly fewer. */
10743 io_size = get_remote_packet_size ();
10744 buffer = xmalloc (io_size);
10745 make_cleanup (xfree, buffer);
10746
10747 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10748
10749 bytes_in_buffer = 0;
10750 saw_eof = 0;
10751 offset = 0;
10752 while (bytes_in_buffer || !saw_eof)
10753 {
10754 if (!saw_eof)
10755 {
3e43a32a
MS
10756 bytes = fread (buffer + bytes_in_buffer, 1,
10757 io_size - bytes_in_buffer,
a6b151f1
DJ
10758 file);
10759 if (bytes == 0)
10760 {
10761 if (ferror (file))
10762 error (_("Error reading %s."), local_file);
10763 else
10764 {
10765 /* EOF. Unless there is something still in the
10766 buffer from the last iteration, we are done. */
10767 saw_eof = 1;
10768 if (bytes_in_buffer == 0)
10769 break;
10770 }
10771 }
10772 }
10773 else
10774 bytes = 0;
10775
10776 bytes += bytes_in_buffer;
10777 bytes_in_buffer = 0;
10778
0d866f62
TT
10779 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
10780 fd, buffer, bytes,
3e43a32a 10781 offset, &remote_errno);
a6b151f1
DJ
10782
10783 if (retcode < 0)
10784 remote_hostio_error (remote_errno);
10785 else if (retcode == 0)
10786 error (_("Remote write of %d bytes returned 0!"), bytes);
10787 else if (retcode < bytes)
10788 {
10789 /* Short write. Save the rest of the read data for the next
10790 write. */
10791 bytes_in_buffer = bytes - retcode;
10792 memmove (buffer, buffer + retcode, bytes_in_buffer);
10793 }
10794
10795 offset += retcode;
10796 }
10797
10798 discard_cleanups (close_cleanup);
df39ea25 10799 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
10800 remote_hostio_error (remote_errno);
10801
10802 if (from_tty)
10803 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10804 do_cleanups (back_to);
10805}
10806
10807void
10808remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10809{
10810 struct cleanup *back_to, *close_cleanup;
cea39f65 10811 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
10812 FILE *file;
10813 gdb_byte *buffer;
10814 ULONGEST offset;
5d93a237 10815 struct remote_state *rs = get_remote_state ();
a6b151f1 10816
5d93a237 10817 if (!rs->remote_desc)
a6b151f1
DJ
10818 error (_("command can only be used with remote target"));
10819
07c138c8 10820 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 10821 remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
a6b151f1
DJ
10822 if (fd == -1)
10823 remote_hostio_error (remote_errno);
10824
614c279d 10825 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
10826 if (file == NULL)
10827 perror_with_name (local_file);
7c8a8b04 10828 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
10829
10830 /* Send up to this many bytes at once. They won't all fit in the
10831 remote packet limit, so we'll transfer slightly fewer. */
10832 io_size = get_remote_packet_size ();
10833 buffer = xmalloc (io_size);
10834 make_cleanup (xfree, buffer);
10835
10836 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10837
10838 offset = 0;
10839 while (1)
10840 {
a3be983c
TT
10841 bytes = remote_hostio_pread (find_target_at (process_stratum),
10842 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
10843 if (bytes == 0)
10844 /* Success, but no bytes, means end-of-file. */
10845 break;
10846 if (bytes == -1)
10847 remote_hostio_error (remote_errno);
10848
10849 offset += bytes;
10850
10851 bytes = fwrite (buffer, 1, bytes, file);
10852 if (bytes == 0)
10853 perror_with_name (local_file);
10854 }
10855
10856 discard_cleanups (close_cleanup);
df39ea25 10857 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
10858 remote_hostio_error (remote_errno);
10859
10860 if (from_tty)
10861 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10862 do_cleanups (back_to);
10863}
10864
10865void
10866remote_file_delete (const char *remote_file, int from_tty)
10867{
10868 int retcode, remote_errno;
5d93a237 10869 struct remote_state *rs = get_remote_state ();
a6b151f1 10870
5d93a237 10871 if (!rs->remote_desc)
a6b151f1
DJ
10872 error (_("command can only be used with remote target"));
10873
dbbca37d 10874 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 10875 NULL, remote_file, &remote_errno);
a6b151f1
DJ
10876 if (retcode == -1)
10877 remote_hostio_error (remote_errno);
10878
10879 if (from_tty)
10880 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10881}
10882
10883static void
10884remote_put_command (char *args, int from_tty)
10885{
10886 struct cleanup *back_to;
10887 char **argv;
10888
d1a41061
PP
10889 if (args == NULL)
10890 error_no_arg (_("file to put"));
10891
10892 argv = gdb_buildargv (args);
a6b151f1
DJ
10893 back_to = make_cleanup_freeargv (argv);
10894 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10895 error (_("Invalid parameters to remote put"));
10896
10897 remote_file_put (argv[0], argv[1], from_tty);
10898
10899 do_cleanups (back_to);
10900}
10901
10902static void
10903remote_get_command (char *args, int from_tty)
10904{
10905 struct cleanup *back_to;
10906 char **argv;
10907
d1a41061
PP
10908 if (args == NULL)
10909 error_no_arg (_("file to get"));
10910
10911 argv = gdb_buildargv (args);
a6b151f1
DJ
10912 back_to = make_cleanup_freeargv (argv);
10913 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10914 error (_("Invalid parameters to remote get"));
10915
10916 remote_file_get (argv[0], argv[1], from_tty);
10917
10918 do_cleanups (back_to);
10919}
10920
10921static void
10922remote_delete_command (char *args, int from_tty)
10923{
10924 struct cleanup *back_to;
10925 char **argv;
10926
d1a41061
PP
10927 if (args == NULL)
10928 error_no_arg (_("file to delete"));
10929
10930 argv = gdb_buildargv (args);
a6b151f1
DJ
10931 back_to = make_cleanup_freeargv (argv);
10932 if (argv[0] == NULL || argv[1] != NULL)
10933 error (_("Invalid parameters to remote delete"));
10934
10935 remote_file_delete (argv[0], from_tty);
10936
10937 do_cleanups (back_to);
10938}
10939
10940static void
10941remote_command (char *args, int from_tty)
10942{
635c7e8a 10943 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
10944}
10945
b2175913 10946static int
19db3e69 10947remote_can_execute_reverse (struct target_ops *self)
b2175913 10948{
4082afcc
PA
10949 if (packet_support (PACKET_bs) == PACKET_ENABLE
10950 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
10951 return 1;
10952 else
10953 return 0;
b2175913
MS
10954}
10955
74531fed 10956static int
2a9a2795 10957remote_supports_non_stop (struct target_ops *self)
74531fed
PA
10958{
10959 return 1;
10960}
10961
03583c20 10962static int
2bfc0540 10963remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
10964{
10965 /* Only supported in extended mode. */
10966 return 0;
10967}
10968
8a305172 10969static int
86ce2668 10970remote_supports_multi_process (struct target_ops *self)
8a305172
PA
10971{
10972 struct remote_state *rs = get_remote_state ();
a744cf53 10973
901f9912
UW
10974 /* Only extended-remote handles being attached to multiple
10975 processes, even though plain remote can use the multi-process
10976 thread id extensions, so that GDB knows the target process's
10977 PID. */
10978 return rs->extended && remote_multi_process_p (rs);
8a305172
PA
10979}
10980
70221824 10981static int
782b2b07
SS
10982remote_supports_cond_tracepoints (void)
10983{
4082afcc 10984 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
10985}
10986
3788aec7 10987static int
efcc2da7 10988remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 10989{
4082afcc 10990 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
10991}
10992
70221824 10993static int
7a697b8d
SS
10994remote_supports_fast_tracepoints (void)
10995{
4082afcc 10996 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
10997}
10998
0fb4aa4b
PA
10999static int
11000remote_supports_static_tracepoints (void)
11001{
4082afcc 11002 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
11003}
11004
1e4d1764
YQ
11005static int
11006remote_supports_install_in_trace (void)
11007{
4082afcc 11008 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
11009}
11010
d248b706 11011static int
7d178d6a 11012remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 11013{
4082afcc
PA
11014 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11015 == PACKET_ENABLE);
d248b706
KY
11016}
11017
3065dfb6 11018static int
6de37a3a 11019remote_supports_string_tracing (struct target_ops *self)
3065dfb6 11020{
4082afcc 11021 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
11022}
11023
d3ce09f5 11024static int
78eff0ec 11025remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 11026{
4082afcc 11027 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
11028}
11029
35b1e5cc 11030static void
ecae04e1 11031remote_trace_init (struct target_ops *self)
35b1e5cc
SS
11032{
11033 putpkt ("QTinit");
11034 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 11035 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11036 error (_("Target does not support this command."));
11037}
11038
11039static void free_actions_list (char **actions_list);
11040static void free_actions_list_cleanup_wrapper (void *);
11041static void
11042free_actions_list_cleanup_wrapper (void *al)
11043{
11044 free_actions_list (al);
11045}
11046
11047static void
11048free_actions_list (char **actions_list)
11049{
11050 int ndx;
11051
11052 if (actions_list == 0)
11053 return;
11054
11055 for (ndx = 0; actions_list[ndx]; ndx++)
11056 xfree (actions_list[ndx]);
11057
11058 xfree (actions_list);
11059}
11060
409873ef
SS
11061/* Recursive routine to walk through command list including loops, and
11062 download packets for each command. */
11063
11064static void
11065remote_download_command_source (int num, ULONGEST addr,
11066 struct command_line *cmds)
11067{
11068 struct remote_state *rs = get_remote_state ();
11069 struct command_line *cmd;
11070
11071 for (cmd = cmds; cmd; cmd = cmd->next)
11072 {
0df8b418 11073 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11074 strcpy (rs->buf, "QTDPsrc:");
11075 encode_source_string (num, addr, "cmd", cmd->line,
11076 rs->buf + strlen (rs->buf),
11077 rs->buf_size - strlen (rs->buf));
11078 putpkt (rs->buf);
11079 remote_get_noisy_reply (&target_buf, &target_buf_size);
11080 if (strcmp (target_buf, "OK"))
11081 warning (_("Target does not support source download."));
11082
11083 if (cmd->control_type == while_control
11084 || cmd->control_type == while_stepping_control)
11085 {
11086 remote_download_command_source (num, addr, *cmd->body_list);
11087
0df8b418 11088 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11089 strcpy (rs->buf, "QTDPsrc:");
11090 encode_source_string (num, addr, "cmd", "end",
11091 rs->buf + strlen (rs->buf),
11092 rs->buf_size - strlen (rs->buf));
11093 putpkt (rs->buf);
11094 remote_get_noisy_reply (&target_buf, &target_buf_size);
11095 if (strcmp (target_buf, "OK"))
11096 warning (_("Target does not support source download."));
11097 }
11098 }
11099}
11100
35b1e5cc 11101static void
548f7808 11102remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 11103{
bba74b36 11104#define BUF_SIZE 2048
e8ba3115 11105
35b1e5cc 11106 CORE_ADDR tpaddr;
409873ef 11107 char addrbuf[40];
bba74b36 11108 char buf[BUF_SIZE];
35b1e5cc
SS
11109 char **tdp_actions;
11110 char **stepping_actions;
11111 int ndx;
11112 struct cleanup *old_chain = NULL;
11113 struct agent_expr *aexpr;
11114 struct cleanup *aexpr_chain = NULL;
11115 char *pkt;
e8ba3115 11116 struct breakpoint *b = loc->owner;
d9b3f62e 11117 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 11118
dc673c81 11119 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
11120 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11121 tdp_actions);
11122 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11123 stepping_actions);
11124
11125 tpaddr = loc->address;
11126 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
11127 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11128 addrbuf, /* address */
11129 (b->enable_state == bp_enabled ? 'E' : 'D'),
11130 t->step_count, t->pass_count);
e8ba3115
YQ
11131 /* Fast tracepoints are mostly handled by the target, but we can
11132 tell the target how big of an instruction block should be moved
11133 around. */
11134 if (b->type == bp_fast_tracepoint)
11135 {
11136 /* Only test for support at download time; we may not know
11137 target capabilities at definition time. */
11138 if (remote_supports_fast_tracepoints ())
35b1e5cc 11139 {
6b940e6a
PL
11140 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11141 NULL))
bba74b36 11142 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 11143 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 11144 else
e8ba3115
YQ
11145 /* If it passed validation at definition but fails now,
11146 something is very wrong. */
11147 internal_error (__FILE__, __LINE__,
11148 _("Fast tracepoint not "
11149 "valid during download"));
35b1e5cc 11150 }
e8ba3115
YQ
11151 else
11152 /* Fast tracepoints are functionally identical to regular
11153 tracepoints, so don't take lack of support as a reason to
11154 give up on the trace run. */
11155 warning (_("Target does not support fast tracepoints, "
11156 "downloading %d as regular tracepoint"), b->number);
11157 }
11158 else if (b->type == bp_static_tracepoint)
11159 {
11160 /* Only test for support at download time; we may not know
11161 target capabilities at definition time. */
11162 if (remote_supports_static_tracepoints ())
0fb4aa4b 11163 {
e8ba3115 11164 struct static_tracepoint_marker marker;
0fb4aa4b 11165
e8ba3115
YQ
11166 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11167 strcat (buf, ":S");
0fb4aa4b 11168 else
e8ba3115 11169 error (_("Static tracepoint not valid during download"));
0fb4aa4b 11170 }
e8ba3115
YQ
11171 else
11172 /* Fast tracepoints are functionally identical to regular
11173 tracepoints, so don't take lack of support as a reason
11174 to give up on the trace run. */
11175 error (_("Target does not support static tracepoints"));
11176 }
11177 /* If the tracepoint has a conditional, make it into an agent
11178 expression and append to the definition. */
11179 if (loc->cond)
11180 {
11181 /* Only test support at download time, we may not know target
11182 capabilities at definition time. */
11183 if (remote_supports_cond_tracepoints ())
35b1e5cc 11184 {
e8ba3115
YQ
11185 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11186 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
11187 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11188 aexpr->len);
e8ba3115
YQ
11189 pkt = buf + strlen (buf);
11190 for (ndx = 0; ndx < aexpr->len; ++ndx)
11191 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11192 *pkt = '\0';
11193 do_cleanups (aexpr_chain);
35b1e5cc 11194 }
e8ba3115
YQ
11195 else
11196 warning (_("Target does not support conditional tracepoints, "
11197 "ignoring tp %d cond"), b->number);
11198 }
35b1e5cc 11199
d9b3f62e 11200 if (b->commands || *default_collect)
e8ba3115
YQ
11201 strcat (buf, "-");
11202 putpkt (buf);
11203 remote_get_noisy_reply (&target_buf, &target_buf_size);
11204 if (strcmp (target_buf, "OK"))
11205 error (_("Target does not support tracepoints."));
35b1e5cc 11206
e8ba3115
YQ
11207 /* do_single_steps (t); */
11208 if (tdp_actions)
11209 {
11210 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 11211 {
e8ba3115 11212 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11213 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11214 b->number, addrbuf, /* address */
11215 tdp_actions[ndx],
11216 ((tdp_actions[ndx + 1] || stepping_actions)
11217 ? '-' : 0));
e8ba3115
YQ
11218 putpkt (buf);
11219 remote_get_noisy_reply (&target_buf,
11220 &target_buf_size);
11221 if (strcmp (target_buf, "OK"))
11222 error (_("Error on target while setting tracepoints."));
35b1e5cc 11223 }
e8ba3115
YQ
11224 }
11225 if (stepping_actions)
11226 {
11227 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 11228 {
e8ba3115 11229 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11230 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11231 b->number, addrbuf, /* address */
11232 ((ndx == 0) ? "S" : ""),
11233 stepping_actions[ndx],
11234 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
11235 putpkt (buf);
11236 remote_get_noisy_reply (&target_buf,
11237 &target_buf_size);
11238 if (strcmp (target_buf, "OK"))
11239 error (_("Error on target while setting tracepoints."));
35b1e5cc 11240 }
e8ba3115 11241 }
409873ef 11242
4082afcc 11243 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115
YQ
11244 {
11245 if (b->addr_string)
409873ef 11246 {
e8ba3115
YQ
11247 strcpy (buf, "QTDPsrc:");
11248 encode_source_string (b->number, loc->address,
11249 "at", b->addr_string, buf + strlen (buf),
11250 2048 - strlen (buf));
409873ef 11251
e8ba3115
YQ
11252 putpkt (buf);
11253 remote_get_noisy_reply (&target_buf, &target_buf_size);
11254 if (strcmp (target_buf, "OK"))
11255 warning (_("Target does not support source download."));
409873ef 11256 }
e8ba3115
YQ
11257 if (b->cond_string)
11258 {
11259 strcpy (buf, "QTDPsrc:");
11260 encode_source_string (b->number, loc->address,
11261 "cond", b->cond_string, buf + strlen (buf),
11262 2048 - strlen (buf));
11263 putpkt (buf);
11264 remote_get_noisy_reply (&target_buf, &target_buf_size);
11265 if (strcmp (target_buf, "OK"))
11266 warning (_("Target does not support source download."));
11267 }
11268 remote_download_command_source (b->number, loc->address,
11269 breakpoint_commands (b));
35b1e5cc 11270 }
e8ba3115
YQ
11271
11272 do_cleanups (old_chain);
35b1e5cc
SS
11273}
11274
1e4d1764 11275static int
a52a8357 11276remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 11277{
1e51243a
PA
11278 struct remote_state *rs = get_remote_state ();
11279 struct trace_status *ts;
11280 int status;
11281
11282 /* Don't try to install tracepoints until we've relocated our
11283 symbols, and fetched and merged the target's tracepoint list with
11284 ours. */
11285 if (rs->starting_up)
11286 return 0;
11287
11288 ts = current_trace_status ();
8bd200f1 11289 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
11290
11291 if (status == -1 || !ts->running_known || !ts->running)
11292 return 0;
11293
11294 /* If we are in a tracing experiment, but remote stub doesn't support
11295 installing tracepoint in trace, we have to return. */
11296 if (!remote_supports_install_in_trace ())
11297 return 0;
11298
11299 return 1;
11300}
11301
11302
35b1e5cc 11303static void
559d2b81
TT
11304remote_download_trace_state_variable (struct target_ops *self,
11305 struct trace_state_variable *tsv)
35b1e5cc
SS
11306{
11307 struct remote_state *rs = get_remote_state ();
00bf0b85 11308 char *p;
35b1e5cc 11309
bba74b36
YQ
11310 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11311 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11312 tsv->builtin);
00bf0b85
SS
11313 p = rs->buf + strlen (rs->buf);
11314 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11315 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 11316 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 11317 *p++ = '\0';
35b1e5cc
SS
11318 putpkt (rs->buf);
11319 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11320 if (*target_buf == '\0')
11321 error (_("Target does not support this command."));
11322 if (strcmp (target_buf, "OK") != 0)
11323 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
11324}
11325
d248b706 11326static void
46670d57
TT
11327remote_enable_tracepoint (struct target_ops *self,
11328 struct bp_location *location)
d248b706
KY
11329{
11330 struct remote_state *rs = get_remote_state ();
11331 char addr_buf[40];
11332
11333 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
11334 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11335 location->owner->number, addr_buf);
d248b706
KY
11336 putpkt (rs->buf);
11337 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11338 if (*rs->buf == '\0')
11339 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11340 if (strcmp (rs->buf, "OK") != 0)
11341 error (_("Error on target while enabling tracepoint."));
11342}
11343
11344static void
780b049c
TT
11345remote_disable_tracepoint (struct target_ops *self,
11346 struct bp_location *location)
d248b706
KY
11347{
11348 struct remote_state *rs = get_remote_state ();
11349 char addr_buf[40];
11350
11351 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
11352 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
11353 location->owner->number, addr_buf);
d248b706
KY
11354 putpkt (rs->buf);
11355 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11356 if (*rs->buf == '\0')
11357 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
11358 if (strcmp (rs->buf, "OK") != 0)
11359 error (_("Error on target while disabling tracepoint."));
11360}
11361
35b1e5cc 11362static void
583f9a86 11363remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
11364{
11365 asection *s;
81b9b86e 11366 bfd *abfd = NULL;
35b1e5cc 11367 bfd_size_type size;
608bcef2 11368 bfd_vma vma;
35b1e5cc 11369 int anysecs = 0;
c2fa21f1 11370 int offset = 0;
35b1e5cc
SS
11371
11372 if (!exec_bfd)
11373 return; /* No information to give. */
11374
11375 strcpy (target_buf, "QTro");
9779ab84 11376 offset = strlen (target_buf);
35b1e5cc
SS
11377 for (s = exec_bfd->sections; s; s = s->next)
11378 {
11379 char tmp1[40], tmp2[40];
c2fa21f1 11380 int sec_length;
35b1e5cc
SS
11381
11382 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 11383 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
11384 (s->flags & SEC_READONLY) == 0)
11385 continue;
11386
11387 anysecs = 1;
81b9b86e 11388 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 11389 size = bfd_get_section_size (s);
608bcef2
HZ
11390 sprintf_vma (tmp1, vma);
11391 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
11392 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
11393 if (offset + sec_length + 1 > target_buf_size)
11394 {
4082afcc 11395 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 11396 warning (_("\
c2fa21f1
HZ
11397Too many sections for read-only sections definition packet."));
11398 break;
11399 }
bba74b36
YQ
11400 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
11401 tmp1, tmp2);
c2fa21f1 11402 offset += sec_length;
35b1e5cc
SS
11403 }
11404 if (anysecs)
11405 {
11406 putpkt (target_buf);
11407 getpkt (&target_buf, &target_buf_size, 0);
11408 }
11409}
11410
11411static void
e2d1aae3 11412remote_trace_start (struct target_ops *self)
35b1e5cc
SS
11413{
11414 putpkt ("QTStart");
11415 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11416 if (*target_buf == '\0')
11417 error (_("Target does not support this command."));
11418 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11419 error (_("Bogus reply from target: %s"), target_buf);
11420}
11421
11422static int
8bd200f1 11423remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 11424{
953b98d1 11425 /* Initialize it just to avoid a GCC false warning. */
f652de6f 11426 char *p = NULL;
0df8b418 11427 /* FIXME we need to get register block size some other way. */
00bf0b85 11428 extern int trace_regblock_size;
bd3eecc3
PA
11429 enum packet_result result;
11430
4082afcc 11431 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 11432 return -1;
a744cf53 11433
00bf0b85
SS
11434 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
11435
049dc89b
JK
11436 putpkt ("qTStatus");
11437
492d29ea 11438 TRY
67f41397
JK
11439 {
11440 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
11441 }
492d29ea 11442 CATCH (ex, RETURN_MASK_ERROR)
67f41397 11443 {
598d3636
JK
11444 if (ex.error != TARGET_CLOSE_ERROR)
11445 {
11446 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
11447 return -1;
11448 }
11449 throw_exception (ex);
67f41397 11450 }
492d29ea 11451 END_CATCH
00bf0b85 11452
bd3eecc3
PA
11453 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
11454
00bf0b85 11455 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 11456 if (result == PACKET_UNKNOWN)
00bf0b85 11457 return -1;
35b1e5cc 11458
00bf0b85 11459 /* We're working with a live target. */
f5911ea1 11460 ts->filename = NULL;
00bf0b85 11461
00bf0b85 11462 if (*p++ != 'T')
35b1e5cc
SS
11463 error (_("Bogus trace status reply from target: %s"), target_buf);
11464
84cebc4a
YQ
11465 /* Function 'parse_trace_status' sets default value of each field of
11466 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
11467 parse_trace_status (p, ts);
11468
11469 return ts->running;
35b1e5cc
SS
11470}
11471
70221824 11472static void
db90e85c 11473remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
11474 struct uploaded_tp *utp)
11475{
11476 struct remote_state *rs = get_remote_state ();
f196051f
SS
11477 char *reply;
11478 struct bp_location *loc;
11479 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 11480 size_t size = get_remote_packet_size ();
f196051f
SS
11481
11482 if (tp)
11483 {
11484 tp->base.hit_count = 0;
11485 tp->traceframe_usage = 0;
11486 for (loc = tp->base.loc; loc; loc = loc->next)
11487 {
11488 /* If the tracepoint was never downloaded, don't go asking for
11489 any status. */
11490 if (tp->number_on_target == 0)
11491 continue;
bba74b36
YQ
11492 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
11493 phex_nz (loc->address, 0));
f196051f
SS
11494 putpkt (rs->buf);
11495 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11496 if (reply && *reply)
11497 {
11498 if (*reply == 'V')
11499 parse_tracepoint_status (reply + 1, bp, utp);
11500 }
11501 }
11502 }
11503 else if (utp)
11504 {
11505 utp->hit_count = 0;
11506 utp->traceframe_usage = 0;
bba74b36
YQ
11507 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
11508 phex_nz (utp->addr, 0));
f196051f
SS
11509 putpkt (rs->buf);
11510 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11511 if (reply && *reply)
11512 {
11513 if (*reply == 'V')
11514 parse_tracepoint_status (reply + 1, bp, utp);
11515 }
11516 }
11517}
11518
35b1e5cc 11519static void
74499f1b 11520remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
11521{
11522 putpkt ("QTStop");
11523 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11524 if (*target_buf == '\0')
11525 error (_("Target does not support this command."));
11526 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11527 error (_("Bogus reply from target: %s"), target_buf);
11528}
11529
11530static int
bd4c6793
TT
11531remote_trace_find (struct target_ops *self,
11532 enum trace_find_type type, int num,
cc5925ad 11533 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
11534 int *tpp)
11535{
11536 struct remote_state *rs = get_remote_state ();
bba74b36 11537 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
11538 char *p, *reply;
11539 int target_frameno = -1, target_tracept = -1;
11540
e6e4e701
PA
11541 /* Lookups other than by absolute frame number depend on the current
11542 trace selected, so make sure it is correct on the remote end
11543 first. */
11544 if (type != tfind_number)
11545 set_remote_traceframe ();
11546
35b1e5cc
SS
11547 p = rs->buf;
11548 strcpy (p, "QTFrame:");
11549 p = strchr (p, '\0');
11550 switch (type)
11551 {
11552 case tfind_number:
bba74b36 11553 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
11554 break;
11555 case tfind_pc:
bba74b36 11556 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
11557 break;
11558 case tfind_tp:
bba74b36 11559 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
11560 break;
11561 case tfind_range:
bba74b36
YQ
11562 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11563 phex_nz (addr2, 0));
35b1e5cc
SS
11564 break;
11565 case tfind_outside:
bba74b36
YQ
11566 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11567 phex_nz (addr2, 0));
35b1e5cc
SS
11568 break;
11569 default:
9b20d036 11570 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
11571 }
11572
11573 putpkt (rs->buf);
2f65bcb7 11574 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
11575 if (*reply == '\0')
11576 error (_("Target does not support this command."));
35b1e5cc
SS
11577
11578 while (reply && *reply)
11579 switch (*reply)
11580 {
11581 case 'F':
f197e0f1
VP
11582 p = ++reply;
11583 target_frameno = (int) strtol (p, &reply, 16);
11584 if (reply == p)
11585 error (_("Unable to parse trace frame number"));
e6e4e701
PA
11586 /* Don't update our remote traceframe number cache on failure
11587 to select a remote traceframe. */
f197e0f1
VP
11588 if (target_frameno == -1)
11589 return -1;
35b1e5cc
SS
11590 break;
11591 case 'T':
f197e0f1
VP
11592 p = ++reply;
11593 target_tracept = (int) strtol (p, &reply, 16);
11594 if (reply == p)
11595 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
11596 break;
11597 case 'O': /* "OK"? */
11598 if (reply[1] == 'K' && reply[2] == '\0')
11599 reply += 2;
11600 else
11601 error (_("Bogus reply from target: %s"), reply);
11602 break;
11603 default:
11604 error (_("Bogus reply from target: %s"), reply);
11605 }
11606 if (tpp)
11607 *tpp = target_tracept;
e6e4e701 11608
262e1174 11609 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
11610 return target_frameno;
11611}
11612
11613static int
4011015b
TT
11614remote_get_trace_state_variable_value (struct target_ops *self,
11615 int tsvnum, LONGEST *val)
35b1e5cc
SS
11616{
11617 struct remote_state *rs = get_remote_state ();
11618 char *reply;
11619 ULONGEST uval;
11620
e6e4e701
PA
11621 set_remote_traceframe ();
11622
bba74b36 11623 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
11624 putpkt (rs->buf);
11625 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11626 if (reply && *reply)
11627 {
11628 if (*reply == 'V')
11629 {
11630 unpack_varlen_hex (reply + 1, &uval);
11631 *val = (LONGEST) uval;
11632 return 1;
11633 }
11634 }
11635 return 0;
11636}
11637
00bf0b85 11638static int
dc3decaf 11639remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
11640{
11641 struct remote_state *rs = get_remote_state ();
11642 char *p, *reply;
11643
11644 p = rs->buf;
11645 strcpy (p, "QTSave:");
11646 p += strlen (p);
11647 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11648 error (_("Remote file name too long for trace save packet"));
9f1b45b0 11649 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
11650 *p++ = '\0';
11651 putpkt (rs->buf);
ad91cd99 11652 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 11653 if (*reply == '\0')
ad91cd99
PA
11654 error (_("Target does not support this command."));
11655 if (strcmp (reply, "OK") != 0)
11656 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
11657 return 0;
11658}
11659
11660/* This is basically a memory transfer, but needs to be its own packet
11661 because we don't know how the target actually organizes its trace
11662 memory, plus we want to be able to ask for as much as possible, but
11663 not be unhappy if we don't get as much as we ask for. */
11664
11665static LONGEST
88ee6f45
TT
11666remote_get_raw_trace_data (struct target_ops *self,
11667 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
11668{
11669 struct remote_state *rs = get_remote_state ();
11670 char *reply;
11671 char *p;
11672 int rslt;
11673
11674 p = rs->buf;
11675 strcpy (p, "qTBuffer:");
11676 p += strlen (p);
11677 p += hexnumstr (p, offset);
11678 *p++ = ',';
11679 p += hexnumstr (p, len);
11680 *p++ = '\0';
11681
11682 putpkt (rs->buf);
11683 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11684 if (reply && *reply)
11685 {
11686 /* 'l' by itself means we're at the end of the buffer and
11687 there is nothing more to get. */
11688 if (*reply == 'l')
11689 return 0;
11690
11691 /* Convert the reply into binary. Limit the number of bytes to
11692 convert according to our passed-in buffer size, rather than
11693 what was returned in the packet; if the target is
11694 unexpectedly generous and gives us a bigger reply than we
11695 asked for, we don't want to crash. */
11696 rslt = hex2bin (target_buf, buf, len);
11697 return rslt;
11698 }
11699
11700 /* Something went wrong, flag as an error. */
11701 return -1;
11702}
11703
35b1e5cc 11704static void
37b25738 11705remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
11706{
11707 struct remote_state *rs = get_remote_state ();
11708
4082afcc 11709 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 11710 {
ad91cd99
PA
11711 char *reply;
11712
bba74b36 11713 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 11714 putpkt (rs->buf);
ad91cd99
PA
11715 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11716 if (*reply == '\0')
33da3f1c 11717 error (_("Target does not support this command."));
ad91cd99
PA
11718 if (strcmp (reply, "OK") != 0)
11719 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
11720 }
11721 else if (val)
11722 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
11723}
11724
dc146f7c
VP
11725static int
11726remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11727{
11728 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 11729
fe978cb0
PA
11730 if (info && info->priv)
11731 return info->priv->core;
dc146f7c
VP
11732 return -1;
11733}
11734
4daf5ac0 11735static void
736d5b1f 11736remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
11737{
11738 struct remote_state *rs = get_remote_state ();
ad91cd99 11739 char *reply;
4daf5ac0 11740
bba74b36 11741 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 11742 putpkt (rs->buf);
ad91cd99
PA
11743 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11744 if (*reply == '\0')
4daf5ac0 11745 error (_("Target does not support this command."));
ad91cd99
PA
11746 if (strcmp (reply, "OK") != 0)
11747 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
11748}
11749
b3b9301e 11750static struct traceframe_info *
a893e81f 11751remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
11752{
11753 char *text;
11754
11755 text = target_read_stralloc (&current_target,
11756 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11757 if (text != NULL)
11758 {
11759 struct traceframe_info *info;
11760 struct cleanup *back_to = make_cleanup (xfree, text);
11761
11762 info = parse_traceframe_info (text);
11763 do_cleanups (back_to);
11764 return info;
11765 }
11766
11767 return NULL;
11768}
11769
405f8e94
SS
11770/* Handle the qTMinFTPILen packet. Returns the minimum length of
11771 instruction on which a fast tracepoint may be placed. Returns -1
11772 if the packet is not supported, and 0 if the minimum instruction
11773 length is unknown. */
11774
11775static int
0e67620a 11776remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
11777{
11778 struct remote_state *rs = get_remote_state ();
11779 char *reply;
11780
e886a173
PA
11781 /* If we're not debugging a process yet, the IPA can't be
11782 loaded. */
11783 if (!target_has_execution)
11784 return 0;
11785
11786 /* Make sure the remote is pointing at the right process. */
11787 set_general_process ();
11788
bba74b36 11789 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
11790 putpkt (rs->buf);
11791 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11792 if (*reply == '\0')
11793 return -1;
11794 else
11795 {
11796 ULONGEST min_insn_len;
11797
11798 unpack_varlen_hex (reply, &min_insn_len);
11799
11800 return (int) min_insn_len;
11801 }
11802}
11803
f6f899bf 11804static void
4da384be 11805remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 11806{
4082afcc 11807 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
11808 {
11809 struct remote_state *rs = get_remote_state ();
11810 char *buf = rs->buf;
11811 char *endbuf = rs->buf + get_remote_packet_size ();
11812 enum packet_result result;
11813
11814 gdb_assert (val >= 0 || val == -1);
11815 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11816 /* Send -1 as literal "-1" to avoid host size dependency. */
11817 if (val < 0)
11818 {
11819 *buf++ = '-';
11820 buf += hexnumstr (buf, (ULONGEST) -val);
11821 }
11822 else
11823 buf += hexnumstr (buf, (ULONGEST) val);
11824
11825 putpkt (rs->buf);
11826 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11827 result = packet_ok (rs->buf,
11828 &remote_protocol_packets[PACKET_QTBuffer_size]);
11829
11830 if (result != PACKET_OK)
11831 warning (_("Bogus reply from target: %s"), rs->buf);
11832 }
11833}
11834
f196051f 11835static int
d9e68a2c
TT
11836remote_set_trace_notes (struct target_ops *self,
11837 const char *user, const char *notes,
ca623f82 11838 const char *stop_notes)
f196051f
SS
11839{
11840 struct remote_state *rs = get_remote_state ();
11841 char *reply;
11842 char *buf = rs->buf;
11843 char *endbuf = rs->buf + get_remote_packet_size ();
11844 int nbytes;
11845
11846 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11847 if (user)
11848 {
11849 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 11850 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
11851 buf += 2 * nbytes;
11852 *buf++ = ';';
11853 }
11854 if (notes)
11855 {
11856 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 11857 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
11858 buf += 2 * nbytes;
11859 *buf++ = ';';
11860 }
11861 if (stop_notes)
11862 {
11863 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 11864 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
11865 buf += 2 * nbytes;
11866 *buf++ = ';';
11867 }
11868 /* Ensure the buffer is terminated. */
11869 *buf = '\0';
11870
11871 putpkt (rs->buf);
11872 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11873 if (*reply == '\0')
11874 return 0;
11875
11876 if (strcmp (reply, "OK") != 0)
11877 error (_("Bogus reply from target: %s"), reply);
11878
11879 return 1;
11880}
11881
d1feda86 11882static int
2c152180 11883remote_use_agent (struct target_ops *self, int use)
d1feda86 11884{
4082afcc 11885 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
11886 {
11887 struct remote_state *rs = get_remote_state ();
11888
11889 /* If the stub supports QAgent. */
bba74b36 11890 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
11891 putpkt (rs->buf);
11892 getpkt (&rs->buf, &rs->buf_size, 0);
11893
11894 if (strcmp (rs->buf, "OK") == 0)
11895 {
11896 use_agent = use;
11897 return 1;
11898 }
11899 }
11900
11901 return 0;
11902}
11903
11904static int
fe38f897 11905remote_can_use_agent (struct target_ops *self)
d1feda86 11906{
4082afcc 11907 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
11908}
11909
9accd112
MM
11910struct btrace_target_info
11911{
11912 /* The ptid of the traced thread. */
11913 ptid_t ptid;
f4abbc16
MM
11914
11915 /* The obtained branch trace configuration. */
11916 struct btrace_config conf;
9accd112
MM
11917};
11918
f4abbc16
MM
11919/* Reset our idea of our target's btrace configuration. */
11920
11921static void
11922remote_btrace_reset (void)
11923{
11924 struct remote_state *rs = get_remote_state ();
11925
11926 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
11927}
11928
9accd112
MM
11929/* Check whether the target supports branch tracing. */
11930
11931static int
043c3577 11932remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 11933{
4082afcc 11934 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 11935 return 0;
4082afcc 11936 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
11937 return 0;
11938
043c3577
MM
11939 switch (format)
11940 {
11941 case BTRACE_FORMAT_NONE:
11942 return 0;
11943
11944 case BTRACE_FORMAT_BTS:
11945 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
b20a6524
MM
11946
11947 case BTRACE_FORMAT_PT:
11948 /* The trace is decoded on the host. Even if our target supports it,
11949 we still need to have libipt to decode the trace. */
11950#if defined (HAVE_LIBIPT)
11951 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
11952#else /* !defined (HAVE_LIBIPT) */
11953 return 0;
11954#endif /* !defined (HAVE_LIBIPT) */
043c3577
MM
11955 }
11956
11957 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
11958}
11959
f4abbc16
MM
11960/* Synchronize the configuration with the target. */
11961
11962static void
11963btrace_sync_conf (const struct btrace_config *conf)
11964{
d33501a5
MM
11965 struct packet_config *packet;
11966 struct remote_state *rs;
11967 char *buf, *pos, *endbuf;
11968
11969 rs = get_remote_state ();
11970 buf = rs->buf;
11971 endbuf = buf + get_remote_packet_size ();
11972
11973 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
11974 if (packet_config_support (packet) == PACKET_ENABLE
11975 && conf->bts.size != rs->btrace_config.bts.size)
11976 {
11977 pos = buf;
11978 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
11979 conf->bts.size);
11980
11981 putpkt (buf);
11982 getpkt (&buf, &rs->buf_size, 0);
11983
11984 if (packet_ok (buf, packet) == PACKET_ERROR)
11985 {
11986 if (buf[0] == 'E' && buf[1] == '.')
11987 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
11988 else
11989 error (_("Failed to configure the BTS buffer size."));
11990 }
11991
11992 rs->btrace_config.bts.size = conf->bts.size;
11993 }
b20a6524
MM
11994
11995 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
11996 if (packet_config_support (packet) == PACKET_ENABLE
11997 && conf->pt.size != rs->btrace_config.pt.size)
11998 {
11999 pos = buf;
12000 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12001 conf->pt.size);
12002
12003 putpkt (buf);
12004 getpkt (&buf, &rs->buf_size, 0);
12005
12006 if (packet_ok (buf, packet) == PACKET_ERROR)
12007 {
12008 if (buf[0] == 'E' && buf[1] == '.')
12009 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12010 else
12011 error (_("Failed to configure the trace buffer size."));
12012 }
12013
12014 rs->btrace_config.pt.size = conf->pt.size;
12015 }
f4abbc16
MM
12016}
12017
12018/* Read the current thread's btrace configuration from the target and
12019 store it into CONF. */
12020
12021static void
12022btrace_read_config (struct btrace_config *conf)
12023{
12024 char *xml;
12025
12026 xml = target_read_stralloc (&current_target,
b20a6524 12027 TARGET_OBJECT_BTRACE_CONF, "");
f4abbc16
MM
12028 if (xml != NULL)
12029 {
12030 struct cleanup *cleanup;
12031
12032 cleanup = make_cleanup (xfree, xml);
12033 parse_xml_btrace_conf (conf, xml);
12034 do_cleanups (cleanup);
12035 }
12036}
12037
9accd112
MM
12038/* Enable branch tracing. */
12039
12040static struct btrace_target_info *
f4abbc16
MM
12041remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12042 const struct btrace_config *conf)
9accd112
MM
12043{
12044 struct btrace_target_info *tinfo = NULL;
b20a6524 12045 struct packet_config *packet = NULL;
9accd112
MM
12046 struct remote_state *rs = get_remote_state ();
12047 char *buf = rs->buf;
12048 char *endbuf = rs->buf + get_remote_packet_size ();
12049
b20a6524
MM
12050 switch (conf->format)
12051 {
12052 case BTRACE_FORMAT_BTS:
12053 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12054 break;
12055
12056 case BTRACE_FORMAT_PT:
12057 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12058 break;
12059 }
12060
12061 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12062 error (_("Target does not support branch tracing."));
12063
f4abbc16
MM
12064 btrace_sync_conf (conf);
12065
9accd112
MM
12066 set_general_thread (ptid);
12067
12068 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12069 putpkt (rs->buf);
12070 getpkt (&rs->buf, &rs->buf_size, 0);
12071
12072 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12073 {
12074 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12075 error (_("Could not enable branch tracing for %s: %s"),
12076 target_pid_to_str (ptid), rs->buf + 2);
12077 else
12078 error (_("Could not enable branch tracing for %s."),
12079 target_pid_to_str (ptid));
12080 }
12081
12082 tinfo = xzalloc (sizeof (*tinfo));
12083 tinfo->ptid = ptid;
12084
f4abbc16
MM
12085 /* If we fail to read the configuration, we lose some information, but the
12086 tracing itself is not impacted. */
492d29ea
PA
12087 TRY
12088 {
12089 btrace_read_config (&tinfo->conf);
12090 }
12091 CATCH (err, RETURN_MASK_ERROR)
12092 {
12093 if (err.message != NULL)
12094 warning ("%s", err.message);
12095 }
12096 END_CATCH
f4abbc16 12097
9accd112
MM
12098 return tinfo;
12099}
12100
12101/* Disable branch tracing. */
12102
12103static void
25e95349
TT
12104remote_disable_btrace (struct target_ops *self,
12105 struct btrace_target_info *tinfo)
9accd112
MM
12106{
12107 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12108 struct remote_state *rs = get_remote_state ();
12109 char *buf = rs->buf;
12110 char *endbuf = rs->buf + get_remote_packet_size ();
12111
4082afcc 12112 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12113 error (_("Target does not support branch tracing."));
12114
12115 set_general_thread (tinfo->ptid);
12116
12117 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12118 putpkt (rs->buf);
12119 getpkt (&rs->buf, &rs->buf_size, 0);
12120
12121 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12122 {
12123 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12124 error (_("Could not disable branch tracing for %s: %s"),
12125 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12126 else
12127 error (_("Could not disable branch tracing for %s."),
12128 target_pid_to_str (tinfo->ptid));
12129 }
12130
12131 xfree (tinfo);
12132}
12133
12134/* Teardown branch tracing. */
12135
12136static void
1777056d
TT
12137remote_teardown_btrace (struct target_ops *self,
12138 struct btrace_target_info *tinfo)
9accd112
MM
12139{
12140 /* We must not talk to the target during teardown. */
12141 xfree (tinfo);
12142}
12143
12144/* Read the branch trace. */
12145
969c39fb 12146static enum btrace_error
39c49f83 12147remote_read_btrace (struct target_ops *self,
734b0e4b 12148 struct btrace_data *btrace,
969c39fb 12149 struct btrace_target_info *tinfo,
9accd112
MM
12150 enum btrace_read_type type)
12151{
12152 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12153 struct remote_state *rs = get_remote_state ();
969c39fb 12154 struct cleanup *cleanup;
9accd112
MM
12155 const char *annex;
12156 char *xml;
12157
4082afcc 12158 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12159 error (_("Target does not support branch tracing."));
12160
12161#if !defined(HAVE_LIBEXPAT)
12162 error (_("Cannot process branch tracing result. XML parsing not supported."));
12163#endif
12164
12165 switch (type)
12166 {
864089d2 12167 case BTRACE_READ_ALL:
9accd112
MM
12168 annex = "all";
12169 break;
864089d2 12170 case BTRACE_READ_NEW:
9accd112
MM
12171 annex = "new";
12172 break;
969c39fb
MM
12173 case BTRACE_READ_DELTA:
12174 annex = "delta";
12175 break;
9accd112
MM
12176 default:
12177 internal_error (__FILE__, __LINE__,
12178 _("Bad branch tracing read type: %u."),
12179 (unsigned int) type);
12180 }
12181
12182 xml = target_read_stralloc (&current_target,
b20a6524 12183 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
12184 if (xml == NULL)
12185 return BTRACE_ERR_UNKNOWN;
9accd112 12186
969c39fb 12187 cleanup = make_cleanup (xfree, xml);
734b0e4b 12188 parse_xml_btrace (btrace, xml);
969c39fb 12189 do_cleanups (cleanup);
9accd112 12190
969c39fb 12191 return BTRACE_ERR_NONE;
9accd112
MM
12192}
12193
f4abbc16
MM
12194static const struct btrace_config *
12195remote_btrace_conf (struct target_ops *self,
12196 const struct btrace_target_info *tinfo)
12197{
12198 return &tinfo->conf;
12199}
12200
ced63ec0 12201static int
5436ff03 12202remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 12203{
4082afcc
PA
12204 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12205 == PACKET_ENABLE);
ced63ec0
GB
12206}
12207
9dd130a0
TT
12208/* Implementation of to_load. */
12209
12210static void
9cbe5fff 12211remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
12212{
12213 generic_load (name, from_tty);
12214}
12215
c78fa86a
GB
12216/* Accepts an integer PID; returns a string representing a file that
12217 can be opened on the remote side to get the symbols for the child
12218 process. Returns NULL if the operation is not supported. */
12219
12220static char *
12221remote_pid_to_exec_file (struct target_ops *self, int pid)
12222{
12223 static char *filename = NULL;
835205d0
GB
12224 struct inferior *inf;
12225 char *annex = NULL;
c78fa86a
GB
12226
12227 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12228 return NULL;
12229
12230 if (filename != NULL)
12231 xfree (filename);
12232
835205d0
GB
12233 inf = find_inferior_pid (pid);
12234 if (inf == NULL)
12235 internal_error (__FILE__, __LINE__,
12236 _("not currently attached to process %d"), pid);
12237
12238 if (!inf->fake_pid_p)
12239 {
12240 const int annex_size = 9;
12241
12242 annex = alloca (annex_size);
12243 xsnprintf (annex, annex_size, "%x", pid);
12244 }
12245
c78fa86a
GB
12246 filename = target_read_stralloc (&current_target,
12247 TARGET_OBJECT_EXEC_FILE, annex);
12248
12249 return filename;
12250}
12251
c906108c 12252static void
fba45db2 12253init_remote_ops (void)
c906108c 12254{
c5aa993b 12255 remote_ops.to_shortname = "remote";
c906108c 12256 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 12257 remote_ops.to_doc =
c906108c 12258 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
12259Specify the serial device it is connected to\n\
12260(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
12261 remote_ops.to_open = remote_open;
12262 remote_ops.to_close = remote_close;
c906108c 12263 remote_ops.to_detach = remote_detach;
6ad8ae5c 12264 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 12265 remote_ops.to_resume = remote_resume;
c906108c
SS
12266 remote_ops.to_wait = remote_wait;
12267 remote_ops.to_fetch_registers = remote_fetch_registers;
12268 remote_ops.to_store_registers = remote_store_registers;
12269 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 12270 remote_ops.to_files_info = remote_files_info;
c906108c
SS
12271 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12272 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
12273 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12274 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12275 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12276 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
12277 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12278 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
12279 remote_ops.to_watchpoint_addr_within_range =
12280 remote_watchpoint_addr_within_range;
3c3bea1c
GS
12281 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12282 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12283 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
12284 remote_ops.to_region_ok_for_hw_watchpoint
12285 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
12286 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12287 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 12288 remote_ops.to_kill = remote_kill;
9dd130a0 12289 remote_ops.to_load = remote_load;
c906108c 12290 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 12291 remote_ops.to_pass_signals = remote_pass_signals;
9b224c5e 12292 remote_ops.to_program_signals = remote_program_signals;
c906108c 12293 remote_ops.to_thread_alive = remote_thread_alive;
e8032dde 12294 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 12295 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 12296 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 12297 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 12298 remote_ops.to_stop = remote_stop;
bfedc46a 12299 remote_ops.to_interrupt = remote_interrupt;
4b8a223f 12300 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 12301 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 12302 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 12303 remote_ops.to_log_command = serial_log_command;
38691318 12304 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 12305 remote_ops.to_stratum = process_stratum;
c35b1492
PA
12306 remote_ops.to_has_all_memory = default_child_has_all_memory;
12307 remote_ops.to_has_memory = default_child_has_memory;
12308 remote_ops.to_has_stack = default_child_has_stack;
12309 remote_ops.to_has_registers = default_child_has_registers;
12310 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 12311 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 12312 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 12313 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 12314 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
12315 remote_ops.to_flash_erase = remote_flash_erase;
12316 remote_ops.to_flash_done = remote_flash_done;
29709017 12317 remote_ops.to_read_description = remote_read_description;
08388c79 12318 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
12319 remote_ops.to_can_async_p = remote_can_async_p;
12320 remote_ops.to_is_async_p = remote_is_async_p;
12321 remote_ops.to_async = remote_async;
75c99385
PA
12322 remote_ops.to_terminal_inferior = remote_terminal_inferior;
12323 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 12324 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 12325 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
12326 remote_ops.to_supports_disable_randomization
12327 = remote_supports_disable_randomization;
4bd7dc42 12328 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
12329 remote_ops.to_fileio_open = remote_hostio_open;
12330 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
12331 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 12332 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
12333 remote_ops.to_fileio_close = remote_hostio_close;
12334 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 12335 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 12336 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 12337 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 12338 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 12339 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
12340 remote_ops.to_trace_init = remote_trace_init;
12341 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 12342 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
12343 remote_ops.to_download_trace_state_variable
12344 = remote_download_trace_state_variable;
d248b706
KY
12345 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
12346 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
12347 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
12348 remote_ops.to_trace_start = remote_trace_start;
12349 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 12350 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
12351 remote_ops.to_trace_stop = remote_trace_stop;
12352 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
12353 remote_ops.to_get_trace_state_variable_value
12354 = remote_get_trace_state_variable_value;
00bf0b85
SS
12355 remote_ops.to_save_trace_data = remote_save_trace_data;
12356 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
12357 remote_ops.to_upload_trace_state_variables
12358 = remote_upload_trace_state_variables;
00bf0b85 12359 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 12360 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 12361 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 12362 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 12363 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 12364 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 12365 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 12366 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 12367 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 12368 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
12369 remote_ops.to_static_tracepoint_marker_at
12370 = remote_static_tracepoint_marker_at;
12371 remote_ops.to_static_tracepoint_markers_by_strid
12372 = remote_static_tracepoint_markers_by_strid;
b3b9301e 12373 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
12374 remote_ops.to_use_agent = remote_use_agent;
12375 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
12376 remote_ops.to_supports_btrace = remote_supports_btrace;
12377 remote_ops.to_enable_btrace = remote_enable_btrace;
12378 remote_ops.to_disable_btrace = remote_disable_btrace;
12379 remote_ops.to_teardown_btrace = remote_teardown_btrace;
12380 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 12381 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
12382 remote_ops.to_augmented_libraries_svr4_read =
12383 remote_augmented_libraries_svr4_read;
c906108c
SS
12384}
12385
12386/* Set up the extended remote vector by making a copy of the standard
12387 remote vector and adding to it. */
12388
12389static void
fba45db2 12390init_extended_remote_ops (void)
c906108c
SS
12391{
12392 extended_remote_ops = remote_ops;
12393
0f71a2f6 12394 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 12395 extended_remote_ops.to_longname =
c906108c 12396 "Extended remote serial target in gdb-specific protocol";
c5aa993b 12397 extended_remote_ops.to_doc =
c906108c 12398 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
12399Specify the serial device it is connected to (e.g. /dev/ttya).";
12400 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
12401 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
12402 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
12403 extended_remote_ops.to_detach = extended_remote_detach;
12404 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 12405 extended_remote_ops.to_post_attach = extended_remote_post_attach;
82f73884 12406 extended_remote_ops.to_kill = extended_remote_kill;
03583c20
UW
12407 extended_remote_ops.to_supports_disable_randomization
12408 = extended_remote_supports_disable_randomization;
de0d863e 12409 extended_remote_ops.to_follow_fork = remote_follow_fork;
cbb8991c
DB
12410 extended_remote_ops.to_insert_fork_catchpoint
12411 = remote_insert_fork_catchpoint;
12412 extended_remote_ops.to_remove_fork_catchpoint
12413 = remote_remove_fork_catchpoint;
12414 extended_remote_ops.to_insert_vfork_catchpoint
12415 = remote_insert_vfork_catchpoint;
12416 extended_remote_ops.to_remove_vfork_catchpoint
12417 = remote_remove_vfork_catchpoint;
0f71a2f6
JM
12418}
12419
6426a772 12420static int
6a109b6b 12421remote_can_async_p (struct target_ops *ops)
6426a772 12422{
5d93a237
TT
12423 struct remote_state *rs = get_remote_state ();
12424
c6ebd6cf 12425 if (!target_async_permitted)
75c99385
PA
12426 /* We only enable async when the user specifically asks for it. */
12427 return 0;
12428
23860348 12429 /* We're async whenever the serial device is. */
5d93a237 12430 return serial_can_async_p (rs->remote_desc);
6426a772
JM
12431}
12432
12433static int
6a109b6b 12434remote_is_async_p (struct target_ops *ops)
6426a772 12435{
5d93a237
TT
12436 struct remote_state *rs = get_remote_state ();
12437
c6ebd6cf 12438 if (!target_async_permitted)
75c99385
PA
12439 /* We only enable async when the user specifically asks for it. */
12440 return 0;
12441
23860348 12442 /* We're async whenever the serial device is. */
5d93a237 12443 return serial_is_async_p (rs->remote_desc);
6426a772
JM
12444}
12445
2acceee2
JM
12446/* Pass the SERIAL event on and up to the client. One day this code
12447 will be able to delay notifying the client of an event until the
23860348 12448 point where an entire packet has been received. */
2acceee2 12449
2acceee2
JM
12450static serial_event_ftype remote_async_serial_handler;
12451
6426a772 12452static void
819cc324 12453remote_async_serial_handler (struct serial *scb, void *context)
6426a772 12454{
88b496c3
TT
12455 struct remote_state *rs = context;
12456
2acceee2
JM
12457 /* Don't propogate error information up to the client. Instead let
12458 the client find out about the error by querying the target. */
6a3753b3 12459 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
12460}
12461
74531fed
PA
12462static void
12463remote_async_inferior_event_handler (gdb_client_data data)
12464{
12465 inferior_event_handler (INF_REG_EVENT, NULL);
12466}
12467
2acceee2 12468static void
6a3753b3 12469remote_async (struct target_ops *ops, int enable)
2acceee2 12470{
5d93a237
TT
12471 struct remote_state *rs = get_remote_state ();
12472
6a3753b3 12473 if (enable)
2acceee2 12474 {
88b496c3 12475 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
12476
12477 /* If there are pending events in the stop reply queue tell the
12478 event loop to process them. */
12479 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
12480 mark_async_event_handler (remote_async_inferior_event_token);
2acceee2
JM
12481 }
12482 else
b7d2e916
PA
12483 {
12484 serial_async (rs->remote_desc, NULL, NULL);
12485 clear_async_event_handler (remote_async_inferior_event_token);
12486 }
6426a772
JM
12487}
12488
5a2468f5 12489static void
c2d11a7d 12490set_remote_cmd (char *args, int from_tty)
5a2468f5 12491{
635c7e8a 12492 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
12493}
12494
d471ea57
AC
12495static void
12496show_remote_cmd (char *args, int from_tty)
12497{
37a105a1 12498 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 12499 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
12500 struct cleanup *showlist_chain;
12501 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 12502 struct ui_out *uiout = current_uiout;
37a105a1
DJ
12503
12504 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
12505 for (; list != NULL; list = list->next)
12506 if (strcmp (list->name, "Z-packet") == 0)
12507 continue;
427c3a89
DJ
12508 else if (list->type == not_set_cmd)
12509 /* Alias commands are exactly like the original, except they
12510 don't have the normal type. */
12511 continue;
12512 else
37a105a1
DJ
12513 {
12514 struct cleanup *option_chain
12515 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 12516
37a105a1
DJ
12517 ui_out_field_string (uiout, "name", list->name);
12518 ui_out_text (uiout, ": ");
427c3a89 12519 if (list->type == show_cmd)
5b9afe8a 12520 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
12521 else
12522 cmd_func (list, NULL, from_tty);
37a105a1
DJ
12523 /* Close the tuple. */
12524 do_cleanups (option_chain);
12525 }
427c3a89
DJ
12526
12527 /* Close the tuple. */
12528 do_cleanups (showlist_chain);
d471ea57 12529}
5a2468f5 12530
0f71a2f6 12531
23860348 12532/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
12533static void
12534remote_new_objfile (struct objfile *objfile)
12535{
5d93a237
TT
12536 struct remote_state *rs = get_remote_state ();
12537
12538 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 12539 remote_check_symbols ();
dc8acb97
MS
12540}
12541
00bf0b85
SS
12542/* Pull all the tracepoints defined on the target and create local
12543 data structures representing them. We don't want to create real
12544 tracepoints yet, we don't want to mess up the user's existing
12545 collection. */
12546
12547static int
ab6617cc 12548remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 12549{
00bf0b85
SS
12550 struct remote_state *rs = get_remote_state ();
12551 char *p;
d5551862 12552
00bf0b85
SS
12553 /* Ask for a first packet of tracepoint definition. */
12554 putpkt ("qTfP");
12555 getpkt (&rs->buf, &rs->buf_size, 0);
12556 p = rs->buf;
12557 while (*p && *p != 'l')
d5551862 12558 {
00bf0b85
SS
12559 parse_tracepoint_definition (p, utpp);
12560 /* Ask for another packet of tracepoint definition. */
12561 putpkt ("qTsP");
12562 getpkt (&rs->buf, &rs->buf_size, 0);
12563 p = rs->buf;
d5551862 12564 }
00bf0b85 12565 return 0;
d5551862
SS
12566}
12567
00bf0b85 12568static int
181e3713
TT
12569remote_upload_trace_state_variables (struct target_ops *self,
12570 struct uploaded_tsv **utsvp)
d5551862 12571{
00bf0b85 12572 struct remote_state *rs = get_remote_state ();
d5551862 12573 char *p;
d5551862 12574
00bf0b85
SS
12575 /* Ask for a first packet of variable definition. */
12576 putpkt ("qTfV");
d5551862
SS
12577 getpkt (&rs->buf, &rs->buf_size, 0);
12578 p = rs->buf;
00bf0b85 12579 while (*p && *p != 'l')
d5551862 12580 {
00bf0b85
SS
12581 parse_tsv_definition (p, utsvp);
12582 /* Ask for another packet of variable definition. */
12583 putpkt ("qTsV");
d5551862
SS
12584 getpkt (&rs->buf, &rs->buf_size, 0);
12585 p = rs->buf;
12586 }
00bf0b85 12587 return 0;
d5551862
SS
12588}
12589
c1e36e3e
PA
12590/* The "set/show range-stepping" show hook. */
12591
12592static void
12593show_range_stepping (struct ui_file *file, int from_tty,
12594 struct cmd_list_element *c,
12595 const char *value)
12596{
12597 fprintf_filtered (file,
12598 _("Debugger's willingness to use range stepping "
12599 "is %s.\n"), value);
12600}
12601
12602/* The "set/show range-stepping" set hook. */
12603
12604static void
12605set_range_stepping (char *ignore_args, int from_tty,
12606 struct cmd_list_element *c)
12607{
5d93a237
TT
12608 struct remote_state *rs = get_remote_state ();
12609
c1e36e3e
PA
12610 /* Whene enabling, check whether range stepping is actually
12611 supported by the target, and warn if not. */
12612 if (use_range_stepping)
12613 {
5d93a237 12614 if (rs->remote_desc != NULL)
c1e36e3e 12615 {
4082afcc 12616 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
12617 remote_vcont_probe (rs);
12618
4082afcc 12619 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
12620 && rs->supports_vCont.r)
12621 return;
12622 }
12623
12624 warning (_("Range stepping is not supported by the current target"));
12625 }
12626}
12627
c906108c 12628void
fba45db2 12629_initialize_remote (void)
c906108c 12630{
ea9c271d 12631 struct remote_state *rs;
9a7071a8 12632 struct cmd_list_element *cmd;
6f937416 12633 const char *cmd_name;
ea9c271d 12634
0f71a2f6 12635 /* architecture specific data */
2bc416ba 12636 remote_gdbarch_data_handle =
23860348 12637 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
12638 remote_g_packet_data_handle =
12639 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 12640
ea9c271d
DJ
12641 /* Initialize the per-target state. At the moment there is only one
12642 of these, not one per target. Only one target is active at a
cf792862
TT
12643 time. */
12644 remote_state = new_remote_state ();
ea9c271d 12645
c906108c
SS
12646 init_remote_ops ();
12647 add_target (&remote_ops);
12648
12649 init_extended_remote_ops ();
12650 add_target (&extended_remote_ops);
cce74817 12651
dc8acb97 12652 /* Hook into new objfile notification. */
06d3b283 12653 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
12654 /* We're no longer interested in notification events of an inferior
12655 when it exits. */
12656 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 12657
b803fb0f 12658 /* Set up signal handlers. */
934b9bac 12659 async_sigint_remote_token =
b803fb0f 12660 create_async_signal_handler (async_remote_interrupt, NULL);
934b9bac 12661 async_sigint_remote_twice_token =
6d549500 12662 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 12663
c906108c
SS
12664#if 0
12665 init_remote_threadtests ();
12666#endif
12667
722247f1 12668 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 12669 /* set/show remote ... */
d471ea57 12670
1bedd215 12671 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
12672Remote protocol specific variables\n\
12673Configure various remote-protocol specific variables such as\n\
1bedd215 12674the packets being used"),
cff3e48b 12675 &remote_set_cmdlist, "set remote ",
23860348 12676 0 /* allow-unknown */, &setlist);
1bedd215 12677 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
12678Remote protocol specific variables\n\
12679Configure various remote-protocol specific variables such as\n\
1bedd215 12680the packets being used"),
cff3e48b 12681 &remote_show_cmdlist, "show remote ",
23860348 12682 0 /* allow-unknown */, &showlist);
5a2468f5 12683
1a966eab
AC
12684 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
12685Compare section data on target to the exec file.\n\
95cf3b38
DT
12686Argument is a single section name (default: all loaded sections).\n\
12687To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
12688 &cmdlist);
12689
1a966eab
AC
12690 add_cmd ("packet", class_maintenance, packet_command, _("\
12691Send an arbitrary packet to a remote target.\n\
c906108c
SS
12692 maintenance packet TEXT\n\
12693If GDB is talking to an inferior via the GDB serial protocol, then\n\
12694this command sends the string TEXT to the inferior, and displays the\n\
12695response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 12696terminating `#' character and checksum."),
c906108c
SS
12697 &maintenancelist);
12698
7915a72c
AC
12699 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
12700Set whether to send break if interrupted."), _("\
12701Show whether to send break if interrupted."), _("\
12702If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 12703 set_remotebreak, show_remotebreak,
e707bbc2 12704 &setlist, &showlist);
9a7071a8
JB
12705 cmd_name = "remotebreak";
12706 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
12707 deprecate_cmd (cmd, "set remote interrupt-sequence");
12708 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
12709 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
12710 deprecate_cmd (cmd, "show remote interrupt-sequence");
12711
12712 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
12713 interrupt_sequence_modes, &interrupt_sequence_mode,
12714 _("\
9a7071a8
JB
12715Set interrupt sequence to remote target."), _("\
12716Show interrupt sequence to remote target."), _("\
12717Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
12718 NULL, show_interrupt_sequence,
12719 &remote_set_cmdlist,
12720 &remote_show_cmdlist);
12721
12722 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
12723 &interrupt_on_connect, _("\
12724Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12725Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12726If set, interrupt sequence is sent to remote target."),
12727 NULL, NULL,
12728 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 12729
23860348 12730 /* Install commands for configuring memory read/write packets. */
11cf8741 12731
1a966eab
AC
12732 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
12733Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 12734 &setlist);
1a966eab
AC
12735 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
12736Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
12737 &showlist);
12738 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
12739 set_memory_write_packet_size, _("\
12740Set the maximum number of bytes per memory-write packet.\n\
12741Specify the number of bytes in a packet or 0 (zero) for the\n\
12742default packet size. The actual limit is further reduced\n\
12743dependent on the target. Specify ``fixed'' to disable the\n\
12744further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
12745 &remote_set_cmdlist);
12746 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
12747 set_memory_read_packet_size, _("\
12748Set the maximum number of bytes per memory-read packet.\n\
12749Specify the number of bytes in a packet or 0 (zero) for the\n\
12750default packet size. The actual limit is further reduced\n\
12751dependent on the target. Specify ``fixed'' to disable the\n\
12752further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
12753 &remote_set_cmdlist);
12754 add_cmd ("memory-write-packet-size", no_class,
12755 show_memory_write_packet_size,
1a966eab 12756 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
12757 &remote_show_cmdlist);
12758 add_cmd ("memory-read-packet-size", no_class,
12759 show_memory_read_packet_size,
1a966eab 12760 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 12761 &remote_show_cmdlist);
c906108c 12762
b3f42336 12763 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
12764 &remote_hw_watchpoint_limit, _("\
12765Set the maximum number of target hardware watchpoints."), _("\
12766Show the maximum number of target hardware watchpoints."), _("\
12767Specify a negative limit for unlimited."),
3e43a32a
MS
12768 NULL, NULL, /* FIXME: i18n: The maximum
12769 number of target hardware
12770 watchpoints is %s. */
b3f42336 12771 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
12772 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
12773 &remote_hw_watchpoint_length_limit, _("\
12774Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
12775Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
12776Specify a negative limit for unlimited."),
12777 NULL, NULL, /* FIXME: i18n: The maximum
12778 length (in bytes) of a target
12779 hardware watchpoint is %s. */
12780 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 12781 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
12782 &remote_hw_breakpoint_limit, _("\
12783Set the maximum number of target hardware breakpoints."), _("\
12784Show the maximum number of target hardware breakpoints."), _("\
12785Specify a negative limit for unlimited."),
3e43a32a
MS
12786 NULL, NULL, /* FIXME: i18n: The maximum
12787 number of target hardware
12788 breakpoints is %s. */
b3f42336 12789 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 12790
1b493192
PA
12791 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
12792 &remote_address_size, _("\
4d28ad1e
AC
12793Set the maximum size of the address (in bits) in a memory packet."), _("\
12794Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
12795 NULL,
12796 NULL, /* FIXME: i18n: */
12797 &setlist, &showlist);
c906108c 12798
ca4f7f8b
PA
12799 init_all_packet_configs ();
12800
444abaca 12801 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 12802 "X", "binary-download", 1);
0f71a2f6 12803
444abaca 12804 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 12805 "vCont", "verbose-resume", 0);
506fb367 12806
89be2091
DJ
12807 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
12808 "QPassSignals", "pass-signals", 0);
12809
9b224c5e
PA
12810 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
12811 "QProgramSignals", "program-signals", 0);
12812
444abaca 12813 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 12814 "qSymbol", "symbol-lookup", 0);
dc8acb97 12815
444abaca 12816 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 12817 "P", "set-register", 1);
d471ea57 12818
444abaca 12819 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 12820 "p", "fetch-register", 1);
b96ec7ac 12821
444abaca 12822 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 12823 "Z0", "software-breakpoint", 0);
d471ea57 12824
444abaca 12825 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 12826 "Z1", "hardware-breakpoint", 0);
d471ea57 12827
444abaca 12828 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 12829 "Z2", "write-watchpoint", 0);
d471ea57 12830
444abaca 12831 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 12832 "Z3", "read-watchpoint", 0);
d471ea57 12833
444abaca 12834 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 12835 "Z4", "access-watchpoint", 0);
d471ea57 12836
0876f84a
DJ
12837 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
12838 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 12839
c78fa86a
GB
12840 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
12841 "qXfer:exec-file:read", "pid-to-exec-file", 0);
12842
23181151
DJ
12843 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
12844 "qXfer:features:read", "target-features", 0);
12845
cfa9d6d9
DJ
12846 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
12847 "qXfer:libraries:read", "library-info", 0);
12848
2268b414
JK
12849 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12850 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12851
fd79ecee
DJ
12852 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12853 "qXfer:memory-map:read", "memory-map", 0);
12854
0e7f50da
UW
12855 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12856 "qXfer:spu:read", "read-spu-object", 0);
12857
12858 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12859 "qXfer:spu:write", "write-spu-object", 0);
12860
07e059b5
VP
12861 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12862 "qXfer:osdata:read", "osdata", 0);
12863
dc146f7c
VP
12864 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12865 "qXfer:threads:read", "threads", 0);
12866
4aa995e1
PA
12867 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12868 "qXfer:siginfo:read", "read-siginfo-object", 0);
12869
12870 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12871 "qXfer:siginfo:write", "write-siginfo-object", 0);
12872
b3b9301e
PA
12873 add_packet_config_cmd
12874 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 12875 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 12876
169081d0
TG
12877 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12878 "qXfer:uib:read", "unwind-info-block", 0);
12879
444abaca 12880 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 12881 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
12882 0);
12883
711e434b
PM
12884 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12885 "qGetTIBAddr", "get-thread-information-block-address",
12886 0);
12887
40ab02ce
MS
12888 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12889 "bc", "reverse-continue", 0);
12890
12891 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12892 "bs", "reverse-step", 0);
12893
be2a5f71
DJ
12894 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12895 "qSupported", "supported-packets", 0);
12896
08388c79
DE
12897 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12898 "qSearch:memory", "search-memory", 0);
12899
bd3eecc3
PA
12900 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12901 "qTStatus", "trace-status", 0);
12902
15a201c8
GB
12903 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
12904 "vFile:setfs", "hostio-setfs", 0);
12905
a6b151f1
DJ
12906 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12907 "vFile:open", "hostio-open", 0);
12908
12909 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12910 "vFile:pread", "hostio-pread", 0);
12911
12912 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12913 "vFile:pwrite", "hostio-pwrite", 0);
12914
12915 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12916 "vFile:close", "hostio-close", 0);
12917
12918 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12919 "vFile:unlink", "hostio-unlink", 0);
12920
b9e7b9c3
UW
12921 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12922 "vFile:readlink", "hostio-readlink", 0);
12923
0a93529c
GB
12924 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
12925 "vFile:fstat", "hostio-fstat", 0);
12926
2d717e4f
DJ
12927 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12928 "vAttach", "attach", 0);
12929
12930 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12931 "vRun", "run", 0);
12932
a6f3e723
SL
12933 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12934 "QStartNoAckMode", "noack", 0);
12935
82f73884
PA
12936 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12937 "vKill", "kill", 0);
12938
0b16c5cf
PA
12939 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12940 "qAttached", "query-attached", 0);
12941
782b2b07 12942 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
12943 "ConditionalTracepoints",
12944 "conditional-tracepoints", 0);
3788aec7
LM
12945
12946 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12947 "ConditionalBreakpoints",
12948 "conditional-breakpoints", 0);
12949
d3ce09f5
SS
12950 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12951 "BreakpointCommands",
12952 "breakpoint-commands", 0);
12953
7a697b8d
SS
12954 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12955 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 12956
409873ef
SS
12957 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12958 "TracepointSource", "TracepointSource", 0);
12959
d914c394
SS
12960 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12961 "QAllow", "allow", 0);
12962
0fb4aa4b
PA
12963 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12964 "StaticTracepoints", "static-tracepoints", 0);
12965
1e4d1764
YQ
12966 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12967 "InstallInTrace", "install-in-trace", 0);
12968
0fb4aa4b
PA
12969 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12970 "qXfer:statictrace:read", "read-sdata-object", 0);
12971
78d85199
YQ
12972 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12973 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12974
03583c20
UW
12975 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12976 "QDisableRandomization", "disable-randomization", 0);
12977
d1feda86
YQ
12978 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12979 "QAgent", "agent", 0);
12980
f6f899bf
HAQ
12981 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12982 "QTBuffer:size", "trace-buffer-size", 0);
12983
9accd112
MM
12984 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12985 "Qbtrace:off", "disable-btrace", 0);
12986
12987 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
12988 "Qbtrace:bts", "enable-btrace-bts", 0);
12989
12990 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
12991 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
12992
12993 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12994 "qXfer:btrace", "read-btrace", 0);
12995
f4abbc16
MM
12996 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
12997 "qXfer:btrace-conf", "read-btrace-conf", 0);
12998
d33501a5
MM
12999 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13000 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13001
f7e6eed5
PA
13002 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13003 "swbreak-feature", "swbreak-feature", 0);
13004
13005 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13006 "hwbreak-feature", "hwbreak-feature", 0);
13007
89245bc0
DB
13008 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13009 "fork-event-feature", "fork-event-feature", 0);
13010
13011 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13012 "vfork-event-feature", "vfork-event-feature", 0);
13013
b20a6524
MM
13014 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13015 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13016
0b736949
DB
13017 /* Assert that we've registered "set remote foo-packet" commands
13018 for all packet configs. */
ca4f7f8b
PA
13019 {
13020 int i;
13021
13022 for (i = 0; i < PACKET_MAX; i++)
13023 {
13024 /* Ideally all configs would have a command associated. Some
13025 still don't though. */
13026 int excepted;
13027
13028 switch (i)
13029 {
13030 case PACKET_QNonStop:
13031 case PACKET_multiprocess_feature:
13032 case PACKET_EnableDisableTracepoints_feature:
13033 case PACKET_tracenz_feature:
13034 case PACKET_DisconnectedTracing_feature:
13035 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
13036 case PACKET_qCRC:
13037 /* Additions to this list need to be well justified:
13038 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
13039 excepted = 1;
13040 break;
13041 default:
13042 excepted = 0;
13043 break;
13044 }
13045
13046 /* This catches both forgetting to add a config command, and
13047 forgetting to remove a packet from the exception list. */
13048 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13049 }
13050 }
13051
37a105a1
DJ
13052 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13053 Z sub-packet has its own set and show commands, but users may
13054 have sets to this variable in their .gdbinit files (or in their
13055 documentation). */
e9e68a56 13056 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
13057 &remote_Z_packet_detect, _("\
13058Set use of remote protocol `Z' packets"), _("\
13059Show use of remote protocol `Z' packets "), _("\
3b64bf98 13060When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 13061packets."),
e9e68a56 13062 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
13063 show_remote_protocol_Z_packet_cmd,
13064 /* FIXME: i18n: Use of remote protocol
13065 `Z' packets is %s. */
e9e68a56 13066 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 13067
a6b151f1
DJ
13068 add_prefix_cmd ("remote", class_files, remote_command, _("\
13069Manipulate files on the remote system\n\
13070Transfer files to and from the remote target system."),
13071 &remote_cmdlist, "remote ",
13072 0 /* allow-unknown */, &cmdlist);
13073
13074 add_cmd ("put", class_files, remote_put_command,
13075 _("Copy a local file to the remote system."),
13076 &remote_cmdlist);
13077
13078 add_cmd ("get", class_files, remote_get_command,
13079 _("Copy a remote file to the local system."),
13080 &remote_cmdlist);
13081
13082 add_cmd ("delete", class_files, remote_delete_command,
13083 _("Delete a remote file."),
13084 &remote_cmdlist);
13085
2d717e4f
DJ
13086 remote_exec_file = xstrdup ("");
13087 add_setshow_string_noescape_cmd ("exec-file", class_files,
13088 &remote_exec_file, _("\
13089Set the remote pathname for \"run\""), _("\
13090Show the remote pathname for \"run\""), NULL, NULL, NULL,
13091 &remote_set_cmdlist, &remote_show_cmdlist);
13092
c1e36e3e
PA
13093 add_setshow_boolean_cmd ("range-stepping", class_run,
13094 &use_range_stepping, _("\
13095Enable or disable range stepping."), _("\
13096Show whether target-assisted range stepping is enabled."), _("\
13097If on, and the target supports it, when stepping a source line, GDB\n\
13098tells the target to step the corresponding range of addresses itself instead\n\
13099of issuing multiple single-steps. This speeds up source level\n\
13100stepping. If off, GDB always issues single-steps, even if range\n\
13101stepping is supported by the target. The default is on."),
13102 set_range_stepping,
13103 show_range_stepping,
13104 &setlist,
13105 &showlist);
13106
449092f6
CV
13107 /* Eventually initialize fileio. See fileio.c */
13108 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 13109
ba348170 13110 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 13111 special ptids with it set to != 0. */
ba348170
PA
13112 magic_null_ptid = ptid_build (42000, -1, 1);
13113 not_sent_ptid = ptid_build (42000, -2, 1);
13114 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
13115
13116 target_buf_size = 2048;
13117 target_buf = xmalloc (target_buf_size);
c906108c 13118}
10760264 13119
This page took 3.121464 seconds and 4 git commands to generate.