]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
Implement qXfer:exec-file:read in gdbserver
[thirdparty/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
32d0add0 3 Copyright (C) 1988-2015 Free Software Foundation, Inc.
c906108c 4
c5aa993b
JM
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
c5aa993b
JM
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5aa993b 19
23860348 20/* See the GDB User Guide for details of the GDB remote protocol. */
c5aa993b 21
c906108c 22#include "defs.h"
c906108c
SS
23#include <ctype.h>
24#include <fcntl.h>
c906108c 25#include "inferior.h"
45741a9c 26#include "infrun.h"
c906108c
SS
27#include "bfd.h"
28#include "symfile.h"
29#include "target.h"
c5aa993b 30/*#include "terminal.h" */
c906108c
SS
31#include "gdbcmd.h"
32#include "objfiles.h"
33#include "gdb-stabs.h"
34#include "gdbthread.h"
c2c6d25f 35#include "remote.h"
722247f1 36#include "remote-notif.h"
4e052eda 37#include "regcache.h"
fd0407d6 38#include "value.h"
6867ae3e 39#include "observer.h"
a77053c2 40#include "solib.h"
37a105a1
DJ
41#include "cli/cli-decode.h"
42#include "cli/cli-setshow.h"
424163ea 43#include "target-descriptions.h"
a4453b7e 44#include "gdb_bfd.h"
614c279d 45#include "filestuff.h"
9c3d6531 46#include "rsp-low.h"
c906108c 47
9846de1b 48#include <sys/time.h>
c906108c 49
43ff13b4 50#include "event-loop.h"
c2c6d25f 51#include "event-top.h"
2acceee2 52#include "inf-loop.h"
43ff13b4 53
c906108c
SS
54#include <signal.h>
55#include "serial.h"
56
6240bebf
MS
57#include "gdbcore.h" /* for exec_bfd */
58
449092f6 59#include "remote-fileio.h"
a6b151f1 60#include "gdb/fileio.h"
53ce3c39 61#include <sys/stat.h>
dc146f7c 62#include "xml-support.h"
449092f6 63
fd79ecee
DJ
64#include "memory-map.h"
65
35b1e5cc
SS
66#include "tracepoint.h"
67#include "ax.h"
68#include "ax-gdb.h"
d1feda86 69#include "agent.h"
9accd112 70#include "btrace.h"
35b1e5cc 71
0df8b418 72/* Temp hacks for tracepoint encoding migration. */
35b1e5cc
SS
73static char *target_buf;
74static long target_buf_size;
35b1e5cc 75
6765f3e5
DJ
76/* The size to align memory write packets, when practical. The protocol
77 does not guarantee any alignment, and gdb will generate short
78 writes and unaligned writes, but even as a best-effort attempt this
79 can improve bulk transfers. For instance, if a write is misaligned
80 relative to the target's data bus, the stub may need to make an extra
81 round trip fetching data from the target. This doesn't make a
82 huge difference, but it's easy to do, so we try to be helpful.
83
84 The alignment chosen is arbitrary; usually data bus width is
85 important here, not the possibly larger cache line size. */
86enum { REMOTE_ALIGN_WRITES = 16 };
87
23860348 88/* Prototypes for local functions. */
934b9bac 89static void async_cleanup_sigint_signal_handler (void *dummy);
6d820c5c 90static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
74531fed 91static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
fee9eda9 92 int forever, int *is_notif);
6426a772 93
934b9bac
JK
94static void async_handle_remote_sigint (int);
95static void async_handle_remote_sigint_twice (int);
43ff13b4 96
a14ed312 97static void remote_files_info (struct target_ops *ignore);
c906108c 98
f32dbf8c
MM
99static void remote_prepare_to_store (struct target_ops *self,
100 struct regcache *regcache);
c906108c 101
014f9477
TT
102static void remote_open_1 (const char *, int, struct target_ops *,
103 int extended_p);
c906108c 104
de90e03d 105static void remote_close (struct target_ops *self);
c906108c 106
136d6dae 107static void remote_mourn (struct target_ops *ops);
c906108c 108
a14ed312 109static void extended_remote_restart (void);
c906108c 110
136d6dae 111static void extended_remote_mourn (struct target_ops *);
c906108c 112
6d820c5c 113static void remote_send (char **buf, long *sizeof_buf_p);
c906108c 114
a14ed312 115static int readchar (int timeout);
c906108c 116
c33e31fd
PA
117static void remote_serial_write (const char *str, int len);
118
7d85a9c0 119static void remote_kill (struct target_ops *ops);
c906108c 120
6a109b6b 121static int remote_can_async_p (struct target_ops *);
75c99385 122
6a109b6b 123static int remote_is_async_p (struct target_ops *);
75c99385 124
6a3753b3 125static void remote_async (struct target_ops *ops, int enable);
75c99385 126
934b9bac 127static void sync_remote_interrupt_twice (int signo);
7a292a7a 128
a14ed312 129static void interrupt_query (void);
c906108c 130
79d7f229
PA
131static void set_general_thread (struct ptid ptid);
132static void set_continue_thread (struct ptid ptid);
c906108c 133
a14ed312 134static void get_offsets (void);
c906108c 135
6d820c5c
DJ
136static void skip_frame (void);
137
138static long read_frame (char **buf_p, long *sizeof_buf);
c906108c 139
a14ed312 140static int hexnumlen (ULONGEST num);
c906108c 141
a14ed312 142static void init_remote_ops (void);
c906108c 143
a14ed312 144static void init_extended_remote_ops (void);
c906108c 145
1eab8a48 146static void remote_stop (struct target_ops *self, ptid_t);
c906108c 147
a14ed312 148static int stubhex (int ch);
c906108c 149
a14ed312 150static int hexnumstr (char *, ULONGEST);
c906108c 151
a14ed312 152static int hexnumnstr (char *, ULONGEST, int);
2df3850c 153
a14ed312 154static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 155
baa336ce 156static void print_packet (const char *);
c906108c 157
a14ed312 158static void compare_sections_command (char *, int);
c906108c 159
a14ed312 160static void packet_command (char *, int);
c906108c 161
a14ed312 162static int stub_unpack_int (char *buff, int fieldlength);
c906108c 163
39f77062 164static ptid_t remote_current_thread (ptid_t oldptid);
c906108c 165
baa336ce 166static int putpkt_binary (const char *buf, int cnt);
c906108c 167
a14ed312 168static void check_binary_download (CORE_ADDR addr);
c906108c 169
5a2468f5 170struct packet_config;
5a2468f5 171
a14ed312 172static void show_packet_config_cmd (struct packet_config *config);
5a2468f5 173
bb572ddd
DJ
174static void show_remote_protocol_packet_cmd (struct ui_file *file,
175 int from_tty,
176 struct cmd_list_element *c,
177 const char *value);
178
82f73884
PA
179static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
180static ptid_t read_ptid (char *buf, char **obuf);
181
c378d69d 182static void remote_set_permissions (struct target_ops *self);
d914c394 183
d5551862 184struct remote_state;
8bd200f1
TT
185static int remote_get_trace_status (struct target_ops *self,
186 struct trace_status *ts);
d5551862 187
ab6617cc
TT
188static int remote_upload_tracepoints (struct target_ops *self,
189 struct uploaded_tp **utpp);
00bf0b85 190
181e3713
TT
191static int remote_upload_trace_state_variables (struct target_ops *self,
192 struct uploaded_tsv **utsvp);
00bf0b85 193
c8d104ad
PA
194static void remote_query_supported (void);
195
36d25514 196static void remote_check_symbols (void);
c8d104ad 197
a14ed312 198void _initialize_remote (void);
c906108c 199
74531fed 200struct stop_reply;
74531fed 201static void stop_reply_xfree (struct stop_reply *);
722247f1 202static void remote_parse_stop_reply (char *, struct stop_reply *);
74531fed 203static void push_stop_reply (struct stop_reply *);
bcc75809 204static void discard_pending_stop_replies_in_queue (struct remote_state *);
74531fed
PA
205static int peek_stop_reply (ptid_t ptid);
206
207static void remote_async_inferior_event_handler (gdb_client_data);
74531fed 208
e3594fd1 209static void remote_terminal_ours (struct target_ops *self);
d3fd5342 210
d962ef82
DJ
211static int remote_read_description_p (struct target_ops *target);
212
176a6961 213static void remote_console_output (char *msg);
dde08ee1 214
efcc2da7 215static int remote_supports_cond_breakpoints (struct target_ops *self);
b775012e 216
78eff0ec 217static int remote_can_run_breakpoint_commands (struct target_ops *self);
d3ce09f5 218
f4abbc16
MM
219static void remote_btrace_reset (void);
220
a6b151f1
DJ
221/* For "remote". */
222
223static struct cmd_list_element *remote_cmdlist;
224
bb572ddd
DJ
225/* For "set remote" and "show remote". */
226
227static struct cmd_list_element *remote_set_cmdlist;
228static struct cmd_list_element *remote_show_cmdlist;
229
d458bd84
PA
230/* Stub vCont actions support.
231
232 Each field is a boolean flag indicating whether the stub reports
233 support for the corresponding action. */
234
235struct vCont_action_support
236{
237 /* vCont;t */
238 int t;
c1e36e3e
PA
239
240 /* vCont;r */
241 int r;
d458bd84
PA
242};
243
c1e36e3e
PA
244/* Controls whether GDB is willing to use range stepping. */
245
246static int use_range_stepping = 1;
247
0d031856
TT
248#define OPAQUETHREADBYTES 8
249
250/* a 64 bit opaque identifier */
251typedef unsigned char threadref[OPAQUETHREADBYTES];
252
253/* About this many threadisds fit in a packet. */
254
255#define MAXTHREADLISTRESULTS 32
256
ea9c271d
DJ
257/* Description of the remote protocol state for the currently
258 connected target. This is per-target state, and independent of the
259 selected architecture. */
260
261struct remote_state
262{
263 /* A buffer to use for incoming packets, and its current size. The
264 buffer is grown dynamically for larger incoming packets.
265 Outgoing packets may also be constructed in this buffer.
266 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
267 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
268 packets. */
269 char *buf;
270 long buf_size;
be2a5f71 271
1e51243a
PA
272 /* True if we're going through initial connection setup (finding out
273 about the remote side's threads, relocating symbols, etc.). */
274 int starting_up;
275
be2a5f71
DJ
276 /* If we negotiated packet size explicitly (and thus can bypass
277 heuristics for the largest packet size that will not overflow
278 a buffer in the stub), this will be set to that packet size.
279 Otherwise zero, meaning to use the guessed size. */
280 long explicit_packet_size;
2d717e4f
DJ
281
282 /* remote_wait is normally called when the target is running and
283 waits for a stop reply packet. But sometimes we need to call it
284 when the target is already stopped. We can send a "?" packet
285 and have remote_wait read the response. Or, if we already have
286 the response, we can stash it in BUF and tell remote_wait to
287 skip calling getpkt. This flag is set when BUF contains a
288 stop reply packet and the target is not waiting. */
289 int cached_wait_status;
a6f3e723
SL
290
291 /* True, if in no ack mode. That is, neither GDB nor the stub will
292 expect acks from each other. The connection is assumed to be
293 reliable. */
294 int noack_mode;
82f73884
PA
295
296 /* True if we're connected in extended remote mode. */
297 int extended;
298
e24a49d8
PA
299 /* True if we resumed the target and we're waiting for the target to
300 stop. In the mean time, we can't start another command/query.
301 The remote server wouldn't be ready to process it, so we'd
302 timeout waiting for a reply that would never come and eventually
303 we'd close the connection. This can happen in asynchronous mode
304 because we allow GDB commands while the target is running. */
305 int waiting_for_stop_reply;
74531fed 306
d458bd84
PA
307 /* The status of the stub support for the various vCont actions. */
308 struct vCont_action_support supports_vCont;
782b2b07 309
3a29589a
DJ
310 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
311 responded to that. */
312 int ctrlc_pending_p;
5d93a237
TT
313
314 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
315 remote_open knows that we don't have a file open when the program
316 starts. */
317 struct serial *remote_desc;
47f8a51d
TT
318
319 /* These are the threads which we last sent to the remote system. The
320 TID member will be -1 for all or -2 for not sent yet. */
321 ptid_t general_thread;
322 ptid_t continue_thread;
262e1174
TT
323
324 /* This is the traceframe which we last selected on the remote system.
325 It will be -1 if no traceframe is selected. */
326 int remote_traceframe_number;
747dc59d
TT
327
328 char *last_pass_packet;
5e4a05c4
TT
329
330 /* The last QProgramSignals packet sent to the target. We bypass
331 sending a new program signals list down to the target if the new
332 packet is exactly the same as the last we sent. IOW, we only let
333 the target know about program signals list changes. */
334 char *last_program_signals_packet;
b73be471
TT
335
336 enum gdb_signal last_sent_signal;
280ceea3
TT
337
338 int last_sent_step;
8e88304f
TT
339
340 char *finished_object;
341 char *finished_annex;
342 ULONGEST finished_offset;
b80fafe3
TT
343
344 /* Should we try the 'ThreadInfo' query packet?
345
346 This variable (NOT available to the user: auto-detect only!)
347 determines whether GDB will use the new, simpler "ThreadInfo"
348 query or the older, more complex syntax for thread queries.
349 This is an auto-detect variable (set to true at each connect,
350 and set to false when the target fails to recognize it). */
351 int use_threadinfo_query;
352 int use_threadextra_query;
88b496c3 353
ee154bee
TT
354 /* This is set to the data address of the access causing the target
355 to stop for a watchpoint. */
356 CORE_ADDR remote_watch_data_address;
357
f7e6eed5
PA
358 /* Whether the target stopped for a breakpoint/watchpoint. */
359 enum target_stop_reason stop_reason;
0d031856
TT
360
361 threadref echo_nextthread;
362 threadref nextthread;
363 threadref resultthreadlist[MAXTHREADLISTRESULTS];
5965e028
YQ
364
365 /* The state of remote notification. */
366 struct remote_notif_state *notif_state;
f4abbc16
MM
367
368 /* The branch trace configuration. */
369 struct btrace_config btrace_config;
ea9c271d
DJ
370};
371
dc146f7c
VP
372/* Private data that we'll store in (struct thread_info)->private. */
373struct private_thread_info
374{
375 char *extra;
376 int core;
377};
378
379static void
380free_private_thread_info (struct private_thread_info *info)
381{
382 xfree (info->extra);
383 xfree (info);
384}
385
ea9c271d
DJ
386/* This data could be associated with a target, but we do not always
387 have access to the current target when we need it, so for now it is
388 static. This will be fine for as long as only one target is in use
389 at a time. */
cf792862 390static struct remote_state *remote_state;
ea9c271d
DJ
391
392static struct remote_state *
0b83947e 393get_remote_state_raw (void)
ea9c271d 394{
cf792862
TT
395 return remote_state;
396}
397
398/* Allocate a new struct remote_state with xmalloc, initialize it, and
399 return it. */
400
401static struct remote_state *
402new_remote_state (void)
403{
404 struct remote_state *result = XCNEW (struct remote_state);
405
406 /* The default buffer size is unimportant; it will be expanded
407 whenever a larger buffer is needed. */
408 result->buf_size = 400;
409 result->buf = xmalloc (result->buf_size);
262e1174 410 result->remote_traceframe_number = -1;
b73be471 411 result->last_sent_signal = GDB_SIGNAL_0;
cf792862
TT
412
413 return result;
ea9c271d
DJ
414}
415
416/* Description of the remote protocol for a given architecture. */
d01949b6 417
ad10f812
AC
418struct packet_reg
419{
420 long offset; /* Offset into G packet. */
421 long regnum; /* GDB's internal register number. */
422 LONGEST pnum; /* Remote protocol register number. */
b323314b 423 int in_g_packet; /* Always part of G packet. */
f5656ead 424 /* long size in bytes; == register_size (target_gdbarch (), regnum);
23860348 425 at present. */
f5656ead 426 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
c9f4d572 427 at present. */
ad10f812
AC
428};
429
ea9c271d 430struct remote_arch_state
d01949b6 431{
ad10f812
AC
432 /* Description of the remote protocol registers. */
433 long sizeof_g_packet;
b323314b
AC
434
435 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 436 (making an array gdbarch_num_regs in size). */
b323314b 437 struct packet_reg *regs;
ad10f812 438
d01949b6
AC
439 /* This is the size (in chars) of the first response to the ``g''
440 packet. It is used as a heuristic when determining the maximum
441 size of memory-read and memory-write packets. A target will
442 typically only reserve a buffer large enough to hold the ``g''
443 packet. The size does not include packet overhead (headers and
23860348 444 trailers). */
d01949b6
AC
445 long actual_register_packet_size;
446
447 /* This is the maximum size (in chars) of a non read/write packet.
23860348 448 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
449 long remote_packet_size;
450};
451
35b1e5cc
SS
452/* Utility: generate error from an incoming stub packet. */
453static void
454trace_error (char *buf)
455{
456 if (*buf++ != 'E')
457 return; /* not an error msg */
458 switch (*buf)
459 {
460 case '1': /* malformed packet error */
461 if (*++buf == '0') /* general case: */
462 error (_("remote.c: error in outgoing packet."));
463 else
464 error (_("remote.c: error in outgoing packet at field #%ld."),
465 strtol (buf, NULL, 16));
35b1e5cc
SS
466 default:
467 error (_("Target returns error code '%s'."), buf);
468 }
469}
470
471/* Utility: wait for reply from stub, while accepting "O" packets. */
472static char *
473remote_get_noisy_reply (char **buf_p,
474 long *sizeof_buf)
475{
476 do /* Loop on reply from remote stub. */
477 {
478 char *buf;
a744cf53 479
0df8b418 480 QUIT; /* Allow user to bail out with ^C. */
35b1e5cc
SS
481 getpkt (buf_p, sizeof_buf, 0);
482 buf = *buf_p;
ad91cd99 483 if (buf[0] == 'E')
35b1e5cc 484 trace_error (buf);
61012eef 485 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
486 {
487 ULONGEST ul;
488 CORE_ADDR from, to, org_to;
489 char *p, *pp;
490 int adjusted_size = 0;
7556d4a4 491 int relocated = 0;
dde08ee1
PA
492
493 p = buf + strlen ("qRelocInsn:");
494 pp = unpack_varlen_hex (p, &ul);
495 if (*pp != ';')
cb91c06a 496 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
497 from = ul;
498
499 p = pp + 1;
a9cbf802 500 unpack_varlen_hex (p, &ul);
dde08ee1
PA
501 to = ul;
502
503 org_to = to;
504
492d29ea 505 TRY
dde08ee1 506 {
f5656ead 507 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 508 relocated = 1;
dde08ee1 509 }
492d29ea 510 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
511 {
512 if (ex.error == MEMORY_ERROR)
513 {
514 /* Propagate memory errors silently back to the
515 target. The stub may have limited the range of
516 addresses we can write to, for example. */
517 }
518 else
519 {
520 /* Something unexpectedly bad happened. Be verbose
521 so we can tell what, and propagate the error back
522 to the stub, so it doesn't get stuck waiting for
523 a response. */
524 exception_fprintf (gdb_stderr, ex,
525 _("warning: relocating instruction: "));
526 }
527 putpkt ("E01");
528 }
492d29ea 529 END_CATCH
7556d4a4
PA
530
531 if (relocated)
dde08ee1
PA
532 {
533 adjusted_size = to - org_to;
534
bba74b36 535 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
536 putpkt (buf);
537 }
dde08ee1 538 }
ad91cd99 539 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
540 remote_console_output (buf + 1); /* 'O' message from stub */
541 else
0df8b418 542 return buf; /* Here's the actual reply. */
35b1e5cc
SS
543 }
544 while (1);
545}
3c3bea1c 546
d01949b6
AC
547/* Handle for retreving the remote protocol data from gdbarch. */
548static struct gdbarch_data *remote_gdbarch_data_handle;
549
ea9c271d
DJ
550static struct remote_arch_state *
551get_remote_arch_state (void)
d01949b6 552{
f5656ead 553 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
d01949b6
AC
554}
555
0b83947e
DJ
556/* Fetch the global remote target state. */
557
558static struct remote_state *
559get_remote_state (void)
560{
561 /* Make sure that the remote architecture state has been
562 initialized, because doing so might reallocate rs->buf. Any
563 function which calls getpkt also needs to be mindful of changes
564 to rs->buf, but this call limits the number of places which run
565 into trouble. */
566 get_remote_arch_state ();
567
568 return get_remote_state_raw ();
569}
570
74ca34ce
DJ
571static int
572compare_pnums (const void *lhs_, const void *rhs_)
573{
574 const struct packet_reg * const *lhs = lhs_;
575 const struct packet_reg * const *rhs = rhs_;
576
577 if ((*lhs)->pnum < (*rhs)->pnum)
578 return -1;
579 else if ((*lhs)->pnum == (*rhs)->pnum)
580 return 0;
581 else
582 return 1;
583}
584
c21236dc
PA
585static int
586map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 587{
74ca34ce 588 int regnum, num_remote_regs, offset;
74ca34ce 589 struct packet_reg **remote_regs;
ea9c271d 590
4a22f64d 591 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 592 {
c21236dc 593 struct packet_reg *r = &regs[regnum];
baef701f 594
4a22f64d 595 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
596 /* Do not try to fetch zero-sized (placeholder) registers. */
597 r->pnum = -1;
598 else
599 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
600
b323314b 601 r->regnum = regnum;
74ca34ce
DJ
602 }
603
604 /* Define the g/G packet format as the contents of each register
605 with a remote protocol number, in order of ascending protocol
606 number. */
607
4a22f64d 608 remote_regs = alloca (gdbarch_num_regs (gdbarch)
c21236dc 609 * sizeof (struct packet_reg *));
f57d151a 610 for (num_remote_regs = 0, regnum = 0;
4a22f64d 611 regnum < gdbarch_num_regs (gdbarch);
f57d151a 612 regnum++)
c21236dc
PA
613 if (regs[regnum].pnum != -1)
614 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 615
74ca34ce
DJ
616 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
617 compare_pnums);
618
619 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
620 {
621 remote_regs[regnum]->in_g_packet = 1;
622 remote_regs[regnum]->offset = offset;
4a22f64d 623 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
624 }
625
c21236dc
PA
626 return offset;
627}
628
629/* Given the architecture described by GDBARCH, return the remote
630 protocol register's number and the register's offset in the g/G
631 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
632 If the target does not have a mapping for REGNUM, return false,
633 otherwise, return true. */
634
635int
636remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
637 int *pnum, int *poffset)
638{
639 int sizeof_g_packet;
640 struct packet_reg *regs;
641 struct cleanup *old_chain;
642
643 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
644
645 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
646 old_chain = make_cleanup (xfree, regs);
647
648 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
649
650 *pnum = regs[regnum].pnum;
651 *poffset = regs[regnum].offset;
652
653 do_cleanups (old_chain);
654
655 return *pnum != -1;
656}
657
658static void *
659init_remote_state (struct gdbarch *gdbarch)
660{
661 struct remote_state *rs = get_remote_state_raw ();
662 struct remote_arch_state *rsa;
663
664 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
665
666 /* Use the architecture to build a regnum<->pnum table, which will be
667 1:1 unless a feature set specifies otherwise. */
668 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
669 gdbarch_num_regs (gdbarch),
670 struct packet_reg);
671
74ca34ce
DJ
672 /* Record the maximum possible size of the g packet - it may turn out
673 to be smaller. */
c21236dc 674 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 675
0df8b418 676 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
677 remote stubs have a hardwired buffer size of 400 bytes
678 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
679 as the maximum packet-size to ensure that the packet and an extra
680 NUL character can always fit in the buffer. This stops GDB
681 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
682 already a full buffer (As of 1999-12-04 that was most stubs). */
683 rsa->remote_packet_size = 400 - 1;
d01949b6 684
ea9c271d
DJ
685 /* This one is filled in when a ``g'' packet is received. */
686 rsa->actual_register_packet_size = 0;
687
688 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
689 default, adjust the size accordingly. Remember that each byte is
690 encoded as two characters. 32 is the overhead for the packet
691 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 692 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 693 little. */
ea9c271d
DJ
694 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
695 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 696
ea9c271d
DJ
697 /* Make sure that the packet buffer is plenty big enough for
698 this architecture. */
699 if (rs->buf_size < rsa->remote_packet_size)
700 {
701 rs->buf_size = 2 * rsa->remote_packet_size;
7fca722e 702 rs->buf = xrealloc (rs->buf, rs->buf_size);
ea9c271d 703 }
6d820c5c 704
ea9c271d
DJ
705 return rsa;
706}
707
708/* Return the current allowed size of a remote packet. This is
709 inferred from the current architecture, and should be used to
710 limit the length of outgoing packets. */
711static long
712get_remote_packet_size (void)
713{
be2a5f71 714 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
715 struct remote_arch_state *rsa = get_remote_arch_state ();
716
be2a5f71
DJ
717 if (rs->explicit_packet_size)
718 return rs->explicit_packet_size;
719
ea9c271d 720 return rsa->remote_packet_size;
d01949b6
AC
721}
722
ad10f812 723static struct packet_reg *
ea9c271d 724packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 725{
f5656ead 726 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
b323314b
AC
727 return NULL;
728 else
ad10f812 729 {
ea9c271d 730 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 731
b323314b
AC
732 gdb_assert (r->regnum == regnum);
733 return r;
ad10f812 734 }
ad10f812
AC
735}
736
737static struct packet_reg *
ea9c271d 738packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 739{
b323314b 740 int i;
a744cf53 741
f5656ead 742 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
ad10f812 743 {
ea9c271d 744 struct packet_reg *r = &rsa->regs[i];
a744cf53 745
b323314b
AC
746 if (r->pnum == pnum)
747 return r;
ad10f812
AC
748 }
749 return NULL;
d01949b6
AC
750}
751
c906108c
SS
752static struct target_ops remote_ops;
753
754static struct target_ops extended_remote_ops;
755
6426a772
JM
756/* FIXME: cagney/1999-09-23: Even though getpkt was called with
757 ``forever'' still use the normal timeout mechanism. This is
758 currently used by the ASYNC code to guarentee that target reads
759 during the initial connect always time-out. Once getpkt has been
760 modified to return a timeout indication and, in turn
761 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 762 this can go away. */
6426a772
JM
763static int wait_forever_enabled_p = 1;
764
9a7071a8
JB
765/* Allow the user to specify what sequence to send to the remote
766 when he requests a program interruption: Although ^C is usually
767 what remote systems expect (this is the default, here), it is
768 sometimes preferable to send a break. On other systems such
769 as the Linux kernel, a break followed by g, which is Magic SysRq g
770 is required in order to interrupt the execution. */
771const char interrupt_sequence_control_c[] = "Ctrl-C";
772const char interrupt_sequence_break[] = "BREAK";
773const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 774static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
775 {
776 interrupt_sequence_control_c,
777 interrupt_sequence_break,
778 interrupt_sequence_break_g,
779 NULL
780 };
781static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
782
783static void
784show_interrupt_sequence (struct ui_file *file, int from_tty,
785 struct cmd_list_element *c,
786 const char *value)
787{
788 if (interrupt_sequence_mode == interrupt_sequence_control_c)
789 fprintf_filtered (file,
790 _("Send the ASCII ETX character (Ctrl-c) "
791 "to the remote target to interrupt the "
792 "execution of the program.\n"));
793 else if (interrupt_sequence_mode == interrupt_sequence_break)
794 fprintf_filtered (file,
795 _("send a break signal to the remote target "
796 "to interrupt the execution of the program.\n"));
797 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
798 fprintf_filtered (file,
799 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
800 "the remote target to interrupt the execution "
801 "of Linux kernel.\n"));
802 else
803 internal_error (__FILE__, __LINE__,
804 _("Invalid value for interrupt_sequence_mode: %s."),
805 interrupt_sequence_mode);
806}
6426a772 807
9a7071a8
JB
808/* This boolean variable specifies whether interrupt_sequence is sent
809 to the remote target when gdb connects to it.
810 This is mostly needed when you debug the Linux kernel: The Linux kernel
811 expects BREAK g which is Magic SysRq g for connecting gdb. */
812static int interrupt_on_connect = 0;
c906108c 813
9a7071a8
JB
814/* This variable is used to implement the "set/show remotebreak" commands.
815 Since these commands are now deprecated in favor of "set/show remote
816 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
817static int remote_break;
818
9a7071a8
JB
819static void
820set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
821{
822 if (remote_break)
823 interrupt_sequence_mode = interrupt_sequence_break;
824 else
825 interrupt_sequence_mode = interrupt_sequence_control_c;
826}
827
828static void
829show_remotebreak (struct ui_file *file, int from_tty,
830 struct cmd_list_element *c,
831 const char *value)
832{
833}
834
c906108c
SS
835/* This variable sets the number of bits in an address that are to be
836 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 837 leading zeros, the entire address would be sent. This variable
c906108c
SS
838 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
839 initial implementation of remote.c restricted the address sent in
840 memory packets to ``host::sizeof long'' bytes - (typically 32
841 bits). Consequently, for 64 bit targets, the upper 32 bits of an
842 address was never sent. Since fixing this bug may cause a break in
843 some remote targets this variable is principly provided to
23860348 844 facilitate backward compatibility. */
c906108c 845
883b9c6c 846static unsigned int remote_address_size;
c906108c 847
75c99385
PA
848/* Temporary to track who currently owns the terminal. See
849 remote_terminal_* for more details. */
6426a772
JM
850
851static int remote_async_terminal_ours_p;
852
2d717e4f
DJ
853/* The executable file to use for "run" on the remote side. */
854
855static char *remote_exec_file = "";
856
11cf8741 857\f
11cf8741 858/* User configurable variables for the number of characters in a
ea9c271d
DJ
859 memory read/write packet. MIN (rsa->remote_packet_size,
860 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 861 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
862 (speed up transfers). The variables ``preferred_*'' (the user
863 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 864 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
865
866struct memory_packet_config
867{
868 char *name;
869 long size;
870 int fixed_p;
871};
872
873/* Compute the current size of a read/write packet. Since this makes
874 use of ``actual_register_packet_size'' the computation is dynamic. */
875
876static long
877get_memory_packet_size (struct memory_packet_config *config)
878{
d01949b6 879 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
880 struct remote_arch_state *rsa = get_remote_arch_state ();
881
11cf8741
JM
882 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
883 law?) that some hosts don't cope very well with large alloca()
884 calls. Eventually the alloca() code will be replaced by calls to
885 xmalloc() and make_cleanups() allowing this restriction to either
23860348 886 be lifted or removed. */
11cf8741
JM
887#ifndef MAX_REMOTE_PACKET_SIZE
888#define MAX_REMOTE_PACKET_SIZE 16384
889#endif
3de11b2e 890 /* NOTE: 20 ensures we can write at least one byte. */
11cf8741 891#ifndef MIN_REMOTE_PACKET_SIZE
3de11b2e 892#define MIN_REMOTE_PACKET_SIZE 20
11cf8741
JM
893#endif
894 long what_they_get;
895 if (config->fixed_p)
896 {
897 if (config->size <= 0)
898 what_they_get = MAX_REMOTE_PACKET_SIZE;
899 else
900 what_they_get = config->size;
901 }
902 else
903 {
ea9c271d 904 what_they_get = get_remote_packet_size ();
23860348 905 /* Limit the packet to the size specified by the user. */
11cf8741
JM
906 if (config->size > 0
907 && what_they_get > config->size)
908 what_they_get = config->size;
be2a5f71
DJ
909
910 /* Limit it to the size of the targets ``g'' response unless we have
911 permission from the stub to use a larger packet size. */
912 if (rs->explicit_packet_size == 0
913 && rsa->actual_register_packet_size > 0
914 && what_they_get > rsa->actual_register_packet_size)
915 what_they_get = rsa->actual_register_packet_size;
11cf8741
JM
916 }
917 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
918 what_they_get = MAX_REMOTE_PACKET_SIZE;
919 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
920 what_they_get = MIN_REMOTE_PACKET_SIZE;
6d820c5c
DJ
921
922 /* Make sure there is room in the global buffer for this packet
923 (including its trailing NUL byte). */
924 if (rs->buf_size < what_they_get + 1)
925 {
926 rs->buf_size = 2 * what_they_get;
927 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
928 }
929
11cf8741
JM
930 return what_they_get;
931}
932
0df8b418 933/* Update the size of a read/write packet. If they user wants
23860348 934 something really big then do a sanity check. */
11cf8741
JM
935
936static void
937set_memory_packet_size (char *args, struct memory_packet_config *config)
938{
939 int fixed_p = config->fixed_p;
940 long size = config->size;
a744cf53 941
11cf8741 942 if (args == NULL)
8a3fe4f8 943 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
944 else if (strcmp (args, "hard") == 0
945 || strcmp (args, "fixed") == 0)
946 fixed_p = 1;
947 else if (strcmp (args, "soft") == 0
948 || strcmp (args, "limit") == 0)
949 fixed_p = 0;
950 else
951 {
952 char *end;
a744cf53 953
11cf8741
JM
954 size = strtoul (args, &end, 0);
955 if (args == end)
8a3fe4f8 956 error (_("Invalid %s (bad syntax)."), config->name);
11cf8741
JM
957#if 0
958 /* Instead of explicitly capping the size of a packet to
959 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
960 instead allowed to set the size to something arbitrarily
23860348 961 large. */
11cf8741 962 if (size > MAX_REMOTE_PACKET_SIZE)
8a3fe4f8 963 error (_("Invalid %s (too large)."), config->name);
11cf8741
JM
964#endif
965 }
23860348 966 /* Extra checks? */
11cf8741
JM
967 if (fixed_p && !config->fixed_p)
968 {
e2e0b3e5
AC
969 if (! query (_("The target may not be able to correctly handle a %s\n"
970 "of %ld bytes. Change the packet size? "),
11cf8741 971 config->name, size))
8a3fe4f8 972 error (_("Packet size not changed."));
11cf8741 973 }
23860348 974 /* Update the config. */
11cf8741
JM
975 config->fixed_p = fixed_p;
976 config->size = size;
977}
978
979static void
980show_memory_packet_size (struct memory_packet_config *config)
981{
a3f17187 982 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 983 if (config->fixed_p)
a3f17187 984 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
985 get_memory_packet_size (config));
986 else
a3f17187 987 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
988 get_memory_packet_size (config));
989}
990
991static struct memory_packet_config memory_write_packet_config =
992{
993 "memory-write-packet-size",
994};
995
996static void
997set_memory_write_packet_size (char *args, int from_tty)
998{
999 set_memory_packet_size (args, &memory_write_packet_config);
1000}
1001
1002static void
1003show_memory_write_packet_size (char *args, int from_tty)
1004{
1005 show_memory_packet_size (&memory_write_packet_config);
1006}
1007
1008static long
1009get_memory_write_packet_size (void)
1010{
1011 return get_memory_packet_size (&memory_write_packet_config);
1012}
1013
1014static struct memory_packet_config memory_read_packet_config =
1015{
1016 "memory-read-packet-size",
1017};
1018
1019static void
1020set_memory_read_packet_size (char *args, int from_tty)
1021{
1022 set_memory_packet_size (args, &memory_read_packet_config);
1023}
1024
1025static void
1026show_memory_read_packet_size (char *args, int from_tty)
1027{
1028 show_memory_packet_size (&memory_read_packet_config);
1029}
1030
1031static long
1032get_memory_read_packet_size (void)
1033{
1034 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1035
11cf8741
JM
1036 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1037 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1038 increased beyond this. */
1039 if (size > get_remote_packet_size ())
1040 size = get_remote_packet_size ();
11cf8741
JM
1041 return size;
1042}
1043
11cf8741 1044\f
5a2468f5 1045/* Generic configuration support for packets the stub optionally
0df8b418 1046 supports. Allows the user to specify the use of the packet as well
23860348 1047 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1048
1049enum packet_support
1050 {
1051 PACKET_SUPPORT_UNKNOWN = 0,
1052 PACKET_ENABLE,
1053 PACKET_DISABLE
1054 };
1055
5a2468f5
JM
1056struct packet_config
1057 {
bb572ddd
DJ
1058 const char *name;
1059 const char *title;
4082afcc
PA
1060
1061 /* If auto, GDB auto-detects support for this packet or feature,
1062 either through qSupported, or by trying the packet and looking
1063 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1064 packet. If false, the packet is disabled. Configs that don't
1065 have an associated command always have this set to auto. */
7f19b9a2 1066 enum auto_boolean detect;
4082afcc
PA
1067
1068 /* Does the target support this packet? */
5a2468f5
JM
1069 enum packet_support support;
1070 };
1071
d471ea57 1072/* Analyze a packet's return value and update the packet config
23860348 1073 accordingly. */
d471ea57
AC
1074
1075enum packet_result
1076{
1077 PACKET_ERROR,
1078 PACKET_OK,
1079 PACKET_UNKNOWN
1080};
1081
4082afcc
PA
1082static enum packet_support packet_config_support (struct packet_config *config);
1083static enum packet_support packet_support (int packet);
5a2468f5
JM
1084
1085static void
fba45db2 1086show_packet_config_cmd (struct packet_config *config)
5a2468f5
JM
1087{
1088 char *support = "internal-error";
a744cf53 1089
4082afcc 1090 switch (packet_config_support (config))
5a2468f5
JM
1091 {
1092 case PACKET_ENABLE:
1093 support = "enabled";
1094 break;
1095 case PACKET_DISABLE:
1096 support = "disabled";
1097 break;
1098 case PACKET_SUPPORT_UNKNOWN:
1099 support = "unknown";
1100 break;
1101 }
1102 switch (config->detect)
1103 {
7f19b9a2 1104 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1105 printf_filtered (_("Support for the `%s' packet "
1106 "is auto-detected, currently %s.\n"),
37a105a1 1107 config->name, support);
5a2468f5 1108 break;
7f19b9a2
AC
1109 case AUTO_BOOLEAN_TRUE:
1110 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1111 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1112 config->name, support);
8e248173 1113 break;
5a2468f5
JM
1114 }
1115}
1116
1117static void
bb572ddd
DJ
1118add_packet_config_cmd (struct packet_config *config, const char *name,
1119 const char *title, int legacy)
d471ea57 1120{
5a2468f5
JM
1121 char *set_doc;
1122 char *show_doc;
d471ea57 1123 char *cmd_name;
3ed07be4 1124
5a2468f5
JM
1125 config->name = name;
1126 config->title = title;
b435e160
AC
1127 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1128 name, title);
3e43a32a
MS
1129 show_doc = xstrprintf ("Show current use of remote "
1130 "protocol `%s' (%s) packet",
b435e160 1131 name, title);
d471ea57 1132 /* set/show TITLE-packet {auto,on,off} */
b435e160 1133 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1134 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1135 &config->detect, set_doc,
1136 show_doc, NULL, /* help_doc */
4082afcc 1137 NULL,
bb572ddd
DJ
1138 show_remote_protocol_packet_cmd,
1139 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1140 /* The command code copies the documentation strings. */
1141 xfree (set_doc);
1142 xfree (show_doc);
23860348 1143 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1144 if (legacy)
1145 {
1146 char *legacy_name;
a744cf53 1147
b435e160 1148 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1149 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1150 &remote_set_cmdlist);
d471ea57 1151 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1152 &remote_show_cmdlist);
d471ea57 1153 }
5a2468f5
JM
1154}
1155
d471ea57 1156static enum packet_result
a76d924d 1157packet_check_result (const char *buf)
5a2468f5 1158{
d471ea57 1159 if (buf[0] != '\0')
5a2468f5 1160 {
d471ea57 1161 /* The stub recognized the packet request. Check that the
23860348 1162 operation succeeded. */
a76d924d
DJ
1163 if (buf[0] == 'E'
1164 && isxdigit (buf[1]) && isxdigit (buf[2])
1165 && buf[3] == '\0')
1166 /* "Enn" - definitly an error. */
1167 return PACKET_ERROR;
1168
1169 /* Always treat "E." as an error. This will be used for
1170 more verbose error messages, such as E.memtypes. */
1171 if (buf[0] == 'E' && buf[1] == '.')
1172 return PACKET_ERROR;
1173
1174 /* The packet may or may not be OK. Just assume it is. */
1175 return PACKET_OK;
1176 }
1177 else
1178 /* The stub does not support the packet. */
1179 return PACKET_UNKNOWN;
1180}
1181
1182static enum packet_result
1183packet_ok (const char *buf, struct packet_config *config)
1184{
1185 enum packet_result result;
1186
4082afcc
PA
1187 if (config->detect != AUTO_BOOLEAN_TRUE
1188 && config->support == PACKET_DISABLE)
1189 internal_error (__FILE__, __LINE__,
1190 _("packet_ok: attempt to use a disabled packet"));
1191
a76d924d
DJ
1192 result = packet_check_result (buf);
1193 switch (result)
1194 {
1195 case PACKET_OK:
1196 case PACKET_ERROR:
1197 /* The stub recognized the packet request. */
4082afcc 1198 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1199 {
d471ea57
AC
1200 if (remote_debug)
1201 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1202 "Packet %s (%s) is supported\n",
1203 config->name, config->title);
d471ea57 1204 config->support = PACKET_ENABLE;
d471ea57 1205 }
a76d924d
DJ
1206 break;
1207 case PACKET_UNKNOWN:
23860348 1208 /* The stub does not support the packet. */
4082afcc
PA
1209 if (config->detect == AUTO_BOOLEAN_AUTO
1210 && config->support == PACKET_ENABLE)
d471ea57 1211 {
4082afcc
PA
1212 /* If the stub previously indicated that the packet was
1213 supported then there is a protocol error. */
1214 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1215 config->name, config->title);
1216 }
1217 else if (config->detect == AUTO_BOOLEAN_TRUE)
1218 {
1219 /* The user set it wrong. */
1220 error (_("Enabled packet %s (%s) not recognized by stub"),
1221 config->name, config->title);
d471ea57 1222 }
4082afcc
PA
1223
1224 if (remote_debug)
1225 fprintf_unfiltered (gdb_stdlog,
1226 "Packet %s (%s) is NOT supported\n",
1227 config->name, config->title);
1228 config->support = PACKET_DISABLE;
a76d924d 1229 break;
5a2468f5 1230 }
a76d924d
DJ
1231
1232 return result;
5a2468f5
JM
1233}
1234
444abaca
DJ
1235enum {
1236 PACKET_vCont = 0,
1237 PACKET_X,
1238 PACKET_qSymbol,
1239 PACKET_P,
1240 PACKET_p,
1241 PACKET_Z0,
1242 PACKET_Z1,
1243 PACKET_Z2,
1244 PACKET_Z3,
1245 PACKET_Z4,
a6b151f1
DJ
1246 PACKET_vFile_open,
1247 PACKET_vFile_pread,
1248 PACKET_vFile_pwrite,
1249 PACKET_vFile_close,
1250 PACKET_vFile_unlink,
b9e7b9c3 1251 PACKET_vFile_readlink,
0a93529c 1252 PACKET_vFile_fstat,
0876f84a 1253 PACKET_qXfer_auxv,
23181151 1254 PACKET_qXfer_features,
c78fa86a 1255 PACKET_qXfer_exec_file,
cfa9d6d9 1256 PACKET_qXfer_libraries,
2268b414 1257 PACKET_qXfer_libraries_svr4,
fd79ecee 1258 PACKET_qXfer_memory_map,
0e7f50da
UW
1259 PACKET_qXfer_spu_read,
1260 PACKET_qXfer_spu_write,
07e059b5 1261 PACKET_qXfer_osdata,
dc146f7c 1262 PACKET_qXfer_threads,
0fb4aa4b 1263 PACKET_qXfer_statictrace_read,
b3b9301e 1264 PACKET_qXfer_traceframe_info,
169081d0 1265 PACKET_qXfer_uib,
711e434b 1266 PACKET_qGetTIBAddr,
444abaca 1267 PACKET_qGetTLSAddr,
be2a5f71 1268 PACKET_qSupported,
bd3eecc3 1269 PACKET_qTStatus,
89be2091 1270 PACKET_QPassSignals,
9b224c5e 1271 PACKET_QProgramSignals,
936d2992 1272 PACKET_qCRC,
08388c79 1273 PACKET_qSearch_memory,
2d717e4f
DJ
1274 PACKET_vAttach,
1275 PACKET_vRun,
a6f3e723 1276 PACKET_QStartNoAckMode,
82f73884 1277 PACKET_vKill,
4aa995e1
PA
1278 PACKET_qXfer_siginfo_read,
1279 PACKET_qXfer_siginfo_write,
0b16c5cf 1280 PACKET_qAttached,
4082afcc
PA
1281
1282 /* Support for conditional tracepoints. */
782b2b07 1283 PACKET_ConditionalTracepoints,
4082afcc
PA
1284
1285 /* Support for target-side breakpoint conditions. */
3788aec7 1286 PACKET_ConditionalBreakpoints,
4082afcc
PA
1287
1288 /* Support for target-side breakpoint commands. */
d3ce09f5 1289 PACKET_BreakpointCommands,
4082afcc
PA
1290
1291 /* Support for fast tracepoints. */
7a697b8d 1292 PACKET_FastTracepoints,
4082afcc
PA
1293
1294 /* Support for static tracepoints. */
0fb4aa4b 1295 PACKET_StaticTracepoints,
4082afcc
PA
1296
1297 /* Support for installing tracepoints while a trace experiment is
1298 running. */
1e4d1764 1299 PACKET_InstallInTrace,
4082afcc 1300
40ab02ce
MS
1301 PACKET_bc,
1302 PACKET_bs,
409873ef 1303 PACKET_TracepointSource,
d914c394 1304 PACKET_QAllow,
78d85199 1305 PACKET_qXfer_fdpic,
03583c20 1306 PACKET_QDisableRandomization,
d1feda86 1307 PACKET_QAgent,
f6f899bf 1308 PACKET_QTBuffer_size,
9accd112
MM
1309 PACKET_Qbtrace_off,
1310 PACKET_Qbtrace_bts,
1311 PACKET_qXfer_btrace,
4082afcc
PA
1312
1313 /* Support for the QNonStop packet. */
1314 PACKET_QNonStop,
1315
1316 /* Support for multi-process extensions. */
1317 PACKET_multiprocess_feature,
1318
1319 /* Support for enabling and disabling tracepoints while a trace
1320 experiment is running. */
1321 PACKET_EnableDisableTracepoints_feature,
1322
1323 /* Support for collecting strings using the tracenz bytecode. */
1324 PACKET_tracenz_feature,
1325
1326 /* Support for continuing to run a trace experiment while GDB is
1327 disconnected. */
1328 PACKET_DisconnectedTracing_feature,
1329
1330 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1331 PACKET_augmented_libraries_svr4_read_feature,
1332
f4abbc16
MM
1333 /* Support for the qXfer:btrace-conf:read packet. */
1334 PACKET_qXfer_btrace_conf,
1335
d33501a5
MM
1336 /* Support for the Qbtrace-conf:bts:size packet. */
1337 PACKET_Qbtrace_conf_bts_size,
1338
f7e6eed5
PA
1339 /* Support for swbreak+ feature. */
1340 PACKET_swbreak_feature,
1341
1342 /* Support for hwbreak+ feature. */
1343 PACKET_hwbreak_feature,
1344
444abaca
DJ
1345 PACKET_MAX
1346};
506fb367 1347
444abaca 1348static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1349
f7e6eed5
PA
1350/* Returns the packet's corresponding "set remote foo-packet" command
1351 state. See struct packet_config for more details. */
1352
1353static enum auto_boolean
1354packet_set_cmd_state (int packet)
1355{
1356 return remote_protocol_packets[packet].detect;
1357}
1358
4082afcc
PA
1359/* Returns whether a given packet or feature is supported. This takes
1360 into account the state of the corresponding "set remote foo-packet"
1361 command, which may be used to bypass auto-detection. */
dc8acb97 1362
4082afcc
PA
1363static enum packet_support
1364packet_config_support (struct packet_config *config)
1365{
1366 switch (config->detect)
444abaca 1367 {
4082afcc
PA
1368 case AUTO_BOOLEAN_TRUE:
1369 return PACKET_ENABLE;
1370 case AUTO_BOOLEAN_FALSE:
1371 return PACKET_DISABLE;
1372 case AUTO_BOOLEAN_AUTO:
1373 return config->support;
1374 default:
1375 gdb_assert_not_reached (_("bad switch"));
444abaca 1376 }
4082afcc
PA
1377}
1378
1379/* Same as packet_config_support, but takes the packet's enum value as
1380 argument. */
1381
1382static enum packet_support
1383packet_support (int packet)
1384{
1385 struct packet_config *config = &remote_protocol_packets[packet];
1386
1387 return packet_config_support (config);
dc8acb97
MS
1388}
1389
5a2468f5 1390static void
444abaca
DJ
1391show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1392 struct cmd_list_element *c,
1393 const char *value)
5a2468f5 1394{
444abaca 1395 struct packet_config *packet;
5a2468f5 1396
444abaca
DJ
1397 for (packet = remote_protocol_packets;
1398 packet < &remote_protocol_packets[PACKET_MAX];
1399 packet++)
1400 {
1401 if (&packet->detect == c->var)
1402 {
1403 show_packet_config_cmd (packet);
1404 return;
1405 }
1406 }
9b20d036 1407 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1408 c->name);
5a2468f5
JM
1409}
1410
d471ea57
AC
1411/* Should we try one of the 'Z' requests? */
1412
1413enum Z_packet_type
1414{
1415 Z_PACKET_SOFTWARE_BP,
1416 Z_PACKET_HARDWARE_BP,
1417 Z_PACKET_WRITE_WP,
1418 Z_PACKET_READ_WP,
1419 Z_PACKET_ACCESS_WP,
1420 NR_Z_PACKET_TYPES
1421};
96baa820 1422
d471ea57 1423/* For compatibility with older distributions. Provide a ``set remote
23860348 1424 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1425
7f19b9a2 1426static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1427
1428static void
fba45db2
KB
1429set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1430 struct cmd_list_element *c)
96baa820 1431{
d471ea57 1432 int i;
a744cf53 1433
d471ea57 1434 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1435 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1436}
1437
1438static void
08546159
AC
1439show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1440 struct cmd_list_element *c,
1441 const char *value)
96baa820 1442{
d471ea57 1443 int i;
a744cf53 1444
d471ea57
AC
1445 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1446 {
444abaca 1447 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1448 }
96baa820
JM
1449}
1450
4082afcc
PA
1451/* Returns true if the multi-process extensions are in effect. */
1452
1453static int
1454remote_multi_process_p (struct remote_state *rs)
1455{
1456 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1457}
1458
23860348 1459/* Tokens for use by the asynchronous signal handlers for SIGINT. */
934b9bac
JK
1460static struct async_signal_handler *async_sigint_remote_twice_token;
1461static struct async_signal_handler *async_sigint_remote_token;
43ff13b4 1462
74531fed
PA
1463\f
1464/* Asynchronous signal handle registered as event loop source for
1465 when we have pending events ready to be passed to the core. */
1466
1467static struct async_event_handler *remote_async_inferior_event_token;
1468
c906108c
SS
1469\f
1470
79d7f229
PA
1471static ptid_t magic_null_ptid;
1472static ptid_t not_sent_ptid;
1473static ptid_t any_thread_ptid;
1474
0b16c5cf
PA
1475/* Find out if the stub attached to PID (and hence GDB should offer to
1476 detach instead of killing it when bailing out). */
1477
1478static int
1479remote_query_attached (int pid)
1480{
1481 struct remote_state *rs = get_remote_state ();
bba74b36 1482 size_t size = get_remote_packet_size ();
0b16c5cf 1483
4082afcc 1484 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1485 return 0;
1486
1487 if (remote_multi_process_p (rs))
bba74b36 1488 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1489 else
bba74b36 1490 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1491
1492 putpkt (rs->buf);
1493 getpkt (&rs->buf, &rs->buf_size, 0);
1494
1495 switch (packet_ok (rs->buf,
1554e9be 1496 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1497 {
1498 case PACKET_OK:
1499 if (strcmp (rs->buf, "1") == 0)
1500 return 1;
1501 break;
1502 case PACKET_ERROR:
1503 warning (_("Remote failure reply: %s"), rs->buf);
1504 break;
1505 case PACKET_UNKNOWN:
1506 break;
1507 }
1508
1509 return 0;
1510}
1511
49c62f2e
PA
1512/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1513 has been invented by GDB, instead of reported by the target. Since
1514 we can be connected to a remote system before before knowing about
1515 any inferior, mark the target with execution when we find the first
1516 inferior. If ATTACHED is 1, then we had just attached to this
1517 inferior. If it is 0, then we just created this inferior. If it
1518 is -1, then try querying the remote stub to find out if it had
1519 attached to the inferior or not. */
1941c569
PA
1520
1521static struct inferior *
49c62f2e 1522remote_add_inferior (int fake_pid_p, int pid, int attached)
1941c569 1523{
1941c569
PA
1524 struct inferior *inf;
1525
0b16c5cf
PA
1526 /* Check whether this process we're learning about is to be
1527 considered attached, or if is to be considered to have been
1528 spawned by the stub. */
1529 if (attached == -1)
1530 attached = remote_query_attached (pid);
1531
f5656ead 1532 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1533 {
1534 /* If the target shares code across all inferiors, then every
1535 attach adds a new inferior. */
1536 inf = add_inferior (pid);
1537
1538 /* ... and every inferior is bound to the same program space.
1539 However, each inferior may still have its own address
1540 space. */
1541 inf->aspace = maybe_new_address_space ();
1542 inf->pspace = current_program_space;
1543 }
1544 else
1545 {
1546 /* In the traditional debugging scenario, there's a 1-1 match
1547 between program/address spaces. We simply bind the inferior
1548 to the program space's address space. */
1549 inf = current_inferior ();
1550 inferior_appeared (inf, pid);
1551 }
1941c569 1552
0b16c5cf 1553 inf->attach_flag = attached;
49c62f2e 1554 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1555
1941c569
PA
1556 return inf;
1557}
1558
1559/* Add thread PTID to GDB's thread list. Tag it as executing/running
1560 according to RUNNING. */
1561
c906108c 1562static void
1941c569 1563remote_add_thread (ptid_t ptid, int running)
c906108c 1564{
b7ea362b
PA
1565 struct remote_state *rs = get_remote_state ();
1566
1567 /* GDB historically didn't pull threads in the initial connection
1568 setup. If the remote target doesn't even have a concept of
1569 threads (e.g., a bare-metal target), even if internally we
1570 consider that a single-threaded target, mentioning a new thread
1571 might be confusing to the user. Be silent then, preserving the
1572 age old behavior. */
1573 if (rs->starting_up)
1574 add_thread_silent (ptid);
1575 else
1576 add_thread (ptid);
1941c569
PA
1577
1578 set_executing (ptid, running);
1579 set_running (ptid, running);
1580}
1581
1582/* Come here when we learn about a thread id from the remote target.
1583 It may be the first time we hear about such thread, so take the
1584 opportunity to add it to GDB's thread list. In case this is the
1585 first time we're noticing its corresponding inferior, add it to
1586 GDB's inferior list as well. */
1587
1588static void
1589remote_notice_new_inferior (ptid_t currthread, int running)
1590{
c906108c
SS
1591 /* If this is a new thread, add it to GDB's thread list.
1592 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1593
1594 if (in_thread_list (currthread) && is_exited (currthread))
1595 {
1596 /* We're seeing an event on a thread id we knew had exited.
1597 This has to be a new thread reusing the old id. Add it. */
1941c569 1598 remote_add_thread (currthread, running);
82f73884
PA
1599 return;
1600 }
1601
79d7f229 1602 if (!in_thread_list (currthread))
c0a2216e 1603 {
1941c569 1604 struct inferior *inf = NULL;
bad34192 1605 int pid = ptid_get_pid (currthread);
1941c569 1606
bad34192
PA
1607 if (ptid_is_pid (inferior_ptid)
1608 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1609 {
1610 /* inferior_ptid has no thread member yet. This can happen
1611 with the vAttach -> remote_wait,"TAAthread:" path if the
1612 stub doesn't support qC. This is the first stop reported
1613 after an attach, so this is the main thread. Update the
1614 ptid in the thread list. */
bad34192
PA
1615 if (in_thread_list (pid_to_ptid (pid)))
1616 thread_change_ptid (inferior_ptid, currthread);
1617 else
1618 {
1619 remote_add_thread (currthread, running);
1620 inferior_ptid = currthread;
1621 }
dc146f7c 1622 return;
c0a2216e 1623 }
82f73884
PA
1624
1625 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1626 {
1627 /* inferior_ptid is not set yet. This can happen with the
1628 vRun -> remote_wait,"TAAthread:" path if the stub
1629 doesn't support qC. This is the first stop reported
1630 after an attach, so this is the main thread. Update the
1631 ptid in the thread list. */
dc146f7c 1632 thread_change_ptid (inferior_ptid, currthread);
82f73884 1633 return;
c0a2216e 1634 }
82f73884 1635
29c87f7f
PA
1636 /* When connecting to a target remote, or to a target
1637 extended-remote which already was debugging an inferior, we
1638 may not know about it yet. Add it before adding its child
1639 thread, so notifications are emitted in a sensible order. */
1640 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1641 {
1642 struct remote_state *rs = get_remote_state ();
1643 int fake_pid_p = !remote_multi_process_p (rs);
1644
1645 inf = remote_add_inferior (fake_pid_p,
1646 ptid_get_pid (currthread), -1);
1647 }
29c87f7f 1648
82f73884 1649 /* This is really a new thread. Add it. */
1941c569
PA
1650 remote_add_thread (currthread, running);
1651
1652 /* If we found a new inferior, let the common code do whatever
1653 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1654 breakpoints), unless we're just setting up an all-stop
1655 connection. */
1941c569 1656 if (inf != NULL)
b7ea362b
PA
1657 {
1658 struct remote_state *rs = get_remote_state ();
1659
1660 if (non_stop || !rs->starting_up)
1661 notice_new_inferior (currthread, running, 0);
1662 }
c0a2216e 1663 }
c906108c
SS
1664}
1665
dc146f7c
VP
1666/* Return the private thread data, creating it if necessary. */
1667
70221824 1668static struct private_thread_info *
dc146f7c
VP
1669demand_private_info (ptid_t ptid)
1670{
1671 struct thread_info *info = find_thread_ptid (ptid);
1672
1673 gdb_assert (info);
1674
fe978cb0 1675 if (!info->priv)
dc146f7c 1676 {
fe978cb0 1677 info->priv = xmalloc (sizeof (*(info->priv)));
dc146f7c 1678 info->private_dtor = free_private_thread_info;
fe978cb0
PA
1679 info->priv->core = -1;
1680 info->priv->extra = 0;
dc146f7c
VP
1681 }
1682
fe978cb0 1683 return info->priv;
dc146f7c
VP
1684}
1685
74531fed
PA
1686/* Call this function as a result of
1687 1) A halt indication (T packet) containing a thread id
1688 2) A direct query of currthread
0df8b418 1689 3) Successful execution of set thread */
74531fed
PA
1690
1691static void
47f8a51d 1692record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1693{
47f8a51d 1694 rs->general_thread = currthread;
74531fed
PA
1695}
1696
89be2091
DJ
1697/* If 'QPassSignals' is supported, tell the remote stub what signals
1698 it can simply pass through to the inferior without reporting. */
1699
1700static void
94bedb42
TT
1701remote_pass_signals (struct target_ops *self,
1702 int numsigs, unsigned char *pass_signals)
89be2091 1703{
4082afcc 1704 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
1705 {
1706 char *pass_packet, *p;
89be2091 1707 int count = 0, i;
747dc59d 1708 struct remote_state *rs = get_remote_state ();
89be2091
DJ
1709
1710 gdb_assert (numsigs < 256);
1711 for (i = 0; i < numsigs; i++)
1712 {
2455069d 1713 if (pass_signals[i])
89be2091
DJ
1714 count++;
1715 }
1716 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1717 strcpy (pass_packet, "QPassSignals:");
1718 p = pass_packet + strlen (pass_packet);
1719 for (i = 0; i < numsigs; i++)
1720 {
2455069d 1721 if (pass_signals[i])
89be2091
DJ
1722 {
1723 if (i >= 16)
1724 *p++ = tohex (i >> 4);
1725 *p++ = tohex (i & 15);
1726 if (count)
1727 *p++ = ';';
1728 else
1729 break;
1730 count--;
1731 }
1732 }
1733 *p = 0;
747dc59d 1734 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 1735 {
89be2091
DJ
1736 putpkt (pass_packet);
1737 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1738 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
1739 if (rs->last_pass_packet)
1740 xfree (rs->last_pass_packet);
1741 rs->last_pass_packet = pass_packet;
89be2091
DJ
1742 }
1743 else
1744 xfree (pass_packet);
1745 }
1746}
1747
9b224c5e
PA
1748/* If 'QProgramSignals' is supported, tell the remote stub what
1749 signals it should pass through to the inferior when detaching. */
1750
1751static void
daf5e9b6
TT
1752remote_program_signals (struct target_ops *self,
1753 int numsigs, unsigned char *signals)
9b224c5e 1754{
4082afcc 1755 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
1756 {
1757 char *packet, *p;
1758 int count = 0, i;
5e4a05c4 1759 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
1760
1761 gdb_assert (numsigs < 256);
1762 for (i = 0; i < numsigs; i++)
1763 {
1764 if (signals[i])
1765 count++;
1766 }
1767 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1768 strcpy (packet, "QProgramSignals:");
1769 p = packet + strlen (packet);
1770 for (i = 0; i < numsigs; i++)
1771 {
1772 if (signal_pass_state (i))
1773 {
1774 if (i >= 16)
1775 *p++ = tohex (i >> 4);
1776 *p++ = tohex (i & 15);
1777 if (count)
1778 *p++ = ';';
1779 else
1780 break;
1781 count--;
1782 }
1783 }
1784 *p = 0;
5e4a05c4
TT
1785 if (!rs->last_program_signals_packet
1786 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 1787 {
9b224c5e
PA
1788 putpkt (packet);
1789 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1790 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
1791 xfree (rs->last_program_signals_packet);
1792 rs->last_program_signals_packet = packet;
9b224c5e
PA
1793 }
1794 else
1795 xfree (packet);
1796 }
1797}
1798
79d7f229
PA
1799/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1800 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1801 thread. If GEN is set, set the general thread, if not, then set
1802 the step/continue thread. */
c906108c 1803static void
79d7f229 1804set_thread (struct ptid ptid, int gen)
c906108c 1805{
d01949b6 1806 struct remote_state *rs = get_remote_state ();
47f8a51d 1807 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 1808 char *buf = rs->buf;
79d7f229 1809 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 1810
79d7f229 1811 if (ptid_equal (state, ptid))
c906108c
SS
1812 return;
1813
79d7f229
PA
1814 *buf++ = 'H';
1815 *buf++ = gen ? 'g' : 'c';
1816 if (ptid_equal (ptid, magic_null_ptid))
1817 xsnprintf (buf, endbuf - buf, "0");
1818 else if (ptid_equal (ptid, any_thread_ptid))
1819 xsnprintf (buf, endbuf - buf, "0");
1820 else if (ptid_equal (ptid, minus_one_ptid))
1821 xsnprintf (buf, endbuf - buf, "-1");
1822 else
82f73884 1823 write_ptid (buf, endbuf, ptid);
79d7f229 1824 putpkt (rs->buf);
6d820c5c 1825 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 1826 if (gen)
47f8a51d 1827 rs->general_thread = ptid;
c906108c 1828 else
47f8a51d 1829 rs->continue_thread = ptid;
c906108c 1830}
79d7f229
PA
1831
1832static void
1833set_general_thread (struct ptid ptid)
1834{
1835 set_thread (ptid, 1);
1836}
1837
1838static void
1839set_continue_thread (struct ptid ptid)
1840{
1841 set_thread (ptid, 0);
1842}
1843
3c9c4b83
PA
1844/* Change the remote current process. Which thread within the process
1845 ends up selected isn't important, as long as it is the same process
1846 as what INFERIOR_PTID points to.
1847
1848 This comes from that fact that there is no explicit notion of
1849 "selected process" in the protocol. The selected process for
1850 general operations is the process the selected general thread
1851 belongs to. */
1852
1853static void
1854set_general_process (void)
1855{
1856 struct remote_state *rs = get_remote_state ();
1857
1858 /* If the remote can't handle multiple processes, don't bother. */
901f9912 1859 if (!rs->extended || !remote_multi_process_p (rs))
3c9c4b83
PA
1860 return;
1861
1862 /* We only need to change the remote current thread if it's pointing
1863 at some other process. */
47f8a51d 1864 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
1865 set_general_thread (inferior_ptid);
1866}
1867
c906108c 1868\f
7d1a114c
PA
1869/* Return nonzero if this is the main thread that we made up ourselves
1870 to model non-threaded targets as single-threaded. */
c906108c
SS
1871
1872static int
7d1a114c 1873remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 1874{
6d820c5c 1875 struct remote_state *rs = get_remote_state ();
82f73884 1876 char *p, *endp;
c906108c 1877
c0a2216e
PA
1878 if (ptid_equal (ptid, magic_null_ptid))
1879 /* The main thread is always alive. */
1880 return 1;
1881
ba348170 1882 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
1883 /* The main thread is always alive. This can happen after a
1884 vAttach, if the remote side doesn't support
1885 multi-threading. */
1886 return 1;
1887
7d1a114c
PA
1888 return 0;
1889}
1890
1891/* Return nonzero if the thread PTID is still alive on the remote
1892 system. */
1893
1894static int
1895remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1896{
1897 struct remote_state *rs = get_remote_state ();
1898 char *p, *endp;
1899
1900 /* Check if this is a thread that we made up ourselves to model
1901 non-threaded targets as single-threaded. */
1902 if (remote_thread_always_alive (ops, ptid))
1903 return 1;
1904
82f73884
PA
1905 p = rs->buf;
1906 endp = rs->buf + get_remote_packet_size ();
1907
1908 *p++ = 'T';
1909 write_ptid (p, endp, ptid);
1910
2e9f7625 1911 putpkt (rs->buf);
6d820c5c 1912 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 1913 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
1914}
1915
1916/* About these extended threadlist and threadinfo packets. They are
1917 variable length packets but, the fields within them are often fixed
1918 length. They are redundent enough to send over UDP as is the
1919 remote protocol in general. There is a matching unit test module
1920 in libstub. */
1921
23860348 1922/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 1923 libstub protocol encoding, and remote.c. It is not particularly
23860348 1924 changable. */
cce74817
JM
1925
1926/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 1927 Plan to fix this. */
cce74817 1928
23860348 1929typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 1930
9d1f7ab2 1931/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 1932 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
1933
1934struct gdb_ext_thread_info
c5aa993b 1935 {
23860348 1936 threadref threadid; /* External form of thread reference. */
2bc416ba 1937 int active; /* Has state interesting to GDB?
23860348 1938 regs, stack. */
2bc416ba 1939 char display[256]; /* Brief state display, name,
cedea757 1940 blocked/suspended. */
23860348 1941 char shortname[32]; /* To be used to name threads. */
2bc416ba 1942 char more_display[256]; /* Long info, statistics, queue depth,
23860348 1943 whatever. */
c5aa993b 1944 };
cce74817
JM
1945
1946/* The volume of remote transfers can be limited by submitting
1947 a mask containing bits specifying the desired information.
1948 Use a union of these values as the 'selection' parameter to
0df8b418 1949 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
1950
1951#define TAG_THREADID 1
1952#define TAG_EXISTS 2
1953#define TAG_DISPLAY 4
1954#define TAG_THREADNAME 8
c5aa993b 1955#define TAG_MOREDISPLAY 16
cce74817 1956
23860348 1957#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 1958
a14ed312 1959static char *unpack_nibble (char *buf, int *val);
cce74817 1960
a14ed312 1961static char *unpack_byte (char *buf, int *value);
cce74817 1962
a14ed312 1963static char *pack_int (char *buf, int value);
cce74817 1964
a14ed312 1965static char *unpack_int (char *buf, int *value);
cce74817 1966
a14ed312 1967static char *unpack_string (char *src, char *dest, int length);
cce74817 1968
23860348 1969static char *pack_threadid (char *pkt, threadref *id);
cce74817 1970
23860348 1971static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 1972
23860348 1973void int_to_threadref (threadref *id, int value);
cce74817 1974
23860348 1975static int threadref_to_int (threadref *ref);
cce74817 1976
23860348 1977static void copy_threadref (threadref *dest, threadref *src);
cce74817 1978
23860348 1979static int threadmatch (threadref *dest, threadref *src);
cce74817 1980
2bc416ba 1981static char *pack_threadinfo_request (char *pkt, int mode,
23860348 1982 threadref *id);
cce74817 1983
a14ed312 1984static int remote_unpack_thread_info_response (char *pkt,
23860348 1985 threadref *expectedref,
a14ed312
KB
1986 struct gdb_ext_thread_info
1987 *info);
cce74817
JM
1988
1989
2bc416ba 1990static int remote_get_threadinfo (threadref *threadid,
23860348 1991 int fieldset, /*TAG mask */
a14ed312 1992 struct gdb_ext_thread_info *info);
cce74817 1993
a14ed312
KB
1994static char *pack_threadlist_request (char *pkt, int startflag,
1995 int threadcount,
23860348 1996 threadref *nextthread);
cce74817 1997
a14ed312
KB
1998static int parse_threadlist_response (char *pkt,
1999 int result_limit,
23860348 2000 threadref *original_echo,
2bc416ba 2001 threadref *resultlist,
23860348 2002 int *doneflag);
cce74817 2003
a14ed312 2004static int remote_get_threadlist (int startflag,
23860348 2005 threadref *nextthread,
a14ed312
KB
2006 int result_limit,
2007 int *done,
2bc416ba 2008 int *result_count,
23860348 2009 threadref *threadlist);
cce74817 2010
23860348 2011typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2012
a14ed312
KB
2013static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2014 void *context, int looplimit);
cce74817 2015
23860348 2016static int remote_newthread_step (threadref *ref, void *context);
cce74817 2017
82f73884
PA
2018
2019/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2020 buffer we're allowed to write to. Returns
2021 BUF+CHARACTERS_WRITTEN. */
2022
2023static char *
2024write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2025{
2026 int pid, tid;
2027 struct remote_state *rs = get_remote_state ();
2028
2029 if (remote_multi_process_p (rs))
2030 {
2031 pid = ptid_get_pid (ptid);
2032 if (pid < 0)
2033 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2034 else
2035 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2036 }
ba348170 2037 tid = ptid_get_lwp (ptid);
82f73884
PA
2038 if (tid < 0)
2039 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2040 else
2041 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2042
2043 return buf;
2044}
2045
2046/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2047 passed the last parsed char. Returns null_ptid on error. */
2048
2049static ptid_t
2050read_ptid (char *buf, char **obuf)
2051{
2052 char *p = buf;
2053 char *pp;
2054 ULONGEST pid = 0, tid = 0;
82f73884
PA
2055
2056 if (*p == 'p')
2057 {
2058 /* Multi-process ptid. */
2059 pp = unpack_varlen_hex (p + 1, &pid);
2060 if (*pp != '.')
b37520b6 2061 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2062
2063 p = pp;
2064 pp = unpack_varlen_hex (p + 1, &tid);
2065 if (obuf)
2066 *obuf = pp;
ba348170 2067 return ptid_build (pid, tid, 0);
82f73884
PA
2068 }
2069
2070 /* No multi-process. Just a tid. */
2071 pp = unpack_varlen_hex (p, &tid);
2072
2073 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2074 what's in inferior_ptid, unless it's null at this point. If so,
2075 then since there's no way to know the pid of the reported
2076 threads, use the magic number. */
2077 if (ptid_equal (inferior_ptid, null_ptid))
2078 pid = ptid_get_pid (magic_null_ptid);
2079 else
2080 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2081
2082 if (obuf)
2083 *obuf = pp;
ba348170 2084 return ptid_build (pid, tid, 0);
82f73884
PA
2085}
2086
c906108c 2087static int
fba45db2 2088stubhex (int ch)
c906108c
SS
2089{
2090 if (ch >= 'a' && ch <= 'f')
2091 return ch - 'a' + 10;
2092 if (ch >= '0' && ch <= '9')
2093 return ch - '0';
2094 if (ch >= 'A' && ch <= 'F')
2095 return ch - 'A' + 10;
2096 return -1;
2097}
2098
2099static int
fba45db2 2100stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2101{
2102 int nibble;
2103 int retval = 0;
2104
2105 while (fieldlength)
2106 {
2107 nibble = stubhex (*buff++);
2108 retval |= nibble;
2109 fieldlength--;
2110 if (fieldlength)
2111 retval = retval << 4;
2112 }
2113 return retval;
2114}
2115
c906108c 2116static char *
fba45db2 2117unpack_nibble (char *buf, int *val)
c906108c 2118{
b7589f7d 2119 *val = fromhex (*buf++);
c906108c
SS
2120 return buf;
2121}
2122
c906108c 2123static char *
fba45db2 2124unpack_byte (char *buf, int *value)
c906108c
SS
2125{
2126 *value = stub_unpack_int (buf, 2);
2127 return buf + 2;
2128}
2129
2130static char *
fba45db2 2131pack_int (char *buf, int value)
c906108c
SS
2132{
2133 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2134 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2135 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2136 buf = pack_hex_byte (buf, (value & 0xff));
2137 return buf;
2138}
2139
2140static char *
fba45db2 2141unpack_int (char *buf, int *value)
c906108c
SS
2142{
2143 *value = stub_unpack_int (buf, 8);
2144 return buf + 8;
2145}
2146
23860348 2147#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2148static char *pack_string (char *pkt, char *string);
c906108c
SS
2149
2150static char *
fba45db2 2151pack_string (char *pkt, char *string)
c906108c
SS
2152{
2153 char ch;
2154 int len;
2155
2156 len = strlen (string);
2157 if (len > 200)
23860348 2158 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2159 pkt = pack_hex_byte (pkt, len);
2160 while (len-- > 0)
2161 {
2162 ch = *string++;
2163 if ((ch == '\0') || (ch == '#'))
23860348 2164 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2165 *pkt++ = ch;
2166 }
2167 return pkt;
2168}
2169#endif /* 0 (unused) */
2170
2171static char *
fba45db2 2172unpack_string (char *src, char *dest, int length)
c906108c
SS
2173{
2174 while (length--)
2175 *dest++ = *src++;
2176 *dest = '\0';
2177 return src;
2178}
2179
2180static char *
fba45db2 2181pack_threadid (char *pkt, threadref *id)
c906108c
SS
2182{
2183 char *limit;
2184 unsigned char *altid;
2185
2186 altid = (unsigned char *) id;
2187 limit = pkt + BUF_THREAD_ID_SIZE;
2188 while (pkt < limit)
2189 pkt = pack_hex_byte (pkt, *altid++);
2190 return pkt;
2191}
2192
2193
2194static char *
fba45db2 2195unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2196{
2197 char *altref;
2198 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2199 int x, y;
2200
2201 altref = (char *) id;
2202
2203 while (inbuf < limit)
2204 {
2205 x = stubhex (*inbuf++);
2206 y = stubhex (*inbuf++);
2207 *altref++ = (x << 4) | y;
2208 }
2209 return inbuf;
2210}
2211
2212/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2213 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2214 to use 64bit thread references internally. This is an adapter
2215 function. */
2216
2217void
fba45db2 2218int_to_threadref (threadref *id, int value)
c906108c
SS
2219{
2220 unsigned char *scan;
2221
2222 scan = (unsigned char *) id;
2223 {
2224 int i = 4;
2225 while (i--)
2226 *scan++ = 0;
2227 }
2228 *scan++ = (value >> 24) & 0xff;
2229 *scan++ = (value >> 16) & 0xff;
2230 *scan++ = (value >> 8) & 0xff;
2231 *scan++ = (value & 0xff);
2232}
2233
2234static int
fba45db2 2235threadref_to_int (threadref *ref)
c906108c
SS
2236{
2237 int i, value = 0;
2238 unsigned char *scan;
2239
cfd77fa1 2240 scan = *ref;
c906108c
SS
2241 scan += 4;
2242 i = 4;
2243 while (i-- > 0)
2244 value = (value << 8) | ((*scan++) & 0xff);
2245 return value;
2246}
2247
2248static void
fba45db2 2249copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2250{
2251 int i;
2252 unsigned char *csrc, *cdest;
2253
2254 csrc = (unsigned char *) src;
2255 cdest = (unsigned char *) dest;
2256 i = 8;
2257 while (i--)
2258 *cdest++ = *csrc++;
2259}
2260
2261static int
fba45db2 2262threadmatch (threadref *dest, threadref *src)
c906108c 2263{
23860348 2264 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2265#if 0
2266 unsigned char *srcp, *destp;
2267 int i, result;
2268 srcp = (char *) src;
2269 destp = (char *) dest;
2270
2271 result = 1;
2272 while (i-- > 0)
2273 result &= (*srcp++ == *destp++) ? 1 : 0;
2274 return result;
2275#endif
2276 return 1;
2277}
2278
2279/*
c5aa993b
JM
2280 threadid:1, # always request threadid
2281 context_exists:2,
2282 display:4,
2283 unique_name:8,
2284 more_display:16
2285 */
c906108c
SS
2286
2287/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2288
2289static char *
fba45db2 2290pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2291{
23860348
MS
2292 *pkt++ = 'q'; /* Info Query */
2293 *pkt++ = 'P'; /* process or thread info */
2294 pkt = pack_int (pkt, mode); /* mode */
c906108c 2295 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2296 *pkt = '\0'; /* terminate */
c906108c
SS
2297 return pkt;
2298}
2299
23860348 2300/* These values tag the fields in a thread info response packet. */
c906108c 2301/* Tagging the fields allows us to request specific fields and to
23860348 2302 add more fields as time goes by. */
c906108c 2303
23860348 2304#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2305#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2306 fetch registers and its stack? */
c5aa993b 2307#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2308#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2309#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2310 the process. */
c906108c
SS
2311
2312static int
fba45db2
KB
2313remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2314 struct gdb_ext_thread_info *info)
c906108c 2315{
d01949b6 2316 struct remote_state *rs = get_remote_state ();
c906108c 2317 int mask, length;
cfd77fa1 2318 int tag;
c906108c 2319 threadref ref;
6d820c5c 2320 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2321 int retval = 1;
2322
23860348 2323 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2324 info->active = 0;
2325 info->display[0] = '\0';
2326 info->shortname[0] = '\0';
2327 info->more_display[0] = '\0';
2328
23860348
MS
2329 /* Assume the characters indicating the packet type have been
2330 stripped. */
c906108c
SS
2331 pkt = unpack_int (pkt, &mask); /* arg mask */
2332 pkt = unpack_threadid (pkt, &ref);
2333
2334 if (mask == 0)
8a3fe4f8 2335 warning (_("Incomplete response to threadinfo request."));
c906108c 2336 if (!threadmatch (&ref, expectedref))
23860348 2337 { /* This is an answer to a different request. */
8a3fe4f8 2338 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2339 return 0;
2340 }
2341 copy_threadref (&info->threadid, &ref);
2342
23860348 2343 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2344
23860348
MS
2345 /* Packets are terminated with nulls. */
2346 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2347 {
2348 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2349 pkt = unpack_byte (pkt, &length); /* length */
2350 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2351 {
8a3fe4f8 2352 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2353 retval = 0;
2354 break;
2355 }
2356 if (tag == TAG_THREADID)
2357 {
2358 if (length != 16)
2359 {
8a3fe4f8 2360 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2361 retval = 0;
2362 break;
2363 }
2364 pkt = unpack_threadid (pkt, &ref);
2365 mask = mask & ~TAG_THREADID;
2366 continue;
2367 }
2368 if (tag == TAG_EXISTS)
2369 {
2370 info->active = stub_unpack_int (pkt, length);
2371 pkt += length;
2372 mask = mask & ~(TAG_EXISTS);
2373 if (length > 8)
2374 {
8a3fe4f8 2375 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2376 retval = 0;
2377 break;
2378 }
2379 continue;
2380 }
2381 if (tag == TAG_THREADNAME)
2382 {
2383 pkt = unpack_string (pkt, &info->shortname[0], length);
2384 mask = mask & ~TAG_THREADNAME;
2385 continue;
2386 }
2387 if (tag == TAG_DISPLAY)
2388 {
2389 pkt = unpack_string (pkt, &info->display[0], length);
2390 mask = mask & ~TAG_DISPLAY;
2391 continue;
2392 }
2393 if (tag == TAG_MOREDISPLAY)
2394 {
2395 pkt = unpack_string (pkt, &info->more_display[0], length);
2396 mask = mask & ~TAG_MOREDISPLAY;
2397 continue;
2398 }
8a3fe4f8 2399 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2400 break; /* Not a tag we know about. */
c906108c
SS
2401 }
2402 return retval;
2403}
2404
2405static int
fba45db2
KB
2406remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2407 struct gdb_ext_thread_info *info)
c906108c 2408{
d01949b6 2409 struct remote_state *rs = get_remote_state ();
c906108c 2410 int result;
c906108c 2411
2e9f7625
DJ
2412 pack_threadinfo_request (rs->buf, fieldset, threadid);
2413 putpkt (rs->buf);
6d820c5c 2414 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2415
2416 if (rs->buf[0] == '\0')
2417 return 0;
2418
2e9f7625 2419 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2420 threadid, info);
c906108c
SS
2421 return result;
2422}
2423
c906108c
SS
2424/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2425
2426static char *
fba45db2
KB
2427pack_threadlist_request (char *pkt, int startflag, int threadcount,
2428 threadref *nextthread)
c906108c
SS
2429{
2430 *pkt++ = 'q'; /* info query packet */
2431 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2432 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2433 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2434 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2435 *pkt = '\0';
2436 return pkt;
2437}
2438
2439/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2440
2441static int
fba45db2
KB
2442parse_threadlist_response (char *pkt, int result_limit,
2443 threadref *original_echo, threadref *resultlist,
2444 int *doneflag)
c906108c 2445{
d01949b6 2446 struct remote_state *rs = get_remote_state ();
c906108c
SS
2447 char *limit;
2448 int count, resultcount, done;
2449
2450 resultcount = 0;
2451 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2452 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2453 /* done parse past here */
c906108c
SS
2454 pkt = unpack_byte (pkt, &count); /* count field */
2455 pkt = unpack_nibble (pkt, &done);
2456 /* The first threadid is the argument threadid. */
2457 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2458 while ((count-- > 0) && (pkt < limit))
2459 {
2460 pkt = unpack_threadid (pkt, resultlist++);
2461 if (resultcount++ >= result_limit)
2462 break;
2463 }
2464 if (doneflag)
2465 *doneflag = done;
2466 return resultcount;
2467}
2468
6dc54d91
PA
2469/* Fetch the next batch of threads from the remote. Returns -1 if the
2470 qL packet is not supported, 0 on error and 1 on success. */
2471
c906108c 2472static int
fba45db2
KB
2473remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2474 int *done, int *result_count, threadref *threadlist)
c906108c 2475{
d01949b6 2476 struct remote_state *rs = get_remote_state ();
c906108c
SS
2477 int result = 1;
2478
23860348 2479 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2480 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2481 >= get_remote_packet_size ())
ea9c271d 2482 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2483
6d820c5c
DJ
2484 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2485 putpkt (rs->buf);
2486 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2487 if (*rs->buf == '\0')
6dc54d91
PA
2488 {
2489 /* Packet not supported. */
2490 return -1;
2491 }
2492
2493 *result_count =
2494 parse_threadlist_response (rs->buf + 2, result_limit,
2495 &rs->echo_nextthread, threadlist, done);
c906108c 2496
0d031856 2497 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2498 {
23860348
MS
2499 /* FIXME: This is a good reason to drop the packet. */
2500 /* Possably, there is a duplicate response. */
c906108c
SS
2501 /* Possabilities :
2502 retransmit immediatly - race conditions
2503 retransmit after timeout - yes
2504 exit
2505 wait for packet, then exit
2506 */
8a3fe4f8 2507 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2508 return 0; /* I choose simply exiting. */
c906108c
SS
2509 }
2510 if (*result_count <= 0)
2511 {
2512 if (*done != 1)
2513 {
8a3fe4f8 2514 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2515 result = 0;
2516 }
2517 return result; /* break; */
2518 }
2519 if (*result_count > result_limit)
2520 {
2521 *result_count = 0;
8a3fe4f8 2522 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2523 return 0;
2524 }
2525 return result;
2526}
2527
6dc54d91
PA
2528/* Fetch the list of remote threads, with the qL packet, and call
2529 STEPFUNCTION for each thread found. Stops iterating and returns 1
2530 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2531 STEPFUNCTION returns false. If the packet is not supported,
2532 returns -1. */
c906108c 2533
c906108c 2534static int
fba45db2
KB
2535remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2536 int looplimit)
c906108c 2537{
0d031856 2538 struct remote_state *rs = get_remote_state ();
c906108c
SS
2539 int done, i, result_count;
2540 int startflag = 1;
2541 int result = 1;
2542 int loopcount = 0;
c906108c
SS
2543
2544 done = 0;
2545 while (!done)
2546 {
2547 if (loopcount++ > looplimit)
2548 {
2549 result = 0;
8a3fe4f8 2550 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2551 break;
2552 }
6dc54d91
PA
2553 result = remote_get_threadlist (startflag, &rs->nextthread,
2554 MAXTHREADLISTRESULTS,
2555 &done, &result_count,
2556 rs->resultthreadlist);
2557 if (result <= 0)
2558 break;
23860348 2559 /* Clear for later iterations. */
c906108c
SS
2560 startflag = 0;
2561 /* Setup to resume next batch of thread references, set nextthread. */
2562 if (result_count >= 1)
0d031856
TT
2563 copy_threadref (&rs->nextthread,
2564 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2565 i = 0;
2566 while (result_count--)
6dc54d91
PA
2567 {
2568 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2569 {
2570 result = 0;
2571 break;
2572 }
2573 }
c906108c
SS
2574 }
2575 return result;
2576}
2577
6dc54d91
PA
2578/* A thread found on the remote target. */
2579
2580typedef struct thread_item
2581{
2582 /* The thread's PTID. */
2583 ptid_t ptid;
2584
2585 /* The thread's extra info. May be NULL. */
2586 char *extra;
2587
2588 /* The core the thread was running on. -1 if not known. */
2589 int core;
2590} thread_item_t;
2591DEF_VEC_O(thread_item_t);
2592
2593/* Context passed around to the various methods listing remote
2594 threads. As new threads are found, they're added to the ITEMS
2595 vector. */
2596
2597struct threads_listing_context
2598{
2599 /* The threads found on the remote target. */
2600 VEC (thread_item_t) *items;
2601};
2602
80134cf5
PA
2603/* Discard the contents of the constructed thread listing context. */
2604
2605static void
2606clear_threads_listing_context (void *p)
2607{
2608 struct threads_listing_context *context = p;
2609 int i;
2610 struct thread_item *item;
2611
2612 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2613 xfree (item->extra);
2614
2615 VEC_free (thread_item_t, context->items);
2616}
2617
c906108c 2618static int
6dc54d91 2619remote_newthread_step (threadref *ref, void *data)
c906108c 2620{
6dc54d91
PA
2621 struct threads_listing_context *context = data;
2622 struct thread_item item;
79d7f229 2623 int pid = ptid_get_pid (inferior_ptid);
39f77062 2624
6dc54d91
PA
2625 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2626 item.core = -1;
2627 item.extra = NULL;
2628
2629 VEC_safe_push (thread_item_t, context->items, &item);
2630
c906108c
SS
2631 return 1; /* continue iterator */
2632}
2633
2634#define CRAZY_MAX_THREADS 1000
2635
39f77062
KB
2636static ptid_t
2637remote_current_thread (ptid_t oldpid)
c906108c 2638{
d01949b6 2639 struct remote_state *rs = get_remote_state ();
c906108c
SS
2640
2641 putpkt ("qC");
6d820c5c 2642 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2643 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
82f73884 2644 return read_ptid (&rs->buf[2], NULL);
c906108c
SS
2645 else
2646 return oldpid;
2647}
2648
6dc54d91 2649/* List remote threads using the deprecated qL packet. */
cce74817 2650
6dc54d91
PA
2651static int
2652remote_get_threads_with_ql (struct target_ops *ops,
2653 struct threads_listing_context *context)
c906108c 2654{
6dc54d91
PA
2655 if (remote_threadlist_iterator (remote_newthread_step, context,
2656 CRAZY_MAX_THREADS) >= 0)
2657 return 1;
2658
2659 return 0;
c906108c
SS
2660}
2661
dc146f7c
VP
2662#if defined(HAVE_LIBEXPAT)
2663
dc146f7c
VP
2664static void
2665start_thread (struct gdb_xml_parser *parser,
2666 const struct gdb_xml_element *element,
2667 void *user_data, VEC(gdb_xml_value_s) *attributes)
2668{
6dc54d91 2669 struct threads_listing_context *data = user_data;
dc146f7c
VP
2670
2671 struct thread_item item;
2672 char *id;
3d2c1d41 2673 struct gdb_xml_value *attr;
dc146f7c 2674
3d2c1d41 2675 id = xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
2676 item.ptid = read_ptid (id, NULL);
2677
3d2c1d41
PA
2678 attr = xml_find_attribute (attributes, "core");
2679 if (attr != NULL)
2680 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
2681 else
2682 item.core = -1;
2683
2684 item.extra = 0;
2685
2686 VEC_safe_push (thread_item_t, data->items, &item);
2687}
2688
2689static void
2690end_thread (struct gdb_xml_parser *parser,
2691 const struct gdb_xml_element *element,
2692 void *user_data, const char *body_text)
2693{
6dc54d91 2694 struct threads_listing_context *data = user_data;
dc146f7c
VP
2695
2696 if (body_text && *body_text)
2ae2a0b7 2697 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
2698}
2699
2700const struct gdb_xml_attribute thread_attributes[] = {
2701 { "id", GDB_XML_AF_NONE, NULL, NULL },
2702 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2703 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2704};
2705
2706const struct gdb_xml_element thread_children[] = {
2707 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2708};
2709
2710const struct gdb_xml_element threads_children[] = {
2711 { "thread", thread_attributes, thread_children,
2712 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2713 start_thread, end_thread },
2714 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2715};
2716
2717const struct gdb_xml_element threads_elements[] = {
2718 { "threads", NULL, threads_children,
2719 GDB_XML_EF_NONE, NULL, NULL },
2720 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2721};
2722
2723#endif
2724
6dc54d91 2725/* List remote threads using qXfer:threads:read. */
9d1f7ab2 2726
6dc54d91
PA
2727static int
2728remote_get_threads_with_qxfer (struct target_ops *ops,
2729 struct threads_listing_context *context)
0f71a2f6 2730{
dc146f7c 2731#if defined(HAVE_LIBEXPAT)
4082afcc 2732 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 2733 {
6dc54d91 2734 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 2735 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 2736
6dc54d91 2737 if (xml != NULL && *xml != '\0')
dc146f7c 2738 {
6dc54d91
PA
2739 gdb_xml_parse_quick (_("threads"), "threads.dtd",
2740 threads_elements, xml, context);
dc146f7c
VP
2741 }
2742
2743 do_cleanups (back_to);
6dc54d91 2744 return 1;
dc146f7c
VP
2745 }
2746#endif
2747
6dc54d91
PA
2748 return 0;
2749}
2750
2751/* List remote threads using qfThreadInfo/qsThreadInfo. */
2752
2753static int
2754remote_get_threads_with_qthreadinfo (struct target_ops *ops,
2755 struct threads_listing_context *context)
2756{
2757 struct remote_state *rs = get_remote_state ();
2758
b80fafe3 2759 if (rs->use_threadinfo_query)
9d1f7ab2 2760 {
6dc54d91
PA
2761 char *bufp;
2762
9d1f7ab2 2763 putpkt ("qfThreadInfo");
6d820c5c 2764 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2765 bufp = rs->buf;
9d1f7ab2 2766 if (bufp[0] != '\0') /* q packet recognized */
802188a7 2767 {
9d1f7ab2
MS
2768 while (*bufp++ == 'm') /* reply contains one or more TID */
2769 {
2770 do
2771 {
6dc54d91
PA
2772 struct thread_item item;
2773
2774 item.ptid = read_ptid (bufp, &bufp);
2775 item.core = -1;
2776 item.extra = NULL;
2777
2778 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
2779 }
2780 while (*bufp++ == ','); /* comma-separated list */
2781 putpkt ("qsThreadInfo");
6d820c5c 2782 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 2783 bufp = rs->buf;
9d1f7ab2 2784 }
6dc54d91
PA
2785 return 1;
2786 }
2787 else
2788 {
2789 /* Packet not recognized. */
2790 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
2791 }
2792 }
2793
6dc54d91
PA
2794 return 0;
2795}
2796
e8032dde 2797/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
2798 targets. */
2799
2800static void
e8032dde 2801remote_update_thread_list (struct target_ops *ops)
6dc54d91
PA
2802{
2803 struct remote_state *rs = get_remote_state ();
2804 struct threads_listing_context context;
2805 struct cleanup *old_chain;
ab970af1 2806 int got_list = 0;
e8032dde 2807
6dc54d91
PA
2808 context.items = NULL;
2809 old_chain = make_cleanup (clear_threads_listing_context, &context);
2810
2811 /* We have a few different mechanisms to fetch the thread list. Try
2812 them all, starting with the most preferred one first, falling
2813 back to older methods. */
2814 if (remote_get_threads_with_qxfer (ops, &context)
2815 || remote_get_threads_with_qthreadinfo (ops, &context)
2816 || remote_get_threads_with_ql (ops, &context))
2817 {
2818 int i;
2819 struct thread_item *item;
ab970af1
PA
2820 struct thread_info *tp, *tmp;
2821
2822 got_list = 1;
2823
7d1a114c
PA
2824 if (VEC_empty (thread_item_t, context.items)
2825 && remote_thread_always_alive (ops, inferior_ptid))
2826 {
2827 /* Some targets don't really support threads, but still
2828 reply an (empty) thread list in response to the thread
2829 listing packets, instead of replying "packet not
2830 supported". Exit early so we don't delete the main
2831 thread. */
2832 do_cleanups (old_chain);
2833 return;
2834 }
2835
ab970af1
PA
2836 /* CONTEXT now holds the current thread list on the remote
2837 target end. Delete GDB-side threads no longer found on the
2838 target. */
8a06aea7 2839 ALL_THREADS_SAFE (tp, tmp)
ab970af1
PA
2840 {
2841 for (i = 0;
2842 VEC_iterate (thread_item_t, context.items, i, item);
2843 ++i)
2844 {
2845 if (ptid_equal (item->ptid, tp->ptid))
2846 break;
2847 }
2848
2849 if (i == VEC_length (thread_item_t, context.items))
2850 {
2851 /* Not found. */
2852 delete_thread (tp->ptid);
2853 }
2854 }
74531fed 2855
ab970af1 2856 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
2857 for (i = 0;
2858 VEC_iterate (thread_item_t, context.items, i, item);
2859 ++i)
2860 {
2861 if (!ptid_equal (item->ptid, null_ptid))
2862 {
2863 struct private_thread_info *info;
2864 /* In non-stop mode, we assume new found threads are
2865 running until proven otherwise with a stop reply. In
2866 all-stop, we can only get here if all threads are
2867 stopped. */
2868 int running = non_stop ? 1 : 0;
2869
2870 remote_notice_new_inferior (item->ptid, running);
2871
2872 info = demand_private_info (item->ptid);
2873 info->core = item->core;
2874 info->extra = item->extra;
2875 item->extra = NULL;
2876 }
2877 }
2878 }
2879
ab970af1
PA
2880 if (!got_list)
2881 {
2882 /* If no thread listing method is supported, then query whether
2883 each known thread is alive, one by one, with the T packet.
2884 If the target doesn't support threads at all, then this is a
2885 no-op. See remote_thread_alive. */
2886 prune_threads ();
2887 }
2888
6dc54d91 2889 do_cleanups (old_chain);
9d1f7ab2
MS
2890}
2891
802188a7 2892/*
9d1f7ab2
MS
2893 * Collect a descriptive string about the given thread.
2894 * The target may say anything it wants to about the thread
2895 * (typically info about its blocked / runnable state, name, etc.).
2896 * This string will appear in the info threads display.
802188a7 2897 *
9d1f7ab2
MS
2898 * Optional: targets are not required to implement this function.
2899 */
2900
2901static char *
c15906d8 2902remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 2903{
d01949b6 2904 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
2905 int result;
2906 int set;
2907 threadref id;
2908 struct gdb_ext_thread_info threadinfo;
23860348 2909 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
2910 int n = 0; /* position in display_buf */
2911
5d93a237 2912 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 2913 internal_error (__FILE__, __LINE__,
e2e0b3e5 2914 _("remote_threads_extra_info"));
9d1f7ab2 2915
60e569b9 2916 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 2917 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
2918 /* This is the main thread which was added by GDB. The remote
2919 server doesn't know about it. */
2920 return NULL;
2921
4082afcc 2922 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
2923 {
2924 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 2925
fe978cb0
PA
2926 if (info && info->priv)
2927 return info->priv->extra;
dc146f7c
VP
2928 else
2929 return NULL;
2930 }
2931
b80fafe3 2932 if (rs->use_threadextra_query)
9d1f7ab2 2933 {
82f73884
PA
2934 char *b = rs->buf;
2935 char *endb = rs->buf + get_remote_packet_size ();
2936
2937 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2938 b += strlen (b);
2939 write_ptid (b, endb, tp->ptid);
2940
2e9f7625 2941 putpkt (rs->buf);
6d820c5c 2942 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2943 if (rs->buf[0] != 0)
9d1f7ab2 2944 {
2e9f7625
DJ
2945 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2946 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 2947 display_buf [result] = '\0';
9d1f7ab2
MS
2948 return display_buf;
2949 }
0f71a2f6 2950 }
9d1f7ab2
MS
2951
2952 /* If the above query fails, fall back to the old method. */
b80fafe3 2953 rs->use_threadextra_query = 0;
9d1f7ab2
MS
2954 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2955 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 2956 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
2957 if (remote_get_threadinfo (&id, set, &threadinfo))
2958 if (threadinfo.active)
0f71a2f6 2959 {
9d1f7ab2 2960 if (*threadinfo.shortname)
2bc416ba 2961 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 2962 " Name: %s,", threadinfo.shortname);
9d1f7ab2 2963 if (*threadinfo.display)
2bc416ba 2964 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 2965 " State: %s,", threadinfo.display);
9d1f7ab2 2966 if (*threadinfo.more_display)
2bc416ba 2967 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 2968 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
2969
2970 if (n > 0)
c5aa993b 2971 {
23860348 2972 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
2973 if (',' == display_buf[n-1])
2974 display_buf[n-1] = ' ';
2975 return display_buf;
c5aa993b 2976 }
0f71a2f6 2977 }
9d1f7ab2 2978 return NULL;
0f71a2f6 2979}
c906108c 2980\f
c5aa993b 2981
0fb4aa4b 2982static int
61fc905d 2983remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
2984 struct static_tracepoint_marker *marker)
2985{
2986 struct remote_state *rs = get_remote_state ();
2987 char *p = rs->buf;
2988
bba74b36 2989 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
2990 p += strlen (p);
2991 p += hexnumstr (p, addr);
2992 putpkt (rs->buf);
2993 getpkt (&rs->buf, &rs->buf_size, 0);
2994 p = rs->buf;
2995
2996 if (*p == 'E')
2997 error (_("Remote failure reply: %s"), p);
2998
2999 if (*p++ == 'm')
3000 {
3001 parse_static_tracepoint_marker_definition (p, &p, marker);
3002 return 1;
3003 }
3004
3005 return 0;
3006}
3007
0fb4aa4b 3008static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3009remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3010 const char *strid)
0fb4aa4b
PA
3011{
3012 struct remote_state *rs = get_remote_state ();
3013 VEC(static_tracepoint_marker_p) *markers = NULL;
3014 struct static_tracepoint_marker *marker = NULL;
3015 struct cleanup *old_chain;
3016 char *p;
3017
3018 /* Ask for a first packet of static tracepoint marker
3019 definition. */
3020 putpkt ("qTfSTM");
3021 getpkt (&rs->buf, &rs->buf_size, 0);
3022 p = rs->buf;
3023 if (*p == 'E')
3024 error (_("Remote failure reply: %s"), p);
3025
3026 old_chain = make_cleanup (free_current_marker, &marker);
3027
3028 while (*p++ == 'm')
3029 {
3030 if (marker == NULL)
3031 marker = XCNEW (struct static_tracepoint_marker);
3032
3033 do
3034 {
3035 parse_static_tracepoint_marker_definition (p, &p, marker);
3036
3037 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3038 {
3039 VEC_safe_push (static_tracepoint_marker_p,
3040 markers, marker);
3041 marker = NULL;
3042 }
3043 else
3044 {
3045 release_static_tracepoint_marker (marker);
3046 memset (marker, 0, sizeof (*marker));
3047 }
3048 }
3049 while (*p++ == ','); /* comma-separated list */
3050 /* Ask for another packet of static tracepoint definition. */
3051 putpkt ("qTsSTM");
3052 getpkt (&rs->buf, &rs->buf_size, 0);
3053 p = rs->buf;
3054 }
3055
3056 do_cleanups (old_chain);
3057 return markers;
3058}
3059
3060\f
10760264
JB
3061/* Implement the to_get_ada_task_ptid function for the remote targets. */
3062
3063static ptid_t
1e6b91a4 3064remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3065{
ba348170 3066 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3067}
3068\f
3069
24b06219 3070/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3071
3072static void
fba45db2 3073extended_remote_restart (void)
c906108c 3074{
d01949b6 3075 struct remote_state *rs = get_remote_state ();
c906108c
SS
3076
3077 /* Send the restart command; for reasons I don't understand the
3078 remote side really expects a number after the "R". */
ea9c271d 3079 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3080 putpkt (rs->buf);
c906108c 3081
ad9a8f3f 3082 remote_fileio_reset ();
c906108c
SS
3083}
3084\f
3085/* Clean up connection to a remote debugger. */
3086
c906108c 3087static void
de90e03d 3088remote_close (struct target_ops *self)
c906108c 3089{
5d93a237
TT
3090 struct remote_state *rs = get_remote_state ();
3091
3092 if (rs->remote_desc == NULL)
d3fd5342
PA
3093 return; /* already closed */
3094
3095 /* Make sure we leave stdin registered in the event loop, and we
3096 don't leave the async SIGINT signal handler installed. */
e3594fd1 3097 remote_terminal_ours (self);
ce5ce7ed 3098
5d93a237
TT
3099 serial_close (rs->remote_desc);
3100 rs->remote_desc = NULL;
ce5ce7ed
PA
3101
3102 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3103 of all the inferiors and their threads we were controlling.
3104 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3105 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3106 inferior_ptid = null_ptid;
f67fd822 3107 discard_all_inferiors ();
ce5ce7ed 3108
f48ff2a7
YQ
3109 /* We are closing the remote target, so we should discard
3110 everything of this target. */
bcc75809 3111 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3112
3113 if (remote_async_inferior_event_token)
3114 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3115
5965e028 3116 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3117
3118 trace_reset_local_state ();
c906108c
SS
3119}
3120
23860348 3121/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3122
3123static void
fba45db2 3124get_offsets (void)
c906108c 3125{
d01949b6 3126 struct remote_state *rs = get_remote_state ();
2e9f7625 3127 char *buf;
085dd6e6 3128 char *ptr;
31d99776
DJ
3129 int lose, num_segments = 0, do_sections, do_segments;
3130 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3131 struct section_offsets *offs;
31d99776
DJ
3132 struct symfile_segment_data *data;
3133
3134 if (symfile_objfile == NULL)
3135 return;
c906108c
SS
3136
3137 putpkt ("qOffsets");
6d820c5c 3138 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3139 buf = rs->buf;
c906108c
SS
3140
3141 if (buf[0] == '\000')
3142 return; /* Return silently. Stub doesn't support
23860348 3143 this command. */
c906108c
SS
3144 if (buf[0] == 'E')
3145 {
8a3fe4f8 3146 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3147 return;
3148 }
3149
3150 /* Pick up each field in turn. This used to be done with scanf, but
3151 scanf will make trouble if CORE_ADDR size doesn't match
3152 conversion directives correctly. The following code will work
3153 with any size of CORE_ADDR. */
3154 text_addr = data_addr = bss_addr = 0;
3155 ptr = buf;
3156 lose = 0;
3157
61012eef 3158 if (startswith (ptr, "Text="))
c906108c
SS
3159 {
3160 ptr += 5;
3161 /* Don't use strtol, could lose on big values. */
3162 while (*ptr && *ptr != ';')
3163 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3164
61012eef 3165 if (startswith (ptr, ";Data="))
31d99776
DJ
3166 {
3167 ptr += 6;
3168 while (*ptr && *ptr != ';')
3169 data_addr = (data_addr << 4) + fromhex (*ptr++);
3170 }
3171 else
3172 lose = 1;
3173
61012eef 3174 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3175 {
3176 ptr += 5;
3177 while (*ptr && *ptr != ';')
3178 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3179
31d99776
DJ
3180 if (bss_addr != data_addr)
3181 warning (_("Target reported unsupported offsets: %s"), buf);
3182 }
3183 else
3184 lose = 1;
3185 }
61012eef 3186 else if (startswith (ptr, "TextSeg="))
c906108c 3187 {
31d99776
DJ
3188 ptr += 8;
3189 /* Don't use strtol, could lose on big values. */
c906108c 3190 while (*ptr && *ptr != ';')
31d99776
DJ
3191 text_addr = (text_addr << 4) + fromhex (*ptr++);
3192 num_segments = 1;
3193
61012eef 3194 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3195 {
3196 ptr += 9;
3197 while (*ptr && *ptr != ';')
3198 data_addr = (data_addr << 4) + fromhex (*ptr++);
3199 num_segments++;
3200 }
c906108c
SS
3201 }
3202 else
3203 lose = 1;
3204
3205 if (lose)
8a3fe4f8 3206 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3207 else if (*ptr != '\0')
3208 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3209
802188a7 3210 offs = ((struct section_offsets *)
a39a16c4 3211 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3212 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3213 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3214
31d99776
DJ
3215 data = get_symfile_segment_data (symfile_objfile->obfd);
3216 do_segments = (data != NULL);
3217 do_sections = num_segments == 0;
c906108c 3218
28c32713 3219 if (num_segments > 0)
31d99776 3220 {
31d99776
DJ
3221 segments[0] = text_addr;
3222 segments[1] = data_addr;
3223 }
28c32713
JB
3224 /* If we have two segments, we can still try to relocate everything
3225 by assuming that the .text and .data offsets apply to the whole
3226 text and data segments. Convert the offsets given in the packet
3227 to base addresses for symfile_map_offsets_to_segments. */
3228 else if (data && data->num_segments == 2)
3229 {
3230 segments[0] = data->segment_bases[0] + text_addr;
3231 segments[1] = data->segment_bases[1] + data_addr;
3232 num_segments = 2;
3233 }
8d385431
DJ
3234 /* If the object file has only one segment, assume that it is text
3235 rather than data; main programs with no writable data are rare,
3236 but programs with no code are useless. Of course the code might
3237 have ended up in the data segment... to detect that we would need
3238 the permissions here. */
3239 else if (data && data->num_segments == 1)
3240 {
3241 segments[0] = data->segment_bases[0] + text_addr;
3242 num_segments = 1;
3243 }
28c32713
JB
3244 /* There's no way to relocate by segment. */
3245 else
3246 do_segments = 0;
31d99776
DJ
3247
3248 if (do_segments)
3249 {
3250 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3251 offs, num_segments, segments);
3252
3253 if (ret == 0 && !do_sections)
3e43a32a
MS
3254 error (_("Can not handle qOffsets TextSeg "
3255 "response with this symbol file"));
31d99776
DJ
3256
3257 if (ret > 0)
3258 do_sections = 0;
3259 }
c906108c 3260
9ef895d6
DJ
3261 if (data)
3262 free_symfile_segment_data (data);
31d99776
DJ
3263
3264 if (do_sections)
3265 {
3266 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3267
3e43a32a
MS
3268 /* This is a temporary kludge to force data and bss to use the
3269 same offsets because that's what nlmconv does now. The real
3270 solution requires changes to the stub and remote.c that I
3271 don't have time to do right now. */
31d99776
DJ
3272
3273 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3274 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3275 }
c906108c
SS
3276
3277 objfile_relocate (symfile_objfile, offs);
3278}
3279
74531fed
PA
3280/* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3281 threads we know are stopped already. This is used during the
3282 initial remote connection in non-stop mode --- threads that are
3283 reported as already being stopped are left stopped. */
3284
3285static int
3286set_stop_requested_callback (struct thread_info *thread, void *data)
3287{
3288 /* If we have a stop reply for this thread, it must be stopped. */
3289 if (peek_stop_reply (thread->ptid))
3290 set_stop_requested (thread->ptid, 1);
3291
3292 return 0;
3293}
3294
9a7071a8
JB
3295/* Send interrupt_sequence to remote target. */
3296static void
eeae04df 3297send_interrupt_sequence (void)
9a7071a8 3298{
5d93a237
TT
3299 struct remote_state *rs = get_remote_state ();
3300
9a7071a8 3301 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3302 remote_serial_write ("\x03", 1);
9a7071a8 3303 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3304 serial_send_break (rs->remote_desc);
9a7071a8
JB
3305 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3306 {
5d93a237 3307 serial_send_break (rs->remote_desc);
c33e31fd 3308 remote_serial_write ("g", 1);
9a7071a8
JB
3309 }
3310 else
3311 internal_error (__FILE__, __LINE__,
3312 _("Invalid value for interrupt_sequence_mode: %s."),
3313 interrupt_sequence_mode);
3314}
3315
3405876a
PA
3316
3317/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3318 and extract the PTID. Returns NULL_PTID if not found. */
3319
3320static ptid_t
3321stop_reply_extract_thread (char *stop_reply)
3322{
3323 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3324 {
3325 char *p;
3326
3327 /* Txx r:val ; r:val (...) */
3328 p = &stop_reply[3];
3329
3330 /* Look for "register" named "thread". */
3331 while (*p != '\0')
3332 {
3333 char *p1;
3334
3335 p1 = strchr (p, ':');
3336 if (p1 == NULL)
3337 return null_ptid;
3338
3339 if (strncmp (p, "thread", p1 - p) == 0)
3340 return read_ptid (++p1, &p);
3341
3342 p1 = strchr (p, ';');
3343 if (p1 == NULL)
3344 return null_ptid;
3345 p1++;
3346
3347 p = p1;
3348 }
3349 }
3350
3351 return null_ptid;
3352}
3353
b7ea362b
PA
3354/* Determine the remote side's current thread. If we have a stop
3355 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3356 "thread" register we can extract the current thread from. If not,
3357 ask the remote which is the current thread with qC. The former
3358 method avoids a roundtrip. */
3359
3360static ptid_t
3361get_current_thread (char *wait_status)
3362{
3363 ptid_t ptid;
3364
3365 /* Note we don't use remote_parse_stop_reply as that makes use of
3366 the target architecture, which we haven't yet fully determined at
3367 this point. */
3368 if (wait_status != NULL)
3369 ptid = stop_reply_extract_thread (wait_status);
3370 if (ptid_equal (ptid, null_ptid))
3371 ptid = remote_current_thread (inferior_ptid);
3372
3373 return ptid;
3374}
3375
49c62f2e
PA
3376/* Query the remote target for which is the current thread/process,
3377 add it to our tables, and update INFERIOR_PTID. The caller is
3378 responsible for setting the state such that the remote end is ready
3405876a
PA
3379 to return the current thread.
3380
3381 This function is called after handling the '?' or 'vRun' packets,
3382 whose response is a stop reply from which we can also try
3383 extracting the thread. If the target doesn't support the explicit
3384 qC query, we infer the current thread from that stop reply, passed
3385 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3386
3387static void
3405876a 3388add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3389{
3390 struct remote_state *rs = get_remote_state ();
3391 int fake_pid_p = 0;
3405876a 3392 ptid_t ptid = null_ptid;
49c62f2e
PA
3393
3394 inferior_ptid = null_ptid;
3395
b7ea362b
PA
3396 /* Now, if we have thread information, update inferior_ptid. */
3397 ptid = get_current_thread (wait_status);
3405876a 3398
49c62f2e
PA
3399 if (!ptid_equal (ptid, null_ptid))
3400 {
3401 if (!remote_multi_process_p (rs))
3402 fake_pid_p = 1;
3403
3404 inferior_ptid = ptid;
3405 }
3406 else
3407 {
3408 /* Without this, some commands which require an active target
3409 (such as kill) won't work. This variable serves (at least)
3410 double duty as both the pid of the target process (if it has
3411 such), and as a flag indicating that a target is active. */
3412 inferior_ptid = magic_null_ptid;
3413 fake_pid_p = 1;
3414 }
3415
3416 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1);
3417
3418 /* Add the main thread. */
3419 add_thread_silent (inferior_ptid);
3420}
3421
9cbc821d 3422static void
04bd08de 3423remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 3424{
c8d104ad
PA
3425 struct remote_state *rs = get_remote_state ();
3426 struct packet_config *noack_config;
2d717e4f 3427 char *wait_status = NULL;
8621d6a9 3428
23860348 3429 immediate_quit++; /* Allow user to interrupt it. */
522002f9 3430 QUIT;
c906108c 3431
9a7071a8
JB
3432 if (interrupt_on_connect)
3433 send_interrupt_sequence ();
3434
57e12211 3435 /* Ack any packet which the remote side has already sent. */
5d93a237 3436 serial_write (rs->remote_desc, "+", 1);
57e12211 3437
1e51243a
PA
3438 /* Signal other parts that we're going through the initial setup,
3439 and so things may not be stable yet. */
3440 rs->starting_up = 1;
3441
c8d104ad
PA
3442 /* The first packet we send to the target is the optional "supported
3443 packets" request. If the target can answer this, it will tell us
3444 which later probes to skip. */
3445 remote_query_supported ();
3446
d914c394 3447 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 3448 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 3449 remote_set_permissions (target);
d914c394 3450
c8d104ad
PA
3451 /* Next, we possibly activate noack mode.
3452
3453 If the QStartNoAckMode packet configuration is set to AUTO,
3454 enable noack mode if the stub reported a wish for it with
3455 qSupported.
3456
3457 If set to TRUE, then enable noack mode even if the stub didn't
3458 report it in qSupported. If the stub doesn't reply OK, the
3459 session ends with an error.
3460
3461 If FALSE, then don't activate noack mode, regardless of what the
3462 stub claimed should be the default with qSupported. */
3463
3464 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 3465 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
3466 {
3467 putpkt ("QStartNoAckMode");
3468 getpkt (&rs->buf, &rs->buf_size, 0);
3469 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3470 rs->noack_mode = 1;
3471 }
3472
04bd08de 3473 if (extended_p)
5fe04517
PA
3474 {
3475 /* Tell the remote that we are using the extended protocol. */
3476 putpkt ("!");
3477 getpkt (&rs->buf, &rs->buf_size, 0);
3478 }
3479
9b224c5e
PA
3480 /* Let the target know which signals it is allowed to pass down to
3481 the program. */
3482 update_signals_program_target ();
3483
d962ef82
DJ
3484 /* Next, if the target can specify a description, read it. We do
3485 this before anything involving memory or registers. */
3486 target_find_description ();
3487
6c95b8df
PA
3488 /* Next, now that we know something about the target, update the
3489 address spaces in the program spaces. */
3490 update_address_spaces ();
3491
50c71eaf
PA
3492 /* On OSs where the list of libraries is global to all
3493 processes, we fetch them early. */
f5656ead 3494 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 3495 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 3496
74531fed
PA
3497 if (non_stop)
3498 {
4082afcc 3499 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
3500 error (_("Non-stop mode requested, but remote "
3501 "does not support non-stop"));
74531fed
PA
3502
3503 putpkt ("QNonStop:1");
3504 getpkt (&rs->buf, &rs->buf_size, 0);
3505
3506 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3507 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
3508
3509 /* Find about threads and processes the stub is already
3510 controlling. We default to adding them in the running state.
3511 The '?' query below will then tell us about which threads are
3512 stopped. */
e8032dde 3513 remote_update_thread_list (target);
74531fed 3514 }
4082afcc 3515 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
3516 {
3517 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 3518 Request it explicitly. */
74531fed
PA
3519 putpkt ("QNonStop:0");
3520 getpkt (&rs->buf, &rs->buf_size, 0);
3521
3522 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3523 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
3524 }
3525
a0743c90
YQ
3526 /* Upload TSVs regardless of whether the target is running or not. The
3527 remote stub, such as GDBserver, may have some predefined or builtin
3528 TSVs, even if the target is not running. */
8bd200f1 3529 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
3530 {
3531 struct uploaded_tsv *uploaded_tsvs = NULL;
3532
181e3713 3533 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
3534 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3535 }
3536
2d717e4f
DJ
3537 /* Check whether the target is running now. */
3538 putpkt ("?");
3539 getpkt (&rs->buf, &rs->buf_size, 0);
3540
74531fed 3541 if (!non_stop)
2d717e4f 3542 {
e714e1bf
UW
3543 ptid_t ptid;
3544 int fake_pid_p = 0;
3545 struct inferior *inf;
3546
74531fed 3547 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 3548 {
04bd08de 3549 if (!extended_p)
74531fed 3550 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
3551
3552 /* We're connected, but not running. Drop out before we
3553 call start_remote. */
e278ad5b 3554 rs->starting_up = 0;
c35b1492 3555 return;
2d717e4f
DJ
3556 }
3557 else
74531fed 3558 {
74531fed
PA
3559 /* Save the reply for later. */
3560 wait_status = alloca (strlen (rs->buf) + 1);
3561 strcpy (wait_status, rs->buf);
3562 }
3563
b7ea362b 3564 /* Fetch thread list. */
e8032dde 3565 target_update_thread_list ();
b7ea362b 3566
74531fed
PA
3567 /* Let the stub know that we want it to return the thread. */
3568 set_continue_thread (minus_one_ptid);
3569
b7ea362b
PA
3570 if (thread_count () == 0)
3571 {
3572 /* Target has no concept of threads at all. GDB treats
3573 non-threaded target as single-threaded; add a main
3574 thread. */
3575 add_current_inferior_and_thread (wait_status);
3576 }
3577 else
3578 {
3579 /* We have thread information; select the thread the target
3580 says should be current. If we're reconnecting to a
3581 multi-threaded program, this will ideally be the thread
3582 that last reported an event before GDB disconnected. */
3583 inferior_ptid = get_current_thread (wait_status);
3584 if (ptid_equal (inferior_ptid, null_ptid))
3585 {
3586 /* Odd... The target was able to list threads, but not
3587 tell us which thread was current (no "thread"
3588 register in T stop reply?). Just pick the first
3589 thread in the thread list then. */
3590 inferior_ptid = thread_list->ptid;
3591 }
3592 }
74531fed 3593
6e586cc5
YQ
3594 /* init_wait_for_inferior should be called before get_offsets in order
3595 to manage `inserted' flag in bp loc in a correct state.
3596 breakpoint_init_inferior, called from init_wait_for_inferior, set
3597 `inserted' flag to 0, while before breakpoint_re_set, called from
3598 start_remote, set `inserted' flag to 1. In the initialization of
3599 inferior, breakpoint_init_inferior should be called first, and then
3600 breakpoint_re_set can be called. If this order is broken, state of
3601 `inserted' flag is wrong, and cause some problems on breakpoint
3602 manipulation. */
3603 init_wait_for_inferior ();
3604
74531fed
PA
3605 get_offsets (); /* Get text, data & bss offsets. */
3606
d962ef82
DJ
3607 /* If we could not find a description using qXfer, and we know
3608 how to do it some other way, try again. This is not
3609 supported for non-stop; it could be, but it is tricky if
3610 there are no stopped threads when we connect. */
04bd08de 3611 if (remote_read_description_p (target)
f5656ead 3612 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
3613 {
3614 target_clear_description ();
3615 target_find_description ();
3616 }
3617
74531fed
PA
3618 /* Use the previously fetched status. */
3619 gdb_assert (wait_status != NULL);
3620 strcpy (rs->buf, wait_status);
3621 rs->cached_wait_status = 1;
3622
3623 immediate_quit--;
04bd08de 3624 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
3625 }
3626 else
3627 {
68c97600
PA
3628 /* Clear WFI global state. Do this before finding about new
3629 threads and inferiors, and setting the current inferior.
3630 Otherwise we would clear the proceed status of the current
3631 inferior when we want its stop_soon state to be preserved
3632 (see notice_new_inferior). */
3633 init_wait_for_inferior ();
3634
74531fed
PA
3635 /* In non-stop, we will either get an "OK", meaning that there
3636 are no stopped threads at this time; or, a regular stop
3637 reply. In the latter case, there may be more than one thread
3638 stopped --- we pull them all out using the vStopped
3639 mechanism. */
3640 if (strcmp (rs->buf, "OK") != 0)
3641 {
722247f1 3642 struct notif_client *notif = &notif_client_stop;
2d717e4f 3643
722247f1
YQ
3644 /* remote_notif_get_pending_replies acks this one, and gets
3645 the rest out. */
f48ff2a7 3646 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
3647 = remote_notif_parse (notif, rs->buf);
3648 remote_notif_get_pending_events (notif);
c906108c 3649
74531fed
PA
3650 /* Make sure that threads that were stopped remain
3651 stopped. */
3652 iterate_over_threads (set_stop_requested_callback, NULL);
3653 }
2d717e4f 3654
74531fed 3655 if (target_can_async_p ())
6a3753b3 3656 target_async (1);
c906108c 3657
74531fed
PA
3658 if (thread_count () == 0)
3659 {
04bd08de 3660 if (!extended_p)
74531fed 3661 error (_("The target is not running (try extended-remote?)"));
82f73884 3662
c35b1492
PA
3663 /* We're connected, but not running. Drop out before we
3664 call start_remote. */
e278ad5b 3665 rs->starting_up = 0;
c35b1492
PA
3666 return;
3667 }
74531fed
PA
3668
3669 /* Let the stub know that we want it to return the thread. */
c0a2216e 3670
74531fed
PA
3671 /* Force the stub to choose a thread. */
3672 set_general_thread (null_ptid);
c906108c 3673
74531fed
PA
3674 /* Query it. */
3675 inferior_ptid = remote_current_thread (minus_one_ptid);
3676 if (ptid_equal (inferior_ptid, minus_one_ptid))
3677 error (_("remote didn't report the current thread in non-stop mode"));
c906108c 3678
74531fed
PA
3679 get_offsets (); /* Get text, data & bss offsets. */
3680
3681 /* In non-stop mode, any cached wait status will be stored in
3682 the stop reply queue. */
3683 gdb_assert (wait_status == NULL);
f0223081 3684
2455069d 3685 /* Report all signals during attach/startup. */
94bedb42 3686 remote_pass_signals (target, 0, NULL);
74531fed 3687 }
c8d104ad 3688
c8d104ad
PA
3689 /* If we connected to a live target, do some additional setup. */
3690 if (target_has_execution)
3691 {
f4ccffad 3692 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 3693 remote_check_symbols ();
c8d104ad 3694 }
50c71eaf 3695
d5551862
SS
3696 /* Possibly the target has been engaged in a trace run started
3697 previously; find out where things are at. */
8bd200f1 3698 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 3699 {
00bf0b85 3700 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 3701
00bf0b85
SS
3702 if (current_trace_status ()->running)
3703 printf_filtered (_("Trace is already running on the target.\n"));
3704
ab6617cc 3705 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
3706
3707 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
3708 }
3709
1e51243a
PA
3710 /* The thread and inferior lists are now synchronized with the
3711 target, our symbols have been relocated, and we're merged the
3712 target's tracepoints with ours. We're done with basic start
3713 up. */
3714 rs->starting_up = 0;
3715
a25a5a45
PA
3716 /* Maybe breakpoints are global and need to be inserted now. */
3717 if (breakpoints_should_be_inserted_now ())
50c71eaf 3718 insert_breakpoints ();
c906108c
SS
3719}
3720
3721/* Open a connection to a remote debugger.
3722 NAME is the filename used for communication. */
3723
3724static void
014f9477 3725remote_open (const char *name, int from_tty)
c906108c 3726{
75c99385 3727 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
3728}
3729
c906108c
SS
3730/* Open a connection to a remote debugger using the extended
3731 remote gdb protocol. NAME is the filename used for communication. */
3732
3733static void
014f9477 3734extended_remote_open (const char *name, int from_tty)
c906108c 3735{
75c99385 3736 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
3737}
3738
ca4f7f8b
PA
3739/* Reset all packets back to "unknown support". Called when opening a
3740 new connection to a remote target. */
c906108c 3741
d471ea57 3742static void
ca4f7f8b 3743reset_all_packet_configs_support (void)
d471ea57
AC
3744{
3745 int i;
a744cf53 3746
444abaca 3747 for (i = 0; i < PACKET_MAX; i++)
4082afcc 3748 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
3749}
3750
ca4f7f8b
PA
3751/* Initialize all packet configs. */
3752
3753static void
3754init_all_packet_configs (void)
3755{
3756 int i;
3757
3758 for (i = 0; i < PACKET_MAX; i++)
3759 {
3760 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
3761 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3762 }
3763}
3764
23860348 3765/* Symbol look-up. */
dc8acb97
MS
3766
3767static void
36d25514 3768remote_check_symbols (void)
dc8acb97 3769{
d01949b6 3770 struct remote_state *rs = get_remote_state ();
dc8acb97 3771 char *msg, *reply, *tmp;
3b7344d5 3772 struct bound_minimal_symbol sym;
dc8acb97
MS
3773 int end;
3774
63154eca
PA
3775 /* The remote side has no concept of inferiors that aren't running
3776 yet, it only knows about running processes. If we're connected
3777 but our current inferior is not running, we should not invite the
3778 remote target to request symbol lookups related to its
3779 (unrelated) current process. */
3780 if (!target_has_execution)
3781 return;
3782
4082afcc 3783 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
3784 return;
3785
63154eca
PA
3786 /* Make sure the remote is pointing at the right process. Note
3787 there's no way to select "no process". */
3c9c4b83
PA
3788 set_general_process ();
3789
6d820c5c
DJ
3790 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3791 because we need both at the same time. */
ea9c271d 3792 msg = alloca (get_remote_packet_size ());
6d820c5c 3793
23860348 3794 /* Invite target to request symbol lookups. */
dc8acb97
MS
3795
3796 putpkt ("qSymbol::");
6d820c5c
DJ
3797 getpkt (&rs->buf, &rs->buf_size, 0);
3798 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2e9f7625 3799 reply = rs->buf;
dc8acb97 3800
61012eef 3801 while (startswith (reply, "qSymbol:"))
dc8acb97 3802 {
77e371c0
TT
3803 struct bound_minimal_symbol sym;
3804
dc8acb97 3805 tmp = &reply[8];
cfd77fa1 3806 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
3807 msg[end] = '\0';
3808 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 3809 if (sym.minsym == NULL)
ea9c271d 3810 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 3811 else
2bbe3cc1 3812 {
f5656ead 3813 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 3814 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
3815
3816 /* If this is a function address, return the start of code
3817 instead of any data function descriptor. */
f5656ead 3818 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
3819 sym_addr,
3820 &current_target);
3821
3822 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 3823 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
3824 }
3825
dc8acb97 3826 putpkt (msg);
6d820c5c 3827 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3828 reply = rs->buf;
dc8acb97
MS
3829 }
3830}
3831
9db8d71f 3832static struct serial *
baa336ce 3833remote_serial_open (const char *name)
9db8d71f
DJ
3834{
3835 static int udp_warning = 0;
3836
3837 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3838 of in ser-tcp.c, because it is the remote protocol assuming that the
3839 serial connection is reliable and not the serial connection promising
3840 to be. */
61012eef 3841 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 3842 {
3e43a32a
MS
3843 warning (_("The remote protocol may be unreliable over UDP.\n"
3844 "Some events may be lost, rendering further debugging "
3845 "impossible."));
9db8d71f
DJ
3846 udp_warning = 1;
3847 }
3848
3849 return serial_open (name);
3850}
3851
d914c394
SS
3852/* Inform the target of our permission settings. The permission flags
3853 work without this, but if the target knows the settings, it can do
3854 a couple things. First, it can add its own check, to catch cases
3855 that somehow manage to get by the permissions checks in target
3856 methods. Second, if the target is wired to disallow particular
3857 settings (for instance, a system in the field that is not set up to
3858 be able to stop at a breakpoint), it can object to any unavailable
3859 permissions. */
3860
3861void
c378d69d 3862remote_set_permissions (struct target_ops *self)
d914c394
SS
3863{
3864 struct remote_state *rs = get_remote_state ();
3865
bba74b36
YQ
3866 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3867 "WriteReg:%x;WriteMem:%x;"
3868 "InsertBreak:%x;InsertTrace:%x;"
3869 "InsertFastTrace:%x;Stop:%x",
3870 may_write_registers, may_write_memory,
3871 may_insert_breakpoints, may_insert_tracepoints,
3872 may_insert_fast_tracepoints, may_stop);
d914c394
SS
3873 putpkt (rs->buf);
3874 getpkt (&rs->buf, &rs->buf_size, 0);
3875
3876 /* If the target didn't like the packet, warn the user. Do not try
3877 to undo the user's settings, that would just be maddening. */
3878 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 3879 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
3880}
3881
be2a5f71
DJ
3882/* This type describes each known response to the qSupported
3883 packet. */
3884struct protocol_feature
3885{
3886 /* The name of this protocol feature. */
3887 const char *name;
3888
3889 /* The default for this protocol feature. */
3890 enum packet_support default_support;
3891
3892 /* The function to call when this feature is reported, or after
3893 qSupported processing if the feature is not supported.
3894 The first argument points to this structure. The second
3895 argument indicates whether the packet requested support be
3896 enabled, disabled, or probed (or the default, if this function
3897 is being called at the end of processing and this feature was
3898 not reported). The third argument may be NULL; if not NULL, it
3899 is a NUL-terminated string taken from the packet following
3900 this feature's name and an equals sign. */
3901 void (*func) (const struct protocol_feature *, enum packet_support,
3902 const char *);
3903
3904 /* The corresponding packet for this feature. Only used if
3905 FUNC is remote_supported_packet. */
3906 int packet;
3907};
3908
be2a5f71
DJ
3909static void
3910remote_supported_packet (const struct protocol_feature *feature,
3911 enum packet_support support,
3912 const char *argument)
3913{
3914 if (argument)
3915 {
3916 warning (_("Remote qSupported response supplied an unexpected value for"
3917 " \"%s\"."), feature->name);
3918 return;
3919 }
3920
4082afcc 3921 remote_protocol_packets[feature->packet].support = support;
be2a5f71 3922}
be2a5f71
DJ
3923
3924static void
3925remote_packet_size (const struct protocol_feature *feature,
3926 enum packet_support support, const char *value)
3927{
3928 struct remote_state *rs = get_remote_state ();
3929
3930 int packet_size;
3931 char *value_end;
3932
3933 if (support != PACKET_ENABLE)
3934 return;
3935
3936 if (value == NULL || *value == '\0')
3937 {
3938 warning (_("Remote target reported \"%s\" without a size."),
3939 feature->name);
3940 return;
3941 }
3942
3943 errno = 0;
3944 packet_size = strtol (value, &value_end, 16);
3945 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3946 {
3947 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3948 feature->name, value);
3949 return;
3950 }
3951
3952 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3953 {
3954 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3955 packet_size, MAX_REMOTE_PACKET_SIZE);
3956 packet_size = MAX_REMOTE_PACKET_SIZE;
3957 }
3958
3959 /* Record the new maximum packet size. */
3960 rs->explicit_packet_size = packet_size;
3961}
3962
dc473cfb 3963static const struct protocol_feature remote_protocol_features[] = {
0876f84a 3964 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 3965 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 3966 PACKET_qXfer_auxv },
c78fa86a
GB
3967 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
3968 PACKET_qXfer_exec_file },
23181151
DJ
3969 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3970 PACKET_qXfer_features },
cfa9d6d9
DJ
3971 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3972 PACKET_qXfer_libraries },
2268b414
JK
3973 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
3974 PACKET_qXfer_libraries_svr4 },
ced63ec0 3975 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 3976 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 3977 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 3978 PACKET_qXfer_memory_map },
4de6483e
UW
3979 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3980 PACKET_qXfer_spu_read },
3981 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3982 PACKET_qXfer_spu_write },
07e059b5
VP
3983 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3984 PACKET_qXfer_osdata },
dc146f7c
VP
3985 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
3986 PACKET_qXfer_threads },
b3b9301e
PA
3987 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
3988 PACKET_qXfer_traceframe_info },
89be2091
DJ
3989 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3990 PACKET_QPassSignals },
9b224c5e
PA
3991 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
3992 PACKET_QProgramSignals },
a6f3e723
SL
3993 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
3994 PACKET_QStartNoAckMode },
4082afcc
PA
3995 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
3996 PACKET_multiprocess_feature },
3997 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
3998 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
3999 PACKET_qXfer_siginfo_read },
4000 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4001 PACKET_qXfer_siginfo_write },
4082afcc 4002 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4003 PACKET_ConditionalTracepoints },
4082afcc 4004 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4005 PACKET_ConditionalBreakpoints },
4082afcc 4006 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4007 PACKET_BreakpointCommands },
4082afcc 4008 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4009 PACKET_FastTracepoints },
4082afcc 4010 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4011 PACKET_StaticTracepoints },
4082afcc 4012 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4013 PACKET_InstallInTrace},
4082afcc
PA
4014 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4015 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4016 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4017 PACKET_bc },
4018 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4019 PACKET_bs },
409873ef
SS
4020 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4021 PACKET_TracepointSource },
d914c394
SS
4022 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4023 PACKET_QAllow },
4082afcc
PA
4024 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4025 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4026 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4027 PACKET_qXfer_fdpic },
169081d0
TG
4028 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4029 PACKET_qXfer_uib },
03583c20
UW
4030 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4031 PACKET_QDisableRandomization },
d1feda86 4032 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4033 { "QTBuffer:size", PACKET_DISABLE,
4034 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4035 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4036 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4037 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4038 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4039 PACKET_qXfer_btrace },
4040 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4041 PACKET_qXfer_btrace_conf },
4042 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4043 PACKET_Qbtrace_conf_bts_size },
4044 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4045 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
be2a5f71
DJ
4046};
4047
c8d5aac9
L
4048static char *remote_support_xml;
4049
4050/* Register string appended to "xmlRegisters=" in qSupported query. */
4051
4052void
6e39997a 4053register_remote_support_xml (const char *xml)
c8d5aac9
L
4054{
4055#if defined(HAVE_LIBEXPAT)
4056 if (remote_support_xml == NULL)
c4f7c687 4057 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4058 else
4059 {
4060 char *copy = xstrdup (remote_support_xml + 13);
4061 char *p = strtok (copy, ",");
4062
4063 do
4064 {
4065 if (strcmp (p, xml) == 0)
4066 {
4067 /* already there */
4068 xfree (copy);
4069 return;
4070 }
4071 }
4072 while ((p = strtok (NULL, ",")) != NULL);
4073 xfree (copy);
4074
94b0dee1
PA
4075 remote_support_xml = reconcat (remote_support_xml,
4076 remote_support_xml, ",", xml,
4077 (char *) NULL);
c8d5aac9
L
4078 }
4079#endif
4080}
4081
4082static char *
4083remote_query_supported_append (char *msg, const char *append)
4084{
4085 if (msg)
94b0dee1 4086 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4087 else
4088 return xstrdup (append);
4089}
4090
be2a5f71
DJ
4091static void
4092remote_query_supported (void)
4093{
4094 struct remote_state *rs = get_remote_state ();
4095 char *next;
4096 int i;
4097 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4098
4099 /* The packet support flags are handled differently for this packet
4100 than for most others. We treat an error, a disabled packet, and
4101 an empty response identically: any features which must be reported
4102 to be used will be automatically disabled. An empty buffer
4103 accomplishes this, since that is also the representation for a list
4104 containing no features. */
4105
4106 rs->buf[0] = 0;
4082afcc 4107 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4108 {
c8d5aac9 4109 char *q = NULL;
94b0dee1 4110 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4111
901f9912 4112 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4113
f7e6eed5
PA
4114 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4115 q = remote_query_supported_append (q, "swbreak+");
4116 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4117 q = remote_query_supported_append (q, "hwbreak+");
4118
c8d5aac9
L
4119 if (remote_support_xml)
4120 q = remote_query_supported_append (q, remote_support_xml);
4121
dde08ee1
PA
4122 q = remote_query_supported_append (q, "qRelocInsn+");
4123
4124 q = reconcat (q, "qSupported:", q, (char *) NULL);
4125 putpkt (q);
82f73884 4126
94b0dee1
PA
4127 do_cleanups (old_chain);
4128
be2a5f71
DJ
4129 getpkt (&rs->buf, &rs->buf_size, 0);
4130
4131 /* If an error occured, warn, but do not return - just reset the
4132 buffer to empty and go on to disable features. */
4133 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4134 == PACKET_ERROR)
4135 {
4136 warning (_("Remote failure reply: %s"), rs->buf);
4137 rs->buf[0] = 0;
4138 }
4139 }
4140
4141 memset (seen, 0, sizeof (seen));
4142
4143 next = rs->buf;
4144 while (*next)
4145 {
4146 enum packet_support is_supported;
4147 char *p, *end, *name_end, *value;
4148
4149 /* First separate out this item from the rest of the packet. If
4150 there's another item after this, we overwrite the separator
4151 (terminated strings are much easier to work with). */
4152 p = next;
4153 end = strchr (p, ';');
4154 if (end == NULL)
4155 {
4156 end = p + strlen (p);
4157 next = end;
4158 }
4159 else
4160 {
89be2091
DJ
4161 *end = '\0';
4162 next = end + 1;
4163
be2a5f71
DJ
4164 if (end == p)
4165 {
4166 warning (_("empty item in \"qSupported\" response"));
4167 continue;
4168 }
be2a5f71
DJ
4169 }
4170
4171 name_end = strchr (p, '=');
4172 if (name_end)
4173 {
4174 /* This is a name=value entry. */
4175 is_supported = PACKET_ENABLE;
4176 value = name_end + 1;
4177 *name_end = '\0';
4178 }
4179 else
4180 {
4181 value = NULL;
4182 switch (end[-1])
4183 {
4184 case '+':
4185 is_supported = PACKET_ENABLE;
4186 break;
4187
4188 case '-':
4189 is_supported = PACKET_DISABLE;
4190 break;
4191
4192 case '?':
4193 is_supported = PACKET_SUPPORT_UNKNOWN;
4194 break;
4195
4196 default:
3e43a32a
MS
4197 warning (_("unrecognized item \"%s\" "
4198 "in \"qSupported\" response"), p);
be2a5f71
DJ
4199 continue;
4200 }
4201 end[-1] = '\0';
4202 }
4203
4204 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4205 if (strcmp (remote_protocol_features[i].name, p) == 0)
4206 {
4207 const struct protocol_feature *feature;
4208
4209 seen[i] = 1;
4210 feature = &remote_protocol_features[i];
4211 feature->func (feature, is_supported, value);
4212 break;
4213 }
4214 }
4215
4216 /* If we increased the packet size, make sure to increase the global
4217 buffer size also. We delay this until after parsing the entire
4218 qSupported packet, because this is the same buffer we were
4219 parsing. */
4220 if (rs->buf_size < rs->explicit_packet_size)
4221 {
4222 rs->buf_size = rs->explicit_packet_size;
4223 rs->buf = xrealloc (rs->buf, rs->buf_size);
4224 }
4225
4226 /* Handle the defaults for unmentioned features. */
4227 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4228 if (!seen[i])
4229 {
4230 const struct protocol_feature *feature;
4231
4232 feature = &remote_protocol_features[i];
4233 feature->func (feature, feature->default_support, NULL);
4234 }
4235}
4236
78a095c3
JK
4237/* Remove any of the remote.c targets from target stack. Upper targets depend
4238 on it so remove them first. */
4239
4240static void
4241remote_unpush_target (void)
4242{
4243 pop_all_targets_above (process_stratum - 1);
4244}
be2a5f71 4245
c906108c 4246static void
014f9477 4247remote_open_1 (const char *name, int from_tty,
3e43a32a 4248 struct target_ops *target, int extended_p)
c906108c 4249{
d01949b6 4250 struct remote_state *rs = get_remote_state ();
a6f3e723 4251
c906108c 4252 if (name == 0)
8a3fe4f8 4253 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4254 "serial device is attached to the remote system\n"
8a3fe4f8 4255 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4256
23860348 4257 /* See FIXME above. */
c6ebd6cf 4258 if (!target_async_permitted)
92d1e331 4259 wait_forever_enabled_p = 1;
6426a772 4260
2d717e4f 4261 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4262 Ask this question first, before target_preopen has a chance to kill
4263 anything. */
5d93a237 4264 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4265 {
78a095c3
JK
4266 if (from_tty
4267 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4268 error (_("Still connected."));
4269 }
4270
78a095c3 4271 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4272 target_preopen (from_tty);
4273
89be2091 4274 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4275 xfree (rs->last_pass_packet);
4276 rs->last_pass_packet = NULL;
89be2091 4277
9b224c5e
PA
4278 /* Make sure we send the program signals list the next time we
4279 resume. */
5e4a05c4
TT
4280 xfree (rs->last_program_signals_packet);
4281 rs->last_program_signals_packet = NULL;
9b224c5e 4282
ad9a8f3f 4283 remote_fileio_reset ();
1dd41f16
NS
4284 reopen_exec_file ();
4285 reread_symbols ();
4286
5d93a237
TT
4287 rs->remote_desc = remote_serial_open (name);
4288 if (!rs->remote_desc)
c906108c
SS
4289 perror_with_name (name);
4290
4291 if (baud_rate != -1)
4292 {
5d93a237 4293 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4294 {
9b74d5d3
KB
4295 /* The requested speed could not be set. Error out to
4296 top level after closing remote_desc. Take care to
4297 set remote_desc to NULL to avoid closing remote_desc
4298 more than once. */
5d93a237
TT
4299 serial_close (rs->remote_desc);
4300 rs->remote_desc = NULL;
c906108c
SS
4301 perror_with_name (name);
4302 }
4303 }
4304
236af5e3 4305 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 4306 serial_raw (rs->remote_desc);
c906108c
SS
4307
4308 /* If there is something sitting in the buffer we might take it as a
4309 response to a command, which would be bad. */
5d93a237 4310 serial_flush_input (rs->remote_desc);
c906108c
SS
4311
4312 if (from_tty)
4313 {
4314 puts_filtered ("Remote debugging using ");
4315 puts_filtered (name);
4316 puts_filtered ("\n");
4317 }
23860348 4318 push_target (target); /* Switch to using remote target now. */
c906108c 4319
74531fed
PA
4320 /* Register extra event sources in the event loop. */
4321 remote_async_inferior_event_token
4322 = create_async_event_handler (remote_async_inferior_event_handler,
4323 NULL);
5965e028 4324 rs->notif_state = remote_notif_state_allocate ();
74531fed 4325
be2a5f71
DJ
4326 /* Reset the target state; these things will be queried either by
4327 remote_query_supported or as they are needed. */
ca4f7f8b 4328 reset_all_packet_configs_support ();
74531fed 4329 rs->cached_wait_status = 0;
be2a5f71 4330 rs->explicit_packet_size = 0;
a6f3e723 4331 rs->noack_mode = 0;
82f73884 4332 rs->extended = extended_p;
e24a49d8 4333 rs->waiting_for_stop_reply = 0;
3a29589a 4334 rs->ctrlc_pending_p = 0;
802188a7 4335
47f8a51d
TT
4336 rs->general_thread = not_sent_ptid;
4337 rs->continue_thread = not_sent_ptid;
262e1174 4338 rs->remote_traceframe_number = -1;
c906108c 4339
9d1f7ab2 4340 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
4341 rs->use_threadinfo_query = 1;
4342 rs->use_threadextra_query = 1;
9d1f7ab2 4343
c6ebd6cf 4344 if (target_async_permitted)
92d1e331 4345 {
23860348 4346 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4347 remote_async_terminal_ours_p = 1;
4348
4349 /* FIXME: cagney/1999-09-23: During the initial connection it is
4350 assumed that the target is already ready and able to respond to
0df8b418 4351 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4352 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4353 around this. Eventually a mechanism that allows
92d1e331 4354 wait_for_inferior() to expect/get timeouts will be
23860348 4355 implemented. */
92d1e331
DJ
4356 wait_forever_enabled_p = 0;
4357 }
4358
23860348 4359 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4360 no_shared_libraries (NULL, 0);
f78f6cf1 4361
74531fed
PA
4362 /* Start afresh. */
4363 init_thread_list ();
4364
36918e70 4365 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4366 target (we'd otherwise be in an inconsistent state) and then
4367 propogate the error on up the exception chain. This ensures that
4368 the caller doesn't stumble along blindly assuming that the
4369 function succeeded. The CLI doesn't have this problem but other
4370 UI's, such as MI do.
36918e70
AC
4371
4372 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4373 this function should return an error indication letting the
ce2826aa 4374 caller restore the previous state. Unfortunately the command
36918e70
AC
4375 ``target remote'' is directly wired to this function making that
4376 impossible. On a positive note, the CLI side of this problem has
4377 been fixed - the function set_cmd_context() makes it possible for
4378 all the ``target ....'' commands to share a common callback
4379 function. See cli-dump.c. */
109c3e39 4380 {
2d717e4f 4381
492d29ea 4382 TRY
04bd08de
TT
4383 {
4384 remote_start_remote (from_tty, target, extended_p);
4385 }
492d29ea 4386 CATCH (ex, RETURN_MASK_ALL)
109c3e39 4387 {
c8d104ad
PA
4388 /* Pop the partially set up target - unless something else did
4389 already before throwing the exception. */
5d93a237 4390 if (rs->remote_desc != NULL)
78a095c3 4391 remote_unpush_target ();
c6ebd6cf 4392 if (target_async_permitted)
109c3e39
AC
4393 wait_forever_enabled_p = 1;
4394 throw_exception (ex);
4395 }
492d29ea 4396 END_CATCH
109c3e39 4397 }
c906108c 4398
f4abbc16
MM
4399 remote_btrace_reset ();
4400
c6ebd6cf 4401 if (target_async_permitted)
92d1e331 4402 wait_forever_enabled_p = 1;
43ff13b4
JM
4403}
4404
c906108c
SS
4405/* This takes a program previously attached to and detaches it. After
4406 this is done, GDB can be used to debug some other program. We
4407 better not have left any breakpoints in the target program or it'll
4408 die when it hits one. */
4409
4410static void
52554a0e 4411remote_detach_1 (const char *args, int from_tty, int extended)
c906108c 4412{
82f73884 4413 int pid = ptid_get_pid (inferior_ptid);
d01949b6 4414 struct remote_state *rs = get_remote_state ();
c906108c
SS
4415
4416 if (args)
8a3fe4f8 4417 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 4418
2d717e4f
DJ
4419 if (!target_has_execution)
4420 error (_("No process to detach from."));
4421
7cee1e54
PA
4422 if (from_tty)
4423 {
4424 char *exec_file = get_exec_file (0);
4425 if (exec_file == NULL)
4426 exec_file = "";
4427 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4428 target_pid_to_str (pid_to_ptid (pid)));
4429 gdb_flush (gdb_stdout);
4430 }
4431
c906108c 4432 /* Tell the remote target to detach. */
82f73884 4433 if (remote_multi_process_p (rs))
bba74b36 4434 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
82f73884
PA
4435 else
4436 strcpy (rs->buf, "D");
4437
4ddda9b5
PA
4438 putpkt (rs->buf);
4439 getpkt (&rs->buf, &rs->buf_size, 0);
4440
82f73884
PA
4441 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4442 ;
4443 else if (rs->buf[0] == '\0')
4444 error (_("Remote doesn't know how to detach"));
4445 else
4ddda9b5 4446 error (_("Can't detach process."));
c906108c 4447
7cee1e54
PA
4448 if (from_tty && !extended)
4449 puts_filtered (_("Ending remote debugging.\n"));
82f73884 4450
82f73884 4451 target_mourn_inferior ();
2d717e4f
DJ
4452}
4453
4454static void
52554a0e 4455remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f
DJ
4456{
4457 remote_detach_1 (args, from_tty, 0);
4458}
4459
4460static void
52554a0e 4461extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f
DJ
4462{
4463 remote_detach_1 (args, from_tty, 1);
c906108c
SS
4464}
4465
6ad8ae5c
DJ
4466/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4467
43ff13b4 4468static void
fee354ee 4469remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 4470{
43ff13b4 4471 if (args)
2d717e4f 4472 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 4473
2d717e4f 4474 /* Make sure we unpush even the extended remote targets; mourn
20f796c9 4475 won't do it. So call remote_mourn directly instead of
2d717e4f 4476 target_mourn_inferior. */
20f796c9 4477 remote_mourn (target);
2d717e4f 4478
43ff13b4
JM
4479 if (from_tty)
4480 puts_filtered ("Ending remote debugging.\n");
4481}
4482
2d717e4f
DJ
4483/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4484 be chatty about it. */
4485
4486static void
20f796c9
GB
4487extended_remote_attach (struct target_ops *target, const char *args,
4488 int from_tty)
2d717e4f
DJ
4489{
4490 struct remote_state *rs = get_remote_state ();
be86555c 4491 int pid;
96ef3384 4492 char *wait_status = NULL;
2d717e4f 4493
74164c56 4494 pid = parse_pid_to_attach (args);
2d717e4f 4495
74164c56
JK
4496 /* Remote PID can be freely equal to getpid, do not check it here the same
4497 way as in other targets. */
2d717e4f 4498
4082afcc 4499 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
4500 error (_("This target does not support attaching to a process"));
4501
7cee1e54
PA
4502 if (from_tty)
4503 {
4504 char *exec_file = get_exec_file (0);
4505
4506 if (exec_file)
4507 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4508 target_pid_to_str (pid_to_ptid (pid)));
4509 else
4510 printf_unfiltered (_("Attaching to %s\n"),
4511 target_pid_to_str (pid_to_ptid (pid)));
4512
4513 gdb_flush (gdb_stdout);
4514 }
4515
bba74b36 4516 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
4517 putpkt (rs->buf);
4518 getpkt (&rs->buf, &rs->buf_size, 0);
4519
4082afcc
PA
4520 switch (packet_ok (rs->buf,
4521 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 4522 {
4082afcc 4523 case PACKET_OK:
74531fed
PA
4524 if (!non_stop)
4525 {
4526 /* Save the reply for later. */
4527 wait_status = alloca (strlen (rs->buf) + 1);
4528 strcpy (wait_status, rs->buf);
4529 }
4530 else if (strcmp (rs->buf, "OK") != 0)
4531 error (_("Attaching to %s failed with: %s"),
4532 target_pid_to_str (pid_to_ptid (pid)),
4533 rs->buf);
4082afcc
PA
4534 break;
4535 case PACKET_UNKNOWN:
4536 error (_("This target does not support attaching to a process"));
4537 default:
4538 error (_("Attaching to %s failed"),
4539 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 4540 }
2d717e4f 4541
49c62f2e 4542 set_current_inferior (remote_add_inferior (0, pid, 1));
bad34192 4543
2d717e4f 4544 inferior_ptid = pid_to_ptid (pid);
79d7f229 4545
bad34192
PA
4546 if (non_stop)
4547 {
4548 struct thread_info *thread;
79d7f229 4549
bad34192 4550 /* Get list of threads. */
e8032dde 4551 remote_update_thread_list (target);
82f73884 4552
bad34192
PA
4553 thread = first_thread_of_process (pid);
4554 if (thread)
4555 inferior_ptid = thread->ptid;
4556 else
4557 inferior_ptid = pid_to_ptid (pid);
4558
4559 /* Invalidate our notion of the remote current thread. */
47f8a51d 4560 record_currthread (rs, minus_one_ptid);
bad34192 4561 }
74531fed 4562 else
bad34192
PA
4563 {
4564 /* Now, if we have thread information, update inferior_ptid. */
4565 inferior_ptid = remote_current_thread (inferior_ptid);
4566
4567 /* Add the main thread to the thread list. */
4568 add_thread_silent (inferior_ptid);
4569 }
c0a2216e 4570
96ef3384
UW
4571 /* Next, if the target can specify a description, read it. We do
4572 this before anything involving memory or registers. */
4573 target_find_description ();
4574
74531fed
PA
4575 if (!non_stop)
4576 {
4577 /* Use the previously fetched status. */
4578 gdb_assert (wait_status != NULL);
4579
4580 if (target_can_async_p ())
4581 {
722247f1
YQ
4582 struct notif_event *reply
4583 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 4584
722247f1 4585 push_stop_reply ((struct stop_reply *) reply);
74531fed 4586
6a3753b3 4587 target_async (1);
74531fed
PA
4588 }
4589 else
4590 {
4591 gdb_assert (wait_status != NULL);
4592 strcpy (rs->buf, wait_status);
4593 rs->cached_wait_status = 1;
4594 }
4595 }
4596 else
4597 gdb_assert (wait_status == NULL);
2d717e4f
DJ
4598}
4599
b9c1d481
AS
4600/* Implementation of the to_post_attach method. */
4601
4602static void
4603extended_remote_post_attach (struct target_ops *ops, int pid)
4604{
4605 /* In certain cases GDB might not have had the chance to start
4606 symbol lookup up until now. This could happen if the debugged
4607 binary is not using shared libraries, the vsyscall page is not
4608 present (on Linux) and the binary itself hadn't changed since the
4609 debugging process was started. */
4610 if (symfile_objfile != NULL)
4611 remote_check_symbols();
4612}
4613
c906108c 4614\f
506fb367
DJ
4615/* Check for the availability of vCont. This function should also check
4616 the response. */
c906108c
SS
4617
4618static void
6d820c5c 4619remote_vcont_probe (struct remote_state *rs)
c906108c 4620{
2e9f7625 4621 char *buf;
6d820c5c 4622
2e9f7625
DJ
4623 strcpy (rs->buf, "vCont?");
4624 putpkt (rs->buf);
6d820c5c 4625 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4626 buf = rs->buf;
c906108c 4627
506fb367 4628 /* Make sure that the features we assume are supported. */
61012eef 4629 if (startswith (buf, "vCont"))
506fb367
DJ
4630 {
4631 char *p = &buf[5];
4632 int support_s, support_S, support_c, support_C;
4633
4634 support_s = 0;
4635 support_S = 0;
4636 support_c = 0;
4637 support_C = 0;
d458bd84 4638 rs->supports_vCont.t = 0;
c1e36e3e 4639 rs->supports_vCont.r = 0;
506fb367
DJ
4640 while (p && *p == ';')
4641 {
4642 p++;
4643 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4644 support_s = 1;
4645 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4646 support_S = 1;
4647 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4648 support_c = 1;
4649 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4650 support_C = 1;
74531fed 4651 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 4652 rs->supports_vCont.t = 1;
c1e36e3e
PA
4653 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4654 rs->supports_vCont.r = 1;
506fb367
DJ
4655
4656 p = strchr (p, ';');
4657 }
c906108c 4658
506fb367
DJ
4659 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4660 BUF will make packet_ok disable the packet. */
4661 if (!support_s || !support_S || !support_c || !support_C)
4662 buf[0] = 0;
4663 }
c906108c 4664
444abaca 4665 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 4666}
c906108c 4667
0d8f58ca
PA
4668/* Helper function for building "vCont" resumptions. Write a
4669 resumption to P. ENDP points to one-passed-the-end of the buffer
4670 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4671 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4672 resumed thread should be single-stepped and/or signalled. If PTID
4673 equals minus_one_ptid, then all threads are resumed; if PTID
4674 represents a process, then all threads of the process are resumed;
4675 the thread to be stepped and/or signalled is given in the global
4676 INFERIOR_PTID. */
4677
4678static char *
4679append_resumption (char *p, char *endp,
2ea28649 4680 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
4681{
4682 struct remote_state *rs = get_remote_state ();
4683
a493e3e2 4684 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 4685 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
4686 else if (step
4687 /* GDB is willing to range step. */
4688 && use_range_stepping
4689 /* Target supports range stepping. */
4690 && rs->supports_vCont.r
4691 /* We don't currently support range stepping multiple
4692 threads with a wildcard (though the protocol allows it,
4693 so stubs shouldn't make an active effort to forbid
4694 it). */
4695 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4696 {
4697 struct thread_info *tp;
4698
4699 if (ptid_equal (ptid, minus_one_ptid))
4700 {
4701 /* If we don't know about the target thread's tid, then
4702 we're resuming magic_null_ptid (see caller). */
4703 tp = find_thread_ptid (magic_null_ptid);
4704 }
4705 else
4706 tp = find_thread_ptid (ptid);
4707 gdb_assert (tp != NULL);
4708
4709 if (tp->control.may_range_step)
4710 {
4711 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4712
4713 p += xsnprintf (p, endp - p, ";r%s,%s",
4714 phex_nz (tp->control.step_range_start,
4715 addr_size),
4716 phex_nz (tp->control.step_range_end,
4717 addr_size));
4718 }
4719 else
4720 p += xsnprintf (p, endp - p, ";s");
4721 }
0d8f58ca
PA
4722 else if (step)
4723 p += xsnprintf (p, endp - p, ";s");
a493e3e2 4724 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
4725 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4726 else
4727 p += xsnprintf (p, endp - p, ";c");
4728
4729 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4730 {
4731 ptid_t nptid;
4732
4733 /* All (-1) threads of process. */
ba348170 4734 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
4735
4736 p += xsnprintf (p, endp - p, ":");
4737 p = write_ptid (p, endp, nptid);
4738 }
4739 else if (!ptid_equal (ptid, minus_one_ptid))
4740 {
4741 p += xsnprintf (p, endp - p, ":");
4742 p = write_ptid (p, endp, ptid);
4743 }
4744
4745 return p;
4746}
4747
e5ef252a
PA
4748/* Append a vCont continue-with-signal action for threads that have a
4749 non-zero stop signal. */
4750
4751static char *
4752append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4753{
4754 struct thread_info *thread;
4755
034f788c 4756 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
4757 if (ptid_match (thread->ptid, ptid)
4758 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 4759 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
4760 {
4761 p = append_resumption (p, endp, thread->ptid,
4762 0, thread->suspend.stop_signal);
4763 thread->suspend.stop_signal = GDB_SIGNAL_0;
4764 }
4765
4766 return p;
4767}
4768
506fb367
DJ
4769/* Resume the remote inferior by using a "vCont" packet. The thread
4770 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
4771 resumed thread should be single-stepped and/or signalled. If PTID
4772 equals minus_one_ptid, then all threads are resumed; the thread to
4773 be stepped and/or signalled is given in the global INFERIOR_PTID.
4774 This function returns non-zero iff it resumes the inferior.
44eaed12 4775
506fb367
DJ
4776 This function issues a strict subset of all possible vCont commands at the
4777 moment. */
44eaed12 4778
506fb367 4779static int
2ea28649 4780remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
4781{
4782 struct remote_state *rs = get_remote_state ();
82f73884
PA
4783 char *p;
4784 char *endp;
44eaed12 4785
4082afcc 4786 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 4787 remote_vcont_probe (rs);
44eaed12 4788
4082afcc 4789 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 4790 return 0;
44eaed12 4791
82f73884
PA
4792 p = rs->buf;
4793 endp = rs->buf + get_remote_packet_size ();
4794
506fb367
DJ
4795 /* If we could generate a wider range of packets, we'd have to worry
4796 about overflowing BUF. Should there be a generic
4797 "multi-part-packet" packet? */
4798
0d8f58ca
PA
4799 p += xsnprintf (p, endp - p, "vCont");
4800
79d7f229 4801 if (ptid_equal (ptid, magic_null_ptid))
c906108c 4802 {
79d7f229
PA
4803 /* MAGIC_NULL_PTID means that we don't have any active threads,
4804 so we don't have any TID numbers the inferior will
4805 understand. Make sure to only send forms that do not specify
4806 a TID. */
a9cbf802 4807 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 4808 }
0d8f58ca 4809 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 4810 {
0d8f58ca
PA
4811 /* Resume all threads (of all processes, or of a single
4812 process), with preference for INFERIOR_PTID. This assumes
4813 inferior_ptid belongs to the set of all threads we are about
4814 to resume. */
a493e3e2 4815 if (step || siggnal != GDB_SIGNAL_0)
82f73884 4816 {
0d8f58ca
PA
4817 /* Step inferior_ptid, with or without signal. */
4818 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 4819 }
0d8f58ca 4820
e5ef252a
PA
4821 /* Also pass down any pending signaled resumption for other
4822 threads not the current. */
4823 p = append_pending_thread_resumptions (p, endp, ptid);
4824
0d8f58ca 4825 /* And continue others without a signal. */
a493e3e2 4826 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
4827 }
4828 else
506fb367
DJ
4829 {
4830 /* Scheduler locking; resume only PTID. */
a9cbf802 4831 append_resumption (p, endp, ptid, step, siggnal);
506fb367 4832 }
c906108c 4833
82f73884
PA
4834 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4835 putpkt (rs->buf);
506fb367 4836
74531fed
PA
4837 if (non_stop)
4838 {
4839 /* In non-stop, the stub replies to vCont with "OK". The stop
4840 reply will be reported asynchronously by means of a `%Stop'
4841 notification. */
4842 getpkt (&rs->buf, &rs->buf_size, 0);
4843 if (strcmp (rs->buf, "OK") != 0)
4844 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4845 }
4846
506fb367 4847 return 1;
c906108c 4848}
43ff13b4 4849
506fb367
DJ
4850/* Tell the remote machine to resume. */
4851
43ff13b4 4852static void
28439f5e 4853remote_resume (struct target_ops *ops,
2ea28649 4854 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 4855{
d01949b6 4856 struct remote_state *rs = get_remote_state ();
2e9f7625 4857 char *buf;
43ff13b4 4858
722247f1
YQ
4859 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
4860 (explained in remote-notif.c:handle_notification) so
4861 remote_notif_process is not called. We need find a place where
4862 it is safe to start a 'vNotif' sequence. It is good to do it
4863 before resuming inferior, because inferior was stopped and no RSP
4864 traffic at that moment. */
4865 if (!non_stop)
5965e028 4866 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 4867
b73be471 4868 rs->last_sent_signal = siggnal;
280ceea3 4869 rs->last_sent_step = step;
43ff13b4 4870
506fb367 4871 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
4872 /* No reverse support (yet) for vCont. */
4873 if (execution_direction != EXEC_REVERSE)
4874 if (remote_vcont_resume (ptid, step, siggnal))
4875 goto done;
506fb367 4876
79d7f229
PA
4877 /* All other supported resume packets do use Hc, so set the continue
4878 thread. */
4879 if (ptid_equal (ptid, minus_one_ptid))
4880 set_continue_thread (any_thread_ptid);
506fb367 4881 else
79d7f229 4882 set_continue_thread (ptid);
506fb367 4883
2e9f7625 4884 buf = rs->buf;
b2175913
MS
4885 if (execution_direction == EXEC_REVERSE)
4886 {
4887 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 4888 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 4889 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 4890 siggnal);
40ab02ce 4891
4082afcc 4892 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
40ab02ce 4893 error (_("Remote reverse-step not supported."));
4082afcc 4894 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
08c93ed9 4895 error (_("Remote reverse-continue not supported."));
40ab02ce 4896
b2175913
MS
4897 strcpy (buf, step ? "bs" : "bc");
4898 }
a493e3e2 4899 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
4900 {
4901 buf[0] = step ? 'S' : 'C';
c5aa993b 4902 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 4903 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
4904 buf[3] = '\0';
4905 }
4906 else
c5aa993b 4907 strcpy (buf, step ? "s" : "c");
506fb367 4908
44eaed12 4909 putpkt (buf);
43ff13b4 4910
75c99385 4911 done:
2acceee2 4912 /* We are about to start executing the inferior, let's register it
0df8b418
MS
4913 with the event loop. NOTE: this is the one place where all the
4914 execution commands end up. We could alternatively do this in each
23860348 4915 of the execution commands in infcmd.c. */
2acceee2
JM
4916 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4917 into infcmd.c in order to allow inferior function calls to work
23860348 4918 NOT asynchronously. */
362646f5 4919 if (target_can_async_p ())
6a3753b3 4920 target_async (1);
e24a49d8
PA
4921
4922 /* We've just told the target to resume. The remote server will
4923 wait for the inferior to stop, and then send a stop reply. In
4924 the mean time, we can't start another command/query ourselves
74531fed
PA
4925 because the stub wouldn't be ready to process it. This applies
4926 only to the base all-stop protocol, however. In non-stop (which
4927 only supports vCont), the stub replies with an "OK", and is
4928 immediate able to process further serial input. */
4929 if (!non_stop)
4930 rs->waiting_for_stop_reply = 1;
43ff13b4 4931}
c906108c 4932\f
43ff13b4
JM
4933
4934/* Set up the signal handler for SIGINT, while the target is
23860348 4935 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 4936static void
934b9bac 4937async_initialize_sigint_signal_handler (void)
43ff13b4 4938{
934b9bac 4939 signal (SIGINT, async_handle_remote_sigint);
43ff13b4
JM
4940}
4941
23860348 4942/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 4943static void
934b9bac 4944async_handle_remote_sigint (int sig)
43ff13b4 4945{
934b9bac 4946 signal (sig, async_handle_remote_sigint_twice);
b2ee242b
PA
4947 /* Note we need to go through gdb_call_async_signal_handler in order
4948 to wake up the event loop on Windows. */
4949 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
43ff13b4
JM
4950}
4951
4952/* Signal handler for SIGINT, installed after SIGINT has already been
4953 sent once. It will take effect the second time that the user sends
23860348 4954 a ^C. */
43ff13b4 4955static void
934b9bac 4956async_handle_remote_sigint_twice (int sig)
43ff13b4 4957{
934b9bac 4958 signal (sig, async_handle_remote_sigint);
b2ee242b
PA
4959 /* See note in async_handle_remote_sigint. */
4960 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
43ff13b4
JM
4961}
4962
6426a772 4963/* Perform the real interruption of the target execution, in response
23860348 4964 to a ^C. */
c5aa993b 4965static void
fba45db2 4966async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
4967{
4968 if (remote_debug)
248fd3bf 4969 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
43ff13b4 4970
94cc34af 4971 target_stop (inferior_ptid);
43ff13b4
JM
4972}
4973
0df8b418 4974/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 4975 up on the target alltogether. */
47e1ce27 4976static void
fba45db2 4977async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 4978{
2df3850c 4979 if (remote_debug)
248fd3bf 4980 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
b803fb0f
DJ
4981
4982 interrupt_query ();
43ff13b4
JM
4983}
4984
4985/* Reinstall the usual SIGINT handlers, after the target has
23860348 4986 stopped. */
6426a772 4987static void
934b9bac 4988async_cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
4989{
4990 signal (SIGINT, handle_sigint);
43ff13b4
JM
4991}
4992
c906108c
SS
4993/* Send ^C to target to halt it. Target will respond, and send us a
4994 packet. */
507f3c78 4995static void (*ofunc) (int);
c906108c 4996
0df8b418
MS
4997/* The command line interface's stop routine. This function is installed
4998 as a signal handler for SIGINT. The first time a user requests a
4999 stop, we call remote_stop to send a break or ^C. If there is no
7a292a7a 5000 response from the target (it didn't stop when the user requested it),
23860348 5001 we ask the user if he'd like to detach from the target. */
c906108c 5002static void
934b9bac 5003sync_remote_interrupt (int signo)
c906108c 5004{
23860348 5005 /* If this doesn't work, try more severe steps. */
934b9bac 5006 signal (signo, sync_remote_interrupt_twice);
7a292a7a 5007
934b9bac 5008 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
7a292a7a
SS
5009}
5010
5011/* The user typed ^C twice. */
5012
5013static void
934b9bac 5014sync_remote_interrupt_twice (int signo)
7a292a7a
SS
5015{
5016 signal (signo, ofunc);
934b9bac
JK
5017 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5018 signal (signo, sync_remote_interrupt);
c906108c 5019}
7a292a7a 5020
74531fed
PA
5021/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5022 thread, all threads of a remote process, or all threads of all
5023 processes. */
5024
5025static void
5026remote_stop_ns (ptid_t ptid)
5027{
5028 struct remote_state *rs = get_remote_state ();
5029 char *p = rs->buf;
5030 char *endp = rs->buf + get_remote_packet_size ();
74531fed 5031
4082afcc 5032 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
5033 remote_vcont_probe (rs);
5034
d458bd84 5035 if (!rs->supports_vCont.t)
74531fed
PA
5036 error (_("Remote server does not support stopping threads"));
5037
f91d3df5
PA
5038 if (ptid_equal (ptid, minus_one_ptid)
5039 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5040 p += xsnprintf (p, endp - p, "vCont;t");
5041 else
5042 {
5043 ptid_t nptid;
5044
74531fed
PA
5045 p += xsnprintf (p, endp - p, "vCont;t:");
5046
5047 if (ptid_is_pid (ptid))
5048 /* All (-1) threads of process. */
ba348170 5049 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
5050 else
5051 {
5052 /* Small optimization: if we already have a stop reply for
5053 this thread, no use in telling the stub we want this
5054 stopped. */
5055 if (peek_stop_reply (ptid))
5056 return;
5057
5058 nptid = ptid;
5059 }
5060
a9cbf802 5061 write_ptid (p, endp, nptid);
74531fed
PA
5062 }
5063
5064 /* In non-stop, we get an immediate OK reply. The stop reply will
5065 come in asynchronously by notification. */
5066 putpkt (rs->buf);
5067 getpkt (&rs->buf, &rs->buf_size, 0);
5068 if (strcmp (rs->buf, "OK") != 0)
5069 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5070}
5071
5072/* All-stop version of target_stop. Sends a break or a ^C to stop the
5073 remote target. It is undefined which thread of which process
5074 reports the stop. */
5075
5076static void
5077remote_stop_as (ptid_t ptid)
5078{
5079 struct remote_state *rs = get_remote_state ();
5080
3a29589a
DJ
5081 rs->ctrlc_pending_p = 1;
5082
74531fed
PA
5083 /* If the inferior is stopped already, but the core didn't know
5084 about it yet, just ignore the request. The cached wait status
5085 will be collected in remote_wait. */
5086 if (rs->cached_wait_status)
5087 return;
5088
9a7071a8
JB
5089 /* Send interrupt_sequence to remote target. */
5090 send_interrupt_sequence ();
74531fed
PA
5091}
5092
0df8b418 5093/* This is the generic stop called via the target vector. When a target
7a292a7a 5094 interrupt is requested, either by the command line or the GUI, we
23860348 5095 will eventually end up here. */
74531fed 5096
c906108c 5097static void
1eab8a48 5098remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5099{
7a292a7a 5100 if (remote_debug)
0f71a2f6 5101 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5102
74531fed
PA
5103 if (non_stop)
5104 remote_stop_ns (ptid);
c906108c 5105 else
74531fed 5106 remote_stop_as (ptid);
c906108c
SS
5107}
5108
5109/* Ask the user what to do when an interrupt is received. */
5110
5111static void
fba45db2 5112interrupt_query (void)
c906108c
SS
5113{
5114 target_terminal_ours ();
5115
d9d41e78 5116 if (target_is_async_p ())
c906108c 5117 {
74531fed 5118 signal (SIGINT, handle_sigint);
039e3c22 5119 quit ();
c906108c 5120 }
74531fed
PA
5121 else
5122 {
9e2f0ad4
HZ
5123 if (query (_("Interrupted while waiting for the program.\n\
5124Give up (and stop debugging it)? ")))
74531fed 5125 {
78a095c3 5126 remote_unpush_target ();
039e3c22 5127 quit ();
74531fed
PA
5128 }
5129 }
c906108c
SS
5130
5131 target_terminal_inferior ();
5132}
5133
6426a772
JM
5134/* Enable/disable target terminal ownership. Most targets can use
5135 terminal groups to control terminal ownership. Remote targets are
5136 different in that explicit transfer of ownership to/from GDB/target
23860348 5137 is required. */
6426a772
JM
5138
5139static void
d2f640d4 5140remote_terminal_inferior (struct target_ops *self)
6426a772 5141{
c6ebd6cf 5142 if (!target_async_permitted)
75c99385
PA
5143 /* Nothing to do. */
5144 return;
5145
d9d2d8b6
PA
5146 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5147 idempotent. The event-loop GDB talking to an asynchronous target
5148 with a synchronous command calls this function from both
5149 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5150 transfer the terminal to the target when it shouldn't this guard
5151 can go away. */
6426a772
JM
5152 if (!remote_async_terminal_ours_p)
5153 return;
5154 delete_file_handler (input_fd);
5155 remote_async_terminal_ours_p = 0;
934b9bac 5156 async_initialize_sigint_signal_handler ();
6426a772
JM
5157 /* NOTE: At this point we could also register our selves as the
5158 recipient of all input. Any characters typed could then be
23860348 5159 passed on down to the target. */
6426a772
JM
5160}
5161
5162static void
e3594fd1 5163remote_terminal_ours (struct target_ops *self)
6426a772 5164{
c6ebd6cf 5165 if (!target_async_permitted)
75c99385
PA
5166 /* Nothing to do. */
5167 return;
5168
5169 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5170 if (remote_async_terminal_ours_p)
5171 return;
934b9bac 5172 async_cleanup_sigint_signal_handler (NULL);
6426a772
JM
5173 add_file_handler (input_fd, stdin_event_handler, 0);
5174 remote_async_terminal_ours_p = 1;
5175}
5176
176a6961 5177static void
917317f4 5178remote_console_output (char *msg)
c906108c
SS
5179{
5180 char *p;
5181
c5aa993b 5182 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5183 {
5184 char tb[2];
5185 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5186
c906108c
SS
5187 tb[0] = c;
5188 tb[1] = 0;
43ff13b4 5189 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5190 }
00db5b94
PA
5191 gdb_flush (gdb_stdtarg);
5192}
74531fed
PA
5193
5194typedef struct cached_reg
5195{
5196 int num;
5197 gdb_byte data[MAX_REGISTER_SIZE];
5198} cached_reg_t;
5199
5200DEF_VEC_O(cached_reg_t);
5201
722247f1 5202typedef struct stop_reply
74531fed 5203{
722247f1 5204 struct notif_event base;
74531fed 5205
722247f1 5206 /* The identifier of the thread about this event */
74531fed
PA
5207 ptid_t ptid;
5208
340e3c99 5209 /* The remote state this event is associated with. When the remote
bcc75809
YQ
5210 connection, represented by a remote_state object, is closed,
5211 all the associated stop_reply events should be released. */
5212 struct remote_state *rs;
5213
74531fed
PA
5214 struct target_waitstatus ws;
5215
15148d6a
PA
5216 /* Expedited registers. This makes remote debugging a bit more
5217 efficient for those targets that provide critical registers as
5218 part of their normal status mechanism (as another roundtrip to
5219 fetch them is avoided). */
74531fed
PA
5220 VEC(cached_reg_t) *regcache;
5221
f7e6eed5
PA
5222 enum target_stop_reason stop_reason;
5223
74531fed
PA
5224 CORE_ADDR watch_data_address;
5225
dc146f7c 5226 int core;
722247f1 5227} *stop_reply_p;
a744cf53 5228
722247f1
YQ
5229DECLARE_QUEUE_P (stop_reply_p);
5230DEFINE_QUEUE_P (stop_reply_p);
5231/* The list of already fetched and acknowledged stop events. This
5232 queue is used for notification Stop, and other notifications
5233 don't need queue for their events, because the notification events
5234 of Stop can't be consumed immediately, so that events should be
5235 queued first, and be consumed by remote_wait_{ns,as} one per
5236 time. Other notifications can consume their events immediately,
5237 so queue is not needed for them. */
5238static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
5239
5240static void
5241stop_reply_xfree (struct stop_reply *r)
5242{
f48ff2a7 5243 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
5244}
5245
722247f1
YQ
5246static void
5247remote_notif_stop_parse (struct notif_client *self, char *buf,
5248 struct notif_event *event)
5249{
5250 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5251}
5252
5253static void
5254remote_notif_stop_ack (struct notif_client *self, char *buf,
5255 struct notif_event *event)
5256{
5257 struct stop_reply *stop_reply = (struct stop_reply *) event;
5258
5259 /* acknowledge */
5260 putpkt ((char *) self->ack_command);
5261
5262 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5263 /* We got an unknown stop reply. */
5264 error (_("Unknown stop reply"));
5265
5266 push_stop_reply (stop_reply);
5267}
5268
5269static int
5270remote_notif_stop_can_get_pending_events (struct notif_client *self)
5271{
5272 /* We can't get pending events in remote_notif_process for
5273 notification stop, and we have to do this in remote_wait_ns
5274 instead. If we fetch all queued events from stub, remote stub
5275 may exit and we have no chance to process them back in
5276 remote_wait_ns. */
5277 mark_async_event_handler (remote_async_inferior_event_token);
5278 return 0;
5279}
5280
5281static void
5282stop_reply_dtr (struct notif_event *event)
5283{
5284 struct stop_reply *r = (struct stop_reply *) event;
5285
5286 VEC_free (cached_reg_t, r->regcache);
5287}
5288
5289static struct notif_event *
5290remote_notif_stop_alloc_reply (void)
5291{
5292 struct notif_event *r
70ba0933 5293 = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
5294
5295 r->dtr = stop_reply_dtr;
5296
5297 return r;
5298}
5299
5300/* A client of notification Stop. */
5301
5302struct notif_client notif_client_stop =
5303{
5304 "Stop",
5305 "vStopped",
5306 remote_notif_stop_parse,
5307 remote_notif_stop_ack,
5308 remote_notif_stop_can_get_pending_events,
5309 remote_notif_stop_alloc_reply,
f48ff2a7 5310 REMOTE_NOTIF_STOP,
722247f1
YQ
5311};
5312
5313/* A parameter to pass data in and out. */
5314
5315struct queue_iter_param
5316{
5317 void *input;
5318 struct stop_reply *output;
5319};
5320
f48ff2a7
YQ
5321/* Remove stop replies in the queue if its pid is equal to the given
5322 inferior's pid. */
722247f1
YQ
5323
5324static int
f48ff2a7
YQ
5325remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5326 QUEUE_ITER (stop_reply_p) *iter,
5327 stop_reply_p event,
5328 void *data)
722247f1
YQ
5329{
5330 struct queue_iter_param *param = data;
5331 struct inferior *inf = param->input;
5332
f48ff2a7 5333 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
5334 {
5335 stop_reply_xfree (event);
5336 QUEUE_remove_elem (stop_reply_p, q, iter);
5337 }
5338
5339 return 1;
5340}
5341
f48ff2a7 5342/* Discard all pending stop replies of inferior INF. */
c906108c 5343
74531fed 5344static void
5f4cf0bb 5345discard_pending_stop_replies (struct inferior *inf)
c906108c 5346{
722247f1
YQ
5347 int i;
5348 struct queue_iter_param param;
f48ff2a7
YQ
5349 struct stop_reply *reply;
5350 struct remote_state *rs = get_remote_state ();
5351 struct remote_notif_state *rns = rs->notif_state;
5352
5353 /* This function can be notified when an inferior exists. When the
5354 target is not remote, the notification state is NULL. */
5355 if (rs->remote_desc == NULL)
5356 return;
5357
5358 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 5359
74531fed 5360 /* Discard the in-flight notification. */
f48ff2a7 5361 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 5362 {
722247f1 5363 stop_reply_xfree (reply);
f48ff2a7 5364 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 5365 }
c906108c 5366
722247f1
YQ
5367 param.input = inf;
5368 param.output = NULL;
74531fed
PA
5369 /* Discard the stop replies we have already pulled with
5370 vStopped. */
722247f1 5371 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
5372 remove_stop_reply_for_inferior, &param);
5373}
5374
bcc75809
YQ
5375/* If its remote state is equal to the given remote state,
5376 remove EVENT from the stop reply queue. */
5377
5378static int
5379remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5380 QUEUE_ITER (stop_reply_p) *iter,
5381 stop_reply_p event,
5382 void *data)
5383{
5384 struct queue_iter_param *param = data;
5385 struct remote_state *rs = param->input;
5386
5387 if (event->rs == rs)
5388 {
5389 stop_reply_xfree (event);
5390 QUEUE_remove_elem (stop_reply_p, q, iter);
5391 }
5392
5393 return 1;
5394}
5395
5396/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
5397
5398static void
bcc75809 5399discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
5400{
5401 struct queue_iter_param param;
5402
bcc75809 5403 param.input = rs;
f48ff2a7
YQ
5404 param.output = NULL;
5405 /* Discard the stop replies we have already pulled with
5406 vStopped. */
5407 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 5408 remove_stop_reply_of_remote_state, &param);
722247f1 5409}
74531fed 5410
722247f1
YQ
5411/* A parameter to pass data in and out. */
5412
5413static int
5414remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5415 QUEUE_ITER (stop_reply_p) *iter,
5416 stop_reply_p event,
5417 void *data)
5418{
5419 struct queue_iter_param *param = data;
5420 ptid_t *ptid = param->input;
5421
5422 if (ptid_match (event->ptid, *ptid))
5423 {
5424 param->output = event;
5425 QUEUE_remove_elem (stop_reply_p, q, iter);
5426 return 0;
c8e38a49 5427 }
722247f1
YQ
5428
5429 return 1;
74531fed 5430}
43ff13b4 5431
722247f1
YQ
5432/* Remove the first reply in 'stop_reply_queue' which matches
5433 PTID. */
2e9f7625 5434
722247f1
YQ
5435static struct stop_reply *
5436remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 5437{
722247f1
YQ
5438 struct queue_iter_param param;
5439
5440 param.input = &ptid;
5441 param.output = NULL;
5442
5443 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5444 remote_notif_remove_once_on_match, &param);
5445 if (notif_debug)
5446 fprintf_unfiltered (gdb_stdlog,
5447 "notif: discard queued event: 'Stop' in %s\n",
5448 target_pid_to_str (ptid));
a744cf53 5449
722247f1 5450 return param.output;
74531fed 5451}
75c99385 5452
74531fed
PA
5453/* Look for a queued stop reply belonging to PTID. If one is found,
5454 remove it from the queue, and return it. Returns NULL if none is
5455 found. If there are still queued events left to process, tell the
5456 event loop to get back to target_wait soon. */
e24a49d8 5457
74531fed
PA
5458static struct stop_reply *
5459queued_stop_reply (ptid_t ptid)
5460{
722247f1 5461 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 5462
722247f1 5463 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
5464 /* There's still at least an event left. */
5465 mark_async_event_handler (remote_async_inferior_event_token);
5466
722247f1 5467 return r;
74531fed
PA
5468}
5469
5470/* Push a fully parsed stop reply in the stop reply queue. Since we
5471 know that we now have at least one queued event left to pass to the
5472 core side, tell the event loop to get back to target_wait soon. */
5473
5474static void
5475push_stop_reply (struct stop_reply *new_event)
5476{
722247f1 5477 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 5478
722247f1
YQ
5479 if (notif_debug)
5480 fprintf_unfiltered (gdb_stdlog,
5481 "notif: push 'Stop' %s to queue %d\n",
5482 target_pid_to_str (new_event->ptid),
5483 QUEUE_length (stop_reply_p,
5484 stop_reply_queue));
74531fed
PA
5485
5486 mark_async_event_handler (remote_async_inferior_event_token);
5487}
5488
722247f1
YQ
5489static int
5490stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5491 QUEUE_ITER (stop_reply_p) *iter,
5492 struct stop_reply *event,
5493 void *data)
5494{
5495 ptid_t *ptid = data;
5496
5497 return !(ptid_equal (*ptid, event->ptid)
5498 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5499}
5500
74531fed
PA
5501/* Returns true if we have a stop reply for PTID. */
5502
5503static int
5504peek_stop_reply (ptid_t ptid)
5505{
722247f1
YQ
5506 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5507 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
5508}
5509
1f10ba14
PA
5510/* Skip PACKET until the next semi-colon (or end of string). */
5511
5512static char *
5513skip_to_semicolon (char *p)
5514{
5515 while (*p != '\0' && *p != ';')
5516 p++;
5517 return p;
5518}
5519
74531fed
PA
5520/* Parse the stop reply in BUF. Either the function succeeds, and the
5521 result is stored in EVENT, or throws an error. */
5522
5523static void
5524remote_parse_stop_reply (char *buf, struct stop_reply *event)
5525{
5526 struct remote_arch_state *rsa = get_remote_arch_state ();
5527 ULONGEST addr;
5528 char *p;
5529
5530 event->ptid = null_ptid;
bcc75809 5531 event->rs = get_remote_state ();
74531fed
PA
5532 event->ws.kind = TARGET_WAITKIND_IGNORE;
5533 event->ws.value.integer = 0;
f7e6eed5 5534 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 5535 event->regcache = NULL;
dc146f7c 5536 event->core = -1;
74531fed
PA
5537
5538 switch (buf[0])
5539 {
5540 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
5541 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5542 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5543 ss = signal number
5544 n... = register number
5545 r... = register contents
5546 */
5547
5548 p = &buf[3]; /* after Txx */
5549 while (*p)
5550 {
5551 char *p1;
cea39f65 5552 int fieldsize;
43ff13b4 5553
1f10ba14
PA
5554 p1 = strchr (p, ':');
5555 if (p1 == NULL)
5556 error (_("Malformed packet(a) (missing colon): %s\n\
5557Packet: '%s'\n"),
5558 p, buf);
5559 if (p == p1)
5560 error (_("Malformed packet(a) (missing register number): %s\n\
5561Packet: '%s'\n"),
5562 p, buf);
3c3bea1c 5563
1f10ba14
PA
5564 /* Some "registers" are actually extended stop information.
5565 Note if you're adding a new entry here: GDB 7.9 and
5566 earlier assume that all register "numbers" that start
5567 with an hex digit are real register numbers. Make sure
5568 the server only sends such a packet if it knows the
5569 client understands it. */
c8e38a49 5570
1f10ba14
PA
5571 if (strncmp (p, "thread", p1 - p) == 0)
5572 event->ptid = read_ptid (++p1, &p);
5573 else if ((strncmp (p, "watch", p1 - p) == 0)
5574 || (strncmp (p, "rwatch", p1 - p) == 0)
5575 || (strncmp (p, "awatch", p1 - p) == 0))
cea39f65 5576 {
f7e6eed5 5577 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
5578 p = unpack_varlen_hex (++p1, &addr);
5579 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 5580 }
f7e6eed5
PA
5581 else if (strncmp (p, "swbreak", p1 - p) == 0)
5582 {
5583 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
5584
5585 /* Make sure the stub doesn't forget to indicate support
5586 with qSupported. */
5587 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
5588 error (_("Unexpected swbreak stop reason"));
5589
5590 /* The value part is documented as "must be empty",
5591 though we ignore it, in case we ever decide to make
5592 use of it in a backward compatible way. */
5593 p = skip_to_semicolon (p1 + 1);
5594 }
5595 else if (strncmp (p, "hwbreak", p1 - p) == 0)
5596 {
5597 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
5598
5599 /* Make sure the stub doesn't forget to indicate support
5600 with qSupported. */
5601 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
5602 error (_("Unexpected hwbreak stop reason"));
5603
5604 /* See above. */
5605 p = skip_to_semicolon (p1 + 1);
5606 }
1f10ba14 5607 else if (strncmp (p, "library", p1 - p) == 0)
cea39f65 5608 {
1f10ba14
PA
5609 event->ws.kind = TARGET_WAITKIND_LOADED;
5610 p = skip_to_semicolon (p1 + 1);
5611 }
5612 else if (strncmp (p, "replaylog", p1 - p) == 0)
5613 {
5614 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5615 /* p1 will indicate "begin" or "end", but it makes
5616 no difference for now, so ignore it. */
5617 p = skip_to_semicolon (p1 + 1);
5618 }
5619 else if (strncmp (p, "core", p1 - p) == 0)
5620 {
5621 ULONGEST c;
a744cf53 5622
1f10ba14
PA
5623 p = unpack_varlen_hex (++p1, &c);
5624 event->core = c;
cea39f65
MS
5625 }
5626 else
5627 {
1f10ba14
PA
5628 ULONGEST pnum;
5629 char *p_temp;
5630
5631 /* Maybe a real ``P'' register number. */
5632 p_temp = unpack_varlen_hex (p, &pnum);
5633 /* If the first invalid character is the colon, we got a
5634 register number. Otherwise, it's an unknown stop
5635 reason. */
5636 if (p_temp == p1)
5637 {
5638 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5639 cached_reg_t cached_reg;
43ff13b4 5640
1f10ba14
PA
5641 if (reg == NULL)
5642 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 5643Packet: '%s'\n"),
1f10ba14 5644 hex_string (pnum), p, buf);
c8e38a49 5645
1f10ba14 5646 cached_reg.num = reg->regnum;
4100683b 5647
1f10ba14
PA
5648 p = p1 + 1;
5649 fieldsize = hex2bin (p, cached_reg.data,
5650 register_size (target_gdbarch (),
5651 reg->regnum));
5652 p += 2 * fieldsize;
5653 if (fieldsize < register_size (target_gdbarch (),
5654 reg->regnum))
5655 warning (_("Remote reply is too short: %s"), buf);
74531fed 5656
1f10ba14
PA
5657 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5658 }
5659 else
5660 {
5661 /* Not a number. Silently skip unknown optional
5662 info. */
5663 p = skip_to_semicolon (p1 + 1);
5664 }
cea39f65 5665 }
c8e38a49 5666
cea39f65
MS
5667 if (*p != ';')
5668 error (_("Remote register badly formatted: %s\nhere: %s"),
5669 buf, p);
5670 ++p;
5671 }
5b5596ff
PA
5672
5673 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
5674 break;
5675
c8e38a49
PA
5676 /* fall through */
5677 case 'S': /* Old style status, just signal only. */
3a09da41
PA
5678 {
5679 int sig;
5680
5681 event->ws.kind = TARGET_WAITKIND_STOPPED;
5682 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
5683 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
5684 event->ws.value.sig = (enum gdb_signal) sig;
5685 else
5686 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5687 }
c8e38a49
PA
5688 break;
5689 case 'W': /* Target exited. */
5690 case 'X':
5691 {
5692 char *p;
5693 int pid;
5694 ULONGEST value;
82f73884 5695
c8e38a49
PA
5696 /* GDB used to accept only 2 hex chars here. Stubs should
5697 only send more if they detect GDB supports multi-process
5698 support. */
5699 p = unpack_varlen_hex (&buf[1], &value);
82f73884 5700
c8e38a49
PA
5701 if (buf[0] == 'W')
5702 {
5703 /* The remote process exited. */
74531fed
PA
5704 event->ws.kind = TARGET_WAITKIND_EXITED;
5705 event->ws.value.integer = value;
c8e38a49
PA
5706 }
5707 else
5708 {
5709 /* The remote process exited with a signal. */
74531fed 5710 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
5711 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
5712 event->ws.value.sig = (enum gdb_signal) value;
5713 else
5714 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 5715 }
82f73884 5716
c8e38a49
PA
5717 /* If no process is specified, assume inferior_ptid. */
5718 pid = ptid_get_pid (inferior_ptid);
5719 if (*p == '\0')
5720 ;
5721 else if (*p == ';')
5722 {
5723 p++;
5724
0b24eb2d 5725 if (*p == '\0')
82f73884 5726 ;
61012eef 5727 else if (startswith (p, "process:"))
82f73884 5728 {
c8e38a49 5729 ULONGEST upid;
a744cf53 5730
c8e38a49
PA
5731 p += sizeof ("process:") - 1;
5732 unpack_varlen_hex (p, &upid);
5733 pid = upid;
82f73884
PA
5734 }
5735 else
5736 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 5737 }
c8e38a49
PA
5738 else
5739 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
5740 event->ptid = pid_to_ptid (pid);
5741 }
5742 break;
5743 }
5744
5745 if (non_stop && ptid_equal (event->ptid, null_ptid))
5746 error (_("No process or thread specified in stop reply: %s"), buf);
5747}
5748
722247f1
YQ
5749/* When the stub wants to tell GDB about a new notification reply, it
5750 sends a notification (%Stop, for example). Those can come it at
5751 any time, hence, we have to make sure that any pending
5752 putpkt/getpkt sequence we're making is finished, before querying
5753 the stub for more events with the corresponding ack command
5754 (vStopped, for example). E.g., if we started a vStopped sequence
5755 immediately upon receiving the notification, something like this
5756 could happen:
74531fed
PA
5757
5758 1.1) --> Hg 1
5759 1.2) <-- OK
5760 1.3) --> g
5761 1.4) <-- %Stop
5762 1.5) --> vStopped
5763 1.6) <-- (registers reply to step #1.3)
5764
5765 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5766 query.
5767
796cb314 5768 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
5769 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5770 doing whatever we were doing:
5771
5772 2.1) --> Hg 1
5773 2.2) <-- OK
5774 2.3) --> g
5775 2.4) <-- %Stop
5776 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5777 2.5) <-- (registers reply to step #2.3)
5778
5779 Eventualy after step #2.5, we return to the event loop, which
5780 notices there's an event on the
5781 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5782 associated callback --- the function below. At this point, we're
5783 always safe to start a vStopped sequence. :
5784
5785 2.6) --> vStopped
5786 2.7) <-- T05 thread:2
5787 2.8) --> vStopped
5788 2.9) --> OK
5789*/
5790
722247f1
YQ
5791void
5792remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
5793{
5794 struct remote_state *rs = get_remote_state ();
74531fed 5795
f48ff2a7 5796 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 5797 {
722247f1
YQ
5798 if (notif_debug)
5799 fprintf_unfiltered (gdb_stdlog,
5800 "notif: process: '%s' ack pending event\n",
5801 nc->name);
74531fed 5802
722247f1 5803 /* acknowledge */
f48ff2a7
YQ
5804 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
5805 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
5806
5807 while (1)
5808 {
5809 getpkt (&rs->buf, &rs->buf_size, 0);
5810 if (strcmp (rs->buf, "OK") == 0)
5811 break;
5812 else
722247f1 5813 remote_notif_ack (nc, rs->buf);
74531fed
PA
5814 }
5815 }
722247f1
YQ
5816 else
5817 {
5818 if (notif_debug)
5819 fprintf_unfiltered (gdb_stdlog,
5820 "notif: process: '%s' no pending reply\n",
5821 nc->name);
5822 }
74531fed
PA
5823}
5824
74531fed
PA
5825/* Called when it is decided that STOP_REPLY holds the info of the
5826 event that is to be returned to the core. This function always
5827 destroys STOP_REPLY. */
5828
5829static ptid_t
5830process_stop_reply (struct stop_reply *stop_reply,
5831 struct target_waitstatus *status)
5832{
5833 ptid_t ptid;
5834
5835 *status = stop_reply->ws;
5836 ptid = stop_reply->ptid;
5837
5838 /* If no thread/process was reported by the stub, assume the current
5839 inferior. */
5840 if (ptid_equal (ptid, null_ptid))
5841 ptid = inferior_ptid;
5842
5f3563ea
PA
5843 if (status->kind != TARGET_WAITKIND_EXITED
5844 && status->kind != TARGET_WAITKIND_SIGNALLED)
74531fed 5845 {
ee154bee
TT
5846 struct remote_state *rs = get_remote_state ();
5847
5f3563ea
PA
5848 /* Expedited registers. */
5849 if (stop_reply->regcache)
5850 {
217f1f79 5851 struct regcache *regcache
f5656ead 5852 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
5853 cached_reg_t *reg;
5854 int ix;
5855
5856 for (ix = 0;
5857 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5858 ix++)
217f1f79 5859 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
5860 VEC_free (cached_reg_t, stop_reply->regcache);
5861 }
74531fed 5862
f7e6eed5 5863 rs->stop_reason = stop_reply->stop_reason;
ee154bee 5864 rs->remote_watch_data_address = stop_reply->watch_data_address;
1941c569
PA
5865
5866 remote_notice_new_inferior (ptid, 0);
dc146f7c 5867 demand_private_info (ptid)->core = stop_reply->core;
74531fed
PA
5868 }
5869
74531fed
PA
5870 stop_reply_xfree (stop_reply);
5871 return ptid;
5872}
5873
5874/* The non-stop mode version of target_wait. */
5875
5876static ptid_t
47608cb1 5877remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
5878{
5879 struct remote_state *rs = get_remote_state ();
74531fed
PA
5880 struct stop_reply *stop_reply;
5881 int ret;
fee9eda9 5882 int is_notif = 0;
74531fed
PA
5883
5884 /* If in non-stop mode, get out of getpkt even if a
5885 notification is received. */
5886
5887 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 5888 0 /* forever */, &is_notif);
74531fed
PA
5889 while (1)
5890 {
fee9eda9 5891 if (ret != -1 && !is_notif)
74531fed
PA
5892 switch (rs->buf[0])
5893 {
5894 case 'E': /* Error of some sort. */
5895 /* We're out of sync with the target now. Did it continue
5896 or not? We can't tell which thread it was in non-stop,
5897 so just ignore this. */
5898 warning (_("Remote failure reply: %s"), rs->buf);
5899 break;
5900 case 'O': /* Console output. */
5901 remote_console_output (rs->buf + 1);
5902 break;
5903 default:
5904 warning (_("Invalid remote reply: %s"), rs->buf);
5905 break;
5906 }
5907
5908 /* Acknowledge a pending stop reply that may have arrived in the
5909 mean time. */
f48ff2a7 5910 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 5911 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
5912
5913 /* If indeed we noticed a stop reply, we're done. */
5914 stop_reply = queued_stop_reply (ptid);
5915 if (stop_reply != NULL)
5916 return process_stop_reply (stop_reply, status);
5917
47608cb1 5918 /* Still no event. If we're just polling for an event, then
74531fed 5919 return to the event loop. */
47608cb1 5920 if (options & TARGET_WNOHANG)
74531fed
PA
5921 {
5922 status->kind = TARGET_WAITKIND_IGNORE;
5923 return minus_one_ptid;
5924 }
5925
47608cb1 5926 /* Otherwise do a blocking wait. */
74531fed 5927 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 5928 1 /* forever */, &is_notif);
74531fed
PA
5929 }
5930}
5931
5932/* Wait until the remote machine stops, then return, storing status in
5933 STATUS just as `wait' would. */
5934
5935static ptid_t
47608cb1 5936remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
5937{
5938 struct remote_state *rs = get_remote_state ();
74531fed 5939 ptid_t event_ptid = null_ptid;
cea39f65 5940 char *buf;
74531fed
PA
5941 struct stop_reply *stop_reply;
5942
47608cb1
PA
5943 again:
5944
74531fed
PA
5945 status->kind = TARGET_WAITKIND_IGNORE;
5946 status->value.integer = 0;
5947
5948 stop_reply = queued_stop_reply (ptid);
5949 if (stop_reply != NULL)
5950 return process_stop_reply (stop_reply, status);
5951
5952 if (rs->cached_wait_status)
5953 /* Use the cached wait status, but only once. */
5954 rs->cached_wait_status = 0;
5955 else
5956 {
5957 int ret;
722247f1 5958 int is_notif;
74531fed
PA
5959
5960 if (!target_is_async_p ())
5961 {
934b9bac 5962 ofunc = signal (SIGINT, sync_remote_interrupt);
74531fed
PA
5963 /* If the user hit C-c before this packet, or between packets,
5964 pretend that it was hit right here. */
522002f9 5965 if (check_quit_flag ())
74531fed 5966 {
522002f9 5967 clear_quit_flag ();
934b9bac 5968 sync_remote_interrupt (SIGINT);
74531fed
PA
5969 }
5970 }
5971
5972 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5973 _never_ wait for ever -> test on target_is_async_p().
5974 However, before we do that we need to ensure that the caller
5975 knows how to take the target into/out of async mode. */
722247f1
YQ
5976 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5977 wait_forever_enabled_p, &is_notif);
5978
5e1b953b
SDJ
5979 if (!target_is_async_p ())
5980 signal (SIGINT, ofunc);
5981
722247f1
YQ
5982 /* GDB gets a notification. Return to core as this event is
5983 not interesting. */
5984 if (ret != -1 && is_notif)
5985 return minus_one_ptid;
74531fed
PA
5986 }
5987
5988 buf = rs->buf;
5989
f7e6eed5 5990 rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed
PA
5991
5992 /* We got something. */
5993 rs->waiting_for_stop_reply = 0;
5994
3a29589a
DJ
5995 /* Assume that the target has acknowledged Ctrl-C unless we receive
5996 an 'F' or 'O' packet. */
5997 if (buf[0] != 'F' && buf[0] != 'O')
5998 rs->ctrlc_pending_p = 0;
5999
74531fed
PA
6000 switch (buf[0])
6001 {
6002 case 'E': /* Error of some sort. */
6003 /* We're out of sync with the target now. Did it continue or
6004 not? Not is more likely, so report a stop. */
6005 warning (_("Remote failure reply: %s"), buf);
6006 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 6007 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
6008 break;
6009 case 'F': /* File-I/O request. */
3a29589a
DJ
6010 remote_fileio_request (buf, rs->ctrlc_pending_p);
6011 rs->ctrlc_pending_p = 0;
74531fed
PA
6012 break;
6013 case 'T': case 'S': case 'X': case 'W':
6014 {
722247f1
YQ
6015 struct stop_reply *stop_reply
6016 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6017 rs->buf);
74531fed 6018
74531fed 6019 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
6020 break;
6021 }
6022 case 'O': /* Console output. */
6023 remote_console_output (buf + 1);
e24a49d8 6024
c8e38a49
PA
6025 /* The target didn't really stop; keep waiting. */
6026 rs->waiting_for_stop_reply = 1;
e24a49d8 6027
c8e38a49
PA
6028 break;
6029 case '\0':
b73be471 6030 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
6031 {
6032 /* Zero length reply means that we tried 'S' or 'C' and the
6033 remote system doesn't support it. */
6034 target_terminal_ours_for_output ();
6035 printf_filtered
6036 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
6037 gdb_signal_to_name (rs->last_sent_signal));
6038 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
6039 target_terminal_inferior ();
6040
280ceea3 6041 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49
PA
6042 putpkt ((char *) buf);
6043
6044 /* We just told the target to resume, so a stop reply is in
6045 order. */
e24a49d8 6046 rs->waiting_for_stop_reply = 1;
c8e38a49 6047 break;
43ff13b4 6048 }
c8e38a49
PA
6049 /* else fallthrough */
6050 default:
6051 warning (_("Invalid remote reply: %s"), buf);
6052 /* Keep waiting. */
6053 rs->waiting_for_stop_reply = 1;
6054 break;
43ff13b4 6055 }
c8e38a49 6056
c8e38a49 6057 if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
6058 {
6059 /* Nothing interesting happened. If we're doing a non-blocking
6060 poll, we're done. Otherwise, go back to waiting. */
6061 if (options & TARGET_WNOHANG)
6062 return minus_one_ptid;
6063 else
6064 goto again;
6065 }
74531fed
PA
6066 else if (status->kind != TARGET_WAITKIND_EXITED
6067 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
6068 {
6069 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 6070 record_currthread (rs, event_ptid);
82f73884
PA
6071 else
6072 event_ptid = inferior_ptid;
43ff13b4 6073 }
74531fed
PA
6074 else
6075 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 6076 record_currthread (rs, minus_one_ptid);
79d7f229 6077
82f73884 6078 return event_ptid;
43ff13b4
JM
6079}
6080
74531fed
PA
6081/* Wait until the remote machine stops, then return, storing status in
6082 STATUS just as `wait' would. */
6083
c8e38a49 6084static ptid_t
117de6a9 6085remote_wait (struct target_ops *ops,
47608cb1 6086 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
6087{
6088 ptid_t event_ptid;
6089
74531fed 6090 if (non_stop)
47608cb1 6091 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 6092 else
47608cb1 6093 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 6094
d9d41e78 6095 if (target_is_async_p ())
c8e38a49 6096 {
74531fed
PA
6097 /* If there are are events left in the queue tell the event loop
6098 to return here. */
722247f1 6099 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 6100 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 6101 }
c8e38a49
PA
6102
6103 return event_ptid;
6104}
6105
74ca34ce 6106/* Fetch a single register using a 'p' packet. */
c906108c 6107
b96ec7ac 6108static int
56be3814 6109fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
6110{
6111 struct remote_state *rs = get_remote_state ();
2e9f7625 6112 char *buf, *p;
b96ec7ac
AC
6113 char regp[MAX_REGISTER_SIZE];
6114 int i;
6115
4082afcc 6116 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
6117 return 0;
6118
6119 if (reg->pnum == -1)
6120 return 0;
6121
2e9f7625 6122 p = rs->buf;
fcad0fa4 6123 *p++ = 'p';
74ca34ce 6124 p += hexnumstr (p, reg->pnum);
fcad0fa4 6125 *p++ = '\0';
1f4437a4
MS
6126 putpkt (rs->buf);
6127 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 6128
2e9f7625
DJ
6129 buf = rs->buf;
6130
74ca34ce
DJ
6131 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6132 {
6133 case PACKET_OK:
6134 break;
6135 case PACKET_UNKNOWN:
6136 return 0;
6137 case PACKET_ERROR:
27a9c0bf
MS
6138 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6139 gdbarch_register_name (get_regcache_arch (regcache),
6140 reg->regnum),
6141 buf);
74ca34ce 6142 }
3f9a994c
JB
6143
6144 /* If this register is unfetchable, tell the regcache. */
6145 if (buf[0] == 'x')
8480adf2 6146 {
56be3814 6147 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 6148 return 1;
b96ec7ac 6149 }
b96ec7ac 6150
3f9a994c
JB
6151 /* Otherwise, parse and supply the value. */
6152 p = buf;
6153 i = 0;
6154 while (p[0] != 0)
6155 {
6156 if (p[1] == 0)
74ca34ce 6157 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
6158
6159 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6160 p += 2;
6161 }
56be3814 6162 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 6163 return 1;
b96ec7ac
AC
6164}
6165
74ca34ce
DJ
6166/* Fetch the registers included in the target's 'g' packet. */
6167
29709017
DJ
6168static int
6169send_g_packet (void)
c906108c 6170{
d01949b6 6171 struct remote_state *rs = get_remote_state ();
cea39f65 6172 int buf_len;
c906108c 6173
bba74b36 6174 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 6175 remote_send (&rs->buf, &rs->buf_size);
c906108c 6176
29709017
DJ
6177 /* We can get out of synch in various cases. If the first character
6178 in the buffer is not a hex character, assume that has happened
6179 and try to fetch another packet to read. */
6180 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6181 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6182 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6183 && rs->buf[0] != 'x') /* New: unavailable register value. */
6184 {
6185 if (remote_debug)
6186 fprintf_unfiltered (gdb_stdlog,
6187 "Bad register packet; fetching a new packet\n");
6188 getpkt (&rs->buf, &rs->buf_size, 0);
6189 }
6190
74ca34ce
DJ
6191 buf_len = strlen (rs->buf);
6192
6193 /* Sanity check the received packet. */
6194 if (buf_len % 2 != 0)
6195 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
6196
6197 return buf_len / 2;
6198}
6199
6200static void
56be3814 6201process_g_packet (struct regcache *regcache)
29709017 6202{
4a22f64d 6203 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
6204 struct remote_state *rs = get_remote_state ();
6205 struct remote_arch_state *rsa = get_remote_arch_state ();
6206 int i, buf_len;
6207 char *p;
6208 char *regs;
6209
6210 buf_len = strlen (rs->buf);
6211
6212 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
6213 if (buf_len > 2 * rsa->sizeof_g_packet)
6214 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6215
6216 /* Save the size of the packet sent to us by the target. It is used
6217 as a heuristic when determining the max size of packets that the
6218 target can safely receive. */
6219 if (rsa->actual_register_packet_size == 0)
6220 rsa->actual_register_packet_size = buf_len;
6221
6222 /* If this is smaller than we guessed the 'g' packet would be,
6223 update our records. A 'g' reply that doesn't include a register's
6224 value implies either that the register is not available, or that
6225 the 'p' packet must be used. */
6226 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 6227 {
74ca34ce
DJ
6228 rsa->sizeof_g_packet = buf_len / 2;
6229
4a22f64d 6230 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 6231 {
74ca34ce
DJ
6232 if (rsa->regs[i].pnum == -1)
6233 continue;
6234
6235 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6236 rsa->regs[i].in_g_packet = 0;
b96ec7ac 6237 else
74ca34ce 6238 rsa->regs[i].in_g_packet = 1;
b96ec7ac 6239 }
74ca34ce 6240 }
b323314b 6241
74ca34ce 6242 regs = alloca (rsa->sizeof_g_packet);
c906108c
SS
6243
6244 /* Unimplemented registers read as all bits zero. */
ea9c271d 6245 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 6246
c906108c
SS
6247 /* Reply describes registers byte by byte, each byte encoded as two
6248 hex characters. Suck them all up, then supply them to the
6249 register cacheing/storage mechanism. */
6250
74ca34ce 6251 p = rs->buf;
ea9c271d 6252 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 6253 {
74ca34ce
DJ
6254 if (p[0] == 0 || p[1] == 0)
6255 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6256 internal_error (__FILE__, __LINE__,
9b20d036 6257 _("unexpected end of 'g' packet reply"));
74ca34ce 6258
c906108c 6259 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 6260 regs[i] = 0; /* 'x' */
c906108c
SS
6261 else
6262 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6263 p += 2;
6264 }
6265
a744cf53
MS
6266 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6267 {
6268 struct packet_reg *r = &rsa->regs[i];
6269
6270 if (r->in_g_packet)
6271 {
6272 if (r->offset * 2 >= strlen (rs->buf))
6273 /* This shouldn't happen - we adjusted in_g_packet above. */
6274 internal_error (__FILE__, __LINE__,
9b20d036 6275 _("unexpected end of 'g' packet reply"));
a744cf53
MS
6276 else if (rs->buf[r->offset * 2] == 'x')
6277 {
6278 gdb_assert (r->offset * 2 < strlen (rs->buf));
6279 /* The register isn't available, mark it as such (at
6280 the same time setting the value to zero). */
6281 regcache_raw_supply (regcache, r->regnum, NULL);
6282 }
6283 else
6284 regcache_raw_supply (regcache, r->regnum,
6285 regs + r->offset);
6286 }
6287 }
c906108c
SS
6288}
6289
29709017 6290static void
56be3814 6291fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
6292{
6293 send_g_packet ();
56be3814 6294 process_g_packet (regcache);
29709017
DJ
6295}
6296
e6e4e701
PA
6297/* Make the remote selected traceframe match GDB's selected
6298 traceframe. */
6299
6300static void
6301set_remote_traceframe (void)
6302{
6303 int newnum;
262e1174 6304 struct remote_state *rs = get_remote_state ();
e6e4e701 6305
262e1174 6306 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
6307 return;
6308
6309 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 6310 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
6311
6312 newnum = target_trace_find (tfind_number,
6313 get_traceframe_number (), 0, 0, NULL);
6314
6315 /* Should not happen. If it does, all bets are off. */
6316 if (newnum != get_traceframe_number ())
6317 warning (_("could not set remote traceframe"));
6318}
6319
74ca34ce 6320static void
28439f5e
PA
6321remote_fetch_registers (struct target_ops *ops,
6322 struct regcache *regcache, int regnum)
74ca34ce 6323{
74ca34ce
DJ
6324 struct remote_arch_state *rsa = get_remote_arch_state ();
6325 int i;
6326
e6e4e701 6327 set_remote_traceframe ();
79d7f229 6328 set_general_thread (inferior_ptid);
74ca34ce
DJ
6329
6330 if (regnum >= 0)
6331 {
6332 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6333
74ca34ce
DJ
6334 gdb_assert (reg != NULL);
6335
6336 /* If this register might be in the 'g' packet, try that first -
6337 we are likely to read more than one register. If this is the
6338 first 'g' packet, we might be overly optimistic about its
6339 contents, so fall back to 'p'. */
6340 if (reg->in_g_packet)
6341 {
56be3814 6342 fetch_registers_using_g (regcache);
74ca34ce
DJ
6343 if (reg->in_g_packet)
6344 return;
6345 }
6346
56be3814 6347 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
6348 return;
6349
6350 /* This register is not available. */
56be3814 6351 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
6352
6353 return;
6354 }
6355
56be3814 6356 fetch_registers_using_g (regcache);
74ca34ce 6357
4a22f64d 6358 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6359 if (!rsa->regs[i].in_g_packet)
56be3814 6360 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
6361 {
6362 /* This register is not available. */
56be3814 6363 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
6364 }
6365}
6366
c906108c
SS
6367/* Prepare to store registers. Since we may send them all (using a
6368 'G' request), we have to read out the ones we don't want to change
6369 first. */
6370
c5aa993b 6371static void
f32dbf8c 6372remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 6373{
ea9c271d 6374 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 6375 int i;
cfd77fa1 6376 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 6377
c906108c 6378 /* Make sure the entire registers array is valid. */
4082afcc 6379 switch (packet_support (PACKET_P))
5a2468f5
JM
6380 {
6381 case PACKET_DISABLE:
6382 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 6383 /* Make sure all the necessary registers are cached. */
4a22f64d 6384 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 6385 if (rsa->regs[i].in_g_packet)
316f2060 6386 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
6387 break;
6388 case PACKET_ENABLE:
6389 break;
6390 }
6391}
6392
ad10f812 6393/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 6394 packet was not recognized. */
5a2468f5
JM
6395
6396static int
1f4437a4
MS
6397store_register_using_P (const struct regcache *regcache,
6398 struct packet_reg *reg)
5a2468f5 6399{
4a22f64d 6400 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 6401 struct remote_state *rs = get_remote_state ();
5a2468f5 6402 /* Try storing a single register. */
6d820c5c 6403 char *buf = rs->buf;
cfd77fa1 6404 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 6405 char *p;
5a2468f5 6406
4082afcc 6407 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
6408 return 0;
6409
6410 if (reg->pnum == -1)
6411 return 0;
6412
ea9c271d 6413 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 6414 p = buf + strlen (buf);
56be3814 6415 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 6416 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
6417 putpkt (rs->buf);
6418 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 6419
74ca34ce
DJ
6420 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6421 {
6422 case PACKET_OK:
6423 return 1;
6424 case PACKET_ERROR:
27a9c0bf
MS
6425 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6426 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
6427 case PACKET_UNKNOWN:
6428 return 0;
6429 default:
6430 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6431 }
c906108c
SS
6432}
6433
23860348
MS
6434/* Store register REGNUM, or all registers if REGNUM == -1, from the
6435 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
6436
6437static void
56be3814 6438store_registers_using_G (const struct regcache *regcache)
c906108c 6439{
d01949b6 6440 struct remote_state *rs = get_remote_state ();
ea9c271d 6441 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 6442 gdb_byte *regs;
c906108c
SS
6443 char *p;
6444
193cb69f
AC
6445 /* Extract all the registers in the regcache copying them into a
6446 local buffer. */
6447 {
b323314b 6448 int i;
a744cf53 6449
ea9c271d
DJ
6450 regs = alloca (rsa->sizeof_g_packet);
6451 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 6452 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 6453 {
ea9c271d 6454 struct packet_reg *r = &rsa->regs[i];
a744cf53 6455
b323314b 6456 if (r->in_g_packet)
56be3814 6457 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
6458 }
6459 }
c906108c
SS
6460
6461 /* Command describes registers byte by byte,
6462 each byte encoded as two hex characters. */
6d820c5c 6463 p = rs->buf;
193cb69f 6464 *p++ = 'G';
74ca34ce
DJ
6465 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6466 updated. */
6467 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
6468 putpkt (rs->buf);
6469 getpkt (&rs->buf, &rs->buf_size, 0);
6470 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
6471 error (_("Could not write registers; remote failure reply '%s'"),
6472 rs->buf);
c906108c 6473}
74ca34ce
DJ
6474
6475/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6476 of the register cache buffer. FIXME: ignores errors. */
6477
6478static void
28439f5e
PA
6479remote_store_registers (struct target_ops *ops,
6480 struct regcache *regcache, int regnum)
74ca34ce 6481{
74ca34ce
DJ
6482 struct remote_arch_state *rsa = get_remote_arch_state ();
6483 int i;
6484
e6e4e701 6485 set_remote_traceframe ();
79d7f229 6486 set_general_thread (inferior_ptid);
74ca34ce
DJ
6487
6488 if (regnum >= 0)
6489 {
6490 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6491
74ca34ce
DJ
6492 gdb_assert (reg != NULL);
6493
6494 /* Always prefer to store registers using the 'P' packet if
6495 possible; we often change only a small number of registers.
6496 Sometimes we change a larger number; we'd need help from a
6497 higher layer to know to use 'G'. */
56be3814 6498 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
6499 return;
6500
6501 /* For now, don't complain if we have no way to write the
6502 register. GDB loses track of unavailable registers too
6503 easily. Some day, this may be an error. We don't have
0df8b418 6504 any way to read the register, either... */
74ca34ce
DJ
6505 if (!reg->in_g_packet)
6506 return;
6507
56be3814 6508 store_registers_using_G (regcache);
74ca34ce
DJ
6509 return;
6510 }
6511
56be3814 6512 store_registers_using_G (regcache);
74ca34ce 6513
4a22f64d 6514 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6515 if (!rsa->regs[i].in_g_packet)
56be3814 6516 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
6517 /* See above for why we do not issue an error here. */
6518 continue;
6519}
c906108c
SS
6520\f
6521
6522/* Return the number of hex digits in num. */
6523
6524static int
fba45db2 6525hexnumlen (ULONGEST num)
c906108c
SS
6526{
6527 int i;
6528
6529 for (i = 0; num != 0; i++)
6530 num >>= 4;
6531
6532 return max (i, 1);
6533}
6534
2df3850c 6535/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
6536
6537static int
fba45db2 6538hexnumstr (char *buf, ULONGEST num)
c906108c 6539{
c906108c 6540 int len = hexnumlen (num);
a744cf53 6541
2df3850c
JM
6542 return hexnumnstr (buf, num, len);
6543}
6544
c906108c 6545
2df3850c 6546/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 6547
2df3850c 6548static int
fba45db2 6549hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
6550{
6551 int i;
6552
6553 buf[width] = '\0';
6554
6555 for (i = width - 1; i >= 0; i--)
c906108c 6556 {
c5aa993b 6557 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
6558 num >>= 4;
6559 }
6560
2df3850c 6561 return width;
c906108c
SS
6562}
6563
23860348 6564/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
6565
6566static CORE_ADDR
fba45db2 6567remote_address_masked (CORE_ADDR addr)
c906108c 6568{
883b9c6c 6569 unsigned int address_size = remote_address_size;
a744cf53 6570
911c95a5
UW
6571 /* If "remoteaddresssize" was not set, default to target address size. */
6572 if (!address_size)
f5656ead 6573 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
6574
6575 if (address_size > 0
6576 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
6577 {
6578 /* Only create a mask when that mask can safely be constructed
23860348 6579 in a ULONGEST variable. */
c906108c 6580 ULONGEST mask = 1;
a744cf53 6581
911c95a5 6582 mask = (mask << address_size) - 1;
c906108c
SS
6583 addr &= mask;
6584 }
6585 return addr;
6586}
6587
6588/* Determine whether the remote target supports binary downloading.
6589 This is accomplished by sending a no-op memory write of zero length
6590 to the target at the specified address. It does not suffice to send
23860348
MS
6591 the whole packet, since many stubs strip the eighth bit and
6592 subsequently compute a wrong checksum, which causes real havoc with
6593 remote_write_bytes.
7a292a7a 6594
96baa820 6595 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 6596 clean. In cases like this, the user should clear "remote
23860348 6597 X-packet". */
96baa820 6598
c906108c 6599static void
fba45db2 6600check_binary_download (CORE_ADDR addr)
c906108c 6601{
d01949b6 6602 struct remote_state *rs = get_remote_state ();
24b06219 6603
4082afcc 6604 switch (packet_support (PACKET_X))
c906108c 6605 {
96baa820
JM
6606 case PACKET_DISABLE:
6607 break;
6608 case PACKET_ENABLE:
6609 break;
6610 case PACKET_SUPPORT_UNKNOWN:
6611 {
96baa820 6612 char *p;
802188a7 6613
2e9f7625 6614 p = rs->buf;
96baa820
JM
6615 *p++ = 'X';
6616 p += hexnumstr (p, (ULONGEST) addr);
6617 *p++ = ',';
6618 p += hexnumstr (p, (ULONGEST) 0);
6619 *p++ = ':';
6620 *p = '\0';
802188a7 6621
2e9f7625 6622 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 6623 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 6624
2e9f7625 6625 if (rs->buf[0] == '\0')
96baa820
JM
6626 {
6627 if (remote_debug)
6628 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
6629 "binary downloading NOT "
6630 "supported by target\n");
444abaca 6631 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
6632 }
6633 else
6634 {
6635 if (remote_debug)
6636 fprintf_unfiltered (gdb_stdlog,
64b9b334 6637 "binary downloading supported by target\n");
444abaca 6638 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
6639 }
6640 break;
6641 }
c906108c
SS
6642 }
6643}
6644
6645/* Write memory data directly to the remote machine.
6646 This does not inform the data cache; the data cache uses this.
a76d924d 6647 HEADER is the starting part of the packet.
c906108c
SS
6648 MEMADDR is the address in the remote memory space.
6649 MYADDR is the address of the buffer in our space.
6650 LEN is the number of bytes.
a76d924d
DJ
6651 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6652 should send data as binary ('X'), or hex-encoded ('M').
6653
6654 The function creates packet of the form
6655 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6656
6657 where encoding of <DATA> is termined by PACKET_FORMAT.
6658
6659 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6660 are omitted.
6661
9b409511
YQ
6662 Return the transferred status, error or OK (an
6663 'enum target_xfer_status' value). Save the number of bytes
6664 transferred in *XFERED_LEN. Only transfer a single packet. */
c906108c 6665
9b409511 6666static enum target_xfer_status
a76d924d 6667remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
5d6df423 6668 const gdb_byte *myaddr, ULONGEST len,
9b409511
YQ
6669 ULONGEST *xfered_len, char packet_format,
6670 int use_length)
c906108c 6671{
6d820c5c 6672 struct remote_state *rs = get_remote_state ();
cfd77fa1 6673 char *p;
a76d924d
DJ
6674 char *plen = NULL;
6675 int plenlen = 0;
917317f4
JM
6676 int todo;
6677 int nr_bytes;
a257b5bb 6678 int payload_size;
6765f3e5 6679 int payload_length;
a76d924d
DJ
6680 int header_length;
6681
6682 if (packet_format != 'X' && packet_format != 'M')
6683 internal_error (__FILE__, __LINE__,
9b20d036 6684 _("remote_write_bytes_aux: bad packet format"));
c906108c 6685
5d6df423 6686 if (len == 0)
9b409511 6687 return TARGET_XFER_EOF;
b2182ed2 6688
3de11b2e 6689 payload_size = get_memory_write_packet_size ();
2bc416ba 6690
6d820c5c
DJ
6691 /* The packet buffer will be large enough for the payload;
6692 get_memory_packet_size ensures this. */
a76d924d 6693 rs->buf[0] = '\0';
c906108c 6694
a257b5bb 6695 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
6696 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6697
a76d924d
DJ
6698 payload_size -= strlen ("$,:#NN");
6699 if (!use_length)
0df8b418 6700 /* The comma won't be used. */
a76d924d
DJ
6701 payload_size += 1;
6702 header_length = strlen (header);
6703 payload_size -= header_length;
3de11b2e 6704 payload_size -= hexnumlen (memaddr);
c906108c 6705
a76d924d 6706 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 6707
a76d924d
DJ
6708 strcat (rs->buf, header);
6709 p = rs->buf + strlen (header);
6710
6711 /* Compute a best guess of the number of bytes actually transfered. */
6712 if (packet_format == 'X')
c906108c 6713 {
23860348 6714 /* Best guess at number of bytes that will fit. */
a257b5bb 6715 todo = min (len, payload_size);
a76d924d
DJ
6716 if (use_length)
6717 payload_size -= hexnumlen (todo);
3de11b2e 6718 todo = min (todo, payload_size);
a76d924d
DJ
6719 }
6720 else
6721 {
23860348 6722 /* Num bytes that will fit. */
a257b5bb 6723 todo = min (len, payload_size / 2);
a76d924d
DJ
6724 if (use_length)
6725 payload_size -= hexnumlen (todo);
3de11b2e 6726 todo = min (todo, payload_size / 2);
917317f4 6727 }
a76d924d 6728
3de11b2e
NS
6729 if (todo <= 0)
6730 internal_error (__FILE__, __LINE__,
405f8e94 6731 _("minimum packet size too small to write data"));
802188a7 6732
6765f3e5
DJ
6733 /* If we already need another packet, then try to align the end
6734 of this packet to a useful boundary. */
6735 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6736 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6737
a257b5bb 6738 /* Append "<memaddr>". */
917317f4
JM
6739 memaddr = remote_address_masked (memaddr);
6740 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 6741
a76d924d
DJ
6742 if (use_length)
6743 {
6744 /* Append ",". */
6745 *p++ = ',';
802188a7 6746
a76d924d
DJ
6747 /* Append <len>. Retain the location/size of <len>. It may need to
6748 be adjusted once the packet body has been created. */
6749 plen = p;
6750 plenlen = hexnumstr (p, (ULONGEST) todo);
6751 p += plenlen;
6752 }
a257b5bb
AC
6753
6754 /* Append ":". */
917317f4
JM
6755 *p++ = ':';
6756 *p = '\0';
802188a7 6757
a257b5bb 6758 /* Append the packet body. */
a76d924d 6759 if (packet_format == 'X')
917317f4 6760 {
917317f4
JM
6761 /* Binary mode. Send target system values byte by byte, in
6762 increasing byte addresses. Only escape certain critical
6763 characters. */
bc20a4af
PA
6764 payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
6765 &nr_bytes, payload_size);
6765f3e5
DJ
6766
6767 /* If not all TODO bytes fit, then we'll need another packet. Make
9b7194bc
DJ
6768 a second try to keep the end of the packet aligned. Don't do
6769 this if the packet is tiny. */
6770 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6765f3e5
DJ
6771 {
6772 int new_nr_bytes;
6773
6774 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6775 - memaddr);
6776 if (new_nr_bytes != nr_bytes)
6777 payload_length = remote_escape_output (myaddr, new_nr_bytes,
bc20a4af 6778 (gdb_byte *) p, &nr_bytes,
6765f3e5
DJ
6779 payload_size);
6780 }
6781
6782 p += payload_length;
a76d924d 6783 if (use_length && nr_bytes < todo)
c906108c 6784 {
802188a7 6785 /* Escape chars have filled up the buffer prematurely,
917317f4
JM
6786 and we have actually sent fewer bytes than planned.
6787 Fix-up the length field of the packet. Use the same
6788 number of characters as before. */
917317f4
JM
6789 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6790 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 6791 }
a76d924d
DJ
6792 }
6793 else
6794 {
917317f4
JM
6795 /* Normal mode: Send target system values byte by byte, in
6796 increasing byte addresses. Each byte is encoded as a two hex
6797 value. */
2644f393 6798 nr_bytes = bin2hex (myaddr, p, todo);
aa6c0017 6799 p += 2 * nr_bytes;
c906108c 6800 }
802188a7 6801
2e9f7625 6802 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 6803 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 6804
2e9f7625 6805 if (rs->buf[0] == 'E')
00d84524 6806 return TARGET_XFER_E_IO;
802188a7 6807
23860348
MS
6808 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6809 fewer bytes than we'd planned. */
9b409511
YQ
6810 *xfered_len = (ULONGEST) nr_bytes;
6811 return TARGET_XFER_OK;
c906108c
SS
6812}
6813
a76d924d
DJ
6814/* Write memory data directly to the remote machine.
6815 This does not inform the data cache; the data cache uses this.
6816 MEMADDR is the address in the remote memory space.
6817 MYADDR is the address of the buffer in our space.
6818 LEN is the number of bytes.
6819
9b409511
YQ
6820 Return the transferred status, error or OK (an
6821 'enum target_xfer_status' value). Save the number of bytes
6822 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 6823
9b409511
YQ
6824static enum target_xfer_status
6825remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
6826 ULONGEST *xfered_len)
a76d924d
DJ
6827{
6828 char *packet_format = 0;
6829
6830 /* Check whether the target supports binary download. */
6831 check_binary_download (memaddr);
6832
4082afcc 6833 switch (packet_support (PACKET_X))
a76d924d
DJ
6834 {
6835 case PACKET_ENABLE:
6836 packet_format = "X";
6837 break;
6838 case PACKET_DISABLE:
6839 packet_format = "M";
6840 break;
6841 case PACKET_SUPPORT_UNKNOWN:
6842 internal_error (__FILE__, __LINE__,
6843 _("remote_write_bytes: bad internal state"));
6844 default:
6845 internal_error (__FILE__, __LINE__, _("bad switch"));
6846 }
6847
6848 return remote_write_bytes_aux (packet_format,
9b409511
YQ
6849 memaddr, myaddr, len, xfered_len,
6850 packet_format[0], 1);
a76d924d
DJ
6851}
6852
9217e74e
YQ
6853/* Read memory data directly from the remote machine.
6854 This does not use the data cache; the data cache uses this.
6855 MEMADDR is the address in the remote memory space.
6856 MYADDR is the address of the buffer in our space.
6857 LEN is the number of bytes.
6858
6859 Return the transferred status, error or OK (an
6860 'enum target_xfer_status' value). Save the number of bytes
6861 transferred in *XFERED_LEN. */
6862
6863static enum target_xfer_status
6864remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len,
6865 ULONGEST *xfered_len)
6866{
6867 struct remote_state *rs = get_remote_state ();
6868 int max_buf_size; /* Max size of packet output buffer. */
6869 char *p;
6870 int todo;
6871 int i;
6872
6873 max_buf_size = get_memory_read_packet_size ();
6874 /* The packet buffer will be large enough for the payload;
6875 get_memory_packet_size ensures this. */
6876
6877 /* Number if bytes that will fit. */
6878 todo = min (len, max_buf_size / 2);
6879
6880 /* Construct "m"<memaddr>","<len>". */
6881 memaddr = remote_address_masked (memaddr);
6882 p = rs->buf;
6883 *p++ = 'm';
6884 p += hexnumstr (p, (ULONGEST) memaddr);
6885 *p++ = ',';
6886 p += hexnumstr (p, (ULONGEST) todo);
6887 *p = '\0';
6888 putpkt (rs->buf);
6889 getpkt (&rs->buf, &rs->buf_size, 0);
6890 if (rs->buf[0] == 'E'
6891 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6892 && rs->buf[3] == '\0')
6893 return TARGET_XFER_E_IO;
6894 /* Reply describes memory byte by byte, each byte encoded as two hex
6895 characters. */
6896 p = rs->buf;
6897 i = hex2bin (p, myaddr, todo);
6898 /* Return what we have. Let higher layers handle partial reads. */
6899 *xfered_len = (ULONGEST) i;
6900 return TARGET_XFER_OK;
6901}
6902
b55fbac4
YQ
6903/* Using the set of read-only target sections of remote, read live
6904 read-only memory.
8acf9577
YQ
6905
6906 For interface/parameters/return description see target.h,
6907 to_xfer_partial. */
6908
6909static enum target_xfer_status
b55fbac4
YQ
6910remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
6911 ULONGEST memaddr, ULONGEST len,
6912 ULONGEST *xfered_len)
8acf9577
YQ
6913{
6914 struct target_section *secp;
6915 struct target_section_table *table;
6916
6917 secp = target_section_by_addr (ops, memaddr);
6918 if (secp != NULL
6919 && (bfd_get_section_flags (secp->the_bfd_section->owner,
6920 secp->the_bfd_section)
6921 & SEC_READONLY))
6922 {
6923 struct target_section *p;
6924 ULONGEST memend = memaddr + len;
6925
6926 table = target_get_section_table (ops);
6927
6928 for (p = table->sections; p < table->sections_end; p++)
6929 {
6930 if (memaddr >= p->addr)
6931 {
6932 if (memend <= p->endaddr)
6933 {
6934 /* Entire transfer is within this section. */
b55fbac4
YQ
6935 return remote_read_bytes_1 (memaddr, readbuf, len,
6936 xfered_len);
8acf9577
YQ
6937 }
6938 else if (memaddr >= p->endaddr)
6939 {
6940 /* This section ends before the transfer starts. */
6941 continue;
6942 }
6943 else
6944 {
6945 /* This section overlaps the transfer. Just do half. */
6946 len = p->endaddr - memaddr;
b55fbac4
YQ
6947 return remote_read_bytes_1 (memaddr, readbuf, len,
6948 xfered_len);
8acf9577
YQ
6949 }
6950 }
6951 }
6952 }
6953
6954 return TARGET_XFER_EOF;
6955}
6956
9217e74e
YQ
6957/* Similar to remote_read_bytes_1, but it reads from the remote stub
6958 first if the requested memory is unavailable in traceframe.
6959 Otherwise, fall back to remote_read_bytes_1. */
c906108c 6960
9b409511 6961static enum target_xfer_status
8acf9577
YQ
6962remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
6963 gdb_byte *myaddr, ULONGEST len, ULONGEST *xfered_len)
c906108c 6964{
6b6aa828 6965 if (len == 0)
96c4f946 6966 return TARGET_XFER_EOF;
b2182ed2 6967
8acf9577
YQ
6968 if (get_traceframe_number () != -1)
6969 {
6970 VEC(mem_range_s) *available;
6971
6972 /* If we fail to get the set of available memory, then the
6973 target does not support querying traceframe info, and so we
6974 attempt reading from the traceframe anyway (assuming the
6975 target implements the old QTro packet then). */
6976 if (traceframe_available_memory (&available, memaddr, len))
6977 {
6978 struct cleanup *old_chain;
6979
6980 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
6981
6982 if (VEC_empty (mem_range_s, available)
6983 || VEC_index (mem_range_s, available, 0)->start != memaddr)
6984 {
6985 enum target_xfer_status res;
6986
6987 /* Don't read into the traceframe's available
6988 memory. */
6989 if (!VEC_empty (mem_range_s, available))
6990 {
6991 LONGEST oldlen = len;
6992
6993 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
6994 gdb_assert (len <= oldlen);
6995 }
6996
6997 do_cleanups (old_chain);
6998
6999 /* This goes through the topmost target again. */
b55fbac4 7000 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8acf9577
YQ
7001 len, xfered_len);
7002 if (res == TARGET_XFER_OK)
7003 return TARGET_XFER_OK;
7004 else
7005 {
7006 /* No use trying further, we know some memory starting
7007 at MEMADDR isn't available. */
7008 *xfered_len = len;
7009 return TARGET_XFER_UNAVAILABLE;
7010 }
7011 }
7012
7013 /* Don't try to read more than how much is available, in
7014 case the target implements the deprecated QTro packet to
7015 cater for older GDBs (the target's knowledge of read-only
7016 sections may be outdated by now). */
7017 len = VEC_index (mem_range_s, available, 0)->length;
7018
7019 do_cleanups (old_chain);
7020 }
7021 }
7022
9217e74e 7023 return remote_read_bytes_1 (memaddr, myaddr, len, xfered_len);
c906108c 7024}
74531fed 7025
c906108c 7026\f
c906108c 7027
a76d924d
DJ
7028/* Sends a packet with content determined by the printf format string
7029 FORMAT and the remaining arguments, then gets the reply. Returns
7030 whether the packet was a success, a failure, or unknown. */
7031
77b64a49
PA
7032static enum packet_result remote_send_printf (const char *format, ...)
7033 ATTRIBUTE_PRINTF (1, 2);
7034
2c0b251b 7035static enum packet_result
a76d924d
DJ
7036remote_send_printf (const char *format, ...)
7037{
7038 struct remote_state *rs = get_remote_state ();
7039 int max_size = get_remote_packet_size ();
a76d924d 7040 va_list ap;
a744cf53 7041
a76d924d
DJ
7042 va_start (ap, format);
7043
7044 rs->buf[0] = '\0';
7045 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 7046 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
7047
7048 if (putpkt (rs->buf) < 0)
7049 error (_("Communication problem with target."));
7050
7051 rs->buf[0] = '\0';
7052 getpkt (&rs->buf, &rs->buf_size, 0);
7053
7054 return packet_check_result (rs->buf);
7055}
7056
7057static void
7058restore_remote_timeout (void *p)
7059{
7060 int value = *(int *)p;
a744cf53 7061
a76d924d
DJ
7062 remote_timeout = value;
7063}
7064
7065/* Flash writing can take quite some time. We'll set
7066 effectively infinite timeout for flash operations.
7067 In future, we'll need to decide on a better approach. */
7068static const int remote_flash_timeout = 1000;
7069
7070static void
7071remote_flash_erase (struct target_ops *ops,
7072 ULONGEST address, LONGEST length)
7073{
f5656ead 7074 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
7075 int saved_remote_timeout = remote_timeout;
7076 enum packet_result ret;
a76d924d
DJ
7077 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7078 &saved_remote_timeout);
a744cf53 7079
a76d924d
DJ
7080 remote_timeout = remote_flash_timeout;
7081
7082 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 7083 phex (address, addr_size),
a76d924d
DJ
7084 phex (length, 4));
7085 switch (ret)
7086 {
7087 case PACKET_UNKNOWN:
7088 error (_("Remote target does not support flash erase"));
7089 case PACKET_ERROR:
7090 error (_("Error erasing flash with vFlashErase packet"));
7091 default:
7092 break;
7093 }
7094
7095 do_cleanups (back_to);
7096}
7097
9b409511
YQ
7098static enum target_xfer_status
7099remote_flash_write (struct target_ops *ops, ULONGEST address,
7100 ULONGEST length, ULONGEST *xfered_len,
7101 const gdb_byte *data)
a76d924d
DJ
7102{
7103 int saved_remote_timeout = remote_timeout;
9b409511 7104 enum target_xfer_status ret;
a76d924d 7105 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 7106 &saved_remote_timeout);
a76d924d
DJ
7107
7108 remote_timeout = remote_flash_timeout;
9b409511
YQ
7109 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length,
7110 xfered_len,'X', 0);
a76d924d
DJ
7111 do_cleanups (back_to);
7112
7113 return ret;
7114}
7115
7116static void
7117remote_flash_done (struct target_ops *ops)
7118{
7119 int saved_remote_timeout = remote_timeout;
7120 int ret;
7121 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7122 &saved_remote_timeout);
7123
7124 remote_timeout = remote_flash_timeout;
7125 ret = remote_send_printf ("vFlashDone");
7126 do_cleanups (back_to);
7127
7128 switch (ret)
7129 {
7130 case PACKET_UNKNOWN:
7131 error (_("Remote target does not support vFlashDone"));
7132 case PACKET_ERROR:
7133 error (_("Error finishing flash operation"));
7134 default:
7135 break;
7136 }
7137}
7138
c906108c 7139static void
fba45db2 7140remote_files_info (struct target_ops *ignore)
c906108c
SS
7141{
7142 puts_filtered ("Debugging a target over a serial line.\n");
7143}
7144\f
7145/* Stuff for dealing with the packets which are part of this protocol.
7146 See comment at top of file for details. */
7147
1927e618
PA
7148/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7149 error to higher layers. Called when a serial error is detected.
7150 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
7151 the system error message for errno at function entry and final dot
7152 for output compatibility with throw_perror_with_name. */
1927e618
PA
7153
7154static void
7155unpush_and_perror (const char *string)
7156{
d6cb50a2 7157 int saved_errno = errno;
1927e618
PA
7158
7159 remote_unpush_target ();
d6cb50a2
JK
7160 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7161 safe_strerror (saved_errno));
1927e618
PA
7162}
7163
0876f84a 7164/* Read a single character from the remote end. */
c906108c
SS
7165
7166static int
fba45db2 7167readchar (int timeout)
c906108c
SS
7168{
7169 int ch;
5d93a237 7170 struct remote_state *rs = get_remote_state ();
c906108c 7171
5d93a237 7172 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 7173
2acceee2 7174 if (ch >= 0)
0876f84a 7175 return ch;
2acceee2
JM
7176
7177 switch ((enum serial_rc) ch)
c906108c
SS
7178 {
7179 case SERIAL_EOF:
78a095c3 7180 remote_unpush_target ();
598d3636 7181 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 7182 /* no return */
c906108c 7183 case SERIAL_ERROR:
1927e618
PA
7184 unpush_and_perror (_("Remote communication error. "
7185 "Target disconnected."));
2acceee2 7186 /* no return */
c906108c 7187 case SERIAL_TIMEOUT:
2acceee2 7188 break;
c906108c 7189 }
2acceee2 7190 return ch;
c906108c
SS
7191}
7192
c33e31fd
PA
7193/* Wrapper for serial_write that closes the target and throws if
7194 writing fails. */
7195
7196static void
7197remote_serial_write (const char *str, int len)
7198{
5d93a237
TT
7199 struct remote_state *rs = get_remote_state ();
7200
7201 if (serial_write (rs->remote_desc, str, len))
c33e31fd 7202 {
1927e618
PA
7203 unpush_and_perror (_("Remote communication error. "
7204 "Target disconnected."));
c33e31fd
PA
7205 }
7206}
7207
6d820c5c
DJ
7208/* Send the command in *BUF to the remote machine, and read the reply
7209 into *BUF. Report an error if we get an error reply. Resize
7210 *BUF using xrealloc if necessary to hold the result, and update
7211 *SIZEOF_BUF. */
c906108c
SS
7212
7213static void
6d820c5c
DJ
7214remote_send (char **buf,
7215 long *sizeof_buf)
c906108c 7216{
6d820c5c 7217 putpkt (*buf);
c2d11a7d 7218 getpkt (buf, sizeof_buf, 0);
c906108c 7219
6d820c5c
DJ
7220 if ((*buf)[0] == 'E')
7221 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
7222}
7223
6e5abd65
PA
7224/* Return a pointer to an xmalloc'ed string representing an escaped
7225 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7226 etc. The caller is responsible for releasing the returned
7227 memory. */
7228
7229static char *
7230escape_buffer (const char *buf, int n)
7231{
7232 struct cleanup *old_chain;
7233 struct ui_file *stb;
7234 char *str;
6e5abd65
PA
7235
7236 stb = mem_fileopen ();
7237 old_chain = make_cleanup_ui_file_delete (stb);
7238
6ef284bd 7239 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 7240 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
7241 do_cleanups (old_chain);
7242 return str;
7243}
7244
c906108c
SS
7245/* Display a null-terminated packet on stdout, for debugging, using C
7246 string notation. */
7247
7248static void
baa336ce 7249print_packet (const char *buf)
c906108c
SS
7250{
7251 puts_filtered ("\"");
43e526b9 7252 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
7253 puts_filtered ("\"");
7254}
7255
7256int
baa336ce 7257putpkt (const char *buf)
c906108c
SS
7258{
7259 return putpkt_binary (buf, strlen (buf));
7260}
7261
7262/* Send a packet to the remote machine, with error checking. The data
23860348 7263 of the packet is in BUF. The string in BUF can be at most
ea9c271d 7264 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
7265 and for a possible /0 if we are debugging (remote_debug) and want
7266 to print the sent packet as a string. */
c906108c
SS
7267
7268static int
baa336ce 7269putpkt_binary (const char *buf, int cnt)
c906108c 7270{
2d717e4f 7271 struct remote_state *rs = get_remote_state ();
c906108c
SS
7272 int i;
7273 unsigned char csum = 0;
11cf8741 7274 char *buf2 = alloca (cnt + 6);
085dd6e6 7275
c906108c
SS
7276 int ch;
7277 int tcount = 0;
7278 char *p;
dd61ec5c 7279 char *message;
c906108c 7280
e24a49d8
PA
7281 /* Catch cases like trying to read memory or listing threads while
7282 we're waiting for a stop reply. The remote server wouldn't be
7283 ready to handle this request, so we'd hang and timeout. We don't
7284 have to worry about this in synchronous mode, because in that
7285 case it's not possible to issue a command while the target is
74531fed
PA
7286 running. This is not a problem in non-stop mode, because in that
7287 case, the stub is always ready to process serial input. */
d9d41e78 7288 if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
9597b22a
DE
7289 {
7290 error (_("Cannot execute this command while the target is running.\n"
7291 "Use the \"interrupt\" command to stop the target\n"
7292 "and then try again."));
7293 }
e24a49d8 7294
2d717e4f
DJ
7295 /* We're sending out a new packet. Make sure we don't look at a
7296 stale cached response. */
7297 rs->cached_wait_status = 0;
7298
c906108c
SS
7299 /* Copy the packet into buffer BUF2, encapsulating it
7300 and giving it a checksum. */
7301
c906108c
SS
7302 p = buf2;
7303 *p++ = '$';
7304
7305 for (i = 0; i < cnt; i++)
7306 {
7307 csum += buf[i];
7308 *p++ = buf[i];
7309 }
7310 *p++ = '#';
7311 *p++ = tohex ((csum >> 4) & 0xf);
7312 *p++ = tohex (csum & 0xf);
7313
7314 /* Send it over and over until we get a positive ack. */
7315
7316 while (1)
7317 {
7318 int started_error_output = 0;
7319
7320 if (remote_debug)
7321 {
6e5abd65
PA
7322 struct cleanup *old_chain;
7323 char *str;
7324
c906108c 7325 *p = '\0';
6e5abd65
PA
7326 str = escape_buffer (buf2, p - buf2);
7327 old_chain = make_cleanup (xfree, str);
7328 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 7329 gdb_flush (gdb_stdlog);
6e5abd65 7330 do_cleanups (old_chain);
c906108c 7331 }
c33e31fd 7332 remote_serial_write (buf2, p - buf2);
c906108c 7333
a6f3e723
SL
7334 /* If this is a no acks version of the remote protocol, send the
7335 packet and move on. */
7336 if (rs->noack_mode)
7337 break;
7338
74531fed
PA
7339 /* Read until either a timeout occurs (-2) or '+' is read.
7340 Handle any notification that arrives in the mean time. */
c906108c
SS
7341 while (1)
7342 {
7343 ch = readchar (remote_timeout);
7344
c5aa993b 7345 if (remote_debug)
c906108c
SS
7346 {
7347 switch (ch)
7348 {
7349 case '+':
1216fa2c 7350 case '-':
c906108c
SS
7351 case SERIAL_TIMEOUT:
7352 case '$':
74531fed 7353 case '%':
c906108c
SS
7354 if (started_error_output)
7355 {
7356 putchar_unfiltered ('\n');
7357 started_error_output = 0;
7358 }
7359 }
7360 }
7361
7362 switch (ch)
7363 {
7364 case '+':
7365 if (remote_debug)
0f71a2f6 7366 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 7367 return 1;
1216fa2c
AC
7368 case '-':
7369 if (remote_debug)
7370 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 7371 /* FALLTHROUGH */
c906108c 7372 case SERIAL_TIMEOUT:
c5aa993b 7373 tcount++;
c906108c
SS
7374 if (tcount > 3)
7375 return 0;
23860348 7376 break; /* Retransmit buffer. */
c906108c
SS
7377 case '$':
7378 {
40e3f985 7379 if (remote_debug)
2bc416ba 7380 fprintf_unfiltered (gdb_stdlog,
23860348 7381 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
7382 /* It's probably an old response sent because an ACK
7383 was lost. Gobble up the packet and ack it so it
7384 doesn't get retransmitted when we resend this
7385 packet. */
6d820c5c 7386 skip_frame ();
c33e31fd 7387 remote_serial_write ("+", 1);
23860348 7388 continue; /* Now, go look for +. */
c906108c 7389 }
74531fed
PA
7390
7391 case '%':
7392 {
7393 int val;
7394
7395 /* If we got a notification, handle it, and go back to looking
7396 for an ack. */
7397 /* We've found the start of a notification. Now
7398 collect the data. */
7399 val = read_frame (&rs->buf, &rs->buf_size);
7400 if (val >= 0)
7401 {
7402 if (remote_debug)
7403 {
6e5abd65
PA
7404 struct cleanup *old_chain;
7405 char *str;
7406
7407 str = escape_buffer (rs->buf, val);
7408 old_chain = make_cleanup (xfree, str);
7409 fprintf_unfiltered (gdb_stdlog,
7410 " Notification received: %s\n",
7411 str);
7412 do_cleanups (old_chain);
74531fed 7413 }
5965e028 7414 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
7415 /* We're in sync now, rewait for the ack. */
7416 tcount = 0;
7417 }
7418 else
7419 {
7420 if (remote_debug)
7421 {
7422 if (!started_error_output)
7423 {
7424 started_error_output = 1;
7425 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7426 }
7427 fputc_unfiltered (ch & 0177, gdb_stdlog);
7428 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7429 }
7430 }
7431 continue;
7432 }
7433 /* fall-through */
c906108c
SS
7434 default:
7435 if (remote_debug)
7436 {
7437 if (!started_error_output)
7438 {
7439 started_error_output = 1;
0f71a2f6 7440 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 7441 }
0f71a2f6 7442 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
7443 }
7444 continue;
7445 }
23860348 7446 break; /* Here to retransmit. */
c906108c
SS
7447 }
7448
7449#if 0
7450 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
7451 able to get out next time we call QUIT, without anything as
7452 violent as interrupt_query. If we want to provide a way out of
7453 here without getting to the next QUIT, it should be based on
7454 hitting ^C twice as in remote_wait. */
c906108c
SS
7455 if (quit_flag)
7456 {
7457 quit_flag = 0;
7458 interrupt_query ();
7459 }
7460#endif
7461 }
a6f3e723 7462 return 0;
c906108c
SS
7463}
7464
6d820c5c
DJ
7465/* Come here after finding the start of a frame when we expected an
7466 ack. Do our best to discard the rest of this packet. */
7467
7468static void
7469skip_frame (void)
7470{
7471 int c;
7472
7473 while (1)
7474 {
7475 c = readchar (remote_timeout);
7476 switch (c)
7477 {
7478 case SERIAL_TIMEOUT:
7479 /* Nothing we can do. */
7480 return;
7481 case '#':
7482 /* Discard the two bytes of checksum and stop. */
7483 c = readchar (remote_timeout);
7484 if (c >= 0)
7485 c = readchar (remote_timeout);
7486
7487 return;
7488 case '*': /* Run length encoding. */
7489 /* Discard the repeat count. */
7490 c = readchar (remote_timeout);
7491 if (c < 0)
7492 return;
7493 break;
7494 default:
7495 /* A regular character. */
7496 break;
7497 }
7498 }
7499}
7500
c906108c 7501/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
7502 into *BUF, verifying the checksum, length, and handling run-length
7503 compression. NUL terminate the buffer. If there is not enough room,
7504 expand *BUF using xrealloc.
c906108c 7505
c2d11a7d
JM
7506 Returns -1 on error, number of characters in buffer (ignoring the
7507 trailing NULL) on success. (could be extended to return one of the
23860348 7508 SERIAL status indications). */
c2d11a7d
JM
7509
7510static long
6d820c5c
DJ
7511read_frame (char **buf_p,
7512 long *sizeof_buf)
c906108c
SS
7513{
7514 unsigned char csum;
c2d11a7d 7515 long bc;
c906108c 7516 int c;
6d820c5c 7517 char *buf = *buf_p;
a6f3e723 7518 struct remote_state *rs = get_remote_state ();
c906108c
SS
7519
7520 csum = 0;
c2d11a7d 7521 bc = 0;
c906108c
SS
7522
7523 while (1)
7524 {
7525 c = readchar (remote_timeout);
c906108c
SS
7526 switch (c)
7527 {
7528 case SERIAL_TIMEOUT:
7529 if (remote_debug)
0f71a2f6 7530 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 7531 return -1;
c906108c
SS
7532 case '$':
7533 if (remote_debug)
0f71a2f6
JM
7534 fputs_filtered ("Saw new packet start in middle of old one\n",
7535 gdb_stdlog);
23860348 7536 return -1; /* Start a new packet, count retries. */
c906108c
SS
7537 case '#':
7538 {
7539 unsigned char pktcsum;
e1b09194
AC
7540 int check_0 = 0;
7541 int check_1 = 0;
c906108c 7542
c2d11a7d 7543 buf[bc] = '\0';
c906108c 7544
e1b09194
AC
7545 check_0 = readchar (remote_timeout);
7546 if (check_0 >= 0)
7547 check_1 = readchar (remote_timeout);
802188a7 7548
e1b09194
AC
7549 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7550 {
7551 if (remote_debug)
2bc416ba 7552 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 7553 gdb_stdlog);
e1b09194
AC
7554 return -1;
7555 }
7556 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
7557 {
7558 if (remote_debug)
2bc416ba 7559 fputs_filtered ("Communication error in checksum\n",
23860348 7560 gdb_stdlog);
40e3f985
FN
7561 return -1;
7562 }
c906108c 7563
a6f3e723
SL
7564 /* Don't recompute the checksum; with no ack packets we
7565 don't have any way to indicate a packet retransmission
7566 is necessary. */
7567 if (rs->noack_mode)
7568 return bc;
7569
e1b09194 7570 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 7571 if (csum == pktcsum)
c2d11a7d 7572 return bc;
c906108c 7573
c5aa993b 7574 if (remote_debug)
c906108c 7575 {
6e5abd65
PA
7576 struct cleanup *old_chain;
7577 char *str;
7578
7579 str = escape_buffer (buf, bc);
7580 old_chain = make_cleanup (xfree, str);
7581 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7582 "Bad checksum, sentsum=0x%x, "
7583 "csum=0x%x, buf=%s\n",
6e5abd65
PA
7584 pktcsum, csum, str);
7585 do_cleanups (old_chain);
c906108c 7586 }
c2d11a7d 7587 /* Number of characters in buffer ignoring trailing
23860348 7588 NULL. */
c2d11a7d 7589 return -1;
c906108c 7590 }
23860348 7591 case '*': /* Run length encoding. */
c2c6d25f
JM
7592 {
7593 int repeat;
c906108c 7594
a744cf53 7595 csum += c;
b4501125
AC
7596 c = readchar (remote_timeout);
7597 csum += c;
23860348 7598 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 7599
23860348 7600 /* The character before ``*'' is repeated. */
c2d11a7d 7601
6d820c5c 7602 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 7603 {
6d820c5c
DJ
7604 if (bc + repeat - 1 >= *sizeof_buf - 1)
7605 {
7606 /* Make some more room in the buffer. */
7607 *sizeof_buf += repeat;
7608 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7609 buf = *buf_p;
7610 }
7611
c2d11a7d
JM
7612 memset (&buf[bc], buf[bc - 1], repeat);
7613 bc += repeat;
c2c6d25f
JM
7614 continue;
7615 }
7616
c2d11a7d 7617 buf[bc] = '\0';
6d820c5c 7618 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 7619 return -1;
c2c6d25f 7620 }
c906108c 7621 default:
6d820c5c 7622 if (bc >= *sizeof_buf - 1)
c906108c 7623 {
6d820c5c
DJ
7624 /* Make some more room in the buffer. */
7625 *sizeof_buf *= 2;
7626 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7627 buf = *buf_p;
c906108c
SS
7628 }
7629
6d820c5c
DJ
7630 buf[bc++] = c;
7631 csum += c;
7632 continue;
c906108c
SS
7633 }
7634 }
7635}
7636
7637/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
7638 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7639 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7640 rather than timing out; this is used (in synchronous mode) to wait
7641 for a target that is is executing user code to stop. */
d9fcf2fb
JM
7642/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7643 don't have to change all the calls to getpkt to deal with the
7644 return value, because at the moment I don't know what the right
23860348 7645 thing to do it for those. */
c906108c 7646void
6d820c5c
DJ
7647getpkt (char **buf,
7648 long *sizeof_buf,
c2d11a7d 7649 int forever)
d9fcf2fb
JM
7650{
7651 int timed_out;
7652
7653 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7654}
7655
7656
7657/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
7658 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7659 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7660 rather than timing out; this is used (in synchronous mode) to wait
7661 for a target that is is executing user code to stop. If FOREVER ==
7662 0, this function is allowed to time out gracefully and return an
74531fed
PA
7663 indication of this to the caller. Otherwise return the number of
7664 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
7665 enough reason to return to the caller. *IS_NOTIF is an output
7666 boolean that indicates whether *BUF holds a notification or not
7667 (a regular packet). */
74531fed 7668
3172dc30 7669static int
74531fed 7670getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 7671 int expecting_notif, int *is_notif)
c906108c 7672{
2d717e4f 7673 struct remote_state *rs = get_remote_state ();
c906108c
SS
7674 int c;
7675 int tries;
7676 int timeout;
df4b58fe 7677 int val = -1;
c906108c 7678
2d717e4f
DJ
7679 /* We're reading a new response. Make sure we don't look at a
7680 previously cached response. */
7681 rs->cached_wait_status = 0;
7682
6d820c5c 7683 strcpy (*buf, "timeout");
c906108c
SS
7684
7685 if (forever)
74531fed
PA
7686 timeout = watchdog > 0 ? watchdog : -1;
7687 else if (expecting_notif)
7688 timeout = 0; /* There should already be a char in the buffer. If
7689 not, bail out. */
c906108c
SS
7690 else
7691 timeout = remote_timeout;
7692
7693#define MAX_TRIES 3
7694
74531fed
PA
7695 /* Process any number of notifications, and then return when
7696 we get a packet. */
7697 for (;;)
c906108c 7698 {
d9c43928 7699 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
7700 times. */
7701 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 7702 {
74531fed
PA
7703 /* This can loop forever if the remote side sends us
7704 characters continuously, but if it pauses, we'll get
7705 SERIAL_TIMEOUT from readchar because of timeout. Then
7706 we'll count that as a retry.
7707
7708 Note that even when forever is set, we will only wait
7709 forever prior to the start of a packet. After that, we
7710 expect characters to arrive at a brisk pace. They should
7711 show up within remote_timeout intervals. */
7712 do
7713 c = readchar (timeout);
7714 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
7715
7716 if (c == SERIAL_TIMEOUT)
7717 {
74531fed
PA
7718 if (expecting_notif)
7719 return -1; /* Don't complain, it's normal to not get
7720 anything in this case. */
7721
23860348 7722 if (forever) /* Watchdog went off? Kill the target. */
c906108c 7723 {
2acceee2 7724 QUIT;
78a095c3 7725 remote_unpush_target ();
598d3636
JK
7726 throw_error (TARGET_CLOSE_ERROR,
7727 _("Watchdog timeout has expired. "
7728 "Target detached."));
c906108c 7729 }
c906108c 7730 if (remote_debug)
0f71a2f6 7731 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 7732 }
74531fed
PA
7733 else
7734 {
7735 /* We've found the start of a packet or notification.
7736 Now collect the data. */
7737 val = read_frame (buf, sizeof_buf);
7738 if (val >= 0)
7739 break;
7740 }
7741
c33e31fd 7742 remote_serial_write ("-", 1);
c906108c 7743 }
c906108c 7744
74531fed
PA
7745 if (tries > MAX_TRIES)
7746 {
7747 /* We have tried hard enough, and just can't receive the
7748 packet/notification. Give up. */
7749 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 7750
74531fed
PA
7751 /* Skip the ack char if we're in no-ack mode. */
7752 if (!rs->noack_mode)
c33e31fd 7753 remote_serial_write ("+", 1);
74531fed
PA
7754 return -1;
7755 }
c906108c 7756
74531fed
PA
7757 /* If we got an ordinary packet, return that to our caller. */
7758 if (c == '$')
c906108c
SS
7759 {
7760 if (remote_debug)
43e526b9 7761 {
6e5abd65
PA
7762 struct cleanup *old_chain;
7763 char *str;
7764
7765 str = escape_buffer (*buf, val);
7766 old_chain = make_cleanup (xfree, str);
7767 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7768 do_cleanups (old_chain);
43e526b9 7769 }
a6f3e723
SL
7770
7771 /* Skip the ack char if we're in no-ack mode. */
7772 if (!rs->noack_mode)
c33e31fd 7773 remote_serial_write ("+", 1);
fee9eda9
YQ
7774 if (is_notif != NULL)
7775 *is_notif = 0;
0876f84a 7776 return val;
c906108c
SS
7777 }
7778
74531fed
PA
7779 /* If we got a notification, handle it, and go back to looking
7780 for a packet. */
7781 else
7782 {
7783 gdb_assert (c == '%');
7784
7785 if (remote_debug)
7786 {
6e5abd65
PA
7787 struct cleanup *old_chain;
7788 char *str;
7789
7790 str = escape_buffer (*buf, val);
7791 old_chain = make_cleanup (xfree, str);
7792 fprintf_unfiltered (gdb_stdlog,
7793 " Notification received: %s\n",
7794 str);
7795 do_cleanups (old_chain);
74531fed 7796 }
fee9eda9
YQ
7797 if (is_notif != NULL)
7798 *is_notif = 1;
c906108c 7799
5965e028 7800 handle_notification (rs->notif_state, *buf);
c906108c 7801
74531fed 7802 /* Notifications require no acknowledgement. */
a6f3e723 7803
74531fed 7804 if (expecting_notif)
fee9eda9 7805 return val;
74531fed
PA
7806 }
7807 }
7808}
7809
7810static int
7811getpkt_sane (char **buf, long *sizeof_buf, int forever)
7812{
fee9eda9 7813 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
7814}
7815
7816static int
fee9eda9
YQ
7817getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
7818 int *is_notif)
74531fed 7819{
fee9eda9
YQ
7820 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
7821 is_notif);
c906108c 7822}
74531fed 7823
c906108c
SS
7824\f
7825static void
7d85a9c0 7826remote_kill (struct target_ops *ops)
43ff13b4 7827{
0fdf84ca
PA
7828
7829 /* Catch errors so the user can quit from gdb even when we
23860348 7830 aren't on speaking terms with the remote system. */
492d29ea 7831 TRY
0fdf84ca
PA
7832 {
7833 putpkt ("k");
7834 }
492d29ea 7835 CATCH (ex, RETURN_MASK_ERROR)
0fdf84ca
PA
7836 {
7837 if (ex.error == TARGET_CLOSE_ERROR)
7838 {
7839 /* If we got an (EOF) error that caused the target
7840 to go away, then we're done, that's what we wanted.
7841 "k" is susceptible to cause a premature EOF, given
7842 that the remote server isn't actually required to
7843 reply to "k", and it can happen that it doesn't
7844 even get to reply ACK to the "k". */
7845 return;
7846 }
7847
7848 /* Otherwise, something went wrong. We didn't actually kill
7849 the target. Just propagate the exception, and let the
7850 user or higher layers decide what to do. */
7851 throw_exception (ex);
7852 }
492d29ea 7853 END_CATCH
43ff13b4 7854
0fdf84ca
PA
7855 /* We've killed the remote end, we get to mourn it. Since this is
7856 target remote, single-process, mourning the inferior also
7857 unpushes remote_ops. */
43ff13b4
JM
7858 target_mourn_inferior ();
7859}
7860
82f73884
PA
7861static int
7862remote_vkill (int pid, struct remote_state *rs)
7863{
4082afcc 7864 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
7865 return -1;
7866
7867 /* Tell the remote target to detach. */
bba74b36 7868 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
7869 putpkt (rs->buf);
7870 getpkt (&rs->buf, &rs->buf_size, 0);
7871
4082afcc
PA
7872 switch (packet_ok (rs->buf,
7873 &remote_protocol_packets[PACKET_vKill]))
7874 {
7875 case PACKET_OK:
7876 return 0;
7877 case PACKET_ERROR:
7878 return 1;
7879 case PACKET_UNKNOWN:
7880 return -1;
7881 default:
7882 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7883 }
82f73884
PA
7884}
7885
7886static void
7d85a9c0 7887extended_remote_kill (struct target_ops *ops)
82f73884
PA
7888{
7889 int res;
7890 int pid = ptid_get_pid (inferior_ptid);
7891 struct remote_state *rs = get_remote_state ();
7892
7893 res = remote_vkill (pid, rs);
901f9912 7894 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
82f73884
PA
7895 {
7896 /* Don't try 'k' on a multi-process aware stub -- it has no way
7897 to specify the pid. */
7898
7899 putpkt ("k");
7900#if 0
7901 getpkt (&rs->buf, &rs->buf_size, 0);
7902 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7903 res = 1;
7904#else
7905 /* Don't wait for it to die. I'm not really sure it matters whether
7906 we do or not. For the existing stubs, kill is a noop. */
7907 res = 0;
7908#endif
7909 }
7910
7911 if (res != 0)
7912 error (_("Can't kill process"));
7913
82f73884
PA
7914 target_mourn_inferior ();
7915}
7916
c906108c 7917static void
20f796c9 7918remote_mourn (struct target_ops *target)
c906108c
SS
7919{
7920 unpush_target (target);
ce5ce7ed 7921
8a2492ee
PA
7922 /* remote_close takes care of doing most of the clean up. */
7923 generic_mourn_inferior ();
c906108c
SS
7924}
7925
2d717e4f 7926static void
20f796c9 7927extended_remote_mourn (struct target_ops *target)
2d717e4f
DJ
7928{
7929 struct remote_state *rs = get_remote_state ();
c906108c 7930
e24a49d8
PA
7931 /* In case we got here due to an error, but we're going to stay
7932 connected. */
7933 rs->waiting_for_stop_reply = 0;
7934
dc1981d7
PA
7935 /* If the current general thread belonged to the process we just
7936 detached from or has exited, the remote side current general
7937 thread becomes undefined. Considering a case like this:
7938
7939 - We just got here due to a detach.
7940 - The process that we're detaching from happens to immediately
7941 report a global breakpoint being hit in non-stop mode, in the
7942 same thread we had selected before.
7943 - GDB attaches to this process again.
7944 - This event happens to be the next event we handle.
7945
7946 GDB would consider that the current general thread didn't need to
7947 be set on the stub side (with Hg), since for all it knew,
7948 GENERAL_THREAD hadn't changed.
7949
7950 Notice that although in all-stop mode, the remote server always
7951 sets the current thread to the thread reporting the stop event,
7952 that doesn't happen in non-stop mode; in non-stop, the stub *must
7953 not* change the current thread when reporting a breakpoint hit,
7954 due to the decoupling of event reporting and event handling.
7955
7956 To keep things simple, we always invalidate our notion of the
7957 current thread. */
47f8a51d 7958 record_currthread (rs, minus_one_ptid);
dc1981d7 7959
2d717e4f
DJ
7960 /* Unlike "target remote", we do not want to unpush the target; then
7961 the next time the user says "run", we won't be connected. */
7962
48aa3c27
PA
7963 /* Call common code to mark the inferior as not running. */
7964 generic_mourn_inferior ();
7965
d729566a 7966 if (!have_inferiors ())
2d717e4f 7967 {
82f73884
PA
7968 if (!remote_multi_process_p (rs))
7969 {
7970 /* Check whether the target is running now - some remote stubs
7971 automatically restart after kill. */
7972 putpkt ("?");
7973 getpkt (&rs->buf, &rs->buf_size, 0);
7974
7975 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7976 {
3e43a32a
MS
7977 /* Assume that the target has been restarted. Set
7978 inferior_ptid so that bits of core GDB realizes
7979 there's something here, e.g., so that the user can
7980 say "kill" again. */
82f73884
PA
7981 inferior_ptid = magic_null_ptid;
7982 }
82f73884 7983 }
2d717e4f
DJ
7984 }
7985}
c906108c 7986
03583c20 7987static int
2bfc0540 7988extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 7989{
4082afcc 7990 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
7991}
7992
7993static void
7994extended_remote_disable_randomization (int val)
7995{
7996 struct remote_state *rs = get_remote_state ();
7997 char *reply;
7998
bba74b36
YQ
7999 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8000 val);
03583c20
UW
8001 putpkt (rs->buf);
8002 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8003 if (*reply == '\0')
8004 error (_("Target does not support QDisableRandomization."));
8005 if (strcmp (reply, "OK") != 0)
8006 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8007}
8008
2d717e4f
DJ
8009static int
8010extended_remote_run (char *args)
8011{
8012 struct remote_state *rs = get_remote_state ();
2d717e4f 8013 int len;
c906108c 8014
2d717e4f
DJ
8015 /* If the user has disabled vRun support, or we have detected that
8016 support is not available, do not try it. */
4082afcc 8017 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 8018 return -1;
424163ea 8019
2d717e4f
DJ
8020 strcpy (rs->buf, "vRun;");
8021 len = strlen (rs->buf);
c906108c 8022
2d717e4f
DJ
8023 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8024 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
8025 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8026 strlen (remote_exec_file));
2d717e4f 8027
d1a41061 8028 gdb_assert (args != NULL);
2d717e4f
DJ
8029 if (*args)
8030 {
8031 struct cleanup *back_to;
8032 int i;
8033 char **argv;
8034
d1a41061 8035 argv = gdb_buildargv (args);
6e366df1 8036 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
8037 for (i = 0; argv[i] != NULL; i++)
8038 {
8039 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8040 error (_("Argument list too long for run packet"));
8041 rs->buf[len++] = ';';
9f1b45b0
TT
8042 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8043 strlen (argv[i]));
2d717e4f
DJ
8044 }
8045 do_cleanups (back_to);
8046 }
8047
8048 rs->buf[len++] = '\0';
8049
8050 putpkt (rs->buf);
8051 getpkt (&rs->buf, &rs->buf_size, 0);
8052
4082afcc 8053 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 8054 {
4082afcc 8055 case PACKET_OK:
3405876a 8056 /* We have a wait response. All is well. */
2d717e4f 8057 return 0;
4082afcc
PA
8058 case PACKET_UNKNOWN:
8059 return -1;
8060 case PACKET_ERROR:
2d717e4f
DJ
8061 if (remote_exec_file[0] == '\0')
8062 error (_("Running the default executable on the remote target failed; "
8063 "try \"set remote exec-file\"?"));
8064 else
8065 error (_("Running \"%s\" on the remote target failed"),
8066 remote_exec_file);
4082afcc
PA
8067 default:
8068 gdb_assert_not_reached (_("bad switch"));
2d717e4f 8069 }
c906108c
SS
8070}
8071
2d717e4f
DJ
8072/* In the extended protocol we want to be able to do things like
8073 "run" and have them basically work as expected. So we need
8074 a special create_inferior function. We support changing the
8075 executable file and the command line arguments, but not the
8076 environment. */
8077
43ff13b4 8078static void
77a19445
TT
8079extended_remote_create_inferior (struct target_ops *ops,
8080 char *exec_file, char *args,
8081 char **env, int from_tty)
43ff13b4 8082{
3405876a
PA
8083 int run_worked;
8084 char *stop_reply;
8085 struct remote_state *rs = get_remote_state ();
8086
43ff13b4 8087 /* If running asynchronously, register the target file descriptor
23860348 8088 with the event loop. */
75c99385 8089 if (target_can_async_p ())
6a3753b3 8090 target_async (1);
43ff13b4 8091
03583c20 8092 /* Disable address space randomization if requested (and supported). */
2bfc0540 8093 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
8094 extended_remote_disable_randomization (disable_randomization);
8095
43ff13b4 8096 /* Now restart the remote server. */
3405876a
PA
8097 run_worked = extended_remote_run (args) != -1;
8098 if (!run_worked)
2d717e4f
DJ
8099 {
8100 /* vRun was not supported. Fail if we need it to do what the
8101 user requested. */
8102 if (remote_exec_file[0])
8103 error (_("Remote target does not support \"set remote exec-file\""));
8104 if (args[0])
8105 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 8106
2d717e4f
DJ
8107 /* Fall back to "R". */
8108 extended_remote_restart ();
8109 }
424163ea 8110
6c95b8df
PA
8111 if (!have_inferiors ())
8112 {
8113 /* Clean up from the last time we ran, before we mark the target
8114 running again. This will mark breakpoints uninserted, and
8115 get_offsets may insert breakpoints. */
8116 init_thread_list ();
8117 init_wait_for_inferior ();
8118 }
45280a52 8119
3405876a
PA
8120 /* vRun's success return is a stop reply. */
8121 stop_reply = run_worked ? rs->buf : NULL;
8122 add_current_inferior_and_thread (stop_reply);
c0a2216e 8123
2d717e4f
DJ
8124 /* Get updated offsets, if the stub uses qOffsets. */
8125 get_offsets ();
2d717e4f 8126}
c906108c 8127\f
c5aa993b 8128
b775012e
LM
8129/* Given a location's target info BP_TGT and the packet buffer BUF, output
8130 the list of conditions (in agent expression bytecode format), if any, the
8131 target needs to evaluate. The output is placed into the packet buffer
bba74b36 8132 started from BUF and ended at BUF_END. */
b775012e
LM
8133
8134static int
8135remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
8136 struct bp_target_info *bp_tgt, char *buf,
8137 char *buf_end)
b775012e
LM
8138{
8139 struct agent_expr *aexpr = NULL;
8140 int i, ix;
8141 char *pkt;
8142 char *buf_start = buf;
8143
8144 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8145 return 0;
8146
8147 buf += strlen (buf);
bba74b36 8148 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
8149 buf++;
8150
8151 /* Send conditions to the target and free the vector. */
8152 for (ix = 0;
8153 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8154 ix++)
8155 {
bba74b36 8156 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
8157 buf += strlen (buf);
8158 for (i = 0; i < aexpr->len; ++i)
8159 buf = pack_hex_byte (buf, aexpr->buf[i]);
8160 *buf = '\0';
8161 }
b775012e
LM
8162 return 0;
8163}
8164
d3ce09f5
SS
8165static void
8166remote_add_target_side_commands (struct gdbarch *gdbarch,
8167 struct bp_target_info *bp_tgt, char *buf)
8168{
8169 struct agent_expr *aexpr = NULL;
8170 int i, ix;
8171
8172 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8173 return;
8174
8175 buf += strlen (buf);
8176
8177 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8178 buf += strlen (buf);
8179
8180 /* Concatenate all the agent expressions that are commands into the
8181 cmds parameter. */
8182 for (ix = 0;
8183 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8184 ix++)
8185 {
8186 sprintf (buf, "X%x,", aexpr->len);
8187 buf += strlen (buf);
8188 for (i = 0; i < aexpr->len; ++i)
8189 buf = pack_hex_byte (buf, aexpr->buf[i]);
8190 *buf = '\0';
8191 }
d3ce09f5
SS
8192}
8193
8181d85f
DJ
8194/* Insert a breakpoint. On targets that have software breakpoint
8195 support, we ask the remote target to do the work; on targets
8196 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
8197
8198static int
3db08215
MM
8199remote_insert_breakpoint (struct target_ops *ops,
8200 struct gdbarch *gdbarch,
a6d9a66e 8201 struct bp_target_info *bp_tgt)
c906108c 8202{
d471ea57
AC
8203 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8204 If it succeeds, then set the support to PACKET_ENABLE. If it
8205 fails, and the user has explicitly requested the Z support then
23860348 8206 report an error, otherwise, mark it disabled and go on. */
802188a7 8207
4082afcc 8208 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 8209 {
0d5ed153 8210 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 8211 struct remote_state *rs;
bba74b36 8212 char *p, *endbuf;
7c0f6dcc 8213 int bpsize;
b775012e 8214 struct condition_list *cond = NULL;
4fff2411 8215
28439a30
PA
8216 /* Make sure the remote is pointing at the right process, if
8217 necessary. */
8218 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8219 set_general_process ();
8220
a1dcb23a 8221 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
8222
8223 rs = get_remote_state ();
8224 p = rs->buf;
bba74b36 8225 endbuf = rs->buf + get_remote_packet_size ();
802188a7 8226
96baa820
JM
8227 *(p++) = 'Z';
8228 *(p++) = '0';
8229 *(p++) = ',';
7c0f6dcc 8230 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 8231 p += hexnumstr (p, addr);
bba74b36 8232 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 8233
efcc2da7 8234 if (remote_supports_cond_breakpoints (ops))
bba74b36 8235 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8236
78eff0ec 8237 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
8238 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8239
6d820c5c
DJ
8240 putpkt (rs->buf);
8241 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8242
6d820c5c 8243 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 8244 {
d471ea57
AC
8245 case PACKET_ERROR:
8246 return -1;
8247 case PACKET_OK:
7c0f6dcc
JL
8248 bp_tgt->placed_address = addr;
8249 bp_tgt->placed_size = bpsize;
d471ea57
AC
8250 return 0;
8251 case PACKET_UNKNOWN:
8252 break;
96baa820
JM
8253 }
8254 }
c906108c 8255
0000e5cc
PA
8256 /* If this breakpoint has target-side commands but this stub doesn't
8257 support Z0 packets, throw error. */
8258 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8259 throw_error (NOT_SUPPORTED_ERROR, _("\
8260Target doesn't support breakpoints that have target side commands."));
8261
3db08215 8262 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8263}
8264
8265static int
3db08215
MM
8266remote_remove_breakpoint (struct target_ops *ops,
8267 struct gdbarch *gdbarch,
a6d9a66e 8268 struct bp_target_info *bp_tgt)
c906108c 8269{
8181d85f 8270 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 8271 struct remote_state *rs = get_remote_state ();
96baa820 8272
4082afcc 8273 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 8274 {
6d820c5c 8275 char *p = rs->buf;
bba74b36 8276 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 8277
28439a30
PA
8278 /* Make sure the remote is pointing at the right process, if
8279 necessary. */
8280 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8281 set_general_process ();
8282
96baa820
JM
8283 *(p++) = 'z';
8284 *(p++) = '0';
8285 *(p++) = ',';
8286
8181d85f
DJ
8287 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8288 p += hexnumstr (p, addr);
bba74b36 8289 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 8290
6d820c5c
DJ
8291 putpkt (rs->buf);
8292 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8293
6d820c5c 8294 return (rs->buf[0] == 'E');
96baa820
JM
8295 }
8296
3db08215 8297 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8298}
8299
d471ea57
AC
8300static int
8301watchpoint_to_Z_packet (int type)
8302{
8303 switch (type)
8304 {
8305 case hw_write:
bb858e6a 8306 return Z_PACKET_WRITE_WP;
d471ea57
AC
8307 break;
8308 case hw_read:
bb858e6a 8309 return Z_PACKET_READ_WP;
d471ea57
AC
8310 break;
8311 case hw_access:
bb858e6a 8312 return Z_PACKET_ACCESS_WP;
d471ea57
AC
8313 break;
8314 default:
8e65ff28 8315 internal_error (__FILE__, __LINE__,
e2e0b3e5 8316 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
8317 }
8318}
8319
3c3bea1c 8320static int
7bb99c53
TT
8321remote_insert_watchpoint (struct target_ops *self,
8322 CORE_ADDR addr, int len, int type,
0cf6dd15 8323 struct expression *cond)
96baa820 8324{
d01949b6 8325 struct remote_state *rs = get_remote_state ();
bba74b36 8326 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8327 char *p;
d471ea57 8328 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 8329
4082afcc 8330 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 8331 return 1;
802188a7 8332
28439a30
PA
8333 /* Make sure the remote is pointing at the right process, if
8334 necessary. */
8335 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8336 set_general_process ();
8337
bba74b36 8338 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 8339 p = strchr (rs->buf, '\0');
96baa820
JM
8340 addr = remote_address_masked (addr);
8341 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8342 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 8343
6d820c5c
DJ
8344 putpkt (rs->buf);
8345 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8346
6d820c5c 8347 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8348 {
8349 case PACKET_ERROR:
d471ea57 8350 return -1;
85d721b8
PA
8351 case PACKET_UNKNOWN:
8352 return 1;
d471ea57
AC
8353 case PACKET_OK:
8354 return 0;
8355 }
8e65ff28 8356 internal_error (__FILE__, __LINE__,
e2e0b3e5 8357 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
8358}
8359
283002cf
MR
8360static int
8361remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8362 CORE_ADDR start, int length)
8363{
8364 CORE_ADDR diff = remote_address_masked (addr - start);
8365
8366 return diff < length;
8367}
8368
d471ea57 8369
3c3bea1c 8370static int
11b5219a
TT
8371remote_remove_watchpoint (struct target_ops *self,
8372 CORE_ADDR addr, int len, int type,
0cf6dd15 8373 struct expression *cond)
96baa820 8374{
d01949b6 8375 struct remote_state *rs = get_remote_state ();
bba74b36 8376 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8377 char *p;
d471ea57
AC
8378 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8379
4082afcc 8380 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 8381 return -1;
802188a7 8382
28439a30
PA
8383 /* Make sure the remote is pointing at the right process, if
8384 necessary. */
8385 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8386 set_general_process ();
8387
bba74b36 8388 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 8389 p = strchr (rs->buf, '\0');
96baa820
JM
8390 addr = remote_address_masked (addr);
8391 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8392 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
8393 putpkt (rs->buf);
8394 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8395
6d820c5c 8396 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8397 {
8398 case PACKET_ERROR:
8399 case PACKET_UNKNOWN:
8400 return -1;
8401 case PACKET_OK:
8402 return 0;
8403 }
8e65ff28 8404 internal_error (__FILE__, __LINE__,
e2e0b3e5 8405 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
8406}
8407
3c3bea1c 8408
501eef12 8409int remote_hw_watchpoint_limit = -1;
480a3f21 8410int remote_hw_watchpoint_length_limit = -1;
501eef12 8411int remote_hw_breakpoint_limit = -1;
d471ea57 8412
480a3f21 8413static int
31568a15
TT
8414remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8415 CORE_ADDR addr, int len)
480a3f21
PW
8416{
8417 if (remote_hw_watchpoint_length_limit == 0)
8418 return 0;
8419 else if (remote_hw_watchpoint_length_limit < 0)
8420 return 1;
8421 else if (len <= remote_hw_watchpoint_length_limit)
8422 return 1;
8423 else
8424 return 0;
8425}
8426
b9362cc7 8427static int
5461485a
TT
8428remote_check_watch_resources (struct target_ops *self,
8429 int type, int cnt, int ot)
96baa820 8430{
3c3bea1c
GS
8431 if (type == bp_hardware_breakpoint)
8432 {
8433 if (remote_hw_breakpoint_limit == 0)
8434 return 0;
501eef12
AC
8435 else if (remote_hw_breakpoint_limit < 0)
8436 return 1;
3c3bea1c
GS
8437 else if (cnt <= remote_hw_breakpoint_limit)
8438 return 1;
8439 }
8440 else
8441 {
8442 if (remote_hw_watchpoint_limit == 0)
8443 return 0;
501eef12
AC
8444 else if (remote_hw_watchpoint_limit < 0)
8445 return 1;
3c3bea1c
GS
8446 else if (ot)
8447 return -1;
8448 else if (cnt <= remote_hw_watchpoint_limit)
8449 return 1;
8450 }
8451 return -1;
8452}
8453
f7e6eed5
PA
8454/* The to_stopped_by_sw_breakpoint method of target remote. */
8455
8456static int
8457remote_stopped_by_sw_breakpoint (struct target_ops *ops)
8458{
8459 struct remote_state *rs = get_remote_state ();
8460
8461 return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
8462}
8463
8464/* The to_supports_stopped_by_sw_breakpoint method of target
8465 remote. */
8466
8467static int
8468remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
8469{
8470 struct remote_state *rs = get_remote_state ();
8471
8472 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
8473}
8474
8475/* The to_stopped_by_hw_breakpoint method of target remote. */
8476
8477static int
8478remote_stopped_by_hw_breakpoint (struct target_ops *ops)
8479{
8480 struct remote_state *rs = get_remote_state ();
8481
8482 return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
8483}
8484
8485/* The to_supports_stopped_by_hw_breakpoint method of target
8486 remote. */
8487
8488static int
8489remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
8490{
8491 struct remote_state *rs = get_remote_state ();
8492
8493 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
8494}
8495
b9362cc7 8496static int
6a109b6b 8497remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 8498{
ee154bee
TT
8499 struct remote_state *rs = get_remote_state ();
8500
f7e6eed5 8501 return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
3c3bea1c
GS
8502}
8503
4aa7a7f5
JJ
8504static int
8505remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 8506{
ee154bee 8507 struct remote_state *rs = get_remote_state ();
4aa7a7f5 8508 int rc = 0;
a744cf53 8509
6a109b6b 8510 if (remote_stopped_by_watchpoint (target))
4aa7a7f5 8511 {
ee154bee 8512 *addr_p = rs->remote_watch_data_address;
4aa7a7f5
JJ
8513 rc = 1;
8514 }
8515
8516 return rc;
3c3bea1c
GS
8517}
8518
8519
8520static int
23a26771 8521remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 8522 struct bp_target_info *bp_tgt)
3c3bea1c 8523{
0d5ed153 8524 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 8525 struct remote_state *rs;
bba74b36 8526 char *p, *endbuf;
dd61ec5c 8527 char *message;
0d5ed153 8528 int bpsize;
802188a7 8529
c8189ed1 8530 /* The length field should be set to the size of a breakpoint
8181d85f 8531 instruction, even though we aren't inserting one ourselves. */
c8189ed1 8532
0d5ed153 8533 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 8534
4082afcc 8535 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 8536 return -1;
2bc416ba 8537
28439a30
PA
8538 /* Make sure the remote is pointing at the right process, if
8539 necessary. */
8540 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8541 set_general_process ();
8542
4fff2411
JZ
8543 rs = get_remote_state ();
8544 p = rs->buf;
bba74b36 8545 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 8546
96baa820
JM
8547 *(p++) = 'Z';
8548 *(p++) = '1';
8549 *(p++) = ',';
802188a7 8550
0d5ed153 8551 addr = remote_address_masked (addr);
96baa820 8552 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 8553 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 8554
efcc2da7 8555 if (remote_supports_cond_breakpoints (self))
bba74b36 8556 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8557
78eff0ec 8558 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
8559 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8560
6d820c5c
DJ
8561 putpkt (rs->buf);
8562 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8563
6d820c5c 8564 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
8565 {
8566 case PACKET_ERROR:
dd61ec5c
MW
8567 if (rs->buf[1] == '.')
8568 {
8569 message = strchr (rs->buf + 2, '.');
8570 if (message)
0316657e 8571 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
8572 }
8573 return -1;
d471ea57
AC
8574 case PACKET_UNKNOWN:
8575 return -1;
8576 case PACKET_OK:
0d5ed153
MR
8577 bp_tgt->placed_address = addr;
8578 bp_tgt->placed_size = bpsize;
d471ea57
AC
8579 return 0;
8580 }
8e65ff28 8581 internal_error (__FILE__, __LINE__,
e2e0b3e5 8582 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
8583}
8584
d471ea57 8585
802188a7 8586static int
a64dc96c 8587remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 8588 struct bp_target_info *bp_tgt)
96baa820 8589{
8181d85f 8590 CORE_ADDR addr;
d01949b6 8591 struct remote_state *rs = get_remote_state ();
6d820c5c 8592 char *p = rs->buf;
bba74b36 8593 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 8594
4082afcc 8595 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 8596 return -1;
802188a7 8597
28439a30
PA
8598 /* Make sure the remote is pointing at the right process, if
8599 necessary. */
8600 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8601 set_general_process ();
8602
96baa820
JM
8603 *(p++) = 'z';
8604 *(p++) = '1';
8605 *(p++) = ',';
802188a7 8606
8181d85f 8607 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 8608 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8609 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 8610
6d820c5c
DJ
8611 putpkt (rs->buf);
8612 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 8613
6d820c5c 8614 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
8615 {
8616 case PACKET_ERROR:
8617 case PACKET_UNKNOWN:
8618 return -1;
8619 case PACKET_OK:
8620 return 0;
8621 }
8e65ff28 8622 internal_error (__FILE__, __LINE__,
e2e0b3e5 8623 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 8624}
96baa820 8625
4a5e7a5b
PA
8626/* Verify memory using the "qCRC:" request. */
8627
8628static int
8629remote_verify_memory (struct target_ops *ops,
8630 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8631{
8632 struct remote_state *rs = get_remote_state ();
8633 unsigned long host_crc, target_crc;
8634 char *tmp;
8635
936d2992
PA
8636 /* It doesn't make sense to use qCRC if the remote target is
8637 connected but not running. */
8638 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
8639 {
8640 enum packet_result result;
28439a30 8641
936d2992
PA
8642 /* Make sure the remote is pointing at the right process. */
8643 set_general_process ();
4a5e7a5b 8644
936d2992
PA
8645 /* FIXME: assumes lma can fit into long. */
8646 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8647 (long) lma, (long) size);
8648 putpkt (rs->buf);
4a5e7a5b 8649
936d2992
PA
8650 /* Be clever; compute the host_crc before waiting for target
8651 reply. */
8652 host_crc = xcrc32 (data, size, 0xffffffff);
8653
8654 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 8655
936d2992
PA
8656 result = packet_ok (rs->buf,
8657 &remote_protocol_packets[PACKET_qCRC]);
8658 if (result == PACKET_ERROR)
8659 return -1;
8660 else if (result == PACKET_OK)
8661 {
8662 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8663 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 8664
936d2992
PA
8665 return (host_crc == target_crc);
8666 }
8667 }
4a5e7a5b 8668
936d2992 8669 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
8670}
8671
c906108c
SS
8672/* compare-sections command
8673
8674 With no arguments, compares each loadable section in the exec bfd
8675 with the same memory range on the target, and reports mismatches.
4a5e7a5b 8676 Useful for verifying the image on the target against the exec file. */
e514a9d6 8677
c906108c 8678static void
fba45db2 8679compare_sections_command (char *args, int from_tty)
c906108c
SS
8680{
8681 asection *s;
c906108c 8682 struct cleanup *old_chain;
948f8e3d 8683 gdb_byte *sectdata;
ce359b09 8684 const char *sectname;
c906108c
SS
8685 bfd_size_type size;
8686 bfd_vma lma;
8687 int matched = 0;
8688 int mismatched = 0;
4a5e7a5b 8689 int res;
95cf3b38 8690 int read_only = 0;
c906108c
SS
8691
8692 if (!exec_bfd)
8a3fe4f8 8693 error (_("command cannot be used without an exec file"));
c906108c 8694
28439a30
PA
8695 /* Make sure the remote is pointing at the right process. */
8696 set_general_process ();
8697
95cf3b38
DT
8698 if (args != NULL && strcmp (args, "-r") == 0)
8699 {
8700 read_only = 1;
8701 args = NULL;
8702 }
8703
c5aa993b 8704 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
8705 {
8706 if (!(s->flags & SEC_LOAD))
0df8b418 8707 continue; /* Skip non-loadable section. */
c906108c 8708
95cf3b38
DT
8709 if (read_only && (s->flags & SEC_READONLY) == 0)
8710 continue; /* Skip writeable sections */
8711
2c500098 8712 size = bfd_get_section_size (s);
c906108c 8713 if (size == 0)
0df8b418 8714 continue; /* Skip zero-length section. */
c906108c 8715
ce359b09 8716 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 8717 if (args && strcmp (args, sectname) != 0)
0df8b418 8718 continue; /* Not the section selected by user. */
c906108c 8719
0df8b418 8720 matched = 1; /* Do this section. */
c906108c 8721 lma = s->lma;
c906108c 8722
c906108c 8723 sectdata = xmalloc (size);
b8c9b27d 8724 old_chain = make_cleanup (xfree, sectdata);
c906108c 8725 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 8726
4a5e7a5b
PA
8727 res = target_verify_memory (sectdata, lma, size);
8728
8729 if (res == -1)
5af949e3 8730 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
8731 paddress (target_gdbarch (), lma),
8732 paddress (target_gdbarch (), lma + size));
c906108c 8733
5af949e3 8734 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
8735 paddress (target_gdbarch (), lma),
8736 paddress (target_gdbarch (), lma + size));
4a5e7a5b 8737 if (res)
c906108c
SS
8738 printf_filtered ("matched.\n");
8739 else
c5aa993b
JM
8740 {
8741 printf_filtered ("MIS-MATCHED!\n");
8742 mismatched++;
8743 }
c906108c
SS
8744
8745 do_cleanups (old_chain);
8746 }
8747 if (mismatched > 0)
936d2992 8748 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 8749the loaded file\n"));
c906108c 8750 if (args && !matched)
a3f17187 8751 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
8752}
8753
0e7f50da
UW
8754/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8755 into remote target. The number of bytes written to the remote
8756 target is returned, or -1 for error. */
8757
9b409511 8758static enum target_xfer_status
0e7f50da
UW
8759remote_write_qxfer (struct target_ops *ops, const char *object_name,
8760 const char *annex, const gdb_byte *writebuf,
9b409511 8761 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
8762 struct packet_config *packet)
8763{
8764 int i, buf_len;
8765 ULONGEST n;
0e7f50da
UW
8766 struct remote_state *rs = get_remote_state ();
8767 int max_size = get_memory_write_packet_size ();
8768
8769 if (packet->support == PACKET_DISABLE)
2ed4b548 8770 return TARGET_XFER_E_IO;
0e7f50da
UW
8771
8772 /* Insert header. */
8773 i = snprintf (rs->buf, max_size,
8774 "qXfer:%s:write:%s:%s:",
8775 object_name, annex ? annex : "",
8776 phex_nz (offset, sizeof offset));
8777 max_size -= (i + 1);
8778
8779 /* Escape as much data as fits into rs->buf. */
8780 buf_len = remote_escape_output
bc20a4af 8781 (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
8782
8783 if (putpkt_binary (rs->buf, i + buf_len) < 0
8784 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8785 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 8786 return TARGET_XFER_E_IO;
0e7f50da
UW
8787
8788 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
8789
8790 *xfered_len = n;
8791 return TARGET_XFER_OK;
0e7f50da
UW
8792}
8793
0876f84a
DJ
8794/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8795 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8796 number of bytes read is returned, or 0 for EOF, or -1 for error.
8797 The number of bytes read may be less than LEN without indicating an
8798 EOF. PACKET is checked and updated to indicate whether the remote
8799 target supports this object. */
8800
9b409511 8801static enum target_xfer_status
0876f84a
DJ
8802remote_read_qxfer (struct target_ops *ops, const char *object_name,
8803 const char *annex,
8804 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 8805 ULONGEST *xfered_len,
0876f84a
DJ
8806 struct packet_config *packet)
8807{
0876f84a 8808 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
8809 LONGEST i, n, packet_len;
8810
8811 if (packet->support == PACKET_DISABLE)
2ed4b548 8812 return TARGET_XFER_E_IO;
0876f84a
DJ
8813
8814 /* Check whether we've cached an end-of-object packet that matches
8815 this request. */
8e88304f 8816 if (rs->finished_object)
0876f84a 8817 {
8e88304f
TT
8818 if (strcmp (object_name, rs->finished_object) == 0
8819 && strcmp (annex ? annex : "", rs->finished_annex) == 0
8820 && offset == rs->finished_offset)
9b409511
YQ
8821 return TARGET_XFER_EOF;
8822
0876f84a
DJ
8823
8824 /* Otherwise, we're now reading something different. Discard
8825 the cache. */
8e88304f
TT
8826 xfree (rs->finished_object);
8827 xfree (rs->finished_annex);
8828 rs->finished_object = NULL;
8829 rs->finished_annex = NULL;
0876f84a
DJ
8830 }
8831
8832 /* Request only enough to fit in a single packet. The actual data
8833 may not, since we don't know how much of it will need to be escaped;
8834 the target is free to respond with slightly less data. We subtract
8835 five to account for the response type and the protocol frame. */
8836 n = min (get_remote_packet_size () - 5, len);
8837 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8838 object_name, annex ? annex : "",
8839 phex_nz (offset, sizeof offset),
8840 phex_nz (n, sizeof n));
8841 i = putpkt (rs->buf);
8842 if (i < 0)
2ed4b548 8843 return TARGET_XFER_E_IO;
0876f84a
DJ
8844
8845 rs->buf[0] = '\0';
8846 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8847 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 8848 return TARGET_XFER_E_IO;
0876f84a
DJ
8849
8850 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8851 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8852
8853 /* 'm' means there is (or at least might be) more data after this
8854 batch. That does not make sense unless there's at least one byte
8855 of data in this reply. */
8856 if (rs->buf[0] == 'm' && packet_len == 1)
8857 error (_("Remote qXfer reply contained no data."));
8858
8859 /* Got some data. */
bc20a4af
PA
8860 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
8861 packet_len - 1, readbuf, n);
0876f84a
DJ
8862
8863 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
8864 or possibly empty. If we have the final block of a non-empty
8865 object, record this fact to bypass a subsequent partial read. */
8866 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 8867 {
8e88304f
TT
8868 rs->finished_object = xstrdup (object_name);
8869 rs->finished_annex = xstrdup (annex ? annex : "");
8870 rs->finished_offset = offset + i;
0876f84a
DJ
8871 }
8872
9b409511
YQ
8873 if (i == 0)
8874 return TARGET_XFER_EOF;
8875 else
8876 {
8877 *xfered_len = i;
8878 return TARGET_XFER_OK;
8879 }
0876f84a
DJ
8880}
8881
9b409511 8882static enum target_xfer_status
4b8a223f 8883remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 8884 const char *annex, gdb_byte *readbuf,
9b409511
YQ
8885 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
8886 ULONGEST *xfered_len)
c906108c 8887{
82f73884 8888 struct remote_state *rs;
c906108c 8889 int i;
6d820c5c 8890 char *p2;
1e3ff5ad 8891 char query_type;
c906108c 8892
e6e4e701 8893 set_remote_traceframe ();
82f73884
PA
8894 set_general_thread (inferior_ptid);
8895
8896 rs = get_remote_state ();
8897
b2182ed2 8898 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
8899 if (object == TARGET_OBJECT_MEMORY)
8900 {
2d717e4f
DJ
8901 /* If the remote target is connected but not running, we should
8902 pass this request down to a lower stratum (e.g. the executable
8903 file). */
8904 if (!target_has_execution)
9b409511 8905 return TARGET_XFER_EOF;
2d717e4f 8906
21e3b9b9 8907 if (writebuf != NULL)
9b409511 8908 return remote_write_bytes (offset, writebuf, len, xfered_len);
21e3b9b9 8909 else
8acf9577 8910 return remote_read_bytes (ops, offset, readbuf, len, xfered_len);
21e3b9b9
DJ
8911 }
8912
0df8b418 8913 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
8914 if (object == TARGET_OBJECT_SPU)
8915 {
8916 if (readbuf)
8917 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
8918 xfered_len, &remote_protocol_packets
8919 [PACKET_qXfer_spu_read]);
0e7f50da
UW
8920 else
8921 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
8922 xfered_len, &remote_protocol_packets
8923 [PACKET_qXfer_spu_write]);
0e7f50da
UW
8924 }
8925
4aa995e1
PA
8926 /* Handle extra signal info using qxfer packets. */
8927 if (object == TARGET_OBJECT_SIGNAL_INFO)
8928 {
8929 if (readbuf)
8930 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 8931 xfered_len, &remote_protocol_packets
4aa995e1
PA
8932 [PACKET_qXfer_siginfo_read]);
8933 else
3e43a32a 8934 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 8935 writebuf, offset, len, xfered_len,
4aa995e1
PA
8936 &remote_protocol_packets
8937 [PACKET_qXfer_siginfo_write]);
8938 }
8939
0fb4aa4b
PA
8940 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8941 {
8942 if (readbuf)
3e43a32a 8943 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 8944 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
8945 &remote_protocol_packets
8946 [PACKET_qXfer_statictrace_read]);
8947 else
2ed4b548 8948 return TARGET_XFER_E_IO;
0fb4aa4b
PA
8949 }
8950
a76d924d
DJ
8951 /* Only handle flash writes. */
8952 if (writebuf != NULL)
8953 {
8954 LONGEST xfered;
8955
8956 switch (object)
8957 {
8958 case TARGET_OBJECT_FLASH:
9b409511
YQ
8959 return remote_flash_write (ops, offset, len, xfered_len,
8960 writebuf);
a76d924d
DJ
8961
8962 default:
2ed4b548 8963 return TARGET_XFER_E_IO;
a76d924d
DJ
8964 }
8965 }
4b8a223f 8966
1e3ff5ad
AC
8967 /* Map pre-existing objects onto letters. DO NOT do this for new
8968 objects!!! Instead specify new query packets. */
8969 switch (object)
c906108c 8970 {
1e3ff5ad
AC
8971 case TARGET_OBJECT_AVR:
8972 query_type = 'R';
8973 break;
802188a7
RM
8974
8975 case TARGET_OBJECT_AUXV:
0876f84a
DJ
8976 gdb_assert (annex == NULL);
8977 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 8978 xfered_len,
0876f84a 8979 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 8980
23181151
DJ
8981 case TARGET_OBJECT_AVAILABLE_FEATURES:
8982 return remote_read_qxfer
9b409511 8983 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
8984 &remote_protocol_packets[PACKET_qXfer_features]);
8985
cfa9d6d9
DJ
8986 case TARGET_OBJECT_LIBRARIES:
8987 return remote_read_qxfer
9b409511 8988 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
8989 &remote_protocol_packets[PACKET_qXfer_libraries]);
8990
2268b414
JK
8991 case TARGET_OBJECT_LIBRARIES_SVR4:
8992 return remote_read_qxfer
9b409511 8993 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
8994 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
8995
fd79ecee
DJ
8996 case TARGET_OBJECT_MEMORY_MAP:
8997 gdb_assert (annex == NULL);
8998 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 8999 xfered_len,
fd79ecee
DJ
9000 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9001
07e059b5
VP
9002 case TARGET_OBJECT_OSDATA:
9003 /* Should only get here if we're connected. */
5d93a237 9004 gdb_assert (rs->remote_desc);
07e059b5 9005 return remote_read_qxfer
9b409511 9006 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
9007 &remote_protocol_packets[PACKET_qXfer_osdata]);
9008
dc146f7c
VP
9009 case TARGET_OBJECT_THREADS:
9010 gdb_assert (annex == NULL);
9011 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 9012 xfered_len,
dc146f7c
VP
9013 &remote_protocol_packets[PACKET_qXfer_threads]);
9014
b3b9301e
PA
9015 case TARGET_OBJECT_TRACEFRAME_INFO:
9016 gdb_assert (annex == NULL);
9017 return remote_read_qxfer
9b409511 9018 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 9019 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
9020
9021 case TARGET_OBJECT_FDPIC:
9022 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 9023 xfered_len,
78d85199 9024 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
9025
9026 case TARGET_OBJECT_OPENVMS_UIB:
9027 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 9028 xfered_len,
169081d0
TG
9029 &remote_protocol_packets[PACKET_qXfer_uib]);
9030
9accd112
MM
9031 case TARGET_OBJECT_BTRACE:
9032 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 9033 xfered_len,
9accd112
MM
9034 &remote_protocol_packets[PACKET_qXfer_btrace]);
9035
f4abbc16
MM
9036 case TARGET_OBJECT_BTRACE_CONF:
9037 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9038 len, xfered_len,
9039 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9040
c78fa86a
GB
9041 case TARGET_OBJECT_EXEC_FILE:
9042 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9043 len, xfered_len,
9044 &remote_protocol_packets[PACKET_qXfer_exec_file]);
9045
1e3ff5ad 9046 default:
2ed4b548 9047 return TARGET_XFER_E_IO;
c906108c
SS
9048 }
9049
0df8b418 9050 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 9051 large enough let the caller deal with it. */
ea9c271d 9052 if (len < get_remote_packet_size ())
2ed4b548 9053 return TARGET_XFER_E_IO;
ea9c271d 9054 len = get_remote_packet_size ();
1e3ff5ad 9055
23860348 9056 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 9057 if (!rs->remote_desc)
8a3fe4f8 9058 error (_("remote query is only available after target open"));
c906108c 9059
1e3ff5ad 9060 gdb_assert (annex != NULL);
4b8a223f 9061 gdb_assert (readbuf != NULL);
c906108c 9062
6d820c5c 9063 p2 = rs->buf;
c906108c
SS
9064 *p2++ = 'q';
9065 *p2++ = query_type;
9066
23860348
MS
9067 /* We used one buffer char for the remote protocol q command and
9068 another for the query type. As the remote protocol encapsulation
9069 uses 4 chars plus one extra in case we are debugging
9070 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9071 string. */
c906108c 9072 i = 0;
ea9c271d 9073 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 9074 {
1e3ff5ad
AC
9075 /* Bad caller may have sent forbidden characters. */
9076 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9077 *p2++ = annex[i];
c906108c
SS
9078 i++;
9079 }
1e3ff5ad
AC
9080 *p2 = '\0';
9081 gdb_assert (annex[i] == '\0');
c906108c 9082
6d820c5c 9083 i = putpkt (rs->buf);
c5aa993b 9084 if (i < 0)
2ed4b548 9085 return TARGET_XFER_E_IO;
c906108c 9086
6d820c5c
DJ
9087 getpkt (&rs->buf, &rs->buf_size, 0);
9088 strcpy ((char *) readbuf, rs->buf);
c906108c 9089
9b409511
YQ
9090 *xfered_len = strlen ((char *) readbuf);
9091 return TARGET_XFER_OK;
c906108c
SS
9092}
9093
08388c79
DE
9094static int
9095remote_search_memory (struct target_ops* ops,
9096 CORE_ADDR start_addr, ULONGEST search_space_len,
9097 const gdb_byte *pattern, ULONGEST pattern_len,
9098 CORE_ADDR *found_addrp)
9099{
f5656ead 9100 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
9101 struct remote_state *rs = get_remote_state ();
9102 int max_size = get_memory_write_packet_size ();
9103 struct packet_config *packet =
9104 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
9105 /* Number of packet bytes used to encode the pattern;
9106 this could be more than PATTERN_LEN due to escape characters. */
08388c79 9107 int escaped_pattern_len;
0df8b418 9108 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
9109 int used_pattern_len;
9110 int i;
9111 int found;
9112 ULONGEST found_addr;
9113
9114 /* Don't go to the target if we don't have to.
9115 This is done before checking packet->support to avoid the possibility that
9116 a success for this edge case means the facility works in general. */
9117 if (pattern_len > search_space_len)
9118 return 0;
9119 if (pattern_len == 0)
9120 {
9121 *found_addrp = start_addr;
9122 return 1;
9123 }
9124
9125 /* If we already know the packet isn't supported, fall back to the simple
9126 way of searching memory. */
9127
4082afcc 9128 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
9129 {
9130 /* Target doesn't provided special support, fall back and use the
9131 standard support (copy memory and do the search here). */
9132 return simple_search_memory (ops, start_addr, search_space_len,
9133 pattern, pattern_len, found_addrp);
9134 }
9135
28439a30
PA
9136 /* Make sure the remote is pointing at the right process. */
9137 set_general_process ();
9138
08388c79
DE
9139 /* Insert header. */
9140 i = snprintf (rs->buf, max_size,
9141 "qSearch:memory:%s;%s;",
5af949e3 9142 phex_nz (start_addr, addr_size),
08388c79
DE
9143 phex_nz (search_space_len, sizeof (search_space_len)));
9144 max_size -= (i + 1);
9145
9146 /* Escape as much data as fits into rs->buf. */
9147 escaped_pattern_len =
bc20a4af 9148 remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
08388c79
DE
9149 &used_pattern_len, max_size);
9150
9151 /* Bail if the pattern is too large. */
9152 if (used_pattern_len != pattern_len)
9b20d036 9153 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
9154
9155 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9156 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9157 || packet_ok (rs->buf, packet) != PACKET_OK)
9158 {
9159 /* The request may not have worked because the command is not
9160 supported. If so, fall back to the simple way. */
9161 if (packet->support == PACKET_DISABLE)
9162 {
9163 return simple_search_memory (ops, start_addr, search_space_len,
9164 pattern, pattern_len, found_addrp);
9165 }
9166 return -1;
9167 }
9168
9169 if (rs->buf[0] == '0')
9170 found = 0;
9171 else if (rs->buf[0] == '1')
9172 {
9173 found = 1;
9174 if (rs->buf[1] != ',')
10e0fa18 9175 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9176 unpack_varlen_hex (rs->buf + 2, &found_addr);
9177 *found_addrp = found_addr;
9178 }
9179 else
10e0fa18 9180 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9181
9182 return found;
9183}
9184
96baa820 9185static void
a30bf1f1 9186remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 9187 struct ui_file *outbuf)
96baa820 9188{
d01949b6 9189 struct remote_state *rs = get_remote_state ();
2e9f7625 9190 char *p = rs->buf;
96baa820 9191
5d93a237 9192 if (!rs->remote_desc)
8a3fe4f8 9193 error (_("remote rcmd is only available after target open"));
96baa820 9194
23860348 9195 /* Send a NULL command across as an empty command. */
7be570e7
JM
9196 if (command == NULL)
9197 command = "";
9198
23860348 9199 /* The query prefix. */
2e9f7625
DJ
9200 strcpy (rs->buf, "qRcmd,");
9201 p = strchr (rs->buf, '\0');
96baa820 9202
3e43a32a
MS
9203 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9204 > get_remote_packet_size ())
8a3fe4f8 9205 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 9206
23860348 9207 /* Encode the actual command. */
a30bf1f1 9208 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 9209
6d820c5c 9210 if (putpkt (rs->buf) < 0)
8a3fe4f8 9211 error (_("Communication problem with target."));
96baa820
JM
9212
9213 /* get/display the response */
9214 while (1)
9215 {
2e9f7625
DJ
9216 char *buf;
9217
00bf0b85 9218 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 9219 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 9220 rs->buf[0] = '\0';
5b37825d
PW
9221 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9222 {
9223 /* Timeout. Continue to (try to) read responses.
9224 This is better than stopping with an error, assuming the stub
9225 is still executing the (long) monitor command.
9226 If needed, the user can interrupt gdb using C-c, obtaining
9227 an effect similar to stop on timeout. */
9228 continue;
9229 }
2e9f7625 9230 buf = rs->buf;
96baa820 9231 if (buf[0] == '\0')
8a3fe4f8 9232 error (_("Target does not support this command."));
96baa820
JM
9233 if (buf[0] == 'O' && buf[1] != 'K')
9234 {
23860348 9235 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
9236 continue;
9237 }
9238 if (strcmp (buf, "OK") == 0)
9239 break;
7be570e7
JM
9240 if (strlen (buf) == 3 && buf[0] == 'E'
9241 && isdigit (buf[1]) && isdigit (buf[2]))
9242 {
8a3fe4f8 9243 error (_("Protocol error with Rcmd"));
7be570e7 9244 }
96baa820
JM
9245 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9246 {
9247 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 9248
96baa820
JM
9249 fputc_unfiltered (c, outbuf);
9250 }
9251 break;
9252 }
9253}
9254
fd79ecee
DJ
9255static VEC(mem_region_s) *
9256remote_memory_map (struct target_ops *ops)
9257{
9258 VEC(mem_region_s) *result = NULL;
9259 char *text = target_read_stralloc (&current_target,
9260 TARGET_OBJECT_MEMORY_MAP, NULL);
9261
9262 if (text)
9263 {
9264 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 9265
fd79ecee
DJ
9266 result = parse_memory_map (text);
9267 do_cleanups (back_to);
9268 }
9269
9270 return result;
9271}
9272
c906108c 9273static void
fba45db2 9274packet_command (char *args, int from_tty)
c906108c 9275{
d01949b6 9276 struct remote_state *rs = get_remote_state ();
c906108c 9277
5d93a237 9278 if (!rs->remote_desc)
8a3fe4f8 9279 error (_("command can only be used with remote target"));
c906108c 9280
c5aa993b 9281 if (!args)
8a3fe4f8 9282 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
9283
9284 puts_filtered ("sending: ");
9285 print_packet (args);
9286 puts_filtered ("\n");
9287 putpkt (args);
9288
6d820c5c 9289 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 9290 puts_filtered ("received: ");
6d820c5c 9291 print_packet (rs->buf);
c906108c
SS
9292 puts_filtered ("\n");
9293}
9294
9295#if 0
23860348 9296/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 9297
a14ed312 9298static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 9299
a14ed312 9300static void threadset_test_cmd (char *cmd, int tty);
c906108c 9301
a14ed312 9302static void threadalive_test (char *cmd, int tty);
c906108c 9303
a14ed312 9304static void threadlist_test_cmd (char *cmd, int tty);
c906108c 9305
23860348 9306int get_and_display_threadinfo (threadref *ref);
c906108c 9307
a14ed312 9308static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 9309
23860348 9310static int thread_display_step (threadref *ref, void *context);
c906108c 9311
a14ed312 9312static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 9313
a14ed312 9314static void init_remote_threadtests (void);
c906108c 9315
23860348 9316#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
9317
9318static void
fba45db2 9319threadset_test_cmd (char *cmd, int tty)
c906108c
SS
9320{
9321 int sample_thread = SAMPLE_THREAD;
9322
a3f17187 9323 printf_filtered (_("Remote threadset test\n"));
79d7f229 9324 set_general_thread (sample_thread);
c906108c
SS
9325}
9326
9327
9328static void
fba45db2 9329threadalive_test (char *cmd, int tty)
c906108c
SS
9330{
9331 int sample_thread = SAMPLE_THREAD;
79d7f229 9332 int pid = ptid_get_pid (inferior_ptid);
ba348170 9333 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 9334
79d7f229 9335 if (remote_thread_alive (ptid))
c906108c
SS
9336 printf_filtered ("PASS: Thread alive test\n");
9337 else
9338 printf_filtered ("FAIL: Thread alive test\n");
9339}
9340
23860348 9341void output_threadid (char *title, threadref *ref);
c906108c
SS
9342
9343void
fba45db2 9344output_threadid (char *title, threadref *ref)
c906108c
SS
9345{
9346 char hexid[20];
9347
23860348 9348 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
9349 hexid[16] = 0;
9350 printf_filtered ("%s %s\n", title, (&hexid[0]));
9351}
9352
9353static void
fba45db2 9354threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
9355{
9356 int startflag = 1;
9357 threadref nextthread;
9358 int done, result_count;
9359 threadref threadlist[3];
9360
9361 printf_filtered ("Remote Threadlist test\n");
9362 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9363 &result_count, &threadlist[0]))
9364 printf_filtered ("FAIL: threadlist test\n");
9365 else
9366 {
9367 threadref *scan = threadlist;
9368 threadref *limit = scan + result_count;
9369
9370 while (scan < limit)
9371 output_threadid (" thread ", scan++);
9372 }
9373}
9374
9375void
fba45db2 9376display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
9377{
9378 output_threadid ("Threadid: ", &info->threadid);
9379 printf_filtered ("Name: %s\n ", info->shortname);
9380 printf_filtered ("State: %s\n", info->display);
9381 printf_filtered ("other: %s\n\n", info->more_display);
9382}
9383
9384int
fba45db2 9385get_and_display_threadinfo (threadref *ref)
c906108c
SS
9386{
9387 int result;
9388 int set;
9389 struct gdb_ext_thread_info threadinfo;
9390
9391 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9392 | TAG_MOREDISPLAY | TAG_DISPLAY;
9393 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9394 display_thread_info (&threadinfo);
9395 return result;
9396}
9397
9398static void
fba45db2 9399threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
9400{
9401 int athread = SAMPLE_THREAD;
9402 threadref thread;
9403 int set;
9404
9405 int_to_threadref (&thread, athread);
9406 printf_filtered ("Remote Threadinfo test\n");
9407 if (!get_and_display_threadinfo (&thread))
9408 printf_filtered ("FAIL cannot get thread info\n");
9409}
9410
9411static int
fba45db2 9412thread_display_step (threadref *ref, void *context)
c906108c
SS
9413{
9414 /* output_threadid(" threadstep ",ref); *//* simple test */
9415 return get_and_display_threadinfo (ref);
9416}
9417
9418static void
fba45db2 9419threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
9420{
9421 printf_filtered ("Remote Threadlist update test\n");
9422 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9423}
9424
9425static void
9426init_remote_threadtests (void)
9427{
3e43a32a
MS
9428 add_com ("tlist", class_obscure, threadlist_test_cmd,
9429 _("Fetch and print the remote list of "
9430 "thread identifiers, one pkt only"));
c906108c 9431 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 9432 _("Fetch and display info about one thread"));
c906108c 9433 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 9434 _("Test setting to a different thread"));
c906108c 9435 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 9436 _("Iterate through updating all remote thread info"));
c906108c 9437 add_com ("talive", class_obscure, threadalive_test,
1bedd215 9438 _(" Remote thread alive test "));
c906108c
SS
9439}
9440
9441#endif /* 0 */
9442
f3fb8c85
MS
9443/* Convert a thread ID to a string. Returns the string in a static
9444 buffer. */
9445
9446static char *
117de6a9 9447remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 9448{
79d7f229 9449 static char buf[64];
82f73884 9450 struct remote_state *rs = get_remote_state ();
f3fb8c85 9451
7cee1e54
PA
9452 if (ptid_equal (ptid, null_ptid))
9453 return normal_pid_to_str (ptid);
9454 else if (ptid_is_pid (ptid))
ecd0ada5
PA
9455 {
9456 /* Printing an inferior target id. */
9457
9458 /* When multi-process extensions are off, there's no way in the
9459 remote protocol to know the remote process id, if there's any
9460 at all. There's one exception --- when we're connected with
9461 target extended-remote, and we manually attached to a process
9462 with "attach PID". We don't record anywhere a flag that
9463 allows us to distinguish that case from the case of
9464 connecting with extended-remote and the stub already being
9465 attached to a process, and reporting yes to qAttached, hence
9466 no smart special casing here. */
9467 if (!remote_multi_process_p (rs))
9468 {
9469 xsnprintf (buf, sizeof buf, "Remote target");
9470 return buf;
9471 }
9472
9473 return normal_pid_to_str (ptid);
82f73884 9474 }
ecd0ada5 9475 else
79d7f229 9476 {
ecd0ada5
PA
9477 if (ptid_equal (magic_null_ptid, ptid))
9478 xsnprintf (buf, sizeof buf, "Thread <main>");
901f9912 9479 else if (rs->extended && remote_multi_process_p (rs))
ecd0ada5 9480 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
ba348170 9481 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
9482 else
9483 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 9484 ptid_get_lwp (ptid));
79d7f229
PA
9485 return buf;
9486 }
f3fb8c85
MS
9487}
9488
38691318
KB
9489/* Get the address of the thread local variable in OBJFILE which is
9490 stored at OFFSET within the thread local storage for thread PTID. */
9491
9492static CORE_ADDR
117de6a9
PA
9493remote_get_thread_local_address (struct target_ops *ops,
9494 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 9495{
4082afcc 9496 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
9497 {
9498 struct remote_state *rs = get_remote_state ();
6d820c5c 9499 char *p = rs->buf;
82f73884 9500 char *endp = rs->buf + get_remote_packet_size ();
571dd617 9501 enum packet_result result;
38691318
KB
9502
9503 strcpy (p, "qGetTLSAddr:");
9504 p += strlen (p);
82f73884 9505 p = write_ptid (p, endp, ptid);
38691318
KB
9506 *p++ = ',';
9507 p += hexnumstr (p, offset);
9508 *p++ = ',';
9509 p += hexnumstr (p, lm);
9510 *p++ = '\0';
9511
6d820c5c
DJ
9512 putpkt (rs->buf);
9513 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
9514 result = packet_ok (rs->buf,
9515 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 9516 if (result == PACKET_OK)
38691318
KB
9517 {
9518 ULONGEST result;
9519
6d820c5c 9520 unpack_varlen_hex (rs->buf, &result);
38691318
KB
9521 return result;
9522 }
571dd617 9523 else if (result == PACKET_UNKNOWN)
109c3e39
AC
9524 throw_error (TLS_GENERIC_ERROR,
9525 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 9526 else
109c3e39
AC
9527 throw_error (TLS_GENERIC_ERROR,
9528 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
9529 }
9530 else
109c3e39
AC
9531 throw_error (TLS_GENERIC_ERROR,
9532 _("TLS not supported or disabled on this target"));
38691318
KB
9533 /* Not reached. */
9534 return 0;
9535}
9536
711e434b
PM
9537/* Provide thread local base, i.e. Thread Information Block address.
9538 Returns 1 if ptid is found and thread_local_base is non zero. */
9539
70221824 9540static int
bd7ae0f5 9541remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 9542{
4082afcc 9543 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
9544 {
9545 struct remote_state *rs = get_remote_state ();
9546 char *p = rs->buf;
9547 char *endp = rs->buf + get_remote_packet_size ();
9548 enum packet_result result;
9549
9550 strcpy (p, "qGetTIBAddr:");
9551 p += strlen (p);
9552 p = write_ptid (p, endp, ptid);
9553 *p++ = '\0';
9554
9555 putpkt (rs->buf);
9556 getpkt (&rs->buf, &rs->buf_size, 0);
9557 result = packet_ok (rs->buf,
9558 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9559 if (result == PACKET_OK)
9560 {
9561 ULONGEST result;
9562
9563 unpack_varlen_hex (rs->buf, &result);
9564 if (addr)
9565 *addr = (CORE_ADDR) result;
9566 return 1;
9567 }
9568 else if (result == PACKET_UNKNOWN)
9569 error (_("Remote target doesn't support qGetTIBAddr packet"));
9570 else
9571 error (_("Remote target failed to process qGetTIBAddr request"));
9572 }
9573 else
9574 error (_("qGetTIBAddr not supported or disabled on this target"));
9575 /* Not reached. */
9576 return 0;
9577}
9578
29709017
DJ
9579/* Support for inferring a target description based on the current
9580 architecture and the size of a 'g' packet. While the 'g' packet
9581 can have any size (since optional registers can be left off the
9582 end), some sizes are easily recognizable given knowledge of the
9583 approximate architecture. */
9584
9585struct remote_g_packet_guess
9586{
9587 int bytes;
9588 const struct target_desc *tdesc;
9589};
9590typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9591DEF_VEC_O(remote_g_packet_guess_s);
9592
9593struct remote_g_packet_data
9594{
9595 VEC(remote_g_packet_guess_s) *guesses;
9596};
9597
9598static struct gdbarch_data *remote_g_packet_data_handle;
9599
9600static void *
9601remote_g_packet_data_init (struct obstack *obstack)
9602{
9603 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9604}
9605
9606void
9607register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9608 const struct target_desc *tdesc)
9609{
9610 struct remote_g_packet_data *data
9611 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9612 struct remote_g_packet_guess new_guess, *guess;
9613 int ix;
9614
9615 gdb_assert (tdesc != NULL);
9616
9617 for (ix = 0;
9618 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9619 ix++)
9620 if (guess->bytes == bytes)
9621 internal_error (__FILE__, __LINE__,
9b20d036 9622 _("Duplicate g packet description added for size %d"),
29709017
DJ
9623 bytes);
9624
9625 new_guess.bytes = bytes;
9626 new_guess.tdesc = tdesc;
9627 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9628}
9629
d962ef82
DJ
9630/* Return 1 if remote_read_description would do anything on this target
9631 and architecture, 0 otherwise. */
9632
9633static int
9634remote_read_description_p (struct target_ops *target)
9635{
9636 struct remote_g_packet_data *data
f5656ead 9637 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
d962ef82
DJ
9638
9639 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9640 return 1;
9641
9642 return 0;
9643}
9644
29709017
DJ
9645static const struct target_desc *
9646remote_read_description (struct target_ops *target)
9647{
9648 struct remote_g_packet_data *data
f5656ead 9649 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
29709017 9650
d962ef82
DJ
9651 /* Do not try this during initial connection, when we do not know
9652 whether there is a running but stopped thread. */
9653 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 9654 return target->beneath->to_read_description (target->beneath);
d962ef82 9655
29709017
DJ
9656 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9657 {
9658 struct remote_g_packet_guess *guess;
9659 int ix;
9660 int bytes = send_g_packet ();
9661
9662 for (ix = 0;
9663 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9664 ix++)
9665 if (guess->bytes == bytes)
9666 return guess->tdesc;
9667
9668 /* We discard the g packet. A minor optimization would be to
9669 hold on to it, and fill the register cache once we have selected
9670 an architecture, but it's too tricky to do safely. */
9671 }
9672
2117c711 9673 return target->beneath->to_read_description (target->beneath);
29709017
DJ
9674}
9675
a6b151f1
DJ
9676/* Remote file transfer support. This is host-initiated I/O, not
9677 target-initiated; for target-initiated, see remote-fileio.c. */
9678
9679/* If *LEFT is at least the length of STRING, copy STRING to
9680 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9681 decrease *LEFT. Otherwise raise an error. */
9682
9683static void
9684remote_buffer_add_string (char **buffer, int *left, char *string)
9685{
9686 int len = strlen (string);
9687
9688 if (len > *left)
9689 error (_("Packet too long for target."));
9690
9691 memcpy (*buffer, string, len);
9692 *buffer += len;
9693 *left -= len;
9694
9695 /* NUL-terminate the buffer as a convenience, if there is
9696 room. */
9697 if (*left)
9698 **buffer = '\0';
9699}
9700
9701/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9702 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9703 decrease *LEFT. Otherwise raise an error. */
9704
9705static void
9706remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9707 int len)
9708{
9709 if (2 * len > *left)
9710 error (_("Packet too long for target."));
9711
9712 bin2hex (bytes, *buffer, len);
9713 *buffer += 2 * len;
9714 *left -= 2 * len;
9715
9716 /* NUL-terminate the buffer as a convenience, if there is
9717 room. */
9718 if (*left)
9719 **buffer = '\0';
9720}
9721
9722/* If *LEFT is large enough, convert VALUE to hex and add it to
9723 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9724 decrease *LEFT. Otherwise raise an error. */
9725
9726static void
9727remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9728{
9729 int len = hexnumlen (value);
9730
9731 if (len > *left)
9732 error (_("Packet too long for target."));
9733
9734 hexnumstr (*buffer, value);
9735 *buffer += len;
9736 *left -= len;
9737
9738 /* NUL-terminate the buffer as a convenience, if there is
9739 room. */
9740 if (*left)
9741 **buffer = '\0';
9742}
9743
9744/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9745 value, *REMOTE_ERRNO to the remote error number or zero if none
9746 was included, and *ATTACHMENT to point to the start of the annex
9747 if any. The length of the packet isn't needed here; there may
9748 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9749
9750 Return 0 if the packet could be parsed, -1 if it could not. If
9751 -1 is returned, the other variables may not be initialized. */
9752
9753static int
9754remote_hostio_parse_result (char *buffer, int *retcode,
9755 int *remote_errno, char **attachment)
9756{
9757 char *p, *p2;
9758
9759 *remote_errno = 0;
9760 *attachment = NULL;
9761
9762 if (buffer[0] != 'F')
9763 return -1;
9764
9765 errno = 0;
9766 *retcode = strtol (&buffer[1], &p, 16);
9767 if (errno != 0 || p == &buffer[1])
9768 return -1;
9769
9770 /* Check for ",errno". */
9771 if (*p == ',')
9772 {
9773 errno = 0;
9774 *remote_errno = strtol (p + 1, &p2, 16);
9775 if (errno != 0 || p + 1 == p2)
9776 return -1;
9777 p = p2;
9778 }
9779
9780 /* Check for ";attachment". If there is no attachment, the
9781 packet should end here. */
9782 if (*p == ';')
9783 {
9784 *attachment = p + 1;
9785 return 0;
9786 }
9787 else if (*p == '\0')
9788 return 0;
9789 else
9790 return -1;
9791}
9792
9793/* Send a prepared I/O packet to the target and read its response.
9794 The prepared packet is in the global RS->BUF before this function
9795 is called, and the answer is there when we return.
9796
9797 COMMAND_BYTES is the length of the request to send, which may include
9798 binary data. WHICH_PACKET is the packet configuration to check
9799 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9800 is set to the error number and -1 is returned. Otherwise the value
9801 returned by the function is returned.
9802
9803 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9804 attachment is expected; an error will be reported if there's a
9805 mismatch. If one is found, *ATTACHMENT will be set to point into
9806 the packet buffer and *ATTACHMENT_LEN will be set to the
9807 attachment's length. */
9808
9809static int
9810remote_hostio_send_command (int command_bytes, int which_packet,
9811 int *remote_errno, char **attachment,
9812 int *attachment_len)
9813{
9814 struct remote_state *rs = get_remote_state ();
9815 int ret, bytes_read;
9816 char *attachment_tmp;
9817
5d93a237 9818 if (!rs->remote_desc
4082afcc 9819 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
9820 {
9821 *remote_errno = FILEIO_ENOSYS;
9822 return -1;
9823 }
9824
9825 putpkt_binary (rs->buf, command_bytes);
9826 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9827
9828 /* If it timed out, something is wrong. Don't try to parse the
9829 buffer. */
9830 if (bytes_read < 0)
9831 {
9832 *remote_errno = FILEIO_EINVAL;
9833 return -1;
9834 }
9835
9836 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9837 {
9838 case PACKET_ERROR:
9839 *remote_errno = FILEIO_EINVAL;
9840 return -1;
9841 case PACKET_UNKNOWN:
9842 *remote_errno = FILEIO_ENOSYS;
9843 return -1;
9844 case PACKET_OK:
9845 break;
9846 }
9847
9848 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9849 &attachment_tmp))
9850 {
9851 *remote_errno = FILEIO_EINVAL;
9852 return -1;
9853 }
9854
9855 /* Make sure we saw an attachment if and only if we expected one. */
9856 if ((attachment_tmp == NULL && attachment != NULL)
9857 || (attachment_tmp != NULL && attachment == NULL))
9858 {
9859 *remote_errno = FILEIO_EINVAL;
9860 return -1;
9861 }
9862
9863 /* If an attachment was found, it must point into the packet buffer;
9864 work out how many bytes there were. */
9865 if (attachment_tmp != NULL)
9866 {
9867 *attachment = attachment_tmp;
9868 *attachment_len = bytes_read - (*attachment - rs->buf);
9869 }
9870
9871 return ret;
9872}
9873
4bd7dc42
GB
9874/* Return nonzero if the filesystem accessed by the target_fileio_*
9875 methods is the local filesystem, zero otherwise. */
9876
9877static int
9878remote_filesystem_is_local (struct target_ops *self)
9879{
9880 return 0;
9881}
9882
a6b151f1
DJ
9883/* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9884 remote file descriptor, or -1 if an error occurs (and set
9885 *REMOTE_ERRNO). */
9886
9887static int
cd897586
TT
9888remote_hostio_open (struct target_ops *self,
9889 const char *filename, int flags, int mode,
a6b151f1
DJ
9890 int *remote_errno)
9891{
9892 struct remote_state *rs = get_remote_state ();
9893 char *p = rs->buf;
9894 int left = get_remote_packet_size () - 1;
9895
9896 remote_buffer_add_string (&p, &left, "vFile:open:");
9897
9898 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9899 strlen (filename));
9900 remote_buffer_add_string (&p, &left, ",");
9901
9902 remote_buffer_add_int (&p, &left, flags);
9903 remote_buffer_add_string (&p, &left, ",");
9904
9905 remote_buffer_add_int (&p, &left, mode);
9906
9907 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9908 remote_errno, NULL, NULL);
9909}
9910
9911/* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9912 Return the number of bytes written, or -1 if an error occurs (and
9913 set *REMOTE_ERRNO). */
9914
9915static int
0d866f62
TT
9916remote_hostio_pwrite (struct target_ops *self,
9917 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
9918 ULONGEST offset, int *remote_errno)
9919{
9920 struct remote_state *rs = get_remote_state ();
9921 char *p = rs->buf;
9922 int left = get_remote_packet_size ();
9923 int out_len;
9924
9925 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9926
9927 remote_buffer_add_int (&p, &left, fd);
9928 remote_buffer_add_string (&p, &left, ",");
9929
9930 remote_buffer_add_int (&p, &left, offset);
9931 remote_buffer_add_string (&p, &left, ",");
9932
bc20a4af 9933 p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
a6b151f1
DJ
9934 get_remote_packet_size () - (p - rs->buf));
9935
9936 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9937 remote_errno, NULL, NULL);
9938}
9939
9940/* Read up to LEN bytes FD on the remote target into READ_BUF
9941 Return the number of bytes read, or -1 if an error occurs (and
9942 set *REMOTE_ERRNO). */
9943
9944static int
a3be983c
TT
9945remote_hostio_pread (struct target_ops *self,
9946 int fd, gdb_byte *read_buf, int len,
a6b151f1
DJ
9947 ULONGEST offset, int *remote_errno)
9948{
9949 struct remote_state *rs = get_remote_state ();
9950 char *p = rs->buf;
9951 char *attachment;
9952 int left = get_remote_packet_size ();
9953 int ret, attachment_len;
9954 int read_len;
9955
9956 remote_buffer_add_string (&p, &left, "vFile:pread:");
9957
9958 remote_buffer_add_int (&p, &left, fd);
9959 remote_buffer_add_string (&p, &left, ",");
9960
9961 remote_buffer_add_int (&p, &left, len);
9962 remote_buffer_add_string (&p, &left, ",");
9963
9964 remote_buffer_add_int (&p, &left, offset);
9965
9966 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9967 remote_errno, &attachment,
9968 &attachment_len);
9969
9970 if (ret < 0)
9971 return ret;
9972
bc20a4af 9973 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
9974 read_buf, len);
9975 if (read_len != ret)
9976 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9977
9978 return ret;
9979}
9980
9981/* Close FD on the remote target. Return 0, or -1 if an error occurs
9982 (and set *REMOTE_ERRNO). */
9983
9984static int
df39ea25 9985remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
9986{
9987 struct remote_state *rs = get_remote_state ();
9988 char *p = rs->buf;
9989 int left = get_remote_packet_size () - 1;
9990
9991 remote_buffer_add_string (&p, &left, "vFile:close:");
9992
9993 remote_buffer_add_int (&p, &left, fd);
9994
9995 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
9996 remote_errno, NULL, NULL);
9997}
9998
9999/* Unlink FILENAME on the remote target. Return 0, or -1 if an error
10000 occurs (and set *REMOTE_ERRNO). */
10001
10002static int
dbbca37d
TT
10003remote_hostio_unlink (struct target_ops *self,
10004 const char *filename, int *remote_errno)
a6b151f1
DJ
10005{
10006 struct remote_state *rs = get_remote_state ();
10007 char *p = rs->buf;
10008 int left = get_remote_packet_size () - 1;
10009
10010 remote_buffer_add_string (&p, &left, "vFile:unlink:");
10011
10012 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10013 strlen (filename));
10014
10015 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10016 remote_errno, NULL, NULL);
10017}
10018
b9e7b9c3
UW
10019/* Read value of symbolic link FILENAME on the remote target. Return
10020 a null-terminated string allocated via xmalloc, or NULL if an error
10021 occurs (and set *REMOTE_ERRNO). */
10022
10023static char *
fab5aa7c
TT
10024remote_hostio_readlink (struct target_ops *self,
10025 const char *filename, int *remote_errno)
b9e7b9c3
UW
10026{
10027 struct remote_state *rs = get_remote_state ();
10028 char *p = rs->buf;
10029 char *attachment;
10030 int left = get_remote_packet_size ();
10031 int len, attachment_len;
10032 int read_len;
10033 char *ret;
10034
10035 remote_buffer_add_string (&p, &left, "vFile:readlink:");
10036
10037 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10038 strlen (filename));
10039
10040 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10041 remote_errno, &attachment,
10042 &attachment_len);
10043
10044 if (len < 0)
10045 return NULL;
10046
10047 ret = xmalloc (len + 1);
10048
bc20a4af
PA
10049 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10050 (gdb_byte *) ret, len);
b9e7b9c3
UW
10051 if (read_len != len)
10052 error (_("Readlink returned %d, but %d bytes."), len, read_len);
10053
10054 ret[len] = '\0';
10055 return ret;
10056}
10057
0a93529c
GB
10058/* Read information about the open file FD on the remote target
10059 into ST. Return 0 on success, or -1 if an error occurs (and
10060 set *REMOTE_ERRNO). */
10061
10062static int
10063remote_hostio_fstat (struct target_ops *self,
10064 int fd, struct stat *st,
10065 int *remote_errno)
10066{
10067 struct remote_state *rs = get_remote_state ();
10068 char *p = rs->buf;
10069 int left = get_remote_packet_size ();
10070 int attachment_len, ret;
10071 char *attachment;
10072 struct fio_stat fst;
10073 int read_len;
10074
464b0089
GB
10075 remote_buffer_add_string (&p, &left, "vFile:fstat:");
10076
10077 remote_buffer_add_int (&p, &left, fd);
10078
10079 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
10080 remote_errno, &attachment,
10081 &attachment_len);
10082 if (ret < 0)
0a93529c 10083 {
464b0089
GB
10084 if (*remote_errno != FILEIO_ENOSYS)
10085 return ret;
10086
0a93529c
GB
10087 /* Strictly we should return -1, ENOSYS here, but when
10088 "set sysroot remote:" was implemented in August 2008
10089 BFD's need for a stat function was sidestepped with
10090 this hack. This was not remedied until March 2015
10091 so we retain the previous behavior to avoid breaking
10092 compatibility.
10093
10094 Note that the memset is a March 2015 addition; older
10095 GDBs set st_size *and nothing else* so the structure
10096 would have garbage in all other fields. This might
10097 break something but retaining the previous behavior
10098 here would be just too wrong. */
10099
10100 memset (st, 0, sizeof (struct stat));
10101 st->st_size = INT_MAX;
10102 return 0;
10103 }
10104
0a93529c
GB
10105 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10106 (gdb_byte *) &fst, sizeof (fst));
10107
10108 if (read_len != ret)
10109 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
10110
10111 if (read_len != sizeof (fst))
10112 error (_("vFile:fstat returned %d bytes, but expecting %d."),
10113 read_len, (int) sizeof (fst));
10114
10115 remote_fileio_to_host_stat (&fst, st);
10116
10117 return 0;
10118}
10119
a6b151f1
DJ
10120static int
10121remote_fileio_errno_to_host (int errnum)
10122{
10123 switch (errnum)
10124 {
10125 case FILEIO_EPERM:
10126 return EPERM;
10127 case FILEIO_ENOENT:
10128 return ENOENT;
10129 case FILEIO_EINTR:
10130 return EINTR;
10131 case FILEIO_EIO:
10132 return EIO;
10133 case FILEIO_EBADF:
10134 return EBADF;
10135 case FILEIO_EACCES:
10136 return EACCES;
10137 case FILEIO_EFAULT:
10138 return EFAULT;
10139 case FILEIO_EBUSY:
10140 return EBUSY;
10141 case FILEIO_EEXIST:
10142 return EEXIST;
10143 case FILEIO_ENODEV:
10144 return ENODEV;
10145 case FILEIO_ENOTDIR:
10146 return ENOTDIR;
10147 case FILEIO_EISDIR:
10148 return EISDIR;
10149 case FILEIO_EINVAL:
10150 return EINVAL;
10151 case FILEIO_ENFILE:
10152 return ENFILE;
10153 case FILEIO_EMFILE:
10154 return EMFILE;
10155 case FILEIO_EFBIG:
10156 return EFBIG;
10157 case FILEIO_ENOSPC:
10158 return ENOSPC;
10159 case FILEIO_ESPIPE:
10160 return ESPIPE;
10161 case FILEIO_EROFS:
10162 return EROFS;
10163 case FILEIO_ENOSYS:
10164 return ENOSYS;
10165 case FILEIO_ENAMETOOLONG:
10166 return ENAMETOOLONG;
10167 }
10168 return -1;
10169}
10170
10171static char *
10172remote_hostio_error (int errnum)
10173{
10174 int host_error = remote_fileio_errno_to_host (errnum);
10175
10176 if (host_error == -1)
10177 error (_("Unknown remote I/O error %d"), errnum);
10178 else
10179 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10180}
10181
a6b151f1
DJ
10182static void
10183remote_hostio_close_cleanup (void *opaque)
10184{
10185 int fd = *(int *) opaque;
10186 int remote_errno;
10187
df39ea25 10188 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
10189}
10190
10191void
10192remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10193{
10194 struct cleanup *back_to, *close_cleanup;
10195 int retcode, fd, remote_errno, bytes, io_size;
10196 FILE *file;
10197 gdb_byte *buffer;
10198 int bytes_in_buffer;
10199 int saw_eof;
10200 ULONGEST offset;
5d93a237 10201 struct remote_state *rs = get_remote_state ();
a6b151f1 10202
5d93a237 10203 if (!rs->remote_desc)
a6b151f1
DJ
10204 error (_("command can only be used with remote target"));
10205
614c279d 10206 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
10207 if (file == NULL)
10208 perror_with_name (local_file);
7c8a8b04 10209 back_to = make_cleanup_fclose (file);
a6b151f1 10210
cd897586
TT
10211 fd = remote_hostio_open (find_target_at (process_stratum),
10212 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1
DJ
10213 | FILEIO_O_TRUNC),
10214 0700, &remote_errno);
10215 if (fd == -1)
10216 remote_hostio_error (remote_errno);
10217
10218 /* Send up to this many bytes at once. They won't all fit in the
10219 remote packet limit, so we'll transfer slightly fewer. */
10220 io_size = get_remote_packet_size ();
10221 buffer = xmalloc (io_size);
10222 make_cleanup (xfree, buffer);
10223
10224 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10225
10226 bytes_in_buffer = 0;
10227 saw_eof = 0;
10228 offset = 0;
10229 while (bytes_in_buffer || !saw_eof)
10230 {
10231 if (!saw_eof)
10232 {
3e43a32a
MS
10233 bytes = fread (buffer + bytes_in_buffer, 1,
10234 io_size - bytes_in_buffer,
a6b151f1
DJ
10235 file);
10236 if (bytes == 0)
10237 {
10238 if (ferror (file))
10239 error (_("Error reading %s."), local_file);
10240 else
10241 {
10242 /* EOF. Unless there is something still in the
10243 buffer from the last iteration, we are done. */
10244 saw_eof = 1;
10245 if (bytes_in_buffer == 0)
10246 break;
10247 }
10248 }
10249 }
10250 else
10251 bytes = 0;
10252
10253 bytes += bytes_in_buffer;
10254 bytes_in_buffer = 0;
10255
0d866f62
TT
10256 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
10257 fd, buffer, bytes,
3e43a32a 10258 offset, &remote_errno);
a6b151f1
DJ
10259
10260 if (retcode < 0)
10261 remote_hostio_error (remote_errno);
10262 else if (retcode == 0)
10263 error (_("Remote write of %d bytes returned 0!"), bytes);
10264 else if (retcode < bytes)
10265 {
10266 /* Short write. Save the rest of the read data for the next
10267 write. */
10268 bytes_in_buffer = bytes - retcode;
10269 memmove (buffer, buffer + retcode, bytes_in_buffer);
10270 }
10271
10272 offset += retcode;
10273 }
10274
10275 discard_cleanups (close_cleanup);
df39ea25 10276 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
10277 remote_hostio_error (remote_errno);
10278
10279 if (from_tty)
10280 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10281 do_cleanups (back_to);
10282}
10283
10284void
10285remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10286{
10287 struct cleanup *back_to, *close_cleanup;
cea39f65 10288 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
10289 FILE *file;
10290 gdb_byte *buffer;
10291 ULONGEST offset;
5d93a237 10292 struct remote_state *rs = get_remote_state ();
a6b151f1 10293
5d93a237 10294 if (!rs->remote_desc)
a6b151f1
DJ
10295 error (_("command can only be used with remote target"));
10296
cd897586
TT
10297 fd = remote_hostio_open (find_target_at (process_stratum),
10298 remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
a6b151f1
DJ
10299 if (fd == -1)
10300 remote_hostio_error (remote_errno);
10301
614c279d 10302 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
10303 if (file == NULL)
10304 perror_with_name (local_file);
7c8a8b04 10305 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
10306
10307 /* Send up to this many bytes at once. They won't all fit in the
10308 remote packet limit, so we'll transfer slightly fewer. */
10309 io_size = get_remote_packet_size ();
10310 buffer = xmalloc (io_size);
10311 make_cleanup (xfree, buffer);
10312
10313 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10314
10315 offset = 0;
10316 while (1)
10317 {
a3be983c
TT
10318 bytes = remote_hostio_pread (find_target_at (process_stratum),
10319 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
10320 if (bytes == 0)
10321 /* Success, but no bytes, means end-of-file. */
10322 break;
10323 if (bytes == -1)
10324 remote_hostio_error (remote_errno);
10325
10326 offset += bytes;
10327
10328 bytes = fwrite (buffer, 1, bytes, file);
10329 if (bytes == 0)
10330 perror_with_name (local_file);
10331 }
10332
10333 discard_cleanups (close_cleanup);
df39ea25 10334 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
10335 remote_hostio_error (remote_errno);
10336
10337 if (from_tty)
10338 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10339 do_cleanups (back_to);
10340}
10341
10342void
10343remote_file_delete (const char *remote_file, int from_tty)
10344{
10345 int retcode, remote_errno;
5d93a237 10346 struct remote_state *rs = get_remote_state ();
a6b151f1 10347
5d93a237 10348 if (!rs->remote_desc)
a6b151f1
DJ
10349 error (_("command can only be used with remote target"));
10350
dbbca37d
TT
10351 retcode = remote_hostio_unlink (find_target_at (process_stratum),
10352 remote_file, &remote_errno);
a6b151f1
DJ
10353 if (retcode == -1)
10354 remote_hostio_error (remote_errno);
10355
10356 if (from_tty)
10357 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10358}
10359
10360static void
10361remote_put_command (char *args, int from_tty)
10362{
10363 struct cleanup *back_to;
10364 char **argv;
10365
d1a41061
PP
10366 if (args == NULL)
10367 error_no_arg (_("file to put"));
10368
10369 argv = gdb_buildargv (args);
a6b151f1
DJ
10370 back_to = make_cleanup_freeargv (argv);
10371 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10372 error (_("Invalid parameters to remote put"));
10373
10374 remote_file_put (argv[0], argv[1], from_tty);
10375
10376 do_cleanups (back_to);
10377}
10378
10379static void
10380remote_get_command (char *args, int from_tty)
10381{
10382 struct cleanup *back_to;
10383 char **argv;
10384
d1a41061
PP
10385 if (args == NULL)
10386 error_no_arg (_("file to get"));
10387
10388 argv = gdb_buildargv (args);
a6b151f1
DJ
10389 back_to = make_cleanup_freeargv (argv);
10390 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10391 error (_("Invalid parameters to remote get"));
10392
10393 remote_file_get (argv[0], argv[1], from_tty);
10394
10395 do_cleanups (back_to);
10396}
10397
10398static void
10399remote_delete_command (char *args, int from_tty)
10400{
10401 struct cleanup *back_to;
10402 char **argv;
10403
d1a41061
PP
10404 if (args == NULL)
10405 error_no_arg (_("file to delete"));
10406
10407 argv = gdb_buildargv (args);
a6b151f1
DJ
10408 back_to = make_cleanup_freeargv (argv);
10409 if (argv[0] == NULL || argv[1] != NULL)
10410 error (_("Invalid parameters to remote delete"));
10411
10412 remote_file_delete (argv[0], from_tty);
10413
10414 do_cleanups (back_to);
10415}
10416
10417static void
10418remote_command (char *args, int from_tty)
10419{
635c7e8a 10420 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
10421}
10422
b2175913 10423static int
19db3e69 10424remote_can_execute_reverse (struct target_ops *self)
b2175913 10425{
4082afcc
PA
10426 if (packet_support (PACKET_bs) == PACKET_ENABLE
10427 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
10428 return 1;
10429 else
10430 return 0;
b2175913
MS
10431}
10432
74531fed 10433static int
2a9a2795 10434remote_supports_non_stop (struct target_ops *self)
74531fed
PA
10435{
10436 return 1;
10437}
10438
03583c20 10439static int
2bfc0540 10440remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
10441{
10442 /* Only supported in extended mode. */
10443 return 0;
10444}
10445
8a305172 10446static int
86ce2668 10447remote_supports_multi_process (struct target_ops *self)
8a305172
PA
10448{
10449 struct remote_state *rs = get_remote_state ();
a744cf53 10450
901f9912
UW
10451 /* Only extended-remote handles being attached to multiple
10452 processes, even though plain remote can use the multi-process
10453 thread id extensions, so that GDB knows the target process's
10454 PID. */
10455 return rs->extended && remote_multi_process_p (rs);
8a305172
PA
10456}
10457
70221824 10458static int
782b2b07
SS
10459remote_supports_cond_tracepoints (void)
10460{
4082afcc 10461 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
10462}
10463
3788aec7 10464static int
efcc2da7 10465remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 10466{
4082afcc 10467 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
10468}
10469
70221824 10470static int
7a697b8d
SS
10471remote_supports_fast_tracepoints (void)
10472{
4082afcc 10473 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
10474}
10475
0fb4aa4b
PA
10476static int
10477remote_supports_static_tracepoints (void)
10478{
4082afcc 10479 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
10480}
10481
1e4d1764
YQ
10482static int
10483remote_supports_install_in_trace (void)
10484{
4082afcc 10485 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
10486}
10487
d248b706 10488static int
7d178d6a 10489remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 10490{
4082afcc
PA
10491 return (packet_support (PACKET_EnableDisableTracepoints_feature)
10492 == PACKET_ENABLE);
d248b706
KY
10493}
10494
3065dfb6 10495static int
6de37a3a 10496remote_supports_string_tracing (struct target_ops *self)
3065dfb6 10497{
4082afcc 10498 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
10499}
10500
d3ce09f5 10501static int
78eff0ec 10502remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 10503{
4082afcc 10504 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
10505}
10506
35b1e5cc 10507static void
ecae04e1 10508remote_trace_init (struct target_ops *self)
35b1e5cc
SS
10509{
10510 putpkt ("QTinit");
10511 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 10512 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
10513 error (_("Target does not support this command."));
10514}
10515
10516static void free_actions_list (char **actions_list);
10517static void free_actions_list_cleanup_wrapper (void *);
10518static void
10519free_actions_list_cleanup_wrapper (void *al)
10520{
10521 free_actions_list (al);
10522}
10523
10524static void
10525free_actions_list (char **actions_list)
10526{
10527 int ndx;
10528
10529 if (actions_list == 0)
10530 return;
10531
10532 for (ndx = 0; actions_list[ndx]; ndx++)
10533 xfree (actions_list[ndx]);
10534
10535 xfree (actions_list);
10536}
10537
409873ef
SS
10538/* Recursive routine to walk through command list including loops, and
10539 download packets for each command. */
10540
10541static void
10542remote_download_command_source (int num, ULONGEST addr,
10543 struct command_line *cmds)
10544{
10545 struct remote_state *rs = get_remote_state ();
10546 struct command_line *cmd;
10547
10548 for (cmd = cmds; cmd; cmd = cmd->next)
10549 {
0df8b418 10550 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
10551 strcpy (rs->buf, "QTDPsrc:");
10552 encode_source_string (num, addr, "cmd", cmd->line,
10553 rs->buf + strlen (rs->buf),
10554 rs->buf_size - strlen (rs->buf));
10555 putpkt (rs->buf);
10556 remote_get_noisy_reply (&target_buf, &target_buf_size);
10557 if (strcmp (target_buf, "OK"))
10558 warning (_("Target does not support source download."));
10559
10560 if (cmd->control_type == while_control
10561 || cmd->control_type == while_stepping_control)
10562 {
10563 remote_download_command_source (num, addr, *cmd->body_list);
10564
0df8b418 10565 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
10566 strcpy (rs->buf, "QTDPsrc:");
10567 encode_source_string (num, addr, "cmd", "end",
10568 rs->buf + strlen (rs->buf),
10569 rs->buf_size - strlen (rs->buf));
10570 putpkt (rs->buf);
10571 remote_get_noisy_reply (&target_buf, &target_buf_size);
10572 if (strcmp (target_buf, "OK"))
10573 warning (_("Target does not support source download."));
10574 }
10575 }
10576}
10577
35b1e5cc 10578static void
548f7808 10579remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 10580{
bba74b36 10581#define BUF_SIZE 2048
e8ba3115 10582
35b1e5cc 10583 CORE_ADDR tpaddr;
409873ef 10584 char addrbuf[40];
bba74b36 10585 char buf[BUF_SIZE];
35b1e5cc
SS
10586 char **tdp_actions;
10587 char **stepping_actions;
10588 int ndx;
10589 struct cleanup *old_chain = NULL;
10590 struct agent_expr *aexpr;
10591 struct cleanup *aexpr_chain = NULL;
10592 char *pkt;
e8ba3115 10593 struct breakpoint *b = loc->owner;
d9b3f62e 10594 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 10595
dc673c81 10596 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
10597 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10598 tdp_actions);
10599 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10600 stepping_actions);
10601
10602 tpaddr = loc->address;
10603 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
10604 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10605 addrbuf, /* address */
10606 (b->enable_state == bp_enabled ? 'E' : 'D'),
10607 t->step_count, t->pass_count);
e8ba3115
YQ
10608 /* Fast tracepoints are mostly handled by the target, but we can
10609 tell the target how big of an instruction block should be moved
10610 around. */
10611 if (b->type == bp_fast_tracepoint)
10612 {
10613 /* Only test for support at download time; we may not know
10614 target capabilities at definition time. */
10615 if (remote_supports_fast_tracepoints ())
35b1e5cc 10616 {
e8ba3115 10617 int isize;
35b1e5cc 10618
f5656ead 10619 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
e8ba3115 10620 tpaddr, &isize, NULL))
bba74b36
YQ
10621 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10622 isize);
35b1e5cc 10623 else
e8ba3115
YQ
10624 /* If it passed validation at definition but fails now,
10625 something is very wrong. */
10626 internal_error (__FILE__, __LINE__,
10627 _("Fast tracepoint not "
10628 "valid during download"));
35b1e5cc 10629 }
e8ba3115
YQ
10630 else
10631 /* Fast tracepoints are functionally identical to regular
10632 tracepoints, so don't take lack of support as a reason to
10633 give up on the trace run. */
10634 warning (_("Target does not support fast tracepoints, "
10635 "downloading %d as regular tracepoint"), b->number);
10636 }
10637 else if (b->type == bp_static_tracepoint)
10638 {
10639 /* Only test for support at download time; we may not know
10640 target capabilities at definition time. */
10641 if (remote_supports_static_tracepoints ())
0fb4aa4b 10642 {
e8ba3115 10643 struct static_tracepoint_marker marker;
0fb4aa4b 10644
e8ba3115
YQ
10645 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10646 strcat (buf, ":S");
0fb4aa4b 10647 else
e8ba3115 10648 error (_("Static tracepoint not valid during download"));
0fb4aa4b 10649 }
e8ba3115
YQ
10650 else
10651 /* Fast tracepoints are functionally identical to regular
10652 tracepoints, so don't take lack of support as a reason
10653 to give up on the trace run. */
10654 error (_("Target does not support static tracepoints"));
10655 }
10656 /* If the tracepoint has a conditional, make it into an agent
10657 expression and append to the definition. */
10658 if (loc->cond)
10659 {
10660 /* Only test support at download time, we may not know target
10661 capabilities at definition time. */
10662 if (remote_supports_cond_tracepoints ())
35b1e5cc 10663 {
e8ba3115
YQ
10664 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10665 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
10666 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10667 aexpr->len);
e8ba3115
YQ
10668 pkt = buf + strlen (buf);
10669 for (ndx = 0; ndx < aexpr->len; ++ndx)
10670 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10671 *pkt = '\0';
10672 do_cleanups (aexpr_chain);
35b1e5cc 10673 }
e8ba3115
YQ
10674 else
10675 warning (_("Target does not support conditional tracepoints, "
10676 "ignoring tp %d cond"), b->number);
10677 }
35b1e5cc 10678
d9b3f62e 10679 if (b->commands || *default_collect)
e8ba3115
YQ
10680 strcat (buf, "-");
10681 putpkt (buf);
10682 remote_get_noisy_reply (&target_buf, &target_buf_size);
10683 if (strcmp (target_buf, "OK"))
10684 error (_("Target does not support tracepoints."));
35b1e5cc 10685
e8ba3115
YQ
10686 /* do_single_steps (t); */
10687 if (tdp_actions)
10688 {
10689 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 10690 {
e8ba3115 10691 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
10692 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10693 b->number, addrbuf, /* address */
10694 tdp_actions[ndx],
10695 ((tdp_actions[ndx + 1] || stepping_actions)
10696 ? '-' : 0));
e8ba3115
YQ
10697 putpkt (buf);
10698 remote_get_noisy_reply (&target_buf,
10699 &target_buf_size);
10700 if (strcmp (target_buf, "OK"))
10701 error (_("Error on target while setting tracepoints."));
35b1e5cc 10702 }
e8ba3115
YQ
10703 }
10704 if (stepping_actions)
10705 {
10706 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 10707 {
e8ba3115 10708 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
10709 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10710 b->number, addrbuf, /* address */
10711 ((ndx == 0) ? "S" : ""),
10712 stepping_actions[ndx],
10713 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
10714 putpkt (buf);
10715 remote_get_noisy_reply (&target_buf,
10716 &target_buf_size);
10717 if (strcmp (target_buf, "OK"))
10718 error (_("Error on target while setting tracepoints."));
35b1e5cc 10719 }
e8ba3115 10720 }
409873ef 10721
4082afcc 10722 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115
YQ
10723 {
10724 if (b->addr_string)
409873ef 10725 {
e8ba3115
YQ
10726 strcpy (buf, "QTDPsrc:");
10727 encode_source_string (b->number, loc->address,
10728 "at", b->addr_string, buf + strlen (buf),
10729 2048 - strlen (buf));
409873ef 10730
e8ba3115
YQ
10731 putpkt (buf);
10732 remote_get_noisy_reply (&target_buf, &target_buf_size);
10733 if (strcmp (target_buf, "OK"))
10734 warning (_("Target does not support source download."));
409873ef 10735 }
e8ba3115
YQ
10736 if (b->cond_string)
10737 {
10738 strcpy (buf, "QTDPsrc:");
10739 encode_source_string (b->number, loc->address,
10740 "cond", b->cond_string, buf + strlen (buf),
10741 2048 - strlen (buf));
10742 putpkt (buf);
10743 remote_get_noisy_reply (&target_buf, &target_buf_size);
10744 if (strcmp (target_buf, "OK"))
10745 warning (_("Target does not support source download."));
10746 }
10747 remote_download_command_source (b->number, loc->address,
10748 breakpoint_commands (b));
35b1e5cc 10749 }
e8ba3115
YQ
10750
10751 do_cleanups (old_chain);
35b1e5cc
SS
10752}
10753
1e4d1764 10754static int
a52a8357 10755remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 10756{
1e51243a
PA
10757 struct remote_state *rs = get_remote_state ();
10758 struct trace_status *ts;
10759 int status;
10760
10761 /* Don't try to install tracepoints until we've relocated our
10762 symbols, and fetched and merged the target's tracepoint list with
10763 ours. */
10764 if (rs->starting_up)
10765 return 0;
10766
10767 ts = current_trace_status ();
8bd200f1 10768 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
10769
10770 if (status == -1 || !ts->running_known || !ts->running)
10771 return 0;
10772
10773 /* If we are in a tracing experiment, but remote stub doesn't support
10774 installing tracepoint in trace, we have to return. */
10775 if (!remote_supports_install_in_trace ())
10776 return 0;
10777
10778 return 1;
10779}
10780
10781
35b1e5cc 10782static void
559d2b81
TT
10783remote_download_trace_state_variable (struct target_ops *self,
10784 struct trace_state_variable *tsv)
35b1e5cc
SS
10785{
10786 struct remote_state *rs = get_remote_state ();
00bf0b85 10787 char *p;
35b1e5cc 10788
bba74b36
YQ
10789 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10790 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10791 tsv->builtin);
00bf0b85
SS
10792 p = rs->buf + strlen (rs->buf);
10793 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10794 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 10795 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 10796 *p++ = '\0';
35b1e5cc
SS
10797 putpkt (rs->buf);
10798 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
10799 if (*target_buf == '\0')
10800 error (_("Target does not support this command."));
10801 if (strcmp (target_buf, "OK") != 0)
10802 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
10803}
10804
d248b706 10805static void
46670d57
TT
10806remote_enable_tracepoint (struct target_ops *self,
10807 struct bp_location *location)
d248b706
KY
10808{
10809 struct remote_state *rs = get_remote_state ();
10810 char addr_buf[40];
10811
10812 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
10813 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10814 location->owner->number, addr_buf);
d248b706
KY
10815 putpkt (rs->buf);
10816 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10817 if (*rs->buf == '\0')
10818 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10819 if (strcmp (rs->buf, "OK") != 0)
10820 error (_("Error on target while enabling tracepoint."));
10821}
10822
10823static void
780b049c
TT
10824remote_disable_tracepoint (struct target_ops *self,
10825 struct bp_location *location)
d248b706
KY
10826{
10827 struct remote_state *rs = get_remote_state ();
10828 char addr_buf[40];
10829
10830 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
10831 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10832 location->owner->number, addr_buf);
d248b706
KY
10833 putpkt (rs->buf);
10834 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10835 if (*rs->buf == '\0')
10836 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10837 if (strcmp (rs->buf, "OK") != 0)
10838 error (_("Error on target while disabling tracepoint."));
10839}
10840
35b1e5cc 10841static void
583f9a86 10842remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
10843{
10844 asection *s;
81b9b86e 10845 bfd *abfd = NULL;
35b1e5cc 10846 bfd_size_type size;
608bcef2 10847 bfd_vma vma;
35b1e5cc 10848 int anysecs = 0;
c2fa21f1 10849 int offset = 0;
35b1e5cc
SS
10850
10851 if (!exec_bfd)
10852 return; /* No information to give. */
10853
10854 strcpy (target_buf, "QTro");
9779ab84 10855 offset = strlen (target_buf);
35b1e5cc
SS
10856 for (s = exec_bfd->sections; s; s = s->next)
10857 {
10858 char tmp1[40], tmp2[40];
c2fa21f1 10859 int sec_length;
35b1e5cc
SS
10860
10861 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 10862 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
10863 (s->flags & SEC_READONLY) == 0)
10864 continue;
10865
10866 anysecs = 1;
81b9b86e 10867 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 10868 size = bfd_get_section_size (s);
608bcef2
HZ
10869 sprintf_vma (tmp1, vma);
10870 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
10871 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10872 if (offset + sec_length + 1 > target_buf_size)
10873 {
4082afcc 10874 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 10875 warning (_("\
c2fa21f1
HZ
10876Too many sections for read-only sections definition packet."));
10877 break;
10878 }
bba74b36
YQ
10879 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10880 tmp1, tmp2);
c2fa21f1 10881 offset += sec_length;
35b1e5cc
SS
10882 }
10883 if (anysecs)
10884 {
10885 putpkt (target_buf);
10886 getpkt (&target_buf, &target_buf_size, 0);
10887 }
10888}
10889
10890static void
e2d1aae3 10891remote_trace_start (struct target_ops *self)
35b1e5cc
SS
10892{
10893 putpkt ("QTStart");
10894 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
10895 if (*target_buf == '\0')
10896 error (_("Target does not support this command."));
10897 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
10898 error (_("Bogus reply from target: %s"), target_buf);
10899}
10900
10901static int
8bd200f1 10902remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 10903{
953b98d1 10904 /* Initialize it just to avoid a GCC false warning. */
f652de6f 10905 char *p = NULL;
0df8b418 10906 /* FIXME we need to get register block size some other way. */
00bf0b85 10907 extern int trace_regblock_size;
bd3eecc3
PA
10908 enum packet_result result;
10909
4082afcc 10910 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 10911 return -1;
a744cf53 10912
00bf0b85
SS
10913 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10914
049dc89b
JK
10915 putpkt ("qTStatus");
10916
492d29ea 10917 TRY
67f41397
JK
10918 {
10919 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10920 }
492d29ea 10921 CATCH (ex, RETURN_MASK_ERROR)
67f41397 10922 {
598d3636
JK
10923 if (ex.error != TARGET_CLOSE_ERROR)
10924 {
10925 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10926 return -1;
10927 }
10928 throw_exception (ex);
67f41397 10929 }
492d29ea 10930 END_CATCH
00bf0b85 10931
bd3eecc3
PA
10932 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
10933
00bf0b85 10934 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 10935 if (result == PACKET_UNKNOWN)
00bf0b85 10936 return -1;
35b1e5cc 10937
00bf0b85 10938 /* We're working with a live target. */
f5911ea1 10939 ts->filename = NULL;
00bf0b85 10940
00bf0b85 10941 if (*p++ != 'T')
35b1e5cc
SS
10942 error (_("Bogus trace status reply from target: %s"), target_buf);
10943
84cebc4a
YQ
10944 /* Function 'parse_trace_status' sets default value of each field of
10945 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
10946 parse_trace_status (p, ts);
10947
10948 return ts->running;
35b1e5cc
SS
10949}
10950
70221824 10951static void
db90e85c 10952remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
10953 struct uploaded_tp *utp)
10954{
10955 struct remote_state *rs = get_remote_state ();
f196051f
SS
10956 char *reply;
10957 struct bp_location *loc;
10958 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 10959 size_t size = get_remote_packet_size ();
f196051f
SS
10960
10961 if (tp)
10962 {
10963 tp->base.hit_count = 0;
10964 tp->traceframe_usage = 0;
10965 for (loc = tp->base.loc; loc; loc = loc->next)
10966 {
10967 /* If the tracepoint was never downloaded, don't go asking for
10968 any status. */
10969 if (tp->number_on_target == 0)
10970 continue;
bba74b36
YQ
10971 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
10972 phex_nz (loc->address, 0));
f196051f
SS
10973 putpkt (rs->buf);
10974 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10975 if (reply && *reply)
10976 {
10977 if (*reply == 'V')
10978 parse_tracepoint_status (reply + 1, bp, utp);
10979 }
10980 }
10981 }
10982 else if (utp)
10983 {
10984 utp->hit_count = 0;
10985 utp->traceframe_usage = 0;
bba74b36
YQ
10986 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
10987 phex_nz (utp->addr, 0));
f196051f
SS
10988 putpkt (rs->buf);
10989 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10990 if (reply && *reply)
10991 {
10992 if (*reply == 'V')
10993 parse_tracepoint_status (reply + 1, bp, utp);
10994 }
10995 }
10996}
10997
35b1e5cc 10998static void
74499f1b 10999remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
11000{
11001 putpkt ("QTStop");
11002 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11003 if (*target_buf == '\0')
11004 error (_("Target does not support this command."));
11005 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11006 error (_("Bogus reply from target: %s"), target_buf);
11007}
11008
11009static int
bd4c6793
TT
11010remote_trace_find (struct target_ops *self,
11011 enum trace_find_type type, int num,
cc5925ad 11012 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
11013 int *tpp)
11014{
11015 struct remote_state *rs = get_remote_state ();
bba74b36 11016 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
11017 char *p, *reply;
11018 int target_frameno = -1, target_tracept = -1;
11019
e6e4e701
PA
11020 /* Lookups other than by absolute frame number depend on the current
11021 trace selected, so make sure it is correct on the remote end
11022 first. */
11023 if (type != tfind_number)
11024 set_remote_traceframe ();
11025
35b1e5cc
SS
11026 p = rs->buf;
11027 strcpy (p, "QTFrame:");
11028 p = strchr (p, '\0');
11029 switch (type)
11030 {
11031 case tfind_number:
bba74b36 11032 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
11033 break;
11034 case tfind_pc:
bba74b36 11035 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
11036 break;
11037 case tfind_tp:
bba74b36 11038 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
11039 break;
11040 case tfind_range:
bba74b36
YQ
11041 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11042 phex_nz (addr2, 0));
35b1e5cc
SS
11043 break;
11044 case tfind_outside:
bba74b36
YQ
11045 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11046 phex_nz (addr2, 0));
35b1e5cc
SS
11047 break;
11048 default:
9b20d036 11049 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
11050 }
11051
11052 putpkt (rs->buf);
2f65bcb7 11053 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
11054 if (*reply == '\0')
11055 error (_("Target does not support this command."));
35b1e5cc
SS
11056
11057 while (reply && *reply)
11058 switch (*reply)
11059 {
11060 case 'F':
f197e0f1
VP
11061 p = ++reply;
11062 target_frameno = (int) strtol (p, &reply, 16);
11063 if (reply == p)
11064 error (_("Unable to parse trace frame number"));
e6e4e701
PA
11065 /* Don't update our remote traceframe number cache on failure
11066 to select a remote traceframe. */
f197e0f1
VP
11067 if (target_frameno == -1)
11068 return -1;
35b1e5cc
SS
11069 break;
11070 case 'T':
f197e0f1
VP
11071 p = ++reply;
11072 target_tracept = (int) strtol (p, &reply, 16);
11073 if (reply == p)
11074 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
11075 break;
11076 case 'O': /* "OK"? */
11077 if (reply[1] == 'K' && reply[2] == '\0')
11078 reply += 2;
11079 else
11080 error (_("Bogus reply from target: %s"), reply);
11081 break;
11082 default:
11083 error (_("Bogus reply from target: %s"), reply);
11084 }
11085 if (tpp)
11086 *tpp = target_tracept;
e6e4e701 11087
262e1174 11088 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
11089 return target_frameno;
11090}
11091
11092static int
4011015b
TT
11093remote_get_trace_state_variable_value (struct target_ops *self,
11094 int tsvnum, LONGEST *val)
35b1e5cc
SS
11095{
11096 struct remote_state *rs = get_remote_state ();
11097 char *reply;
11098 ULONGEST uval;
11099
e6e4e701
PA
11100 set_remote_traceframe ();
11101
bba74b36 11102 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
11103 putpkt (rs->buf);
11104 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11105 if (reply && *reply)
11106 {
11107 if (*reply == 'V')
11108 {
11109 unpack_varlen_hex (reply + 1, &uval);
11110 *val = (LONGEST) uval;
11111 return 1;
11112 }
11113 }
11114 return 0;
11115}
11116
00bf0b85 11117static int
dc3decaf 11118remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
11119{
11120 struct remote_state *rs = get_remote_state ();
11121 char *p, *reply;
11122
11123 p = rs->buf;
11124 strcpy (p, "QTSave:");
11125 p += strlen (p);
11126 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11127 error (_("Remote file name too long for trace save packet"));
9f1b45b0 11128 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
11129 *p++ = '\0';
11130 putpkt (rs->buf);
ad91cd99 11131 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 11132 if (*reply == '\0')
ad91cd99
PA
11133 error (_("Target does not support this command."));
11134 if (strcmp (reply, "OK") != 0)
11135 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
11136 return 0;
11137}
11138
11139/* This is basically a memory transfer, but needs to be its own packet
11140 because we don't know how the target actually organizes its trace
11141 memory, plus we want to be able to ask for as much as possible, but
11142 not be unhappy if we don't get as much as we ask for. */
11143
11144static LONGEST
88ee6f45
TT
11145remote_get_raw_trace_data (struct target_ops *self,
11146 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
11147{
11148 struct remote_state *rs = get_remote_state ();
11149 char *reply;
11150 char *p;
11151 int rslt;
11152
11153 p = rs->buf;
11154 strcpy (p, "qTBuffer:");
11155 p += strlen (p);
11156 p += hexnumstr (p, offset);
11157 *p++ = ',';
11158 p += hexnumstr (p, len);
11159 *p++ = '\0';
11160
11161 putpkt (rs->buf);
11162 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11163 if (reply && *reply)
11164 {
11165 /* 'l' by itself means we're at the end of the buffer and
11166 there is nothing more to get. */
11167 if (*reply == 'l')
11168 return 0;
11169
11170 /* Convert the reply into binary. Limit the number of bytes to
11171 convert according to our passed-in buffer size, rather than
11172 what was returned in the packet; if the target is
11173 unexpectedly generous and gives us a bigger reply than we
11174 asked for, we don't want to crash. */
11175 rslt = hex2bin (target_buf, buf, len);
11176 return rslt;
11177 }
11178
11179 /* Something went wrong, flag as an error. */
11180 return -1;
11181}
11182
35b1e5cc 11183static void
37b25738 11184remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
11185{
11186 struct remote_state *rs = get_remote_state ();
11187
4082afcc 11188 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 11189 {
ad91cd99
PA
11190 char *reply;
11191
bba74b36 11192 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 11193 putpkt (rs->buf);
ad91cd99
PA
11194 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11195 if (*reply == '\0')
33da3f1c 11196 error (_("Target does not support this command."));
ad91cd99
PA
11197 if (strcmp (reply, "OK") != 0)
11198 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
11199 }
11200 else if (val)
11201 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
11202}
11203
dc146f7c
VP
11204static int
11205remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11206{
11207 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 11208
fe978cb0
PA
11209 if (info && info->priv)
11210 return info->priv->core;
dc146f7c
VP
11211 return -1;
11212}
11213
4daf5ac0 11214static void
736d5b1f 11215remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
11216{
11217 struct remote_state *rs = get_remote_state ();
ad91cd99 11218 char *reply;
4daf5ac0 11219
bba74b36 11220 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 11221 putpkt (rs->buf);
ad91cd99
PA
11222 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11223 if (*reply == '\0')
4daf5ac0 11224 error (_("Target does not support this command."));
ad91cd99
PA
11225 if (strcmp (reply, "OK") != 0)
11226 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
11227}
11228
b3b9301e 11229static struct traceframe_info *
a893e81f 11230remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
11231{
11232 char *text;
11233
11234 text = target_read_stralloc (&current_target,
11235 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11236 if (text != NULL)
11237 {
11238 struct traceframe_info *info;
11239 struct cleanup *back_to = make_cleanup (xfree, text);
11240
11241 info = parse_traceframe_info (text);
11242 do_cleanups (back_to);
11243 return info;
11244 }
11245
11246 return NULL;
11247}
11248
405f8e94
SS
11249/* Handle the qTMinFTPILen packet. Returns the minimum length of
11250 instruction on which a fast tracepoint may be placed. Returns -1
11251 if the packet is not supported, and 0 if the minimum instruction
11252 length is unknown. */
11253
11254static int
0e67620a 11255remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
11256{
11257 struct remote_state *rs = get_remote_state ();
11258 char *reply;
11259
e886a173
PA
11260 /* If we're not debugging a process yet, the IPA can't be
11261 loaded. */
11262 if (!target_has_execution)
11263 return 0;
11264
11265 /* Make sure the remote is pointing at the right process. */
11266 set_general_process ();
11267
bba74b36 11268 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
11269 putpkt (rs->buf);
11270 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11271 if (*reply == '\0')
11272 return -1;
11273 else
11274 {
11275 ULONGEST min_insn_len;
11276
11277 unpack_varlen_hex (reply, &min_insn_len);
11278
11279 return (int) min_insn_len;
11280 }
11281}
11282
f6f899bf 11283static void
4da384be 11284remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 11285{
4082afcc 11286 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
11287 {
11288 struct remote_state *rs = get_remote_state ();
11289 char *buf = rs->buf;
11290 char *endbuf = rs->buf + get_remote_packet_size ();
11291 enum packet_result result;
11292
11293 gdb_assert (val >= 0 || val == -1);
11294 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11295 /* Send -1 as literal "-1" to avoid host size dependency. */
11296 if (val < 0)
11297 {
11298 *buf++ = '-';
11299 buf += hexnumstr (buf, (ULONGEST) -val);
11300 }
11301 else
11302 buf += hexnumstr (buf, (ULONGEST) val);
11303
11304 putpkt (rs->buf);
11305 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11306 result = packet_ok (rs->buf,
11307 &remote_protocol_packets[PACKET_QTBuffer_size]);
11308
11309 if (result != PACKET_OK)
11310 warning (_("Bogus reply from target: %s"), rs->buf);
11311 }
11312}
11313
f196051f 11314static int
d9e68a2c
TT
11315remote_set_trace_notes (struct target_ops *self,
11316 const char *user, const char *notes,
ca623f82 11317 const char *stop_notes)
f196051f
SS
11318{
11319 struct remote_state *rs = get_remote_state ();
11320 char *reply;
11321 char *buf = rs->buf;
11322 char *endbuf = rs->buf + get_remote_packet_size ();
11323 int nbytes;
11324
11325 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11326 if (user)
11327 {
11328 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 11329 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
11330 buf += 2 * nbytes;
11331 *buf++ = ';';
11332 }
11333 if (notes)
11334 {
11335 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 11336 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
11337 buf += 2 * nbytes;
11338 *buf++ = ';';
11339 }
11340 if (stop_notes)
11341 {
11342 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 11343 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
11344 buf += 2 * nbytes;
11345 *buf++ = ';';
11346 }
11347 /* Ensure the buffer is terminated. */
11348 *buf = '\0';
11349
11350 putpkt (rs->buf);
11351 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11352 if (*reply == '\0')
11353 return 0;
11354
11355 if (strcmp (reply, "OK") != 0)
11356 error (_("Bogus reply from target: %s"), reply);
11357
11358 return 1;
11359}
11360
d1feda86 11361static int
2c152180 11362remote_use_agent (struct target_ops *self, int use)
d1feda86 11363{
4082afcc 11364 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
11365 {
11366 struct remote_state *rs = get_remote_state ();
11367
11368 /* If the stub supports QAgent. */
bba74b36 11369 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
11370 putpkt (rs->buf);
11371 getpkt (&rs->buf, &rs->buf_size, 0);
11372
11373 if (strcmp (rs->buf, "OK") == 0)
11374 {
11375 use_agent = use;
11376 return 1;
11377 }
11378 }
11379
11380 return 0;
11381}
11382
11383static int
fe38f897 11384remote_can_use_agent (struct target_ops *self)
d1feda86 11385{
4082afcc 11386 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
11387}
11388
9accd112
MM
11389struct btrace_target_info
11390{
11391 /* The ptid of the traced thread. */
11392 ptid_t ptid;
f4abbc16
MM
11393
11394 /* The obtained branch trace configuration. */
11395 struct btrace_config conf;
9accd112
MM
11396};
11397
f4abbc16
MM
11398/* Reset our idea of our target's btrace configuration. */
11399
11400static void
11401remote_btrace_reset (void)
11402{
11403 struct remote_state *rs = get_remote_state ();
11404
11405 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
11406}
11407
9accd112
MM
11408/* Check whether the target supports branch tracing. */
11409
11410static int
043c3577 11411remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 11412{
4082afcc 11413 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 11414 return 0;
4082afcc 11415 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
11416 return 0;
11417
043c3577
MM
11418 switch (format)
11419 {
11420 case BTRACE_FORMAT_NONE:
11421 return 0;
11422
11423 case BTRACE_FORMAT_BTS:
11424 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
11425 }
11426
11427 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
11428}
11429
f4abbc16
MM
11430/* Synchronize the configuration with the target. */
11431
11432static void
11433btrace_sync_conf (const struct btrace_config *conf)
11434{
d33501a5
MM
11435 struct packet_config *packet;
11436 struct remote_state *rs;
11437 char *buf, *pos, *endbuf;
11438
11439 rs = get_remote_state ();
11440 buf = rs->buf;
11441 endbuf = buf + get_remote_packet_size ();
11442
11443 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
11444 if (packet_config_support (packet) == PACKET_ENABLE
11445 && conf->bts.size != rs->btrace_config.bts.size)
11446 {
11447 pos = buf;
11448 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
11449 conf->bts.size);
11450
11451 putpkt (buf);
11452 getpkt (&buf, &rs->buf_size, 0);
11453
11454 if (packet_ok (buf, packet) == PACKET_ERROR)
11455 {
11456 if (buf[0] == 'E' && buf[1] == '.')
11457 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
11458 else
11459 error (_("Failed to configure the BTS buffer size."));
11460 }
11461
11462 rs->btrace_config.bts.size = conf->bts.size;
11463 }
f4abbc16
MM
11464}
11465
11466/* Read the current thread's btrace configuration from the target and
11467 store it into CONF. */
11468
11469static void
11470btrace_read_config (struct btrace_config *conf)
11471{
11472 char *xml;
11473
11474 xml = target_read_stralloc (&current_target,
11475 TARGET_OBJECT_BTRACE_CONF, "");
11476 if (xml != NULL)
11477 {
11478 struct cleanup *cleanup;
11479
11480 cleanup = make_cleanup (xfree, xml);
11481 parse_xml_btrace_conf (conf, xml);
11482 do_cleanups (cleanup);
11483 }
11484}
11485
9accd112
MM
11486/* Enable branch tracing. */
11487
11488static struct btrace_target_info *
f4abbc16
MM
11489remote_enable_btrace (struct target_ops *self, ptid_t ptid,
11490 const struct btrace_config *conf)
9accd112
MM
11491{
11492 struct btrace_target_info *tinfo = NULL;
11493 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11494 struct remote_state *rs = get_remote_state ();
11495 char *buf = rs->buf;
11496 char *endbuf = rs->buf + get_remote_packet_size ();
11497
4082afcc 11498 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
11499 error (_("Target does not support branch tracing."));
11500
f4abbc16
MM
11501 btrace_sync_conf (conf);
11502
9accd112
MM
11503 set_general_thread (ptid);
11504
11505 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11506 putpkt (rs->buf);
11507 getpkt (&rs->buf, &rs->buf_size, 0);
11508
11509 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11510 {
11511 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11512 error (_("Could not enable branch tracing for %s: %s"),
11513 target_pid_to_str (ptid), rs->buf + 2);
11514 else
11515 error (_("Could not enable branch tracing for %s."),
11516 target_pid_to_str (ptid));
11517 }
11518
11519 tinfo = xzalloc (sizeof (*tinfo));
11520 tinfo->ptid = ptid;
11521
f4abbc16
MM
11522 /* If we fail to read the configuration, we lose some information, but the
11523 tracing itself is not impacted. */
492d29ea
PA
11524 TRY
11525 {
11526 btrace_read_config (&tinfo->conf);
11527 }
11528 CATCH (err, RETURN_MASK_ERROR)
11529 {
11530 if (err.message != NULL)
11531 warning ("%s", err.message);
11532 }
11533 END_CATCH
f4abbc16 11534
9accd112
MM
11535 return tinfo;
11536}
11537
11538/* Disable branch tracing. */
11539
11540static void
25e95349
TT
11541remote_disable_btrace (struct target_ops *self,
11542 struct btrace_target_info *tinfo)
9accd112
MM
11543{
11544 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11545 struct remote_state *rs = get_remote_state ();
11546 char *buf = rs->buf;
11547 char *endbuf = rs->buf + get_remote_packet_size ();
11548
4082afcc 11549 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
11550 error (_("Target does not support branch tracing."));
11551
11552 set_general_thread (tinfo->ptid);
11553
11554 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11555 putpkt (rs->buf);
11556 getpkt (&rs->buf, &rs->buf_size, 0);
11557
11558 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11559 {
11560 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11561 error (_("Could not disable branch tracing for %s: %s"),
11562 target_pid_to_str (tinfo->ptid), rs->buf + 2);
11563 else
11564 error (_("Could not disable branch tracing for %s."),
11565 target_pid_to_str (tinfo->ptid));
11566 }
11567
11568 xfree (tinfo);
11569}
11570
11571/* Teardown branch tracing. */
11572
11573static void
1777056d
TT
11574remote_teardown_btrace (struct target_ops *self,
11575 struct btrace_target_info *tinfo)
9accd112
MM
11576{
11577 /* We must not talk to the target during teardown. */
11578 xfree (tinfo);
11579}
11580
11581/* Read the branch trace. */
11582
969c39fb 11583static enum btrace_error
39c49f83 11584remote_read_btrace (struct target_ops *self,
734b0e4b 11585 struct btrace_data *btrace,
969c39fb 11586 struct btrace_target_info *tinfo,
9accd112
MM
11587 enum btrace_read_type type)
11588{
11589 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11590 struct remote_state *rs = get_remote_state ();
969c39fb 11591 struct cleanup *cleanup;
9accd112
MM
11592 const char *annex;
11593 char *xml;
11594
4082afcc 11595 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
11596 error (_("Target does not support branch tracing."));
11597
11598#if !defined(HAVE_LIBEXPAT)
11599 error (_("Cannot process branch tracing result. XML parsing not supported."));
11600#endif
11601
11602 switch (type)
11603 {
864089d2 11604 case BTRACE_READ_ALL:
9accd112
MM
11605 annex = "all";
11606 break;
864089d2 11607 case BTRACE_READ_NEW:
9accd112
MM
11608 annex = "new";
11609 break;
969c39fb
MM
11610 case BTRACE_READ_DELTA:
11611 annex = "delta";
11612 break;
9accd112
MM
11613 default:
11614 internal_error (__FILE__, __LINE__,
11615 _("Bad branch tracing read type: %u."),
11616 (unsigned int) type);
11617 }
11618
11619 xml = target_read_stralloc (&current_target,
11620 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
11621 if (xml == NULL)
11622 return BTRACE_ERR_UNKNOWN;
9accd112 11623
969c39fb 11624 cleanup = make_cleanup (xfree, xml);
734b0e4b 11625 parse_xml_btrace (btrace, xml);
969c39fb 11626 do_cleanups (cleanup);
9accd112 11627
969c39fb 11628 return BTRACE_ERR_NONE;
9accd112
MM
11629}
11630
f4abbc16
MM
11631static const struct btrace_config *
11632remote_btrace_conf (struct target_ops *self,
11633 const struct btrace_target_info *tinfo)
11634{
11635 return &tinfo->conf;
11636}
11637
ced63ec0 11638static int
5436ff03 11639remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 11640{
4082afcc
PA
11641 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
11642 == PACKET_ENABLE);
ced63ec0
GB
11643}
11644
9dd130a0
TT
11645/* Implementation of to_load. */
11646
11647static void
9cbe5fff 11648remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
11649{
11650 generic_load (name, from_tty);
11651}
11652
c78fa86a
GB
11653/* Accepts an integer PID; returns a string representing a file that
11654 can be opened on the remote side to get the symbols for the child
11655 process. Returns NULL if the operation is not supported. */
11656
11657static char *
11658remote_pid_to_exec_file (struct target_ops *self, int pid)
11659{
11660 static char *filename = NULL;
11661 char annex[9];
11662
11663 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
11664 return NULL;
11665
11666 if (filename != NULL)
11667 xfree (filename);
11668
11669 xsnprintf (annex, sizeof (annex), "%x", pid);
11670 filename = target_read_stralloc (&current_target,
11671 TARGET_OBJECT_EXEC_FILE, annex);
11672
11673 return filename;
11674}
11675
c906108c 11676static void
fba45db2 11677init_remote_ops (void)
c906108c 11678{
c5aa993b 11679 remote_ops.to_shortname = "remote";
c906108c 11680 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 11681 remote_ops.to_doc =
c906108c 11682 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
11683Specify the serial device it is connected to\n\
11684(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
11685 remote_ops.to_open = remote_open;
11686 remote_ops.to_close = remote_close;
c906108c 11687 remote_ops.to_detach = remote_detach;
6ad8ae5c 11688 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 11689 remote_ops.to_resume = remote_resume;
c906108c
SS
11690 remote_ops.to_wait = remote_wait;
11691 remote_ops.to_fetch_registers = remote_fetch_registers;
11692 remote_ops.to_store_registers = remote_store_registers;
11693 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 11694 remote_ops.to_files_info = remote_files_info;
c906108c
SS
11695 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11696 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
11697 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
11698 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
11699 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
11700 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
11701 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11702 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
11703 remote_ops.to_watchpoint_addr_within_range =
11704 remote_watchpoint_addr_within_range;
3c3bea1c
GS
11705 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11706 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11707 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
11708 remote_ops.to_region_ok_for_hw_watchpoint
11709 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
11710 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11711 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 11712 remote_ops.to_kill = remote_kill;
9dd130a0 11713 remote_ops.to_load = remote_load;
c906108c 11714 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 11715 remote_ops.to_pass_signals = remote_pass_signals;
9b224c5e 11716 remote_ops.to_program_signals = remote_program_signals;
c906108c 11717 remote_ops.to_thread_alive = remote_thread_alive;
e8032dde 11718 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 11719 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 11720 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 11721 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 11722 remote_ops.to_stop = remote_stop;
4b8a223f 11723 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 11724 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 11725 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 11726 remote_ops.to_log_command = serial_log_command;
38691318 11727 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 11728 remote_ops.to_stratum = process_stratum;
c35b1492
PA
11729 remote_ops.to_has_all_memory = default_child_has_all_memory;
11730 remote_ops.to_has_memory = default_child_has_memory;
11731 remote_ops.to_has_stack = default_child_has_stack;
11732 remote_ops.to_has_registers = default_child_has_registers;
11733 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 11734 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 11735 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 11736 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 11737 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
11738 remote_ops.to_flash_erase = remote_flash_erase;
11739 remote_ops.to_flash_done = remote_flash_done;
29709017 11740 remote_ops.to_read_description = remote_read_description;
08388c79 11741 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
11742 remote_ops.to_can_async_p = remote_can_async_p;
11743 remote_ops.to_is_async_p = remote_is_async_p;
11744 remote_ops.to_async = remote_async;
75c99385
PA
11745 remote_ops.to_terminal_inferior = remote_terminal_inferior;
11746 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 11747 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 11748 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
11749 remote_ops.to_supports_disable_randomization
11750 = remote_supports_disable_randomization;
4bd7dc42 11751 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
11752 remote_ops.to_fileio_open = remote_hostio_open;
11753 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11754 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 11755 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
11756 remote_ops.to_fileio_close = remote_hostio_close;
11757 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 11758 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 11759 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 11760 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 11761 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 11762 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
11763 remote_ops.to_trace_init = remote_trace_init;
11764 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 11765 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
11766 remote_ops.to_download_trace_state_variable
11767 = remote_download_trace_state_variable;
d248b706
KY
11768 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11769 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
11770 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11771 remote_ops.to_trace_start = remote_trace_start;
11772 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 11773 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
11774 remote_ops.to_trace_stop = remote_trace_stop;
11775 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
11776 remote_ops.to_get_trace_state_variable_value
11777 = remote_get_trace_state_variable_value;
00bf0b85
SS
11778 remote_ops.to_save_trace_data = remote_save_trace_data;
11779 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
11780 remote_ops.to_upload_trace_state_variables
11781 = remote_upload_trace_state_variables;
00bf0b85 11782 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 11783 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 11784 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 11785 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 11786 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 11787 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 11788 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 11789 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 11790 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 11791 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
11792 remote_ops.to_static_tracepoint_marker_at
11793 = remote_static_tracepoint_marker_at;
11794 remote_ops.to_static_tracepoint_markers_by_strid
11795 = remote_static_tracepoint_markers_by_strid;
b3b9301e 11796 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
11797 remote_ops.to_use_agent = remote_use_agent;
11798 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
11799 remote_ops.to_supports_btrace = remote_supports_btrace;
11800 remote_ops.to_enable_btrace = remote_enable_btrace;
11801 remote_ops.to_disable_btrace = remote_disable_btrace;
11802 remote_ops.to_teardown_btrace = remote_teardown_btrace;
11803 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 11804 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
11805 remote_ops.to_augmented_libraries_svr4_read =
11806 remote_augmented_libraries_svr4_read;
c906108c
SS
11807}
11808
11809/* Set up the extended remote vector by making a copy of the standard
11810 remote vector and adding to it. */
11811
11812static void
fba45db2 11813init_extended_remote_ops (void)
c906108c
SS
11814{
11815 extended_remote_ops = remote_ops;
11816
0f71a2f6 11817 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 11818 extended_remote_ops.to_longname =
c906108c 11819 "Extended remote serial target in gdb-specific protocol";
c5aa993b 11820 extended_remote_ops.to_doc =
c906108c 11821 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
11822Specify the serial device it is connected to (e.g. /dev/ttya).";
11823 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
11824 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11825 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
11826 extended_remote_ops.to_detach = extended_remote_detach;
11827 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 11828 extended_remote_ops.to_post_attach = extended_remote_post_attach;
82f73884 11829 extended_remote_ops.to_kill = extended_remote_kill;
03583c20
UW
11830 extended_remote_ops.to_supports_disable_randomization
11831 = extended_remote_supports_disable_randomization;
0f71a2f6
JM
11832}
11833
6426a772 11834static int
6a109b6b 11835remote_can_async_p (struct target_ops *ops)
6426a772 11836{
5d93a237
TT
11837 struct remote_state *rs = get_remote_state ();
11838
c6ebd6cf 11839 if (!target_async_permitted)
75c99385
PA
11840 /* We only enable async when the user specifically asks for it. */
11841 return 0;
11842
23860348 11843 /* We're async whenever the serial device is. */
5d93a237 11844 return serial_can_async_p (rs->remote_desc);
6426a772
JM
11845}
11846
11847static int
6a109b6b 11848remote_is_async_p (struct target_ops *ops)
6426a772 11849{
5d93a237
TT
11850 struct remote_state *rs = get_remote_state ();
11851
c6ebd6cf 11852 if (!target_async_permitted)
75c99385
PA
11853 /* We only enable async when the user specifically asks for it. */
11854 return 0;
11855
23860348 11856 /* We're async whenever the serial device is. */
5d93a237 11857 return serial_is_async_p (rs->remote_desc);
6426a772
JM
11858}
11859
2acceee2
JM
11860/* Pass the SERIAL event on and up to the client. One day this code
11861 will be able to delay notifying the client of an event until the
23860348 11862 point where an entire packet has been received. */
2acceee2 11863
2acceee2
JM
11864static serial_event_ftype remote_async_serial_handler;
11865
6426a772 11866static void
819cc324 11867remote_async_serial_handler (struct serial *scb, void *context)
6426a772 11868{
88b496c3
TT
11869 struct remote_state *rs = context;
11870
2acceee2
JM
11871 /* Don't propogate error information up to the client. Instead let
11872 the client find out about the error by querying the target. */
6a3753b3 11873 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
11874}
11875
74531fed
PA
11876static void
11877remote_async_inferior_event_handler (gdb_client_data data)
11878{
11879 inferior_event_handler (INF_REG_EVENT, NULL);
11880}
11881
2acceee2 11882static void
6a3753b3 11883remote_async (struct target_ops *ops, int enable)
2acceee2 11884{
5d93a237
TT
11885 struct remote_state *rs = get_remote_state ();
11886
6a3753b3 11887 if (enable)
2acceee2 11888 {
88b496c3 11889 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
11890
11891 /* If there are pending events in the stop reply queue tell the
11892 event loop to process them. */
11893 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
11894 mark_async_event_handler (remote_async_inferior_event_token);
2acceee2
JM
11895 }
11896 else
b7d2e916
PA
11897 {
11898 serial_async (rs->remote_desc, NULL, NULL);
11899 clear_async_event_handler (remote_async_inferior_event_token);
11900 }
6426a772
JM
11901}
11902
5a2468f5 11903static void
c2d11a7d 11904set_remote_cmd (char *args, int from_tty)
5a2468f5 11905{
635c7e8a 11906 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
11907}
11908
d471ea57
AC
11909static void
11910show_remote_cmd (char *args, int from_tty)
11911{
37a105a1 11912 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 11913 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
11914 struct cleanup *showlist_chain;
11915 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 11916 struct ui_out *uiout = current_uiout;
37a105a1
DJ
11917
11918 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
11919 for (; list != NULL; list = list->next)
11920 if (strcmp (list->name, "Z-packet") == 0)
11921 continue;
427c3a89
DJ
11922 else if (list->type == not_set_cmd)
11923 /* Alias commands are exactly like the original, except they
11924 don't have the normal type. */
11925 continue;
11926 else
37a105a1
DJ
11927 {
11928 struct cleanup *option_chain
11929 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 11930
37a105a1
DJ
11931 ui_out_field_string (uiout, "name", list->name);
11932 ui_out_text (uiout, ": ");
427c3a89 11933 if (list->type == show_cmd)
5b9afe8a 11934 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
11935 else
11936 cmd_func (list, NULL, from_tty);
37a105a1
DJ
11937 /* Close the tuple. */
11938 do_cleanups (option_chain);
11939 }
427c3a89
DJ
11940
11941 /* Close the tuple. */
11942 do_cleanups (showlist_chain);
d471ea57 11943}
5a2468f5 11944
0f71a2f6 11945
23860348 11946/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
11947static void
11948remote_new_objfile (struct objfile *objfile)
11949{
5d93a237
TT
11950 struct remote_state *rs = get_remote_state ();
11951
11952 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 11953 remote_check_symbols ();
dc8acb97
MS
11954}
11955
00bf0b85
SS
11956/* Pull all the tracepoints defined on the target and create local
11957 data structures representing them. We don't want to create real
11958 tracepoints yet, we don't want to mess up the user's existing
11959 collection. */
11960
11961static int
ab6617cc 11962remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 11963{
00bf0b85
SS
11964 struct remote_state *rs = get_remote_state ();
11965 char *p;
d5551862 11966
00bf0b85
SS
11967 /* Ask for a first packet of tracepoint definition. */
11968 putpkt ("qTfP");
11969 getpkt (&rs->buf, &rs->buf_size, 0);
11970 p = rs->buf;
11971 while (*p && *p != 'l')
d5551862 11972 {
00bf0b85
SS
11973 parse_tracepoint_definition (p, utpp);
11974 /* Ask for another packet of tracepoint definition. */
11975 putpkt ("qTsP");
11976 getpkt (&rs->buf, &rs->buf_size, 0);
11977 p = rs->buf;
d5551862 11978 }
00bf0b85 11979 return 0;
d5551862
SS
11980}
11981
00bf0b85 11982static int
181e3713
TT
11983remote_upload_trace_state_variables (struct target_ops *self,
11984 struct uploaded_tsv **utsvp)
d5551862 11985{
00bf0b85 11986 struct remote_state *rs = get_remote_state ();
d5551862 11987 char *p;
d5551862 11988
00bf0b85
SS
11989 /* Ask for a first packet of variable definition. */
11990 putpkt ("qTfV");
d5551862
SS
11991 getpkt (&rs->buf, &rs->buf_size, 0);
11992 p = rs->buf;
00bf0b85 11993 while (*p && *p != 'l')
d5551862 11994 {
00bf0b85
SS
11995 parse_tsv_definition (p, utsvp);
11996 /* Ask for another packet of variable definition. */
11997 putpkt ("qTsV");
d5551862
SS
11998 getpkt (&rs->buf, &rs->buf_size, 0);
11999 p = rs->buf;
12000 }
00bf0b85 12001 return 0;
d5551862
SS
12002}
12003
c1e36e3e
PA
12004/* The "set/show range-stepping" show hook. */
12005
12006static void
12007show_range_stepping (struct ui_file *file, int from_tty,
12008 struct cmd_list_element *c,
12009 const char *value)
12010{
12011 fprintf_filtered (file,
12012 _("Debugger's willingness to use range stepping "
12013 "is %s.\n"), value);
12014}
12015
12016/* The "set/show range-stepping" set hook. */
12017
12018static void
12019set_range_stepping (char *ignore_args, int from_tty,
12020 struct cmd_list_element *c)
12021{
5d93a237
TT
12022 struct remote_state *rs = get_remote_state ();
12023
c1e36e3e
PA
12024 /* Whene enabling, check whether range stepping is actually
12025 supported by the target, and warn if not. */
12026 if (use_range_stepping)
12027 {
5d93a237 12028 if (rs->remote_desc != NULL)
c1e36e3e 12029 {
4082afcc 12030 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
12031 remote_vcont_probe (rs);
12032
4082afcc 12033 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
12034 && rs->supports_vCont.r)
12035 return;
12036 }
12037
12038 warning (_("Range stepping is not supported by the current target"));
12039 }
12040}
12041
c906108c 12042void
fba45db2 12043_initialize_remote (void)
c906108c 12044{
ea9c271d 12045 struct remote_state *rs;
9a7071a8 12046 struct cmd_list_element *cmd;
6f937416 12047 const char *cmd_name;
ea9c271d 12048
0f71a2f6 12049 /* architecture specific data */
2bc416ba 12050 remote_gdbarch_data_handle =
23860348 12051 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
12052 remote_g_packet_data_handle =
12053 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 12054
ea9c271d
DJ
12055 /* Initialize the per-target state. At the moment there is only one
12056 of these, not one per target. Only one target is active at a
cf792862
TT
12057 time. */
12058 remote_state = new_remote_state ();
ea9c271d 12059
c906108c
SS
12060 init_remote_ops ();
12061 add_target (&remote_ops);
12062
12063 init_extended_remote_ops ();
12064 add_target (&extended_remote_ops);
cce74817 12065
dc8acb97 12066 /* Hook into new objfile notification. */
06d3b283 12067 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
12068 /* We're no longer interested in notification events of an inferior
12069 when it exits. */
12070 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 12071
b803fb0f 12072 /* Set up signal handlers. */
934b9bac 12073 async_sigint_remote_token =
b803fb0f 12074 create_async_signal_handler (async_remote_interrupt, NULL);
934b9bac 12075 async_sigint_remote_twice_token =
6d549500 12076 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 12077
c906108c
SS
12078#if 0
12079 init_remote_threadtests ();
12080#endif
12081
722247f1 12082 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 12083 /* set/show remote ... */
d471ea57 12084
1bedd215 12085 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
12086Remote protocol specific variables\n\
12087Configure various remote-protocol specific variables such as\n\
1bedd215 12088the packets being used"),
cff3e48b 12089 &remote_set_cmdlist, "set remote ",
23860348 12090 0 /* allow-unknown */, &setlist);
1bedd215 12091 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
12092Remote protocol specific variables\n\
12093Configure various remote-protocol specific variables such as\n\
1bedd215 12094the packets being used"),
cff3e48b 12095 &remote_show_cmdlist, "show remote ",
23860348 12096 0 /* allow-unknown */, &showlist);
5a2468f5 12097
1a966eab
AC
12098 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
12099Compare section data on target to the exec file.\n\
95cf3b38
DT
12100Argument is a single section name (default: all loaded sections).\n\
12101To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
12102 &cmdlist);
12103
1a966eab
AC
12104 add_cmd ("packet", class_maintenance, packet_command, _("\
12105Send an arbitrary packet to a remote target.\n\
c906108c
SS
12106 maintenance packet TEXT\n\
12107If GDB is talking to an inferior via the GDB serial protocol, then\n\
12108this command sends the string TEXT to the inferior, and displays the\n\
12109response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 12110terminating `#' character and checksum."),
c906108c
SS
12111 &maintenancelist);
12112
7915a72c
AC
12113 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
12114Set whether to send break if interrupted."), _("\
12115Show whether to send break if interrupted."), _("\
12116If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 12117 set_remotebreak, show_remotebreak,
e707bbc2 12118 &setlist, &showlist);
9a7071a8
JB
12119 cmd_name = "remotebreak";
12120 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
12121 deprecate_cmd (cmd, "set remote interrupt-sequence");
12122 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
12123 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
12124 deprecate_cmd (cmd, "show remote interrupt-sequence");
12125
12126 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
12127 interrupt_sequence_modes, &interrupt_sequence_mode,
12128 _("\
9a7071a8
JB
12129Set interrupt sequence to remote target."), _("\
12130Show interrupt sequence to remote target."), _("\
12131Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
12132 NULL, show_interrupt_sequence,
12133 &remote_set_cmdlist,
12134 &remote_show_cmdlist);
12135
12136 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
12137 &interrupt_on_connect, _("\
12138Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12139Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12140If set, interrupt sequence is sent to remote target."),
12141 NULL, NULL,
12142 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 12143
23860348 12144 /* Install commands for configuring memory read/write packets. */
11cf8741 12145
1a966eab
AC
12146 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
12147Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 12148 &setlist);
1a966eab
AC
12149 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
12150Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
12151 &showlist);
12152 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
12153 set_memory_write_packet_size, _("\
12154Set the maximum number of bytes per memory-write packet.\n\
12155Specify the number of bytes in a packet or 0 (zero) for the\n\
12156default packet size. The actual limit is further reduced\n\
12157dependent on the target. Specify ``fixed'' to disable the\n\
12158further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
12159 &remote_set_cmdlist);
12160 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
12161 set_memory_read_packet_size, _("\
12162Set the maximum number of bytes per memory-read packet.\n\
12163Specify the number of bytes in a packet or 0 (zero) for the\n\
12164default packet size. The actual limit is further reduced\n\
12165dependent on the target. Specify ``fixed'' to disable the\n\
12166further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
12167 &remote_set_cmdlist);
12168 add_cmd ("memory-write-packet-size", no_class,
12169 show_memory_write_packet_size,
1a966eab 12170 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
12171 &remote_show_cmdlist);
12172 add_cmd ("memory-read-packet-size", no_class,
12173 show_memory_read_packet_size,
1a966eab 12174 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 12175 &remote_show_cmdlist);
c906108c 12176
b3f42336 12177 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
12178 &remote_hw_watchpoint_limit, _("\
12179Set the maximum number of target hardware watchpoints."), _("\
12180Show the maximum number of target hardware watchpoints."), _("\
12181Specify a negative limit for unlimited."),
3e43a32a
MS
12182 NULL, NULL, /* FIXME: i18n: The maximum
12183 number of target hardware
12184 watchpoints is %s. */
b3f42336 12185 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
12186 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
12187 &remote_hw_watchpoint_length_limit, _("\
12188Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
12189Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
12190Specify a negative limit for unlimited."),
12191 NULL, NULL, /* FIXME: i18n: The maximum
12192 length (in bytes) of a target
12193 hardware watchpoint is %s. */
12194 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 12195 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
12196 &remote_hw_breakpoint_limit, _("\
12197Set the maximum number of target hardware breakpoints."), _("\
12198Show the maximum number of target hardware breakpoints."), _("\
12199Specify a negative limit for unlimited."),
3e43a32a
MS
12200 NULL, NULL, /* FIXME: i18n: The maximum
12201 number of target hardware
12202 breakpoints is %s. */
b3f42336 12203 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 12204
1b493192
PA
12205 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
12206 &remote_address_size, _("\
4d28ad1e
AC
12207Set the maximum size of the address (in bits) in a memory packet."), _("\
12208Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
12209 NULL,
12210 NULL, /* FIXME: i18n: */
12211 &setlist, &showlist);
c906108c 12212
ca4f7f8b
PA
12213 init_all_packet_configs ();
12214
444abaca 12215 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 12216 "X", "binary-download", 1);
0f71a2f6 12217
444abaca 12218 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 12219 "vCont", "verbose-resume", 0);
506fb367 12220
89be2091
DJ
12221 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
12222 "QPassSignals", "pass-signals", 0);
12223
9b224c5e
PA
12224 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
12225 "QProgramSignals", "program-signals", 0);
12226
444abaca 12227 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 12228 "qSymbol", "symbol-lookup", 0);
dc8acb97 12229
444abaca 12230 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 12231 "P", "set-register", 1);
d471ea57 12232
444abaca 12233 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 12234 "p", "fetch-register", 1);
b96ec7ac 12235
444abaca 12236 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 12237 "Z0", "software-breakpoint", 0);
d471ea57 12238
444abaca 12239 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 12240 "Z1", "hardware-breakpoint", 0);
d471ea57 12241
444abaca 12242 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 12243 "Z2", "write-watchpoint", 0);
d471ea57 12244
444abaca 12245 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 12246 "Z3", "read-watchpoint", 0);
d471ea57 12247
444abaca 12248 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 12249 "Z4", "access-watchpoint", 0);
d471ea57 12250
0876f84a
DJ
12251 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
12252 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 12253
c78fa86a
GB
12254 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
12255 "qXfer:exec-file:read", "pid-to-exec-file", 0);
12256
23181151
DJ
12257 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
12258 "qXfer:features:read", "target-features", 0);
12259
cfa9d6d9
DJ
12260 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
12261 "qXfer:libraries:read", "library-info", 0);
12262
2268b414
JK
12263 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12264 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12265
fd79ecee
DJ
12266 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12267 "qXfer:memory-map:read", "memory-map", 0);
12268
0e7f50da
UW
12269 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12270 "qXfer:spu:read", "read-spu-object", 0);
12271
12272 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12273 "qXfer:spu:write", "write-spu-object", 0);
12274
07e059b5
VP
12275 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12276 "qXfer:osdata:read", "osdata", 0);
12277
dc146f7c
VP
12278 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12279 "qXfer:threads:read", "threads", 0);
12280
4aa995e1
PA
12281 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12282 "qXfer:siginfo:read", "read-siginfo-object", 0);
12283
12284 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12285 "qXfer:siginfo:write", "write-siginfo-object", 0);
12286
b3b9301e
PA
12287 add_packet_config_cmd
12288 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 12289 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 12290
169081d0
TG
12291 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12292 "qXfer:uib:read", "unwind-info-block", 0);
12293
444abaca 12294 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 12295 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
12296 0);
12297
711e434b
PM
12298 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12299 "qGetTIBAddr", "get-thread-information-block-address",
12300 0);
12301
40ab02ce
MS
12302 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12303 "bc", "reverse-continue", 0);
12304
12305 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12306 "bs", "reverse-step", 0);
12307
be2a5f71
DJ
12308 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12309 "qSupported", "supported-packets", 0);
12310
08388c79
DE
12311 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12312 "qSearch:memory", "search-memory", 0);
12313
bd3eecc3
PA
12314 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12315 "qTStatus", "trace-status", 0);
12316
a6b151f1
DJ
12317 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12318 "vFile:open", "hostio-open", 0);
12319
12320 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12321 "vFile:pread", "hostio-pread", 0);
12322
12323 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12324 "vFile:pwrite", "hostio-pwrite", 0);
12325
12326 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12327 "vFile:close", "hostio-close", 0);
12328
12329 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12330 "vFile:unlink", "hostio-unlink", 0);
12331
b9e7b9c3
UW
12332 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12333 "vFile:readlink", "hostio-readlink", 0);
12334
0a93529c
GB
12335 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
12336 "vFile:fstat", "hostio-fstat", 0);
12337
2d717e4f
DJ
12338 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12339 "vAttach", "attach", 0);
12340
12341 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12342 "vRun", "run", 0);
12343
a6f3e723
SL
12344 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12345 "QStartNoAckMode", "noack", 0);
12346
82f73884
PA
12347 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12348 "vKill", "kill", 0);
12349
0b16c5cf
PA
12350 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12351 "qAttached", "query-attached", 0);
12352
782b2b07 12353 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
12354 "ConditionalTracepoints",
12355 "conditional-tracepoints", 0);
3788aec7
LM
12356
12357 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12358 "ConditionalBreakpoints",
12359 "conditional-breakpoints", 0);
12360
d3ce09f5
SS
12361 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12362 "BreakpointCommands",
12363 "breakpoint-commands", 0);
12364
7a697b8d
SS
12365 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12366 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 12367
409873ef
SS
12368 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12369 "TracepointSource", "TracepointSource", 0);
12370
d914c394
SS
12371 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12372 "QAllow", "allow", 0);
12373
0fb4aa4b
PA
12374 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12375 "StaticTracepoints", "static-tracepoints", 0);
12376
1e4d1764
YQ
12377 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12378 "InstallInTrace", "install-in-trace", 0);
12379
0fb4aa4b
PA
12380 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12381 "qXfer:statictrace:read", "read-sdata-object", 0);
12382
78d85199
YQ
12383 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12384 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12385
03583c20
UW
12386 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12387 "QDisableRandomization", "disable-randomization", 0);
12388
d1feda86
YQ
12389 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12390 "QAgent", "agent", 0);
12391
f6f899bf
HAQ
12392 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12393 "QTBuffer:size", "trace-buffer-size", 0);
12394
9accd112
MM
12395 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12396 "Qbtrace:off", "disable-btrace", 0);
12397
12398 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12399 "Qbtrace:bts", "enable-btrace", 0);
12400
12401 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12402 "qXfer:btrace", "read-btrace", 0);
12403
f4abbc16
MM
12404 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
12405 "qXfer:btrace-conf", "read-btrace-conf", 0);
12406
d33501a5
MM
12407 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
12408 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
12409
f7e6eed5
PA
12410 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
12411 "swbreak-feature", "swbreak-feature", 0);
12412
12413 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
12414 "hwbreak-feature", "hwbreak-feature", 0);
12415
0b736949
DB
12416 /* Assert that we've registered "set remote foo-packet" commands
12417 for all packet configs. */
ca4f7f8b
PA
12418 {
12419 int i;
12420
12421 for (i = 0; i < PACKET_MAX; i++)
12422 {
12423 /* Ideally all configs would have a command associated. Some
12424 still don't though. */
12425 int excepted;
12426
12427 switch (i)
12428 {
12429 case PACKET_QNonStop:
12430 case PACKET_multiprocess_feature:
12431 case PACKET_EnableDisableTracepoints_feature:
12432 case PACKET_tracenz_feature:
12433 case PACKET_DisconnectedTracing_feature:
12434 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
12435 case PACKET_qCRC:
12436 /* Additions to this list need to be well justified:
12437 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
12438 excepted = 1;
12439 break;
12440 default:
12441 excepted = 0;
12442 break;
12443 }
12444
12445 /* This catches both forgetting to add a config command, and
12446 forgetting to remove a packet from the exception list. */
12447 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
12448 }
12449 }
12450
37a105a1
DJ
12451 /* Keep the old ``set remote Z-packet ...'' working. Each individual
12452 Z sub-packet has its own set and show commands, but users may
12453 have sets to this variable in their .gdbinit files (or in their
12454 documentation). */
e9e68a56 12455 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
12456 &remote_Z_packet_detect, _("\
12457Set use of remote protocol `Z' packets"), _("\
12458Show use of remote protocol `Z' packets "), _("\
3b64bf98 12459When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 12460packets."),
e9e68a56 12461 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
12462 show_remote_protocol_Z_packet_cmd,
12463 /* FIXME: i18n: Use of remote protocol
12464 `Z' packets is %s. */
e9e68a56 12465 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 12466
a6b151f1
DJ
12467 add_prefix_cmd ("remote", class_files, remote_command, _("\
12468Manipulate files on the remote system\n\
12469Transfer files to and from the remote target system."),
12470 &remote_cmdlist, "remote ",
12471 0 /* allow-unknown */, &cmdlist);
12472
12473 add_cmd ("put", class_files, remote_put_command,
12474 _("Copy a local file to the remote system."),
12475 &remote_cmdlist);
12476
12477 add_cmd ("get", class_files, remote_get_command,
12478 _("Copy a remote file to the local system."),
12479 &remote_cmdlist);
12480
12481 add_cmd ("delete", class_files, remote_delete_command,
12482 _("Delete a remote file."),
12483 &remote_cmdlist);
12484
2d717e4f
DJ
12485 remote_exec_file = xstrdup ("");
12486 add_setshow_string_noescape_cmd ("exec-file", class_files,
12487 &remote_exec_file, _("\
12488Set the remote pathname for \"run\""), _("\
12489Show the remote pathname for \"run\""), NULL, NULL, NULL,
12490 &remote_set_cmdlist, &remote_show_cmdlist);
12491
c1e36e3e
PA
12492 add_setshow_boolean_cmd ("range-stepping", class_run,
12493 &use_range_stepping, _("\
12494Enable or disable range stepping."), _("\
12495Show whether target-assisted range stepping is enabled."), _("\
12496If on, and the target supports it, when stepping a source line, GDB\n\
12497tells the target to step the corresponding range of addresses itself instead\n\
12498of issuing multiple single-steps. This speeds up source level\n\
12499stepping. If off, GDB always issues single-steps, even if range\n\
12500stepping is supported by the target. The default is on."),
12501 set_range_stepping,
12502 show_range_stepping,
12503 &setlist,
12504 &showlist);
12505
449092f6
CV
12506 /* Eventually initialize fileio. See fileio.c */
12507 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 12508
ba348170 12509 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 12510 special ptids with it set to != 0. */
ba348170
PA
12511 magic_null_ptid = ptid_build (42000, -1, 1);
12512 not_sent_ptid = ptid_build (42000, -2, 1);
12513 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
12514
12515 target_buf_size = 2048;
12516 target_buf = xmalloc (target_buf_size);
c906108c 12517}
10760264 12518