Fix extraneous complaints about missing expected TLS relocation.
[deliverable/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
618f726f 3 Copyright (C) 1988-2016 Free Software Foundation, Inc.
c906108c 4
c5aa993b
JM
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
c5aa993b
JM
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5aa993b 19
23860348 20/* See the GDB User Guide for details of the GDB remote protocol. */
c5aa993b 21
c906108c 22#include "defs.h"
c906108c
SS
23#include <ctype.h>
24#include <fcntl.h>
c906108c 25#include "inferior.h"
45741a9c 26#include "infrun.h"
c906108c
SS
27#include "bfd.h"
28#include "symfile.h"
29#include "target.h"
c5aa993b 30/*#include "terminal.h" */
c906108c
SS
31#include "gdbcmd.h"
32#include "objfiles.h"
33#include "gdb-stabs.h"
34#include "gdbthread.h"
c2c6d25f 35#include "remote.h"
722247f1 36#include "remote-notif.h"
4e052eda 37#include "regcache.h"
fd0407d6 38#include "value.h"
6867ae3e 39#include "observer.h"
a77053c2 40#include "solib.h"
37a105a1
DJ
41#include "cli/cli-decode.h"
42#include "cli/cli-setshow.h"
424163ea 43#include "target-descriptions.h"
a4453b7e 44#include "gdb_bfd.h"
614c279d 45#include "filestuff.h"
9c3d6531 46#include "rsp-low.h"
6b940e6a 47#include "disasm.h"
f00aae0f 48#include "location.h"
c906108c 49
438e1e42 50#include "gdb_sys_time.h"
c906108c 51
43ff13b4 52#include "event-loop.h"
c2c6d25f 53#include "event-top.h"
2acceee2 54#include "inf-loop.h"
43ff13b4 55
c906108c
SS
56#include <signal.h>
57#include "serial.h"
58
6240bebf
MS
59#include "gdbcore.h" /* for exec_bfd */
60
449092f6 61#include "remote-fileio.h"
a6b151f1 62#include "gdb/fileio.h"
53ce3c39 63#include <sys/stat.h>
dc146f7c 64#include "xml-support.h"
449092f6 65
fd79ecee
DJ
66#include "memory-map.h"
67
35b1e5cc
SS
68#include "tracepoint.h"
69#include "ax.h"
70#include "ax-gdb.h"
d1feda86 71#include "agent.h"
9accd112 72#include "btrace.h"
c0272db5 73#include "record-btrace.h"
35b1e5cc 74
0df8b418 75/* Temp hacks for tracepoint encoding migration. */
35b1e5cc
SS
76static char *target_buf;
77static long target_buf_size;
35b1e5cc 78
94585166
DB
79/* Per-program-space data key. */
80static const struct program_space_data *remote_pspace_data;
81
82/* The variable registered as the control variable used by the
83 remote exec-file commands. While the remote exec-file setting is
84 per-program-space, the set/show machinery uses this as the
85 location of the remote exec-file value. */
86static char *remote_exec_file_var;
87
6765f3e5
DJ
88/* The size to align memory write packets, when practical. The protocol
89 does not guarantee any alignment, and gdb will generate short
90 writes and unaligned writes, but even as a best-effort attempt this
91 can improve bulk transfers. For instance, if a write is misaligned
92 relative to the target's data bus, the stub may need to make an extra
93 round trip fetching data from the target. This doesn't make a
94 huge difference, but it's easy to do, so we try to be helpful.
95
96 The alignment chosen is arbitrary; usually data bus width is
97 important here, not the possibly larger cache line size. */
98enum { REMOTE_ALIGN_WRITES = 16 };
99
23860348 100/* Prototypes for local functions. */
6d820c5c 101static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
74531fed 102static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
fee9eda9 103 int forever, int *is_notif);
6426a772 104
a14ed312 105static void remote_files_info (struct target_ops *ignore);
c906108c 106
f32dbf8c
MM
107static void remote_prepare_to_store (struct target_ops *self,
108 struct regcache *regcache);
c906108c 109
014f9477
TT
110static void remote_open_1 (const char *, int, struct target_ops *,
111 int extended_p);
c906108c 112
de90e03d 113static void remote_close (struct target_ops *self);
c906108c 114
cbb8991c
DB
115struct remote_state;
116
117static int remote_vkill (int pid, struct remote_state *rs);
118
8020350c
DB
119static void remote_kill_k (void);
120
136d6dae 121static void remote_mourn (struct target_ops *ops);
c906108c 122
a14ed312 123static void extended_remote_restart (void);
c906108c 124
6d820c5c 125static void remote_send (char **buf, long *sizeof_buf_p);
c906108c 126
a14ed312 127static int readchar (int timeout);
c906108c 128
c33e31fd
PA
129static void remote_serial_write (const char *str, int len);
130
7d85a9c0 131static void remote_kill (struct target_ops *ops);
c906108c 132
6a109b6b 133static int remote_can_async_p (struct target_ops *);
75c99385 134
6a109b6b 135static int remote_is_async_p (struct target_ops *);
75c99385 136
6a3753b3 137static void remote_async (struct target_ops *ops, int enable);
75c99385 138
65706a29
PA
139static void remote_thread_events (struct target_ops *ops, int enable);
140
a14ed312 141static void interrupt_query (void);
c906108c 142
79d7f229
PA
143static void set_general_thread (struct ptid ptid);
144static void set_continue_thread (struct ptid ptid);
c906108c 145
a14ed312 146static void get_offsets (void);
c906108c 147
6d820c5c
DJ
148static void skip_frame (void);
149
150static long read_frame (char **buf_p, long *sizeof_buf);
c906108c 151
a14ed312 152static int hexnumlen (ULONGEST num);
c906108c 153
a14ed312 154static void init_remote_ops (void);
c906108c 155
a14ed312 156static void init_extended_remote_ops (void);
c906108c 157
1eab8a48 158static void remote_stop (struct target_ops *self, ptid_t);
c906108c 159
a14ed312 160static int stubhex (int ch);
c906108c 161
a14ed312 162static int hexnumstr (char *, ULONGEST);
c906108c 163
a14ed312 164static int hexnumnstr (char *, ULONGEST, int);
2df3850c 165
a14ed312 166static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 167
baa336ce 168static void print_packet (const char *);
c906108c 169
a14ed312 170static void compare_sections_command (char *, int);
c906108c 171
a14ed312 172static void packet_command (char *, int);
c906108c 173
a14ed312 174static int stub_unpack_int (char *buff, int fieldlength);
c906108c 175
39f77062 176static ptid_t remote_current_thread (ptid_t oldptid);
c906108c 177
baa336ce 178static int putpkt_binary (const char *buf, int cnt);
c906108c 179
a14ed312 180static void check_binary_download (CORE_ADDR addr);
c906108c 181
5a2468f5 182struct packet_config;
5a2468f5 183
a14ed312 184static void show_packet_config_cmd (struct packet_config *config);
5a2468f5 185
bb572ddd
DJ
186static void show_remote_protocol_packet_cmd (struct ui_file *file,
187 int from_tty,
188 struct cmd_list_element *c,
189 const char *value);
190
82f73884
PA
191static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
192static ptid_t read_ptid (char *buf, char **obuf);
193
c378d69d 194static void remote_set_permissions (struct target_ops *self);
d914c394 195
8bd200f1
TT
196static int remote_get_trace_status (struct target_ops *self,
197 struct trace_status *ts);
d5551862 198
ab6617cc
TT
199static int remote_upload_tracepoints (struct target_ops *self,
200 struct uploaded_tp **utpp);
00bf0b85 201
181e3713
TT
202static int remote_upload_trace_state_variables (struct target_ops *self,
203 struct uploaded_tsv **utsvp);
00bf0b85 204
c8d104ad
PA
205static void remote_query_supported (void);
206
36d25514 207static void remote_check_symbols (void);
c8d104ad 208
a14ed312 209void _initialize_remote (void);
c906108c 210
74531fed 211struct stop_reply;
74531fed 212static void stop_reply_xfree (struct stop_reply *);
722247f1 213static void remote_parse_stop_reply (char *, struct stop_reply *);
74531fed 214static void push_stop_reply (struct stop_reply *);
bcc75809 215static void discard_pending_stop_replies_in_queue (struct remote_state *);
74531fed
PA
216static int peek_stop_reply (ptid_t ptid);
217
cbb8991c
DB
218struct threads_listing_context;
219static void remove_new_fork_children (struct threads_listing_context *);
220
74531fed 221static void remote_async_inferior_event_handler (gdb_client_data);
74531fed 222
e3594fd1 223static void remote_terminal_ours (struct target_ops *self);
d3fd5342 224
d962ef82
DJ
225static int remote_read_description_p (struct target_ops *target);
226
176a6961 227static void remote_console_output (char *msg);
dde08ee1 228
efcc2da7 229static int remote_supports_cond_breakpoints (struct target_ops *self);
b775012e 230
78eff0ec 231static int remote_can_run_breakpoint_commands (struct target_ops *self);
d3ce09f5 232
f4abbc16
MM
233static void remote_btrace_reset (void);
234
c0272db5
TW
235static void remote_btrace_maybe_reopen (void);
236
221e1a37
PA
237static int stop_reply_queue_length (void);
238
80152258
PA
239static void readahead_cache_invalidate (void);
240
048094ac
PA
241static void remote_unpush_and_throw (void);
242
a6b151f1
DJ
243/* For "remote". */
244
245static struct cmd_list_element *remote_cmdlist;
246
bb572ddd
DJ
247/* For "set remote" and "show remote". */
248
249static struct cmd_list_element *remote_set_cmdlist;
250static struct cmd_list_element *remote_show_cmdlist;
251
d458bd84
PA
252/* Stub vCont actions support.
253
254 Each field is a boolean flag indicating whether the stub reports
255 support for the corresponding action. */
256
257struct vCont_action_support
258{
259 /* vCont;t */
260 int t;
c1e36e3e
PA
261
262 /* vCont;r */
263 int r;
750ce8d1
YQ
264
265 /* vCont;s */
266 int s;
267
268 /* vCont;S */
269 int S;
d458bd84
PA
270};
271
c1e36e3e
PA
272/* Controls whether GDB is willing to use range stepping. */
273
274static int use_range_stepping = 1;
275
0d031856
TT
276#define OPAQUETHREADBYTES 8
277
278/* a 64 bit opaque identifier */
279typedef unsigned char threadref[OPAQUETHREADBYTES];
280
281/* About this many threadisds fit in a packet. */
282
283#define MAXTHREADLISTRESULTS 32
284
80152258
PA
285/* Data for the vFile:pread readahead cache. */
286
287struct readahead_cache
288{
289 /* The file descriptor for the file that is being cached. -1 if the
290 cache is invalid. */
291 int fd;
292
293 /* The offset into the file that the cache buffer corresponds
294 to. */
295 ULONGEST offset;
296
297 /* The buffer holding the cache contents. */
298 gdb_byte *buf;
299 /* The buffer's size. We try to read as much as fits into a packet
300 at a time. */
301 size_t bufsize;
302
303 /* Cache hit and miss counters. */
304 ULONGEST hit_count;
305 ULONGEST miss_count;
306};
307
ea9c271d
DJ
308/* Description of the remote protocol state for the currently
309 connected target. This is per-target state, and independent of the
310 selected architecture. */
311
312struct remote_state
313{
314 /* A buffer to use for incoming packets, and its current size. The
315 buffer is grown dynamically for larger incoming packets.
316 Outgoing packets may also be constructed in this buffer.
317 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
318 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
319 packets. */
320 char *buf;
321 long buf_size;
be2a5f71 322
1e51243a
PA
323 /* True if we're going through initial connection setup (finding out
324 about the remote side's threads, relocating symbols, etc.). */
325 int starting_up;
326
be2a5f71
DJ
327 /* If we negotiated packet size explicitly (and thus can bypass
328 heuristics for the largest packet size that will not overflow
329 a buffer in the stub), this will be set to that packet size.
330 Otherwise zero, meaning to use the guessed size. */
331 long explicit_packet_size;
2d717e4f
DJ
332
333 /* remote_wait is normally called when the target is running and
334 waits for a stop reply packet. But sometimes we need to call it
335 when the target is already stopped. We can send a "?" packet
336 and have remote_wait read the response. Or, if we already have
337 the response, we can stash it in BUF and tell remote_wait to
338 skip calling getpkt. This flag is set when BUF contains a
339 stop reply packet and the target is not waiting. */
340 int cached_wait_status;
a6f3e723
SL
341
342 /* True, if in no ack mode. That is, neither GDB nor the stub will
343 expect acks from each other. The connection is assumed to be
344 reliable. */
345 int noack_mode;
82f73884
PA
346
347 /* True if we're connected in extended remote mode. */
348 int extended;
349
e24a49d8
PA
350 /* True if we resumed the target and we're waiting for the target to
351 stop. In the mean time, we can't start another command/query.
352 The remote server wouldn't be ready to process it, so we'd
353 timeout waiting for a reply that would never come and eventually
354 we'd close the connection. This can happen in asynchronous mode
355 because we allow GDB commands while the target is running. */
356 int waiting_for_stop_reply;
74531fed 357
d458bd84
PA
358 /* The status of the stub support for the various vCont actions. */
359 struct vCont_action_support supports_vCont;
782b2b07 360
3a29589a
DJ
361 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
362 responded to that. */
363 int ctrlc_pending_p;
5d93a237 364
048094ac
PA
365 /* True if we saw a Ctrl-C while reading or writing from/to the
366 remote descriptor. At that point it is not safe to send a remote
367 interrupt packet, so we instead remember we saw the Ctrl-C and
368 process it once we're done with sending/receiving the current
369 packet, which should be shortly. If however that takes too long,
370 and the user presses Ctrl-C again, we offer to disconnect. */
371 int got_ctrlc_during_io;
372
5d93a237
TT
373 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
374 remote_open knows that we don't have a file open when the program
375 starts. */
376 struct serial *remote_desc;
47f8a51d
TT
377
378 /* These are the threads which we last sent to the remote system. The
379 TID member will be -1 for all or -2 for not sent yet. */
380 ptid_t general_thread;
381 ptid_t continue_thread;
262e1174
TT
382
383 /* This is the traceframe which we last selected on the remote system.
384 It will be -1 if no traceframe is selected. */
385 int remote_traceframe_number;
747dc59d
TT
386
387 char *last_pass_packet;
5e4a05c4
TT
388
389 /* The last QProgramSignals packet sent to the target. We bypass
390 sending a new program signals list down to the target if the new
391 packet is exactly the same as the last we sent. IOW, we only let
392 the target know about program signals list changes. */
393 char *last_program_signals_packet;
b73be471
TT
394
395 enum gdb_signal last_sent_signal;
280ceea3
TT
396
397 int last_sent_step;
8e88304f 398
3a00c802
PA
399 /* The execution direction of the last resume we got. */
400 enum exec_direction_kind last_resume_exec_dir;
401
8e88304f
TT
402 char *finished_object;
403 char *finished_annex;
404 ULONGEST finished_offset;
b80fafe3
TT
405
406 /* Should we try the 'ThreadInfo' query packet?
407
408 This variable (NOT available to the user: auto-detect only!)
409 determines whether GDB will use the new, simpler "ThreadInfo"
410 query or the older, more complex syntax for thread queries.
411 This is an auto-detect variable (set to true at each connect,
412 and set to false when the target fails to recognize it). */
413 int use_threadinfo_query;
414 int use_threadextra_query;
88b496c3 415
0d031856
TT
416 threadref echo_nextthread;
417 threadref nextthread;
418 threadref resultthreadlist[MAXTHREADLISTRESULTS];
5965e028
YQ
419
420 /* The state of remote notification. */
421 struct remote_notif_state *notif_state;
f4abbc16
MM
422
423 /* The branch trace configuration. */
424 struct btrace_config btrace_config;
15a201c8
GB
425
426 /* The argument to the last "vFile:setfs:" packet we sent, used
427 to avoid sending repeated unnecessary "vFile:setfs:" packets.
428 Initialized to -1 to indicate that no "vFile:setfs:" packet
429 has yet been sent. */
430 int fs_pid;
80152258
PA
431
432 /* A readahead cache for vFile:pread. Often, reading a binary
433 involves a sequence of small reads. E.g., when parsing an ELF
434 file. A readahead cache helps mostly the case of remote
435 debugging on a connection with higher latency, due to the
436 request/reply nature of the RSP. We only cache data for a single
437 file descriptor at a time. */
438 struct readahead_cache readahead_cache;
ea9c271d
DJ
439};
440
dc146f7c
VP
441/* Private data that we'll store in (struct thread_info)->private. */
442struct private_thread_info
443{
444 char *extra;
79efa585 445 char *name;
dc146f7c 446 int core;
799a2abe
PA
447
448 /* Whether the target stopped for a breakpoint/watchpoint. */
449 enum target_stop_reason stop_reason;
450
451 /* This is set to the data address of the access causing the target
452 to stop for a watchpoint. */
453 CORE_ADDR watch_data_address;
dc146f7c
VP
454};
455
456static void
457free_private_thread_info (struct private_thread_info *info)
458{
459 xfree (info->extra);
79efa585 460 xfree (info->name);
dc146f7c
VP
461 xfree (info);
462}
463
ea9c271d
DJ
464/* This data could be associated with a target, but we do not always
465 have access to the current target when we need it, so for now it is
466 static. This will be fine for as long as only one target is in use
467 at a time. */
cf792862 468static struct remote_state *remote_state;
ea9c271d
DJ
469
470static struct remote_state *
0b83947e 471get_remote_state_raw (void)
ea9c271d 472{
cf792862
TT
473 return remote_state;
474}
475
476/* Allocate a new struct remote_state with xmalloc, initialize it, and
477 return it. */
478
479static struct remote_state *
480new_remote_state (void)
481{
482 struct remote_state *result = XCNEW (struct remote_state);
483
484 /* The default buffer size is unimportant; it will be expanded
485 whenever a larger buffer is needed. */
486 result->buf_size = 400;
224c3ddb 487 result->buf = (char *) xmalloc (result->buf_size);
262e1174 488 result->remote_traceframe_number = -1;
b73be471 489 result->last_sent_signal = GDB_SIGNAL_0;
3a00c802 490 result->last_resume_exec_dir = EXEC_FORWARD;
15a201c8 491 result->fs_pid = -1;
cf792862
TT
492
493 return result;
ea9c271d
DJ
494}
495
496/* Description of the remote protocol for a given architecture. */
d01949b6 497
ad10f812
AC
498struct packet_reg
499{
500 long offset; /* Offset into G packet. */
501 long regnum; /* GDB's internal register number. */
502 LONGEST pnum; /* Remote protocol register number. */
b323314b 503 int in_g_packet; /* Always part of G packet. */
f5656ead 504 /* long size in bytes; == register_size (target_gdbarch (), regnum);
23860348 505 at present. */
f5656ead 506 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
c9f4d572 507 at present. */
ad10f812
AC
508};
509
ea9c271d 510struct remote_arch_state
d01949b6 511{
ad10f812
AC
512 /* Description of the remote protocol registers. */
513 long sizeof_g_packet;
b323314b
AC
514
515 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 516 (making an array gdbarch_num_regs in size). */
b323314b 517 struct packet_reg *regs;
ad10f812 518
d01949b6
AC
519 /* This is the size (in chars) of the first response to the ``g''
520 packet. It is used as a heuristic when determining the maximum
521 size of memory-read and memory-write packets. A target will
522 typically only reserve a buffer large enough to hold the ``g''
523 packet. The size does not include packet overhead (headers and
23860348 524 trailers). */
d01949b6
AC
525 long actual_register_packet_size;
526
527 /* This is the maximum size (in chars) of a non read/write packet.
23860348 528 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
529 long remote_packet_size;
530};
531
35b1e5cc
SS
532/* Utility: generate error from an incoming stub packet. */
533static void
534trace_error (char *buf)
535{
536 if (*buf++ != 'E')
537 return; /* not an error msg */
538 switch (*buf)
539 {
540 case '1': /* malformed packet error */
541 if (*++buf == '0') /* general case: */
542 error (_("remote.c: error in outgoing packet."));
543 else
544 error (_("remote.c: error in outgoing packet at field #%ld."),
545 strtol (buf, NULL, 16));
35b1e5cc
SS
546 default:
547 error (_("Target returns error code '%s'."), buf);
548 }
549}
550
551/* Utility: wait for reply from stub, while accepting "O" packets. */
552static char *
553remote_get_noisy_reply (char **buf_p,
554 long *sizeof_buf)
555{
556 do /* Loop on reply from remote stub. */
557 {
558 char *buf;
a744cf53 559
0df8b418 560 QUIT; /* Allow user to bail out with ^C. */
35b1e5cc
SS
561 getpkt (buf_p, sizeof_buf, 0);
562 buf = *buf_p;
ad91cd99 563 if (buf[0] == 'E')
35b1e5cc 564 trace_error (buf);
61012eef 565 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
566 {
567 ULONGEST ul;
568 CORE_ADDR from, to, org_to;
569 char *p, *pp;
570 int adjusted_size = 0;
7556d4a4 571 int relocated = 0;
dde08ee1
PA
572
573 p = buf + strlen ("qRelocInsn:");
574 pp = unpack_varlen_hex (p, &ul);
575 if (*pp != ';')
cb91c06a 576 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
577 from = ul;
578
579 p = pp + 1;
a9cbf802 580 unpack_varlen_hex (p, &ul);
dde08ee1
PA
581 to = ul;
582
583 org_to = to;
584
492d29ea 585 TRY
dde08ee1 586 {
f5656ead 587 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 588 relocated = 1;
dde08ee1 589 }
492d29ea 590 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
591 {
592 if (ex.error == MEMORY_ERROR)
593 {
594 /* Propagate memory errors silently back to the
595 target. The stub may have limited the range of
596 addresses we can write to, for example. */
597 }
598 else
599 {
600 /* Something unexpectedly bad happened. Be verbose
601 so we can tell what, and propagate the error back
602 to the stub, so it doesn't get stuck waiting for
603 a response. */
604 exception_fprintf (gdb_stderr, ex,
605 _("warning: relocating instruction: "));
606 }
607 putpkt ("E01");
608 }
492d29ea 609 END_CATCH
7556d4a4
PA
610
611 if (relocated)
dde08ee1
PA
612 {
613 adjusted_size = to - org_to;
614
bba74b36 615 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
616 putpkt (buf);
617 }
dde08ee1 618 }
ad91cd99 619 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
620 remote_console_output (buf + 1); /* 'O' message from stub */
621 else
0df8b418 622 return buf; /* Here's the actual reply. */
35b1e5cc
SS
623 }
624 while (1);
625}
3c3bea1c 626
d01949b6
AC
627/* Handle for retreving the remote protocol data from gdbarch. */
628static struct gdbarch_data *remote_gdbarch_data_handle;
629
ea9c271d
DJ
630static struct remote_arch_state *
631get_remote_arch_state (void)
d01949b6 632{
17d8546e 633 gdb_assert (target_gdbarch () != NULL);
19ba03f4
SM
634 return ((struct remote_arch_state *)
635 gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
d01949b6
AC
636}
637
0b83947e
DJ
638/* Fetch the global remote target state. */
639
640static struct remote_state *
641get_remote_state (void)
642{
643 /* Make sure that the remote architecture state has been
644 initialized, because doing so might reallocate rs->buf. Any
645 function which calls getpkt also needs to be mindful of changes
646 to rs->buf, but this call limits the number of places which run
647 into trouble. */
648 get_remote_arch_state ();
649
650 return get_remote_state_raw ();
651}
652
94585166
DB
653/* Cleanup routine for the remote module's pspace data. */
654
655static void
656remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
657{
19ba03f4 658 char *remote_exec_file = (char *) arg;
94585166
DB
659
660 xfree (remote_exec_file);
661}
662
663/* Fetch the remote exec-file from the current program space. */
664
665static const char *
666get_remote_exec_file (void)
667{
668 char *remote_exec_file;
669
19ba03f4
SM
670 remote_exec_file
671 = (char *) program_space_data (current_program_space,
672 remote_pspace_data);
94585166
DB
673 if (remote_exec_file == NULL)
674 return "";
675
676 return remote_exec_file;
677}
678
679/* Set the remote exec file for PSPACE. */
680
681static void
682set_pspace_remote_exec_file (struct program_space *pspace,
683 char *remote_exec_file)
684{
19ba03f4 685 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
94585166
DB
686
687 xfree (old_file);
688 set_program_space_data (pspace, remote_pspace_data,
689 xstrdup (remote_exec_file));
690}
691
692/* The "set/show remote exec-file" set command hook. */
693
694static void
695set_remote_exec_file (char *ignored, int from_tty,
696 struct cmd_list_element *c)
697{
698 gdb_assert (remote_exec_file_var != NULL);
699 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
700}
701
702/* The "set/show remote exec-file" show command hook. */
703
704static void
705show_remote_exec_file (struct ui_file *file, int from_tty,
706 struct cmd_list_element *cmd, const char *value)
707{
708 fprintf_filtered (file, "%s\n", remote_exec_file_var);
709}
710
74ca34ce
DJ
711static int
712compare_pnums (const void *lhs_, const void *rhs_)
713{
19ba03f4
SM
714 const struct packet_reg * const *lhs
715 = (const struct packet_reg * const *) lhs_;
716 const struct packet_reg * const *rhs
717 = (const struct packet_reg * const *) rhs_;
74ca34ce
DJ
718
719 if ((*lhs)->pnum < (*rhs)->pnum)
720 return -1;
721 else if ((*lhs)->pnum == (*rhs)->pnum)
722 return 0;
723 else
724 return 1;
725}
726
c21236dc
PA
727static int
728map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 729{
74ca34ce 730 int regnum, num_remote_regs, offset;
74ca34ce 731 struct packet_reg **remote_regs;
ea9c271d 732
4a22f64d 733 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 734 {
c21236dc 735 struct packet_reg *r = &regs[regnum];
baef701f 736
4a22f64d 737 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
738 /* Do not try to fetch zero-sized (placeholder) registers. */
739 r->pnum = -1;
740 else
741 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
742
b323314b 743 r->regnum = regnum;
74ca34ce
DJ
744 }
745
746 /* Define the g/G packet format as the contents of each register
747 with a remote protocol number, in order of ascending protocol
748 number. */
749
224c3ddb 750 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 751 for (num_remote_regs = 0, regnum = 0;
4a22f64d 752 regnum < gdbarch_num_regs (gdbarch);
f57d151a 753 regnum++)
c21236dc
PA
754 if (regs[regnum].pnum != -1)
755 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 756
74ca34ce
DJ
757 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
758 compare_pnums);
759
760 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
761 {
762 remote_regs[regnum]->in_g_packet = 1;
763 remote_regs[regnum]->offset = offset;
4a22f64d 764 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
765 }
766
c21236dc
PA
767 return offset;
768}
769
770/* Given the architecture described by GDBARCH, return the remote
771 protocol register's number and the register's offset in the g/G
772 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
773 If the target does not have a mapping for REGNUM, return false,
774 otherwise, return true. */
775
776int
777remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
778 int *pnum, int *poffset)
779{
c21236dc
PA
780 struct packet_reg *regs;
781 struct cleanup *old_chain;
782
783 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
784
224c3ddb 785 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
c21236dc
PA
786 old_chain = make_cleanup (xfree, regs);
787
54887903 788 map_regcache_remote_table (gdbarch, regs);
c21236dc
PA
789
790 *pnum = regs[regnum].pnum;
791 *poffset = regs[regnum].offset;
792
793 do_cleanups (old_chain);
794
795 return *pnum != -1;
796}
797
798static void *
799init_remote_state (struct gdbarch *gdbarch)
800{
801 struct remote_state *rs = get_remote_state_raw ();
802 struct remote_arch_state *rsa;
803
804 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
805
806 /* Use the architecture to build a regnum<->pnum table, which will be
807 1:1 unless a feature set specifies otherwise. */
808 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
809 gdbarch_num_regs (gdbarch),
810 struct packet_reg);
811
74ca34ce
DJ
812 /* Record the maximum possible size of the g packet - it may turn out
813 to be smaller. */
c21236dc 814 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 815
0df8b418 816 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
817 remote stubs have a hardwired buffer size of 400 bytes
818 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
819 as the maximum packet-size to ensure that the packet and an extra
820 NUL character can always fit in the buffer. This stops GDB
821 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
822 already a full buffer (As of 1999-12-04 that was most stubs). */
823 rsa->remote_packet_size = 400 - 1;
d01949b6 824
ea9c271d
DJ
825 /* This one is filled in when a ``g'' packet is received. */
826 rsa->actual_register_packet_size = 0;
827
828 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
829 default, adjust the size accordingly. Remember that each byte is
830 encoded as two characters. 32 is the overhead for the packet
831 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 832 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 833 little. */
ea9c271d
DJ
834 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
835 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 836
ea9c271d
DJ
837 /* Make sure that the packet buffer is plenty big enough for
838 this architecture. */
839 if (rs->buf_size < rsa->remote_packet_size)
840 {
841 rs->buf_size = 2 * rsa->remote_packet_size;
224c3ddb 842 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
ea9c271d 843 }
6d820c5c 844
ea9c271d
DJ
845 return rsa;
846}
847
848/* Return the current allowed size of a remote packet. This is
849 inferred from the current architecture, and should be used to
850 limit the length of outgoing packets. */
851static long
852get_remote_packet_size (void)
853{
be2a5f71 854 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
855 struct remote_arch_state *rsa = get_remote_arch_state ();
856
be2a5f71
DJ
857 if (rs->explicit_packet_size)
858 return rs->explicit_packet_size;
859
ea9c271d 860 return rsa->remote_packet_size;
d01949b6
AC
861}
862
ad10f812 863static struct packet_reg *
ea9c271d 864packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 865{
f5656ead 866 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
b323314b
AC
867 return NULL;
868 else
ad10f812 869 {
ea9c271d 870 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 871
b323314b
AC
872 gdb_assert (r->regnum == regnum);
873 return r;
ad10f812 874 }
ad10f812
AC
875}
876
877static struct packet_reg *
ea9c271d 878packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 879{
b323314b 880 int i;
a744cf53 881
f5656ead 882 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
ad10f812 883 {
ea9c271d 884 struct packet_reg *r = &rsa->regs[i];
a744cf53 885
b323314b
AC
886 if (r->pnum == pnum)
887 return r;
ad10f812
AC
888 }
889 return NULL;
d01949b6
AC
890}
891
c906108c
SS
892static struct target_ops remote_ops;
893
894static struct target_ops extended_remote_ops;
895
6426a772
JM
896/* FIXME: cagney/1999-09-23: Even though getpkt was called with
897 ``forever'' still use the normal timeout mechanism. This is
898 currently used by the ASYNC code to guarentee that target reads
899 during the initial connect always time-out. Once getpkt has been
900 modified to return a timeout indication and, in turn
901 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 902 this can go away. */
6426a772
JM
903static int wait_forever_enabled_p = 1;
904
9a7071a8
JB
905/* Allow the user to specify what sequence to send to the remote
906 when he requests a program interruption: Although ^C is usually
907 what remote systems expect (this is the default, here), it is
908 sometimes preferable to send a break. On other systems such
909 as the Linux kernel, a break followed by g, which is Magic SysRq g
910 is required in order to interrupt the execution. */
911const char interrupt_sequence_control_c[] = "Ctrl-C";
912const char interrupt_sequence_break[] = "BREAK";
913const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 914static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
915 {
916 interrupt_sequence_control_c,
917 interrupt_sequence_break,
918 interrupt_sequence_break_g,
919 NULL
920 };
921static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
922
923static void
924show_interrupt_sequence (struct ui_file *file, int from_tty,
925 struct cmd_list_element *c,
926 const char *value)
927{
928 if (interrupt_sequence_mode == interrupt_sequence_control_c)
929 fprintf_filtered (file,
930 _("Send the ASCII ETX character (Ctrl-c) "
931 "to the remote target to interrupt the "
932 "execution of the program.\n"));
933 else if (interrupt_sequence_mode == interrupt_sequence_break)
934 fprintf_filtered (file,
935 _("send a break signal to the remote target "
936 "to interrupt the execution of the program.\n"));
937 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
938 fprintf_filtered (file,
939 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
940 "the remote target to interrupt the execution "
941 "of Linux kernel.\n"));
942 else
943 internal_error (__FILE__, __LINE__,
944 _("Invalid value for interrupt_sequence_mode: %s."),
945 interrupt_sequence_mode);
946}
6426a772 947
9a7071a8
JB
948/* This boolean variable specifies whether interrupt_sequence is sent
949 to the remote target when gdb connects to it.
950 This is mostly needed when you debug the Linux kernel: The Linux kernel
951 expects BREAK g which is Magic SysRq g for connecting gdb. */
952static int interrupt_on_connect = 0;
c906108c 953
9a7071a8
JB
954/* This variable is used to implement the "set/show remotebreak" commands.
955 Since these commands are now deprecated in favor of "set/show remote
956 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
957static int remote_break;
958
9a7071a8
JB
959static void
960set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
961{
962 if (remote_break)
963 interrupt_sequence_mode = interrupt_sequence_break;
964 else
965 interrupt_sequence_mode = interrupt_sequence_control_c;
966}
967
968static void
969show_remotebreak (struct ui_file *file, int from_tty,
970 struct cmd_list_element *c,
971 const char *value)
972{
973}
974
c906108c
SS
975/* This variable sets the number of bits in an address that are to be
976 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 977 leading zeros, the entire address would be sent. This variable
c906108c
SS
978 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
979 initial implementation of remote.c restricted the address sent in
980 memory packets to ``host::sizeof long'' bytes - (typically 32
981 bits). Consequently, for 64 bit targets, the upper 32 bits of an
982 address was never sent. Since fixing this bug may cause a break in
983 some remote targets this variable is principly provided to
23860348 984 facilitate backward compatibility. */
c906108c 985
883b9c6c 986static unsigned int remote_address_size;
c906108c 987
75c99385
PA
988/* Temporary to track who currently owns the terminal. See
989 remote_terminal_* for more details. */
6426a772
JM
990
991static int remote_async_terminal_ours_p;
992
11cf8741 993\f
11cf8741 994/* User configurable variables for the number of characters in a
ea9c271d
DJ
995 memory read/write packet. MIN (rsa->remote_packet_size,
996 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 997 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
998 (speed up transfers). The variables ``preferred_*'' (the user
999 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 1000 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
1001
1002struct memory_packet_config
1003{
1004 char *name;
1005 long size;
1006 int fixed_p;
1007};
1008
a5c0808e
PA
1009/* The default max memory-write-packet-size. The 16k is historical.
1010 (It came from older GDB's using alloca for buffers and the
1011 knowledge (folklore?) that some hosts don't cope very well with
1012 large alloca calls.) */
1013#define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1014
1015/* The minimum remote packet size for memory transfers. Ensures we
1016 can write at least one byte. */
1017#define MIN_MEMORY_PACKET_SIZE 20
1018
11cf8741
JM
1019/* Compute the current size of a read/write packet. Since this makes
1020 use of ``actual_register_packet_size'' the computation is dynamic. */
1021
1022static long
1023get_memory_packet_size (struct memory_packet_config *config)
1024{
d01949b6 1025 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
1026 struct remote_arch_state *rsa = get_remote_arch_state ();
1027
11cf8741
JM
1028 long what_they_get;
1029 if (config->fixed_p)
1030 {
1031 if (config->size <= 0)
a5c0808e 1032 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
11cf8741
JM
1033 else
1034 what_they_get = config->size;
1035 }
1036 else
1037 {
ea9c271d 1038 what_they_get = get_remote_packet_size ();
23860348 1039 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1040 if (config->size > 0
1041 && what_they_get > config->size)
1042 what_they_get = config->size;
be2a5f71
DJ
1043
1044 /* Limit it to the size of the targets ``g'' response unless we have
1045 permission from the stub to use a larger packet size. */
1046 if (rs->explicit_packet_size == 0
1047 && rsa->actual_register_packet_size > 0
1048 && what_they_get > rsa->actual_register_packet_size)
1049 what_they_get = rsa->actual_register_packet_size;
11cf8741 1050 }
a5c0808e
PA
1051 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1052 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1053
1054 /* Make sure there is room in the global buffer for this packet
1055 (including its trailing NUL byte). */
1056 if (rs->buf_size < what_they_get + 1)
1057 {
1058 rs->buf_size = 2 * what_they_get;
224c3ddb 1059 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
6d820c5c
DJ
1060 }
1061
11cf8741
JM
1062 return what_they_get;
1063}
1064
0df8b418 1065/* Update the size of a read/write packet. If they user wants
23860348 1066 something really big then do a sanity check. */
11cf8741
JM
1067
1068static void
1069set_memory_packet_size (char *args, struct memory_packet_config *config)
1070{
1071 int fixed_p = config->fixed_p;
1072 long size = config->size;
a744cf53 1073
11cf8741 1074 if (args == NULL)
8a3fe4f8 1075 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1076 else if (strcmp (args, "hard") == 0
1077 || strcmp (args, "fixed") == 0)
1078 fixed_p = 1;
1079 else if (strcmp (args, "soft") == 0
1080 || strcmp (args, "limit") == 0)
1081 fixed_p = 0;
1082 else
1083 {
1084 char *end;
a744cf53 1085
11cf8741
JM
1086 size = strtoul (args, &end, 0);
1087 if (args == end)
8a3fe4f8 1088 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1089
1090 /* Instead of explicitly capping the size of a packet to or
1091 disallowing it, the user is allowed to set the size to
1092 something arbitrarily large. */
11cf8741 1093 }
a5c0808e
PA
1094
1095 /* So that the query shows the correct value. */
1096 if (size <= 0)
1097 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1098
23860348 1099 /* Extra checks? */
11cf8741
JM
1100 if (fixed_p && !config->fixed_p)
1101 {
e2e0b3e5
AC
1102 if (! query (_("The target may not be able to correctly handle a %s\n"
1103 "of %ld bytes. Change the packet size? "),
11cf8741 1104 config->name, size))
8a3fe4f8 1105 error (_("Packet size not changed."));
11cf8741 1106 }
23860348 1107 /* Update the config. */
11cf8741
JM
1108 config->fixed_p = fixed_p;
1109 config->size = size;
1110}
1111
1112static void
1113show_memory_packet_size (struct memory_packet_config *config)
1114{
a3f17187 1115 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1116 if (config->fixed_p)
a3f17187 1117 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
1118 get_memory_packet_size (config));
1119 else
a3f17187 1120 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
1121 get_memory_packet_size (config));
1122}
1123
1124static struct memory_packet_config memory_write_packet_config =
1125{
1126 "memory-write-packet-size",
1127};
1128
1129static void
1130set_memory_write_packet_size (char *args, int from_tty)
1131{
1132 set_memory_packet_size (args, &memory_write_packet_config);
1133}
1134
1135static void
1136show_memory_write_packet_size (char *args, int from_tty)
1137{
1138 show_memory_packet_size (&memory_write_packet_config);
1139}
1140
1141static long
1142get_memory_write_packet_size (void)
1143{
1144 return get_memory_packet_size (&memory_write_packet_config);
1145}
1146
1147static struct memory_packet_config memory_read_packet_config =
1148{
1149 "memory-read-packet-size",
1150};
1151
1152static void
1153set_memory_read_packet_size (char *args, int from_tty)
1154{
1155 set_memory_packet_size (args, &memory_read_packet_config);
1156}
1157
1158static void
1159show_memory_read_packet_size (char *args, int from_tty)
1160{
1161 show_memory_packet_size (&memory_read_packet_config);
1162}
1163
1164static long
1165get_memory_read_packet_size (void)
1166{
1167 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1168
11cf8741
JM
1169 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1170 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1171 increased beyond this. */
1172 if (size > get_remote_packet_size ())
1173 size = get_remote_packet_size ();
11cf8741
JM
1174 return size;
1175}
1176
11cf8741 1177\f
5a2468f5 1178/* Generic configuration support for packets the stub optionally
0df8b418 1179 supports. Allows the user to specify the use of the packet as well
23860348 1180 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1181
1182enum packet_support
1183 {
1184 PACKET_SUPPORT_UNKNOWN = 0,
1185 PACKET_ENABLE,
1186 PACKET_DISABLE
1187 };
1188
5a2468f5
JM
1189struct packet_config
1190 {
bb572ddd
DJ
1191 const char *name;
1192 const char *title;
4082afcc
PA
1193
1194 /* If auto, GDB auto-detects support for this packet or feature,
1195 either through qSupported, or by trying the packet and looking
1196 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1197 packet. If false, the packet is disabled. Configs that don't
1198 have an associated command always have this set to auto. */
7f19b9a2 1199 enum auto_boolean detect;
4082afcc
PA
1200
1201 /* Does the target support this packet? */
5a2468f5
JM
1202 enum packet_support support;
1203 };
1204
d471ea57 1205/* Analyze a packet's return value and update the packet config
23860348 1206 accordingly. */
d471ea57
AC
1207
1208enum packet_result
1209{
1210 PACKET_ERROR,
1211 PACKET_OK,
1212 PACKET_UNKNOWN
1213};
1214
4082afcc
PA
1215static enum packet_support packet_config_support (struct packet_config *config);
1216static enum packet_support packet_support (int packet);
5a2468f5
JM
1217
1218static void
fba45db2 1219show_packet_config_cmd (struct packet_config *config)
5a2468f5
JM
1220{
1221 char *support = "internal-error";
a744cf53 1222
4082afcc 1223 switch (packet_config_support (config))
5a2468f5
JM
1224 {
1225 case PACKET_ENABLE:
1226 support = "enabled";
1227 break;
1228 case PACKET_DISABLE:
1229 support = "disabled";
1230 break;
1231 case PACKET_SUPPORT_UNKNOWN:
1232 support = "unknown";
1233 break;
1234 }
1235 switch (config->detect)
1236 {
7f19b9a2 1237 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1238 printf_filtered (_("Support for the `%s' packet "
1239 "is auto-detected, currently %s.\n"),
37a105a1 1240 config->name, support);
5a2468f5 1241 break;
7f19b9a2
AC
1242 case AUTO_BOOLEAN_TRUE:
1243 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1244 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1245 config->name, support);
8e248173 1246 break;
5a2468f5
JM
1247 }
1248}
1249
1250static void
bb572ddd
DJ
1251add_packet_config_cmd (struct packet_config *config, const char *name,
1252 const char *title, int legacy)
d471ea57 1253{
5a2468f5
JM
1254 char *set_doc;
1255 char *show_doc;
d471ea57 1256 char *cmd_name;
3ed07be4 1257
5a2468f5
JM
1258 config->name = name;
1259 config->title = title;
b435e160
AC
1260 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1261 name, title);
3e43a32a
MS
1262 show_doc = xstrprintf ("Show current use of remote "
1263 "protocol `%s' (%s) packet",
b435e160 1264 name, title);
d471ea57 1265 /* set/show TITLE-packet {auto,on,off} */
b435e160 1266 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1267 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1268 &config->detect, set_doc,
1269 show_doc, NULL, /* help_doc */
4082afcc 1270 NULL,
bb572ddd
DJ
1271 show_remote_protocol_packet_cmd,
1272 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1273 /* The command code copies the documentation strings. */
1274 xfree (set_doc);
1275 xfree (show_doc);
23860348 1276 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1277 if (legacy)
1278 {
1279 char *legacy_name;
a744cf53 1280
b435e160 1281 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1282 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1283 &remote_set_cmdlist);
d471ea57 1284 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1285 &remote_show_cmdlist);
d471ea57 1286 }
5a2468f5
JM
1287}
1288
d471ea57 1289static enum packet_result
a76d924d 1290packet_check_result (const char *buf)
5a2468f5 1291{
d471ea57 1292 if (buf[0] != '\0')
5a2468f5 1293 {
d471ea57 1294 /* The stub recognized the packet request. Check that the
23860348 1295 operation succeeded. */
a76d924d
DJ
1296 if (buf[0] == 'E'
1297 && isxdigit (buf[1]) && isxdigit (buf[2])
1298 && buf[3] == '\0')
1299 /* "Enn" - definitly an error. */
1300 return PACKET_ERROR;
1301
1302 /* Always treat "E." as an error. This will be used for
1303 more verbose error messages, such as E.memtypes. */
1304 if (buf[0] == 'E' && buf[1] == '.')
1305 return PACKET_ERROR;
1306
1307 /* The packet may or may not be OK. Just assume it is. */
1308 return PACKET_OK;
1309 }
1310 else
1311 /* The stub does not support the packet. */
1312 return PACKET_UNKNOWN;
1313}
1314
1315static enum packet_result
1316packet_ok (const char *buf, struct packet_config *config)
1317{
1318 enum packet_result result;
1319
4082afcc
PA
1320 if (config->detect != AUTO_BOOLEAN_TRUE
1321 && config->support == PACKET_DISABLE)
1322 internal_error (__FILE__, __LINE__,
1323 _("packet_ok: attempt to use a disabled packet"));
1324
a76d924d
DJ
1325 result = packet_check_result (buf);
1326 switch (result)
1327 {
1328 case PACKET_OK:
1329 case PACKET_ERROR:
1330 /* The stub recognized the packet request. */
4082afcc 1331 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1332 {
d471ea57
AC
1333 if (remote_debug)
1334 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1335 "Packet %s (%s) is supported\n",
1336 config->name, config->title);
d471ea57 1337 config->support = PACKET_ENABLE;
d471ea57 1338 }
a76d924d
DJ
1339 break;
1340 case PACKET_UNKNOWN:
23860348 1341 /* The stub does not support the packet. */
4082afcc
PA
1342 if (config->detect == AUTO_BOOLEAN_AUTO
1343 && config->support == PACKET_ENABLE)
d471ea57 1344 {
4082afcc
PA
1345 /* If the stub previously indicated that the packet was
1346 supported then there is a protocol error. */
1347 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1348 config->name, config->title);
1349 }
1350 else if (config->detect == AUTO_BOOLEAN_TRUE)
1351 {
1352 /* The user set it wrong. */
1353 error (_("Enabled packet %s (%s) not recognized by stub"),
1354 config->name, config->title);
d471ea57 1355 }
4082afcc
PA
1356
1357 if (remote_debug)
1358 fprintf_unfiltered (gdb_stdlog,
1359 "Packet %s (%s) is NOT supported\n",
1360 config->name, config->title);
1361 config->support = PACKET_DISABLE;
a76d924d 1362 break;
5a2468f5 1363 }
a76d924d
DJ
1364
1365 return result;
5a2468f5
JM
1366}
1367
444abaca
DJ
1368enum {
1369 PACKET_vCont = 0,
1370 PACKET_X,
1371 PACKET_qSymbol,
1372 PACKET_P,
1373 PACKET_p,
1374 PACKET_Z0,
1375 PACKET_Z1,
1376 PACKET_Z2,
1377 PACKET_Z3,
1378 PACKET_Z4,
15a201c8 1379 PACKET_vFile_setfs,
a6b151f1
DJ
1380 PACKET_vFile_open,
1381 PACKET_vFile_pread,
1382 PACKET_vFile_pwrite,
1383 PACKET_vFile_close,
1384 PACKET_vFile_unlink,
b9e7b9c3 1385 PACKET_vFile_readlink,
0a93529c 1386 PACKET_vFile_fstat,
0876f84a 1387 PACKET_qXfer_auxv,
23181151 1388 PACKET_qXfer_features,
c78fa86a 1389 PACKET_qXfer_exec_file,
cfa9d6d9 1390 PACKET_qXfer_libraries,
2268b414 1391 PACKET_qXfer_libraries_svr4,
fd79ecee 1392 PACKET_qXfer_memory_map,
0e7f50da
UW
1393 PACKET_qXfer_spu_read,
1394 PACKET_qXfer_spu_write,
07e059b5 1395 PACKET_qXfer_osdata,
dc146f7c 1396 PACKET_qXfer_threads,
0fb4aa4b 1397 PACKET_qXfer_statictrace_read,
b3b9301e 1398 PACKET_qXfer_traceframe_info,
169081d0 1399 PACKET_qXfer_uib,
711e434b 1400 PACKET_qGetTIBAddr,
444abaca 1401 PACKET_qGetTLSAddr,
be2a5f71 1402 PACKET_qSupported,
bd3eecc3 1403 PACKET_qTStatus,
89be2091 1404 PACKET_QPassSignals,
82075af2 1405 PACKET_QCatchSyscalls,
9b224c5e 1406 PACKET_QProgramSignals,
936d2992 1407 PACKET_qCRC,
08388c79 1408 PACKET_qSearch_memory,
2d717e4f
DJ
1409 PACKET_vAttach,
1410 PACKET_vRun,
a6f3e723 1411 PACKET_QStartNoAckMode,
82f73884 1412 PACKET_vKill,
4aa995e1
PA
1413 PACKET_qXfer_siginfo_read,
1414 PACKET_qXfer_siginfo_write,
0b16c5cf 1415 PACKET_qAttached,
4082afcc
PA
1416
1417 /* Support for conditional tracepoints. */
782b2b07 1418 PACKET_ConditionalTracepoints,
4082afcc
PA
1419
1420 /* Support for target-side breakpoint conditions. */
3788aec7 1421 PACKET_ConditionalBreakpoints,
4082afcc
PA
1422
1423 /* Support for target-side breakpoint commands. */
d3ce09f5 1424 PACKET_BreakpointCommands,
4082afcc
PA
1425
1426 /* Support for fast tracepoints. */
7a697b8d 1427 PACKET_FastTracepoints,
4082afcc
PA
1428
1429 /* Support for static tracepoints. */
0fb4aa4b 1430 PACKET_StaticTracepoints,
4082afcc
PA
1431
1432 /* Support for installing tracepoints while a trace experiment is
1433 running. */
1e4d1764 1434 PACKET_InstallInTrace,
4082afcc 1435
40ab02ce
MS
1436 PACKET_bc,
1437 PACKET_bs,
409873ef 1438 PACKET_TracepointSource,
d914c394 1439 PACKET_QAllow,
78d85199 1440 PACKET_qXfer_fdpic,
03583c20 1441 PACKET_QDisableRandomization,
d1feda86 1442 PACKET_QAgent,
f6f899bf 1443 PACKET_QTBuffer_size,
9accd112
MM
1444 PACKET_Qbtrace_off,
1445 PACKET_Qbtrace_bts,
b20a6524 1446 PACKET_Qbtrace_pt,
9accd112 1447 PACKET_qXfer_btrace,
4082afcc
PA
1448
1449 /* Support for the QNonStop packet. */
1450 PACKET_QNonStop,
1451
65706a29
PA
1452 /* Support for the QThreadEvents packet. */
1453 PACKET_QThreadEvents,
1454
4082afcc
PA
1455 /* Support for multi-process extensions. */
1456 PACKET_multiprocess_feature,
1457
1458 /* Support for enabling and disabling tracepoints while a trace
1459 experiment is running. */
1460 PACKET_EnableDisableTracepoints_feature,
1461
1462 /* Support for collecting strings using the tracenz bytecode. */
1463 PACKET_tracenz_feature,
1464
1465 /* Support for continuing to run a trace experiment while GDB is
1466 disconnected. */
1467 PACKET_DisconnectedTracing_feature,
1468
1469 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1470 PACKET_augmented_libraries_svr4_read_feature,
1471
f4abbc16
MM
1472 /* Support for the qXfer:btrace-conf:read packet. */
1473 PACKET_qXfer_btrace_conf,
1474
d33501a5
MM
1475 /* Support for the Qbtrace-conf:bts:size packet. */
1476 PACKET_Qbtrace_conf_bts_size,
1477
f7e6eed5
PA
1478 /* Support for swbreak+ feature. */
1479 PACKET_swbreak_feature,
1480
1481 /* Support for hwbreak+ feature. */
1482 PACKET_hwbreak_feature,
1483
89245bc0
DB
1484 /* Support for fork events. */
1485 PACKET_fork_event_feature,
1486
1487 /* Support for vfork events. */
1488 PACKET_vfork_event_feature,
1489
b20a6524
MM
1490 /* Support for the Qbtrace-conf:pt:size packet. */
1491 PACKET_Qbtrace_conf_pt_size,
1492
94585166
DB
1493 /* Support for exec events. */
1494 PACKET_exec_event_feature,
1495
750ce8d1
YQ
1496 /* Support for query supported vCont actions. */
1497 PACKET_vContSupported,
1498
de979965
PA
1499 /* Support remote CTRL-C. */
1500 PACKET_vCtrlC,
1501
f2faf941
PA
1502 /* Support TARGET_WAITKIND_NO_RESUMED. */
1503 PACKET_no_resumed,
1504
444abaca
DJ
1505 PACKET_MAX
1506};
506fb367 1507
444abaca 1508static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1509
f7e6eed5
PA
1510/* Returns the packet's corresponding "set remote foo-packet" command
1511 state. See struct packet_config for more details. */
1512
1513static enum auto_boolean
1514packet_set_cmd_state (int packet)
1515{
1516 return remote_protocol_packets[packet].detect;
1517}
1518
4082afcc
PA
1519/* Returns whether a given packet or feature is supported. This takes
1520 into account the state of the corresponding "set remote foo-packet"
1521 command, which may be used to bypass auto-detection. */
dc8acb97 1522
4082afcc
PA
1523static enum packet_support
1524packet_config_support (struct packet_config *config)
1525{
1526 switch (config->detect)
444abaca 1527 {
4082afcc
PA
1528 case AUTO_BOOLEAN_TRUE:
1529 return PACKET_ENABLE;
1530 case AUTO_BOOLEAN_FALSE:
1531 return PACKET_DISABLE;
1532 case AUTO_BOOLEAN_AUTO:
1533 return config->support;
1534 default:
1535 gdb_assert_not_reached (_("bad switch"));
444abaca 1536 }
4082afcc
PA
1537}
1538
1539/* Same as packet_config_support, but takes the packet's enum value as
1540 argument. */
1541
1542static enum packet_support
1543packet_support (int packet)
1544{
1545 struct packet_config *config = &remote_protocol_packets[packet];
1546
1547 return packet_config_support (config);
dc8acb97
MS
1548}
1549
5a2468f5 1550static void
444abaca
DJ
1551show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1552 struct cmd_list_element *c,
1553 const char *value)
5a2468f5 1554{
444abaca 1555 struct packet_config *packet;
5a2468f5 1556
444abaca
DJ
1557 for (packet = remote_protocol_packets;
1558 packet < &remote_protocol_packets[PACKET_MAX];
1559 packet++)
1560 {
1561 if (&packet->detect == c->var)
1562 {
1563 show_packet_config_cmd (packet);
1564 return;
1565 }
1566 }
9b20d036 1567 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1568 c->name);
5a2468f5
JM
1569}
1570
d471ea57
AC
1571/* Should we try one of the 'Z' requests? */
1572
1573enum Z_packet_type
1574{
1575 Z_PACKET_SOFTWARE_BP,
1576 Z_PACKET_HARDWARE_BP,
1577 Z_PACKET_WRITE_WP,
1578 Z_PACKET_READ_WP,
1579 Z_PACKET_ACCESS_WP,
1580 NR_Z_PACKET_TYPES
1581};
96baa820 1582
d471ea57 1583/* For compatibility with older distributions. Provide a ``set remote
23860348 1584 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1585
7f19b9a2 1586static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1587
1588static void
fba45db2
KB
1589set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1590 struct cmd_list_element *c)
96baa820 1591{
d471ea57 1592 int i;
a744cf53 1593
d471ea57 1594 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1595 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1596}
1597
1598static void
08546159
AC
1599show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1600 struct cmd_list_element *c,
1601 const char *value)
96baa820 1602{
d471ea57 1603 int i;
a744cf53 1604
d471ea57
AC
1605 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1606 {
444abaca 1607 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1608 }
96baa820
JM
1609}
1610
4082afcc
PA
1611/* Returns true if the multi-process extensions are in effect. */
1612
1613static int
1614remote_multi_process_p (struct remote_state *rs)
1615{
1616 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1617}
1618
de0d863e
DB
1619/* Returns true if fork events are supported. */
1620
1621static int
1622remote_fork_event_p (struct remote_state *rs)
1623{
1624 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1625}
1626
c269dbdb
DB
1627/* Returns true if vfork events are supported. */
1628
1629static int
1630remote_vfork_event_p (struct remote_state *rs)
1631{
1632 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1633}
1634
d46addbb
DB
1635/* Returns true if exec events are supported. */
1636
1637static int
1638remote_exec_event_p (struct remote_state *rs)
1639{
1640 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1641}
1642
cbb8991c
DB
1643/* Insert fork catchpoint target routine. If fork events are enabled
1644 then return success, nothing more to do. */
1645
1646static int
1647remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1648{
1649 struct remote_state *rs = get_remote_state ();
1650
1651 return !remote_fork_event_p (rs);
1652}
1653
1654/* Remove fork catchpoint target routine. Nothing to do, just
1655 return success. */
1656
1657static int
1658remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1659{
1660 return 0;
1661}
1662
1663/* Insert vfork catchpoint target routine. If vfork events are enabled
1664 then return success, nothing more to do. */
1665
1666static int
1667remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1668{
1669 struct remote_state *rs = get_remote_state ();
1670
1671 return !remote_vfork_event_p (rs);
1672}
1673
1674/* Remove vfork catchpoint target routine. Nothing to do, just
1675 return success. */
1676
1677static int
1678remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1679{
1680 return 0;
1681}
1682
d46addbb
DB
1683/* Insert exec catchpoint target routine. If exec events are
1684 enabled, just return success. */
1685
1686static int
1687remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1688{
1689 struct remote_state *rs = get_remote_state ();
1690
1691 return !remote_exec_event_p (rs);
1692}
1693
1694/* Remove exec catchpoint target routine. Nothing to do, just
1695 return success. */
1696
1697static int
1698remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1699{
1700 return 0;
1701}
1702
74531fed
PA
1703\f
1704/* Asynchronous signal handle registered as event loop source for
1705 when we have pending events ready to be passed to the core. */
1706
1707static struct async_event_handler *remote_async_inferior_event_token;
1708
c906108c
SS
1709\f
1710
79d7f229
PA
1711static ptid_t magic_null_ptid;
1712static ptid_t not_sent_ptid;
1713static ptid_t any_thread_ptid;
1714
0b16c5cf
PA
1715/* Find out if the stub attached to PID (and hence GDB should offer to
1716 detach instead of killing it when bailing out). */
1717
1718static int
1719remote_query_attached (int pid)
1720{
1721 struct remote_state *rs = get_remote_state ();
bba74b36 1722 size_t size = get_remote_packet_size ();
0b16c5cf 1723
4082afcc 1724 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1725 return 0;
1726
1727 if (remote_multi_process_p (rs))
bba74b36 1728 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1729 else
bba74b36 1730 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1731
1732 putpkt (rs->buf);
1733 getpkt (&rs->buf, &rs->buf_size, 0);
1734
1735 switch (packet_ok (rs->buf,
1554e9be 1736 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1737 {
1738 case PACKET_OK:
1739 if (strcmp (rs->buf, "1") == 0)
1740 return 1;
1741 break;
1742 case PACKET_ERROR:
1743 warning (_("Remote failure reply: %s"), rs->buf);
1744 break;
1745 case PACKET_UNKNOWN:
1746 break;
1747 }
1748
1749 return 0;
1750}
1751
49c62f2e
PA
1752/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1753 has been invented by GDB, instead of reported by the target. Since
1754 we can be connected to a remote system before before knowing about
1755 any inferior, mark the target with execution when we find the first
1756 inferior. If ATTACHED is 1, then we had just attached to this
1757 inferior. If it is 0, then we just created this inferior. If it
1758 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
1759 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1760 attempt to open this inferior's executable as the main executable
1761 if no main executable is open already. */
1941c569
PA
1762
1763static struct inferior *
1b6e6f5c
GB
1764remote_add_inferior (int fake_pid_p, int pid, int attached,
1765 int try_open_exec)
1941c569 1766{
1941c569
PA
1767 struct inferior *inf;
1768
0b16c5cf
PA
1769 /* Check whether this process we're learning about is to be
1770 considered attached, or if is to be considered to have been
1771 spawned by the stub. */
1772 if (attached == -1)
1773 attached = remote_query_attached (pid);
1774
f5656ead 1775 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1776 {
1777 /* If the target shares code across all inferiors, then every
1778 attach adds a new inferior. */
1779 inf = add_inferior (pid);
1780
1781 /* ... and every inferior is bound to the same program space.
1782 However, each inferior may still have its own address
1783 space. */
1784 inf->aspace = maybe_new_address_space ();
1785 inf->pspace = current_program_space;
1786 }
1787 else
1788 {
1789 /* In the traditional debugging scenario, there's a 1-1 match
1790 between program/address spaces. We simply bind the inferior
1791 to the program space's address space. */
1792 inf = current_inferior ();
1793 inferior_appeared (inf, pid);
1794 }
1941c569 1795
0b16c5cf 1796 inf->attach_flag = attached;
49c62f2e 1797 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1798
1b6e6f5c
GB
1799 /* If no main executable is currently open then attempt to
1800 open the file that was executed to create this inferior. */
835205d0 1801 if (try_open_exec && get_exec_file (0) == NULL)
1b6e6f5c
GB
1802 exec_file_locate_attach (pid, 1);
1803
1941c569
PA
1804 return inf;
1805}
1806
1807/* Add thread PTID to GDB's thread list. Tag it as executing/running
1808 according to RUNNING. */
1809
c906108c 1810static void
0d5b594f 1811remote_add_thread (ptid_t ptid, int running, int executing)
c906108c 1812{
b7ea362b
PA
1813 struct remote_state *rs = get_remote_state ();
1814
1815 /* GDB historically didn't pull threads in the initial connection
1816 setup. If the remote target doesn't even have a concept of
1817 threads (e.g., a bare-metal target), even if internally we
1818 consider that a single-threaded target, mentioning a new thread
1819 might be confusing to the user. Be silent then, preserving the
1820 age old behavior. */
1821 if (rs->starting_up)
1822 add_thread_silent (ptid);
1823 else
1824 add_thread (ptid);
1941c569 1825
0d5b594f 1826 set_executing (ptid, executing);
1941c569
PA
1827 set_running (ptid, running);
1828}
1829
1830/* Come here when we learn about a thread id from the remote target.
1831 It may be the first time we hear about such thread, so take the
1832 opportunity to add it to GDB's thread list. In case this is the
1833 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
1834 GDB's inferior list as well. EXECUTING indicates whether the
1835 thread is (internally) executing or stopped. */
1941c569
PA
1836
1837static void
0d5b594f 1838remote_notice_new_inferior (ptid_t currthread, int executing)
1941c569 1839{
0d5b594f
PA
1840 /* In non-stop mode, we assume new found threads are (externally)
1841 running until proven otherwise with a stop reply. In all-stop,
1842 we can only get here if all threads are stopped. */
1843 int running = target_is_non_stop_p () ? 1 : 0;
1844
c906108c
SS
1845 /* If this is a new thread, add it to GDB's thread list.
1846 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1847
1848 if (in_thread_list (currthread) && is_exited (currthread))
1849 {
1850 /* We're seeing an event on a thread id we knew had exited.
1851 This has to be a new thread reusing the old id. Add it. */
0d5b594f 1852 remote_add_thread (currthread, running, executing);
82f73884
PA
1853 return;
1854 }
1855
79d7f229 1856 if (!in_thread_list (currthread))
c0a2216e 1857 {
1941c569 1858 struct inferior *inf = NULL;
bad34192 1859 int pid = ptid_get_pid (currthread);
1941c569 1860
bad34192
PA
1861 if (ptid_is_pid (inferior_ptid)
1862 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1863 {
1864 /* inferior_ptid has no thread member yet. This can happen
1865 with the vAttach -> remote_wait,"TAAthread:" path if the
1866 stub doesn't support qC. This is the first stop reported
1867 after an attach, so this is the main thread. Update the
1868 ptid in the thread list. */
bad34192
PA
1869 if (in_thread_list (pid_to_ptid (pid)))
1870 thread_change_ptid (inferior_ptid, currthread);
1871 else
1872 {
0d5b594f 1873 remote_add_thread (currthread, running, executing);
bad34192
PA
1874 inferior_ptid = currthread;
1875 }
dc146f7c 1876 return;
c0a2216e 1877 }
82f73884
PA
1878
1879 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1880 {
1881 /* inferior_ptid is not set yet. This can happen with the
1882 vRun -> remote_wait,"TAAthread:" path if the stub
1883 doesn't support qC. This is the first stop reported
1884 after an attach, so this is the main thread. Update the
1885 ptid in the thread list. */
dc146f7c 1886 thread_change_ptid (inferior_ptid, currthread);
82f73884 1887 return;
c0a2216e 1888 }
82f73884 1889
29c87f7f
PA
1890 /* When connecting to a target remote, or to a target
1891 extended-remote which already was debugging an inferior, we
1892 may not know about it yet. Add it before adding its child
1893 thread, so notifications are emitted in a sensible order. */
1894 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1895 {
1896 struct remote_state *rs = get_remote_state ();
1897 int fake_pid_p = !remote_multi_process_p (rs);
1898
1899 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 1900 ptid_get_pid (currthread), -1, 1);
49c62f2e 1901 }
29c87f7f 1902
82f73884 1903 /* This is really a new thread. Add it. */
0d5b594f 1904 remote_add_thread (currthread, running, executing);
1941c569
PA
1905
1906 /* If we found a new inferior, let the common code do whatever
1907 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1908 breakpoints), unless we're just setting up an all-stop
1909 connection. */
1941c569 1910 if (inf != NULL)
b7ea362b
PA
1911 {
1912 struct remote_state *rs = get_remote_state ();
1913
6efcd9a8 1914 if (!rs->starting_up)
0d5b594f 1915 notice_new_inferior (currthread, executing, 0);
b7ea362b 1916 }
c0a2216e 1917 }
c906108c
SS
1918}
1919
dc146f7c
VP
1920/* Return the private thread data, creating it if necessary. */
1921
70221824 1922static struct private_thread_info *
dc146f7c
VP
1923demand_private_info (ptid_t ptid)
1924{
1925 struct thread_info *info = find_thread_ptid (ptid);
1926
1927 gdb_assert (info);
1928
fe978cb0 1929 if (!info->priv)
dc146f7c 1930 {
8d749320 1931 info->priv = XNEW (struct private_thread_info);
dc146f7c 1932 info->private_dtor = free_private_thread_info;
fe978cb0 1933 info->priv->core = -1;
8020350c
DB
1934 info->priv->extra = NULL;
1935 info->priv->name = NULL;
dc146f7c
VP
1936 }
1937
fe978cb0 1938 return info->priv;
dc146f7c
VP
1939}
1940
74531fed
PA
1941/* Call this function as a result of
1942 1) A halt indication (T packet) containing a thread id
1943 2) A direct query of currthread
0df8b418 1944 3) Successful execution of set thread */
74531fed
PA
1945
1946static void
47f8a51d 1947record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1948{
47f8a51d 1949 rs->general_thread = currthread;
74531fed
PA
1950}
1951
89be2091
DJ
1952/* If 'QPassSignals' is supported, tell the remote stub what signals
1953 it can simply pass through to the inferior without reporting. */
1954
1955static void
94bedb42
TT
1956remote_pass_signals (struct target_ops *self,
1957 int numsigs, unsigned char *pass_signals)
89be2091 1958{
4082afcc 1959 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
1960 {
1961 char *pass_packet, *p;
89be2091 1962 int count = 0, i;
747dc59d 1963 struct remote_state *rs = get_remote_state ();
89be2091
DJ
1964
1965 gdb_assert (numsigs < 256);
1966 for (i = 0; i < numsigs; i++)
1967 {
2455069d 1968 if (pass_signals[i])
89be2091
DJ
1969 count++;
1970 }
224c3ddb 1971 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
1972 strcpy (pass_packet, "QPassSignals:");
1973 p = pass_packet + strlen (pass_packet);
1974 for (i = 0; i < numsigs; i++)
1975 {
2455069d 1976 if (pass_signals[i])
89be2091
DJ
1977 {
1978 if (i >= 16)
1979 *p++ = tohex (i >> 4);
1980 *p++ = tohex (i & 15);
1981 if (count)
1982 *p++ = ';';
1983 else
1984 break;
1985 count--;
1986 }
1987 }
1988 *p = 0;
747dc59d 1989 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 1990 {
89be2091
DJ
1991 putpkt (pass_packet);
1992 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1993 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
1994 if (rs->last_pass_packet)
1995 xfree (rs->last_pass_packet);
1996 rs->last_pass_packet = pass_packet;
89be2091
DJ
1997 }
1998 else
1999 xfree (pass_packet);
2000 }
2001}
2002
82075af2
JS
2003/* If 'QCatchSyscalls' is supported, tell the remote stub
2004 to report syscalls to GDB. */
2005
2006static int
2007remote_set_syscall_catchpoint (struct target_ops *self,
2008 int pid, int needed, int any_count,
2009 int table_size, int *table)
2010{
2011 char *catch_packet;
2012 enum packet_result result;
2013 int n_sysno = 0;
2014
2015 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2016 {
2017 /* Not supported. */
2018 return 1;
2019 }
2020
2021 if (needed && !any_count)
2022 {
2023 int i;
2024
2025 /* Count how many syscalls are to be caught (table[sysno] != 0). */
2026 for (i = 0; i < table_size; i++)
2027 {
2028 if (table[i] != 0)
2029 n_sysno++;
2030 }
2031 }
2032
2033 if (remote_debug)
2034 {
2035 fprintf_unfiltered (gdb_stdlog,
2036 "remote_set_syscall_catchpoint "
2037 "pid %d needed %d any_count %d n_sysno %d\n",
2038 pid, needed, any_count, n_sysno);
2039 }
2040
2041 if (needed)
2042 {
2043 /* Prepare a packet with the sysno list, assuming max 8+1
2044 characters for a sysno. If the resulting packet size is too
2045 big, fallback on the non-selective packet. */
2046 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2047
c0518081 2048 catch_packet = (char *) xmalloc (maxpktsz);
82075af2
JS
2049 strcpy (catch_packet, "QCatchSyscalls:1");
2050 if (!any_count)
2051 {
2052 int i;
2053 char *p;
2054
2055 p = catch_packet;
2056 p += strlen (p);
2057
2058 /* Add in catch_packet each syscall to be caught (table[i] != 0). */
2059 for (i = 0; i < table_size; i++)
2060 {
2061 if (table[i] != 0)
2062 p += xsnprintf (p, catch_packet + maxpktsz - p, ";%x", i);
2063 }
2064 }
2065 if (strlen (catch_packet) > get_remote_packet_size ())
2066 {
2067 /* catch_packet too big. Fallback to less efficient
2068 non selective mode, with GDB doing the filtering. */
2069 catch_packet[sizeof ("QCatchSyscalls:1") - 1] = 0;
2070 }
2071 }
2072 else
2073 catch_packet = xstrdup ("QCatchSyscalls:0");
2074
2075 {
2076 struct cleanup *old_chain = make_cleanup (xfree, catch_packet);
2077 struct remote_state *rs = get_remote_state ();
2078
2079 putpkt (catch_packet);
2080 getpkt (&rs->buf, &rs->buf_size, 0);
2081 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2082 do_cleanups (old_chain);
2083 if (result == PACKET_OK)
2084 return 0;
2085 else
2086 return -1;
2087 }
2088}
2089
9b224c5e
PA
2090/* If 'QProgramSignals' is supported, tell the remote stub what
2091 signals it should pass through to the inferior when detaching. */
2092
2093static void
daf5e9b6
TT
2094remote_program_signals (struct target_ops *self,
2095 int numsigs, unsigned char *signals)
9b224c5e 2096{
4082afcc 2097 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2098 {
2099 char *packet, *p;
2100 int count = 0, i;
5e4a05c4 2101 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
2102
2103 gdb_assert (numsigs < 256);
2104 for (i = 0; i < numsigs; i++)
2105 {
2106 if (signals[i])
2107 count++;
2108 }
224c3ddb 2109 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2110 strcpy (packet, "QProgramSignals:");
2111 p = packet + strlen (packet);
2112 for (i = 0; i < numsigs; i++)
2113 {
2114 if (signal_pass_state (i))
2115 {
2116 if (i >= 16)
2117 *p++ = tohex (i >> 4);
2118 *p++ = tohex (i & 15);
2119 if (count)
2120 *p++ = ';';
2121 else
2122 break;
2123 count--;
2124 }
2125 }
2126 *p = 0;
5e4a05c4
TT
2127 if (!rs->last_program_signals_packet
2128 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2129 {
9b224c5e
PA
2130 putpkt (packet);
2131 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2132 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2133 xfree (rs->last_program_signals_packet);
2134 rs->last_program_signals_packet = packet;
9b224c5e
PA
2135 }
2136 else
2137 xfree (packet);
2138 }
2139}
2140
79d7f229
PA
2141/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2142 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2143 thread. If GEN is set, set the general thread, if not, then set
2144 the step/continue thread. */
c906108c 2145static void
79d7f229 2146set_thread (struct ptid ptid, int gen)
c906108c 2147{
d01949b6 2148 struct remote_state *rs = get_remote_state ();
47f8a51d 2149 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 2150 char *buf = rs->buf;
79d7f229 2151 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 2152
79d7f229 2153 if (ptid_equal (state, ptid))
c906108c
SS
2154 return;
2155
79d7f229
PA
2156 *buf++ = 'H';
2157 *buf++ = gen ? 'g' : 'c';
2158 if (ptid_equal (ptid, magic_null_ptid))
2159 xsnprintf (buf, endbuf - buf, "0");
2160 else if (ptid_equal (ptid, any_thread_ptid))
2161 xsnprintf (buf, endbuf - buf, "0");
2162 else if (ptid_equal (ptid, minus_one_ptid))
2163 xsnprintf (buf, endbuf - buf, "-1");
2164 else
82f73884 2165 write_ptid (buf, endbuf, ptid);
79d7f229 2166 putpkt (rs->buf);
6d820c5c 2167 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2168 if (gen)
47f8a51d 2169 rs->general_thread = ptid;
c906108c 2170 else
47f8a51d 2171 rs->continue_thread = ptid;
c906108c 2172}
79d7f229
PA
2173
2174static void
2175set_general_thread (struct ptid ptid)
2176{
2177 set_thread (ptid, 1);
2178}
2179
2180static void
2181set_continue_thread (struct ptid ptid)
2182{
2183 set_thread (ptid, 0);
2184}
2185
3c9c4b83
PA
2186/* Change the remote current process. Which thread within the process
2187 ends up selected isn't important, as long as it is the same process
2188 as what INFERIOR_PTID points to.
2189
2190 This comes from that fact that there is no explicit notion of
2191 "selected process" in the protocol. The selected process for
2192 general operations is the process the selected general thread
2193 belongs to. */
2194
2195static void
2196set_general_process (void)
2197{
2198 struct remote_state *rs = get_remote_state ();
2199
2200 /* If the remote can't handle multiple processes, don't bother. */
8020350c 2201 if (!remote_multi_process_p (rs))
3c9c4b83
PA
2202 return;
2203
2204 /* We only need to change the remote current thread if it's pointing
2205 at some other process. */
47f8a51d 2206 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
2207 set_general_thread (inferior_ptid);
2208}
2209
c906108c 2210\f
7d1a114c
PA
2211/* Return nonzero if this is the main thread that we made up ourselves
2212 to model non-threaded targets as single-threaded. */
c906108c
SS
2213
2214static int
7d1a114c 2215remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 2216{
c0a2216e
PA
2217 if (ptid_equal (ptid, magic_null_ptid))
2218 /* The main thread is always alive. */
2219 return 1;
2220
ba348170 2221 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2222 /* The main thread is always alive. This can happen after a
2223 vAttach, if the remote side doesn't support
2224 multi-threading. */
2225 return 1;
2226
7d1a114c
PA
2227 return 0;
2228}
2229
2230/* Return nonzero if the thread PTID is still alive on the remote
2231 system. */
2232
2233static int
2234remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2235{
2236 struct remote_state *rs = get_remote_state ();
2237 char *p, *endp;
2238
2239 /* Check if this is a thread that we made up ourselves to model
2240 non-threaded targets as single-threaded. */
2241 if (remote_thread_always_alive (ops, ptid))
2242 return 1;
2243
82f73884
PA
2244 p = rs->buf;
2245 endp = rs->buf + get_remote_packet_size ();
2246
2247 *p++ = 'T';
2248 write_ptid (p, endp, ptid);
2249
2e9f7625 2250 putpkt (rs->buf);
6d820c5c 2251 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2252 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2253}
2254
79efa585
SM
2255/* Return a pointer to a thread name if we know it and NULL otherwise.
2256 The thread_info object owns the memory for the name. */
2257
2258static const char *
2259remote_thread_name (struct target_ops *ops, struct thread_info *info)
2260{
2261 if (info->priv != NULL)
2262 return info->priv->name;
2263
2264 return NULL;
2265}
2266
c906108c
SS
2267/* About these extended threadlist and threadinfo packets. They are
2268 variable length packets but, the fields within them are often fixed
2269 length. They are redundent enough to send over UDP as is the
2270 remote protocol in general. There is a matching unit test module
2271 in libstub. */
2272
23860348 2273/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2274 libstub protocol encoding, and remote.c. It is not particularly
23860348 2275 changable. */
cce74817
JM
2276
2277/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2278 Plan to fix this. */
cce74817 2279
23860348 2280typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2281
9d1f7ab2 2282/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2283 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2284
2285struct gdb_ext_thread_info
c5aa993b 2286 {
23860348 2287 threadref threadid; /* External form of thread reference. */
2bc416ba 2288 int active; /* Has state interesting to GDB?
23860348 2289 regs, stack. */
2bc416ba 2290 char display[256]; /* Brief state display, name,
cedea757 2291 blocked/suspended. */
23860348 2292 char shortname[32]; /* To be used to name threads. */
2bc416ba 2293 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2294 whatever. */
c5aa993b 2295 };
cce74817
JM
2296
2297/* The volume of remote transfers can be limited by submitting
2298 a mask containing bits specifying the desired information.
2299 Use a union of these values as the 'selection' parameter to
0df8b418 2300 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2301
2302#define TAG_THREADID 1
2303#define TAG_EXISTS 2
2304#define TAG_DISPLAY 4
2305#define TAG_THREADNAME 8
c5aa993b 2306#define TAG_MOREDISPLAY 16
cce74817 2307
23860348 2308#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2309
a14ed312 2310static char *unpack_nibble (char *buf, int *val);
cce74817 2311
a14ed312 2312static char *unpack_byte (char *buf, int *value);
cce74817 2313
a14ed312 2314static char *pack_int (char *buf, int value);
cce74817 2315
a14ed312 2316static char *unpack_int (char *buf, int *value);
cce74817 2317
a14ed312 2318static char *unpack_string (char *src, char *dest, int length);
cce74817 2319
23860348 2320static char *pack_threadid (char *pkt, threadref *id);
cce74817 2321
23860348 2322static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2323
23860348 2324void int_to_threadref (threadref *id, int value);
cce74817 2325
23860348 2326static int threadref_to_int (threadref *ref);
cce74817 2327
23860348 2328static void copy_threadref (threadref *dest, threadref *src);
cce74817 2329
23860348 2330static int threadmatch (threadref *dest, threadref *src);
cce74817 2331
2bc416ba 2332static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2333 threadref *id);
cce74817 2334
a14ed312 2335static int remote_unpack_thread_info_response (char *pkt,
23860348 2336 threadref *expectedref,
a14ed312
KB
2337 struct gdb_ext_thread_info
2338 *info);
cce74817
JM
2339
2340
2bc416ba 2341static int remote_get_threadinfo (threadref *threadid,
23860348 2342 int fieldset, /*TAG mask */
a14ed312 2343 struct gdb_ext_thread_info *info);
cce74817 2344
a14ed312
KB
2345static char *pack_threadlist_request (char *pkt, int startflag,
2346 int threadcount,
23860348 2347 threadref *nextthread);
cce74817 2348
a14ed312
KB
2349static int parse_threadlist_response (char *pkt,
2350 int result_limit,
23860348 2351 threadref *original_echo,
2bc416ba 2352 threadref *resultlist,
23860348 2353 int *doneflag);
cce74817 2354
a14ed312 2355static int remote_get_threadlist (int startflag,
23860348 2356 threadref *nextthread,
a14ed312
KB
2357 int result_limit,
2358 int *done,
2bc416ba 2359 int *result_count,
23860348 2360 threadref *threadlist);
cce74817 2361
23860348 2362typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2363
a14ed312
KB
2364static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2365 void *context, int looplimit);
cce74817 2366
23860348 2367static int remote_newthread_step (threadref *ref, void *context);
cce74817 2368
82f73884
PA
2369
2370/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2371 buffer we're allowed to write to. Returns
2372 BUF+CHARACTERS_WRITTEN. */
2373
2374static char *
2375write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2376{
2377 int pid, tid;
2378 struct remote_state *rs = get_remote_state ();
2379
2380 if (remote_multi_process_p (rs))
2381 {
2382 pid = ptid_get_pid (ptid);
2383 if (pid < 0)
2384 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2385 else
2386 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2387 }
ba348170 2388 tid = ptid_get_lwp (ptid);
82f73884
PA
2389 if (tid < 0)
2390 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2391 else
2392 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2393
2394 return buf;
2395}
2396
2397/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2398 passed the last parsed char. Returns null_ptid on error. */
2399
2400static ptid_t
2401read_ptid (char *buf, char **obuf)
2402{
2403 char *p = buf;
2404 char *pp;
2405 ULONGEST pid = 0, tid = 0;
82f73884
PA
2406
2407 if (*p == 'p')
2408 {
2409 /* Multi-process ptid. */
2410 pp = unpack_varlen_hex (p + 1, &pid);
2411 if (*pp != '.')
b37520b6 2412 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2413
2414 p = pp;
2415 pp = unpack_varlen_hex (p + 1, &tid);
2416 if (obuf)
2417 *obuf = pp;
ba348170 2418 return ptid_build (pid, tid, 0);
82f73884
PA
2419 }
2420
2421 /* No multi-process. Just a tid. */
2422 pp = unpack_varlen_hex (p, &tid);
2423
c9f35b34
KB
2424 /* Return null_ptid when no thread id is found. */
2425 if (p == pp)
2426 {
2427 if (obuf)
2428 *obuf = pp;
2429 return null_ptid;
2430 }
2431
82f73884 2432 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2433 what's in inferior_ptid, unless it's null at this point. If so,
2434 then since there's no way to know the pid of the reported
2435 threads, use the magic number. */
2436 if (ptid_equal (inferior_ptid, null_ptid))
2437 pid = ptid_get_pid (magic_null_ptid);
2438 else
2439 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2440
2441 if (obuf)
2442 *obuf = pp;
ba348170 2443 return ptid_build (pid, tid, 0);
82f73884
PA
2444}
2445
c906108c 2446static int
fba45db2 2447stubhex (int ch)
c906108c
SS
2448{
2449 if (ch >= 'a' && ch <= 'f')
2450 return ch - 'a' + 10;
2451 if (ch >= '0' && ch <= '9')
2452 return ch - '0';
2453 if (ch >= 'A' && ch <= 'F')
2454 return ch - 'A' + 10;
2455 return -1;
2456}
2457
2458static int
fba45db2 2459stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2460{
2461 int nibble;
2462 int retval = 0;
2463
2464 while (fieldlength)
2465 {
2466 nibble = stubhex (*buff++);
2467 retval |= nibble;
2468 fieldlength--;
2469 if (fieldlength)
2470 retval = retval << 4;
2471 }
2472 return retval;
2473}
2474
c906108c 2475static char *
fba45db2 2476unpack_nibble (char *buf, int *val)
c906108c 2477{
b7589f7d 2478 *val = fromhex (*buf++);
c906108c
SS
2479 return buf;
2480}
2481
c906108c 2482static char *
fba45db2 2483unpack_byte (char *buf, int *value)
c906108c
SS
2484{
2485 *value = stub_unpack_int (buf, 2);
2486 return buf + 2;
2487}
2488
2489static char *
fba45db2 2490pack_int (char *buf, int value)
c906108c
SS
2491{
2492 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2493 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2494 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2495 buf = pack_hex_byte (buf, (value & 0xff));
2496 return buf;
2497}
2498
2499static char *
fba45db2 2500unpack_int (char *buf, int *value)
c906108c
SS
2501{
2502 *value = stub_unpack_int (buf, 8);
2503 return buf + 8;
2504}
2505
23860348 2506#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2507static char *pack_string (char *pkt, char *string);
c906108c
SS
2508
2509static char *
fba45db2 2510pack_string (char *pkt, char *string)
c906108c
SS
2511{
2512 char ch;
2513 int len;
2514
2515 len = strlen (string);
2516 if (len > 200)
23860348 2517 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2518 pkt = pack_hex_byte (pkt, len);
2519 while (len-- > 0)
2520 {
2521 ch = *string++;
2522 if ((ch == '\0') || (ch == '#'))
23860348 2523 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2524 *pkt++ = ch;
2525 }
2526 return pkt;
2527}
2528#endif /* 0 (unused) */
2529
2530static char *
fba45db2 2531unpack_string (char *src, char *dest, int length)
c906108c
SS
2532{
2533 while (length--)
2534 *dest++ = *src++;
2535 *dest = '\0';
2536 return src;
2537}
2538
2539static char *
fba45db2 2540pack_threadid (char *pkt, threadref *id)
c906108c
SS
2541{
2542 char *limit;
2543 unsigned char *altid;
2544
2545 altid = (unsigned char *) id;
2546 limit = pkt + BUF_THREAD_ID_SIZE;
2547 while (pkt < limit)
2548 pkt = pack_hex_byte (pkt, *altid++);
2549 return pkt;
2550}
2551
2552
2553static char *
fba45db2 2554unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2555{
2556 char *altref;
2557 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2558 int x, y;
2559
2560 altref = (char *) id;
2561
2562 while (inbuf < limit)
2563 {
2564 x = stubhex (*inbuf++);
2565 y = stubhex (*inbuf++);
2566 *altref++ = (x << 4) | y;
2567 }
2568 return inbuf;
2569}
2570
2571/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2572 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2573 to use 64bit thread references internally. This is an adapter
2574 function. */
2575
2576void
fba45db2 2577int_to_threadref (threadref *id, int value)
c906108c
SS
2578{
2579 unsigned char *scan;
2580
2581 scan = (unsigned char *) id;
2582 {
2583 int i = 4;
2584 while (i--)
2585 *scan++ = 0;
2586 }
2587 *scan++ = (value >> 24) & 0xff;
2588 *scan++ = (value >> 16) & 0xff;
2589 *scan++ = (value >> 8) & 0xff;
2590 *scan++ = (value & 0xff);
2591}
2592
2593static int
fba45db2 2594threadref_to_int (threadref *ref)
c906108c
SS
2595{
2596 int i, value = 0;
2597 unsigned char *scan;
2598
cfd77fa1 2599 scan = *ref;
c906108c
SS
2600 scan += 4;
2601 i = 4;
2602 while (i-- > 0)
2603 value = (value << 8) | ((*scan++) & 0xff);
2604 return value;
2605}
2606
2607static void
fba45db2 2608copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2609{
2610 int i;
2611 unsigned char *csrc, *cdest;
2612
2613 csrc = (unsigned char *) src;
2614 cdest = (unsigned char *) dest;
2615 i = 8;
2616 while (i--)
2617 *cdest++ = *csrc++;
2618}
2619
2620static int
fba45db2 2621threadmatch (threadref *dest, threadref *src)
c906108c 2622{
23860348 2623 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2624#if 0
2625 unsigned char *srcp, *destp;
2626 int i, result;
2627 srcp = (char *) src;
2628 destp = (char *) dest;
2629
2630 result = 1;
2631 while (i-- > 0)
2632 result &= (*srcp++ == *destp++) ? 1 : 0;
2633 return result;
2634#endif
2635 return 1;
2636}
2637
2638/*
c5aa993b
JM
2639 threadid:1, # always request threadid
2640 context_exists:2,
2641 display:4,
2642 unique_name:8,
2643 more_display:16
2644 */
c906108c
SS
2645
2646/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2647
2648static char *
fba45db2 2649pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2650{
23860348
MS
2651 *pkt++ = 'q'; /* Info Query */
2652 *pkt++ = 'P'; /* process or thread info */
2653 pkt = pack_int (pkt, mode); /* mode */
c906108c 2654 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2655 *pkt = '\0'; /* terminate */
c906108c
SS
2656 return pkt;
2657}
2658
23860348 2659/* These values tag the fields in a thread info response packet. */
c906108c 2660/* Tagging the fields allows us to request specific fields and to
23860348 2661 add more fields as time goes by. */
c906108c 2662
23860348 2663#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2664#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2665 fetch registers and its stack? */
c5aa993b 2666#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2667#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2668#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2669 the process. */
c906108c
SS
2670
2671static int
fba45db2
KB
2672remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2673 struct gdb_ext_thread_info *info)
c906108c 2674{
d01949b6 2675 struct remote_state *rs = get_remote_state ();
c906108c 2676 int mask, length;
cfd77fa1 2677 int tag;
c906108c 2678 threadref ref;
6d820c5c 2679 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2680 int retval = 1;
2681
23860348 2682 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2683 info->active = 0;
2684 info->display[0] = '\0';
2685 info->shortname[0] = '\0';
2686 info->more_display[0] = '\0';
2687
23860348
MS
2688 /* Assume the characters indicating the packet type have been
2689 stripped. */
c906108c
SS
2690 pkt = unpack_int (pkt, &mask); /* arg mask */
2691 pkt = unpack_threadid (pkt, &ref);
2692
2693 if (mask == 0)
8a3fe4f8 2694 warning (_("Incomplete response to threadinfo request."));
c906108c 2695 if (!threadmatch (&ref, expectedref))
23860348 2696 { /* This is an answer to a different request. */
8a3fe4f8 2697 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2698 return 0;
2699 }
2700 copy_threadref (&info->threadid, &ref);
2701
23860348 2702 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2703
23860348
MS
2704 /* Packets are terminated with nulls. */
2705 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2706 {
2707 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2708 pkt = unpack_byte (pkt, &length); /* length */
2709 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2710 {
8a3fe4f8 2711 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2712 retval = 0;
2713 break;
2714 }
2715 if (tag == TAG_THREADID)
2716 {
2717 if (length != 16)
2718 {
8a3fe4f8 2719 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2720 retval = 0;
2721 break;
2722 }
2723 pkt = unpack_threadid (pkt, &ref);
2724 mask = mask & ~TAG_THREADID;
2725 continue;
2726 }
2727 if (tag == TAG_EXISTS)
2728 {
2729 info->active = stub_unpack_int (pkt, length);
2730 pkt += length;
2731 mask = mask & ~(TAG_EXISTS);
2732 if (length > 8)
2733 {
8a3fe4f8 2734 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2735 retval = 0;
2736 break;
2737 }
2738 continue;
2739 }
2740 if (tag == TAG_THREADNAME)
2741 {
2742 pkt = unpack_string (pkt, &info->shortname[0], length);
2743 mask = mask & ~TAG_THREADNAME;
2744 continue;
2745 }
2746 if (tag == TAG_DISPLAY)
2747 {
2748 pkt = unpack_string (pkt, &info->display[0], length);
2749 mask = mask & ~TAG_DISPLAY;
2750 continue;
2751 }
2752 if (tag == TAG_MOREDISPLAY)
2753 {
2754 pkt = unpack_string (pkt, &info->more_display[0], length);
2755 mask = mask & ~TAG_MOREDISPLAY;
2756 continue;
2757 }
8a3fe4f8 2758 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2759 break; /* Not a tag we know about. */
c906108c
SS
2760 }
2761 return retval;
2762}
2763
2764static int
fba45db2
KB
2765remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2766 struct gdb_ext_thread_info *info)
c906108c 2767{
d01949b6 2768 struct remote_state *rs = get_remote_state ();
c906108c 2769 int result;
c906108c 2770
2e9f7625
DJ
2771 pack_threadinfo_request (rs->buf, fieldset, threadid);
2772 putpkt (rs->buf);
6d820c5c 2773 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2774
2775 if (rs->buf[0] == '\0')
2776 return 0;
2777
2e9f7625 2778 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2779 threadid, info);
c906108c
SS
2780 return result;
2781}
2782
c906108c
SS
2783/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2784
2785static char *
fba45db2
KB
2786pack_threadlist_request (char *pkt, int startflag, int threadcount,
2787 threadref *nextthread)
c906108c
SS
2788{
2789 *pkt++ = 'q'; /* info query packet */
2790 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2791 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2792 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2793 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2794 *pkt = '\0';
2795 return pkt;
2796}
2797
2798/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2799
2800static int
fba45db2
KB
2801parse_threadlist_response (char *pkt, int result_limit,
2802 threadref *original_echo, threadref *resultlist,
2803 int *doneflag)
c906108c 2804{
d01949b6 2805 struct remote_state *rs = get_remote_state ();
c906108c
SS
2806 char *limit;
2807 int count, resultcount, done;
2808
2809 resultcount = 0;
2810 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2811 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2812 /* done parse past here */
c906108c
SS
2813 pkt = unpack_byte (pkt, &count); /* count field */
2814 pkt = unpack_nibble (pkt, &done);
2815 /* The first threadid is the argument threadid. */
2816 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2817 while ((count-- > 0) && (pkt < limit))
2818 {
2819 pkt = unpack_threadid (pkt, resultlist++);
2820 if (resultcount++ >= result_limit)
2821 break;
2822 }
2823 if (doneflag)
2824 *doneflag = done;
2825 return resultcount;
2826}
2827
6dc54d91
PA
2828/* Fetch the next batch of threads from the remote. Returns -1 if the
2829 qL packet is not supported, 0 on error and 1 on success. */
2830
c906108c 2831static int
fba45db2
KB
2832remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2833 int *done, int *result_count, threadref *threadlist)
c906108c 2834{
d01949b6 2835 struct remote_state *rs = get_remote_state ();
c906108c
SS
2836 int result = 1;
2837
23860348 2838 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2839 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2840 >= get_remote_packet_size ())
ea9c271d 2841 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2842
6d820c5c
DJ
2843 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2844 putpkt (rs->buf);
2845 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2846 if (*rs->buf == '\0')
6dc54d91
PA
2847 {
2848 /* Packet not supported. */
2849 return -1;
2850 }
2851
2852 *result_count =
2853 parse_threadlist_response (rs->buf + 2, result_limit,
2854 &rs->echo_nextthread, threadlist, done);
c906108c 2855
0d031856 2856 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2857 {
23860348
MS
2858 /* FIXME: This is a good reason to drop the packet. */
2859 /* Possably, there is a duplicate response. */
c906108c
SS
2860 /* Possabilities :
2861 retransmit immediatly - race conditions
2862 retransmit after timeout - yes
2863 exit
2864 wait for packet, then exit
2865 */
8a3fe4f8 2866 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2867 return 0; /* I choose simply exiting. */
c906108c
SS
2868 }
2869 if (*result_count <= 0)
2870 {
2871 if (*done != 1)
2872 {
8a3fe4f8 2873 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2874 result = 0;
2875 }
2876 return result; /* break; */
2877 }
2878 if (*result_count > result_limit)
2879 {
2880 *result_count = 0;
8a3fe4f8 2881 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2882 return 0;
2883 }
2884 return result;
2885}
2886
6dc54d91
PA
2887/* Fetch the list of remote threads, with the qL packet, and call
2888 STEPFUNCTION for each thread found. Stops iterating and returns 1
2889 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2890 STEPFUNCTION returns false. If the packet is not supported,
2891 returns -1. */
c906108c 2892
c906108c 2893static int
fba45db2
KB
2894remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2895 int looplimit)
c906108c 2896{
0d031856 2897 struct remote_state *rs = get_remote_state ();
c906108c
SS
2898 int done, i, result_count;
2899 int startflag = 1;
2900 int result = 1;
2901 int loopcount = 0;
c906108c
SS
2902
2903 done = 0;
2904 while (!done)
2905 {
2906 if (loopcount++ > looplimit)
2907 {
2908 result = 0;
8a3fe4f8 2909 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2910 break;
2911 }
6dc54d91
PA
2912 result = remote_get_threadlist (startflag, &rs->nextthread,
2913 MAXTHREADLISTRESULTS,
2914 &done, &result_count,
2915 rs->resultthreadlist);
2916 if (result <= 0)
2917 break;
23860348 2918 /* Clear for later iterations. */
c906108c
SS
2919 startflag = 0;
2920 /* Setup to resume next batch of thread references, set nextthread. */
2921 if (result_count >= 1)
0d031856
TT
2922 copy_threadref (&rs->nextthread,
2923 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2924 i = 0;
2925 while (result_count--)
6dc54d91
PA
2926 {
2927 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2928 {
2929 result = 0;
2930 break;
2931 }
2932 }
c906108c
SS
2933 }
2934 return result;
2935}
2936
6dc54d91
PA
2937/* A thread found on the remote target. */
2938
2939typedef struct thread_item
2940{
2941 /* The thread's PTID. */
2942 ptid_t ptid;
2943
2944 /* The thread's extra info. May be NULL. */
2945 char *extra;
2946
79efa585
SM
2947 /* The thread's name. May be NULL. */
2948 char *name;
2949
6dc54d91
PA
2950 /* The core the thread was running on. -1 if not known. */
2951 int core;
2952} thread_item_t;
2953DEF_VEC_O(thread_item_t);
2954
2955/* Context passed around to the various methods listing remote
2956 threads. As new threads are found, they're added to the ITEMS
2957 vector. */
2958
2959struct threads_listing_context
2960{
2961 /* The threads found on the remote target. */
2962 VEC (thread_item_t) *items;
2963};
2964
80134cf5
PA
2965/* Discard the contents of the constructed thread listing context. */
2966
2967static void
2968clear_threads_listing_context (void *p)
2969{
19ba03f4
SM
2970 struct threads_listing_context *context
2971 = (struct threads_listing_context *) p;
80134cf5
PA
2972 int i;
2973 struct thread_item *item;
2974
2975 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
79efa585
SM
2976 {
2977 xfree (item->extra);
2978 xfree (item->name);
2979 }
80134cf5
PA
2980
2981 VEC_free (thread_item_t, context->items);
2982}
2983
cbb8991c
DB
2984/* Remove the thread specified as the related_pid field of WS
2985 from the CONTEXT list. */
2986
2987static void
2988threads_listing_context_remove (struct target_waitstatus *ws,
2989 struct threads_listing_context *context)
2990{
2991 struct thread_item *item;
2992 int i;
2993 ptid_t child_ptid = ws->value.related_pid;
2994
2995 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2996 {
2997 if (ptid_equal (item->ptid, child_ptid))
2998 {
2999 VEC_ordered_remove (thread_item_t, context->items, i);
3000 break;
3001 }
3002 }
3003}
3004
c906108c 3005static int
6dc54d91 3006remote_newthread_step (threadref *ref, void *data)
c906108c 3007{
19ba03f4
SM
3008 struct threads_listing_context *context
3009 = (struct threads_listing_context *) data;
6dc54d91 3010 struct thread_item item;
79d7f229 3011 int pid = ptid_get_pid (inferior_ptid);
39f77062 3012
6dc54d91
PA
3013 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3014 item.core = -1;
2e3b657e 3015 item.name = NULL;
6dc54d91
PA
3016 item.extra = NULL;
3017
3018 VEC_safe_push (thread_item_t, context->items, &item);
3019
c906108c
SS
3020 return 1; /* continue iterator */
3021}
3022
3023#define CRAZY_MAX_THREADS 1000
3024
39f77062
KB
3025static ptid_t
3026remote_current_thread (ptid_t oldpid)
c906108c 3027{
d01949b6 3028 struct remote_state *rs = get_remote_state ();
c906108c
SS
3029
3030 putpkt ("qC");
6d820c5c 3031 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3032 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34
KB
3033 {
3034 char *obuf;
3035 ptid_t result;
3036
3037 result = read_ptid (&rs->buf[2], &obuf);
3038 if (*obuf != '\0' && remote_debug)
3039 fprintf_unfiltered (gdb_stdlog,
3040 "warning: garbage in qC reply\n");
3041
3042 return result;
3043 }
c906108c
SS
3044 else
3045 return oldpid;
3046}
3047
6dc54d91 3048/* List remote threads using the deprecated qL packet. */
cce74817 3049
6dc54d91
PA
3050static int
3051remote_get_threads_with_ql (struct target_ops *ops,
3052 struct threads_listing_context *context)
c906108c 3053{
6dc54d91
PA
3054 if (remote_threadlist_iterator (remote_newthread_step, context,
3055 CRAZY_MAX_THREADS) >= 0)
3056 return 1;
3057
3058 return 0;
c906108c
SS
3059}
3060
dc146f7c
VP
3061#if defined(HAVE_LIBEXPAT)
3062
dc146f7c
VP
3063static void
3064start_thread (struct gdb_xml_parser *parser,
3065 const struct gdb_xml_element *element,
3066 void *user_data, VEC(gdb_xml_value_s) *attributes)
3067{
19ba03f4
SM
3068 struct threads_listing_context *data
3069 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3070
3071 struct thread_item item;
3072 char *id;
3d2c1d41 3073 struct gdb_xml_value *attr;
dc146f7c 3074
19ba03f4 3075 id = (char *) xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
3076 item.ptid = read_ptid (id, NULL);
3077
3d2c1d41
PA
3078 attr = xml_find_attribute (attributes, "core");
3079 if (attr != NULL)
3080 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
3081 else
3082 item.core = -1;
3083
79efa585 3084 attr = xml_find_attribute (attributes, "name");
e1961661 3085 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
79efa585 3086
dc146f7c
VP
3087 item.extra = 0;
3088
3089 VEC_safe_push (thread_item_t, data->items, &item);
3090}
3091
3092static void
3093end_thread (struct gdb_xml_parser *parser,
3094 const struct gdb_xml_element *element,
3095 void *user_data, const char *body_text)
3096{
19ba03f4
SM
3097 struct threads_listing_context *data
3098 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3099
3100 if (body_text && *body_text)
2ae2a0b7 3101 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
3102}
3103
3104const struct gdb_xml_attribute thread_attributes[] = {
3105 { "id", GDB_XML_AF_NONE, NULL, NULL },
3106 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3107 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3108 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3109};
3110
3111const struct gdb_xml_element thread_children[] = {
3112 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3113};
3114
3115const struct gdb_xml_element threads_children[] = {
3116 { "thread", thread_attributes, thread_children,
3117 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3118 start_thread, end_thread },
3119 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3120};
3121
3122const struct gdb_xml_element threads_elements[] = {
3123 { "threads", NULL, threads_children,
3124 GDB_XML_EF_NONE, NULL, NULL },
3125 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3126};
3127
3128#endif
3129
6dc54d91 3130/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3131
6dc54d91
PA
3132static int
3133remote_get_threads_with_qxfer (struct target_ops *ops,
3134 struct threads_listing_context *context)
0f71a2f6 3135{
dc146f7c 3136#if defined(HAVE_LIBEXPAT)
4082afcc 3137 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3138 {
6dc54d91 3139 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 3140 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 3141
6dc54d91 3142 if (xml != NULL && *xml != '\0')
dc146f7c 3143 {
6dc54d91
PA
3144 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3145 threads_elements, xml, context);
dc146f7c
VP
3146 }
3147
3148 do_cleanups (back_to);
6dc54d91 3149 return 1;
dc146f7c
VP
3150 }
3151#endif
3152
6dc54d91
PA
3153 return 0;
3154}
3155
3156/* List remote threads using qfThreadInfo/qsThreadInfo. */
3157
3158static int
3159remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3160 struct threads_listing_context *context)
3161{
3162 struct remote_state *rs = get_remote_state ();
3163
b80fafe3 3164 if (rs->use_threadinfo_query)
9d1f7ab2 3165 {
6dc54d91
PA
3166 char *bufp;
3167
9d1f7ab2 3168 putpkt ("qfThreadInfo");
6d820c5c 3169 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3170 bufp = rs->buf;
9d1f7ab2 3171 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3172 {
9d1f7ab2
MS
3173 while (*bufp++ == 'm') /* reply contains one or more TID */
3174 {
3175 do
3176 {
6dc54d91
PA
3177 struct thread_item item;
3178
3179 item.ptid = read_ptid (bufp, &bufp);
3180 item.core = -1;
2e3b657e 3181 item.name = NULL;
6dc54d91
PA
3182 item.extra = NULL;
3183
3184 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
3185 }
3186 while (*bufp++ == ','); /* comma-separated list */
3187 putpkt ("qsThreadInfo");
6d820c5c 3188 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3189 bufp = rs->buf;
9d1f7ab2 3190 }
6dc54d91
PA
3191 return 1;
3192 }
3193 else
3194 {
3195 /* Packet not recognized. */
3196 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3197 }
3198 }
3199
6dc54d91
PA
3200 return 0;
3201}
3202
e8032dde 3203/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3204 targets. */
3205
3206static void
e8032dde 3207remote_update_thread_list (struct target_ops *ops)
6dc54d91 3208{
6dc54d91
PA
3209 struct threads_listing_context context;
3210 struct cleanup *old_chain;
ab970af1 3211 int got_list = 0;
e8032dde 3212
6dc54d91
PA
3213 context.items = NULL;
3214 old_chain = make_cleanup (clear_threads_listing_context, &context);
3215
3216 /* We have a few different mechanisms to fetch the thread list. Try
3217 them all, starting with the most preferred one first, falling
3218 back to older methods. */
3219 if (remote_get_threads_with_qxfer (ops, &context)
3220 || remote_get_threads_with_qthreadinfo (ops, &context)
3221 || remote_get_threads_with_ql (ops, &context))
3222 {
3223 int i;
3224 struct thread_item *item;
ab970af1
PA
3225 struct thread_info *tp, *tmp;
3226
3227 got_list = 1;
3228
7d1a114c
PA
3229 if (VEC_empty (thread_item_t, context.items)
3230 && remote_thread_always_alive (ops, inferior_ptid))
3231 {
3232 /* Some targets don't really support threads, but still
3233 reply an (empty) thread list in response to the thread
3234 listing packets, instead of replying "packet not
3235 supported". Exit early so we don't delete the main
3236 thread. */
3237 do_cleanups (old_chain);
3238 return;
3239 }
3240
ab970af1
PA
3241 /* CONTEXT now holds the current thread list on the remote
3242 target end. Delete GDB-side threads no longer found on the
3243 target. */
8a06aea7 3244 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3245 {
ab970af1
PA
3246 for (i = 0;
3247 VEC_iterate (thread_item_t, context.items, i, item);
3248 ++i)
3249 {
3250 if (ptid_equal (item->ptid, tp->ptid))
3251 break;
3252 }
3253
3254 if (i == VEC_length (thread_item_t, context.items))
3255 {
3256 /* Not found. */
3257 delete_thread (tp->ptid);
3258 }
cbb8991c
DB
3259 }
3260
3261 /* Remove any unreported fork child threads from CONTEXT so
3262 that we don't interfere with follow fork, which is where
3263 creation of such threads is handled. */
3264 remove_new_fork_children (&context);
74531fed 3265
ab970af1 3266 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
3267 for (i = 0;
3268 VEC_iterate (thread_item_t, context.items, i, item);
3269 ++i)
3270 {
3271 if (!ptid_equal (item->ptid, null_ptid))
3272 {
3273 struct private_thread_info *info;
3274 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
3275 executing until proven otherwise with a stop reply.
3276 In all-stop, we can only get here if all threads are
6dc54d91 3277 stopped. */
0d5b594f 3278 int executing = target_is_non_stop_p () ? 1 : 0;
6dc54d91 3279
0d5b594f 3280 remote_notice_new_inferior (item->ptid, executing);
6dc54d91
PA
3281
3282 info = demand_private_info (item->ptid);
3283 info->core = item->core;
3284 info->extra = item->extra;
3285 item->extra = NULL;
79efa585
SM
3286 info->name = item->name;
3287 item->name = NULL;
6dc54d91
PA
3288 }
3289 }
3290 }
3291
ab970af1
PA
3292 if (!got_list)
3293 {
3294 /* If no thread listing method is supported, then query whether
3295 each known thread is alive, one by one, with the T packet.
3296 If the target doesn't support threads at all, then this is a
3297 no-op. See remote_thread_alive. */
3298 prune_threads ();
3299 }
3300
6dc54d91 3301 do_cleanups (old_chain);
9d1f7ab2
MS
3302}
3303
802188a7 3304/*
9d1f7ab2
MS
3305 * Collect a descriptive string about the given thread.
3306 * The target may say anything it wants to about the thread
3307 * (typically info about its blocked / runnable state, name, etc.).
3308 * This string will appear in the info threads display.
802188a7 3309 *
9d1f7ab2
MS
3310 * Optional: targets are not required to implement this function.
3311 */
3312
3313static char *
c15906d8 3314remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 3315{
d01949b6 3316 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3317 int result;
3318 int set;
3319 threadref id;
3320 struct gdb_ext_thread_info threadinfo;
23860348 3321 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3322 int n = 0; /* position in display_buf */
3323
5d93a237 3324 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3325 internal_error (__FILE__, __LINE__,
e2e0b3e5 3326 _("remote_threads_extra_info"));
9d1f7ab2 3327
60e569b9 3328 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3329 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3330 /* This is the main thread which was added by GDB. The remote
3331 server doesn't know about it. */
3332 return NULL;
3333
4082afcc 3334 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3335 {
3336 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3337
fe978cb0
PA
3338 if (info && info->priv)
3339 return info->priv->extra;
dc146f7c
VP
3340 else
3341 return NULL;
3342 }
3343
b80fafe3 3344 if (rs->use_threadextra_query)
9d1f7ab2 3345 {
82f73884
PA
3346 char *b = rs->buf;
3347 char *endb = rs->buf + get_remote_packet_size ();
3348
3349 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3350 b += strlen (b);
3351 write_ptid (b, endb, tp->ptid);
3352
2e9f7625 3353 putpkt (rs->buf);
6d820c5c 3354 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3355 if (rs->buf[0] != 0)
9d1f7ab2 3356 {
2e9f7625
DJ
3357 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3358 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3359 display_buf [result] = '\0';
9d1f7ab2
MS
3360 return display_buf;
3361 }
0f71a2f6 3362 }
9d1f7ab2
MS
3363
3364 /* If the above query fails, fall back to the old method. */
b80fafe3 3365 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3366 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3367 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3368 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3369 if (remote_get_threadinfo (&id, set, &threadinfo))
3370 if (threadinfo.active)
0f71a2f6 3371 {
9d1f7ab2 3372 if (*threadinfo.shortname)
2bc416ba 3373 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3374 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3375 if (*threadinfo.display)
2bc416ba 3376 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3377 " State: %s,", threadinfo.display);
9d1f7ab2 3378 if (*threadinfo.more_display)
2bc416ba 3379 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3380 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3381
3382 if (n > 0)
c5aa993b 3383 {
23860348 3384 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3385 if (',' == display_buf[n-1])
3386 display_buf[n-1] = ' ';
3387 return display_buf;
c5aa993b 3388 }
0f71a2f6 3389 }
9d1f7ab2 3390 return NULL;
0f71a2f6 3391}
c906108c 3392\f
c5aa993b 3393
0fb4aa4b 3394static int
61fc905d 3395remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
3396 struct static_tracepoint_marker *marker)
3397{
3398 struct remote_state *rs = get_remote_state ();
3399 char *p = rs->buf;
3400
bba74b36 3401 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3402 p += strlen (p);
3403 p += hexnumstr (p, addr);
3404 putpkt (rs->buf);
3405 getpkt (&rs->buf, &rs->buf_size, 0);
3406 p = rs->buf;
3407
3408 if (*p == 'E')
3409 error (_("Remote failure reply: %s"), p);
3410
3411 if (*p++ == 'm')
3412 {
3413 parse_static_tracepoint_marker_definition (p, &p, marker);
3414 return 1;
3415 }
3416
3417 return 0;
3418}
3419
0fb4aa4b 3420static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3421remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3422 const char *strid)
0fb4aa4b
PA
3423{
3424 struct remote_state *rs = get_remote_state ();
3425 VEC(static_tracepoint_marker_p) *markers = NULL;
3426 struct static_tracepoint_marker *marker = NULL;
3427 struct cleanup *old_chain;
3428 char *p;
3429
3430 /* Ask for a first packet of static tracepoint marker
3431 definition. */
3432 putpkt ("qTfSTM");
3433 getpkt (&rs->buf, &rs->buf_size, 0);
3434 p = rs->buf;
3435 if (*p == 'E')
3436 error (_("Remote failure reply: %s"), p);
3437
3438 old_chain = make_cleanup (free_current_marker, &marker);
3439
3440 while (*p++ == 'm')
3441 {
3442 if (marker == NULL)
3443 marker = XCNEW (struct static_tracepoint_marker);
3444
3445 do
3446 {
3447 parse_static_tracepoint_marker_definition (p, &p, marker);
3448
3449 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3450 {
3451 VEC_safe_push (static_tracepoint_marker_p,
3452 markers, marker);
3453 marker = NULL;
3454 }
3455 else
3456 {
3457 release_static_tracepoint_marker (marker);
3458 memset (marker, 0, sizeof (*marker));
3459 }
3460 }
3461 while (*p++ == ','); /* comma-separated list */
3462 /* Ask for another packet of static tracepoint definition. */
3463 putpkt ("qTsSTM");
3464 getpkt (&rs->buf, &rs->buf_size, 0);
3465 p = rs->buf;
3466 }
3467
3468 do_cleanups (old_chain);
3469 return markers;
3470}
3471
3472\f
10760264
JB
3473/* Implement the to_get_ada_task_ptid function for the remote targets. */
3474
3475static ptid_t
1e6b91a4 3476remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3477{
ba348170 3478 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3479}
3480\f
3481
24b06219 3482/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3483
3484static void
fba45db2 3485extended_remote_restart (void)
c906108c 3486{
d01949b6 3487 struct remote_state *rs = get_remote_state ();
c906108c
SS
3488
3489 /* Send the restart command; for reasons I don't understand the
3490 remote side really expects a number after the "R". */
ea9c271d 3491 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3492 putpkt (rs->buf);
c906108c 3493
ad9a8f3f 3494 remote_fileio_reset ();
c906108c
SS
3495}
3496\f
3497/* Clean up connection to a remote debugger. */
3498
c906108c 3499static void
de90e03d 3500remote_close (struct target_ops *self)
c906108c 3501{
5d93a237
TT
3502 struct remote_state *rs = get_remote_state ();
3503
3504 if (rs->remote_desc == NULL)
d3fd5342
PA
3505 return; /* already closed */
3506
048094ac 3507 /* Make sure we leave stdin registered in the event loop. */
e3594fd1 3508 remote_terminal_ours (self);
ce5ce7ed 3509
5d93a237
TT
3510 serial_close (rs->remote_desc);
3511 rs->remote_desc = NULL;
ce5ce7ed
PA
3512
3513 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3514 of all the inferiors and their threads we were controlling.
3515 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3516 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3517 inferior_ptid = null_ptid;
f67fd822 3518 discard_all_inferiors ();
ce5ce7ed 3519
f48ff2a7
YQ
3520 /* We are closing the remote target, so we should discard
3521 everything of this target. */
bcc75809 3522 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3523
3524 if (remote_async_inferior_event_token)
3525 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3526
5965e028 3527 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3528
3529 trace_reset_local_state ();
c906108c
SS
3530}
3531
23860348 3532/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3533
3534static void
fba45db2 3535get_offsets (void)
c906108c 3536{
d01949b6 3537 struct remote_state *rs = get_remote_state ();
2e9f7625 3538 char *buf;
085dd6e6 3539 char *ptr;
31d99776
DJ
3540 int lose, num_segments = 0, do_sections, do_segments;
3541 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3542 struct section_offsets *offs;
31d99776
DJ
3543 struct symfile_segment_data *data;
3544
3545 if (symfile_objfile == NULL)
3546 return;
c906108c
SS
3547
3548 putpkt ("qOffsets");
6d820c5c 3549 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3550 buf = rs->buf;
c906108c
SS
3551
3552 if (buf[0] == '\000')
3553 return; /* Return silently. Stub doesn't support
23860348 3554 this command. */
c906108c
SS
3555 if (buf[0] == 'E')
3556 {
8a3fe4f8 3557 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3558 return;
3559 }
3560
3561 /* Pick up each field in turn. This used to be done with scanf, but
3562 scanf will make trouble if CORE_ADDR size doesn't match
3563 conversion directives correctly. The following code will work
3564 with any size of CORE_ADDR. */
3565 text_addr = data_addr = bss_addr = 0;
3566 ptr = buf;
3567 lose = 0;
3568
61012eef 3569 if (startswith (ptr, "Text="))
c906108c
SS
3570 {
3571 ptr += 5;
3572 /* Don't use strtol, could lose on big values. */
3573 while (*ptr && *ptr != ';')
3574 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3575
61012eef 3576 if (startswith (ptr, ";Data="))
31d99776
DJ
3577 {
3578 ptr += 6;
3579 while (*ptr && *ptr != ';')
3580 data_addr = (data_addr << 4) + fromhex (*ptr++);
3581 }
3582 else
3583 lose = 1;
3584
61012eef 3585 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3586 {
3587 ptr += 5;
3588 while (*ptr && *ptr != ';')
3589 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3590
31d99776
DJ
3591 if (bss_addr != data_addr)
3592 warning (_("Target reported unsupported offsets: %s"), buf);
3593 }
3594 else
3595 lose = 1;
3596 }
61012eef 3597 else if (startswith (ptr, "TextSeg="))
c906108c 3598 {
31d99776
DJ
3599 ptr += 8;
3600 /* Don't use strtol, could lose on big values. */
c906108c 3601 while (*ptr && *ptr != ';')
31d99776
DJ
3602 text_addr = (text_addr << 4) + fromhex (*ptr++);
3603 num_segments = 1;
3604
61012eef 3605 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3606 {
3607 ptr += 9;
3608 while (*ptr && *ptr != ';')
3609 data_addr = (data_addr << 4) + fromhex (*ptr++);
3610 num_segments++;
3611 }
c906108c
SS
3612 }
3613 else
3614 lose = 1;
3615
3616 if (lose)
8a3fe4f8 3617 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3618 else if (*ptr != '\0')
3619 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3620
802188a7 3621 offs = ((struct section_offsets *)
a39a16c4 3622 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3623 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3624 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3625
31d99776
DJ
3626 data = get_symfile_segment_data (symfile_objfile->obfd);
3627 do_segments = (data != NULL);
3628 do_sections = num_segments == 0;
c906108c 3629
28c32713 3630 if (num_segments > 0)
31d99776 3631 {
31d99776
DJ
3632 segments[0] = text_addr;
3633 segments[1] = data_addr;
3634 }
28c32713
JB
3635 /* If we have two segments, we can still try to relocate everything
3636 by assuming that the .text and .data offsets apply to the whole
3637 text and data segments. Convert the offsets given in the packet
3638 to base addresses for symfile_map_offsets_to_segments. */
3639 else if (data && data->num_segments == 2)
3640 {
3641 segments[0] = data->segment_bases[0] + text_addr;
3642 segments[1] = data->segment_bases[1] + data_addr;
3643 num_segments = 2;
3644 }
8d385431
DJ
3645 /* If the object file has only one segment, assume that it is text
3646 rather than data; main programs with no writable data are rare,
3647 but programs with no code are useless. Of course the code might
3648 have ended up in the data segment... to detect that we would need
3649 the permissions here. */
3650 else if (data && data->num_segments == 1)
3651 {
3652 segments[0] = data->segment_bases[0] + text_addr;
3653 num_segments = 1;
3654 }
28c32713
JB
3655 /* There's no way to relocate by segment. */
3656 else
3657 do_segments = 0;
31d99776
DJ
3658
3659 if (do_segments)
3660 {
3661 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3662 offs, num_segments, segments);
3663
3664 if (ret == 0 && !do_sections)
3e43a32a
MS
3665 error (_("Can not handle qOffsets TextSeg "
3666 "response with this symbol file"));
31d99776
DJ
3667
3668 if (ret > 0)
3669 do_sections = 0;
3670 }
c906108c 3671
9ef895d6
DJ
3672 if (data)
3673 free_symfile_segment_data (data);
31d99776
DJ
3674
3675 if (do_sections)
3676 {
3677 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3678
3e43a32a
MS
3679 /* This is a temporary kludge to force data and bss to use the
3680 same offsets because that's what nlmconv does now. The real
3681 solution requires changes to the stub and remote.c that I
3682 don't have time to do right now. */
31d99776
DJ
3683
3684 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3685 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3686 }
c906108c
SS
3687
3688 objfile_relocate (symfile_objfile, offs);
3689}
3690
9a7071a8
JB
3691/* Send interrupt_sequence to remote target. */
3692static void
eeae04df 3693send_interrupt_sequence (void)
9a7071a8 3694{
5d93a237
TT
3695 struct remote_state *rs = get_remote_state ();
3696
9a7071a8 3697 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3698 remote_serial_write ("\x03", 1);
9a7071a8 3699 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3700 serial_send_break (rs->remote_desc);
9a7071a8
JB
3701 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3702 {
5d93a237 3703 serial_send_break (rs->remote_desc);
c33e31fd 3704 remote_serial_write ("g", 1);
9a7071a8
JB
3705 }
3706 else
3707 internal_error (__FILE__, __LINE__,
3708 _("Invalid value for interrupt_sequence_mode: %s."),
3709 interrupt_sequence_mode);
3710}
3711
3405876a
PA
3712
3713/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3714 and extract the PTID. Returns NULL_PTID if not found. */
3715
3716static ptid_t
3717stop_reply_extract_thread (char *stop_reply)
3718{
3719 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3720 {
3721 char *p;
3722
3723 /* Txx r:val ; r:val (...) */
3724 p = &stop_reply[3];
3725
3726 /* Look for "register" named "thread". */
3727 while (*p != '\0')
3728 {
3729 char *p1;
3730
3731 p1 = strchr (p, ':');
3732 if (p1 == NULL)
3733 return null_ptid;
3734
3735 if (strncmp (p, "thread", p1 - p) == 0)
3736 return read_ptid (++p1, &p);
3737
3738 p1 = strchr (p, ';');
3739 if (p1 == NULL)
3740 return null_ptid;
3741 p1++;
3742
3743 p = p1;
3744 }
3745 }
3746
3747 return null_ptid;
3748}
3749
b7ea362b
PA
3750/* Determine the remote side's current thread. If we have a stop
3751 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3752 "thread" register we can extract the current thread from. If not,
3753 ask the remote which is the current thread with qC. The former
3754 method avoids a roundtrip. */
3755
3756static ptid_t
3757get_current_thread (char *wait_status)
3758{
6a49a997 3759 ptid_t ptid = null_ptid;
b7ea362b
PA
3760
3761 /* Note we don't use remote_parse_stop_reply as that makes use of
3762 the target architecture, which we haven't yet fully determined at
3763 this point. */
3764 if (wait_status != NULL)
3765 ptid = stop_reply_extract_thread (wait_status);
3766 if (ptid_equal (ptid, null_ptid))
3767 ptid = remote_current_thread (inferior_ptid);
3768
3769 return ptid;
3770}
3771
49c62f2e
PA
3772/* Query the remote target for which is the current thread/process,
3773 add it to our tables, and update INFERIOR_PTID. The caller is
3774 responsible for setting the state such that the remote end is ready
3405876a
PA
3775 to return the current thread.
3776
3777 This function is called after handling the '?' or 'vRun' packets,
3778 whose response is a stop reply from which we can also try
3779 extracting the thread. If the target doesn't support the explicit
3780 qC query, we infer the current thread from that stop reply, passed
3781 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3782
3783static void
3405876a 3784add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3785{
3786 struct remote_state *rs = get_remote_state ();
3787 int fake_pid_p = 0;
6a49a997 3788 ptid_t ptid;
49c62f2e
PA
3789
3790 inferior_ptid = null_ptid;
3791
b7ea362b
PA
3792 /* Now, if we have thread information, update inferior_ptid. */
3793 ptid = get_current_thread (wait_status);
3405876a 3794
49c62f2e
PA
3795 if (!ptid_equal (ptid, null_ptid))
3796 {
3797 if (!remote_multi_process_p (rs))
3798 fake_pid_p = 1;
3799
3800 inferior_ptid = ptid;
3801 }
3802 else
3803 {
3804 /* Without this, some commands which require an active target
3805 (such as kill) won't work. This variable serves (at least)
3806 double duty as both the pid of the target process (if it has
3807 such), and as a flag indicating that a target is active. */
3808 inferior_ptid = magic_null_ptid;
3809 fake_pid_p = 1;
3810 }
3811
1b6e6f5c 3812 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
49c62f2e
PA
3813
3814 /* Add the main thread. */
3815 add_thread_silent (inferior_ptid);
3816}
3817
6efcd9a8
PA
3818/* Print info about a thread that was found already stopped on
3819 connection. */
3820
3821static void
3822print_one_stopped_thread (struct thread_info *thread)
3823{
3824 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3825
3826 switch_to_thread (thread->ptid);
3827 stop_pc = get_frame_pc (get_current_frame ());
3828 set_current_sal_from_frame (get_current_frame ());
3829
3830 thread->suspend.waitstatus_pending_p = 0;
3831
3832 if (ws->kind == TARGET_WAITKIND_STOPPED)
3833 {
3834 enum gdb_signal sig = ws->value.sig;
3835
3836 if (signal_print_state (sig))
3837 observer_notify_signal_received (sig);
3838 }
3839 observer_notify_normal_stop (NULL, 1);
3840}
3841
221e1a37
PA
3842/* Process all initial stop replies the remote side sent in response
3843 to the ? packet. These indicate threads that were already stopped
3844 on initial connection. We mark these threads as stopped and print
3845 their current frame before giving the user the prompt. */
3846
3847static void
6efcd9a8 3848process_initial_stop_replies (int from_tty)
221e1a37
PA
3849{
3850 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
3851 struct inferior *inf;
3852 struct thread_info *thread;
3853 struct thread_info *selected = NULL;
3854 struct thread_info *lowest_stopped = NULL;
3855 struct thread_info *first = NULL;
221e1a37
PA
3856
3857 /* Consume the initial pending events. */
3858 while (pending_stop_replies-- > 0)
3859 {
3860 ptid_t waiton_ptid = minus_one_ptid;
3861 ptid_t event_ptid;
3862 struct target_waitstatus ws;
3863 int ignore_event = 0;
6efcd9a8 3864 struct thread_info *thread;
221e1a37
PA
3865
3866 memset (&ws, 0, sizeof (ws));
3867 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3868 if (remote_debug)
3869 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3870
3871 switch (ws.kind)
3872 {
3873 case TARGET_WAITKIND_IGNORE:
3874 case TARGET_WAITKIND_NO_RESUMED:
3875 case TARGET_WAITKIND_SIGNALLED:
3876 case TARGET_WAITKIND_EXITED:
3877 /* We shouldn't see these, but if we do, just ignore. */
3878 if (remote_debug)
3879 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3880 ignore_event = 1;
3881 break;
3882
3883 case TARGET_WAITKIND_EXECD:
3884 xfree (ws.value.execd_pathname);
3885 break;
3886 default:
3887 break;
3888 }
3889
3890 if (ignore_event)
3891 continue;
3892
6efcd9a8 3893 thread = find_thread_ptid (event_ptid);
221e1a37
PA
3894
3895 if (ws.kind == TARGET_WAITKIND_STOPPED)
3896 {
3897 enum gdb_signal sig = ws.value.sig;
3898
3899 /* Stubs traditionally report SIGTRAP as initial signal,
3900 instead of signal 0. Suppress it. */
3901 if (sig == GDB_SIGNAL_TRAP)
3902 sig = GDB_SIGNAL_0;
6efcd9a8
PA
3903 thread->suspend.stop_signal = sig;
3904 ws.value.sig = sig;
3905 }
221e1a37 3906
6efcd9a8
PA
3907 thread->suspend.waitstatus = ws;
3908
3909 if (ws.kind != TARGET_WAITKIND_STOPPED
3910 || ws.value.sig != GDB_SIGNAL_0)
3911 thread->suspend.waitstatus_pending_p = 1;
3912
3913 set_executing (event_ptid, 0);
3914 set_running (event_ptid, 0);
3915 }
3916
3917 /* "Notice" the new inferiors before anything related to
3918 registers/memory. */
3919 ALL_INFERIORS (inf)
3920 {
3921 if (inf->pid == 0)
3922 continue;
3923
3924 inf->needs_setup = 1;
3925
3926 if (non_stop)
3927 {
3928 thread = any_live_thread_of_process (inf->pid);
3929 notice_new_inferior (thread->ptid,
3930 thread->state == THREAD_RUNNING,
3931 from_tty);
3932 }
3933 }
3934
3935 /* If all-stop on top of non-stop, pause all threads. Note this
3936 records the threads' stop pc, so must be done after "noticing"
3937 the inferiors. */
3938 if (!non_stop)
3939 {
3940 stop_all_threads ();
3941
3942 /* If all threads of an inferior were already stopped, we
3943 haven't setup the inferior yet. */
3944 ALL_INFERIORS (inf)
3945 {
3946 if (inf->pid == 0)
3947 continue;
221e1a37 3948
6efcd9a8
PA
3949 if (inf->needs_setup)
3950 {
3951 thread = any_live_thread_of_process (inf->pid);
3952 switch_to_thread_no_regs (thread);
3953 setup_inferior (0);
3954 }
3955 }
221e1a37 3956 }
6efcd9a8
PA
3957
3958 /* Now go over all threads that are stopped, and print their current
3959 frame. If all-stop, then if there's a signalled thread, pick
3960 that as current. */
3961 ALL_NON_EXITED_THREADS (thread)
3962 {
6efcd9a8
PA
3963 if (first == NULL)
3964 first = thread;
3965
3966 if (!non_stop)
3967 set_running (thread->ptid, 0);
3968 else if (thread->state != THREAD_STOPPED)
3969 continue;
3970
6efcd9a8
PA
3971 if (selected == NULL
3972 && thread->suspend.waitstatus_pending_p)
3973 selected = thread;
3974
5d5658a1
PA
3975 if (lowest_stopped == NULL
3976 || thread->inf->num < lowest_stopped->inf->num
3977 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
3978 lowest_stopped = thread;
3979
3980 if (non_stop)
3981 print_one_stopped_thread (thread);
3982 }
3983
3984 /* In all-stop, we only print the status of one thread, and leave
3985 others with their status pending. */
3986 if (!non_stop)
3987 {
3988 thread = selected;
3989 if (thread == NULL)
3990 thread = lowest_stopped;
3991 if (thread == NULL)
3992 thread = first;
3993
3994 print_one_stopped_thread (thread);
3995 }
3996
3997 /* For "info program". */
3998 thread = inferior_thread ();
3999 if (thread->state == THREAD_STOPPED)
4000 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
4001}
4002
048094ac
PA
4003/* Start the remote connection and sync state. */
4004
9cbc821d 4005static void
04bd08de 4006remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 4007{
c8d104ad
PA
4008 struct remote_state *rs = get_remote_state ();
4009 struct packet_config *noack_config;
2d717e4f 4010 char *wait_status = NULL;
8621d6a9 4011
048094ac
PA
4012 /* Signal other parts that we're going through the initial setup,
4013 and so things may not be stable yet. E.g., we don't try to
4014 install tracepoints until we've relocated symbols. Also, a
4015 Ctrl-C before we're connected and synced up can't interrupt the
4016 target. Instead, it offers to drop the (potentially wedged)
4017 connection. */
4018 rs->starting_up = 1;
4019
522002f9 4020 QUIT;
c906108c 4021
9a7071a8
JB
4022 if (interrupt_on_connect)
4023 send_interrupt_sequence ();
4024
57e12211 4025 /* Ack any packet which the remote side has already sent. */
048094ac 4026 remote_serial_write ("+", 1);
1e51243a 4027
c8d104ad
PA
4028 /* The first packet we send to the target is the optional "supported
4029 packets" request. If the target can answer this, it will tell us
4030 which later probes to skip. */
4031 remote_query_supported ();
4032
d914c394 4033 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 4034 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 4035 remote_set_permissions (target);
d914c394 4036
57809e5e
JK
4037 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4038 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4039 as a reply to known packet. For packet "vFile:setfs:" it is an
4040 invalid reply and GDB would return error in
4041 remote_hostio_set_filesystem, making remote files access impossible.
4042 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4043 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4044 {
4045 const char v_mustreplyempty[] = "vMustReplyEmpty";
4046
4047 putpkt (v_mustreplyempty);
4048 getpkt (&rs->buf, &rs->buf_size, 0);
4049 if (strcmp (rs->buf, "OK") == 0)
4050 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4051 else if (strcmp (rs->buf, "") != 0)
4052 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4053 rs->buf);
4054 }
4055
c8d104ad
PA
4056 /* Next, we possibly activate noack mode.
4057
4058 If the QStartNoAckMode packet configuration is set to AUTO,
4059 enable noack mode if the stub reported a wish for it with
4060 qSupported.
4061
4062 If set to TRUE, then enable noack mode even if the stub didn't
4063 report it in qSupported. If the stub doesn't reply OK, the
4064 session ends with an error.
4065
4066 If FALSE, then don't activate noack mode, regardless of what the
4067 stub claimed should be the default with qSupported. */
4068
4069 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 4070 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
4071 {
4072 putpkt ("QStartNoAckMode");
4073 getpkt (&rs->buf, &rs->buf_size, 0);
4074 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4075 rs->noack_mode = 1;
4076 }
4077
04bd08de 4078 if (extended_p)
5fe04517
PA
4079 {
4080 /* Tell the remote that we are using the extended protocol. */
4081 putpkt ("!");
4082 getpkt (&rs->buf, &rs->buf_size, 0);
4083 }
4084
9b224c5e
PA
4085 /* Let the target know which signals it is allowed to pass down to
4086 the program. */
4087 update_signals_program_target ();
4088
d962ef82
DJ
4089 /* Next, if the target can specify a description, read it. We do
4090 this before anything involving memory or registers. */
4091 target_find_description ();
4092
6c95b8df
PA
4093 /* Next, now that we know something about the target, update the
4094 address spaces in the program spaces. */
4095 update_address_spaces ();
4096
50c71eaf
PA
4097 /* On OSs where the list of libraries is global to all
4098 processes, we fetch them early. */
f5656ead 4099 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 4100 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 4101
6efcd9a8 4102 if (target_is_non_stop_p ())
74531fed 4103 {
4082afcc 4104 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4105 error (_("Non-stop mode requested, but remote "
4106 "does not support non-stop"));
74531fed
PA
4107
4108 putpkt ("QNonStop:1");
4109 getpkt (&rs->buf, &rs->buf_size, 0);
4110
4111 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4112 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
4113
4114 /* Find about threads and processes the stub is already
4115 controlling. We default to adding them in the running state.
4116 The '?' query below will then tell us about which threads are
4117 stopped. */
e8032dde 4118 remote_update_thread_list (target);
74531fed 4119 }
4082afcc 4120 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4121 {
4122 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4123 Request it explicitly. */
74531fed
PA
4124 putpkt ("QNonStop:0");
4125 getpkt (&rs->buf, &rs->buf_size, 0);
4126
4127 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4128 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
4129 }
4130
a0743c90
YQ
4131 /* Upload TSVs regardless of whether the target is running or not. The
4132 remote stub, such as GDBserver, may have some predefined or builtin
4133 TSVs, even if the target is not running. */
8bd200f1 4134 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
4135 {
4136 struct uploaded_tsv *uploaded_tsvs = NULL;
4137
181e3713 4138 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
4139 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4140 }
4141
2d717e4f
DJ
4142 /* Check whether the target is running now. */
4143 putpkt ("?");
4144 getpkt (&rs->buf, &rs->buf_size, 0);
4145
6efcd9a8 4146 if (!target_is_non_stop_p ())
2d717e4f 4147 {
74531fed 4148 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4149 {
04bd08de 4150 if (!extended_p)
74531fed 4151 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4152
4153 /* We're connected, but not running. Drop out before we
4154 call start_remote. */
e278ad5b 4155 rs->starting_up = 0;
c35b1492 4156 return;
2d717e4f
DJ
4157 }
4158 else
74531fed 4159 {
74531fed 4160 /* Save the reply for later. */
224c3ddb 4161 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4162 strcpy (wait_status, rs->buf);
4163 }
4164
b7ea362b 4165 /* Fetch thread list. */
e8032dde 4166 target_update_thread_list ();
b7ea362b 4167
74531fed
PA
4168 /* Let the stub know that we want it to return the thread. */
4169 set_continue_thread (minus_one_ptid);
4170
b7ea362b
PA
4171 if (thread_count () == 0)
4172 {
4173 /* Target has no concept of threads at all. GDB treats
4174 non-threaded target as single-threaded; add a main
4175 thread. */
4176 add_current_inferior_and_thread (wait_status);
4177 }
4178 else
4179 {
4180 /* We have thread information; select the thread the target
4181 says should be current. If we're reconnecting to a
4182 multi-threaded program, this will ideally be the thread
4183 that last reported an event before GDB disconnected. */
4184 inferior_ptid = get_current_thread (wait_status);
4185 if (ptid_equal (inferior_ptid, null_ptid))
4186 {
4187 /* Odd... The target was able to list threads, but not
4188 tell us which thread was current (no "thread"
4189 register in T stop reply?). Just pick the first
4190 thread in the thread list then. */
c9f35b34
KB
4191
4192 if (remote_debug)
4193 fprintf_unfiltered (gdb_stdlog,
4194 "warning: couldn't determine remote "
4195 "current thread; picking first in list.\n");
4196
b7ea362b
PA
4197 inferior_ptid = thread_list->ptid;
4198 }
4199 }
74531fed 4200
6e586cc5
YQ
4201 /* init_wait_for_inferior should be called before get_offsets in order
4202 to manage `inserted' flag in bp loc in a correct state.
4203 breakpoint_init_inferior, called from init_wait_for_inferior, set
4204 `inserted' flag to 0, while before breakpoint_re_set, called from
4205 start_remote, set `inserted' flag to 1. In the initialization of
4206 inferior, breakpoint_init_inferior should be called first, and then
4207 breakpoint_re_set can be called. If this order is broken, state of
4208 `inserted' flag is wrong, and cause some problems on breakpoint
4209 manipulation. */
4210 init_wait_for_inferior ();
4211
74531fed
PA
4212 get_offsets (); /* Get text, data & bss offsets. */
4213
d962ef82
DJ
4214 /* If we could not find a description using qXfer, and we know
4215 how to do it some other way, try again. This is not
4216 supported for non-stop; it could be, but it is tricky if
4217 there are no stopped threads when we connect. */
04bd08de 4218 if (remote_read_description_p (target)
f5656ead 4219 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4220 {
4221 target_clear_description ();
4222 target_find_description ();
4223 }
4224
74531fed
PA
4225 /* Use the previously fetched status. */
4226 gdb_assert (wait_status != NULL);
4227 strcpy (rs->buf, wait_status);
4228 rs->cached_wait_status = 1;
4229
04bd08de 4230 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4231 }
4232 else
4233 {
68c97600
PA
4234 /* Clear WFI global state. Do this before finding about new
4235 threads and inferiors, and setting the current inferior.
4236 Otherwise we would clear the proceed status of the current
4237 inferior when we want its stop_soon state to be preserved
4238 (see notice_new_inferior). */
4239 init_wait_for_inferior ();
4240
74531fed
PA
4241 /* In non-stop, we will either get an "OK", meaning that there
4242 are no stopped threads at this time; or, a regular stop
4243 reply. In the latter case, there may be more than one thread
4244 stopped --- we pull them all out using the vStopped
4245 mechanism. */
4246 if (strcmp (rs->buf, "OK") != 0)
4247 {
722247f1 4248 struct notif_client *notif = &notif_client_stop;
2d717e4f 4249
722247f1
YQ
4250 /* remote_notif_get_pending_replies acks this one, and gets
4251 the rest out. */
f48ff2a7 4252 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
4253 = remote_notif_parse (notif, rs->buf);
4254 remote_notif_get_pending_events (notif);
74531fed 4255 }
2d717e4f 4256
74531fed
PA
4257 if (thread_count () == 0)
4258 {
04bd08de 4259 if (!extended_p)
74531fed 4260 error (_("The target is not running (try extended-remote?)"));
82f73884 4261
c35b1492
PA
4262 /* We're connected, but not running. Drop out before we
4263 call start_remote. */
e278ad5b 4264 rs->starting_up = 0;
c35b1492
PA
4265 return;
4266 }
74531fed 4267
74531fed
PA
4268 /* In non-stop mode, any cached wait status will be stored in
4269 the stop reply queue. */
4270 gdb_assert (wait_status == NULL);
f0223081 4271
2455069d 4272 /* Report all signals during attach/startup. */
94bedb42 4273 remote_pass_signals (target, 0, NULL);
221e1a37
PA
4274
4275 /* If there are already stopped threads, mark them stopped and
4276 report their stops before giving the prompt to the user. */
6efcd9a8 4277 process_initial_stop_replies (from_tty);
221e1a37
PA
4278
4279 if (target_can_async_p ())
4280 target_async (1);
74531fed 4281 }
c8d104ad 4282
c8d104ad
PA
4283 /* If we connected to a live target, do some additional setup. */
4284 if (target_has_execution)
4285 {
f4ccffad 4286 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4287 remote_check_symbols ();
c8d104ad 4288 }
50c71eaf 4289
d5551862
SS
4290 /* Possibly the target has been engaged in a trace run started
4291 previously; find out where things are at. */
8bd200f1 4292 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 4293 {
00bf0b85 4294 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4295
00bf0b85
SS
4296 if (current_trace_status ()->running)
4297 printf_filtered (_("Trace is already running on the target.\n"));
4298
ab6617cc 4299 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
4300
4301 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4302 }
4303
c0272db5
TW
4304 /* Possibly the target has been engaged in a btrace record started
4305 previously; find out where things are at. */
4306 remote_btrace_maybe_reopen ();
4307
1e51243a
PA
4308 /* The thread and inferior lists are now synchronized with the
4309 target, our symbols have been relocated, and we're merged the
4310 target's tracepoints with ours. We're done with basic start
4311 up. */
4312 rs->starting_up = 0;
4313
a25a5a45
PA
4314 /* Maybe breakpoints are global and need to be inserted now. */
4315 if (breakpoints_should_be_inserted_now ())
50c71eaf 4316 insert_breakpoints ();
c906108c
SS
4317}
4318
4319/* Open a connection to a remote debugger.
4320 NAME is the filename used for communication. */
4321
4322static void
014f9477 4323remote_open (const char *name, int from_tty)
c906108c 4324{
75c99385 4325 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
4326}
4327
c906108c
SS
4328/* Open a connection to a remote debugger using the extended
4329 remote gdb protocol. NAME is the filename used for communication. */
4330
4331static void
014f9477 4332extended_remote_open (const char *name, int from_tty)
c906108c 4333{
75c99385 4334 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
4335}
4336
ca4f7f8b
PA
4337/* Reset all packets back to "unknown support". Called when opening a
4338 new connection to a remote target. */
c906108c 4339
d471ea57 4340static void
ca4f7f8b 4341reset_all_packet_configs_support (void)
d471ea57
AC
4342{
4343 int i;
a744cf53 4344
444abaca 4345 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4346 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4347}
4348
ca4f7f8b
PA
4349/* Initialize all packet configs. */
4350
4351static void
4352init_all_packet_configs (void)
4353{
4354 int i;
4355
4356 for (i = 0; i < PACKET_MAX; i++)
4357 {
4358 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4359 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4360 }
4361}
4362
23860348 4363/* Symbol look-up. */
dc8acb97
MS
4364
4365static void
36d25514 4366remote_check_symbols (void)
dc8acb97 4367{
d01949b6 4368 struct remote_state *rs = get_remote_state ();
dc8acb97 4369 char *msg, *reply, *tmp;
dc8acb97 4370 int end;
28170b88 4371 long reply_size;
a5c0808e 4372 struct cleanup *old_chain;
dc8acb97 4373
63154eca
PA
4374 /* The remote side has no concept of inferiors that aren't running
4375 yet, it only knows about running processes. If we're connected
4376 but our current inferior is not running, we should not invite the
4377 remote target to request symbol lookups related to its
4378 (unrelated) current process. */
4379 if (!target_has_execution)
4380 return;
4381
4082afcc 4382 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4383 return;
4384
63154eca
PA
4385 /* Make sure the remote is pointing at the right process. Note
4386 there's no way to select "no process". */
3c9c4b83
PA
4387 set_general_process ();
4388
6d820c5c
DJ
4389 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4390 because we need both at the same time. */
224c3ddb 4391 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4392 old_chain = make_cleanup (xfree, msg);
28170b88
MK
4393 reply = (char *) xmalloc (get_remote_packet_size ());
4394 make_cleanup (free_current_contents, &reply);
4395 reply_size = get_remote_packet_size ();
6d820c5c 4396
23860348 4397 /* Invite target to request symbol lookups. */
dc8acb97
MS
4398
4399 putpkt ("qSymbol::");
28170b88
MK
4400 getpkt (&reply, &reply_size, 0);
4401 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
dc8acb97 4402
61012eef 4403 while (startswith (reply, "qSymbol:"))
dc8acb97 4404 {
77e371c0
TT
4405 struct bound_minimal_symbol sym;
4406
dc8acb97 4407 tmp = &reply[8];
cfd77fa1 4408 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4409 msg[end] = '\0';
4410 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4411 if (sym.minsym == NULL)
ea9c271d 4412 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4413 else
2bbe3cc1 4414 {
f5656ead 4415 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4416 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4417
4418 /* If this is a function address, return the start of code
4419 instead of any data function descriptor. */
f5656ead 4420 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
4421 sym_addr,
4422 &current_target);
4423
4424 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4425 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4426 }
4427
dc8acb97 4428 putpkt (msg);
28170b88 4429 getpkt (&reply, &reply_size, 0);
dc8acb97 4430 }
a5c0808e
PA
4431
4432 do_cleanups (old_chain);
dc8acb97
MS
4433}
4434
9db8d71f 4435static struct serial *
baa336ce 4436remote_serial_open (const char *name)
9db8d71f
DJ
4437{
4438 static int udp_warning = 0;
4439
4440 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4441 of in ser-tcp.c, because it is the remote protocol assuming that the
4442 serial connection is reliable and not the serial connection promising
4443 to be. */
61012eef 4444 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4445 {
3e43a32a
MS
4446 warning (_("The remote protocol may be unreliable over UDP.\n"
4447 "Some events may be lost, rendering further debugging "
4448 "impossible."));
9db8d71f
DJ
4449 udp_warning = 1;
4450 }
4451
4452 return serial_open (name);
4453}
4454
d914c394
SS
4455/* Inform the target of our permission settings. The permission flags
4456 work without this, but if the target knows the settings, it can do
4457 a couple things. First, it can add its own check, to catch cases
4458 that somehow manage to get by the permissions checks in target
4459 methods. Second, if the target is wired to disallow particular
4460 settings (for instance, a system in the field that is not set up to
4461 be able to stop at a breakpoint), it can object to any unavailable
4462 permissions. */
4463
4464void
c378d69d 4465remote_set_permissions (struct target_ops *self)
d914c394
SS
4466{
4467 struct remote_state *rs = get_remote_state ();
4468
bba74b36
YQ
4469 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4470 "WriteReg:%x;WriteMem:%x;"
4471 "InsertBreak:%x;InsertTrace:%x;"
4472 "InsertFastTrace:%x;Stop:%x",
4473 may_write_registers, may_write_memory,
4474 may_insert_breakpoints, may_insert_tracepoints,
4475 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4476 putpkt (rs->buf);
4477 getpkt (&rs->buf, &rs->buf_size, 0);
4478
4479 /* If the target didn't like the packet, warn the user. Do not try
4480 to undo the user's settings, that would just be maddening. */
4481 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4482 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4483}
4484
be2a5f71
DJ
4485/* This type describes each known response to the qSupported
4486 packet. */
4487struct protocol_feature
4488{
4489 /* The name of this protocol feature. */
4490 const char *name;
4491
4492 /* The default for this protocol feature. */
4493 enum packet_support default_support;
4494
4495 /* The function to call when this feature is reported, or after
4496 qSupported processing if the feature is not supported.
4497 The first argument points to this structure. The second
4498 argument indicates whether the packet requested support be
4499 enabled, disabled, or probed (or the default, if this function
4500 is being called at the end of processing and this feature was
4501 not reported). The third argument may be NULL; if not NULL, it
4502 is a NUL-terminated string taken from the packet following
4503 this feature's name and an equals sign. */
4504 void (*func) (const struct protocol_feature *, enum packet_support,
4505 const char *);
4506
4507 /* The corresponding packet for this feature. Only used if
4508 FUNC is remote_supported_packet. */
4509 int packet;
4510};
4511
be2a5f71
DJ
4512static void
4513remote_supported_packet (const struct protocol_feature *feature,
4514 enum packet_support support,
4515 const char *argument)
4516{
4517 if (argument)
4518 {
4519 warning (_("Remote qSupported response supplied an unexpected value for"
4520 " \"%s\"."), feature->name);
4521 return;
4522 }
4523
4082afcc 4524 remote_protocol_packets[feature->packet].support = support;
be2a5f71 4525}
be2a5f71
DJ
4526
4527static void
4528remote_packet_size (const struct protocol_feature *feature,
4529 enum packet_support support, const char *value)
4530{
4531 struct remote_state *rs = get_remote_state ();
4532
4533 int packet_size;
4534 char *value_end;
4535
4536 if (support != PACKET_ENABLE)
4537 return;
4538
4539 if (value == NULL || *value == '\0')
4540 {
4541 warning (_("Remote target reported \"%s\" without a size."),
4542 feature->name);
4543 return;
4544 }
4545
4546 errno = 0;
4547 packet_size = strtol (value, &value_end, 16);
4548 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4549 {
4550 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4551 feature->name, value);
4552 return;
4553 }
4554
be2a5f71
DJ
4555 /* Record the new maximum packet size. */
4556 rs->explicit_packet_size = packet_size;
4557}
4558
dc473cfb 4559static const struct protocol_feature remote_protocol_features[] = {
0876f84a 4560 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 4561 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 4562 PACKET_qXfer_auxv },
c78fa86a
GB
4563 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4564 PACKET_qXfer_exec_file },
23181151
DJ
4565 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4566 PACKET_qXfer_features },
cfa9d6d9
DJ
4567 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4568 PACKET_qXfer_libraries },
2268b414
JK
4569 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4570 PACKET_qXfer_libraries_svr4 },
ced63ec0 4571 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 4572 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 4573 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 4574 PACKET_qXfer_memory_map },
4de6483e
UW
4575 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4576 PACKET_qXfer_spu_read },
4577 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4578 PACKET_qXfer_spu_write },
07e059b5
VP
4579 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4580 PACKET_qXfer_osdata },
dc146f7c
VP
4581 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4582 PACKET_qXfer_threads },
b3b9301e
PA
4583 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4584 PACKET_qXfer_traceframe_info },
89be2091
DJ
4585 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4586 PACKET_QPassSignals },
82075af2
JS
4587 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4588 PACKET_QCatchSyscalls },
9b224c5e
PA
4589 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4590 PACKET_QProgramSignals },
a6f3e723
SL
4591 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4592 PACKET_QStartNoAckMode },
4082afcc
PA
4593 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4594 PACKET_multiprocess_feature },
4595 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4596 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4597 PACKET_qXfer_siginfo_read },
4598 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4599 PACKET_qXfer_siginfo_write },
4082afcc 4600 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4601 PACKET_ConditionalTracepoints },
4082afcc 4602 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4603 PACKET_ConditionalBreakpoints },
4082afcc 4604 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4605 PACKET_BreakpointCommands },
4082afcc 4606 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4607 PACKET_FastTracepoints },
4082afcc 4608 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4609 PACKET_StaticTracepoints },
4082afcc 4610 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4611 PACKET_InstallInTrace},
4082afcc
PA
4612 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4613 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4614 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4615 PACKET_bc },
4616 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4617 PACKET_bs },
409873ef
SS
4618 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4619 PACKET_TracepointSource },
d914c394
SS
4620 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4621 PACKET_QAllow },
4082afcc
PA
4622 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4623 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4624 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4625 PACKET_qXfer_fdpic },
169081d0
TG
4626 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4627 PACKET_qXfer_uib },
03583c20
UW
4628 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4629 PACKET_QDisableRandomization },
d1feda86 4630 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4631 { "QTBuffer:size", PACKET_DISABLE,
4632 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4633 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4634 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4635 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 4636 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 4637 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4638 PACKET_qXfer_btrace },
4639 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4640 PACKET_qXfer_btrace_conf },
4641 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4642 PACKET_Qbtrace_conf_bts_size },
4643 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4644 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
4645 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4646 PACKET_fork_event_feature },
4647 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4648 PACKET_vfork_event_feature },
94585166
DB
4649 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4650 PACKET_exec_event_feature },
b20a6524 4651 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 4652 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
4653 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4654 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 4655 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
be2a5f71
DJ
4656};
4657
c8d5aac9
L
4658static char *remote_support_xml;
4659
4660/* Register string appended to "xmlRegisters=" in qSupported query. */
4661
4662void
6e39997a 4663register_remote_support_xml (const char *xml)
c8d5aac9
L
4664{
4665#if defined(HAVE_LIBEXPAT)
4666 if (remote_support_xml == NULL)
c4f7c687 4667 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4668 else
4669 {
4670 char *copy = xstrdup (remote_support_xml + 13);
4671 char *p = strtok (copy, ",");
4672
4673 do
4674 {
4675 if (strcmp (p, xml) == 0)
4676 {
4677 /* already there */
4678 xfree (copy);
4679 return;
4680 }
4681 }
4682 while ((p = strtok (NULL, ",")) != NULL);
4683 xfree (copy);
4684
94b0dee1
PA
4685 remote_support_xml = reconcat (remote_support_xml,
4686 remote_support_xml, ",", xml,
4687 (char *) NULL);
c8d5aac9
L
4688 }
4689#endif
4690}
4691
4692static char *
4693remote_query_supported_append (char *msg, const char *append)
4694{
4695 if (msg)
94b0dee1 4696 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4697 else
4698 return xstrdup (append);
4699}
4700
be2a5f71
DJ
4701static void
4702remote_query_supported (void)
4703{
4704 struct remote_state *rs = get_remote_state ();
4705 char *next;
4706 int i;
4707 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4708
4709 /* The packet support flags are handled differently for this packet
4710 than for most others. We treat an error, a disabled packet, and
4711 an empty response identically: any features which must be reported
4712 to be used will be automatically disabled. An empty buffer
4713 accomplishes this, since that is also the representation for a list
4714 containing no features. */
4715
4716 rs->buf[0] = 0;
4082afcc 4717 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4718 {
c8d5aac9 4719 char *q = NULL;
94b0dee1 4720 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4721
73b8c1fd
PA
4722 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4723 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4724
f7e6eed5
PA
4725 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4726 q = remote_query_supported_append (q, "swbreak+");
4727 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4728 q = remote_query_supported_append (q, "hwbreak+");
4729
dde08ee1
PA
4730 q = remote_query_supported_append (q, "qRelocInsn+");
4731
8020350c
DB
4732 if (packet_set_cmd_state (PACKET_fork_event_feature)
4733 != AUTO_BOOLEAN_FALSE)
4734 q = remote_query_supported_append (q, "fork-events+");
4735 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4736 != AUTO_BOOLEAN_FALSE)
4737 q = remote_query_supported_append (q, "vfork-events+");
4738 if (packet_set_cmd_state (PACKET_exec_event_feature)
4739 != AUTO_BOOLEAN_FALSE)
4740 q = remote_query_supported_append (q, "exec-events+");
89245bc0 4741
750ce8d1
YQ
4742 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4743 q = remote_query_supported_append (q, "vContSupported+");
4744
65706a29
PA
4745 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4746 q = remote_query_supported_append (q, "QThreadEvents+");
4747
f2faf941
PA
4748 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4749 q = remote_query_supported_append (q, "no-resumed+");
4750
b35d5edb
PA
4751 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4752 the qSupported:xmlRegisters=i386 handling. */
4753 if (remote_support_xml != NULL)
4754 q = remote_query_supported_append (q, remote_support_xml);
4755
dde08ee1
PA
4756 q = reconcat (q, "qSupported:", q, (char *) NULL);
4757 putpkt (q);
82f73884 4758
94b0dee1
PA
4759 do_cleanups (old_chain);
4760
be2a5f71
DJ
4761 getpkt (&rs->buf, &rs->buf_size, 0);
4762
4763 /* If an error occured, warn, but do not return - just reset the
4764 buffer to empty and go on to disable features. */
4765 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4766 == PACKET_ERROR)
4767 {
4768 warning (_("Remote failure reply: %s"), rs->buf);
4769 rs->buf[0] = 0;
4770 }
4771 }
4772
4773 memset (seen, 0, sizeof (seen));
4774
4775 next = rs->buf;
4776 while (*next)
4777 {
4778 enum packet_support is_supported;
4779 char *p, *end, *name_end, *value;
4780
4781 /* First separate out this item from the rest of the packet. If
4782 there's another item after this, we overwrite the separator
4783 (terminated strings are much easier to work with). */
4784 p = next;
4785 end = strchr (p, ';');
4786 if (end == NULL)
4787 {
4788 end = p + strlen (p);
4789 next = end;
4790 }
4791 else
4792 {
89be2091
DJ
4793 *end = '\0';
4794 next = end + 1;
4795
be2a5f71
DJ
4796 if (end == p)
4797 {
4798 warning (_("empty item in \"qSupported\" response"));
4799 continue;
4800 }
be2a5f71
DJ
4801 }
4802
4803 name_end = strchr (p, '=');
4804 if (name_end)
4805 {
4806 /* This is a name=value entry. */
4807 is_supported = PACKET_ENABLE;
4808 value = name_end + 1;
4809 *name_end = '\0';
4810 }
4811 else
4812 {
4813 value = NULL;
4814 switch (end[-1])
4815 {
4816 case '+':
4817 is_supported = PACKET_ENABLE;
4818 break;
4819
4820 case '-':
4821 is_supported = PACKET_DISABLE;
4822 break;
4823
4824 case '?':
4825 is_supported = PACKET_SUPPORT_UNKNOWN;
4826 break;
4827
4828 default:
3e43a32a
MS
4829 warning (_("unrecognized item \"%s\" "
4830 "in \"qSupported\" response"), p);
be2a5f71
DJ
4831 continue;
4832 }
4833 end[-1] = '\0';
4834 }
4835
4836 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4837 if (strcmp (remote_protocol_features[i].name, p) == 0)
4838 {
4839 const struct protocol_feature *feature;
4840
4841 seen[i] = 1;
4842 feature = &remote_protocol_features[i];
4843 feature->func (feature, is_supported, value);
4844 break;
4845 }
4846 }
4847
4848 /* If we increased the packet size, make sure to increase the global
4849 buffer size also. We delay this until after parsing the entire
4850 qSupported packet, because this is the same buffer we were
4851 parsing. */
4852 if (rs->buf_size < rs->explicit_packet_size)
4853 {
4854 rs->buf_size = rs->explicit_packet_size;
224c3ddb 4855 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
4856 }
4857
4858 /* Handle the defaults for unmentioned features. */
4859 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4860 if (!seen[i])
4861 {
4862 const struct protocol_feature *feature;
4863
4864 feature = &remote_protocol_features[i];
4865 feature->func (feature, feature->default_support, NULL);
4866 }
4867}
4868
048094ac
PA
4869/* Serial QUIT handler for the remote serial descriptor.
4870
4871 Defers handling a Ctrl-C until we're done with the current
4872 command/response packet sequence, unless:
4873
4874 - We're setting up the connection. Don't send a remote interrupt
4875 request, as we're not fully synced yet. Quit immediately
4876 instead.
4877
4878 - The target has been resumed in the foreground
4879 (target_terminal_is_ours is false) with a synchronous resume
4880 packet, and we're blocked waiting for the stop reply, thus a
4881 Ctrl-C should be immediately sent to the target.
4882
4883 - We get a second Ctrl-C while still within the same serial read or
4884 write. In that case the serial is seemingly wedged --- offer to
4885 quit/disconnect.
4886
4887 - We see a second Ctrl-C without target response, after having
4888 previously interrupted the target. In that case the target/stub
4889 is probably wedged --- offer to quit/disconnect.
4890*/
4891
4892static void
4893remote_serial_quit_handler (void)
4894{
4895 struct remote_state *rs = get_remote_state ();
4896
4897 if (check_quit_flag ())
4898 {
4899 /* If we're starting up, we're not fully synced yet. Quit
4900 immediately. */
4901 if (rs->starting_up)
4902 quit ();
4903 else if (rs->got_ctrlc_during_io)
4904 {
4905 if (query (_("The target is not responding to GDB commands.\n"
4906 "Stop debugging it? ")))
4907 remote_unpush_and_throw ();
4908 }
4909 /* If ^C has already been sent once, offer to disconnect. */
4910 else if (!target_terminal_is_ours () && rs->ctrlc_pending_p)
4911 interrupt_query ();
4912 /* All-stop protocol, and blocked waiting for stop reply. Send
4913 an interrupt request. */
4914 else if (!target_terminal_is_ours () && rs->waiting_for_stop_reply)
4915 target_interrupt (inferior_ptid);
4916 else
4917 rs->got_ctrlc_during_io = 1;
4918 }
4919}
4920
78a095c3
JK
4921/* Remove any of the remote.c targets from target stack. Upper targets depend
4922 on it so remove them first. */
4923
4924static void
4925remote_unpush_target (void)
4926{
915ef8b1 4927 pop_all_targets_at_and_above (process_stratum);
78a095c3 4928}
be2a5f71 4929
048094ac
PA
4930static void
4931remote_unpush_and_throw (void)
4932{
4933 remote_unpush_target ();
4934 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
4935}
4936
c906108c 4937static void
014f9477 4938remote_open_1 (const char *name, int from_tty,
3e43a32a 4939 struct target_ops *target, int extended_p)
c906108c 4940{
d01949b6 4941 struct remote_state *rs = get_remote_state ();
a6f3e723 4942
c906108c 4943 if (name == 0)
8a3fe4f8 4944 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4945 "serial device is attached to the remote system\n"
8a3fe4f8 4946 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4947
23860348 4948 /* See FIXME above. */
c6ebd6cf 4949 if (!target_async_permitted)
92d1e331 4950 wait_forever_enabled_p = 1;
6426a772 4951
2d717e4f 4952 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4953 Ask this question first, before target_preopen has a chance to kill
4954 anything. */
5d93a237 4955 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4956 {
78a095c3
JK
4957 if (from_tty
4958 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4959 error (_("Still connected."));
4960 }
4961
78a095c3 4962 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4963 target_preopen (from_tty);
4964
89be2091 4965 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4966 xfree (rs->last_pass_packet);
4967 rs->last_pass_packet = NULL;
89be2091 4968
9b224c5e
PA
4969 /* Make sure we send the program signals list the next time we
4970 resume. */
5e4a05c4
TT
4971 xfree (rs->last_program_signals_packet);
4972 rs->last_program_signals_packet = NULL;
9b224c5e 4973
ad9a8f3f 4974 remote_fileio_reset ();
1dd41f16
NS
4975 reopen_exec_file ();
4976 reread_symbols ();
4977
5d93a237
TT
4978 rs->remote_desc = remote_serial_open (name);
4979 if (!rs->remote_desc)
c906108c
SS
4980 perror_with_name (name);
4981
4982 if (baud_rate != -1)
4983 {
5d93a237 4984 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4985 {
9b74d5d3
KB
4986 /* The requested speed could not be set. Error out to
4987 top level after closing remote_desc. Take care to
4988 set remote_desc to NULL to avoid closing remote_desc
4989 more than once. */
5d93a237
TT
4990 serial_close (rs->remote_desc);
4991 rs->remote_desc = NULL;
c906108c
SS
4992 perror_with_name (name);
4993 }
4994 }
4995
236af5e3 4996 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 4997 serial_raw (rs->remote_desc);
c906108c
SS
4998
4999 /* If there is something sitting in the buffer we might take it as a
5000 response to a command, which would be bad. */
5d93a237 5001 serial_flush_input (rs->remote_desc);
c906108c
SS
5002
5003 if (from_tty)
5004 {
5005 puts_filtered ("Remote debugging using ");
5006 puts_filtered (name);
5007 puts_filtered ("\n");
5008 }
23860348 5009 push_target (target); /* Switch to using remote target now. */
c906108c 5010
74531fed
PA
5011 /* Register extra event sources in the event loop. */
5012 remote_async_inferior_event_token
5013 = create_async_event_handler (remote_async_inferior_event_handler,
5014 NULL);
5965e028 5015 rs->notif_state = remote_notif_state_allocate ();
74531fed 5016
be2a5f71
DJ
5017 /* Reset the target state; these things will be queried either by
5018 remote_query_supported or as they are needed. */
ca4f7f8b 5019 reset_all_packet_configs_support ();
74531fed 5020 rs->cached_wait_status = 0;
be2a5f71 5021 rs->explicit_packet_size = 0;
a6f3e723 5022 rs->noack_mode = 0;
82f73884 5023 rs->extended = extended_p;
e24a49d8 5024 rs->waiting_for_stop_reply = 0;
3a29589a 5025 rs->ctrlc_pending_p = 0;
048094ac 5026 rs->got_ctrlc_during_io = 0;
802188a7 5027
47f8a51d
TT
5028 rs->general_thread = not_sent_ptid;
5029 rs->continue_thread = not_sent_ptid;
262e1174 5030 rs->remote_traceframe_number = -1;
c906108c 5031
3a00c802
PA
5032 rs->last_resume_exec_dir = EXEC_FORWARD;
5033
9d1f7ab2 5034 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
5035 rs->use_threadinfo_query = 1;
5036 rs->use_threadextra_query = 1;
9d1f7ab2 5037
80152258
PA
5038 readahead_cache_invalidate ();
5039
048094ac
PA
5040 /* Start out by owning the terminal. */
5041 remote_async_terminal_ours_p = 1;
5042
c6ebd6cf 5043 if (target_async_permitted)
92d1e331 5044 {
92d1e331
DJ
5045 /* FIXME: cagney/1999-09-23: During the initial connection it is
5046 assumed that the target is already ready and able to respond to
0df8b418 5047 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 5048 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 5049 around this. Eventually a mechanism that allows
92d1e331 5050 wait_for_inferior() to expect/get timeouts will be
23860348 5051 implemented. */
92d1e331
DJ
5052 wait_forever_enabled_p = 0;
5053 }
5054
23860348 5055 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 5056 no_shared_libraries (NULL, 0);
f78f6cf1 5057
74531fed
PA
5058 /* Start afresh. */
5059 init_thread_list ();
5060
36918e70 5061 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
5062 target (we'd otherwise be in an inconsistent state) and then
5063 propogate the error on up the exception chain. This ensures that
5064 the caller doesn't stumble along blindly assuming that the
5065 function succeeded. The CLI doesn't have this problem but other
5066 UI's, such as MI do.
36918e70
AC
5067
5068 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5069 this function should return an error indication letting the
ce2826aa 5070 caller restore the previous state. Unfortunately the command
36918e70
AC
5071 ``target remote'' is directly wired to this function making that
5072 impossible. On a positive note, the CLI side of this problem has
5073 been fixed - the function set_cmd_context() makes it possible for
5074 all the ``target ....'' commands to share a common callback
5075 function. See cli-dump.c. */
109c3e39 5076 {
2d717e4f 5077
492d29ea 5078 TRY
04bd08de
TT
5079 {
5080 remote_start_remote (from_tty, target, extended_p);
5081 }
492d29ea 5082 CATCH (ex, RETURN_MASK_ALL)
109c3e39 5083 {
c8d104ad
PA
5084 /* Pop the partially set up target - unless something else did
5085 already before throwing the exception. */
5d93a237 5086 if (rs->remote_desc != NULL)
78a095c3 5087 remote_unpush_target ();
c6ebd6cf 5088 if (target_async_permitted)
109c3e39
AC
5089 wait_forever_enabled_p = 1;
5090 throw_exception (ex);
5091 }
492d29ea 5092 END_CATCH
109c3e39 5093 }
c906108c 5094
f4abbc16
MM
5095 remote_btrace_reset ();
5096
c6ebd6cf 5097 if (target_async_permitted)
92d1e331 5098 wait_forever_enabled_p = 1;
43ff13b4
JM
5099}
5100
de0d863e
DB
5101/* Detach the specified process. */
5102
5103static void
5104remote_detach_pid (int pid)
5105{
5106 struct remote_state *rs = get_remote_state ();
5107
5108 if (remote_multi_process_p (rs))
5109 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5110 else
5111 strcpy (rs->buf, "D");
5112
5113 putpkt (rs->buf);
5114 getpkt (&rs->buf, &rs->buf_size, 0);
5115
5116 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5117 ;
5118 else if (rs->buf[0] == '\0')
5119 error (_("Remote doesn't know how to detach"));
5120 else
5121 error (_("Can't detach process."));
5122}
5123
5124/* This detaches a program to which we previously attached, using
5125 inferior_ptid to identify the process. After this is done, GDB
5126 can be used to debug some other program. We better not have left
5127 any breakpoints in the target program or it'll die when it hits
5128 one. */
c906108c
SS
5129
5130static void
de0d863e 5131remote_detach_1 (const char *args, int from_tty)
c906108c 5132{
82f73884 5133 int pid = ptid_get_pid (inferior_ptid);
d01949b6 5134 struct remote_state *rs = get_remote_state ();
de0d863e
DB
5135 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5136 int is_fork_parent;
c906108c
SS
5137
5138 if (args)
8a3fe4f8 5139 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 5140
2d717e4f
DJ
5141 if (!target_has_execution)
5142 error (_("No process to detach from."));
5143
0f48b757 5144 target_announce_detach (from_tty);
7cee1e54 5145
c906108c 5146 /* Tell the remote target to detach. */
de0d863e 5147 remote_detach_pid (pid);
82f73884 5148
8020350c
DB
5149 /* Exit only if this is the only active inferior. */
5150 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
7cee1e54 5151 puts_filtered (_("Ending remote debugging.\n"));
82f73884 5152
de0d863e
DB
5153 /* Check to see if we are detaching a fork parent. Note that if we
5154 are detaching a fork child, tp == NULL. */
5155 is_fork_parent = (tp != NULL
5156 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5157
5158 /* If doing detach-on-fork, we don't mourn, because that will delete
5159 breakpoints that should be available for the followed inferior. */
5160 if (!is_fork_parent)
5161 target_mourn_inferior ();
5162 else
5163 {
5164 inferior_ptid = null_ptid;
5165 detach_inferior (pid);
5166 }
2d717e4f
DJ
5167}
5168
5169static void
52554a0e 5170remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5171{
de0d863e 5172 remote_detach_1 (args, from_tty);
2d717e4f
DJ
5173}
5174
5175static void
52554a0e 5176extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5177{
de0d863e
DB
5178 remote_detach_1 (args, from_tty);
5179}
5180
5181/* Target follow-fork function for remote targets. On entry, and
5182 at return, the current inferior is the fork parent.
5183
5184 Note that although this is currently only used for extended-remote,
5185 it is named remote_follow_fork in anticipation of using it for the
5186 remote target as well. */
5187
5188static int
5189remote_follow_fork (struct target_ops *ops, int follow_child,
5190 int detach_fork)
5191{
5192 struct remote_state *rs = get_remote_state ();
c269dbdb 5193 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5194
c269dbdb
DB
5195 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5196 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5197 {
5198 /* When following the parent and detaching the child, we detach
5199 the child here. For the case of following the child and
5200 detaching the parent, the detach is done in the target-
5201 independent follow fork code in infrun.c. We can't use
5202 target_detach when detaching an unfollowed child because
5203 the client side doesn't know anything about the child. */
5204 if (detach_fork && !follow_child)
5205 {
5206 /* Detach the fork child. */
5207 ptid_t child_ptid;
5208 pid_t child_pid;
5209
5210 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5211 child_pid = ptid_get_pid (child_ptid);
5212
5213 remote_detach_pid (child_pid);
5214 detach_inferior (child_pid);
5215 }
5216 }
5217 return 0;
c906108c
SS
5218}
5219
94585166
DB
5220/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5221 in the program space of the new inferior. On entry and at return the
5222 current inferior is the exec'ing inferior. INF is the new exec'd
5223 inferior, which may be the same as the exec'ing inferior unless
5224 follow-exec-mode is "new". */
5225
5226static void
5227remote_follow_exec (struct target_ops *ops,
5228 struct inferior *inf, char *execd_pathname)
5229{
5230 /* We know that this is a target file name, so if it has the "target:"
5231 prefix we strip it off before saving it in the program space. */
5232 if (is_target_filename (execd_pathname))
5233 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5234
5235 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5236}
5237
6ad8ae5c
DJ
5238/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5239
43ff13b4 5240static void
fee354ee 5241remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 5242{
43ff13b4 5243 if (args)
2d717e4f 5244 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5245
8020350c
DB
5246 /* Make sure we unpush even the extended remote targets. Calling
5247 target_mourn_inferior won't unpush, and remote_mourn won't
5248 unpush if there is more than one inferior left. */
5249 unpush_target (target);
5250 generic_mourn_inferior ();
2d717e4f 5251
43ff13b4
JM
5252 if (from_tty)
5253 puts_filtered ("Ending remote debugging.\n");
5254}
5255
2d717e4f
DJ
5256/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5257 be chatty about it. */
5258
5259static void
20f796c9
GB
5260extended_remote_attach (struct target_ops *target, const char *args,
5261 int from_tty)
2d717e4f
DJ
5262{
5263 struct remote_state *rs = get_remote_state ();
be86555c 5264 int pid;
96ef3384 5265 char *wait_status = NULL;
2d717e4f 5266
74164c56 5267 pid = parse_pid_to_attach (args);
2d717e4f 5268
74164c56
JK
5269 /* Remote PID can be freely equal to getpid, do not check it here the same
5270 way as in other targets. */
2d717e4f 5271
4082afcc 5272 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5273 error (_("This target does not support attaching to a process"));
5274
7cee1e54
PA
5275 if (from_tty)
5276 {
5277 char *exec_file = get_exec_file (0);
5278
5279 if (exec_file)
5280 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5281 target_pid_to_str (pid_to_ptid (pid)));
5282 else
5283 printf_unfiltered (_("Attaching to %s\n"),
5284 target_pid_to_str (pid_to_ptid (pid)));
5285
5286 gdb_flush (gdb_stdout);
5287 }
5288
bba74b36 5289 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
5290 putpkt (rs->buf);
5291 getpkt (&rs->buf, &rs->buf_size, 0);
5292
4082afcc
PA
5293 switch (packet_ok (rs->buf,
5294 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5295 {
4082afcc 5296 case PACKET_OK:
6efcd9a8 5297 if (!target_is_non_stop_p ())
74531fed
PA
5298 {
5299 /* Save the reply for later. */
224c3ddb 5300 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
5301 strcpy (wait_status, rs->buf);
5302 }
5303 else if (strcmp (rs->buf, "OK") != 0)
5304 error (_("Attaching to %s failed with: %s"),
5305 target_pid_to_str (pid_to_ptid (pid)),
5306 rs->buf);
4082afcc
PA
5307 break;
5308 case PACKET_UNKNOWN:
5309 error (_("This target does not support attaching to a process"));
5310 default:
5311 error (_("Attaching to %s failed"),
5312 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 5313 }
2d717e4f 5314
1b6e6f5c 5315 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5316
2d717e4f 5317 inferior_ptid = pid_to_ptid (pid);
79d7f229 5318
6efcd9a8 5319 if (target_is_non_stop_p ())
bad34192
PA
5320 {
5321 struct thread_info *thread;
79d7f229 5322
bad34192 5323 /* Get list of threads. */
e8032dde 5324 remote_update_thread_list (target);
82f73884 5325
bad34192
PA
5326 thread = first_thread_of_process (pid);
5327 if (thread)
5328 inferior_ptid = thread->ptid;
5329 else
5330 inferior_ptid = pid_to_ptid (pid);
5331
5332 /* Invalidate our notion of the remote current thread. */
47f8a51d 5333 record_currthread (rs, minus_one_ptid);
bad34192 5334 }
74531fed 5335 else
bad34192
PA
5336 {
5337 /* Now, if we have thread information, update inferior_ptid. */
5338 inferior_ptid = remote_current_thread (inferior_ptid);
5339
5340 /* Add the main thread to the thread list. */
5341 add_thread_silent (inferior_ptid);
5342 }
c0a2216e 5343
96ef3384
UW
5344 /* Next, if the target can specify a description, read it. We do
5345 this before anything involving memory or registers. */
5346 target_find_description ();
5347
6efcd9a8 5348 if (!target_is_non_stop_p ())
74531fed
PA
5349 {
5350 /* Use the previously fetched status. */
5351 gdb_assert (wait_status != NULL);
5352
5353 if (target_can_async_p ())
5354 {
722247f1
YQ
5355 struct notif_event *reply
5356 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 5357
722247f1 5358 push_stop_reply ((struct stop_reply *) reply);
74531fed 5359
6a3753b3 5360 target_async (1);
74531fed
PA
5361 }
5362 else
5363 {
5364 gdb_assert (wait_status != NULL);
5365 strcpy (rs->buf, wait_status);
5366 rs->cached_wait_status = 1;
5367 }
5368 }
5369 else
5370 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5371}
5372
b9c1d481
AS
5373/* Implementation of the to_post_attach method. */
5374
5375static void
5376extended_remote_post_attach (struct target_ops *ops, int pid)
5377{
6efcd9a8
PA
5378 /* Get text, data & bss offsets. */
5379 get_offsets ();
5380
b9c1d481
AS
5381 /* In certain cases GDB might not have had the chance to start
5382 symbol lookup up until now. This could happen if the debugged
5383 binary is not using shared libraries, the vsyscall page is not
5384 present (on Linux) and the binary itself hadn't changed since the
5385 debugging process was started. */
5386 if (symfile_objfile != NULL)
5387 remote_check_symbols();
5388}
5389
c906108c 5390\f
506fb367
DJ
5391/* Check for the availability of vCont. This function should also check
5392 the response. */
c906108c
SS
5393
5394static void
6d820c5c 5395remote_vcont_probe (struct remote_state *rs)
c906108c 5396{
2e9f7625 5397 char *buf;
6d820c5c 5398
2e9f7625
DJ
5399 strcpy (rs->buf, "vCont?");
5400 putpkt (rs->buf);
6d820c5c 5401 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5402 buf = rs->buf;
c906108c 5403
506fb367 5404 /* Make sure that the features we assume are supported. */
61012eef 5405 if (startswith (buf, "vCont"))
506fb367
DJ
5406 {
5407 char *p = &buf[5];
750ce8d1 5408 int support_c, support_C;
506fb367 5409
750ce8d1
YQ
5410 rs->supports_vCont.s = 0;
5411 rs->supports_vCont.S = 0;
506fb367
DJ
5412 support_c = 0;
5413 support_C = 0;
d458bd84 5414 rs->supports_vCont.t = 0;
c1e36e3e 5415 rs->supports_vCont.r = 0;
506fb367
DJ
5416 while (p && *p == ';')
5417 {
5418 p++;
5419 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5420 rs->supports_vCont.s = 1;
506fb367 5421 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5422 rs->supports_vCont.S = 1;
506fb367
DJ
5423 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5424 support_c = 1;
5425 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5426 support_C = 1;
74531fed 5427 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5428 rs->supports_vCont.t = 1;
c1e36e3e
PA
5429 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5430 rs->supports_vCont.r = 1;
506fb367
DJ
5431
5432 p = strchr (p, ';');
5433 }
c906108c 5434
750ce8d1
YQ
5435 /* If c, and C are not all supported, we can't use vCont. Clearing
5436 BUF will make packet_ok disable the packet. */
5437 if (!support_c || !support_C)
506fb367
DJ
5438 buf[0] = 0;
5439 }
c906108c 5440
444abaca 5441 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 5442}
c906108c 5443
0d8f58ca
PA
5444/* Helper function for building "vCont" resumptions. Write a
5445 resumption to P. ENDP points to one-passed-the-end of the buffer
5446 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5447 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5448 resumed thread should be single-stepped and/or signalled. If PTID
5449 equals minus_one_ptid, then all threads are resumed; if PTID
5450 represents a process, then all threads of the process are resumed;
5451 the thread to be stepped and/or signalled is given in the global
5452 INFERIOR_PTID. */
5453
5454static char *
5455append_resumption (char *p, char *endp,
2ea28649 5456 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
5457{
5458 struct remote_state *rs = get_remote_state ();
5459
a493e3e2 5460 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5461 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5462 else if (step
5463 /* GDB is willing to range step. */
5464 && use_range_stepping
5465 /* Target supports range stepping. */
5466 && rs->supports_vCont.r
5467 /* We don't currently support range stepping multiple
5468 threads with a wildcard (though the protocol allows it,
5469 so stubs shouldn't make an active effort to forbid
5470 it). */
5471 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5472 {
5473 struct thread_info *tp;
5474
5475 if (ptid_equal (ptid, minus_one_ptid))
5476 {
5477 /* If we don't know about the target thread's tid, then
5478 we're resuming magic_null_ptid (see caller). */
5479 tp = find_thread_ptid (magic_null_ptid);
5480 }
5481 else
5482 tp = find_thread_ptid (ptid);
5483 gdb_assert (tp != NULL);
5484
5485 if (tp->control.may_range_step)
5486 {
5487 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5488
5489 p += xsnprintf (p, endp - p, ";r%s,%s",
5490 phex_nz (tp->control.step_range_start,
5491 addr_size),
5492 phex_nz (tp->control.step_range_end,
5493 addr_size));
5494 }
5495 else
5496 p += xsnprintf (p, endp - p, ";s");
5497 }
0d8f58ca
PA
5498 else if (step)
5499 p += xsnprintf (p, endp - p, ";s");
a493e3e2 5500 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
5501 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5502 else
5503 p += xsnprintf (p, endp - p, ";c");
5504
5505 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5506 {
5507 ptid_t nptid;
5508
5509 /* All (-1) threads of process. */
ba348170 5510 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
5511
5512 p += xsnprintf (p, endp - p, ":");
5513 p = write_ptid (p, endp, nptid);
5514 }
5515 else if (!ptid_equal (ptid, minus_one_ptid))
5516 {
5517 p += xsnprintf (p, endp - p, ":");
5518 p = write_ptid (p, endp, ptid);
5519 }
5520
5521 return p;
5522}
5523
799a2abe
PA
5524/* Clear the thread's private info on resume. */
5525
5526static void
5527resume_clear_thread_private_info (struct thread_info *thread)
5528{
5529 if (thread->priv != NULL)
5530 {
5531 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5532 thread->priv->watch_data_address = 0;
5533 }
5534}
5535
e5ef252a
PA
5536/* Append a vCont continue-with-signal action for threads that have a
5537 non-zero stop signal. */
5538
5539static char *
5540append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5541{
5542 struct thread_info *thread;
5543
034f788c 5544 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
5545 if (ptid_match (thread->ptid, ptid)
5546 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 5547 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
5548 {
5549 p = append_resumption (p, endp, thread->ptid,
5550 0, thread->suspend.stop_signal);
5551 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 5552 resume_clear_thread_private_info (thread);
e5ef252a
PA
5553 }
5554
5555 return p;
5556}
5557
506fb367
DJ
5558/* Resume the remote inferior by using a "vCont" packet. The thread
5559 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
5560 resumed thread should be single-stepped and/or signalled. If PTID
5561 equals minus_one_ptid, then all threads are resumed; the thread to
5562 be stepped and/or signalled is given in the global INFERIOR_PTID.
5563 This function returns non-zero iff it resumes the inferior.
44eaed12 5564
506fb367
DJ
5565 This function issues a strict subset of all possible vCont commands at the
5566 moment. */
44eaed12 5567
506fb367 5568static int
2ea28649 5569remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5570{
5571 struct remote_state *rs = get_remote_state ();
82f73884
PA
5572 char *p;
5573 char *endp;
44eaed12 5574
4082afcc 5575 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5576 remote_vcont_probe (rs);
44eaed12 5577
4082afcc 5578 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5579 return 0;
44eaed12 5580
82f73884
PA
5581 p = rs->buf;
5582 endp = rs->buf + get_remote_packet_size ();
5583
506fb367
DJ
5584 /* If we could generate a wider range of packets, we'd have to worry
5585 about overflowing BUF. Should there be a generic
5586 "multi-part-packet" packet? */
5587
0d8f58ca
PA
5588 p += xsnprintf (p, endp - p, "vCont");
5589
79d7f229 5590 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5591 {
79d7f229
PA
5592 /* MAGIC_NULL_PTID means that we don't have any active threads,
5593 so we don't have any TID numbers the inferior will
5594 understand. Make sure to only send forms that do not specify
5595 a TID. */
a9cbf802 5596 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5597 }
0d8f58ca 5598 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5599 {
0d8f58ca
PA
5600 /* Resume all threads (of all processes, or of a single
5601 process), with preference for INFERIOR_PTID. This assumes
5602 inferior_ptid belongs to the set of all threads we are about
5603 to resume. */
a493e3e2 5604 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5605 {
0d8f58ca
PA
5606 /* Step inferior_ptid, with or without signal. */
5607 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5608 }
0d8f58ca 5609
e5ef252a
PA
5610 /* Also pass down any pending signaled resumption for other
5611 threads not the current. */
5612 p = append_pending_thread_resumptions (p, endp, ptid);
5613
0d8f58ca 5614 /* And continue others without a signal. */
a493e3e2 5615 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5616 }
5617 else
506fb367
DJ
5618 {
5619 /* Scheduler locking; resume only PTID. */
a9cbf802 5620 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5621 }
c906108c 5622
82f73884
PA
5623 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5624 putpkt (rs->buf);
506fb367 5625
6efcd9a8 5626 if (target_is_non_stop_p ())
74531fed
PA
5627 {
5628 /* In non-stop, the stub replies to vCont with "OK". The stop
5629 reply will be reported asynchronously by means of a `%Stop'
5630 notification. */
5631 getpkt (&rs->buf, &rs->buf_size, 0);
5632 if (strcmp (rs->buf, "OK") != 0)
5633 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5634 }
5635
506fb367 5636 return 1;
c906108c 5637}
43ff13b4 5638
506fb367
DJ
5639/* Tell the remote machine to resume. */
5640
43ff13b4 5641static void
28439f5e 5642remote_resume (struct target_ops *ops,
2ea28649 5643 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5644{
d01949b6 5645 struct remote_state *rs = get_remote_state ();
2e9f7625 5646 char *buf;
799a2abe 5647 struct thread_info *thread;
43ff13b4 5648
722247f1
YQ
5649 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5650 (explained in remote-notif.c:handle_notification) so
5651 remote_notif_process is not called. We need find a place where
5652 it is safe to start a 'vNotif' sequence. It is good to do it
5653 before resuming inferior, because inferior was stopped and no RSP
5654 traffic at that moment. */
6efcd9a8 5655 if (!target_is_non_stop_p ())
5965e028 5656 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 5657
b73be471 5658 rs->last_sent_signal = siggnal;
280ceea3 5659 rs->last_sent_step = step;
43ff13b4 5660
3a00c802
PA
5661 rs->last_resume_exec_dir = execution_direction;
5662
506fb367 5663 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
5664 /* No reverse support (yet) for vCont. */
5665 if (execution_direction != EXEC_REVERSE)
5666 if (remote_vcont_resume (ptid, step, siggnal))
5667 goto done;
506fb367 5668
79d7f229
PA
5669 /* All other supported resume packets do use Hc, so set the continue
5670 thread. */
5671 if (ptid_equal (ptid, minus_one_ptid))
5672 set_continue_thread (any_thread_ptid);
506fb367 5673 else
79d7f229 5674 set_continue_thread (ptid);
506fb367 5675
799a2abe
PA
5676 ALL_NON_EXITED_THREADS (thread)
5677 resume_clear_thread_private_info (thread);
5678
2e9f7625 5679 buf = rs->buf;
b2175913
MS
5680 if (execution_direction == EXEC_REVERSE)
5681 {
5682 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 5683 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 5684 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 5685 siggnal);
40ab02ce 5686
4082afcc 5687 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
40ab02ce 5688 error (_("Remote reverse-step not supported."));
4082afcc 5689 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
08c93ed9 5690 error (_("Remote reverse-continue not supported."));
40ab02ce 5691
b2175913
MS
5692 strcpy (buf, step ? "bs" : "bc");
5693 }
a493e3e2 5694 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
5695 {
5696 buf[0] = step ? 'S' : 'C';
c5aa993b 5697 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 5698 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
5699 buf[3] = '\0';
5700 }
5701 else
c5aa993b 5702 strcpy (buf, step ? "s" : "c");
506fb367 5703
44eaed12 5704 putpkt (buf);
43ff13b4 5705
75c99385 5706 done:
2acceee2 5707 /* We are about to start executing the inferior, let's register it
0df8b418
MS
5708 with the event loop. NOTE: this is the one place where all the
5709 execution commands end up. We could alternatively do this in each
23860348 5710 of the execution commands in infcmd.c. */
2acceee2
JM
5711 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5712 into infcmd.c in order to allow inferior function calls to work
23860348 5713 NOT asynchronously. */
362646f5 5714 if (target_can_async_p ())
6a3753b3 5715 target_async (1);
e24a49d8
PA
5716
5717 /* We've just told the target to resume. The remote server will
5718 wait for the inferior to stop, and then send a stop reply. In
5719 the mean time, we can't start another command/query ourselves
74531fed
PA
5720 because the stub wouldn't be ready to process it. This applies
5721 only to the base all-stop protocol, however. In non-stop (which
5722 only supports vCont), the stub replies with an "OK", and is
5723 immediate able to process further serial input. */
6efcd9a8 5724 if (!target_is_non_stop_p ())
74531fed 5725 rs->waiting_for_stop_reply = 1;
43ff13b4 5726}
c906108c 5727\f
43ff13b4 5728
74531fed
PA
5729/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5730 thread, all threads of a remote process, or all threads of all
5731 processes. */
5732
5733static void
5734remote_stop_ns (ptid_t ptid)
5735{
5736 struct remote_state *rs = get_remote_state ();
5737 char *p = rs->buf;
5738 char *endp = rs->buf + get_remote_packet_size ();
74531fed 5739
4082afcc 5740 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
5741 remote_vcont_probe (rs);
5742
d458bd84 5743 if (!rs->supports_vCont.t)
74531fed
PA
5744 error (_("Remote server does not support stopping threads"));
5745
f91d3df5
PA
5746 if (ptid_equal (ptid, minus_one_ptid)
5747 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5748 p += xsnprintf (p, endp - p, "vCont;t");
5749 else
5750 {
5751 ptid_t nptid;
5752
74531fed
PA
5753 p += xsnprintf (p, endp - p, "vCont;t:");
5754
5755 if (ptid_is_pid (ptid))
5756 /* All (-1) threads of process. */
ba348170 5757 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
5758 else
5759 {
5760 /* Small optimization: if we already have a stop reply for
5761 this thread, no use in telling the stub we want this
5762 stopped. */
5763 if (peek_stop_reply (ptid))
5764 return;
5765
5766 nptid = ptid;
5767 }
5768
a9cbf802 5769 write_ptid (p, endp, nptid);
74531fed
PA
5770 }
5771
5772 /* In non-stop, we get an immediate OK reply. The stop reply will
5773 come in asynchronously by notification. */
5774 putpkt (rs->buf);
5775 getpkt (&rs->buf, &rs->buf_size, 0);
5776 if (strcmp (rs->buf, "OK") != 0)
5777 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5778}
5779
bfedc46a
PA
5780/* All-stop version of target_interrupt. Sends a break or a ^C to
5781 interrupt the remote target. It is undefined which thread of which
5782 process reports the interrupt. */
74531fed
PA
5783
5784static void
de979965 5785remote_interrupt_as (void)
74531fed
PA
5786{
5787 struct remote_state *rs = get_remote_state ();
5788
3a29589a
DJ
5789 rs->ctrlc_pending_p = 1;
5790
74531fed
PA
5791 /* If the inferior is stopped already, but the core didn't know
5792 about it yet, just ignore the request. The cached wait status
5793 will be collected in remote_wait. */
5794 if (rs->cached_wait_status)
5795 return;
5796
9a7071a8
JB
5797 /* Send interrupt_sequence to remote target. */
5798 send_interrupt_sequence ();
74531fed
PA
5799}
5800
de979965
PA
5801/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
5802 the remote target. It is undefined which thread of which process
e42de8c7
PA
5803 reports the interrupt. Throws an error if the packet is not
5804 supported by the server. */
de979965 5805
e42de8c7 5806static void
de979965
PA
5807remote_interrupt_ns (void)
5808{
5809 struct remote_state *rs = get_remote_state ();
5810 char *p = rs->buf;
5811 char *endp = rs->buf + get_remote_packet_size ();
5812
5813 xsnprintf (p, endp - p, "vCtrlC");
5814
5815 /* In non-stop, we get an immediate OK reply. The stop reply will
5816 come in asynchronously by notification. */
5817 putpkt (rs->buf);
5818 getpkt (&rs->buf, &rs->buf_size, 0);
5819
5820 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5821 {
5822 case PACKET_OK:
5823 break;
5824 case PACKET_UNKNOWN:
e42de8c7 5825 error (_("No support for interrupting the remote target."));
de979965
PA
5826 case PACKET_ERROR:
5827 error (_("Interrupting target failed: %s"), rs->buf);
5828 }
de979965
PA
5829}
5830
bfedc46a 5831/* Implement the to_stop function for the remote targets. */
74531fed 5832
c906108c 5833static void
1eab8a48 5834remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5835{
7a292a7a 5836 if (remote_debug)
0f71a2f6 5837 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5838
6efcd9a8 5839 if (target_is_non_stop_p ())
74531fed 5840 remote_stop_ns (ptid);
c906108c 5841 else
bfedc46a
PA
5842 {
5843 /* We don't currently have a way to transparently pause the
5844 remote target in all-stop mode. Interrupt it instead. */
de979965 5845 remote_interrupt_as ();
bfedc46a
PA
5846 }
5847}
5848
5849/* Implement the to_interrupt function for the remote targets. */
5850
5851static void
5852remote_interrupt (struct target_ops *self, ptid_t ptid)
5853{
e42de8c7
PA
5854 struct remote_state *rs = get_remote_state ();
5855
bfedc46a
PA
5856 if (remote_debug)
5857 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5858
e42de8c7
PA
5859 if (target_is_non_stop_p ())
5860 remote_interrupt_ns ();
bfedc46a 5861 else
e42de8c7 5862 remote_interrupt_as ();
c906108c
SS
5863}
5864
93692b58
PA
5865/* Implement the to_pass_ctrlc function for the remote targets. */
5866
5867static void
5868remote_pass_ctrlc (struct target_ops *self)
5869{
5870 struct remote_state *rs = get_remote_state ();
5871
5872 if (remote_debug)
5873 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
5874
5875 /* If we're starting up, we're not fully synced yet. Quit
5876 immediately. */
5877 if (rs->starting_up)
5878 quit ();
5879 /* If ^C has already been sent once, offer to disconnect. */
5880 else if (rs->ctrlc_pending_p)
5881 interrupt_query ();
5882 else
5883 target_interrupt (inferior_ptid);
5884}
5885
c906108c
SS
5886/* Ask the user what to do when an interrupt is received. */
5887
5888static void
fba45db2 5889interrupt_query (void)
c906108c 5890{
abc56d60 5891 struct remote_state *rs = get_remote_state ();
c906108c 5892
abc56d60 5893 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 5894 {
abc56d60
PA
5895 if (query (_("The target is not responding to interrupt requests.\n"
5896 "Stop debugging it? ")))
74531fed 5897 {
78a095c3 5898 remote_unpush_target ();
abc56d60 5899 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
5900 }
5901 }
abc56d60
PA
5902 else
5903 {
5904 if (query (_("Interrupted while waiting for the program.\n"
5905 "Give up waiting? ")))
5906 quit ();
5907 }
c906108c
SS
5908}
5909
6426a772
JM
5910/* Enable/disable target terminal ownership. Most targets can use
5911 terminal groups to control terminal ownership. Remote targets are
5912 different in that explicit transfer of ownership to/from GDB/target
23860348 5913 is required. */
6426a772
JM
5914
5915static void
d2f640d4 5916remote_terminal_inferior (struct target_ops *self)
6426a772 5917{
d9d2d8b6
PA
5918 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5919 idempotent. The event-loop GDB talking to an asynchronous target
5920 with a synchronous command calls this function from both
5921 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5922 transfer the terminal to the target when it shouldn't this guard
5923 can go away. */
6426a772
JM
5924 if (!remote_async_terminal_ours_p)
5925 return;
6426a772 5926 remote_async_terminal_ours_p = 0;
6426a772
JM
5927 /* NOTE: At this point we could also register our selves as the
5928 recipient of all input. Any characters typed could then be
23860348 5929 passed on down to the target. */
6426a772
JM
5930}
5931
5932static void
e3594fd1 5933remote_terminal_ours (struct target_ops *self)
6426a772 5934{
75c99385 5935 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5936 if (remote_async_terminal_ours_p)
5937 return;
6426a772
JM
5938 remote_async_terminal_ours_p = 1;
5939}
5940
176a6961 5941static void
917317f4 5942remote_console_output (char *msg)
c906108c
SS
5943{
5944 char *p;
5945
c5aa993b 5946 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5947 {
5948 char tb[2];
5949 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5950
c906108c
SS
5951 tb[0] = c;
5952 tb[1] = 0;
43ff13b4 5953 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5954 }
00db5b94
PA
5955 gdb_flush (gdb_stdtarg);
5956}
74531fed
PA
5957
5958typedef struct cached_reg
5959{
5960 int num;
5961 gdb_byte data[MAX_REGISTER_SIZE];
5962} cached_reg_t;
5963
5964DEF_VEC_O(cached_reg_t);
5965
722247f1 5966typedef struct stop_reply
74531fed 5967{
722247f1 5968 struct notif_event base;
74531fed 5969
722247f1 5970 /* The identifier of the thread about this event */
74531fed
PA
5971 ptid_t ptid;
5972
340e3c99 5973 /* The remote state this event is associated with. When the remote
bcc75809
YQ
5974 connection, represented by a remote_state object, is closed,
5975 all the associated stop_reply events should be released. */
5976 struct remote_state *rs;
5977
74531fed
PA
5978 struct target_waitstatus ws;
5979
15148d6a
PA
5980 /* Expedited registers. This makes remote debugging a bit more
5981 efficient for those targets that provide critical registers as
5982 part of their normal status mechanism (as another roundtrip to
5983 fetch them is avoided). */
74531fed
PA
5984 VEC(cached_reg_t) *regcache;
5985
f7e6eed5
PA
5986 enum target_stop_reason stop_reason;
5987
74531fed
PA
5988 CORE_ADDR watch_data_address;
5989
dc146f7c 5990 int core;
722247f1 5991} *stop_reply_p;
a744cf53 5992
722247f1
YQ
5993DECLARE_QUEUE_P (stop_reply_p);
5994DEFINE_QUEUE_P (stop_reply_p);
5995/* The list of already fetched and acknowledged stop events. This
5996 queue is used for notification Stop, and other notifications
5997 don't need queue for their events, because the notification events
5998 of Stop can't be consumed immediately, so that events should be
5999 queued first, and be consumed by remote_wait_{ns,as} one per
6000 time. Other notifications can consume their events immediately,
6001 so queue is not needed for them. */
6002static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
6003
6004static void
6005stop_reply_xfree (struct stop_reply *r)
6006{
f48ff2a7 6007 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
6008}
6009
221e1a37
PA
6010/* Return the length of the stop reply queue. */
6011
6012static int
6013stop_reply_queue_length (void)
6014{
6015 return QUEUE_length (stop_reply_p, stop_reply_queue);
6016}
6017
722247f1
YQ
6018static void
6019remote_notif_stop_parse (struct notif_client *self, char *buf,
6020 struct notif_event *event)
6021{
6022 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6023}
6024
6025static void
6026remote_notif_stop_ack (struct notif_client *self, char *buf,
6027 struct notif_event *event)
6028{
6029 struct stop_reply *stop_reply = (struct stop_reply *) event;
6030
6031 /* acknowledge */
6032 putpkt ((char *) self->ack_command);
6033
6034 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6035 /* We got an unknown stop reply. */
6036 error (_("Unknown stop reply"));
6037
6038 push_stop_reply (stop_reply);
6039}
6040
6041static int
6042remote_notif_stop_can_get_pending_events (struct notif_client *self)
6043{
6044 /* We can't get pending events in remote_notif_process for
6045 notification stop, and we have to do this in remote_wait_ns
6046 instead. If we fetch all queued events from stub, remote stub
6047 may exit and we have no chance to process them back in
6048 remote_wait_ns. */
6049 mark_async_event_handler (remote_async_inferior_event_token);
6050 return 0;
6051}
6052
6053static void
6054stop_reply_dtr (struct notif_event *event)
6055{
6056 struct stop_reply *r = (struct stop_reply *) event;
6057
6058 VEC_free (cached_reg_t, r->regcache);
6059}
6060
6061static struct notif_event *
6062remote_notif_stop_alloc_reply (void)
6063{
8d749320
SM
6064 /* We cast to a pointer to the "base class". */
6065 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
6066
6067 r->dtr = stop_reply_dtr;
6068
6069 return r;
6070}
6071
6072/* A client of notification Stop. */
6073
6074struct notif_client notif_client_stop =
6075{
6076 "Stop",
6077 "vStopped",
6078 remote_notif_stop_parse,
6079 remote_notif_stop_ack,
6080 remote_notif_stop_can_get_pending_events,
6081 remote_notif_stop_alloc_reply,
f48ff2a7 6082 REMOTE_NOTIF_STOP,
722247f1
YQ
6083};
6084
6085/* A parameter to pass data in and out. */
6086
6087struct queue_iter_param
6088{
6089 void *input;
6090 struct stop_reply *output;
6091};
6092
cbb8991c
DB
6093/* Determine if THREAD is a pending fork parent thread. ARG contains
6094 the pid of the process that owns the threads we want to check, or
6095 -1 if we want to check all threads. */
6096
6097static int
6098is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6099 ptid_t thread_ptid)
6100{
6101 if (ws->kind == TARGET_WAITKIND_FORKED
6102 || ws->kind == TARGET_WAITKIND_VFORKED)
6103 {
6104 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6105 return 1;
6106 }
6107
6108 return 0;
6109}
6110
6111/* Check whether EVENT is a fork event, and if it is, remove the
6112 fork child from the context list passed in DATA. */
6113
6114static int
6115remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6116 QUEUE_ITER (stop_reply_p) *iter,
6117 stop_reply_p event,
6118 void *data)
6119{
19ba03f4
SM
6120 struct queue_iter_param *param = (struct queue_iter_param *) data;
6121 struct threads_listing_context *context
6122 = (struct threads_listing_context *) param->input;
cbb8991c
DB
6123
6124 if (event->ws.kind == TARGET_WAITKIND_FORKED
65706a29
PA
6125 || event->ws.kind == TARGET_WAITKIND_VFORKED
6126 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6127 threads_listing_context_remove (&event->ws, context);
cbb8991c
DB
6128
6129 return 1;
6130}
6131
6132/* If CONTEXT contains any fork child threads that have not been
6133 reported yet, remove them from the CONTEXT list. If such a
6134 thread exists it is because we are stopped at a fork catchpoint
6135 and have not yet called follow_fork, which will set up the
6136 host-side data structures for the new process. */
6137
6138static void
6139remove_new_fork_children (struct threads_listing_context *context)
6140{
6141 struct thread_info * thread;
6142 int pid = -1;
6143 struct notif_client *notif = &notif_client_stop;
6144 struct queue_iter_param param;
6145
6146 /* For any threads stopped at a fork event, remove the corresponding
6147 fork child threads from the CONTEXT list. */
6148 ALL_NON_EXITED_THREADS (thread)
6149 {
4041ed77
DB
6150 struct target_waitstatus *ws;
6151
6152 if (thread->suspend.waitstatus_pending_p)
6153 ws = &thread->suspend.waitstatus;
6154 else
6155 ws = &thread->pending_follow;
cbb8991c
DB
6156
6157 if (is_pending_fork_parent (ws, pid, thread->ptid))
6158 {
6159 threads_listing_context_remove (ws, context);
6160 }
6161 }
6162
6163 /* Check for any pending fork events (not reported or processed yet)
6164 in process PID and remove those fork child threads from the
6165 CONTEXT list as well. */
6166 remote_notif_get_pending_events (notif);
6167 param.input = context;
6168 param.output = NULL;
6169 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6170 remove_child_of_pending_fork, &param);
6171}
6172
f48ff2a7
YQ
6173/* Remove stop replies in the queue if its pid is equal to the given
6174 inferior's pid. */
722247f1
YQ
6175
6176static int
f48ff2a7
YQ
6177remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6178 QUEUE_ITER (stop_reply_p) *iter,
6179 stop_reply_p event,
6180 void *data)
722247f1 6181{
19ba03f4
SM
6182 struct queue_iter_param *param = (struct queue_iter_param *) data;
6183 struct inferior *inf = (struct inferior *) param->input;
722247f1 6184
f48ff2a7 6185 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
6186 {
6187 stop_reply_xfree (event);
6188 QUEUE_remove_elem (stop_reply_p, q, iter);
6189 }
6190
6191 return 1;
6192}
6193
f48ff2a7 6194/* Discard all pending stop replies of inferior INF. */
c906108c 6195
74531fed 6196static void
5f4cf0bb 6197discard_pending_stop_replies (struct inferior *inf)
c906108c 6198{
722247f1 6199 struct queue_iter_param param;
f48ff2a7
YQ
6200 struct stop_reply *reply;
6201 struct remote_state *rs = get_remote_state ();
6202 struct remote_notif_state *rns = rs->notif_state;
6203
6204 /* This function can be notified when an inferior exists. When the
6205 target is not remote, the notification state is NULL. */
6206 if (rs->remote_desc == NULL)
6207 return;
6208
6209 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 6210
74531fed 6211 /* Discard the in-flight notification. */
f48ff2a7 6212 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 6213 {
722247f1 6214 stop_reply_xfree (reply);
f48ff2a7 6215 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 6216 }
c906108c 6217
722247f1
YQ
6218 param.input = inf;
6219 param.output = NULL;
74531fed
PA
6220 /* Discard the stop replies we have already pulled with
6221 vStopped. */
722247f1 6222 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
6223 remove_stop_reply_for_inferior, &param);
6224}
6225
bcc75809
YQ
6226/* If its remote state is equal to the given remote state,
6227 remove EVENT from the stop reply queue. */
6228
6229static int
6230remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6231 QUEUE_ITER (stop_reply_p) *iter,
6232 stop_reply_p event,
6233 void *data)
6234{
19ba03f4
SM
6235 struct queue_iter_param *param = (struct queue_iter_param *) data;
6236 struct remote_state *rs = (struct remote_state *) param->input;
bcc75809
YQ
6237
6238 if (event->rs == rs)
6239 {
6240 stop_reply_xfree (event);
6241 QUEUE_remove_elem (stop_reply_p, q, iter);
6242 }
6243
6244 return 1;
6245}
6246
6247/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
6248
6249static void
bcc75809 6250discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
6251{
6252 struct queue_iter_param param;
6253
bcc75809 6254 param.input = rs;
f48ff2a7
YQ
6255 param.output = NULL;
6256 /* Discard the stop replies we have already pulled with
6257 vStopped. */
6258 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 6259 remove_stop_reply_of_remote_state, &param);
722247f1 6260}
74531fed 6261
722247f1
YQ
6262/* A parameter to pass data in and out. */
6263
6264static int
6265remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6266 QUEUE_ITER (stop_reply_p) *iter,
6267 stop_reply_p event,
6268 void *data)
6269{
19ba03f4
SM
6270 struct queue_iter_param *param = (struct queue_iter_param *) data;
6271 ptid_t *ptid = (ptid_t *) param->input;
722247f1
YQ
6272
6273 if (ptid_match (event->ptid, *ptid))
6274 {
6275 param->output = event;
6276 QUEUE_remove_elem (stop_reply_p, q, iter);
6277 return 0;
c8e38a49 6278 }
722247f1
YQ
6279
6280 return 1;
74531fed 6281}
43ff13b4 6282
722247f1
YQ
6283/* Remove the first reply in 'stop_reply_queue' which matches
6284 PTID. */
2e9f7625 6285
722247f1
YQ
6286static struct stop_reply *
6287remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 6288{
722247f1
YQ
6289 struct queue_iter_param param;
6290
6291 param.input = &ptid;
6292 param.output = NULL;
6293
6294 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6295 remote_notif_remove_once_on_match, &param);
6296 if (notif_debug)
6297 fprintf_unfiltered (gdb_stdlog,
6298 "notif: discard queued event: 'Stop' in %s\n",
6299 target_pid_to_str (ptid));
a744cf53 6300
722247f1 6301 return param.output;
74531fed 6302}
75c99385 6303
74531fed
PA
6304/* Look for a queued stop reply belonging to PTID. If one is found,
6305 remove it from the queue, and return it. Returns NULL if none is
6306 found. If there are still queued events left to process, tell the
6307 event loop to get back to target_wait soon. */
e24a49d8 6308
74531fed
PA
6309static struct stop_reply *
6310queued_stop_reply (ptid_t ptid)
6311{
722247f1 6312 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 6313
722247f1 6314 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
6315 /* There's still at least an event left. */
6316 mark_async_event_handler (remote_async_inferior_event_token);
6317
722247f1 6318 return r;
74531fed
PA
6319}
6320
6321/* Push a fully parsed stop reply in the stop reply queue. Since we
6322 know that we now have at least one queued event left to pass to the
6323 core side, tell the event loop to get back to target_wait soon. */
6324
6325static void
6326push_stop_reply (struct stop_reply *new_event)
6327{
722247f1 6328 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 6329
722247f1
YQ
6330 if (notif_debug)
6331 fprintf_unfiltered (gdb_stdlog,
6332 "notif: push 'Stop' %s to queue %d\n",
6333 target_pid_to_str (new_event->ptid),
6334 QUEUE_length (stop_reply_p,
6335 stop_reply_queue));
74531fed
PA
6336
6337 mark_async_event_handler (remote_async_inferior_event_token);
6338}
6339
722247f1
YQ
6340static int
6341stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6342 QUEUE_ITER (stop_reply_p) *iter,
6343 struct stop_reply *event,
6344 void *data)
6345{
19ba03f4 6346 ptid_t *ptid = (ptid_t *) data;
722247f1
YQ
6347
6348 return !(ptid_equal (*ptid, event->ptid)
6349 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6350}
6351
74531fed
PA
6352/* Returns true if we have a stop reply for PTID. */
6353
6354static int
6355peek_stop_reply (ptid_t ptid)
6356{
722247f1
YQ
6357 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6358 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
6359}
6360
26d56a93
SL
6361/* Helper for remote_parse_stop_reply. Return nonzero if the substring
6362 starting with P and ending with PEND matches PREFIX. */
6363
6364static int
6365strprefix (const char *p, const char *pend, const char *prefix)
6366{
6367 for ( ; p < pend; p++, prefix++)
6368 if (*p != *prefix)
6369 return 0;
6370 return *prefix == '\0';
6371}
6372
74531fed
PA
6373/* Parse the stop reply in BUF. Either the function succeeds, and the
6374 result is stored in EVENT, or throws an error. */
6375
6376static void
6377remote_parse_stop_reply (char *buf, struct stop_reply *event)
6378{
6379 struct remote_arch_state *rsa = get_remote_arch_state ();
6380 ULONGEST addr;
6381 char *p;
94585166 6382 int skipregs = 0;
74531fed
PA
6383
6384 event->ptid = null_ptid;
bcc75809 6385 event->rs = get_remote_state ();
74531fed
PA
6386 event->ws.kind = TARGET_WAITKIND_IGNORE;
6387 event->ws.value.integer = 0;
f7e6eed5 6388 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 6389 event->regcache = NULL;
dc146f7c 6390 event->core = -1;
74531fed
PA
6391
6392 switch (buf[0])
6393 {
6394 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
6395 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6396 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6397 ss = signal number
6398 n... = register number
6399 r... = register contents
6400 */
6401
6402 p = &buf[3]; /* after Txx */
6403 while (*p)
6404 {
6405 char *p1;
cea39f65 6406 int fieldsize;
43ff13b4 6407
1f10ba14
PA
6408 p1 = strchr (p, ':');
6409 if (p1 == NULL)
6410 error (_("Malformed packet(a) (missing colon): %s\n\
6411Packet: '%s'\n"),
6412 p, buf);
6413 if (p == p1)
6414 error (_("Malformed packet(a) (missing register number): %s\n\
6415Packet: '%s'\n"),
6416 p, buf);
3c3bea1c 6417
1f10ba14
PA
6418 /* Some "registers" are actually extended stop information.
6419 Note if you're adding a new entry here: GDB 7.9 and
6420 earlier assume that all register "numbers" that start
6421 with an hex digit are real register numbers. Make sure
6422 the server only sends such a packet if it knows the
6423 client understands it. */
c8e38a49 6424
26d56a93 6425 if (strprefix (p, p1, "thread"))
1f10ba14 6426 event->ptid = read_ptid (++p1, &p);
82075af2
JS
6427 else if (strprefix (p, p1, "syscall_entry"))
6428 {
6429 ULONGEST sysno;
6430
6431 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6432 p = unpack_varlen_hex (++p1, &sysno);
6433 event->ws.value.syscall_number = (int) sysno;
6434 }
6435 else if (strprefix (p, p1, "syscall_return"))
6436 {
6437 ULONGEST sysno;
6438
6439 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6440 p = unpack_varlen_hex (++p1, &sysno);
6441 event->ws.value.syscall_number = (int) sysno;
6442 }
26d56a93
SL
6443 else if (strprefix (p, p1, "watch")
6444 || strprefix (p, p1, "rwatch")
6445 || strprefix (p, p1, "awatch"))
cea39f65 6446 {
f7e6eed5 6447 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
6448 p = unpack_varlen_hex (++p1, &addr);
6449 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 6450 }
26d56a93 6451 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
6452 {
6453 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6454
6455 /* Make sure the stub doesn't forget to indicate support
6456 with qSupported. */
6457 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6458 error (_("Unexpected swbreak stop reason"));
6459
6460 /* The value part is documented as "must be empty",
6461 though we ignore it, in case we ever decide to make
6462 use of it in a backward compatible way. */
8424cc97 6463 p = strchrnul (p1 + 1, ';');
f7e6eed5 6464 }
26d56a93 6465 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
6466 {
6467 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6468
6469 /* Make sure the stub doesn't forget to indicate support
6470 with qSupported. */
6471 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6472 error (_("Unexpected hwbreak stop reason"));
6473
6474 /* See above. */
8424cc97 6475 p = strchrnul (p1 + 1, ';');
f7e6eed5 6476 }
26d56a93 6477 else if (strprefix (p, p1, "library"))
cea39f65 6478 {
1f10ba14 6479 event->ws.kind = TARGET_WAITKIND_LOADED;
8424cc97 6480 p = strchrnul (p1 + 1, ';');
1f10ba14 6481 }
26d56a93 6482 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
6483 {
6484 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6485 /* p1 will indicate "begin" or "end", but it makes
6486 no difference for now, so ignore it. */
8424cc97 6487 p = strchrnul (p1 + 1, ';');
1f10ba14 6488 }
26d56a93 6489 else if (strprefix (p, p1, "core"))
1f10ba14
PA
6490 {
6491 ULONGEST c;
a744cf53 6492
1f10ba14
PA
6493 p = unpack_varlen_hex (++p1, &c);
6494 event->core = c;
cea39f65 6495 }
26d56a93 6496 else if (strprefix (p, p1, "fork"))
de0d863e
DB
6497 {
6498 event->ws.value.related_pid = read_ptid (++p1, &p);
6499 event->ws.kind = TARGET_WAITKIND_FORKED;
6500 }
26d56a93 6501 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
6502 {
6503 event->ws.value.related_pid = read_ptid (++p1, &p);
6504 event->ws.kind = TARGET_WAITKIND_VFORKED;
6505 }
26d56a93 6506 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
6507 {
6508 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
8424cc97 6509 p = strchrnul (p1 + 1, ';');
c269dbdb 6510 }
6ab24463 6511 else if (strprefix (p, p1, "exec"))
94585166
DB
6512 {
6513 ULONGEST ignored;
6514 char pathname[PATH_MAX];
6515 int pathlen;
6516
6517 /* Determine the length of the execd pathname. */
6518 p = unpack_varlen_hex (++p1, &ignored);
6519 pathlen = (p - p1) / 2;
6520
6521 /* Save the pathname for event reporting and for
6522 the next run command. */
6523 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6524 pathname[pathlen] = '\0';
6525
6526 /* This is freed during event handling. */
6527 event->ws.value.execd_pathname = xstrdup (pathname);
6528 event->ws.kind = TARGET_WAITKIND_EXECD;
6529
6530 /* Skip the registers included in this packet, since
6531 they may be for an architecture different from the
6532 one used by the original program. */
6533 skipregs = 1;
6534 }
65706a29
PA
6535 else if (strprefix (p, p1, "create"))
6536 {
6537 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
8424cc97 6538 p = strchrnul (p1 + 1, ';');
65706a29 6539 }
cea39f65
MS
6540 else
6541 {
1f10ba14
PA
6542 ULONGEST pnum;
6543 char *p_temp;
6544
94585166
DB
6545 if (skipregs)
6546 {
8424cc97 6547 p = strchrnul (p1 + 1, ';');
94585166
DB
6548 p++;
6549 continue;
6550 }
6551
1f10ba14
PA
6552 /* Maybe a real ``P'' register number. */
6553 p_temp = unpack_varlen_hex (p, &pnum);
6554 /* If the first invalid character is the colon, we got a
6555 register number. Otherwise, it's an unknown stop
6556 reason. */
6557 if (p_temp == p1)
6558 {
6559 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6560 cached_reg_t cached_reg;
43ff13b4 6561
1f10ba14
PA
6562 if (reg == NULL)
6563 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 6564Packet: '%s'\n"),
1f10ba14 6565 hex_string (pnum), p, buf);
c8e38a49 6566
1f10ba14 6567 cached_reg.num = reg->regnum;
4100683b 6568
1f10ba14
PA
6569 p = p1 + 1;
6570 fieldsize = hex2bin (p, cached_reg.data,
6571 register_size (target_gdbarch (),
6572 reg->regnum));
6573 p += 2 * fieldsize;
6574 if (fieldsize < register_size (target_gdbarch (),
6575 reg->regnum))
6576 warning (_("Remote reply is too short: %s"), buf);
74531fed 6577
1f10ba14
PA
6578 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6579 }
6580 else
6581 {
6582 /* Not a number. Silently skip unknown optional
6583 info. */
8424cc97 6584 p = strchrnul (p1 + 1, ';');
1f10ba14 6585 }
cea39f65 6586 }
c8e38a49 6587
cea39f65
MS
6588 if (*p != ';')
6589 error (_("Remote register badly formatted: %s\nhere: %s"),
6590 buf, p);
6591 ++p;
6592 }
5b5596ff
PA
6593
6594 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6595 break;
6596
c8e38a49
PA
6597 /* fall through */
6598 case 'S': /* Old style status, just signal only. */
3a09da41
PA
6599 {
6600 int sig;
6601
6602 event->ws.kind = TARGET_WAITKIND_STOPPED;
6603 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6604 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6605 event->ws.value.sig = (enum gdb_signal) sig;
6606 else
6607 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6608 }
c8e38a49 6609 break;
65706a29
PA
6610 case 'w': /* Thread exited. */
6611 {
6612 char *p;
6613 ULONGEST value;
6614
6615 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
6616 p = unpack_varlen_hex (&buf[1], &value);
6617 event->ws.value.integer = value;
6618 if (*p != ';')
6619 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 6620 event->ptid = read_ptid (++p, NULL);
65706a29
PA
6621 break;
6622 }
c8e38a49
PA
6623 case 'W': /* Target exited. */
6624 case 'X':
6625 {
6626 char *p;
6627 int pid;
6628 ULONGEST value;
82f73884 6629
c8e38a49
PA
6630 /* GDB used to accept only 2 hex chars here. Stubs should
6631 only send more if they detect GDB supports multi-process
6632 support. */
6633 p = unpack_varlen_hex (&buf[1], &value);
82f73884 6634
c8e38a49
PA
6635 if (buf[0] == 'W')
6636 {
6637 /* The remote process exited. */
74531fed
PA
6638 event->ws.kind = TARGET_WAITKIND_EXITED;
6639 event->ws.value.integer = value;
c8e38a49
PA
6640 }
6641 else
6642 {
6643 /* The remote process exited with a signal. */
74531fed 6644 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
6645 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6646 event->ws.value.sig = (enum gdb_signal) value;
6647 else
6648 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 6649 }
82f73884 6650
c8e38a49
PA
6651 /* If no process is specified, assume inferior_ptid. */
6652 pid = ptid_get_pid (inferior_ptid);
6653 if (*p == '\0')
6654 ;
6655 else if (*p == ';')
6656 {
6657 p++;
6658
0b24eb2d 6659 if (*p == '\0')
82f73884 6660 ;
61012eef 6661 else if (startswith (p, "process:"))
82f73884 6662 {
c8e38a49 6663 ULONGEST upid;
a744cf53 6664
c8e38a49
PA
6665 p += sizeof ("process:") - 1;
6666 unpack_varlen_hex (p, &upid);
6667 pid = upid;
82f73884
PA
6668 }
6669 else
6670 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 6671 }
c8e38a49
PA
6672 else
6673 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
6674 event->ptid = pid_to_ptid (pid);
6675 }
6676 break;
f2faf941
PA
6677 case 'N':
6678 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
6679 event->ptid = minus_one_ptid;
6680 break;
74531fed
PA
6681 }
6682
6efcd9a8 6683 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
74531fed
PA
6684 error (_("No process or thread specified in stop reply: %s"), buf);
6685}
6686
722247f1
YQ
6687/* When the stub wants to tell GDB about a new notification reply, it
6688 sends a notification (%Stop, for example). Those can come it at
6689 any time, hence, we have to make sure that any pending
6690 putpkt/getpkt sequence we're making is finished, before querying
6691 the stub for more events with the corresponding ack command
6692 (vStopped, for example). E.g., if we started a vStopped sequence
6693 immediately upon receiving the notification, something like this
6694 could happen:
74531fed
PA
6695
6696 1.1) --> Hg 1
6697 1.2) <-- OK
6698 1.3) --> g
6699 1.4) <-- %Stop
6700 1.5) --> vStopped
6701 1.6) <-- (registers reply to step #1.3)
6702
6703 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6704 query.
6705
796cb314 6706 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
6707 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6708 doing whatever we were doing:
6709
6710 2.1) --> Hg 1
6711 2.2) <-- OK
6712 2.3) --> g
6713 2.4) <-- %Stop
6714 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6715 2.5) <-- (registers reply to step #2.3)
6716
6717 Eventualy after step #2.5, we return to the event loop, which
6718 notices there's an event on the
6719 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6720 associated callback --- the function below. At this point, we're
6721 always safe to start a vStopped sequence. :
6722
6723 2.6) --> vStopped
6724 2.7) <-- T05 thread:2
6725 2.8) --> vStopped
6726 2.9) --> OK
6727*/
6728
722247f1
YQ
6729void
6730remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
6731{
6732 struct remote_state *rs = get_remote_state ();
74531fed 6733
f48ff2a7 6734 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 6735 {
722247f1
YQ
6736 if (notif_debug)
6737 fprintf_unfiltered (gdb_stdlog,
6738 "notif: process: '%s' ack pending event\n",
6739 nc->name);
74531fed 6740
722247f1 6741 /* acknowledge */
f48ff2a7
YQ
6742 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6743 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
6744
6745 while (1)
6746 {
6747 getpkt (&rs->buf, &rs->buf_size, 0);
6748 if (strcmp (rs->buf, "OK") == 0)
6749 break;
6750 else
722247f1 6751 remote_notif_ack (nc, rs->buf);
74531fed
PA
6752 }
6753 }
722247f1
YQ
6754 else
6755 {
6756 if (notif_debug)
6757 fprintf_unfiltered (gdb_stdlog,
6758 "notif: process: '%s' no pending reply\n",
6759 nc->name);
6760 }
74531fed
PA
6761}
6762
74531fed
PA
6763/* Called when it is decided that STOP_REPLY holds the info of the
6764 event that is to be returned to the core. This function always
6765 destroys STOP_REPLY. */
6766
6767static ptid_t
6768process_stop_reply (struct stop_reply *stop_reply,
6769 struct target_waitstatus *status)
6770{
6771 ptid_t ptid;
6772
6773 *status = stop_reply->ws;
6774 ptid = stop_reply->ptid;
6775
6776 /* If no thread/process was reported by the stub, assume the current
6777 inferior. */
6778 if (ptid_equal (ptid, null_ptid))
6779 ptid = inferior_ptid;
6780
5f3563ea 6781 if (status->kind != TARGET_WAITKIND_EXITED
f2faf941
PA
6782 && status->kind != TARGET_WAITKIND_SIGNALLED
6783 && status->kind != TARGET_WAITKIND_NO_RESUMED)
74531fed 6784 {
799a2abe 6785 struct private_thread_info *remote_thr;
ee154bee 6786
5f3563ea
PA
6787 /* Expedited registers. */
6788 if (stop_reply->regcache)
6789 {
217f1f79 6790 struct regcache *regcache
f5656ead 6791 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
6792 cached_reg_t *reg;
6793 int ix;
6794
6795 for (ix = 0;
6796 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6797 ix++)
217f1f79 6798 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
6799 VEC_free (cached_reg_t, stop_reply->regcache);
6800 }
74531fed 6801
1941c569 6802 remote_notice_new_inferior (ptid, 0);
799a2abe
PA
6803 remote_thr = demand_private_info (ptid);
6804 remote_thr->core = stop_reply->core;
6805 remote_thr->stop_reason = stop_reply->stop_reason;
6806 remote_thr->watch_data_address = stop_reply->watch_data_address;
74531fed
PA
6807 }
6808
74531fed
PA
6809 stop_reply_xfree (stop_reply);
6810 return ptid;
6811}
6812
6813/* The non-stop mode version of target_wait. */
6814
6815static ptid_t
47608cb1 6816remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6817{
6818 struct remote_state *rs = get_remote_state ();
74531fed
PA
6819 struct stop_reply *stop_reply;
6820 int ret;
fee9eda9 6821 int is_notif = 0;
74531fed
PA
6822
6823 /* If in non-stop mode, get out of getpkt even if a
6824 notification is received. */
6825
6826 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6827 0 /* forever */, &is_notif);
74531fed
PA
6828 while (1)
6829 {
fee9eda9 6830 if (ret != -1 && !is_notif)
74531fed
PA
6831 switch (rs->buf[0])
6832 {
6833 case 'E': /* Error of some sort. */
6834 /* We're out of sync with the target now. Did it continue
6835 or not? We can't tell which thread it was in non-stop,
6836 so just ignore this. */
6837 warning (_("Remote failure reply: %s"), rs->buf);
6838 break;
6839 case 'O': /* Console output. */
6840 remote_console_output (rs->buf + 1);
6841 break;
6842 default:
6843 warning (_("Invalid remote reply: %s"), rs->buf);
6844 break;
6845 }
6846
6847 /* Acknowledge a pending stop reply that may have arrived in the
6848 mean time. */
f48ff2a7 6849 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 6850 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
6851
6852 /* If indeed we noticed a stop reply, we're done. */
6853 stop_reply = queued_stop_reply (ptid);
6854 if (stop_reply != NULL)
6855 return process_stop_reply (stop_reply, status);
6856
47608cb1 6857 /* Still no event. If we're just polling for an event, then
74531fed 6858 return to the event loop. */
47608cb1 6859 if (options & TARGET_WNOHANG)
74531fed
PA
6860 {
6861 status->kind = TARGET_WAITKIND_IGNORE;
6862 return minus_one_ptid;
6863 }
6864
47608cb1 6865 /* Otherwise do a blocking wait. */
74531fed 6866 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6867 1 /* forever */, &is_notif);
74531fed
PA
6868 }
6869}
6870
6871/* Wait until the remote machine stops, then return, storing status in
6872 STATUS just as `wait' would. */
6873
6874static ptid_t
47608cb1 6875remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6876{
6877 struct remote_state *rs = get_remote_state ();
74531fed 6878 ptid_t event_ptid = null_ptid;
cea39f65 6879 char *buf;
74531fed
PA
6880 struct stop_reply *stop_reply;
6881
47608cb1
PA
6882 again:
6883
74531fed
PA
6884 status->kind = TARGET_WAITKIND_IGNORE;
6885 status->value.integer = 0;
6886
6887 stop_reply = queued_stop_reply (ptid);
6888 if (stop_reply != NULL)
6889 return process_stop_reply (stop_reply, status);
6890
6891 if (rs->cached_wait_status)
6892 /* Use the cached wait status, but only once. */
6893 rs->cached_wait_status = 0;
6894 else
6895 {
6896 int ret;
722247f1 6897 int is_notif;
567420d1
PA
6898 int forever = ((options & TARGET_WNOHANG) == 0
6899 && wait_forever_enabled_p);
6900
6901 if (!rs->waiting_for_stop_reply)
6902 {
6903 status->kind = TARGET_WAITKIND_NO_RESUMED;
6904 return minus_one_ptid;
6905 }
74531fed 6906
74531fed
PA
6907 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6908 _never_ wait for ever -> test on target_is_async_p().
6909 However, before we do that we need to ensure that the caller
6910 knows how to take the target into/out of async mode. */
722247f1 6911 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 6912 forever, &is_notif);
722247f1
YQ
6913
6914 /* GDB gets a notification. Return to core as this event is
6915 not interesting. */
6916 if (ret != -1 && is_notif)
6917 return minus_one_ptid;
567420d1
PA
6918
6919 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6920 return minus_one_ptid;
74531fed
PA
6921 }
6922
6923 buf = rs->buf;
6924
3a29589a
DJ
6925 /* Assume that the target has acknowledged Ctrl-C unless we receive
6926 an 'F' or 'O' packet. */
6927 if (buf[0] != 'F' && buf[0] != 'O')
6928 rs->ctrlc_pending_p = 0;
6929
74531fed
PA
6930 switch (buf[0])
6931 {
6932 case 'E': /* Error of some sort. */
6933 /* We're out of sync with the target now. Did it continue or
6934 not? Not is more likely, so report a stop. */
29090fb6
LM
6935 rs->waiting_for_stop_reply = 0;
6936
74531fed
PA
6937 warning (_("Remote failure reply: %s"), buf);
6938 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 6939 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
6940 break;
6941 case 'F': /* File-I/O request. */
e42e5352
YQ
6942 /* GDB may access the inferior memory while handling the File-I/O
6943 request, but we don't want GDB accessing memory while waiting
6944 for a stop reply. See the comments in putpkt_binary. Set
6945 waiting_for_stop_reply to 0 temporarily. */
6946 rs->waiting_for_stop_reply = 0;
3a29589a
DJ
6947 remote_fileio_request (buf, rs->ctrlc_pending_p);
6948 rs->ctrlc_pending_p = 0;
e42e5352
YQ
6949 /* GDB handled the File-I/O request, and the target is running
6950 again. Keep waiting for events. */
6951 rs->waiting_for_stop_reply = 1;
74531fed 6952 break;
f2faf941 6953 case 'N': case 'T': case 'S': case 'X': case 'W':
74531fed 6954 {
29090fb6
LM
6955 struct stop_reply *stop_reply;
6956
6957 /* There is a stop reply to handle. */
6958 rs->waiting_for_stop_reply = 0;
6959
6960 stop_reply
722247f1
YQ
6961 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6962 rs->buf);
74531fed 6963
74531fed 6964 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
6965 break;
6966 }
6967 case 'O': /* Console output. */
6968 remote_console_output (buf + 1);
c8e38a49
PA
6969 break;
6970 case '\0':
b73be471 6971 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
6972 {
6973 /* Zero length reply means that we tried 'S' or 'C' and the
6974 remote system doesn't support it. */
6975 target_terminal_ours_for_output ();
6976 printf_filtered
6977 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
6978 gdb_signal_to_name (rs->last_sent_signal));
6979 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
6980 target_terminal_inferior ();
6981
280ceea3 6982 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49 6983 putpkt ((char *) buf);
c8e38a49 6984 break;
43ff13b4 6985 }
c8e38a49
PA
6986 /* else fallthrough */
6987 default:
6988 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 6989 break;
43ff13b4 6990 }
c8e38a49 6991
f2faf941
PA
6992 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
6993 return minus_one_ptid;
6994 else if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
6995 {
6996 /* Nothing interesting happened. If we're doing a non-blocking
6997 poll, we're done. Otherwise, go back to waiting. */
6998 if (options & TARGET_WNOHANG)
6999 return minus_one_ptid;
7000 else
7001 goto again;
7002 }
74531fed
PA
7003 else if (status->kind != TARGET_WAITKIND_EXITED
7004 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
7005 {
7006 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 7007 record_currthread (rs, event_ptid);
82f73884
PA
7008 else
7009 event_ptid = inferior_ptid;
43ff13b4 7010 }
74531fed
PA
7011 else
7012 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 7013 record_currthread (rs, minus_one_ptid);
79d7f229 7014
82f73884 7015 return event_ptid;
43ff13b4
JM
7016}
7017
74531fed
PA
7018/* Wait until the remote machine stops, then return, storing status in
7019 STATUS just as `wait' would. */
7020
c8e38a49 7021static ptid_t
117de6a9 7022remote_wait (struct target_ops *ops,
47608cb1 7023 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
7024{
7025 ptid_t event_ptid;
7026
6efcd9a8 7027 if (target_is_non_stop_p ())
47608cb1 7028 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 7029 else
47608cb1 7030 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 7031
d9d41e78 7032 if (target_is_async_p ())
c8e38a49 7033 {
74531fed
PA
7034 /* If there are are events left in the queue tell the event loop
7035 to return here. */
722247f1 7036 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 7037 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 7038 }
c8e38a49
PA
7039
7040 return event_ptid;
7041}
7042
74ca34ce 7043/* Fetch a single register using a 'p' packet. */
c906108c 7044
b96ec7ac 7045static int
56be3814 7046fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
7047{
7048 struct remote_state *rs = get_remote_state ();
2e9f7625 7049 char *buf, *p;
b96ec7ac
AC
7050 char regp[MAX_REGISTER_SIZE];
7051 int i;
7052
4082afcc 7053 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
7054 return 0;
7055
7056 if (reg->pnum == -1)
7057 return 0;
7058
2e9f7625 7059 p = rs->buf;
fcad0fa4 7060 *p++ = 'p';
74ca34ce 7061 p += hexnumstr (p, reg->pnum);
fcad0fa4 7062 *p++ = '\0';
1f4437a4
MS
7063 putpkt (rs->buf);
7064 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 7065
2e9f7625
DJ
7066 buf = rs->buf;
7067
74ca34ce
DJ
7068 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7069 {
7070 case PACKET_OK:
7071 break;
7072 case PACKET_UNKNOWN:
7073 return 0;
7074 case PACKET_ERROR:
27a9c0bf
MS
7075 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7076 gdbarch_register_name (get_regcache_arch (regcache),
7077 reg->regnum),
7078 buf);
74ca34ce 7079 }
3f9a994c
JB
7080
7081 /* If this register is unfetchable, tell the regcache. */
7082 if (buf[0] == 'x')
8480adf2 7083 {
56be3814 7084 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 7085 return 1;
b96ec7ac 7086 }
b96ec7ac 7087
3f9a994c
JB
7088 /* Otherwise, parse and supply the value. */
7089 p = buf;
7090 i = 0;
7091 while (p[0] != 0)
7092 {
7093 if (p[1] == 0)
74ca34ce 7094 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
7095
7096 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7097 p += 2;
7098 }
56be3814 7099 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 7100 return 1;
b96ec7ac
AC
7101}
7102
74ca34ce
DJ
7103/* Fetch the registers included in the target's 'g' packet. */
7104
29709017
DJ
7105static int
7106send_g_packet (void)
c906108c 7107{
d01949b6 7108 struct remote_state *rs = get_remote_state ();
cea39f65 7109 int buf_len;
c906108c 7110
bba74b36 7111 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 7112 remote_send (&rs->buf, &rs->buf_size);
c906108c 7113
29709017
DJ
7114 /* We can get out of synch in various cases. If the first character
7115 in the buffer is not a hex character, assume that has happened
7116 and try to fetch another packet to read. */
7117 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7118 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7119 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7120 && rs->buf[0] != 'x') /* New: unavailable register value. */
7121 {
7122 if (remote_debug)
7123 fprintf_unfiltered (gdb_stdlog,
7124 "Bad register packet; fetching a new packet\n");
7125 getpkt (&rs->buf, &rs->buf_size, 0);
7126 }
7127
74ca34ce
DJ
7128 buf_len = strlen (rs->buf);
7129
7130 /* Sanity check the received packet. */
7131 if (buf_len % 2 != 0)
7132 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
7133
7134 return buf_len / 2;
7135}
7136
7137static void
56be3814 7138process_g_packet (struct regcache *regcache)
29709017 7139{
4a22f64d 7140 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
7141 struct remote_state *rs = get_remote_state ();
7142 struct remote_arch_state *rsa = get_remote_arch_state ();
7143 int i, buf_len;
7144 char *p;
7145 char *regs;
7146
7147 buf_len = strlen (rs->buf);
7148
7149 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
7150 if (buf_len > 2 * rsa->sizeof_g_packet)
7151 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7152
7153 /* Save the size of the packet sent to us by the target. It is used
7154 as a heuristic when determining the max size of packets that the
7155 target can safely receive. */
7156 if (rsa->actual_register_packet_size == 0)
7157 rsa->actual_register_packet_size = buf_len;
7158
7159 /* If this is smaller than we guessed the 'g' packet would be,
7160 update our records. A 'g' reply that doesn't include a register's
7161 value implies either that the register is not available, or that
7162 the 'p' packet must be used. */
7163 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 7164 {
74ca34ce
DJ
7165 rsa->sizeof_g_packet = buf_len / 2;
7166
4a22f64d 7167 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 7168 {
74ca34ce
DJ
7169 if (rsa->regs[i].pnum == -1)
7170 continue;
7171
7172 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7173 rsa->regs[i].in_g_packet = 0;
b96ec7ac 7174 else
74ca34ce 7175 rsa->regs[i].in_g_packet = 1;
b96ec7ac 7176 }
74ca34ce 7177 }
b323314b 7178
224c3ddb 7179 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
7180
7181 /* Unimplemented registers read as all bits zero. */
ea9c271d 7182 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 7183
c906108c
SS
7184 /* Reply describes registers byte by byte, each byte encoded as two
7185 hex characters. Suck them all up, then supply them to the
7186 register cacheing/storage mechanism. */
7187
74ca34ce 7188 p = rs->buf;
ea9c271d 7189 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 7190 {
74ca34ce
DJ
7191 if (p[0] == 0 || p[1] == 0)
7192 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7193 internal_error (__FILE__, __LINE__,
9b20d036 7194 _("unexpected end of 'g' packet reply"));
74ca34ce 7195
c906108c 7196 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 7197 regs[i] = 0; /* 'x' */
c906108c
SS
7198 else
7199 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7200 p += 2;
7201 }
7202
a744cf53
MS
7203 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7204 {
7205 struct packet_reg *r = &rsa->regs[i];
7206
7207 if (r->in_g_packet)
7208 {
7209 if (r->offset * 2 >= strlen (rs->buf))
7210 /* This shouldn't happen - we adjusted in_g_packet above. */
7211 internal_error (__FILE__, __LINE__,
9b20d036 7212 _("unexpected end of 'g' packet reply"));
a744cf53
MS
7213 else if (rs->buf[r->offset * 2] == 'x')
7214 {
7215 gdb_assert (r->offset * 2 < strlen (rs->buf));
7216 /* The register isn't available, mark it as such (at
7217 the same time setting the value to zero). */
7218 regcache_raw_supply (regcache, r->regnum, NULL);
7219 }
7220 else
7221 regcache_raw_supply (regcache, r->regnum,
7222 regs + r->offset);
7223 }
7224 }
c906108c
SS
7225}
7226
29709017 7227static void
56be3814 7228fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
7229{
7230 send_g_packet ();
56be3814 7231 process_g_packet (regcache);
29709017
DJ
7232}
7233
e6e4e701
PA
7234/* Make the remote selected traceframe match GDB's selected
7235 traceframe. */
7236
7237static void
7238set_remote_traceframe (void)
7239{
7240 int newnum;
262e1174 7241 struct remote_state *rs = get_remote_state ();
e6e4e701 7242
262e1174 7243 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
7244 return;
7245
7246 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 7247 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
7248
7249 newnum = target_trace_find (tfind_number,
7250 get_traceframe_number (), 0, 0, NULL);
7251
7252 /* Should not happen. If it does, all bets are off. */
7253 if (newnum != get_traceframe_number ())
7254 warning (_("could not set remote traceframe"));
7255}
7256
74ca34ce 7257static void
28439f5e
PA
7258remote_fetch_registers (struct target_ops *ops,
7259 struct regcache *regcache, int regnum)
74ca34ce 7260{
74ca34ce
DJ
7261 struct remote_arch_state *rsa = get_remote_arch_state ();
7262 int i;
7263
e6e4e701 7264 set_remote_traceframe ();
79d7f229 7265 set_general_thread (inferior_ptid);
74ca34ce
DJ
7266
7267 if (regnum >= 0)
7268 {
7269 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7270
74ca34ce
DJ
7271 gdb_assert (reg != NULL);
7272
7273 /* If this register might be in the 'g' packet, try that first -
7274 we are likely to read more than one register. If this is the
7275 first 'g' packet, we might be overly optimistic about its
7276 contents, so fall back to 'p'. */
7277 if (reg->in_g_packet)
7278 {
56be3814 7279 fetch_registers_using_g (regcache);
74ca34ce
DJ
7280 if (reg->in_g_packet)
7281 return;
7282 }
7283
56be3814 7284 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
7285 return;
7286
7287 /* This register is not available. */
56be3814 7288 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
7289
7290 return;
7291 }
7292
56be3814 7293 fetch_registers_using_g (regcache);
74ca34ce 7294
4a22f64d 7295 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7296 if (!rsa->regs[i].in_g_packet)
56be3814 7297 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
7298 {
7299 /* This register is not available. */
56be3814 7300 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
7301 }
7302}
7303
c906108c
SS
7304/* Prepare to store registers. Since we may send them all (using a
7305 'G' request), we have to read out the ones we don't want to change
7306 first. */
7307
c5aa993b 7308static void
f32dbf8c 7309remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 7310{
ea9c271d 7311 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 7312 int i;
cfd77fa1 7313 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 7314
c906108c 7315 /* Make sure the entire registers array is valid. */
4082afcc 7316 switch (packet_support (PACKET_P))
5a2468f5
JM
7317 {
7318 case PACKET_DISABLE:
7319 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 7320 /* Make sure all the necessary registers are cached. */
4a22f64d 7321 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 7322 if (rsa->regs[i].in_g_packet)
316f2060 7323 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
7324 break;
7325 case PACKET_ENABLE:
7326 break;
7327 }
7328}
7329
ad10f812 7330/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 7331 packet was not recognized. */
5a2468f5
JM
7332
7333static int
1f4437a4
MS
7334store_register_using_P (const struct regcache *regcache,
7335 struct packet_reg *reg)
5a2468f5 7336{
4a22f64d 7337 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 7338 struct remote_state *rs = get_remote_state ();
5a2468f5 7339 /* Try storing a single register. */
6d820c5c 7340 char *buf = rs->buf;
cfd77fa1 7341 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 7342 char *p;
5a2468f5 7343
4082afcc 7344 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
7345 return 0;
7346
7347 if (reg->pnum == -1)
7348 return 0;
7349
ea9c271d 7350 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 7351 p = buf + strlen (buf);
56be3814 7352 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 7353 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
7354 putpkt (rs->buf);
7355 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 7356
74ca34ce
DJ
7357 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7358 {
7359 case PACKET_OK:
7360 return 1;
7361 case PACKET_ERROR:
27a9c0bf
MS
7362 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7363 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
7364 case PACKET_UNKNOWN:
7365 return 0;
7366 default:
7367 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7368 }
c906108c
SS
7369}
7370
23860348
MS
7371/* Store register REGNUM, or all registers if REGNUM == -1, from the
7372 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
7373
7374static void
56be3814 7375store_registers_using_G (const struct regcache *regcache)
c906108c 7376{
d01949b6 7377 struct remote_state *rs = get_remote_state ();
ea9c271d 7378 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 7379 gdb_byte *regs;
c906108c
SS
7380 char *p;
7381
193cb69f
AC
7382 /* Extract all the registers in the regcache copying them into a
7383 local buffer. */
7384 {
b323314b 7385 int i;
a744cf53 7386
224c3ddb 7387 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 7388 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 7389 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 7390 {
ea9c271d 7391 struct packet_reg *r = &rsa->regs[i];
a744cf53 7392
b323314b 7393 if (r->in_g_packet)
56be3814 7394 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
7395 }
7396 }
c906108c
SS
7397
7398 /* Command describes registers byte by byte,
7399 each byte encoded as two hex characters. */
6d820c5c 7400 p = rs->buf;
193cb69f 7401 *p++ = 'G';
74ca34ce
DJ
7402 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7403 updated. */
7404 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
7405 putpkt (rs->buf);
7406 getpkt (&rs->buf, &rs->buf_size, 0);
7407 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
7408 error (_("Could not write registers; remote failure reply '%s'"),
7409 rs->buf);
c906108c 7410}
74ca34ce
DJ
7411
7412/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7413 of the register cache buffer. FIXME: ignores errors. */
7414
7415static void
28439f5e
PA
7416remote_store_registers (struct target_ops *ops,
7417 struct regcache *regcache, int regnum)
74ca34ce 7418{
74ca34ce
DJ
7419 struct remote_arch_state *rsa = get_remote_arch_state ();
7420 int i;
7421
e6e4e701 7422 set_remote_traceframe ();
79d7f229 7423 set_general_thread (inferior_ptid);
74ca34ce
DJ
7424
7425 if (regnum >= 0)
7426 {
7427 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7428
74ca34ce
DJ
7429 gdb_assert (reg != NULL);
7430
7431 /* Always prefer to store registers using the 'P' packet if
7432 possible; we often change only a small number of registers.
7433 Sometimes we change a larger number; we'd need help from a
7434 higher layer to know to use 'G'. */
56be3814 7435 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
7436 return;
7437
7438 /* For now, don't complain if we have no way to write the
7439 register. GDB loses track of unavailable registers too
7440 easily. Some day, this may be an error. We don't have
0df8b418 7441 any way to read the register, either... */
74ca34ce
DJ
7442 if (!reg->in_g_packet)
7443 return;
7444
56be3814 7445 store_registers_using_G (regcache);
74ca34ce
DJ
7446 return;
7447 }
7448
56be3814 7449 store_registers_using_G (regcache);
74ca34ce 7450
4a22f64d 7451 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7452 if (!rsa->regs[i].in_g_packet)
56be3814 7453 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
7454 /* See above for why we do not issue an error here. */
7455 continue;
7456}
c906108c
SS
7457\f
7458
7459/* Return the number of hex digits in num. */
7460
7461static int
fba45db2 7462hexnumlen (ULONGEST num)
c906108c
SS
7463{
7464 int i;
7465
7466 for (i = 0; num != 0; i++)
7467 num >>= 4;
7468
7469 return max (i, 1);
7470}
7471
2df3850c 7472/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
7473
7474static int
fba45db2 7475hexnumstr (char *buf, ULONGEST num)
c906108c 7476{
c906108c 7477 int len = hexnumlen (num);
a744cf53 7478
2df3850c
JM
7479 return hexnumnstr (buf, num, len);
7480}
7481
c906108c 7482
2df3850c 7483/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 7484
2df3850c 7485static int
fba45db2 7486hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
7487{
7488 int i;
7489
7490 buf[width] = '\0';
7491
7492 for (i = width - 1; i >= 0; i--)
c906108c 7493 {
c5aa993b 7494 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
7495 num >>= 4;
7496 }
7497
2df3850c 7498 return width;
c906108c
SS
7499}
7500
23860348 7501/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
7502
7503static CORE_ADDR
fba45db2 7504remote_address_masked (CORE_ADDR addr)
c906108c 7505{
883b9c6c 7506 unsigned int address_size = remote_address_size;
a744cf53 7507
911c95a5
UW
7508 /* If "remoteaddresssize" was not set, default to target address size. */
7509 if (!address_size)
f5656ead 7510 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
7511
7512 if (address_size > 0
7513 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
7514 {
7515 /* Only create a mask when that mask can safely be constructed
23860348 7516 in a ULONGEST variable. */
c906108c 7517 ULONGEST mask = 1;
a744cf53 7518
911c95a5 7519 mask = (mask << address_size) - 1;
c906108c
SS
7520 addr &= mask;
7521 }
7522 return addr;
7523}
7524
7525/* Determine whether the remote target supports binary downloading.
7526 This is accomplished by sending a no-op memory write of zero length
7527 to the target at the specified address. It does not suffice to send
23860348
MS
7528 the whole packet, since many stubs strip the eighth bit and
7529 subsequently compute a wrong checksum, which causes real havoc with
7530 remote_write_bytes.
7a292a7a 7531
96baa820 7532 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 7533 clean. In cases like this, the user should clear "remote
23860348 7534 X-packet". */
96baa820 7535
c906108c 7536static void
fba45db2 7537check_binary_download (CORE_ADDR addr)
c906108c 7538{
d01949b6 7539 struct remote_state *rs = get_remote_state ();
24b06219 7540
4082afcc 7541 switch (packet_support (PACKET_X))
c906108c 7542 {
96baa820
JM
7543 case PACKET_DISABLE:
7544 break;
7545 case PACKET_ENABLE:
7546 break;
7547 case PACKET_SUPPORT_UNKNOWN:
7548 {
96baa820 7549 char *p;
802188a7 7550
2e9f7625 7551 p = rs->buf;
96baa820
JM
7552 *p++ = 'X';
7553 p += hexnumstr (p, (ULONGEST) addr);
7554 *p++ = ',';
7555 p += hexnumstr (p, (ULONGEST) 0);
7556 *p++ = ':';
7557 *p = '\0';
802188a7 7558
2e9f7625 7559 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7560 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 7561
2e9f7625 7562 if (rs->buf[0] == '\0')
96baa820
JM
7563 {
7564 if (remote_debug)
7565 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7566 "binary downloading NOT "
7567 "supported by target\n");
444abaca 7568 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
7569 }
7570 else
7571 {
7572 if (remote_debug)
7573 fprintf_unfiltered (gdb_stdlog,
64b9b334 7574 "binary downloading supported by target\n");
444abaca 7575 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
7576 }
7577 break;
7578 }
c906108c
SS
7579 }
7580}
7581
124e13d9
SM
7582/* Helper function to resize the payload in order to try to get a good
7583 alignment. We try to write an amount of data such that the next write will
7584 start on an address aligned on REMOTE_ALIGN_WRITES. */
7585
7586static int
7587align_for_efficient_write (int todo, CORE_ADDR memaddr)
7588{
7589 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7590}
7591
c906108c
SS
7592/* Write memory data directly to the remote machine.
7593 This does not inform the data cache; the data cache uses this.
a76d924d 7594 HEADER is the starting part of the packet.
c906108c
SS
7595 MEMADDR is the address in the remote memory space.
7596 MYADDR is the address of the buffer in our space.
124e13d9
SM
7597 LEN_UNITS is the number of addressable units to write.
7598 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
7599 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7600 should send data as binary ('X'), or hex-encoded ('M').
7601
7602 The function creates packet of the form
7603 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7604
124e13d9 7605 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
7606
7607 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7608 are omitted.
7609
9b409511 7610 Return the transferred status, error or OK (an
124e13d9
SM
7611 'enum target_xfer_status' value). Save the number of addressable units
7612 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7613
7614 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7615 exchange between gdb and the stub could look like (?? in place of the
7616 checksum):
7617
7618 -> $m1000,4#??
7619 <- aaaabbbbccccdddd
7620
7621 -> $M1000,3:eeeeffffeeee#??
7622 <- OK
7623
7624 -> $m1000,4#??
7625 <- eeeeffffeeeedddd */
c906108c 7626
9b409511 7627static enum target_xfer_status
a76d924d 7628remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
7629 const gdb_byte *myaddr, ULONGEST len_units,
7630 int unit_size, ULONGEST *xfered_len_units,
7631 char packet_format, int use_length)
c906108c 7632{
6d820c5c 7633 struct remote_state *rs = get_remote_state ();
cfd77fa1 7634 char *p;
a76d924d
DJ
7635 char *plen = NULL;
7636 int plenlen = 0;
124e13d9
SM
7637 int todo_units;
7638 int units_written;
7639 int payload_capacity_bytes;
7640 int payload_length_bytes;
a76d924d
DJ
7641
7642 if (packet_format != 'X' && packet_format != 'M')
7643 internal_error (__FILE__, __LINE__,
9b20d036 7644 _("remote_write_bytes_aux: bad packet format"));
c906108c 7645
124e13d9 7646 if (len_units == 0)
9b409511 7647 return TARGET_XFER_EOF;
b2182ed2 7648
124e13d9 7649 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 7650
6d820c5c
DJ
7651 /* The packet buffer will be large enough for the payload;
7652 get_memory_packet_size ensures this. */
a76d924d 7653 rs->buf[0] = '\0';
c906108c 7654
a257b5bb 7655 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
7656 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7657
124e13d9 7658 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 7659 if (!use_length)
0df8b418 7660 /* The comma won't be used. */
124e13d9
SM
7661 payload_capacity_bytes += 1;
7662 payload_capacity_bytes -= strlen (header);
7663 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 7664
a76d924d 7665 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 7666
a76d924d
DJ
7667 strcat (rs->buf, header);
7668 p = rs->buf + strlen (header);
7669
7670 /* Compute a best guess of the number of bytes actually transfered. */
7671 if (packet_format == 'X')
c906108c 7672 {
23860348 7673 /* Best guess at number of bytes that will fit. */
124e13d9 7674 todo_units = min (len_units, payload_capacity_bytes / unit_size);
a76d924d 7675 if (use_length)
124e13d9
SM
7676 payload_capacity_bytes -= hexnumlen (todo_units);
7677 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
7678 }
7679 else
7680 {
124e13d9
SM
7681 /* Number of bytes that will fit. */
7682 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
a76d924d 7683 if (use_length)
124e13d9
SM
7684 payload_capacity_bytes -= hexnumlen (todo_units);
7685 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
917317f4 7686 }
a76d924d 7687
124e13d9 7688 if (todo_units <= 0)
3de11b2e 7689 internal_error (__FILE__, __LINE__,
405f8e94 7690 _("minimum packet size too small to write data"));
802188a7 7691
6765f3e5
DJ
7692 /* If we already need another packet, then try to align the end
7693 of this packet to a useful boundary. */
124e13d9
SM
7694 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7695 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 7696
a257b5bb 7697 /* Append "<memaddr>". */
917317f4
JM
7698 memaddr = remote_address_masked (memaddr);
7699 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 7700
a76d924d
DJ
7701 if (use_length)
7702 {
7703 /* Append ",". */
7704 *p++ = ',';
802188a7 7705
124e13d9
SM
7706 /* Append the length and retain its location and size. It may need to be
7707 adjusted once the packet body has been created. */
a76d924d 7708 plen = p;
124e13d9 7709 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
7710 p += plenlen;
7711 }
a257b5bb
AC
7712
7713 /* Append ":". */
917317f4
JM
7714 *p++ = ':';
7715 *p = '\0';
802188a7 7716
a257b5bb 7717 /* Append the packet body. */
a76d924d 7718 if (packet_format == 'X')
917317f4 7719 {
917317f4
JM
7720 /* Binary mode. Send target system values byte by byte, in
7721 increasing byte addresses. Only escape certain critical
7722 characters. */
124e13d9
SM
7723 payload_length_bytes =
7724 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7725 &units_written, payload_capacity_bytes);
6765f3e5 7726
124e13d9 7727 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
7728 a second try to keep the end of the packet aligned. Don't do
7729 this if the packet is tiny. */
124e13d9 7730 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 7731 {
124e13d9
SM
7732 int new_todo_units;
7733
7734 new_todo_units = align_for_efficient_write (units_written, memaddr);
7735
7736 if (new_todo_units != units_written)
7737 payload_length_bytes =
7738 remote_escape_output (myaddr, new_todo_units, unit_size,
7739 (gdb_byte *) p, &units_written,
7740 payload_capacity_bytes);
6765f3e5
DJ
7741 }
7742
124e13d9
SM
7743 p += payload_length_bytes;
7744 if (use_length && units_written < todo_units)
c906108c 7745 {
802188a7 7746 /* Escape chars have filled up the buffer prematurely,
124e13d9 7747 and we have actually sent fewer units than planned.
917317f4
JM
7748 Fix-up the length field of the packet. Use the same
7749 number of characters as before. */
124e13d9
SM
7750 plen += hexnumnstr (plen, (ULONGEST) units_written,
7751 plenlen);
917317f4 7752 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 7753 }
a76d924d
DJ
7754 }
7755 else
7756 {
917317f4
JM
7757 /* Normal mode: Send target system values byte by byte, in
7758 increasing byte addresses. Each byte is encoded as a two hex
7759 value. */
124e13d9
SM
7760 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7761 units_written = todo_units;
c906108c 7762 }
802188a7 7763
2e9f7625 7764 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7765 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 7766
2e9f7625 7767 if (rs->buf[0] == 'E')
00d84524 7768 return TARGET_XFER_E_IO;
802188a7 7769
124e13d9
SM
7770 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7771 send fewer units than we'd planned. */
7772 *xfered_len_units = (ULONGEST) units_written;
9b409511 7773 return TARGET_XFER_OK;
c906108c
SS
7774}
7775
a76d924d
DJ
7776/* Write memory data directly to the remote machine.
7777 This does not inform the data cache; the data cache uses this.
7778 MEMADDR is the address in the remote memory space.
7779 MYADDR is the address of the buffer in our space.
7780 LEN is the number of bytes.
7781
9b409511
YQ
7782 Return the transferred status, error or OK (an
7783 'enum target_xfer_status' value). Save the number of bytes
7784 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 7785
9b409511
YQ
7786static enum target_xfer_status
7787remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 7788 int unit_size, ULONGEST *xfered_len)
a76d924d
DJ
7789{
7790 char *packet_format = 0;
7791
7792 /* Check whether the target supports binary download. */
7793 check_binary_download (memaddr);
7794
4082afcc 7795 switch (packet_support (PACKET_X))
a76d924d
DJ
7796 {
7797 case PACKET_ENABLE:
7798 packet_format = "X";
7799 break;
7800 case PACKET_DISABLE:
7801 packet_format = "M";
7802 break;
7803 case PACKET_SUPPORT_UNKNOWN:
7804 internal_error (__FILE__, __LINE__,
7805 _("remote_write_bytes: bad internal state"));
7806 default:
7807 internal_error (__FILE__, __LINE__, _("bad switch"));
7808 }
7809
7810 return remote_write_bytes_aux (packet_format,
124e13d9 7811 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 7812 packet_format[0], 1);
a76d924d
DJ
7813}
7814
9217e74e
YQ
7815/* Read memory data directly from the remote machine.
7816 This does not use the data cache; the data cache uses this.
7817 MEMADDR is the address in the remote memory space.
7818 MYADDR is the address of the buffer in our space.
124e13d9
SM
7819 LEN_UNITS is the number of addressable memory units to read..
7820 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
7821
7822 Return the transferred status, error or OK (an
7823 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
7824 transferred in *XFERED_LEN_UNITS.
7825
7826 See the comment of remote_write_bytes_aux for an example of
7827 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
7828
7829static enum target_xfer_status
124e13d9
SM
7830remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7831 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
7832{
7833 struct remote_state *rs = get_remote_state ();
124e13d9 7834 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 7835 char *p;
124e13d9
SM
7836 int todo_units;
7837 int decoded_bytes;
9217e74e 7838
124e13d9 7839 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
7840 /* The packet buffer will be large enough for the payload;
7841 get_memory_packet_size ensures this. */
7842
124e13d9
SM
7843 /* Number of units that will fit. */
7844 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
7845
7846 /* Construct "m"<memaddr>","<len>". */
7847 memaddr = remote_address_masked (memaddr);
7848 p = rs->buf;
7849 *p++ = 'm';
7850 p += hexnumstr (p, (ULONGEST) memaddr);
7851 *p++ = ',';
124e13d9 7852 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
7853 *p = '\0';
7854 putpkt (rs->buf);
7855 getpkt (&rs->buf, &rs->buf_size, 0);
7856 if (rs->buf[0] == 'E'
7857 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7858 && rs->buf[3] == '\0')
7859 return TARGET_XFER_E_IO;
7860 /* Reply describes memory byte by byte, each byte encoded as two hex
7861 characters. */
7862 p = rs->buf;
124e13d9 7863 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 7864 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 7865 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9217e74e
YQ
7866 return TARGET_XFER_OK;
7867}
7868
b55fbac4
YQ
7869/* Using the set of read-only target sections of remote, read live
7870 read-only memory.
8acf9577
YQ
7871
7872 For interface/parameters/return description see target.h,
7873 to_xfer_partial. */
7874
7875static enum target_xfer_status
b55fbac4
YQ
7876remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7877 ULONGEST memaddr, ULONGEST len,
124e13d9 7878 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
7879{
7880 struct target_section *secp;
7881 struct target_section_table *table;
7882
7883 secp = target_section_by_addr (ops, memaddr);
7884 if (secp != NULL
7885 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7886 secp->the_bfd_section)
7887 & SEC_READONLY))
7888 {
7889 struct target_section *p;
7890 ULONGEST memend = memaddr + len;
7891
7892 table = target_get_section_table (ops);
7893
7894 for (p = table->sections; p < table->sections_end; p++)
7895 {
7896 if (memaddr >= p->addr)
7897 {
7898 if (memend <= p->endaddr)
7899 {
7900 /* Entire transfer is within this section. */
124e13d9 7901 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7902 xfered_len);
8acf9577
YQ
7903 }
7904 else if (memaddr >= p->endaddr)
7905 {
7906 /* This section ends before the transfer starts. */
7907 continue;
7908 }
7909 else
7910 {
7911 /* This section overlaps the transfer. Just do half. */
7912 len = p->endaddr - memaddr;
124e13d9 7913 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7914 xfered_len);
8acf9577
YQ
7915 }
7916 }
7917 }
7918 }
7919
7920 return TARGET_XFER_EOF;
7921}
7922
9217e74e
YQ
7923/* Similar to remote_read_bytes_1, but it reads from the remote stub
7924 first if the requested memory is unavailable in traceframe.
7925 Otherwise, fall back to remote_read_bytes_1. */
c906108c 7926
9b409511 7927static enum target_xfer_status
8acf9577 7928remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
7929 gdb_byte *myaddr, ULONGEST len, int unit_size,
7930 ULONGEST *xfered_len)
c906108c 7931{
6b6aa828 7932 if (len == 0)
96c4f946 7933 return TARGET_XFER_EOF;
b2182ed2 7934
8acf9577
YQ
7935 if (get_traceframe_number () != -1)
7936 {
7937 VEC(mem_range_s) *available;
7938
7939 /* If we fail to get the set of available memory, then the
7940 target does not support querying traceframe info, and so we
7941 attempt reading from the traceframe anyway (assuming the
7942 target implements the old QTro packet then). */
7943 if (traceframe_available_memory (&available, memaddr, len))
7944 {
7945 struct cleanup *old_chain;
7946
7947 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7948
7949 if (VEC_empty (mem_range_s, available)
7950 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7951 {
7952 enum target_xfer_status res;
7953
7954 /* Don't read into the traceframe's available
7955 memory. */
7956 if (!VEC_empty (mem_range_s, available))
7957 {
7958 LONGEST oldlen = len;
7959
7960 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7961 gdb_assert (len <= oldlen);
7962 }
7963
7964 do_cleanups (old_chain);
7965
7966 /* This goes through the topmost target again. */
b55fbac4 7967 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 7968 len, unit_size, xfered_len);
8acf9577
YQ
7969 if (res == TARGET_XFER_OK)
7970 return TARGET_XFER_OK;
7971 else
7972 {
7973 /* No use trying further, we know some memory starting
7974 at MEMADDR isn't available. */
7975 *xfered_len = len;
7976 return TARGET_XFER_UNAVAILABLE;
7977 }
7978 }
7979
7980 /* Don't try to read more than how much is available, in
7981 case the target implements the deprecated QTro packet to
7982 cater for older GDBs (the target's knowledge of read-only
7983 sections may be outdated by now). */
7984 len = VEC_index (mem_range_s, available, 0)->length;
7985
7986 do_cleanups (old_chain);
7987 }
7988 }
7989
124e13d9 7990 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 7991}
74531fed 7992
c906108c 7993\f
c906108c 7994
a76d924d
DJ
7995/* Sends a packet with content determined by the printf format string
7996 FORMAT and the remaining arguments, then gets the reply. Returns
7997 whether the packet was a success, a failure, or unknown. */
7998
77b64a49
PA
7999static enum packet_result remote_send_printf (const char *format, ...)
8000 ATTRIBUTE_PRINTF (1, 2);
8001
2c0b251b 8002static enum packet_result
a76d924d
DJ
8003remote_send_printf (const char *format, ...)
8004{
8005 struct remote_state *rs = get_remote_state ();
8006 int max_size = get_remote_packet_size ();
a76d924d 8007 va_list ap;
a744cf53 8008
a76d924d
DJ
8009 va_start (ap, format);
8010
8011 rs->buf[0] = '\0';
8012 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 8013 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
8014
8015 if (putpkt (rs->buf) < 0)
8016 error (_("Communication problem with target."));
8017
8018 rs->buf[0] = '\0';
8019 getpkt (&rs->buf, &rs->buf_size, 0);
8020
8021 return packet_check_result (rs->buf);
8022}
8023
8024static void
8025restore_remote_timeout (void *p)
8026{
8027 int value = *(int *)p;
a744cf53 8028
a76d924d
DJ
8029 remote_timeout = value;
8030}
8031
8032/* Flash writing can take quite some time. We'll set
8033 effectively infinite timeout for flash operations.
8034 In future, we'll need to decide on a better approach. */
8035static const int remote_flash_timeout = 1000;
8036
8037static void
8038remote_flash_erase (struct target_ops *ops,
8039 ULONGEST address, LONGEST length)
8040{
f5656ead 8041 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
8042 int saved_remote_timeout = remote_timeout;
8043 enum packet_result ret;
a76d924d
DJ
8044 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8045 &saved_remote_timeout);
a744cf53 8046
a76d924d
DJ
8047 remote_timeout = remote_flash_timeout;
8048
8049 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 8050 phex (address, addr_size),
a76d924d
DJ
8051 phex (length, 4));
8052 switch (ret)
8053 {
8054 case PACKET_UNKNOWN:
8055 error (_("Remote target does not support flash erase"));
8056 case PACKET_ERROR:
8057 error (_("Error erasing flash with vFlashErase packet"));
8058 default:
8059 break;
8060 }
8061
8062 do_cleanups (back_to);
8063}
8064
9b409511
YQ
8065static enum target_xfer_status
8066remote_flash_write (struct target_ops *ops, ULONGEST address,
8067 ULONGEST length, ULONGEST *xfered_len,
8068 const gdb_byte *data)
a76d924d
DJ
8069{
8070 int saved_remote_timeout = remote_timeout;
9b409511 8071 enum target_xfer_status ret;
a76d924d 8072 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 8073 &saved_remote_timeout);
a76d924d
DJ
8074
8075 remote_timeout = remote_flash_timeout;
124e13d9 8076 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9b409511 8077 xfered_len,'X', 0);
a76d924d
DJ
8078 do_cleanups (back_to);
8079
8080 return ret;
8081}
8082
8083static void
8084remote_flash_done (struct target_ops *ops)
8085{
8086 int saved_remote_timeout = remote_timeout;
8087 int ret;
8088 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8089 &saved_remote_timeout);
8090
8091 remote_timeout = remote_flash_timeout;
8092 ret = remote_send_printf ("vFlashDone");
8093 do_cleanups (back_to);
8094
8095 switch (ret)
8096 {
8097 case PACKET_UNKNOWN:
8098 error (_("Remote target does not support vFlashDone"));
8099 case PACKET_ERROR:
8100 error (_("Error finishing flash operation"));
8101 default:
8102 break;
8103 }
8104}
8105
c906108c 8106static void
fba45db2 8107remote_files_info (struct target_ops *ignore)
c906108c
SS
8108{
8109 puts_filtered ("Debugging a target over a serial line.\n");
8110}
8111\f
8112/* Stuff for dealing with the packets which are part of this protocol.
8113 See comment at top of file for details. */
8114
1927e618
PA
8115/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8116 error to higher layers. Called when a serial error is detected.
8117 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
8118 the system error message for errno at function entry and final dot
8119 for output compatibility with throw_perror_with_name. */
1927e618
PA
8120
8121static void
8122unpush_and_perror (const char *string)
8123{
d6cb50a2 8124 int saved_errno = errno;
1927e618
PA
8125
8126 remote_unpush_target ();
d6cb50a2
JK
8127 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8128 safe_strerror (saved_errno));
1927e618
PA
8129}
8130
048094ac
PA
8131/* Read a single character from the remote end. The current quit
8132 handler is overridden to avoid quitting in the middle of packet
8133 sequence, as that would break communication with the remote server.
8134 See remote_serial_quit_handler for more detail. */
c906108c
SS
8135
8136static int
fba45db2 8137readchar (int timeout)
c906108c
SS
8138{
8139 int ch;
5d93a237 8140 struct remote_state *rs = get_remote_state ();
048094ac
PA
8141 struct cleanup *old_chain;
8142
8143 old_chain = make_cleanup_override_quit_handler (remote_serial_quit_handler);
8144
8145 rs->got_ctrlc_during_io = 0;
c906108c 8146
5d93a237 8147 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 8148
048094ac
PA
8149 if (rs->got_ctrlc_during_io)
8150 set_quit_flag ();
8151
8152 do_cleanups (old_chain);
8153
2acceee2 8154 if (ch >= 0)
0876f84a 8155 return ch;
2acceee2
JM
8156
8157 switch ((enum serial_rc) ch)
c906108c
SS
8158 {
8159 case SERIAL_EOF:
78a095c3 8160 remote_unpush_target ();
598d3636 8161 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 8162 /* no return */
c906108c 8163 case SERIAL_ERROR:
1927e618
PA
8164 unpush_and_perror (_("Remote communication error. "
8165 "Target disconnected."));
2acceee2 8166 /* no return */
c906108c 8167 case SERIAL_TIMEOUT:
2acceee2 8168 break;
c906108c 8169 }
2acceee2 8170 return ch;
c906108c
SS
8171}
8172
c33e31fd 8173/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
8174 writing fails. The current quit handler is overridden to avoid
8175 quitting in the middle of packet sequence, as that would break
8176 communication with the remote server. See
8177 remote_serial_quit_handler for more detail. */
c33e31fd
PA
8178
8179static void
8180remote_serial_write (const char *str, int len)
8181{
5d93a237 8182 struct remote_state *rs = get_remote_state ();
048094ac
PA
8183 struct cleanup *old_chain;
8184
8185 old_chain = make_cleanup_override_quit_handler (remote_serial_quit_handler);
8186
8187 rs->got_ctrlc_during_io = 0;
5d93a237
TT
8188
8189 if (serial_write (rs->remote_desc, str, len))
c33e31fd 8190 {
1927e618
PA
8191 unpush_and_perror (_("Remote communication error. "
8192 "Target disconnected."));
c33e31fd 8193 }
048094ac
PA
8194
8195 if (rs->got_ctrlc_during_io)
8196 set_quit_flag ();
8197
8198 do_cleanups (old_chain);
c33e31fd
PA
8199}
8200
6d820c5c
DJ
8201/* Send the command in *BUF to the remote machine, and read the reply
8202 into *BUF. Report an error if we get an error reply. Resize
8203 *BUF using xrealloc if necessary to hold the result, and update
8204 *SIZEOF_BUF. */
c906108c
SS
8205
8206static void
6d820c5c
DJ
8207remote_send (char **buf,
8208 long *sizeof_buf)
c906108c 8209{
6d820c5c 8210 putpkt (*buf);
c2d11a7d 8211 getpkt (buf, sizeof_buf, 0);
c906108c 8212
6d820c5c
DJ
8213 if ((*buf)[0] == 'E')
8214 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
8215}
8216
6e5abd65
PA
8217/* Return a pointer to an xmalloc'ed string representing an escaped
8218 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
8219 etc. The caller is responsible for releasing the returned
8220 memory. */
8221
8222static char *
8223escape_buffer (const char *buf, int n)
8224{
8225 struct cleanup *old_chain;
8226 struct ui_file *stb;
8227 char *str;
6e5abd65
PA
8228
8229 stb = mem_fileopen ();
8230 old_chain = make_cleanup_ui_file_delete (stb);
8231
6ef284bd 8232 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 8233 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
8234 do_cleanups (old_chain);
8235 return str;
8236}
8237
c906108c
SS
8238/* Display a null-terminated packet on stdout, for debugging, using C
8239 string notation. */
8240
8241static void
baa336ce 8242print_packet (const char *buf)
c906108c
SS
8243{
8244 puts_filtered ("\"");
43e526b9 8245 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
8246 puts_filtered ("\"");
8247}
8248
8249int
baa336ce 8250putpkt (const char *buf)
c906108c
SS
8251{
8252 return putpkt_binary (buf, strlen (buf));
8253}
8254
8255/* Send a packet to the remote machine, with error checking. The data
23860348 8256 of the packet is in BUF. The string in BUF can be at most
ea9c271d 8257 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
8258 and for a possible /0 if we are debugging (remote_debug) and want
8259 to print the sent packet as a string. */
c906108c
SS
8260
8261static int
baa336ce 8262putpkt_binary (const char *buf, int cnt)
c906108c 8263{
2d717e4f 8264 struct remote_state *rs = get_remote_state ();
c906108c
SS
8265 int i;
8266 unsigned char csum = 0;
224c3ddb 8267 char *buf2 = (char *) xmalloc (cnt + 6);
a5c0808e 8268 struct cleanup *old_chain = make_cleanup (xfree, buf2);
085dd6e6 8269
c906108c
SS
8270 int ch;
8271 int tcount = 0;
8272 char *p;
8273
e24a49d8
PA
8274 /* Catch cases like trying to read memory or listing threads while
8275 we're waiting for a stop reply. The remote server wouldn't be
8276 ready to handle this request, so we'd hang and timeout. We don't
8277 have to worry about this in synchronous mode, because in that
8278 case it's not possible to issue a command while the target is
74531fed
PA
8279 running. This is not a problem in non-stop mode, because in that
8280 case, the stub is always ready to process serial input. */
6efcd9a8
PA
8281 if (!target_is_non_stop_p ()
8282 && target_is_async_p ()
8283 && rs->waiting_for_stop_reply)
9597b22a
DE
8284 {
8285 error (_("Cannot execute this command while the target is running.\n"
8286 "Use the \"interrupt\" command to stop the target\n"
8287 "and then try again."));
8288 }
e24a49d8 8289
2d717e4f
DJ
8290 /* We're sending out a new packet. Make sure we don't look at a
8291 stale cached response. */
8292 rs->cached_wait_status = 0;
8293
c906108c
SS
8294 /* Copy the packet into buffer BUF2, encapsulating it
8295 and giving it a checksum. */
8296
c906108c
SS
8297 p = buf2;
8298 *p++ = '$';
8299
8300 for (i = 0; i < cnt; i++)
8301 {
8302 csum += buf[i];
8303 *p++ = buf[i];
8304 }
8305 *p++ = '#';
8306 *p++ = tohex ((csum >> 4) & 0xf);
8307 *p++ = tohex (csum & 0xf);
8308
8309 /* Send it over and over until we get a positive ack. */
8310
8311 while (1)
8312 {
8313 int started_error_output = 0;
8314
8315 if (remote_debug)
8316 {
6e5abd65
PA
8317 struct cleanup *old_chain;
8318 char *str;
8319
c906108c 8320 *p = '\0';
6e5abd65
PA
8321 str = escape_buffer (buf2, p - buf2);
8322 old_chain = make_cleanup (xfree, str);
8323 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 8324 gdb_flush (gdb_stdlog);
6e5abd65 8325 do_cleanups (old_chain);
c906108c 8326 }
c33e31fd 8327 remote_serial_write (buf2, p - buf2);
c906108c 8328
a6f3e723
SL
8329 /* If this is a no acks version of the remote protocol, send the
8330 packet and move on. */
8331 if (rs->noack_mode)
8332 break;
8333
74531fed
PA
8334 /* Read until either a timeout occurs (-2) or '+' is read.
8335 Handle any notification that arrives in the mean time. */
c906108c
SS
8336 while (1)
8337 {
8338 ch = readchar (remote_timeout);
8339
c5aa993b 8340 if (remote_debug)
c906108c
SS
8341 {
8342 switch (ch)
8343 {
8344 case '+':
1216fa2c 8345 case '-':
c906108c
SS
8346 case SERIAL_TIMEOUT:
8347 case '$':
74531fed 8348 case '%':
c906108c
SS
8349 if (started_error_output)
8350 {
8351 putchar_unfiltered ('\n');
8352 started_error_output = 0;
8353 }
8354 }
8355 }
8356
8357 switch (ch)
8358 {
8359 case '+':
8360 if (remote_debug)
0f71a2f6 8361 fprintf_unfiltered (gdb_stdlog, "Ack\n");
a5c0808e 8362 do_cleanups (old_chain);
c906108c 8363 return 1;
1216fa2c
AC
8364 case '-':
8365 if (remote_debug)
8366 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 8367 /* FALLTHROUGH */
c906108c 8368 case SERIAL_TIMEOUT:
c5aa993b 8369 tcount++;
c906108c 8370 if (tcount > 3)
a5c0808e
PA
8371 {
8372 do_cleanups (old_chain);
8373 return 0;
8374 }
23860348 8375 break; /* Retransmit buffer. */
c906108c
SS
8376 case '$':
8377 {
40e3f985 8378 if (remote_debug)
2bc416ba 8379 fprintf_unfiltered (gdb_stdlog,
23860348 8380 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
8381 /* It's probably an old response sent because an ACK
8382 was lost. Gobble up the packet and ack it so it
8383 doesn't get retransmitted when we resend this
8384 packet. */
6d820c5c 8385 skip_frame ();
c33e31fd 8386 remote_serial_write ("+", 1);
23860348 8387 continue; /* Now, go look for +. */
c906108c 8388 }
74531fed
PA
8389
8390 case '%':
8391 {
8392 int val;
8393
8394 /* If we got a notification, handle it, and go back to looking
8395 for an ack. */
8396 /* We've found the start of a notification. Now
8397 collect the data. */
8398 val = read_frame (&rs->buf, &rs->buf_size);
8399 if (val >= 0)
8400 {
8401 if (remote_debug)
8402 {
6e5abd65
PA
8403 struct cleanup *old_chain;
8404 char *str;
8405
8406 str = escape_buffer (rs->buf, val);
8407 old_chain = make_cleanup (xfree, str);
8408 fprintf_unfiltered (gdb_stdlog,
8409 " Notification received: %s\n",
8410 str);
8411 do_cleanups (old_chain);
74531fed 8412 }
5965e028 8413 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
8414 /* We're in sync now, rewait for the ack. */
8415 tcount = 0;
8416 }
8417 else
8418 {
8419 if (remote_debug)
8420 {
8421 if (!started_error_output)
8422 {
8423 started_error_output = 1;
8424 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8425 }
8426 fputc_unfiltered (ch & 0177, gdb_stdlog);
8427 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8428 }
8429 }
8430 continue;
8431 }
8432 /* fall-through */
c906108c
SS
8433 default:
8434 if (remote_debug)
8435 {
8436 if (!started_error_output)
8437 {
8438 started_error_output = 1;
0f71a2f6 8439 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 8440 }
0f71a2f6 8441 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
8442 }
8443 continue;
8444 }
23860348 8445 break; /* Here to retransmit. */
c906108c
SS
8446 }
8447
8448#if 0
8449 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
8450 able to get out next time we call QUIT, without anything as
8451 violent as interrupt_query. If we want to provide a way out of
8452 here without getting to the next QUIT, it should be based on
8453 hitting ^C twice as in remote_wait. */
c906108c
SS
8454 if (quit_flag)
8455 {
8456 quit_flag = 0;
8457 interrupt_query ();
8458 }
8459#endif
8460 }
a5c0808e
PA
8461
8462 do_cleanups (old_chain);
a6f3e723 8463 return 0;
c906108c
SS
8464}
8465
6d820c5c
DJ
8466/* Come here after finding the start of a frame when we expected an
8467 ack. Do our best to discard the rest of this packet. */
8468
8469static void
8470skip_frame (void)
8471{
8472 int c;
8473
8474 while (1)
8475 {
8476 c = readchar (remote_timeout);
8477 switch (c)
8478 {
8479 case SERIAL_TIMEOUT:
8480 /* Nothing we can do. */
8481 return;
8482 case '#':
8483 /* Discard the two bytes of checksum and stop. */
8484 c = readchar (remote_timeout);
8485 if (c >= 0)
8486 c = readchar (remote_timeout);
8487
8488 return;
8489 case '*': /* Run length encoding. */
8490 /* Discard the repeat count. */
8491 c = readchar (remote_timeout);
8492 if (c < 0)
8493 return;
8494 break;
8495 default:
8496 /* A regular character. */
8497 break;
8498 }
8499 }
8500}
8501
c906108c 8502/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
8503 into *BUF, verifying the checksum, length, and handling run-length
8504 compression. NUL terminate the buffer. If there is not enough room,
8505 expand *BUF using xrealloc.
c906108c 8506
c2d11a7d
JM
8507 Returns -1 on error, number of characters in buffer (ignoring the
8508 trailing NULL) on success. (could be extended to return one of the
23860348 8509 SERIAL status indications). */
c2d11a7d
JM
8510
8511static long
6d820c5c
DJ
8512read_frame (char **buf_p,
8513 long *sizeof_buf)
c906108c
SS
8514{
8515 unsigned char csum;
c2d11a7d 8516 long bc;
c906108c 8517 int c;
6d820c5c 8518 char *buf = *buf_p;
a6f3e723 8519 struct remote_state *rs = get_remote_state ();
c906108c
SS
8520
8521 csum = 0;
c2d11a7d 8522 bc = 0;
c906108c
SS
8523
8524 while (1)
8525 {
8526 c = readchar (remote_timeout);
c906108c
SS
8527 switch (c)
8528 {
8529 case SERIAL_TIMEOUT:
8530 if (remote_debug)
0f71a2f6 8531 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 8532 return -1;
c906108c
SS
8533 case '$':
8534 if (remote_debug)
0f71a2f6
JM
8535 fputs_filtered ("Saw new packet start in middle of old one\n",
8536 gdb_stdlog);
23860348 8537 return -1; /* Start a new packet, count retries. */
c906108c
SS
8538 case '#':
8539 {
8540 unsigned char pktcsum;
e1b09194
AC
8541 int check_0 = 0;
8542 int check_1 = 0;
c906108c 8543
c2d11a7d 8544 buf[bc] = '\0';
c906108c 8545
e1b09194
AC
8546 check_0 = readchar (remote_timeout);
8547 if (check_0 >= 0)
8548 check_1 = readchar (remote_timeout);
802188a7 8549
e1b09194
AC
8550 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8551 {
8552 if (remote_debug)
2bc416ba 8553 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 8554 gdb_stdlog);
e1b09194
AC
8555 return -1;
8556 }
8557 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
8558 {
8559 if (remote_debug)
2bc416ba 8560 fputs_filtered ("Communication error in checksum\n",
23860348 8561 gdb_stdlog);
40e3f985
FN
8562 return -1;
8563 }
c906108c 8564
a6f3e723
SL
8565 /* Don't recompute the checksum; with no ack packets we
8566 don't have any way to indicate a packet retransmission
8567 is necessary. */
8568 if (rs->noack_mode)
8569 return bc;
8570
e1b09194 8571 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 8572 if (csum == pktcsum)
c2d11a7d 8573 return bc;
c906108c 8574
c5aa993b 8575 if (remote_debug)
c906108c 8576 {
6e5abd65
PA
8577 struct cleanup *old_chain;
8578 char *str;
8579
8580 str = escape_buffer (buf, bc);
8581 old_chain = make_cleanup (xfree, str);
8582 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8583 "Bad checksum, sentsum=0x%x, "
8584 "csum=0x%x, buf=%s\n",
6e5abd65
PA
8585 pktcsum, csum, str);
8586 do_cleanups (old_chain);
c906108c 8587 }
c2d11a7d 8588 /* Number of characters in buffer ignoring trailing
23860348 8589 NULL. */
c2d11a7d 8590 return -1;
c906108c 8591 }
23860348 8592 case '*': /* Run length encoding. */
c2c6d25f
JM
8593 {
8594 int repeat;
c906108c 8595
a744cf53 8596 csum += c;
b4501125
AC
8597 c = readchar (remote_timeout);
8598 csum += c;
23860348 8599 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 8600
23860348 8601 /* The character before ``*'' is repeated. */
c2d11a7d 8602
6d820c5c 8603 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 8604 {
6d820c5c
DJ
8605 if (bc + repeat - 1 >= *sizeof_buf - 1)
8606 {
8607 /* Make some more room in the buffer. */
8608 *sizeof_buf += repeat;
224c3ddb 8609 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
8610 buf = *buf_p;
8611 }
8612
c2d11a7d
JM
8613 memset (&buf[bc], buf[bc - 1], repeat);
8614 bc += repeat;
c2c6d25f
JM
8615 continue;
8616 }
8617
c2d11a7d 8618 buf[bc] = '\0';
6d820c5c 8619 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 8620 return -1;
c2c6d25f 8621 }
c906108c 8622 default:
6d820c5c 8623 if (bc >= *sizeof_buf - 1)
c906108c 8624 {
6d820c5c
DJ
8625 /* Make some more room in the buffer. */
8626 *sizeof_buf *= 2;
224c3ddb 8627 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 8628 buf = *buf_p;
c906108c
SS
8629 }
8630
6d820c5c
DJ
8631 buf[bc++] = c;
8632 csum += c;
8633 continue;
c906108c
SS
8634 }
8635 }
8636}
8637
8638/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8639 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8640 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8641 rather than timing out; this is used (in synchronous mode) to wait
8642 for a target that is is executing user code to stop. */
d9fcf2fb
JM
8643/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8644 don't have to change all the calls to getpkt to deal with the
8645 return value, because at the moment I don't know what the right
23860348 8646 thing to do it for those. */
c906108c 8647void
6d820c5c
DJ
8648getpkt (char **buf,
8649 long *sizeof_buf,
c2d11a7d 8650 int forever)
d9fcf2fb 8651{
54887903 8652 getpkt_sane (buf, sizeof_buf, forever);
d9fcf2fb
JM
8653}
8654
8655
8656/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8657 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8658 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8659 rather than timing out; this is used (in synchronous mode) to wait
8660 for a target that is is executing user code to stop. If FOREVER ==
8661 0, this function is allowed to time out gracefully and return an
74531fed
PA
8662 indication of this to the caller. Otherwise return the number of
8663 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
8664 enough reason to return to the caller. *IS_NOTIF is an output
8665 boolean that indicates whether *BUF holds a notification or not
8666 (a regular packet). */
74531fed 8667
3172dc30 8668static int
74531fed 8669getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 8670 int expecting_notif, int *is_notif)
c906108c 8671{
2d717e4f 8672 struct remote_state *rs = get_remote_state ();
c906108c
SS
8673 int c;
8674 int tries;
8675 int timeout;
df4b58fe 8676 int val = -1;
c906108c 8677
2d717e4f
DJ
8678 /* We're reading a new response. Make sure we don't look at a
8679 previously cached response. */
8680 rs->cached_wait_status = 0;
8681
6d820c5c 8682 strcpy (*buf, "timeout");
c906108c
SS
8683
8684 if (forever)
74531fed
PA
8685 timeout = watchdog > 0 ? watchdog : -1;
8686 else if (expecting_notif)
8687 timeout = 0; /* There should already be a char in the buffer. If
8688 not, bail out. */
c906108c
SS
8689 else
8690 timeout = remote_timeout;
8691
8692#define MAX_TRIES 3
8693
74531fed
PA
8694 /* Process any number of notifications, and then return when
8695 we get a packet. */
8696 for (;;)
c906108c 8697 {
d9c43928 8698 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
8699 times. */
8700 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 8701 {
74531fed
PA
8702 /* This can loop forever if the remote side sends us
8703 characters continuously, but if it pauses, we'll get
8704 SERIAL_TIMEOUT from readchar because of timeout. Then
8705 we'll count that as a retry.
8706
8707 Note that even when forever is set, we will only wait
8708 forever prior to the start of a packet. After that, we
8709 expect characters to arrive at a brisk pace. They should
8710 show up within remote_timeout intervals. */
8711 do
8712 c = readchar (timeout);
8713 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
8714
8715 if (c == SERIAL_TIMEOUT)
8716 {
74531fed
PA
8717 if (expecting_notif)
8718 return -1; /* Don't complain, it's normal to not get
8719 anything in this case. */
8720
23860348 8721 if (forever) /* Watchdog went off? Kill the target. */
c906108c 8722 {
78a095c3 8723 remote_unpush_target ();
598d3636
JK
8724 throw_error (TARGET_CLOSE_ERROR,
8725 _("Watchdog timeout has expired. "
8726 "Target detached."));
c906108c 8727 }
c906108c 8728 if (remote_debug)
0f71a2f6 8729 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 8730 }
74531fed
PA
8731 else
8732 {
8733 /* We've found the start of a packet or notification.
8734 Now collect the data. */
8735 val = read_frame (buf, sizeof_buf);
8736 if (val >= 0)
8737 break;
8738 }
8739
c33e31fd 8740 remote_serial_write ("-", 1);
c906108c 8741 }
c906108c 8742
74531fed
PA
8743 if (tries > MAX_TRIES)
8744 {
8745 /* We have tried hard enough, and just can't receive the
8746 packet/notification. Give up. */
8747 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 8748
74531fed
PA
8749 /* Skip the ack char if we're in no-ack mode. */
8750 if (!rs->noack_mode)
c33e31fd 8751 remote_serial_write ("+", 1);
74531fed
PA
8752 return -1;
8753 }
c906108c 8754
74531fed
PA
8755 /* If we got an ordinary packet, return that to our caller. */
8756 if (c == '$')
c906108c
SS
8757 {
8758 if (remote_debug)
43e526b9 8759 {
6e5abd65
PA
8760 struct cleanup *old_chain;
8761 char *str;
8762
8763 str = escape_buffer (*buf, val);
8764 old_chain = make_cleanup (xfree, str);
8765 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8766 do_cleanups (old_chain);
43e526b9 8767 }
a6f3e723
SL
8768
8769 /* Skip the ack char if we're in no-ack mode. */
8770 if (!rs->noack_mode)
c33e31fd 8771 remote_serial_write ("+", 1);
fee9eda9
YQ
8772 if (is_notif != NULL)
8773 *is_notif = 0;
0876f84a 8774 return val;
c906108c
SS
8775 }
8776
74531fed
PA
8777 /* If we got a notification, handle it, and go back to looking
8778 for a packet. */
8779 else
8780 {
8781 gdb_assert (c == '%');
8782
8783 if (remote_debug)
8784 {
6e5abd65
PA
8785 struct cleanup *old_chain;
8786 char *str;
8787
8788 str = escape_buffer (*buf, val);
8789 old_chain = make_cleanup (xfree, str);
8790 fprintf_unfiltered (gdb_stdlog,
8791 " Notification received: %s\n",
8792 str);
8793 do_cleanups (old_chain);
74531fed 8794 }
fee9eda9
YQ
8795 if (is_notif != NULL)
8796 *is_notif = 1;
c906108c 8797
5965e028 8798 handle_notification (rs->notif_state, *buf);
c906108c 8799
74531fed 8800 /* Notifications require no acknowledgement. */
a6f3e723 8801
74531fed 8802 if (expecting_notif)
fee9eda9 8803 return val;
74531fed
PA
8804 }
8805 }
8806}
8807
8808static int
8809getpkt_sane (char **buf, long *sizeof_buf, int forever)
8810{
fee9eda9 8811 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
8812}
8813
8814static int
fee9eda9
YQ
8815getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8816 int *is_notif)
74531fed 8817{
fee9eda9
YQ
8818 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8819 is_notif);
c906108c 8820}
74531fed 8821
cbb8991c
DB
8822/* Check whether EVENT is a fork event for the process specified
8823 by the pid passed in DATA, and if it is, kill the fork child. */
8824
8825static int
8826kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8827 QUEUE_ITER (stop_reply_p) *iter,
8828 stop_reply_p event,
8829 void *data)
8830{
19ba03f4 8831 struct queue_iter_param *param = (struct queue_iter_param *) data;
cbb8991c
DB
8832 int parent_pid = *(int *) param->input;
8833
8834 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8835 {
8836 struct remote_state *rs = get_remote_state ();
8837 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8838 int res;
8839
8840 res = remote_vkill (child_pid, rs);
8841 if (res != 0)
8842 error (_("Can't kill fork child process %d"), child_pid);
8843 }
8844
8845 return 1;
8846}
8847
8848/* Kill any new fork children of process PID that haven't been
8849 processed by follow_fork. */
8850
8851static void
8852kill_new_fork_children (int pid, struct remote_state *rs)
8853{
8854 struct thread_info *thread;
8855 struct notif_client *notif = &notif_client_stop;
8856 struct queue_iter_param param;
8857
8858 /* Kill the fork child threads of any threads in process PID
8859 that are stopped at a fork event. */
8860 ALL_NON_EXITED_THREADS (thread)
8861 {
8862 struct target_waitstatus *ws = &thread->pending_follow;
8863
8864 if (is_pending_fork_parent (ws, pid, thread->ptid))
8865 {
8866 struct remote_state *rs = get_remote_state ();
8867 int child_pid = ptid_get_pid (ws->value.related_pid);
8868 int res;
8869
8870 res = remote_vkill (child_pid, rs);
8871 if (res != 0)
8872 error (_("Can't kill fork child process %d"), child_pid);
8873 }
8874 }
8875
8876 /* Check for any pending fork events (not reported or processed yet)
8877 in process PID and kill those fork child threads as well. */
8878 remote_notif_get_pending_events (notif);
8879 param.input = &pid;
8880 param.output = NULL;
8881 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8882 kill_child_of_pending_fork, &param);
8883}
8884
c906108c 8885\f
8020350c
DB
8886/* Target hook to kill the current inferior. */
8887
c906108c 8888static void
7d85a9c0 8889remote_kill (struct target_ops *ops)
43ff13b4 8890{
8020350c
DB
8891 int res = -1;
8892 int pid = ptid_get_pid (inferior_ptid);
8893 struct remote_state *rs = get_remote_state ();
0fdf84ca 8894
8020350c 8895 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 8896 {
8020350c
DB
8897 /* If we're stopped while forking and we haven't followed yet,
8898 kill the child task. We need to do this before killing the
8899 parent task because if this is a vfork then the parent will
8900 be sleeping. */
8901 kill_new_fork_children (pid, rs);
8902
8903 res = remote_vkill (pid, rs);
8904 if (res == 0)
0fdf84ca 8905 {
8020350c 8906 target_mourn_inferior ();
0fdf84ca
PA
8907 return;
8908 }
8020350c 8909 }
0fdf84ca 8910
8020350c
DB
8911 /* If we are in 'target remote' mode and we are killing the only
8912 inferior, then we will tell gdbserver to exit and unpush the
8913 target. */
8914 if (res == -1 && !remote_multi_process_p (rs)
8915 && number_of_live_inferiors () == 1)
8916 {
8917 remote_kill_k ();
8918
8919 /* We've killed the remote end, we get to mourn it. If we are
8920 not in extended mode, mourning the inferior also unpushes
8921 remote_ops from the target stack, which closes the remote
8922 connection. */
8923 target_mourn_inferior ();
8924
8925 return;
0fdf84ca 8926 }
43ff13b4 8927
8020350c 8928 error (_("Can't kill process"));
43ff13b4
JM
8929}
8930
8020350c
DB
8931/* Send a kill request to the target using the 'vKill' packet. */
8932
82f73884
PA
8933static int
8934remote_vkill (int pid, struct remote_state *rs)
8935{
4082afcc 8936 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
8937 return -1;
8938
8939 /* Tell the remote target to detach. */
bba74b36 8940 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
8941 putpkt (rs->buf);
8942 getpkt (&rs->buf, &rs->buf_size, 0);
8943
4082afcc
PA
8944 switch (packet_ok (rs->buf,
8945 &remote_protocol_packets[PACKET_vKill]))
8946 {
8947 case PACKET_OK:
8948 return 0;
8949 case PACKET_ERROR:
8950 return 1;
8951 case PACKET_UNKNOWN:
8952 return -1;
8953 default:
8954 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8955 }
82f73884
PA
8956}
8957
8020350c
DB
8958/* Send a kill request to the target using the 'k' packet. */
8959
82f73884 8960static void
8020350c 8961remote_kill_k (void)
82f73884 8962{
8020350c
DB
8963 /* Catch errors so the user can quit from gdb even when we
8964 aren't on speaking terms with the remote system. */
8965 TRY
82f73884 8966 {
82f73884 8967 putpkt ("k");
82f73884 8968 }
8020350c
DB
8969 CATCH (ex, RETURN_MASK_ERROR)
8970 {
8971 if (ex.error == TARGET_CLOSE_ERROR)
8972 {
8973 /* If we got an (EOF) error that caused the target
8974 to go away, then we're done, that's what we wanted.
8975 "k" is susceptible to cause a premature EOF, given
8976 that the remote server isn't actually required to
8977 reply to "k", and it can happen that it doesn't
8978 even get to reply ACK to the "k". */
8979 return;
8980 }
82f73884 8981
8020350c
DB
8982 /* Otherwise, something went wrong. We didn't actually kill
8983 the target. Just propagate the exception, and let the
8984 user or higher layers decide what to do. */
8985 throw_exception (ex);
8986 }
8987 END_CATCH
82f73884
PA
8988}
8989
c906108c 8990static void
20f796c9 8991remote_mourn (struct target_ops *target)
c906108c 8992{
8020350c 8993 struct remote_state *rs = get_remote_state ();
ce5ce7ed 8994
8020350c
DB
8995 /* In 'target remote' mode with one inferior, we close the connection. */
8996 if (!rs->extended && number_of_live_inferiors () <= 1)
8997 {
8998 unpush_target (target);
c906108c 8999
8020350c
DB
9000 /* remote_close takes care of doing most of the clean up. */
9001 generic_mourn_inferior ();
9002 return;
9003 }
c906108c 9004
e24a49d8
PA
9005 /* In case we got here due to an error, but we're going to stay
9006 connected. */
9007 rs->waiting_for_stop_reply = 0;
9008
dc1981d7
PA
9009 /* If the current general thread belonged to the process we just
9010 detached from or has exited, the remote side current general
9011 thread becomes undefined. Considering a case like this:
9012
9013 - We just got here due to a detach.
9014 - The process that we're detaching from happens to immediately
9015 report a global breakpoint being hit in non-stop mode, in the
9016 same thread we had selected before.
9017 - GDB attaches to this process again.
9018 - This event happens to be the next event we handle.
9019
9020 GDB would consider that the current general thread didn't need to
9021 be set on the stub side (with Hg), since for all it knew,
9022 GENERAL_THREAD hadn't changed.
9023
9024 Notice that although in all-stop mode, the remote server always
9025 sets the current thread to the thread reporting the stop event,
9026 that doesn't happen in non-stop mode; in non-stop, the stub *must
9027 not* change the current thread when reporting a breakpoint hit,
9028 due to the decoupling of event reporting and event handling.
9029
9030 To keep things simple, we always invalidate our notion of the
9031 current thread. */
47f8a51d 9032 record_currthread (rs, minus_one_ptid);
dc1981d7 9033
8020350c 9034 /* Call common code to mark the inferior as not running. */
48aa3c27
PA
9035 generic_mourn_inferior ();
9036
d729566a 9037 if (!have_inferiors ())
2d717e4f 9038 {
82f73884
PA
9039 if (!remote_multi_process_p (rs))
9040 {
9041 /* Check whether the target is running now - some remote stubs
9042 automatically restart after kill. */
9043 putpkt ("?");
9044 getpkt (&rs->buf, &rs->buf_size, 0);
9045
9046 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9047 {
3e43a32a
MS
9048 /* Assume that the target has been restarted. Set
9049 inferior_ptid so that bits of core GDB realizes
9050 there's something here, e.g., so that the user can
9051 say "kill" again. */
82f73884
PA
9052 inferior_ptid = magic_null_ptid;
9053 }
82f73884 9054 }
2d717e4f
DJ
9055 }
9056}
c906108c 9057
03583c20 9058static int
2bfc0540 9059extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 9060{
4082afcc 9061 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
9062}
9063
9064static void
9065extended_remote_disable_randomization (int val)
9066{
9067 struct remote_state *rs = get_remote_state ();
9068 char *reply;
9069
bba74b36
YQ
9070 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9071 val);
03583c20
UW
9072 putpkt (rs->buf);
9073 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9074 if (*reply == '\0')
9075 error (_("Target does not support QDisableRandomization."));
9076 if (strcmp (reply, "OK") != 0)
9077 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9078}
9079
2d717e4f
DJ
9080static int
9081extended_remote_run (char *args)
9082{
9083 struct remote_state *rs = get_remote_state ();
2d717e4f 9084 int len;
94585166 9085 const char *remote_exec_file = get_remote_exec_file ();
c906108c 9086
2d717e4f
DJ
9087 /* If the user has disabled vRun support, or we have detected that
9088 support is not available, do not try it. */
4082afcc 9089 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 9090 return -1;
424163ea 9091
2d717e4f
DJ
9092 strcpy (rs->buf, "vRun;");
9093 len = strlen (rs->buf);
c906108c 9094
2d717e4f
DJ
9095 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9096 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
9097 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9098 strlen (remote_exec_file));
2d717e4f 9099
d1a41061 9100 gdb_assert (args != NULL);
2d717e4f
DJ
9101 if (*args)
9102 {
9103 struct cleanup *back_to;
9104 int i;
9105 char **argv;
9106
d1a41061 9107 argv = gdb_buildargv (args);
6e366df1 9108 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
9109 for (i = 0; argv[i] != NULL; i++)
9110 {
9111 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9112 error (_("Argument list too long for run packet"));
9113 rs->buf[len++] = ';';
9f1b45b0
TT
9114 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9115 strlen (argv[i]));
2d717e4f
DJ
9116 }
9117 do_cleanups (back_to);
9118 }
9119
9120 rs->buf[len++] = '\0';
9121
9122 putpkt (rs->buf);
9123 getpkt (&rs->buf, &rs->buf_size, 0);
9124
4082afcc 9125 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 9126 {
4082afcc 9127 case PACKET_OK:
3405876a 9128 /* We have a wait response. All is well. */
2d717e4f 9129 return 0;
4082afcc
PA
9130 case PACKET_UNKNOWN:
9131 return -1;
9132 case PACKET_ERROR:
2d717e4f
DJ
9133 if (remote_exec_file[0] == '\0')
9134 error (_("Running the default executable on the remote target failed; "
9135 "try \"set remote exec-file\"?"));
9136 else
9137 error (_("Running \"%s\" on the remote target failed"),
9138 remote_exec_file);
4082afcc
PA
9139 default:
9140 gdb_assert_not_reached (_("bad switch"));
2d717e4f 9141 }
c906108c
SS
9142}
9143
2d717e4f
DJ
9144/* In the extended protocol we want to be able to do things like
9145 "run" and have them basically work as expected. So we need
9146 a special create_inferior function. We support changing the
9147 executable file and the command line arguments, but not the
9148 environment. */
9149
43ff13b4 9150static void
77a19445
TT
9151extended_remote_create_inferior (struct target_ops *ops,
9152 char *exec_file, char *args,
9153 char **env, int from_tty)
43ff13b4 9154{
3405876a
PA
9155 int run_worked;
9156 char *stop_reply;
9157 struct remote_state *rs = get_remote_state ();
94585166 9158 const char *remote_exec_file = get_remote_exec_file ();
3405876a 9159
43ff13b4 9160 /* If running asynchronously, register the target file descriptor
23860348 9161 with the event loop. */
75c99385 9162 if (target_can_async_p ())
6a3753b3 9163 target_async (1);
43ff13b4 9164
03583c20 9165 /* Disable address space randomization if requested (and supported). */
2bfc0540 9166 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
9167 extended_remote_disable_randomization (disable_randomization);
9168
43ff13b4 9169 /* Now restart the remote server. */
3405876a
PA
9170 run_worked = extended_remote_run (args) != -1;
9171 if (!run_worked)
2d717e4f
DJ
9172 {
9173 /* vRun was not supported. Fail if we need it to do what the
9174 user requested. */
9175 if (remote_exec_file[0])
9176 error (_("Remote target does not support \"set remote exec-file\""));
9177 if (args[0])
9178 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 9179
2d717e4f
DJ
9180 /* Fall back to "R". */
9181 extended_remote_restart ();
9182 }
424163ea 9183
6c95b8df
PA
9184 if (!have_inferiors ())
9185 {
9186 /* Clean up from the last time we ran, before we mark the target
9187 running again. This will mark breakpoints uninserted, and
9188 get_offsets may insert breakpoints. */
9189 init_thread_list ();
9190 init_wait_for_inferior ();
9191 }
45280a52 9192
3405876a
PA
9193 /* vRun's success return is a stop reply. */
9194 stop_reply = run_worked ? rs->buf : NULL;
9195 add_current_inferior_and_thread (stop_reply);
c0a2216e 9196
2d717e4f
DJ
9197 /* Get updated offsets, if the stub uses qOffsets. */
9198 get_offsets ();
2d717e4f 9199}
c906108c 9200\f
c5aa993b 9201
b775012e
LM
9202/* Given a location's target info BP_TGT and the packet buffer BUF, output
9203 the list of conditions (in agent expression bytecode format), if any, the
9204 target needs to evaluate. The output is placed into the packet buffer
bba74b36 9205 started from BUF and ended at BUF_END. */
b775012e
LM
9206
9207static int
9208remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
9209 struct bp_target_info *bp_tgt, char *buf,
9210 char *buf_end)
b775012e
LM
9211{
9212 struct agent_expr *aexpr = NULL;
9213 int i, ix;
b775012e
LM
9214
9215 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9216 return 0;
9217
9218 buf += strlen (buf);
bba74b36 9219 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
9220 buf++;
9221
9222 /* Send conditions to the target and free the vector. */
9223 for (ix = 0;
9224 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9225 ix++)
9226 {
bba74b36 9227 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
9228 buf += strlen (buf);
9229 for (i = 0; i < aexpr->len; ++i)
9230 buf = pack_hex_byte (buf, aexpr->buf[i]);
9231 *buf = '\0';
9232 }
b775012e
LM
9233 return 0;
9234}
9235
d3ce09f5
SS
9236static void
9237remote_add_target_side_commands (struct gdbarch *gdbarch,
9238 struct bp_target_info *bp_tgt, char *buf)
9239{
9240 struct agent_expr *aexpr = NULL;
9241 int i, ix;
9242
9243 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9244 return;
9245
9246 buf += strlen (buf);
9247
9248 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9249 buf += strlen (buf);
9250
9251 /* Concatenate all the agent expressions that are commands into the
9252 cmds parameter. */
9253 for (ix = 0;
9254 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9255 ix++)
9256 {
9257 sprintf (buf, "X%x,", aexpr->len);
9258 buf += strlen (buf);
9259 for (i = 0; i < aexpr->len; ++i)
9260 buf = pack_hex_byte (buf, aexpr->buf[i]);
9261 *buf = '\0';
9262 }
d3ce09f5
SS
9263}
9264
8181d85f
DJ
9265/* Insert a breakpoint. On targets that have software breakpoint
9266 support, we ask the remote target to do the work; on targets
9267 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
9268
9269static int
3db08215
MM
9270remote_insert_breakpoint (struct target_ops *ops,
9271 struct gdbarch *gdbarch,
a6d9a66e 9272 struct bp_target_info *bp_tgt)
c906108c 9273{
d471ea57
AC
9274 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9275 If it succeeds, then set the support to PACKET_ENABLE. If it
9276 fails, and the user has explicitly requested the Z support then
23860348 9277 report an error, otherwise, mark it disabled and go on. */
802188a7 9278
4082afcc 9279 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9280 {
0d5ed153 9281 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9282 struct remote_state *rs;
bba74b36 9283 char *p, *endbuf;
7c0f6dcc 9284 int bpsize;
4fff2411 9285
28439a30
PA
9286 /* Make sure the remote is pointing at the right process, if
9287 necessary. */
9288 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9289 set_general_process ();
9290
a1dcb23a 9291 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
9292
9293 rs = get_remote_state ();
9294 p = rs->buf;
bba74b36 9295 endbuf = rs->buf + get_remote_packet_size ();
802188a7 9296
96baa820
JM
9297 *(p++) = 'Z';
9298 *(p++) = '0';
9299 *(p++) = ',';
7c0f6dcc 9300 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 9301 p += hexnumstr (p, addr);
bba74b36 9302 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 9303
efcc2da7 9304 if (remote_supports_cond_breakpoints (ops))
bba74b36 9305 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9306
78eff0ec 9307 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
9308 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9309
6d820c5c
DJ
9310 putpkt (rs->buf);
9311 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9312
6d820c5c 9313 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 9314 {
d471ea57
AC
9315 case PACKET_ERROR:
9316 return -1;
9317 case PACKET_OK:
7c0f6dcc
JL
9318 bp_tgt->placed_address = addr;
9319 bp_tgt->placed_size = bpsize;
d471ea57
AC
9320 return 0;
9321 case PACKET_UNKNOWN:
9322 break;
96baa820
JM
9323 }
9324 }
c906108c 9325
0000e5cc
PA
9326 /* If this breakpoint has target-side commands but this stub doesn't
9327 support Z0 packets, throw error. */
9328 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9329 throw_error (NOT_SUPPORTED_ERROR, _("\
9330Target doesn't support breakpoints that have target side commands."));
9331
3db08215 9332 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9333}
9334
9335static int
3db08215
MM
9336remote_remove_breakpoint (struct target_ops *ops,
9337 struct gdbarch *gdbarch,
a6d9a66e 9338 struct bp_target_info *bp_tgt)
c906108c 9339{
8181d85f 9340 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 9341 struct remote_state *rs = get_remote_state ();
96baa820 9342
4082afcc 9343 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9344 {
6d820c5c 9345 char *p = rs->buf;
bba74b36 9346 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 9347
28439a30
PA
9348 /* Make sure the remote is pointing at the right process, if
9349 necessary. */
9350 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9351 set_general_process ();
9352
96baa820
JM
9353 *(p++) = 'z';
9354 *(p++) = '0';
9355 *(p++) = ',';
9356
8181d85f
DJ
9357 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9358 p += hexnumstr (p, addr);
bba74b36 9359 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 9360
6d820c5c
DJ
9361 putpkt (rs->buf);
9362 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9363
6d820c5c 9364 return (rs->buf[0] == 'E');
96baa820
JM
9365 }
9366
3db08215 9367 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9368}
9369
f486487f 9370static enum Z_packet_type
d471ea57
AC
9371watchpoint_to_Z_packet (int type)
9372{
9373 switch (type)
9374 {
9375 case hw_write:
bb858e6a 9376 return Z_PACKET_WRITE_WP;
d471ea57
AC
9377 break;
9378 case hw_read:
bb858e6a 9379 return Z_PACKET_READ_WP;
d471ea57
AC
9380 break;
9381 case hw_access:
bb858e6a 9382 return Z_PACKET_ACCESS_WP;
d471ea57
AC
9383 break;
9384 default:
8e65ff28 9385 internal_error (__FILE__, __LINE__,
e2e0b3e5 9386 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
9387 }
9388}
9389
3c3bea1c 9390static int
f486487f
SM
9391remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9392 enum target_hw_bp_type type, struct expression *cond)
96baa820 9393{
d01949b6 9394 struct remote_state *rs = get_remote_state ();
bba74b36 9395 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9396 char *p;
d471ea57 9397 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 9398
4082afcc 9399 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 9400 return 1;
802188a7 9401
28439a30
PA
9402 /* Make sure the remote is pointing at the right process, if
9403 necessary. */
9404 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9405 set_general_process ();
9406
bba74b36 9407 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 9408 p = strchr (rs->buf, '\0');
96baa820
JM
9409 addr = remote_address_masked (addr);
9410 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9411 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 9412
6d820c5c
DJ
9413 putpkt (rs->buf);
9414 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9415
6d820c5c 9416 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9417 {
9418 case PACKET_ERROR:
d471ea57 9419 return -1;
85d721b8
PA
9420 case PACKET_UNKNOWN:
9421 return 1;
d471ea57
AC
9422 case PACKET_OK:
9423 return 0;
9424 }
8e65ff28 9425 internal_error (__FILE__, __LINE__,
e2e0b3e5 9426 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
9427}
9428
283002cf
MR
9429static int
9430remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9431 CORE_ADDR start, int length)
9432{
9433 CORE_ADDR diff = remote_address_masked (addr - start);
9434
9435 return diff < length;
9436}
9437
d471ea57 9438
3c3bea1c 9439static int
f486487f
SM
9440remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9441 enum target_hw_bp_type type, struct expression *cond)
96baa820 9442{
d01949b6 9443 struct remote_state *rs = get_remote_state ();
bba74b36 9444 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9445 char *p;
d471ea57
AC
9446 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9447
4082afcc 9448 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 9449 return -1;
802188a7 9450
28439a30
PA
9451 /* Make sure the remote is pointing at the right process, if
9452 necessary. */
9453 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9454 set_general_process ();
9455
bba74b36 9456 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 9457 p = strchr (rs->buf, '\0');
96baa820
JM
9458 addr = remote_address_masked (addr);
9459 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9460 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
9461 putpkt (rs->buf);
9462 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9463
6d820c5c 9464 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9465 {
9466 case PACKET_ERROR:
9467 case PACKET_UNKNOWN:
9468 return -1;
9469 case PACKET_OK:
9470 return 0;
9471 }
8e65ff28 9472 internal_error (__FILE__, __LINE__,
e2e0b3e5 9473 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
9474}
9475
3c3bea1c 9476
501eef12 9477int remote_hw_watchpoint_limit = -1;
480a3f21 9478int remote_hw_watchpoint_length_limit = -1;
501eef12 9479int remote_hw_breakpoint_limit = -1;
d471ea57 9480
480a3f21 9481static int
31568a15
TT
9482remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9483 CORE_ADDR addr, int len)
480a3f21
PW
9484{
9485 if (remote_hw_watchpoint_length_limit == 0)
9486 return 0;
9487 else if (remote_hw_watchpoint_length_limit < 0)
9488 return 1;
9489 else if (len <= remote_hw_watchpoint_length_limit)
9490 return 1;
9491 else
9492 return 0;
9493}
9494
b9362cc7 9495static int
5461485a 9496remote_check_watch_resources (struct target_ops *self,
f486487f 9497 enum bptype type, int cnt, int ot)
96baa820 9498{
3c3bea1c
GS
9499 if (type == bp_hardware_breakpoint)
9500 {
9501 if (remote_hw_breakpoint_limit == 0)
9502 return 0;
501eef12
AC
9503 else if (remote_hw_breakpoint_limit < 0)
9504 return 1;
3c3bea1c
GS
9505 else if (cnt <= remote_hw_breakpoint_limit)
9506 return 1;
9507 }
9508 else
9509 {
9510 if (remote_hw_watchpoint_limit == 0)
9511 return 0;
501eef12
AC
9512 else if (remote_hw_watchpoint_limit < 0)
9513 return 1;
3c3bea1c
GS
9514 else if (ot)
9515 return -1;
9516 else if (cnt <= remote_hw_watchpoint_limit)
9517 return 1;
9518 }
9519 return -1;
9520}
9521
f7e6eed5
PA
9522/* The to_stopped_by_sw_breakpoint method of target remote. */
9523
9524static int
9525remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9526{
799a2abe 9527 struct thread_info *thread = inferior_thread ();
f7e6eed5 9528
799a2abe
PA
9529 return (thread->priv != NULL
9530 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
f7e6eed5
PA
9531}
9532
9533/* The to_supports_stopped_by_sw_breakpoint method of target
9534 remote. */
9535
9536static int
9537remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9538{
f7e6eed5
PA
9539 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9540}
9541
9542/* The to_stopped_by_hw_breakpoint method of target remote. */
9543
9544static int
9545remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9546{
799a2abe 9547 struct thread_info *thread = inferior_thread ();
f7e6eed5 9548
799a2abe
PA
9549 return (thread->priv != NULL
9550 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
f7e6eed5
PA
9551}
9552
9553/* The to_supports_stopped_by_hw_breakpoint method of target
9554 remote. */
9555
9556static int
9557remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9558{
f7e6eed5
PA
9559 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9560}
9561
b9362cc7 9562static int
6a109b6b 9563remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 9564{
799a2abe 9565 struct thread_info *thread = inferior_thread ();
ee154bee 9566
799a2abe
PA
9567 return (thread->priv != NULL
9568 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
3c3bea1c
GS
9569}
9570
4aa7a7f5
JJ
9571static int
9572remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 9573{
799a2abe 9574 struct thread_info *thread = inferior_thread ();
a744cf53 9575
799a2abe
PA
9576 if (thread->priv != NULL
9577 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
4aa7a7f5 9578 {
799a2abe
PA
9579 *addr_p = thread->priv->watch_data_address;
9580 return 1;
4aa7a7f5
JJ
9581 }
9582
799a2abe 9583 return 0;
3c3bea1c
GS
9584}
9585
9586
9587static int
23a26771 9588remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9589 struct bp_target_info *bp_tgt)
3c3bea1c 9590{
0d5ed153 9591 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9592 struct remote_state *rs;
bba74b36 9593 char *p, *endbuf;
dd61ec5c 9594 char *message;
0d5ed153 9595 int bpsize;
802188a7 9596
c8189ed1 9597 /* The length field should be set to the size of a breakpoint
8181d85f 9598 instruction, even though we aren't inserting one ourselves. */
c8189ed1 9599
0d5ed153 9600 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 9601
4082afcc 9602 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9603 return -1;
2bc416ba 9604
28439a30
PA
9605 /* Make sure the remote is pointing at the right process, if
9606 necessary. */
9607 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9608 set_general_process ();
9609
4fff2411
JZ
9610 rs = get_remote_state ();
9611 p = rs->buf;
bba74b36 9612 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 9613
96baa820
JM
9614 *(p++) = 'Z';
9615 *(p++) = '1';
9616 *(p++) = ',';
802188a7 9617
0d5ed153 9618 addr = remote_address_masked (addr);
96baa820 9619 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 9620 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 9621
efcc2da7 9622 if (remote_supports_cond_breakpoints (self))
bba74b36 9623 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9624
78eff0ec 9625 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
9626 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9627
6d820c5c
DJ
9628 putpkt (rs->buf);
9629 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9630
6d820c5c 9631 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9632 {
9633 case PACKET_ERROR:
dd61ec5c
MW
9634 if (rs->buf[1] == '.')
9635 {
9636 message = strchr (rs->buf + 2, '.');
9637 if (message)
0316657e 9638 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
9639 }
9640 return -1;
d471ea57
AC
9641 case PACKET_UNKNOWN:
9642 return -1;
9643 case PACKET_OK:
0d5ed153
MR
9644 bp_tgt->placed_address = addr;
9645 bp_tgt->placed_size = bpsize;
d471ea57
AC
9646 return 0;
9647 }
8e65ff28 9648 internal_error (__FILE__, __LINE__,
e2e0b3e5 9649 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
9650}
9651
d471ea57 9652
802188a7 9653static int
a64dc96c 9654remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9655 struct bp_target_info *bp_tgt)
96baa820 9656{
8181d85f 9657 CORE_ADDR addr;
d01949b6 9658 struct remote_state *rs = get_remote_state ();
6d820c5c 9659 char *p = rs->buf;
bba74b36 9660 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 9661
4082afcc 9662 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9663 return -1;
802188a7 9664
28439a30
PA
9665 /* Make sure the remote is pointing at the right process, if
9666 necessary. */
9667 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9668 set_general_process ();
9669
96baa820
JM
9670 *(p++) = 'z';
9671 *(p++) = '1';
9672 *(p++) = ',';
802188a7 9673
8181d85f 9674 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 9675 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9676 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 9677
6d820c5c
DJ
9678 putpkt (rs->buf);
9679 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 9680
6d820c5c 9681 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9682 {
9683 case PACKET_ERROR:
9684 case PACKET_UNKNOWN:
9685 return -1;
9686 case PACKET_OK:
9687 return 0;
9688 }
8e65ff28 9689 internal_error (__FILE__, __LINE__,
e2e0b3e5 9690 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 9691}
96baa820 9692
4a5e7a5b
PA
9693/* Verify memory using the "qCRC:" request. */
9694
9695static int
9696remote_verify_memory (struct target_ops *ops,
9697 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9698{
9699 struct remote_state *rs = get_remote_state ();
9700 unsigned long host_crc, target_crc;
9701 char *tmp;
9702
936d2992
PA
9703 /* It doesn't make sense to use qCRC if the remote target is
9704 connected but not running. */
9705 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9706 {
9707 enum packet_result result;
28439a30 9708
936d2992
PA
9709 /* Make sure the remote is pointing at the right process. */
9710 set_general_process ();
4a5e7a5b 9711
936d2992
PA
9712 /* FIXME: assumes lma can fit into long. */
9713 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9714 (long) lma, (long) size);
9715 putpkt (rs->buf);
4a5e7a5b 9716
936d2992
PA
9717 /* Be clever; compute the host_crc before waiting for target
9718 reply. */
9719 host_crc = xcrc32 (data, size, 0xffffffff);
9720
9721 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 9722
936d2992
PA
9723 result = packet_ok (rs->buf,
9724 &remote_protocol_packets[PACKET_qCRC]);
9725 if (result == PACKET_ERROR)
9726 return -1;
9727 else if (result == PACKET_OK)
9728 {
9729 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9730 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 9731
936d2992
PA
9732 return (host_crc == target_crc);
9733 }
9734 }
4a5e7a5b 9735
936d2992 9736 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
9737}
9738
c906108c
SS
9739/* compare-sections command
9740
9741 With no arguments, compares each loadable section in the exec bfd
9742 with the same memory range on the target, and reports mismatches.
4a5e7a5b 9743 Useful for verifying the image on the target against the exec file. */
e514a9d6 9744
c906108c 9745static void
fba45db2 9746compare_sections_command (char *args, int from_tty)
c906108c
SS
9747{
9748 asection *s;
c906108c 9749 struct cleanup *old_chain;
948f8e3d 9750 gdb_byte *sectdata;
ce359b09 9751 const char *sectname;
c906108c
SS
9752 bfd_size_type size;
9753 bfd_vma lma;
9754 int matched = 0;
9755 int mismatched = 0;
4a5e7a5b 9756 int res;
95cf3b38 9757 int read_only = 0;
c906108c
SS
9758
9759 if (!exec_bfd)
8a3fe4f8 9760 error (_("command cannot be used without an exec file"));
c906108c 9761
28439a30
PA
9762 /* Make sure the remote is pointing at the right process. */
9763 set_general_process ();
9764
95cf3b38
DT
9765 if (args != NULL && strcmp (args, "-r") == 0)
9766 {
9767 read_only = 1;
9768 args = NULL;
9769 }
9770
c5aa993b 9771 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
9772 {
9773 if (!(s->flags & SEC_LOAD))
0df8b418 9774 continue; /* Skip non-loadable section. */
c906108c 9775
95cf3b38
DT
9776 if (read_only && (s->flags & SEC_READONLY) == 0)
9777 continue; /* Skip writeable sections */
9778
2c500098 9779 size = bfd_get_section_size (s);
c906108c 9780 if (size == 0)
0df8b418 9781 continue; /* Skip zero-length section. */
c906108c 9782
ce359b09 9783 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 9784 if (args && strcmp (args, sectname) != 0)
0df8b418 9785 continue; /* Not the section selected by user. */
c906108c 9786
0df8b418 9787 matched = 1; /* Do this section. */
c906108c 9788 lma = s->lma;
c906108c 9789
224c3ddb 9790 sectdata = (gdb_byte *) xmalloc (size);
b8c9b27d 9791 old_chain = make_cleanup (xfree, sectdata);
c906108c 9792 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 9793
4a5e7a5b
PA
9794 res = target_verify_memory (sectdata, lma, size);
9795
9796 if (res == -1)
5af949e3 9797 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
9798 paddress (target_gdbarch (), lma),
9799 paddress (target_gdbarch (), lma + size));
c906108c 9800
5af949e3 9801 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
9802 paddress (target_gdbarch (), lma),
9803 paddress (target_gdbarch (), lma + size));
4a5e7a5b 9804 if (res)
c906108c
SS
9805 printf_filtered ("matched.\n");
9806 else
c5aa993b
JM
9807 {
9808 printf_filtered ("MIS-MATCHED!\n");
9809 mismatched++;
9810 }
c906108c
SS
9811
9812 do_cleanups (old_chain);
9813 }
9814 if (mismatched > 0)
936d2992 9815 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 9816the loaded file\n"));
c906108c 9817 if (args && !matched)
a3f17187 9818 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
9819}
9820
0e7f50da
UW
9821/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9822 into remote target. The number of bytes written to the remote
9823 target is returned, or -1 for error. */
9824
9b409511 9825static enum target_xfer_status
0e7f50da
UW
9826remote_write_qxfer (struct target_ops *ops, const char *object_name,
9827 const char *annex, const gdb_byte *writebuf,
9b409511 9828 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
9829 struct packet_config *packet)
9830{
9831 int i, buf_len;
9832 ULONGEST n;
0e7f50da
UW
9833 struct remote_state *rs = get_remote_state ();
9834 int max_size = get_memory_write_packet_size ();
9835
9836 if (packet->support == PACKET_DISABLE)
2ed4b548 9837 return TARGET_XFER_E_IO;
0e7f50da
UW
9838
9839 /* Insert header. */
9840 i = snprintf (rs->buf, max_size,
9841 "qXfer:%s:write:%s:%s:",
9842 object_name, annex ? annex : "",
9843 phex_nz (offset, sizeof offset));
9844 max_size -= (i + 1);
9845
9846 /* Escape as much data as fits into rs->buf. */
9847 buf_len = remote_escape_output
124e13d9 9848 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
9849
9850 if (putpkt_binary (rs->buf, i + buf_len) < 0
9851 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9852 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9853 return TARGET_XFER_E_IO;
0e7f50da
UW
9854
9855 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
9856
9857 *xfered_len = n;
9858 return TARGET_XFER_OK;
0e7f50da
UW
9859}
9860
0876f84a
DJ
9861/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9862 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9863 number of bytes read is returned, or 0 for EOF, or -1 for error.
9864 The number of bytes read may be less than LEN without indicating an
9865 EOF. PACKET is checked and updated to indicate whether the remote
9866 target supports this object. */
9867
9b409511 9868static enum target_xfer_status
0876f84a
DJ
9869remote_read_qxfer (struct target_ops *ops, const char *object_name,
9870 const char *annex,
9871 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 9872 ULONGEST *xfered_len,
0876f84a
DJ
9873 struct packet_config *packet)
9874{
0876f84a 9875 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
9876 LONGEST i, n, packet_len;
9877
9878 if (packet->support == PACKET_DISABLE)
2ed4b548 9879 return TARGET_XFER_E_IO;
0876f84a
DJ
9880
9881 /* Check whether we've cached an end-of-object packet that matches
9882 this request. */
8e88304f 9883 if (rs->finished_object)
0876f84a 9884 {
8e88304f
TT
9885 if (strcmp (object_name, rs->finished_object) == 0
9886 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9887 && offset == rs->finished_offset)
9b409511
YQ
9888 return TARGET_XFER_EOF;
9889
0876f84a
DJ
9890
9891 /* Otherwise, we're now reading something different. Discard
9892 the cache. */
8e88304f
TT
9893 xfree (rs->finished_object);
9894 xfree (rs->finished_annex);
9895 rs->finished_object = NULL;
9896 rs->finished_annex = NULL;
0876f84a
DJ
9897 }
9898
9899 /* Request only enough to fit in a single packet. The actual data
9900 may not, since we don't know how much of it will need to be escaped;
9901 the target is free to respond with slightly less data. We subtract
9902 five to account for the response type and the protocol frame. */
9903 n = min (get_remote_packet_size () - 5, len);
9904 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9905 object_name, annex ? annex : "",
9906 phex_nz (offset, sizeof offset),
9907 phex_nz (n, sizeof n));
9908 i = putpkt (rs->buf);
9909 if (i < 0)
2ed4b548 9910 return TARGET_XFER_E_IO;
0876f84a
DJ
9911
9912 rs->buf[0] = '\0';
9913 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9914 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9915 return TARGET_XFER_E_IO;
0876f84a
DJ
9916
9917 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9918 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9919
9920 /* 'm' means there is (or at least might be) more data after this
9921 batch. That does not make sense unless there's at least one byte
9922 of data in this reply. */
9923 if (rs->buf[0] == 'm' && packet_len == 1)
9924 error (_("Remote qXfer reply contained no data."));
9925
9926 /* Got some data. */
bc20a4af
PA
9927 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9928 packet_len - 1, readbuf, n);
0876f84a
DJ
9929
9930 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
9931 or possibly empty. If we have the final block of a non-empty
9932 object, record this fact to bypass a subsequent partial read. */
9933 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 9934 {
8e88304f
TT
9935 rs->finished_object = xstrdup (object_name);
9936 rs->finished_annex = xstrdup (annex ? annex : "");
9937 rs->finished_offset = offset + i;
0876f84a
DJ
9938 }
9939
9b409511
YQ
9940 if (i == 0)
9941 return TARGET_XFER_EOF;
9942 else
9943 {
9944 *xfered_len = i;
9945 return TARGET_XFER_OK;
9946 }
0876f84a
DJ
9947}
9948
9b409511 9949static enum target_xfer_status
4b8a223f 9950remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 9951 const char *annex, gdb_byte *readbuf,
9b409511
YQ
9952 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9953 ULONGEST *xfered_len)
c906108c 9954{
82f73884 9955 struct remote_state *rs;
c906108c 9956 int i;
6d820c5c 9957 char *p2;
1e3ff5ad 9958 char query_type;
124e13d9 9959 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 9960
e6e4e701 9961 set_remote_traceframe ();
82f73884
PA
9962 set_general_thread (inferior_ptid);
9963
9964 rs = get_remote_state ();
9965
b2182ed2 9966 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
9967 if (object == TARGET_OBJECT_MEMORY)
9968 {
2d717e4f
DJ
9969 /* If the remote target is connected but not running, we should
9970 pass this request down to a lower stratum (e.g. the executable
9971 file). */
9972 if (!target_has_execution)
9b409511 9973 return TARGET_XFER_EOF;
2d717e4f 9974
21e3b9b9 9975 if (writebuf != NULL)
124e13d9
SM
9976 return remote_write_bytes (offset, writebuf, len, unit_size,
9977 xfered_len);
21e3b9b9 9978 else
124e13d9
SM
9979 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9980 xfered_len);
21e3b9b9
DJ
9981 }
9982
0df8b418 9983 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
9984 if (object == TARGET_OBJECT_SPU)
9985 {
9986 if (readbuf)
9987 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
9988 xfered_len, &remote_protocol_packets
9989 [PACKET_qXfer_spu_read]);
0e7f50da
UW
9990 else
9991 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
9992 xfered_len, &remote_protocol_packets
9993 [PACKET_qXfer_spu_write]);
0e7f50da
UW
9994 }
9995
4aa995e1
PA
9996 /* Handle extra signal info using qxfer packets. */
9997 if (object == TARGET_OBJECT_SIGNAL_INFO)
9998 {
9999 if (readbuf)
10000 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 10001 xfered_len, &remote_protocol_packets
4aa995e1
PA
10002 [PACKET_qXfer_siginfo_read]);
10003 else
3e43a32a 10004 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 10005 writebuf, offset, len, xfered_len,
4aa995e1
PA
10006 &remote_protocol_packets
10007 [PACKET_qXfer_siginfo_write]);
10008 }
10009
0fb4aa4b
PA
10010 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10011 {
10012 if (readbuf)
3e43a32a 10013 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 10014 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
10015 &remote_protocol_packets
10016 [PACKET_qXfer_statictrace_read]);
10017 else
2ed4b548 10018 return TARGET_XFER_E_IO;
0fb4aa4b
PA
10019 }
10020
a76d924d
DJ
10021 /* Only handle flash writes. */
10022 if (writebuf != NULL)
10023 {
a76d924d
DJ
10024 switch (object)
10025 {
10026 case TARGET_OBJECT_FLASH:
9b409511
YQ
10027 return remote_flash_write (ops, offset, len, xfered_len,
10028 writebuf);
a76d924d
DJ
10029
10030 default:
2ed4b548 10031 return TARGET_XFER_E_IO;
a76d924d
DJ
10032 }
10033 }
4b8a223f 10034
1e3ff5ad
AC
10035 /* Map pre-existing objects onto letters. DO NOT do this for new
10036 objects!!! Instead specify new query packets. */
10037 switch (object)
c906108c 10038 {
1e3ff5ad
AC
10039 case TARGET_OBJECT_AVR:
10040 query_type = 'R';
10041 break;
802188a7
RM
10042
10043 case TARGET_OBJECT_AUXV:
0876f84a
DJ
10044 gdb_assert (annex == NULL);
10045 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 10046 xfered_len,
0876f84a 10047 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 10048
23181151
DJ
10049 case TARGET_OBJECT_AVAILABLE_FEATURES:
10050 return remote_read_qxfer
9b409511 10051 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
10052 &remote_protocol_packets[PACKET_qXfer_features]);
10053
cfa9d6d9
DJ
10054 case TARGET_OBJECT_LIBRARIES:
10055 return remote_read_qxfer
9b409511 10056 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
10057 &remote_protocol_packets[PACKET_qXfer_libraries]);
10058
2268b414
JK
10059 case TARGET_OBJECT_LIBRARIES_SVR4:
10060 return remote_read_qxfer
9b409511 10061 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
10062 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10063
fd79ecee
DJ
10064 case TARGET_OBJECT_MEMORY_MAP:
10065 gdb_assert (annex == NULL);
10066 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 10067 xfered_len,
fd79ecee
DJ
10068 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10069
07e059b5
VP
10070 case TARGET_OBJECT_OSDATA:
10071 /* Should only get here if we're connected. */
5d93a237 10072 gdb_assert (rs->remote_desc);
07e059b5 10073 return remote_read_qxfer
9b409511 10074 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
10075 &remote_protocol_packets[PACKET_qXfer_osdata]);
10076
dc146f7c
VP
10077 case TARGET_OBJECT_THREADS:
10078 gdb_assert (annex == NULL);
10079 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 10080 xfered_len,
dc146f7c
VP
10081 &remote_protocol_packets[PACKET_qXfer_threads]);
10082
b3b9301e
PA
10083 case TARGET_OBJECT_TRACEFRAME_INFO:
10084 gdb_assert (annex == NULL);
10085 return remote_read_qxfer
9b409511 10086 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 10087 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
10088
10089 case TARGET_OBJECT_FDPIC:
10090 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 10091 xfered_len,
78d85199 10092 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
10093
10094 case TARGET_OBJECT_OPENVMS_UIB:
10095 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 10096 xfered_len,
169081d0
TG
10097 &remote_protocol_packets[PACKET_qXfer_uib]);
10098
9accd112
MM
10099 case TARGET_OBJECT_BTRACE:
10100 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 10101 xfered_len,
9accd112
MM
10102 &remote_protocol_packets[PACKET_qXfer_btrace]);
10103
f4abbc16
MM
10104 case TARGET_OBJECT_BTRACE_CONF:
10105 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10106 len, xfered_len,
10107 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10108
c78fa86a
GB
10109 case TARGET_OBJECT_EXEC_FILE:
10110 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10111 len, xfered_len,
10112 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10113
1e3ff5ad 10114 default:
2ed4b548 10115 return TARGET_XFER_E_IO;
c906108c
SS
10116 }
10117
0df8b418 10118 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 10119 large enough let the caller deal with it. */
ea9c271d 10120 if (len < get_remote_packet_size ())
2ed4b548 10121 return TARGET_XFER_E_IO;
ea9c271d 10122 len = get_remote_packet_size ();
1e3ff5ad 10123
23860348 10124 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 10125 if (!rs->remote_desc)
8a3fe4f8 10126 error (_("remote query is only available after target open"));
c906108c 10127
1e3ff5ad 10128 gdb_assert (annex != NULL);
4b8a223f 10129 gdb_assert (readbuf != NULL);
c906108c 10130
6d820c5c 10131 p2 = rs->buf;
c906108c
SS
10132 *p2++ = 'q';
10133 *p2++ = query_type;
10134
23860348
MS
10135 /* We used one buffer char for the remote protocol q command and
10136 another for the query type. As the remote protocol encapsulation
10137 uses 4 chars plus one extra in case we are debugging
10138 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10139 string. */
c906108c 10140 i = 0;
ea9c271d 10141 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 10142 {
1e3ff5ad
AC
10143 /* Bad caller may have sent forbidden characters. */
10144 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10145 *p2++ = annex[i];
c906108c
SS
10146 i++;
10147 }
1e3ff5ad
AC
10148 *p2 = '\0';
10149 gdb_assert (annex[i] == '\0');
c906108c 10150
6d820c5c 10151 i = putpkt (rs->buf);
c5aa993b 10152 if (i < 0)
2ed4b548 10153 return TARGET_XFER_E_IO;
c906108c 10154
6d820c5c
DJ
10155 getpkt (&rs->buf, &rs->buf_size, 0);
10156 strcpy ((char *) readbuf, rs->buf);
c906108c 10157
9b409511
YQ
10158 *xfered_len = strlen ((char *) readbuf);
10159 return TARGET_XFER_OK;
c906108c
SS
10160}
10161
09c98b44
DB
10162/* Implementation of to_get_memory_xfer_limit. */
10163
10164static ULONGEST
10165remote_get_memory_xfer_limit (struct target_ops *ops)
10166{
10167 return get_memory_write_packet_size ();
10168}
10169
08388c79
DE
10170static int
10171remote_search_memory (struct target_ops* ops,
10172 CORE_ADDR start_addr, ULONGEST search_space_len,
10173 const gdb_byte *pattern, ULONGEST pattern_len,
10174 CORE_ADDR *found_addrp)
10175{
f5656ead 10176 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
10177 struct remote_state *rs = get_remote_state ();
10178 int max_size = get_memory_write_packet_size ();
10179 struct packet_config *packet =
10180 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
10181 /* Number of packet bytes used to encode the pattern;
10182 this could be more than PATTERN_LEN due to escape characters. */
08388c79 10183 int escaped_pattern_len;
0df8b418 10184 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
10185 int used_pattern_len;
10186 int i;
10187 int found;
10188 ULONGEST found_addr;
10189
10190 /* Don't go to the target if we don't have to.
10191 This is done before checking packet->support to avoid the possibility that
10192 a success for this edge case means the facility works in general. */
10193 if (pattern_len > search_space_len)
10194 return 0;
10195 if (pattern_len == 0)
10196 {
10197 *found_addrp = start_addr;
10198 return 1;
10199 }
10200
10201 /* If we already know the packet isn't supported, fall back to the simple
10202 way of searching memory. */
10203
4082afcc 10204 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
10205 {
10206 /* Target doesn't provided special support, fall back and use the
10207 standard support (copy memory and do the search here). */
10208 return simple_search_memory (ops, start_addr, search_space_len,
10209 pattern, pattern_len, found_addrp);
10210 }
10211
28439a30
PA
10212 /* Make sure the remote is pointing at the right process. */
10213 set_general_process ();
10214
08388c79
DE
10215 /* Insert header. */
10216 i = snprintf (rs->buf, max_size,
10217 "qSearch:memory:%s;%s;",
5af949e3 10218 phex_nz (start_addr, addr_size),
08388c79
DE
10219 phex_nz (search_space_len, sizeof (search_space_len)));
10220 max_size -= (i + 1);
10221
10222 /* Escape as much data as fits into rs->buf. */
10223 escaped_pattern_len =
124e13d9 10224 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
10225 &used_pattern_len, max_size);
10226
10227 /* Bail if the pattern is too large. */
10228 if (used_pattern_len != pattern_len)
9b20d036 10229 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
10230
10231 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10232 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10233 || packet_ok (rs->buf, packet) != PACKET_OK)
10234 {
10235 /* The request may not have worked because the command is not
10236 supported. If so, fall back to the simple way. */
10237 if (packet->support == PACKET_DISABLE)
10238 {
10239 return simple_search_memory (ops, start_addr, search_space_len,
10240 pattern, pattern_len, found_addrp);
10241 }
10242 return -1;
10243 }
10244
10245 if (rs->buf[0] == '0')
10246 found = 0;
10247 else if (rs->buf[0] == '1')
10248 {
10249 found = 1;
10250 if (rs->buf[1] != ',')
10e0fa18 10251 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10252 unpack_varlen_hex (rs->buf + 2, &found_addr);
10253 *found_addrp = found_addr;
10254 }
10255 else
10e0fa18 10256 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10257
10258 return found;
10259}
10260
96baa820 10261static void
a30bf1f1 10262remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 10263 struct ui_file *outbuf)
96baa820 10264{
d01949b6 10265 struct remote_state *rs = get_remote_state ();
2e9f7625 10266 char *p = rs->buf;
96baa820 10267
5d93a237 10268 if (!rs->remote_desc)
8a3fe4f8 10269 error (_("remote rcmd is only available after target open"));
96baa820 10270
23860348 10271 /* Send a NULL command across as an empty command. */
7be570e7
JM
10272 if (command == NULL)
10273 command = "";
10274
23860348 10275 /* The query prefix. */
2e9f7625
DJ
10276 strcpy (rs->buf, "qRcmd,");
10277 p = strchr (rs->buf, '\0');
96baa820 10278
3e43a32a
MS
10279 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10280 > get_remote_packet_size ())
8a3fe4f8 10281 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 10282
23860348 10283 /* Encode the actual command. */
a30bf1f1 10284 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 10285
6d820c5c 10286 if (putpkt (rs->buf) < 0)
8a3fe4f8 10287 error (_("Communication problem with target."));
96baa820
JM
10288
10289 /* get/display the response */
10290 while (1)
10291 {
2e9f7625
DJ
10292 char *buf;
10293
00bf0b85 10294 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 10295 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 10296 rs->buf[0] = '\0';
5b37825d
PW
10297 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10298 {
10299 /* Timeout. Continue to (try to) read responses.
10300 This is better than stopping with an error, assuming the stub
10301 is still executing the (long) monitor command.
10302 If needed, the user can interrupt gdb using C-c, obtaining
10303 an effect similar to stop on timeout. */
10304 continue;
10305 }
2e9f7625 10306 buf = rs->buf;
96baa820 10307 if (buf[0] == '\0')
8a3fe4f8 10308 error (_("Target does not support this command."));
96baa820
JM
10309 if (buf[0] == 'O' && buf[1] != 'K')
10310 {
23860348 10311 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
10312 continue;
10313 }
10314 if (strcmp (buf, "OK") == 0)
10315 break;
7be570e7
JM
10316 if (strlen (buf) == 3 && buf[0] == 'E'
10317 && isdigit (buf[1]) && isdigit (buf[2]))
10318 {
8a3fe4f8 10319 error (_("Protocol error with Rcmd"));
7be570e7 10320 }
96baa820
JM
10321 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10322 {
10323 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 10324
96baa820
JM
10325 fputc_unfiltered (c, outbuf);
10326 }
10327 break;
10328 }
10329}
10330
fd79ecee
DJ
10331static VEC(mem_region_s) *
10332remote_memory_map (struct target_ops *ops)
10333{
10334 VEC(mem_region_s) *result = NULL;
10335 char *text = target_read_stralloc (&current_target,
10336 TARGET_OBJECT_MEMORY_MAP, NULL);
10337
10338 if (text)
10339 {
10340 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 10341
fd79ecee
DJ
10342 result = parse_memory_map (text);
10343 do_cleanups (back_to);
10344 }
10345
10346 return result;
10347}
10348
c906108c 10349static void
fba45db2 10350packet_command (char *args, int from_tty)
c906108c 10351{
d01949b6 10352 struct remote_state *rs = get_remote_state ();
c906108c 10353
5d93a237 10354 if (!rs->remote_desc)
8a3fe4f8 10355 error (_("command can only be used with remote target"));
c906108c 10356
c5aa993b 10357 if (!args)
8a3fe4f8 10358 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
10359
10360 puts_filtered ("sending: ");
10361 print_packet (args);
10362 puts_filtered ("\n");
10363 putpkt (args);
10364
6d820c5c 10365 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 10366 puts_filtered ("received: ");
6d820c5c 10367 print_packet (rs->buf);
c906108c
SS
10368 puts_filtered ("\n");
10369}
10370
10371#if 0
23860348 10372/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 10373
a14ed312 10374static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 10375
a14ed312 10376static void threadset_test_cmd (char *cmd, int tty);
c906108c 10377
a14ed312 10378static void threadalive_test (char *cmd, int tty);
c906108c 10379
a14ed312 10380static void threadlist_test_cmd (char *cmd, int tty);
c906108c 10381
23860348 10382int get_and_display_threadinfo (threadref *ref);
c906108c 10383
a14ed312 10384static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 10385
23860348 10386static int thread_display_step (threadref *ref, void *context);
c906108c 10387
a14ed312 10388static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 10389
a14ed312 10390static void init_remote_threadtests (void);
c906108c 10391
23860348 10392#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
10393
10394static void
fba45db2 10395threadset_test_cmd (char *cmd, int tty)
c906108c
SS
10396{
10397 int sample_thread = SAMPLE_THREAD;
10398
a3f17187 10399 printf_filtered (_("Remote threadset test\n"));
79d7f229 10400 set_general_thread (sample_thread);
c906108c
SS
10401}
10402
10403
10404static void
fba45db2 10405threadalive_test (char *cmd, int tty)
c906108c
SS
10406{
10407 int sample_thread = SAMPLE_THREAD;
79d7f229 10408 int pid = ptid_get_pid (inferior_ptid);
ba348170 10409 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 10410
79d7f229 10411 if (remote_thread_alive (ptid))
c906108c
SS
10412 printf_filtered ("PASS: Thread alive test\n");
10413 else
10414 printf_filtered ("FAIL: Thread alive test\n");
10415}
10416
23860348 10417void output_threadid (char *title, threadref *ref);
c906108c
SS
10418
10419void
fba45db2 10420output_threadid (char *title, threadref *ref)
c906108c
SS
10421{
10422 char hexid[20];
10423
23860348 10424 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
10425 hexid[16] = 0;
10426 printf_filtered ("%s %s\n", title, (&hexid[0]));
10427}
10428
10429static void
fba45db2 10430threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
10431{
10432 int startflag = 1;
10433 threadref nextthread;
10434 int done, result_count;
10435 threadref threadlist[3];
10436
10437 printf_filtered ("Remote Threadlist test\n");
10438 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10439 &result_count, &threadlist[0]))
10440 printf_filtered ("FAIL: threadlist test\n");
10441 else
10442 {
10443 threadref *scan = threadlist;
10444 threadref *limit = scan + result_count;
10445
10446 while (scan < limit)
10447 output_threadid (" thread ", scan++);
10448 }
10449}
10450
10451void
fba45db2 10452display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
10453{
10454 output_threadid ("Threadid: ", &info->threadid);
10455 printf_filtered ("Name: %s\n ", info->shortname);
10456 printf_filtered ("State: %s\n", info->display);
10457 printf_filtered ("other: %s\n\n", info->more_display);
10458}
10459
10460int
fba45db2 10461get_and_display_threadinfo (threadref *ref)
c906108c
SS
10462{
10463 int result;
10464 int set;
10465 struct gdb_ext_thread_info threadinfo;
10466
10467 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10468 | TAG_MOREDISPLAY | TAG_DISPLAY;
10469 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10470 display_thread_info (&threadinfo);
10471 return result;
10472}
10473
10474static void
fba45db2 10475threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
10476{
10477 int athread = SAMPLE_THREAD;
10478 threadref thread;
10479 int set;
10480
10481 int_to_threadref (&thread, athread);
10482 printf_filtered ("Remote Threadinfo test\n");
10483 if (!get_and_display_threadinfo (&thread))
10484 printf_filtered ("FAIL cannot get thread info\n");
10485}
10486
10487static int
fba45db2 10488thread_display_step (threadref *ref, void *context)
c906108c
SS
10489{
10490 /* output_threadid(" threadstep ",ref); *//* simple test */
10491 return get_and_display_threadinfo (ref);
10492}
10493
10494static void
fba45db2 10495threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
10496{
10497 printf_filtered ("Remote Threadlist update test\n");
10498 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10499}
10500
10501static void
10502init_remote_threadtests (void)
10503{
3e43a32a
MS
10504 add_com ("tlist", class_obscure, threadlist_test_cmd,
10505 _("Fetch and print the remote list of "
10506 "thread identifiers, one pkt only"));
c906108c 10507 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 10508 _("Fetch and display info about one thread"));
c906108c 10509 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 10510 _("Test setting to a different thread"));
c906108c 10511 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 10512 _("Iterate through updating all remote thread info"));
c906108c 10513 add_com ("talive", class_obscure, threadalive_test,
1bedd215 10514 _(" Remote thread alive test "));
c906108c
SS
10515}
10516
10517#endif /* 0 */
10518
f3fb8c85
MS
10519/* Convert a thread ID to a string. Returns the string in a static
10520 buffer. */
10521
10522static char *
117de6a9 10523remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 10524{
79d7f229 10525 static char buf[64];
82f73884 10526 struct remote_state *rs = get_remote_state ();
f3fb8c85 10527
7cee1e54
PA
10528 if (ptid_equal (ptid, null_ptid))
10529 return normal_pid_to_str (ptid);
10530 else if (ptid_is_pid (ptid))
ecd0ada5
PA
10531 {
10532 /* Printing an inferior target id. */
10533
10534 /* When multi-process extensions are off, there's no way in the
10535 remote protocol to know the remote process id, if there's any
10536 at all. There's one exception --- when we're connected with
10537 target extended-remote, and we manually attached to a process
10538 with "attach PID". We don't record anywhere a flag that
10539 allows us to distinguish that case from the case of
10540 connecting with extended-remote and the stub already being
10541 attached to a process, and reporting yes to qAttached, hence
10542 no smart special casing here. */
10543 if (!remote_multi_process_p (rs))
10544 {
10545 xsnprintf (buf, sizeof buf, "Remote target");
10546 return buf;
10547 }
10548
10549 return normal_pid_to_str (ptid);
82f73884 10550 }
ecd0ada5 10551 else
79d7f229 10552 {
ecd0ada5
PA
10553 if (ptid_equal (magic_null_ptid, ptid))
10554 xsnprintf (buf, sizeof buf, "Thread <main>");
8020350c 10555 else if (remote_multi_process_p (rs))
de0d863e
DB
10556 if (ptid_get_lwp (ptid) == 0)
10557 return normal_pid_to_str (ptid);
10558 else
10559 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10560 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
10561 else
10562 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 10563 ptid_get_lwp (ptid));
79d7f229
PA
10564 return buf;
10565 }
f3fb8c85
MS
10566}
10567
38691318
KB
10568/* Get the address of the thread local variable in OBJFILE which is
10569 stored at OFFSET within the thread local storage for thread PTID. */
10570
10571static CORE_ADDR
117de6a9
PA
10572remote_get_thread_local_address (struct target_ops *ops,
10573 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 10574{
4082afcc 10575 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
10576 {
10577 struct remote_state *rs = get_remote_state ();
6d820c5c 10578 char *p = rs->buf;
82f73884 10579 char *endp = rs->buf + get_remote_packet_size ();
571dd617 10580 enum packet_result result;
38691318
KB
10581
10582 strcpy (p, "qGetTLSAddr:");
10583 p += strlen (p);
82f73884 10584 p = write_ptid (p, endp, ptid);
38691318
KB
10585 *p++ = ',';
10586 p += hexnumstr (p, offset);
10587 *p++ = ',';
10588 p += hexnumstr (p, lm);
10589 *p++ = '\0';
10590
6d820c5c
DJ
10591 putpkt (rs->buf);
10592 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
10593 result = packet_ok (rs->buf,
10594 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 10595 if (result == PACKET_OK)
38691318
KB
10596 {
10597 ULONGEST result;
10598
6d820c5c 10599 unpack_varlen_hex (rs->buf, &result);
38691318
KB
10600 return result;
10601 }
571dd617 10602 else if (result == PACKET_UNKNOWN)
109c3e39
AC
10603 throw_error (TLS_GENERIC_ERROR,
10604 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 10605 else
109c3e39
AC
10606 throw_error (TLS_GENERIC_ERROR,
10607 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
10608 }
10609 else
109c3e39
AC
10610 throw_error (TLS_GENERIC_ERROR,
10611 _("TLS not supported or disabled on this target"));
38691318
KB
10612 /* Not reached. */
10613 return 0;
10614}
10615
711e434b
PM
10616/* Provide thread local base, i.e. Thread Information Block address.
10617 Returns 1 if ptid is found and thread_local_base is non zero. */
10618
70221824 10619static int
bd7ae0f5 10620remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 10621{
4082afcc 10622 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
10623 {
10624 struct remote_state *rs = get_remote_state ();
10625 char *p = rs->buf;
10626 char *endp = rs->buf + get_remote_packet_size ();
10627 enum packet_result result;
10628
10629 strcpy (p, "qGetTIBAddr:");
10630 p += strlen (p);
10631 p = write_ptid (p, endp, ptid);
10632 *p++ = '\0';
10633
10634 putpkt (rs->buf);
10635 getpkt (&rs->buf, &rs->buf_size, 0);
10636 result = packet_ok (rs->buf,
10637 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10638 if (result == PACKET_OK)
10639 {
10640 ULONGEST result;
10641
10642 unpack_varlen_hex (rs->buf, &result);
10643 if (addr)
10644 *addr = (CORE_ADDR) result;
10645 return 1;
10646 }
10647 else if (result == PACKET_UNKNOWN)
10648 error (_("Remote target doesn't support qGetTIBAddr packet"));
10649 else
10650 error (_("Remote target failed to process qGetTIBAddr request"));
10651 }
10652 else
10653 error (_("qGetTIBAddr not supported or disabled on this target"));
10654 /* Not reached. */
10655 return 0;
10656}
10657
29709017
DJ
10658/* Support for inferring a target description based on the current
10659 architecture and the size of a 'g' packet. While the 'g' packet
10660 can have any size (since optional registers can be left off the
10661 end), some sizes are easily recognizable given knowledge of the
10662 approximate architecture. */
10663
10664struct remote_g_packet_guess
10665{
10666 int bytes;
10667 const struct target_desc *tdesc;
10668};
10669typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10670DEF_VEC_O(remote_g_packet_guess_s);
10671
10672struct remote_g_packet_data
10673{
10674 VEC(remote_g_packet_guess_s) *guesses;
10675};
10676
10677static struct gdbarch_data *remote_g_packet_data_handle;
10678
10679static void *
10680remote_g_packet_data_init (struct obstack *obstack)
10681{
10682 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10683}
10684
10685void
10686register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10687 const struct target_desc *tdesc)
10688{
10689 struct remote_g_packet_data *data
19ba03f4
SM
10690 = ((struct remote_g_packet_data *)
10691 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
10692 struct remote_g_packet_guess new_guess, *guess;
10693 int ix;
10694
10695 gdb_assert (tdesc != NULL);
10696
10697 for (ix = 0;
10698 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10699 ix++)
10700 if (guess->bytes == bytes)
10701 internal_error (__FILE__, __LINE__,
9b20d036 10702 _("Duplicate g packet description added for size %d"),
29709017
DJ
10703 bytes);
10704
10705 new_guess.bytes = bytes;
10706 new_guess.tdesc = tdesc;
10707 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10708}
10709
d962ef82
DJ
10710/* Return 1 if remote_read_description would do anything on this target
10711 and architecture, 0 otherwise. */
10712
10713static int
10714remote_read_description_p (struct target_ops *target)
10715{
10716 struct remote_g_packet_data *data
19ba03f4
SM
10717 = ((struct remote_g_packet_data *)
10718 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
10719
10720 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10721 return 1;
10722
10723 return 0;
10724}
10725
29709017
DJ
10726static const struct target_desc *
10727remote_read_description (struct target_ops *target)
10728{
10729 struct remote_g_packet_data *data
19ba03f4
SM
10730 = ((struct remote_g_packet_data *)
10731 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 10732
d962ef82
DJ
10733 /* Do not try this during initial connection, when we do not know
10734 whether there is a running but stopped thread. */
10735 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 10736 return target->beneath->to_read_description (target->beneath);
d962ef82 10737
29709017
DJ
10738 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10739 {
10740 struct remote_g_packet_guess *guess;
10741 int ix;
10742 int bytes = send_g_packet ();
10743
10744 for (ix = 0;
10745 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10746 ix++)
10747 if (guess->bytes == bytes)
10748 return guess->tdesc;
10749
10750 /* We discard the g packet. A minor optimization would be to
10751 hold on to it, and fill the register cache once we have selected
10752 an architecture, but it's too tricky to do safely. */
10753 }
10754
2117c711 10755 return target->beneath->to_read_description (target->beneath);
29709017
DJ
10756}
10757
a6b151f1
DJ
10758/* Remote file transfer support. This is host-initiated I/O, not
10759 target-initiated; for target-initiated, see remote-fileio.c. */
10760
10761/* If *LEFT is at least the length of STRING, copy STRING to
10762 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10763 decrease *LEFT. Otherwise raise an error. */
10764
10765static void
10766remote_buffer_add_string (char **buffer, int *left, char *string)
10767{
10768 int len = strlen (string);
10769
10770 if (len > *left)
10771 error (_("Packet too long for target."));
10772
10773 memcpy (*buffer, string, len);
10774 *buffer += len;
10775 *left -= len;
10776
10777 /* NUL-terminate the buffer as a convenience, if there is
10778 room. */
10779 if (*left)
10780 **buffer = '\0';
10781}
10782
10783/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10784 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10785 decrease *LEFT. Otherwise raise an error. */
10786
10787static void
10788remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10789 int len)
10790{
10791 if (2 * len > *left)
10792 error (_("Packet too long for target."));
10793
10794 bin2hex (bytes, *buffer, len);
10795 *buffer += 2 * len;
10796 *left -= 2 * len;
10797
10798 /* NUL-terminate the buffer as a convenience, if there is
10799 room. */
10800 if (*left)
10801 **buffer = '\0';
10802}
10803
10804/* If *LEFT is large enough, convert VALUE to hex and add it to
10805 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10806 decrease *LEFT. Otherwise raise an error. */
10807
10808static void
10809remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10810{
10811 int len = hexnumlen (value);
10812
10813 if (len > *left)
10814 error (_("Packet too long for target."));
10815
10816 hexnumstr (*buffer, value);
10817 *buffer += len;
10818 *left -= len;
10819
10820 /* NUL-terminate the buffer as a convenience, if there is
10821 room. */
10822 if (*left)
10823 **buffer = '\0';
10824}
10825
10826/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10827 value, *REMOTE_ERRNO to the remote error number or zero if none
10828 was included, and *ATTACHMENT to point to the start of the annex
10829 if any. The length of the packet isn't needed here; there may
10830 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10831
10832 Return 0 if the packet could be parsed, -1 if it could not. If
10833 -1 is returned, the other variables may not be initialized. */
10834
10835static int
10836remote_hostio_parse_result (char *buffer, int *retcode,
10837 int *remote_errno, char **attachment)
10838{
10839 char *p, *p2;
10840
10841 *remote_errno = 0;
10842 *attachment = NULL;
10843
10844 if (buffer[0] != 'F')
10845 return -1;
10846
10847 errno = 0;
10848 *retcode = strtol (&buffer[1], &p, 16);
10849 if (errno != 0 || p == &buffer[1])
10850 return -1;
10851
10852 /* Check for ",errno". */
10853 if (*p == ',')
10854 {
10855 errno = 0;
10856 *remote_errno = strtol (p + 1, &p2, 16);
10857 if (errno != 0 || p + 1 == p2)
10858 return -1;
10859 p = p2;
10860 }
10861
10862 /* Check for ";attachment". If there is no attachment, the
10863 packet should end here. */
10864 if (*p == ';')
10865 {
10866 *attachment = p + 1;
10867 return 0;
10868 }
10869 else if (*p == '\0')
10870 return 0;
10871 else
10872 return -1;
10873}
10874
10875/* Send a prepared I/O packet to the target and read its response.
10876 The prepared packet is in the global RS->BUF before this function
10877 is called, and the answer is there when we return.
10878
10879 COMMAND_BYTES is the length of the request to send, which may include
10880 binary data. WHICH_PACKET is the packet configuration to check
10881 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10882 is set to the error number and -1 is returned. Otherwise the value
10883 returned by the function is returned.
10884
10885 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10886 attachment is expected; an error will be reported if there's a
10887 mismatch. If one is found, *ATTACHMENT will be set to point into
10888 the packet buffer and *ATTACHMENT_LEN will be set to the
10889 attachment's length. */
10890
10891static int
10892remote_hostio_send_command (int command_bytes, int which_packet,
10893 int *remote_errno, char **attachment,
10894 int *attachment_len)
10895{
10896 struct remote_state *rs = get_remote_state ();
10897 int ret, bytes_read;
10898 char *attachment_tmp;
10899
5d93a237 10900 if (!rs->remote_desc
4082afcc 10901 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
10902 {
10903 *remote_errno = FILEIO_ENOSYS;
10904 return -1;
10905 }
10906
10907 putpkt_binary (rs->buf, command_bytes);
10908 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10909
10910 /* If it timed out, something is wrong. Don't try to parse the
10911 buffer. */
10912 if (bytes_read < 0)
10913 {
10914 *remote_errno = FILEIO_EINVAL;
10915 return -1;
10916 }
10917
10918 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10919 {
10920 case PACKET_ERROR:
10921 *remote_errno = FILEIO_EINVAL;
10922 return -1;
10923 case PACKET_UNKNOWN:
10924 *remote_errno = FILEIO_ENOSYS;
10925 return -1;
10926 case PACKET_OK:
10927 break;
10928 }
10929
10930 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10931 &attachment_tmp))
10932 {
10933 *remote_errno = FILEIO_EINVAL;
10934 return -1;
10935 }
10936
10937 /* Make sure we saw an attachment if and only if we expected one. */
10938 if ((attachment_tmp == NULL && attachment != NULL)
10939 || (attachment_tmp != NULL && attachment == NULL))
10940 {
10941 *remote_errno = FILEIO_EINVAL;
10942 return -1;
10943 }
10944
10945 /* If an attachment was found, it must point into the packet buffer;
10946 work out how many bytes there were. */
10947 if (attachment_tmp != NULL)
10948 {
10949 *attachment = attachment_tmp;
10950 *attachment_len = bytes_read - (*attachment - rs->buf);
10951 }
10952
10953 return ret;
10954}
10955
80152258
PA
10956/* Invalidate the readahead cache. */
10957
10958static void
10959readahead_cache_invalidate (void)
10960{
10961 struct remote_state *rs = get_remote_state ();
10962
10963 rs->readahead_cache.fd = -1;
10964}
10965
10966/* Invalidate the readahead cache if it is holding data for FD. */
10967
10968static void
10969readahead_cache_invalidate_fd (int fd)
10970{
10971 struct remote_state *rs = get_remote_state ();
10972
10973 if (rs->readahead_cache.fd == fd)
10974 rs->readahead_cache.fd = -1;
10975}
10976
15a201c8
GB
10977/* Set the filesystem remote_hostio functions that take FILENAME
10978 arguments will use. Return 0 on success, or -1 if an error
10979 occurs (and set *REMOTE_ERRNO). */
10980
10981static int
10982remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10983{
10984 struct remote_state *rs = get_remote_state ();
10985 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10986 char *p = rs->buf;
10987 int left = get_remote_packet_size () - 1;
10988 char arg[9];
10989 int ret;
10990
10991 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10992 return 0;
10993
10994 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10995 return 0;
10996
10997 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10998
10999 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11000 remote_buffer_add_string (&p, &left, arg);
11001
11002 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11003 remote_errno, NULL, NULL);
11004
11005 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11006 return 0;
11007
11008 if (ret == 0)
11009 rs->fs_pid = required_pid;
11010
11011 return ret;
11012}
11013
12e2a5fd 11014/* Implementation of to_fileio_open. */
a6b151f1
DJ
11015
11016static int
cd897586 11017remote_hostio_open (struct target_ops *self,
07c138c8 11018 struct inferior *inf, const char *filename,
4313b8c0
GB
11019 int flags, int mode, int warn_if_slow,
11020 int *remote_errno)
a6b151f1
DJ
11021{
11022 struct remote_state *rs = get_remote_state ();
11023 char *p = rs->buf;
11024 int left = get_remote_packet_size () - 1;
11025
4313b8c0
GB
11026 if (warn_if_slow)
11027 {
11028 static int warning_issued = 0;
11029
11030 printf_unfiltered (_("Reading %s from remote target...\n"),
11031 filename);
11032
11033 if (!warning_issued)
11034 {
11035 warning (_("File transfers from remote targets can be slow."
11036 " Use \"set sysroot\" to access files locally"
11037 " instead."));
11038 warning_issued = 1;
11039 }
11040 }
11041
15a201c8
GB
11042 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11043 return -1;
11044
a6b151f1
DJ
11045 remote_buffer_add_string (&p, &left, "vFile:open:");
11046
11047 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11048 strlen (filename));
11049 remote_buffer_add_string (&p, &left, ",");
11050
11051 remote_buffer_add_int (&p, &left, flags);
11052 remote_buffer_add_string (&p, &left, ",");
11053
11054 remote_buffer_add_int (&p, &left, mode);
11055
11056 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11057 remote_errno, NULL, NULL);
11058}
11059
12e2a5fd 11060/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
11061
11062static int
0d866f62
TT
11063remote_hostio_pwrite (struct target_ops *self,
11064 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
11065 ULONGEST offset, int *remote_errno)
11066{
11067 struct remote_state *rs = get_remote_state ();
11068 char *p = rs->buf;
11069 int left = get_remote_packet_size ();
11070 int out_len;
11071
80152258
PA
11072 readahead_cache_invalidate_fd (fd);
11073
a6b151f1
DJ
11074 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11075
11076 remote_buffer_add_int (&p, &left, fd);
11077 remote_buffer_add_string (&p, &left, ",");
11078
11079 remote_buffer_add_int (&p, &left, offset);
11080 remote_buffer_add_string (&p, &left, ",");
11081
124e13d9 11082 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
11083 get_remote_packet_size () - (p - rs->buf));
11084
11085 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11086 remote_errno, NULL, NULL);
11087}
11088
80152258
PA
11089/* Helper for the implementation of to_fileio_pread. Read the file
11090 from the remote side with vFile:pread. */
a6b151f1
DJ
11091
11092static int
80152258
PA
11093remote_hostio_pread_vFile (struct target_ops *self,
11094 int fd, gdb_byte *read_buf, int len,
11095 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
11096{
11097 struct remote_state *rs = get_remote_state ();
11098 char *p = rs->buf;
11099 char *attachment;
11100 int left = get_remote_packet_size ();
11101 int ret, attachment_len;
11102 int read_len;
11103
11104 remote_buffer_add_string (&p, &left, "vFile:pread:");
11105
11106 remote_buffer_add_int (&p, &left, fd);
11107 remote_buffer_add_string (&p, &left, ",");
11108
11109 remote_buffer_add_int (&p, &left, len);
11110 remote_buffer_add_string (&p, &left, ",");
11111
11112 remote_buffer_add_int (&p, &left, offset);
11113
11114 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11115 remote_errno, &attachment,
11116 &attachment_len);
11117
11118 if (ret < 0)
11119 return ret;
11120
bc20a4af 11121 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
11122 read_buf, len);
11123 if (read_len != ret)
11124 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11125
11126 return ret;
11127}
11128
80152258
PA
11129/* Serve pread from the readahead cache. Returns number of bytes
11130 read, or 0 if the request can't be served from the cache. */
11131
11132static int
11133remote_hostio_pread_from_cache (struct remote_state *rs,
11134 int fd, gdb_byte *read_buf, size_t len,
11135 ULONGEST offset)
11136{
11137 struct readahead_cache *cache = &rs->readahead_cache;
11138
11139 if (cache->fd == fd
11140 && cache->offset <= offset
11141 && offset < cache->offset + cache->bufsize)
11142 {
11143 ULONGEST max = cache->offset + cache->bufsize;
11144
11145 if (offset + len > max)
11146 len = max - offset;
11147
11148 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11149 return len;
11150 }
11151
11152 return 0;
11153}
11154
11155/* Implementation of to_fileio_pread. */
11156
11157static int
11158remote_hostio_pread (struct target_ops *self,
11159 int fd, gdb_byte *read_buf, int len,
11160 ULONGEST offset, int *remote_errno)
11161{
11162 int ret;
11163 struct remote_state *rs = get_remote_state ();
11164 struct readahead_cache *cache = &rs->readahead_cache;
11165
11166 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11167 if (ret > 0)
11168 {
11169 cache->hit_count++;
11170
11171 if (remote_debug)
11172 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11173 pulongest (cache->hit_count));
11174 return ret;
11175 }
11176
11177 cache->miss_count++;
11178 if (remote_debug)
11179 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11180 pulongest (cache->miss_count));
11181
11182 cache->fd = fd;
11183 cache->offset = offset;
11184 cache->bufsize = get_remote_packet_size ();
224c3ddb 11185 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258
PA
11186
11187 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11188 cache->offset, remote_errno);
11189 if (ret <= 0)
11190 {
11191 readahead_cache_invalidate_fd (fd);
11192 return ret;
11193 }
11194
11195 cache->bufsize = ret;
11196 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11197}
11198
12e2a5fd 11199/* Implementation of to_fileio_close. */
a6b151f1
DJ
11200
11201static int
df39ea25 11202remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
11203{
11204 struct remote_state *rs = get_remote_state ();
11205 char *p = rs->buf;
11206 int left = get_remote_packet_size () - 1;
11207
80152258
PA
11208 readahead_cache_invalidate_fd (fd);
11209
a6b151f1
DJ
11210 remote_buffer_add_string (&p, &left, "vFile:close:");
11211
11212 remote_buffer_add_int (&p, &left, fd);
11213
11214 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11215 remote_errno, NULL, NULL);
11216}
11217
12e2a5fd 11218/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
11219
11220static int
dbbca37d 11221remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
11222 struct inferior *inf, const char *filename,
11223 int *remote_errno)
a6b151f1
DJ
11224{
11225 struct remote_state *rs = get_remote_state ();
11226 char *p = rs->buf;
11227 int left = get_remote_packet_size () - 1;
11228
15a201c8
GB
11229 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11230 return -1;
11231
a6b151f1
DJ
11232 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11233
11234 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11235 strlen (filename));
11236
11237 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11238 remote_errno, NULL, NULL);
11239}
11240
12e2a5fd 11241/* Implementation of to_fileio_readlink. */
b9e7b9c3
UW
11242
11243static char *
fab5aa7c 11244remote_hostio_readlink (struct target_ops *self,
07c138c8
GB
11245 struct inferior *inf, const char *filename,
11246 int *remote_errno)
b9e7b9c3
UW
11247{
11248 struct remote_state *rs = get_remote_state ();
11249 char *p = rs->buf;
11250 char *attachment;
11251 int left = get_remote_packet_size ();
11252 int len, attachment_len;
11253 int read_len;
11254 char *ret;
11255
15a201c8
GB
11256 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11257 return NULL;
11258
b9e7b9c3
UW
11259 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11260
11261 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11262 strlen (filename));
11263
11264 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11265 remote_errno, &attachment,
11266 &attachment_len);
11267
11268 if (len < 0)
11269 return NULL;
11270
224c3ddb 11271 ret = (char *) xmalloc (len + 1);
b9e7b9c3 11272
bc20a4af
PA
11273 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11274 (gdb_byte *) ret, len);
b9e7b9c3
UW
11275 if (read_len != len)
11276 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11277
11278 ret[len] = '\0';
11279 return ret;
11280}
11281
12e2a5fd 11282/* Implementation of to_fileio_fstat. */
0a93529c
GB
11283
11284static int
11285remote_hostio_fstat (struct target_ops *self,
11286 int fd, struct stat *st,
11287 int *remote_errno)
11288{
11289 struct remote_state *rs = get_remote_state ();
11290 char *p = rs->buf;
11291 int left = get_remote_packet_size ();
11292 int attachment_len, ret;
11293 char *attachment;
11294 struct fio_stat fst;
11295 int read_len;
11296
464b0089
GB
11297 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11298
11299 remote_buffer_add_int (&p, &left, fd);
11300
11301 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11302 remote_errno, &attachment,
11303 &attachment_len);
11304 if (ret < 0)
0a93529c 11305 {
464b0089
GB
11306 if (*remote_errno != FILEIO_ENOSYS)
11307 return ret;
11308
0a93529c
GB
11309 /* Strictly we should return -1, ENOSYS here, but when
11310 "set sysroot remote:" was implemented in August 2008
11311 BFD's need for a stat function was sidestepped with
11312 this hack. This was not remedied until March 2015
11313 so we retain the previous behavior to avoid breaking
11314 compatibility.
11315
11316 Note that the memset is a March 2015 addition; older
11317 GDBs set st_size *and nothing else* so the structure
11318 would have garbage in all other fields. This might
11319 break something but retaining the previous behavior
11320 here would be just too wrong. */
11321
11322 memset (st, 0, sizeof (struct stat));
11323 st->st_size = INT_MAX;
11324 return 0;
11325 }
11326
0a93529c
GB
11327 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11328 (gdb_byte *) &fst, sizeof (fst));
11329
11330 if (read_len != ret)
11331 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11332
11333 if (read_len != sizeof (fst))
11334 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11335 read_len, (int) sizeof (fst));
11336
11337 remote_fileio_to_host_stat (&fst, st);
11338
11339 return 0;
11340}
11341
12e2a5fd 11342/* Implementation of to_filesystem_is_local. */
e3dd7556
GB
11343
11344static int
11345remote_filesystem_is_local (struct target_ops *self)
11346{
11347 /* Valgrind GDB presents itself as a remote target but works
11348 on the local filesystem: it does not implement remote get
11349 and users are not expected to set a sysroot. To handle
11350 this case we treat the remote filesystem as local if the
11351 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11352 does not support vFile:open. */
a3be80c3 11353 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
11354 {
11355 enum packet_support ps = packet_support (PACKET_vFile_open);
11356
11357 if (ps == PACKET_SUPPORT_UNKNOWN)
11358 {
11359 int fd, remote_errno;
11360
11361 /* Try opening a file to probe support. The supplied
11362 filename is irrelevant, we only care about whether
11363 the stub recognizes the packet or not. */
07c138c8 11364 fd = remote_hostio_open (self, NULL, "just probing",
4313b8c0 11365 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
11366 &remote_errno);
11367
11368 if (fd >= 0)
11369 remote_hostio_close (self, fd, &remote_errno);
11370
11371 ps = packet_support (PACKET_vFile_open);
11372 }
11373
11374 if (ps == PACKET_DISABLE)
11375 {
11376 static int warning_issued = 0;
11377
11378 if (!warning_issued)
11379 {
11380 warning (_("remote target does not support file"
11381 " transfer, attempting to access files"
11382 " from local filesystem."));
11383 warning_issued = 1;
11384 }
11385
11386 return 1;
11387 }
11388 }
11389
11390 return 0;
11391}
11392
a6b151f1
DJ
11393static int
11394remote_fileio_errno_to_host (int errnum)
11395{
11396 switch (errnum)
11397 {
11398 case FILEIO_EPERM:
11399 return EPERM;
11400 case FILEIO_ENOENT:
11401 return ENOENT;
11402 case FILEIO_EINTR:
11403 return EINTR;
11404 case FILEIO_EIO:
11405 return EIO;
11406 case FILEIO_EBADF:
11407 return EBADF;
11408 case FILEIO_EACCES:
11409 return EACCES;
11410 case FILEIO_EFAULT:
11411 return EFAULT;
11412 case FILEIO_EBUSY:
11413 return EBUSY;
11414 case FILEIO_EEXIST:
11415 return EEXIST;
11416 case FILEIO_ENODEV:
11417 return ENODEV;
11418 case FILEIO_ENOTDIR:
11419 return ENOTDIR;
11420 case FILEIO_EISDIR:
11421 return EISDIR;
11422 case FILEIO_EINVAL:
11423 return EINVAL;
11424 case FILEIO_ENFILE:
11425 return ENFILE;
11426 case FILEIO_EMFILE:
11427 return EMFILE;
11428 case FILEIO_EFBIG:
11429 return EFBIG;
11430 case FILEIO_ENOSPC:
11431 return ENOSPC;
11432 case FILEIO_ESPIPE:
11433 return ESPIPE;
11434 case FILEIO_EROFS:
11435 return EROFS;
11436 case FILEIO_ENOSYS:
11437 return ENOSYS;
11438 case FILEIO_ENAMETOOLONG:
11439 return ENAMETOOLONG;
11440 }
11441 return -1;
11442}
11443
11444static char *
11445remote_hostio_error (int errnum)
11446{
11447 int host_error = remote_fileio_errno_to_host (errnum);
11448
11449 if (host_error == -1)
11450 error (_("Unknown remote I/O error %d"), errnum);
11451 else
11452 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11453}
11454
a6b151f1
DJ
11455static void
11456remote_hostio_close_cleanup (void *opaque)
11457{
11458 int fd = *(int *) opaque;
11459 int remote_errno;
11460
df39ea25 11461 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
11462}
11463
11464void
11465remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11466{
11467 struct cleanup *back_to, *close_cleanup;
11468 int retcode, fd, remote_errno, bytes, io_size;
11469 FILE *file;
11470 gdb_byte *buffer;
11471 int bytes_in_buffer;
11472 int saw_eof;
11473 ULONGEST offset;
5d93a237 11474 struct remote_state *rs = get_remote_state ();
a6b151f1 11475
5d93a237 11476 if (!rs->remote_desc)
a6b151f1
DJ
11477 error (_("command can only be used with remote target"));
11478
614c279d 11479 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
11480 if (file == NULL)
11481 perror_with_name (local_file);
7c8a8b04 11482 back_to = make_cleanup_fclose (file);
a6b151f1 11483
07c138c8 11484 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 11485 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 11486 | FILEIO_O_TRUNC),
4313b8c0 11487 0700, 0, &remote_errno);
a6b151f1
DJ
11488 if (fd == -1)
11489 remote_hostio_error (remote_errno);
11490
11491 /* Send up to this many bytes at once. They won't all fit in the
11492 remote packet limit, so we'll transfer slightly fewer. */
11493 io_size = get_remote_packet_size ();
224c3ddb 11494 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11495 make_cleanup (xfree, buffer);
11496
11497 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11498
11499 bytes_in_buffer = 0;
11500 saw_eof = 0;
11501 offset = 0;
11502 while (bytes_in_buffer || !saw_eof)
11503 {
11504 if (!saw_eof)
11505 {
3e43a32a
MS
11506 bytes = fread (buffer + bytes_in_buffer, 1,
11507 io_size - bytes_in_buffer,
a6b151f1
DJ
11508 file);
11509 if (bytes == 0)
11510 {
11511 if (ferror (file))
11512 error (_("Error reading %s."), local_file);
11513 else
11514 {
11515 /* EOF. Unless there is something still in the
11516 buffer from the last iteration, we are done. */
11517 saw_eof = 1;
11518 if (bytes_in_buffer == 0)
11519 break;
11520 }
11521 }
11522 }
11523 else
11524 bytes = 0;
11525
11526 bytes += bytes_in_buffer;
11527 bytes_in_buffer = 0;
11528
0d866f62
TT
11529 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11530 fd, buffer, bytes,
3e43a32a 11531 offset, &remote_errno);
a6b151f1
DJ
11532
11533 if (retcode < 0)
11534 remote_hostio_error (remote_errno);
11535 else if (retcode == 0)
11536 error (_("Remote write of %d bytes returned 0!"), bytes);
11537 else if (retcode < bytes)
11538 {
11539 /* Short write. Save the rest of the read data for the next
11540 write. */
11541 bytes_in_buffer = bytes - retcode;
11542 memmove (buffer, buffer + retcode, bytes_in_buffer);
11543 }
11544
11545 offset += retcode;
11546 }
11547
11548 discard_cleanups (close_cleanup);
df39ea25 11549 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11550 remote_hostio_error (remote_errno);
11551
11552 if (from_tty)
11553 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11554 do_cleanups (back_to);
11555}
11556
11557void
11558remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11559{
11560 struct cleanup *back_to, *close_cleanup;
cea39f65 11561 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
11562 FILE *file;
11563 gdb_byte *buffer;
11564 ULONGEST offset;
5d93a237 11565 struct remote_state *rs = get_remote_state ();
a6b151f1 11566
5d93a237 11567 if (!rs->remote_desc)
a6b151f1
DJ
11568 error (_("command can only be used with remote target"));
11569
07c138c8 11570 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
11571 remote_file, FILEIO_O_RDONLY, 0, 0,
11572 &remote_errno);
a6b151f1
DJ
11573 if (fd == -1)
11574 remote_hostio_error (remote_errno);
11575
614c279d 11576 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
11577 if (file == NULL)
11578 perror_with_name (local_file);
7c8a8b04 11579 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
11580
11581 /* Send up to this many bytes at once. They won't all fit in the
11582 remote packet limit, so we'll transfer slightly fewer. */
11583 io_size = get_remote_packet_size ();
224c3ddb 11584 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11585 make_cleanup (xfree, buffer);
11586
11587 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11588
11589 offset = 0;
11590 while (1)
11591 {
a3be983c
TT
11592 bytes = remote_hostio_pread (find_target_at (process_stratum),
11593 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
11594 if (bytes == 0)
11595 /* Success, but no bytes, means end-of-file. */
11596 break;
11597 if (bytes == -1)
11598 remote_hostio_error (remote_errno);
11599
11600 offset += bytes;
11601
11602 bytes = fwrite (buffer, 1, bytes, file);
11603 if (bytes == 0)
11604 perror_with_name (local_file);
11605 }
11606
11607 discard_cleanups (close_cleanup);
df39ea25 11608 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11609 remote_hostio_error (remote_errno);
11610
11611 if (from_tty)
11612 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11613 do_cleanups (back_to);
11614}
11615
11616void
11617remote_file_delete (const char *remote_file, int from_tty)
11618{
11619 int retcode, remote_errno;
5d93a237 11620 struct remote_state *rs = get_remote_state ();
a6b151f1 11621
5d93a237 11622 if (!rs->remote_desc)
a6b151f1
DJ
11623 error (_("command can only be used with remote target"));
11624
dbbca37d 11625 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 11626 NULL, remote_file, &remote_errno);
a6b151f1
DJ
11627 if (retcode == -1)
11628 remote_hostio_error (remote_errno);
11629
11630 if (from_tty)
11631 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11632}
11633
11634static void
11635remote_put_command (char *args, int from_tty)
11636{
11637 struct cleanup *back_to;
11638 char **argv;
11639
d1a41061
PP
11640 if (args == NULL)
11641 error_no_arg (_("file to put"));
11642
11643 argv = gdb_buildargv (args);
a6b151f1
DJ
11644 back_to = make_cleanup_freeargv (argv);
11645 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11646 error (_("Invalid parameters to remote put"));
11647
11648 remote_file_put (argv[0], argv[1], from_tty);
11649
11650 do_cleanups (back_to);
11651}
11652
11653static void
11654remote_get_command (char *args, int from_tty)
11655{
11656 struct cleanup *back_to;
11657 char **argv;
11658
d1a41061
PP
11659 if (args == NULL)
11660 error_no_arg (_("file to get"));
11661
11662 argv = gdb_buildargv (args);
a6b151f1
DJ
11663 back_to = make_cleanup_freeargv (argv);
11664 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11665 error (_("Invalid parameters to remote get"));
11666
11667 remote_file_get (argv[0], argv[1], from_tty);
11668
11669 do_cleanups (back_to);
11670}
11671
11672static void
11673remote_delete_command (char *args, int from_tty)
11674{
11675 struct cleanup *back_to;
11676 char **argv;
11677
d1a41061
PP
11678 if (args == NULL)
11679 error_no_arg (_("file to delete"));
11680
11681 argv = gdb_buildargv (args);
a6b151f1
DJ
11682 back_to = make_cleanup_freeargv (argv);
11683 if (argv[0] == NULL || argv[1] != NULL)
11684 error (_("Invalid parameters to remote delete"));
11685
11686 remote_file_delete (argv[0], from_tty);
11687
11688 do_cleanups (back_to);
11689}
11690
11691static void
11692remote_command (char *args, int from_tty)
11693{
635c7e8a 11694 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
11695}
11696
b2175913 11697static int
19db3e69 11698remote_can_execute_reverse (struct target_ops *self)
b2175913 11699{
4082afcc
PA
11700 if (packet_support (PACKET_bs) == PACKET_ENABLE
11701 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
11702 return 1;
11703 else
11704 return 0;
b2175913
MS
11705}
11706
74531fed 11707static int
2a9a2795 11708remote_supports_non_stop (struct target_ops *self)
74531fed
PA
11709{
11710 return 1;
11711}
11712
03583c20 11713static int
2bfc0540 11714remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
11715{
11716 /* Only supported in extended mode. */
11717 return 0;
11718}
11719
8a305172 11720static int
86ce2668 11721remote_supports_multi_process (struct target_ops *self)
8a305172
PA
11722{
11723 struct remote_state *rs = get_remote_state ();
a744cf53 11724
8020350c 11725 return remote_multi_process_p (rs);
8a305172
PA
11726}
11727
70221824 11728static int
782b2b07
SS
11729remote_supports_cond_tracepoints (void)
11730{
4082afcc 11731 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
11732}
11733
3788aec7 11734static int
efcc2da7 11735remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 11736{
4082afcc 11737 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
11738}
11739
70221824 11740static int
7a697b8d
SS
11741remote_supports_fast_tracepoints (void)
11742{
4082afcc 11743 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
11744}
11745
0fb4aa4b
PA
11746static int
11747remote_supports_static_tracepoints (void)
11748{
4082afcc 11749 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
11750}
11751
1e4d1764
YQ
11752static int
11753remote_supports_install_in_trace (void)
11754{
4082afcc 11755 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
11756}
11757
d248b706 11758static int
7d178d6a 11759remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 11760{
4082afcc
PA
11761 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11762 == PACKET_ENABLE);
d248b706
KY
11763}
11764
3065dfb6 11765static int
6de37a3a 11766remote_supports_string_tracing (struct target_ops *self)
3065dfb6 11767{
4082afcc 11768 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
11769}
11770
d3ce09f5 11771static int
78eff0ec 11772remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 11773{
4082afcc 11774 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
11775}
11776
35b1e5cc 11777static void
ecae04e1 11778remote_trace_init (struct target_ops *self)
35b1e5cc
SS
11779{
11780 putpkt ("QTinit");
11781 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 11782 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11783 error (_("Target does not support this command."));
11784}
11785
11786static void free_actions_list (char **actions_list);
11787static void free_actions_list_cleanup_wrapper (void *);
11788static void
11789free_actions_list_cleanup_wrapper (void *al)
11790{
19ba03f4 11791 free_actions_list ((char **) al);
35b1e5cc
SS
11792}
11793
11794static void
11795free_actions_list (char **actions_list)
11796{
11797 int ndx;
11798
11799 if (actions_list == 0)
11800 return;
11801
11802 for (ndx = 0; actions_list[ndx]; ndx++)
11803 xfree (actions_list[ndx]);
11804
11805 xfree (actions_list);
11806}
11807
409873ef
SS
11808/* Recursive routine to walk through command list including loops, and
11809 download packets for each command. */
11810
11811static void
11812remote_download_command_source (int num, ULONGEST addr,
11813 struct command_line *cmds)
11814{
11815 struct remote_state *rs = get_remote_state ();
11816 struct command_line *cmd;
11817
11818 for (cmd = cmds; cmd; cmd = cmd->next)
11819 {
0df8b418 11820 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11821 strcpy (rs->buf, "QTDPsrc:");
11822 encode_source_string (num, addr, "cmd", cmd->line,
11823 rs->buf + strlen (rs->buf),
11824 rs->buf_size - strlen (rs->buf));
11825 putpkt (rs->buf);
11826 remote_get_noisy_reply (&target_buf, &target_buf_size);
11827 if (strcmp (target_buf, "OK"))
11828 warning (_("Target does not support source download."));
11829
11830 if (cmd->control_type == while_control
11831 || cmd->control_type == while_stepping_control)
11832 {
11833 remote_download_command_source (num, addr, *cmd->body_list);
11834
0df8b418 11835 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11836 strcpy (rs->buf, "QTDPsrc:");
11837 encode_source_string (num, addr, "cmd", "end",
11838 rs->buf + strlen (rs->buf),
11839 rs->buf_size - strlen (rs->buf));
11840 putpkt (rs->buf);
11841 remote_get_noisy_reply (&target_buf, &target_buf_size);
11842 if (strcmp (target_buf, "OK"))
11843 warning (_("Target does not support source download."));
11844 }
11845 }
11846}
11847
35b1e5cc 11848static void
548f7808 11849remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 11850{
bba74b36 11851#define BUF_SIZE 2048
e8ba3115 11852
35b1e5cc 11853 CORE_ADDR tpaddr;
409873ef 11854 char addrbuf[40];
bba74b36 11855 char buf[BUF_SIZE];
35b1e5cc
SS
11856 char **tdp_actions;
11857 char **stepping_actions;
11858 int ndx;
11859 struct cleanup *old_chain = NULL;
11860 struct agent_expr *aexpr;
11861 struct cleanup *aexpr_chain = NULL;
11862 char *pkt;
e8ba3115 11863 struct breakpoint *b = loc->owner;
d9b3f62e 11864 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 11865
dc673c81 11866 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
11867 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11868 tdp_actions);
11869 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11870 stepping_actions);
11871
11872 tpaddr = loc->address;
11873 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
11874 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11875 addrbuf, /* address */
11876 (b->enable_state == bp_enabled ? 'E' : 'D'),
11877 t->step_count, t->pass_count);
e8ba3115
YQ
11878 /* Fast tracepoints are mostly handled by the target, but we can
11879 tell the target how big of an instruction block should be moved
11880 around. */
11881 if (b->type == bp_fast_tracepoint)
11882 {
11883 /* Only test for support at download time; we may not know
11884 target capabilities at definition time. */
11885 if (remote_supports_fast_tracepoints ())
35b1e5cc 11886 {
6b940e6a
PL
11887 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11888 NULL))
bba74b36 11889 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 11890 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 11891 else
e8ba3115
YQ
11892 /* If it passed validation at definition but fails now,
11893 something is very wrong. */
11894 internal_error (__FILE__, __LINE__,
11895 _("Fast tracepoint not "
11896 "valid during download"));
35b1e5cc 11897 }
e8ba3115
YQ
11898 else
11899 /* Fast tracepoints are functionally identical to regular
11900 tracepoints, so don't take lack of support as a reason to
11901 give up on the trace run. */
11902 warning (_("Target does not support fast tracepoints, "
11903 "downloading %d as regular tracepoint"), b->number);
11904 }
11905 else if (b->type == bp_static_tracepoint)
11906 {
11907 /* Only test for support at download time; we may not know
11908 target capabilities at definition time. */
11909 if (remote_supports_static_tracepoints ())
0fb4aa4b 11910 {
e8ba3115 11911 struct static_tracepoint_marker marker;
0fb4aa4b 11912
e8ba3115
YQ
11913 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11914 strcat (buf, ":S");
0fb4aa4b 11915 else
e8ba3115 11916 error (_("Static tracepoint not valid during download"));
0fb4aa4b 11917 }
e8ba3115
YQ
11918 else
11919 /* Fast tracepoints are functionally identical to regular
11920 tracepoints, so don't take lack of support as a reason
11921 to give up on the trace run. */
11922 error (_("Target does not support static tracepoints"));
11923 }
11924 /* If the tracepoint has a conditional, make it into an agent
11925 expression and append to the definition. */
11926 if (loc->cond)
11927 {
11928 /* Only test support at download time, we may not know target
11929 capabilities at definition time. */
11930 if (remote_supports_cond_tracepoints ())
35b1e5cc 11931 {
e8ba3115
YQ
11932 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11933 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
11934 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11935 aexpr->len);
e8ba3115
YQ
11936 pkt = buf + strlen (buf);
11937 for (ndx = 0; ndx < aexpr->len; ++ndx)
11938 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11939 *pkt = '\0';
11940 do_cleanups (aexpr_chain);
35b1e5cc 11941 }
e8ba3115
YQ
11942 else
11943 warning (_("Target does not support conditional tracepoints, "
11944 "ignoring tp %d cond"), b->number);
11945 }
35b1e5cc 11946
d9b3f62e 11947 if (b->commands || *default_collect)
e8ba3115
YQ
11948 strcat (buf, "-");
11949 putpkt (buf);
11950 remote_get_noisy_reply (&target_buf, &target_buf_size);
11951 if (strcmp (target_buf, "OK"))
11952 error (_("Target does not support tracepoints."));
35b1e5cc 11953
e8ba3115
YQ
11954 /* do_single_steps (t); */
11955 if (tdp_actions)
11956 {
11957 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 11958 {
e8ba3115 11959 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11960 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11961 b->number, addrbuf, /* address */
11962 tdp_actions[ndx],
11963 ((tdp_actions[ndx + 1] || stepping_actions)
11964 ? '-' : 0));
e8ba3115
YQ
11965 putpkt (buf);
11966 remote_get_noisy_reply (&target_buf,
11967 &target_buf_size);
11968 if (strcmp (target_buf, "OK"))
11969 error (_("Error on target while setting tracepoints."));
35b1e5cc 11970 }
e8ba3115
YQ
11971 }
11972 if (stepping_actions)
11973 {
11974 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 11975 {
e8ba3115 11976 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11977 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11978 b->number, addrbuf, /* address */
11979 ((ndx == 0) ? "S" : ""),
11980 stepping_actions[ndx],
11981 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
11982 putpkt (buf);
11983 remote_get_noisy_reply (&target_buf,
11984 &target_buf_size);
11985 if (strcmp (target_buf, "OK"))
11986 error (_("Error on target while setting tracepoints."));
35b1e5cc 11987 }
e8ba3115 11988 }
409873ef 11989
4082afcc 11990 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 11991 {
f00aae0f 11992 if (b->location != NULL)
409873ef 11993 {
e8ba3115 11994 strcpy (buf, "QTDPsrc:");
f00aae0f
KS
11995 encode_source_string (b->number, loc->address, "at",
11996 event_location_to_string (b->location),
11997 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115
YQ
11998 putpkt (buf);
11999 remote_get_noisy_reply (&target_buf, &target_buf_size);
12000 if (strcmp (target_buf, "OK"))
12001 warning (_("Target does not support source download."));
409873ef 12002 }
e8ba3115
YQ
12003 if (b->cond_string)
12004 {
12005 strcpy (buf, "QTDPsrc:");
12006 encode_source_string (b->number, loc->address,
12007 "cond", b->cond_string, buf + strlen (buf),
12008 2048 - strlen (buf));
12009 putpkt (buf);
12010 remote_get_noisy_reply (&target_buf, &target_buf_size);
12011 if (strcmp (target_buf, "OK"))
12012 warning (_("Target does not support source download."));
12013 }
12014 remote_download_command_source (b->number, loc->address,
12015 breakpoint_commands (b));
35b1e5cc 12016 }
e8ba3115
YQ
12017
12018 do_cleanups (old_chain);
35b1e5cc
SS
12019}
12020
1e4d1764 12021static int
a52a8357 12022remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 12023{
1e51243a
PA
12024 struct remote_state *rs = get_remote_state ();
12025 struct trace_status *ts;
12026 int status;
12027
12028 /* Don't try to install tracepoints until we've relocated our
12029 symbols, and fetched and merged the target's tracepoint list with
12030 ours. */
12031 if (rs->starting_up)
12032 return 0;
12033
12034 ts = current_trace_status ();
8bd200f1 12035 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
12036
12037 if (status == -1 || !ts->running_known || !ts->running)
12038 return 0;
12039
12040 /* If we are in a tracing experiment, but remote stub doesn't support
12041 installing tracepoint in trace, we have to return. */
12042 if (!remote_supports_install_in_trace ())
12043 return 0;
12044
12045 return 1;
12046}
12047
12048
35b1e5cc 12049static void
559d2b81
TT
12050remote_download_trace_state_variable (struct target_ops *self,
12051 struct trace_state_variable *tsv)
35b1e5cc
SS
12052{
12053 struct remote_state *rs = get_remote_state ();
00bf0b85 12054 char *p;
35b1e5cc 12055
bba74b36
YQ
12056 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12057 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12058 tsv->builtin);
00bf0b85
SS
12059 p = rs->buf + strlen (rs->buf);
12060 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12061 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 12062 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 12063 *p++ = '\0';
35b1e5cc
SS
12064 putpkt (rs->buf);
12065 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12066 if (*target_buf == '\0')
12067 error (_("Target does not support this command."));
12068 if (strcmp (target_buf, "OK") != 0)
12069 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
12070}
12071
d248b706 12072static void
46670d57
TT
12073remote_enable_tracepoint (struct target_ops *self,
12074 struct bp_location *location)
d248b706
KY
12075{
12076 struct remote_state *rs = get_remote_state ();
12077 char addr_buf[40];
12078
12079 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12080 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12081 location->owner->number, addr_buf);
d248b706
KY
12082 putpkt (rs->buf);
12083 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12084 if (*rs->buf == '\0')
12085 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12086 if (strcmp (rs->buf, "OK") != 0)
12087 error (_("Error on target while enabling tracepoint."));
12088}
12089
12090static void
780b049c
TT
12091remote_disable_tracepoint (struct target_ops *self,
12092 struct bp_location *location)
d248b706
KY
12093{
12094 struct remote_state *rs = get_remote_state ();
12095 char addr_buf[40];
12096
12097 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12098 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12099 location->owner->number, addr_buf);
d248b706
KY
12100 putpkt (rs->buf);
12101 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12102 if (*rs->buf == '\0')
12103 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12104 if (strcmp (rs->buf, "OK") != 0)
12105 error (_("Error on target while disabling tracepoint."));
12106}
12107
35b1e5cc 12108static void
583f9a86 12109remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
12110{
12111 asection *s;
81b9b86e 12112 bfd *abfd = NULL;
35b1e5cc 12113 bfd_size_type size;
608bcef2 12114 bfd_vma vma;
35b1e5cc 12115 int anysecs = 0;
c2fa21f1 12116 int offset = 0;
35b1e5cc
SS
12117
12118 if (!exec_bfd)
12119 return; /* No information to give. */
12120
12121 strcpy (target_buf, "QTro");
9779ab84 12122 offset = strlen (target_buf);
35b1e5cc
SS
12123 for (s = exec_bfd->sections; s; s = s->next)
12124 {
12125 char tmp1[40], tmp2[40];
c2fa21f1 12126 int sec_length;
35b1e5cc
SS
12127
12128 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 12129 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
12130 (s->flags & SEC_READONLY) == 0)
12131 continue;
12132
12133 anysecs = 1;
81b9b86e 12134 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 12135 size = bfd_get_section_size (s);
608bcef2
HZ
12136 sprintf_vma (tmp1, vma);
12137 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
12138 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12139 if (offset + sec_length + 1 > target_buf_size)
12140 {
4082afcc 12141 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 12142 warning (_("\
c2fa21f1
HZ
12143Too many sections for read-only sections definition packet."));
12144 break;
12145 }
bba74b36
YQ
12146 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12147 tmp1, tmp2);
c2fa21f1 12148 offset += sec_length;
35b1e5cc
SS
12149 }
12150 if (anysecs)
12151 {
12152 putpkt (target_buf);
12153 getpkt (&target_buf, &target_buf_size, 0);
12154 }
12155}
12156
12157static void
e2d1aae3 12158remote_trace_start (struct target_ops *self)
35b1e5cc
SS
12159{
12160 putpkt ("QTStart");
12161 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12162 if (*target_buf == '\0')
12163 error (_("Target does not support this command."));
12164 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12165 error (_("Bogus reply from target: %s"), target_buf);
12166}
12167
12168static int
8bd200f1 12169remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 12170{
953b98d1 12171 /* Initialize it just to avoid a GCC false warning. */
f652de6f 12172 char *p = NULL;
0df8b418 12173 /* FIXME we need to get register block size some other way. */
00bf0b85 12174 extern int trace_regblock_size;
bd3eecc3
PA
12175 enum packet_result result;
12176
4082afcc 12177 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 12178 return -1;
a744cf53 12179
00bf0b85
SS
12180 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12181
049dc89b
JK
12182 putpkt ("qTStatus");
12183
492d29ea 12184 TRY
67f41397
JK
12185 {
12186 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12187 }
492d29ea 12188 CATCH (ex, RETURN_MASK_ERROR)
67f41397 12189 {
598d3636
JK
12190 if (ex.error != TARGET_CLOSE_ERROR)
12191 {
12192 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12193 return -1;
12194 }
12195 throw_exception (ex);
67f41397 12196 }
492d29ea 12197 END_CATCH
00bf0b85 12198
bd3eecc3
PA
12199 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12200
00bf0b85 12201 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 12202 if (result == PACKET_UNKNOWN)
00bf0b85 12203 return -1;
35b1e5cc 12204
00bf0b85 12205 /* We're working with a live target. */
f5911ea1 12206 ts->filename = NULL;
00bf0b85 12207
00bf0b85 12208 if (*p++ != 'T')
35b1e5cc
SS
12209 error (_("Bogus trace status reply from target: %s"), target_buf);
12210
84cebc4a
YQ
12211 /* Function 'parse_trace_status' sets default value of each field of
12212 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
12213 parse_trace_status (p, ts);
12214
12215 return ts->running;
35b1e5cc
SS
12216}
12217
70221824 12218static void
db90e85c 12219remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
12220 struct uploaded_tp *utp)
12221{
12222 struct remote_state *rs = get_remote_state ();
f196051f
SS
12223 char *reply;
12224 struct bp_location *loc;
12225 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 12226 size_t size = get_remote_packet_size ();
f196051f
SS
12227
12228 if (tp)
12229 {
12230 tp->base.hit_count = 0;
12231 tp->traceframe_usage = 0;
12232 for (loc = tp->base.loc; loc; loc = loc->next)
12233 {
12234 /* If the tracepoint was never downloaded, don't go asking for
12235 any status. */
12236 if (tp->number_on_target == 0)
12237 continue;
bba74b36
YQ
12238 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12239 phex_nz (loc->address, 0));
f196051f
SS
12240 putpkt (rs->buf);
12241 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12242 if (reply && *reply)
12243 {
12244 if (*reply == 'V')
12245 parse_tracepoint_status (reply + 1, bp, utp);
12246 }
12247 }
12248 }
12249 else if (utp)
12250 {
12251 utp->hit_count = 0;
12252 utp->traceframe_usage = 0;
bba74b36
YQ
12253 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12254 phex_nz (utp->addr, 0));
f196051f
SS
12255 putpkt (rs->buf);
12256 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12257 if (reply && *reply)
12258 {
12259 if (*reply == 'V')
12260 parse_tracepoint_status (reply + 1, bp, utp);
12261 }
12262 }
12263}
12264
35b1e5cc 12265static void
74499f1b 12266remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
12267{
12268 putpkt ("QTStop");
12269 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12270 if (*target_buf == '\0')
12271 error (_("Target does not support this command."));
12272 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12273 error (_("Bogus reply from target: %s"), target_buf);
12274}
12275
12276static int
bd4c6793
TT
12277remote_trace_find (struct target_ops *self,
12278 enum trace_find_type type, int num,
cc5925ad 12279 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
12280 int *tpp)
12281{
12282 struct remote_state *rs = get_remote_state ();
bba74b36 12283 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
12284 char *p, *reply;
12285 int target_frameno = -1, target_tracept = -1;
12286
e6e4e701
PA
12287 /* Lookups other than by absolute frame number depend on the current
12288 trace selected, so make sure it is correct on the remote end
12289 first. */
12290 if (type != tfind_number)
12291 set_remote_traceframe ();
12292
35b1e5cc
SS
12293 p = rs->buf;
12294 strcpy (p, "QTFrame:");
12295 p = strchr (p, '\0');
12296 switch (type)
12297 {
12298 case tfind_number:
bba74b36 12299 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
12300 break;
12301 case tfind_pc:
bba74b36 12302 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
12303 break;
12304 case tfind_tp:
bba74b36 12305 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
12306 break;
12307 case tfind_range:
bba74b36
YQ
12308 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12309 phex_nz (addr2, 0));
35b1e5cc
SS
12310 break;
12311 case tfind_outside:
bba74b36
YQ
12312 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12313 phex_nz (addr2, 0));
35b1e5cc
SS
12314 break;
12315 default:
9b20d036 12316 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
12317 }
12318
12319 putpkt (rs->buf);
2f65bcb7 12320 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
12321 if (*reply == '\0')
12322 error (_("Target does not support this command."));
35b1e5cc
SS
12323
12324 while (reply && *reply)
12325 switch (*reply)
12326 {
12327 case 'F':
f197e0f1
VP
12328 p = ++reply;
12329 target_frameno = (int) strtol (p, &reply, 16);
12330 if (reply == p)
12331 error (_("Unable to parse trace frame number"));
e6e4e701
PA
12332 /* Don't update our remote traceframe number cache on failure
12333 to select a remote traceframe. */
f197e0f1
VP
12334 if (target_frameno == -1)
12335 return -1;
35b1e5cc
SS
12336 break;
12337 case 'T':
f197e0f1
VP
12338 p = ++reply;
12339 target_tracept = (int) strtol (p, &reply, 16);
12340 if (reply == p)
12341 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
12342 break;
12343 case 'O': /* "OK"? */
12344 if (reply[1] == 'K' && reply[2] == '\0')
12345 reply += 2;
12346 else
12347 error (_("Bogus reply from target: %s"), reply);
12348 break;
12349 default:
12350 error (_("Bogus reply from target: %s"), reply);
12351 }
12352 if (tpp)
12353 *tpp = target_tracept;
e6e4e701 12354
262e1174 12355 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
12356 return target_frameno;
12357}
12358
12359static int
4011015b
TT
12360remote_get_trace_state_variable_value (struct target_ops *self,
12361 int tsvnum, LONGEST *val)
35b1e5cc
SS
12362{
12363 struct remote_state *rs = get_remote_state ();
12364 char *reply;
12365 ULONGEST uval;
12366
e6e4e701
PA
12367 set_remote_traceframe ();
12368
bba74b36 12369 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
12370 putpkt (rs->buf);
12371 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12372 if (reply && *reply)
12373 {
12374 if (*reply == 'V')
12375 {
12376 unpack_varlen_hex (reply + 1, &uval);
12377 *val = (LONGEST) uval;
12378 return 1;
12379 }
12380 }
12381 return 0;
12382}
12383
00bf0b85 12384static int
dc3decaf 12385remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
12386{
12387 struct remote_state *rs = get_remote_state ();
12388 char *p, *reply;
12389
12390 p = rs->buf;
12391 strcpy (p, "QTSave:");
12392 p += strlen (p);
12393 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12394 error (_("Remote file name too long for trace save packet"));
9f1b45b0 12395 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
12396 *p++ = '\0';
12397 putpkt (rs->buf);
ad91cd99 12398 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 12399 if (*reply == '\0')
ad91cd99
PA
12400 error (_("Target does not support this command."));
12401 if (strcmp (reply, "OK") != 0)
12402 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
12403 return 0;
12404}
12405
12406/* This is basically a memory transfer, but needs to be its own packet
12407 because we don't know how the target actually organizes its trace
12408 memory, plus we want to be able to ask for as much as possible, but
12409 not be unhappy if we don't get as much as we ask for. */
12410
12411static LONGEST
88ee6f45
TT
12412remote_get_raw_trace_data (struct target_ops *self,
12413 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
12414{
12415 struct remote_state *rs = get_remote_state ();
12416 char *reply;
12417 char *p;
12418 int rslt;
12419
12420 p = rs->buf;
12421 strcpy (p, "qTBuffer:");
12422 p += strlen (p);
12423 p += hexnumstr (p, offset);
12424 *p++ = ',';
12425 p += hexnumstr (p, len);
12426 *p++ = '\0';
12427
12428 putpkt (rs->buf);
12429 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12430 if (reply && *reply)
12431 {
12432 /* 'l' by itself means we're at the end of the buffer and
12433 there is nothing more to get. */
12434 if (*reply == 'l')
12435 return 0;
12436
12437 /* Convert the reply into binary. Limit the number of bytes to
12438 convert according to our passed-in buffer size, rather than
12439 what was returned in the packet; if the target is
12440 unexpectedly generous and gives us a bigger reply than we
12441 asked for, we don't want to crash. */
12442 rslt = hex2bin (target_buf, buf, len);
12443 return rslt;
12444 }
12445
12446 /* Something went wrong, flag as an error. */
12447 return -1;
12448}
12449
35b1e5cc 12450static void
37b25738 12451remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
12452{
12453 struct remote_state *rs = get_remote_state ();
12454
4082afcc 12455 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 12456 {
ad91cd99
PA
12457 char *reply;
12458
bba74b36 12459 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 12460 putpkt (rs->buf);
ad91cd99
PA
12461 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12462 if (*reply == '\0')
33da3f1c 12463 error (_("Target does not support this command."));
ad91cd99
PA
12464 if (strcmp (reply, "OK") != 0)
12465 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
12466 }
12467 else if (val)
12468 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
12469}
12470
dc146f7c
VP
12471static int
12472remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12473{
12474 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 12475
fe978cb0
PA
12476 if (info && info->priv)
12477 return info->priv->core;
dc146f7c
VP
12478 return -1;
12479}
12480
4daf5ac0 12481static void
736d5b1f 12482remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
12483{
12484 struct remote_state *rs = get_remote_state ();
ad91cd99 12485 char *reply;
4daf5ac0 12486
bba74b36 12487 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 12488 putpkt (rs->buf);
ad91cd99
PA
12489 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12490 if (*reply == '\0')
4daf5ac0 12491 error (_("Target does not support this command."));
ad91cd99
PA
12492 if (strcmp (reply, "OK") != 0)
12493 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
12494}
12495
b3b9301e 12496static struct traceframe_info *
a893e81f 12497remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
12498{
12499 char *text;
12500
12501 text = target_read_stralloc (&current_target,
12502 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12503 if (text != NULL)
12504 {
12505 struct traceframe_info *info;
12506 struct cleanup *back_to = make_cleanup (xfree, text);
12507
12508 info = parse_traceframe_info (text);
12509 do_cleanups (back_to);
12510 return info;
12511 }
12512
12513 return NULL;
12514}
12515
405f8e94
SS
12516/* Handle the qTMinFTPILen packet. Returns the minimum length of
12517 instruction on which a fast tracepoint may be placed. Returns -1
12518 if the packet is not supported, and 0 if the minimum instruction
12519 length is unknown. */
12520
12521static int
0e67620a 12522remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
12523{
12524 struct remote_state *rs = get_remote_state ();
12525 char *reply;
12526
e886a173
PA
12527 /* If we're not debugging a process yet, the IPA can't be
12528 loaded. */
12529 if (!target_has_execution)
12530 return 0;
12531
12532 /* Make sure the remote is pointing at the right process. */
12533 set_general_process ();
12534
bba74b36 12535 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
12536 putpkt (rs->buf);
12537 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12538 if (*reply == '\0')
12539 return -1;
12540 else
12541 {
12542 ULONGEST min_insn_len;
12543
12544 unpack_varlen_hex (reply, &min_insn_len);
12545
12546 return (int) min_insn_len;
12547 }
12548}
12549
f6f899bf 12550static void
4da384be 12551remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 12552{
4082afcc 12553 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
12554 {
12555 struct remote_state *rs = get_remote_state ();
12556 char *buf = rs->buf;
12557 char *endbuf = rs->buf + get_remote_packet_size ();
12558 enum packet_result result;
12559
12560 gdb_assert (val >= 0 || val == -1);
12561 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12562 /* Send -1 as literal "-1" to avoid host size dependency. */
12563 if (val < 0)
12564 {
12565 *buf++ = '-';
12566 buf += hexnumstr (buf, (ULONGEST) -val);
12567 }
12568 else
12569 buf += hexnumstr (buf, (ULONGEST) val);
12570
12571 putpkt (rs->buf);
12572 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12573 result = packet_ok (rs->buf,
12574 &remote_protocol_packets[PACKET_QTBuffer_size]);
12575
12576 if (result != PACKET_OK)
12577 warning (_("Bogus reply from target: %s"), rs->buf);
12578 }
12579}
12580
f196051f 12581static int
d9e68a2c
TT
12582remote_set_trace_notes (struct target_ops *self,
12583 const char *user, const char *notes,
ca623f82 12584 const char *stop_notes)
f196051f
SS
12585{
12586 struct remote_state *rs = get_remote_state ();
12587 char *reply;
12588 char *buf = rs->buf;
12589 char *endbuf = rs->buf + get_remote_packet_size ();
12590 int nbytes;
12591
12592 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12593 if (user)
12594 {
12595 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 12596 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
12597 buf += 2 * nbytes;
12598 *buf++ = ';';
12599 }
12600 if (notes)
12601 {
12602 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 12603 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
12604 buf += 2 * nbytes;
12605 *buf++ = ';';
12606 }
12607 if (stop_notes)
12608 {
12609 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 12610 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
12611 buf += 2 * nbytes;
12612 *buf++ = ';';
12613 }
12614 /* Ensure the buffer is terminated. */
12615 *buf = '\0';
12616
12617 putpkt (rs->buf);
12618 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12619 if (*reply == '\0')
12620 return 0;
12621
12622 if (strcmp (reply, "OK") != 0)
12623 error (_("Bogus reply from target: %s"), reply);
12624
12625 return 1;
12626}
12627
d1feda86 12628static int
2c152180 12629remote_use_agent (struct target_ops *self, int use)
d1feda86 12630{
4082afcc 12631 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
12632 {
12633 struct remote_state *rs = get_remote_state ();
12634
12635 /* If the stub supports QAgent. */
bba74b36 12636 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
12637 putpkt (rs->buf);
12638 getpkt (&rs->buf, &rs->buf_size, 0);
12639
12640 if (strcmp (rs->buf, "OK") == 0)
12641 {
12642 use_agent = use;
12643 return 1;
12644 }
12645 }
12646
12647 return 0;
12648}
12649
12650static int
fe38f897 12651remote_can_use_agent (struct target_ops *self)
d1feda86 12652{
4082afcc 12653 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
12654}
12655
9accd112
MM
12656struct btrace_target_info
12657{
12658 /* The ptid of the traced thread. */
12659 ptid_t ptid;
f4abbc16
MM
12660
12661 /* The obtained branch trace configuration. */
12662 struct btrace_config conf;
9accd112
MM
12663};
12664
f4abbc16
MM
12665/* Reset our idea of our target's btrace configuration. */
12666
12667static void
12668remote_btrace_reset (void)
12669{
12670 struct remote_state *rs = get_remote_state ();
12671
12672 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12673}
12674
9accd112
MM
12675/* Check whether the target supports branch tracing. */
12676
12677static int
043c3577 12678remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 12679{
4082afcc 12680 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 12681 return 0;
4082afcc 12682 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
12683 return 0;
12684
043c3577
MM
12685 switch (format)
12686 {
12687 case BTRACE_FORMAT_NONE:
12688 return 0;
12689
12690 case BTRACE_FORMAT_BTS:
12691 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
b20a6524
MM
12692
12693 case BTRACE_FORMAT_PT:
12694 /* The trace is decoded on the host. Even if our target supports it,
12695 we still need to have libipt to decode the trace. */
12696#if defined (HAVE_LIBIPT)
12697 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12698#else /* !defined (HAVE_LIBIPT) */
12699 return 0;
12700#endif /* !defined (HAVE_LIBIPT) */
043c3577
MM
12701 }
12702
12703 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
12704}
12705
f4abbc16
MM
12706/* Synchronize the configuration with the target. */
12707
12708static void
12709btrace_sync_conf (const struct btrace_config *conf)
12710{
d33501a5
MM
12711 struct packet_config *packet;
12712 struct remote_state *rs;
12713 char *buf, *pos, *endbuf;
12714
12715 rs = get_remote_state ();
12716 buf = rs->buf;
12717 endbuf = buf + get_remote_packet_size ();
12718
12719 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12720 if (packet_config_support (packet) == PACKET_ENABLE
12721 && conf->bts.size != rs->btrace_config.bts.size)
12722 {
12723 pos = buf;
12724 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12725 conf->bts.size);
12726
12727 putpkt (buf);
12728 getpkt (&buf, &rs->buf_size, 0);
12729
12730 if (packet_ok (buf, packet) == PACKET_ERROR)
12731 {
12732 if (buf[0] == 'E' && buf[1] == '.')
12733 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12734 else
12735 error (_("Failed to configure the BTS buffer size."));
12736 }
12737
12738 rs->btrace_config.bts.size = conf->bts.size;
12739 }
b20a6524
MM
12740
12741 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12742 if (packet_config_support (packet) == PACKET_ENABLE
12743 && conf->pt.size != rs->btrace_config.pt.size)
12744 {
12745 pos = buf;
12746 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12747 conf->pt.size);
12748
12749 putpkt (buf);
12750 getpkt (&buf, &rs->buf_size, 0);
12751
12752 if (packet_ok (buf, packet) == PACKET_ERROR)
12753 {
12754 if (buf[0] == 'E' && buf[1] == '.')
12755 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12756 else
12757 error (_("Failed to configure the trace buffer size."));
12758 }
12759
12760 rs->btrace_config.pt.size = conf->pt.size;
12761 }
f4abbc16
MM
12762}
12763
12764/* Read the current thread's btrace configuration from the target and
12765 store it into CONF. */
12766
12767static void
12768btrace_read_config (struct btrace_config *conf)
12769{
12770 char *xml;
12771
12772 xml = target_read_stralloc (&current_target,
b20a6524 12773 TARGET_OBJECT_BTRACE_CONF, "");
f4abbc16
MM
12774 if (xml != NULL)
12775 {
12776 struct cleanup *cleanup;
12777
12778 cleanup = make_cleanup (xfree, xml);
12779 parse_xml_btrace_conf (conf, xml);
12780 do_cleanups (cleanup);
12781 }
12782}
12783
c0272db5
TW
12784/* Maybe reopen target btrace. */
12785
12786static void
12787remote_btrace_maybe_reopen (void)
12788{
12789 struct remote_state *rs = get_remote_state ();
12790 struct cleanup *cleanup;
12791 struct thread_info *tp;
12792 int btrace_target_pushed = 0;
12793 int warned = 0;
12794
12795 cleanup = make_cleanup_restore_current_thread ();
12796 ALL_NON_EXITED_THREADS (tp)
12797 {
12798 set_general_thread (tp->ptid);
12799
12800 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
12801 btrace_read_config (&rs->btrace_config);
12802
12803 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
12804 continue;
12805
12806#if !defined (HAVE_LIBIPT)
12807 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
12808 {
12809 if (!warned)
12810 {
12811 warned = 1;
12812 warning (_("GDB does not support Intel Processor Trace. "
12813 "\"record\" will not work in this session."));
12814 }
12815
12816 continue;
12817 }
12818#endif /* !defined (HAVE_LIBIPT) */
12819
12820 /* Push target, once, but before anything else happens. This way our
12821 changes to the threads will be cleaned up by unpushing the target
12822 in case btrace_read_config () throws. */
12823 if (!btrace_target_pushed)
12824 {
12825 btrace_target_pushed = 1;
12826 record_btrace_push_target ();
12827 printf_filtered (_("Target is recording using %s.\n"),
12828 btrace_format_string (rs->btrace_config.format));
12829 }
12830
12831 tp->btrace.target = XCNEW (struct btrace_target_info);
12832 tp->btrace.target->ptid = tp->ptid;
12833 tp->btrace.target->conf = rs->btrace_config;
12834 }
12835 do_cleanups (cleanup);
12836}
12837
9accd112
MM
12838/* Enable branch tracing. */
12839
12840static struct btrace_target_info *
f4abbc16
MM
12841remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12842 const struct btrace_config *conf)
9accd112
MM
12843{
12844 struct btrace_target_info *tinfo = NULL;
b20a6524 12845 struct packet_config *packet = NULL;
9accd112
MM
12846 struct remote_state *rs = get_remote_state ();
12847 char *buf = rs->buf;
12848 char *endbuf = rs->buf + get_remote_packet_size ();
12849
b20a6524
MM
12850 switch (conf->format)
12851 {
12852 case BTRACE_FORMAT_BTS:
12853 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12854 break;
12855
12856 case BTRACE_FORMAT_PT:
12857 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12858 break;
12859 }
12860
12861 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12862 error (_("Target does not support branch tracing."));
12863
f4abbc16
MM
12864 btrace_sync_conf (conf);
12865
9accd112
MM
12866 set_general_thread (ptid);
12867
12868 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12869 putpkt (rs->buf);
12870 getpkt (&rs->buf, &rs->buf_size, 0);
12871
12872 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12873 {
12874 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12875 error (_("Could not enable branch tracing for %s: %s"),
12876 target_pid_to_str (ptid), rs->buf + 2);
12877 else
12878 error (_("Could not enable branch tracing for %s."),
12879 target_pid_to_str (ptid));
12880 }
12881
8d749320 12882 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
12883 tinfo->ptid = ptid;
12884
f4abbc16
MM
12885 /* If we fail to read the configuration, we lose some information, but the
12886 tracing itself is not impacted. */
492d29ea
PA
12887 TRY
12888 {
12889 btrace_read_config (&tinfo->conf);
12890 }
12891 CATCH (err, RETURN_MASK_ERROR)
12892 {
12893 if (err.message != NULL)
12894 warning ("%s", err.message);
12895 }
12896 END_CATCH
f4abbc16 12897
9accd112
MM
12898 return tinfo;
12899}
12900
12901/* Disable branch tracing. */
12902
12903static void
25e95349
TT
12904remote_disable_btrace (struct target_ops *self,
12905 struct btrace_target_info *tinfo)
9accd112
MM
12906{
12907 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12908 struct remote_state *rs = get_remote_state ();
12909 char *buf = rs->buf;
12910 char *endbuf = rs->buf + get_remote_packet_size ();
12911
4082afcc 12912 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12913 error (_("Target does not support branch tracing."));
12914
12915 set_general_thread (tinfo->ptid);
12916
12917 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12918 putpkt (rs->buf);
12919 getpkt (&rs->buf, &rs->buf_size, 0);
12920
12921 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12922 {
12923 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12924 error (_("Could not disable branch tracing for %s: %s"),
12925 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12926 else
12927 error (_("Could not disable branch tracing for %s."),
12928 target_pid_to_str (tinfo->ptid));
12929 }
12930
12931 xfree (tinfo);
12932}
12933
12934/* Teardown branch tracing. */
12935
12936static void
1777056d
TT
12937remote_teardown_btrace (struct target_ops *self,
12938 struct btrace_target_info *tinfo)
9accd112
MM
12939{
12940 /* We must not talk to the target during teardown. */
12941 xfree (tinfo);
12942}
12943
12944/* Read the branch trace. */
12945
969c39fb 12946static enum btrace_error
39c49f83 12947remote_read_btrace (struct target_ops *self,
734b0e4b 12948 struct btrace_data *btrace,
969c39fb 12949 struct btrace_target_info *tinfo,
9accd112
MM
12950 enum btrace_read_type type)
12951{
12952 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
969c39fb 12953 struct cleanup *cleanup;
9accd112
MM
12954 const char *annex;
12955 char *xml;
12956
4082afcc 12957 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12958 error (_("Target does not support branch tracing."));
12959
12960#if !defined(HAVE_LIBEXPAT)
12961 error (_("Cannot process branch tracing result. XML parsing not supported."));
12962#endif
12963
12964 switch (type)
12965 {
864089d2 12966 case BTRACE_READ_ALL:
9accd112
MM
12967 annex = "all";
12968 break;
864089d2 12969 case BTRACE_READ_NEW:
9accd112
MM
12970 annex = "new";
12971 break;
969c39fb
MM
12972 case BTRACE_READ_DELTA:
12973 annex = "delta";
12974 break;
9accd112
MM
12975 default:
12976 internal_error (__FILE__, __LINE__,
12977 _("Bad branch tracing read type: %u."),
12978 (unsigned int) type);
12979 }
12980
12981 xml = target_read_stralloc (&current_target,
b20a6524 12982 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
12983 if (xml == NULL)
12984 return BTRACE_ERR_UNKNOWN;
9accd112 12985
969c39fb 12986 cleanup = make_cleanup (xfree, xml);
734b0e4b 12987 parse_xml_btrace (btrace, xml);
969c39fb 12988 do_cleanups (cleanup);
9accd112 12989
969c39fb 12990 return BTRACE_ERR_NONE;
9accd112
MM
12991}
12992
f4abbc16
MM
12993static const struct btrace_config *
12994remote_btrace_conf (struct target_ops *self,
12995 const struct btrace_target_info *tinfo)
12996{
12997 return &tinfo->conf;
12998}
12999
ced63ec0 13000static int
5436ff03 13001remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 13002{
4082afcc
PA
13003 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13004 == PACKET_ENABLE);
ced63ec0
GB
13005}
13006
9dd130a0
TT
13007/* Implementation of to_load. */
13008
13009static void
9cbe5fff 13010remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
13011{
13012 generic_load (name, from_tty);
13013}
13014
c78fa86a
GB
13015/* Accepts an integer PID; returns a string representing a file that
13016 can be opened on the remote side to get the symbols for the child
13017 process. Returns NULL if the operation is not supported. */
13018
13019static char *
13020remote_pid_to_exec_file (struct target_ops *self, int pid)
13021{
13022 static char *filename = NULL;
835205d0
GB
13023 struct inferior *inf;
13024 char *annex = NULL;
c78fa86a
GB
13025
13026 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13027 return NULL;
13028
13029 if (filename != NULL)
13030 xfree (filename);
13031
835205d0
GB
13032 inf = find_inferior_pid (pid);
13033 if (inf == NULL)
13034 internal_error (__FILE__, __LINE__,
13035 _("not currently attached to process %d"), pid);
13036
13037 if (!inf->fake_pid_p)
13038 {
13039 const int annex_size = 9;
13040
224c3ddb 13041 annex = (char *) alloca (annex_size);
835205d0
GB
13042 xsnprintf (annex, annex_size, "%x", pid);
13043 }
13044
c78fa86a
GB
13045 filename = target_read_stralloc (&current_target,
13046 TARGET_OBJECT_EXEC_FILE, annex);
13047
13048 return filename;
13049}
13050
750ce8d1
YQ
13051/* Implement the to_can_do_single_step target_ops method. */
13052
13053static int
13054remote_can_do_single_step (struct target_ops *ops)
13055{
13056 /* We can only tell whether target supports single step or not by
13057 supported s and S vCont actions if the stub supports vContSupported
13058 feature. If the stub doesn't support vContSupported feature,
13059 we have conservatively to think target doesn't supports single
13060 step. */
13061 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13062 {
13063 struct remote_state *rs = get_remote_state ();
13064
13065 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13066 remote_vcont_probe (rs);
13067
13068 return rs->supports_vCont.s && rs->supports_vCont.S;
13069 }
13070 else
13071 return 0;
13072}
13073
3a00c802
PA
13074/* Implementation of the to_execution_direction method for the remote
13075 target. */
13076
13077static enum exec_direction_kind
13078remote_execution_direction (struct target_ops *self)
13079{
13080 struct remote_state *rs = get_remote_state ();
13081
13082 return rs->last_resume_exec_dir;
13083}
13084
c906108c 13085static void
fba45db2 13086init_remote_ops (void)
c906108c 13087{
c5aa993b 13088 remote_ops.to_shortname = "remote";
c906108c 13089 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 13090 remote_ops.to_doc =
c906108c 13091 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
13092Specify the serial device it is connected to\n\
13093(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
13094 remote_ops.to_open = remote_open;
13095 remote_ops.to_close = remote_close;
c906108c 13096 remote_ops.to_detach = remote_detach;
6ad8ae5c 13097 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 13098 remote_ops.to_resume = remote_resume;
c906108c
SS
13099 remote_ops.to_wait = remote_wait;
13100 remote_ops.to_fetch_registers = remote_fetch_registers;
13101 remote_ops.to_store_registers = remote_store_registers;
13102 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 13103 remote_ops.to_files_info = remote_files_info;
c906108c
SS
13104 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13105 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
13106 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13107 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13108 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13109 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
13110 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13111 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
13112 remote_ops.to_watchpoint_addr_within_range =
13113 remote_watchpoint_addr_within_range;
3c3bea1c
GS
13114 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13115 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13116 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
13117 remote_ops.to_region_ok_for_hw_watchpoint
13118 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
13119 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13120 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 13121 remote_ops.to_kill = remote_kill;
9dd130a0 13122 remote_ops.to_load = remote_load;
c906108c 13123 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 13124 remote_ops.to_pass_signals = remote_pass_signals;
82075af2 13125 remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
9b224c5e 13126 remote_ops.to_program_signals = remote_program_signals;
c906108c 13127 remote_ops.to_thread_alive = remote_thread_alive;
79efa585 13128 remote_ops.to_thread_name = remote_thread_name;
e8032dde 13129 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 13130 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 13131 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 13132 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 13133 remote_ops.to_stop = remote_stop;
bfedc46a 13134 remote_ops.to_interrupt = remote_interrupt;
93692b58 13135 remote_ops.to_pass_ctrlc = remote_pass_ctrlc;
4b8a223f 13136 remote_ops.to_xfer_partial = remote_xfer_partial;
09c98b44 13137 remote_ops.to_get_memory_xfer_limit = remote_get_memory_xfer_limit;
96baa820 13138 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 13139 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 13140 remote_ops.to_log_command = serial_log_command;
38691318 13141 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 13142 remote_ops.to_stratum = process_stratum;
c35b1492
PA
13143 remote_ops.to_has_all_memory = default_child_has_all_memory;
13144 remote_ops.to_has_memory = default_child_has_memory;
13145 remote_ops.to_has_stack = default_child_has_stack;
13146 remote_ops.to_has_registers = default_child_has_registers;
13147 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 13148 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 13149 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 13150 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 13151 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
13152 remote_ops.to_flash_erase = remote_flash_erase;
13153 remote_ops.to_flash_done = remote_flash_done;
29709017 13154 remote_ops.to_read_description = remote_read_description;
08388c79 13155 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
13156 remote_ops.to_can_async_p = remote_can_async_p;
13157 remote_ops.to_is_async_p = remote_is_async_p;
13158 remote_ops.to_async = remote_async;
65706a29 13159 remote_ops.to_thread_events = remote_thread_events;
750ce8d1 13160 remote_ops.to_can_do_single_step = remote_can_do_single_step;
75c99385
PA
13161 remote_ops.to_terminal_inferior = remote_terminal_inferior;
13162 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 13163 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 13164 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
13165 remote_ops.to_supports_disable_randomization
13166 = remote_supports_disable_randomization;
4bd7dc42 13167 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
13168 remote_ops.to_fileio_open = remote_hostio_open;
13169 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13170 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 13171 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
13172 remote_ops.to_fileio_close = remote_hostio_close;
13173 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 13174 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 13175 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 13176 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 13177 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 13178 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
13179 remote_ops.to_trace_init = remote_trace_init;
13180 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 13181 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
13182 remote_ops.to_download_trace_state_variable
13183 = remote_download_trace_state_variable;
d248b706
KY
13184 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13185 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
13186 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13187 remote_ops.to_trace_start = remote_trace_start;
13188 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 13189 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
13190 remote_ops.to_trace_stop = remote_trace_stop;
13191 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
13192 remote_ops.to_get_trace_state_variable_value
13193 = remote_get_trace_state_variable_value;
00bf0b85
SS
13194 remote_ops.to_save_trace_data = remote_save_trace_data;
13195 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
13196 remote_ops.to_upload_trace_state_variables
13197 = remote_upload_trace_state_variables;
00bf0b85 13198 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 13199 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 13200 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 13201 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 13202 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 13203 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 13204 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 13205 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 13206 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 13207 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
13208 remote_ops.to_static_tracepoint_marker_at
13209 = remote_static_tracepoint_marker_at;
13210 remote_ops.to_static_tracepoint_markers_by_strid
13211 = remote_static_tracepoint_markers_by_strid;
b3b9301e 13212 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
13213 remote_ops.to_use_agent = remote_use_agent;
13214 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
13215 remote_ops.to_supports_btrace = remote_supports_btrace;
13216 remote_ops.to_enable_btrace = remote_enable_btrace;
13217 remote_ops.to_disable_btrace = remote_disable_btrace;
13218 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13219 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 13220 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
13221 remote_ops.to_augmented_libraries_svr4_read =
13222 remote_augmented_libraries_svr4_read;
8020350c
DB
13223 remote_ops.to_follow_fork = remote_follow_fork;
13224 remote_ops.to_follow_exec = remote_follow_exec;
13225 remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13226 remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13227 remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13228 remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13229 remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13230 remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
3a00c802 13231 remote_ops.to_execution_direction = remote_execution_direction;
c906108c
SS
13232}
13233
13234/* Set up the extended remote vector by making a copy of the standard
13235 remote vector and adding to it. */
13236
13237static void
fba45db2 13238init_extended_remote_ops (void)
c906108c
SS
13239{
13240 extended_remote_ops = remote_ops;
13241
0f71a2f6 13242 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 13243 extended_remote_ops.to_longname =
c906108c 13244 "Extended remote serial target in gdb-specific protocol";
c5aa993b 13245 extended_remote_ops.to_doc =
c906108c 13246 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
13247Specify the serial device it is connected to (e.g. /dev/ttya).";
13248 extended_remote_ops.to_open = extended_remote_open;
c906108c 13249 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
2d717e4f
DJ
13250 extended_remote_ops.to_detach = extended_remote_detach;
13251 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 13252 extended_remote_ops.to_post_attach = extended_remote_post_attach;
03583c20
UW
13253 extended_remote_ops.to_supports_disable_randomization
13254 = extended_remote_supports_disable_randomization;
0f71a2f6
JM
13255}
13256
6426a772 13257static int
6a109b6b 13258remote_can_async_p (struct target_ops *ops)
6426a772 13259{
5d93a237
TT
13260 struct remote_state *rs = get_remote_state ();
13261
c6ebd6cf 13262 if (!target_async_permitted)
75c99385
PA
13263 /* We only enable async when the user specifically asks for it. */
13264 return 0;
13265
23860348 13266 /* We're async whenever the serial device is. */
5d93a237 13267 return serial_can_async_p (rs->remote_desc);
6426a772
JM
13268}
13269
13270static int
6a109b6b 13271remote_is_async_p (struct target_ops *ops)
6426a772 13272{
5d93a237
TT
13273 struct remote_state *rs = get_remote_state ();
13274
c6ebd6cf 13275 if (!target_async_permitted)
75c99385
PA
13276 /* We only enable async when the user specifically asks for it. */
13277 return 0;
13278
23860348 13279 /* We're async whenever the serial device is. */
5d93a237 13280 return serial_is_async_p (rs->remote_desc);
6426a772
JM
13281}
13282
2acceee2
JM
13283/* Pass the SERIAL event on and up to the client. One day this code
13284 will be able to delay notifying the client of an event until the
23860348 13285 point where an entire packet has been received. */
2acceee2 13286
2acceee2
JM
13287static serial_event_ftype remote_async_serial_handler;
13288
6426a772 13289static void
819cc324 13290remote_async_serial_handler (struct serial *scb, void *context)
6426a772 13291{
2acceee2
JM
13292 /* Don't propogate error information up to the client. Instead let
13293 the client find out about the error by querying the target. */
6a3753b3 13294 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
13295}
13296
74531fed
PA
13297static void
13298remote_async_inferior_event_handler (gdb_client_data data)
13299{
13300 inferior_event_handler (INF_REG_EVENT, NULL);
13301}
13302
2acceee2 13303static void
6a3753b3 13304remote_async (struct target_ops *ops, int enable)
2acceee2 13305{
5d93a237
TT
13306 struct remote_state *rs = get_remote_state ();
13307
6a3753b3 13308 if (enable)
2acceee2 13309 {
88b496c3 13310 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
13311
13312 /* If there are pending events in the stop reply queue tell the
13313 event loop to process them. */
13314 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13315 mark_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13316 /* For simplicity, below we clear the pending events token
13317 without remembering whether it is marked, so here we always
13318 mark it. If there's actually no pending notification to
13319 process, this ends up being a no-op (other than a spurious
13320 event-loop wakeup). */
13321 if (target_is_non_stop_p ())
13322 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
13323 }
13324 else
b7d2e916
PA
13325 {
13326 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
13327 /* If the core is disabling async, it doesn't want to be
13328 disturbed with target events. Clear all async event sources
13329 too. */
b7d2e916 13330 clear_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13331 if (target_is_non_stop_p ())
13332 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 13333 }
6426a772
JM
13334}
13335
65706a29
PA
13336/* Implementation of the to_thread_events method. */
13337
13338static void
13339remote_thread_events (struct target_ops *ops, int enable)
13340{
13341 struct remote_state *rs = get_remote_state ();
13342 size_t size = get_remote_packet_size ();
65706a29
PA
13343
13344 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13345 return;
13346
13347 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13348 putpkt (rs->buf);
13349 getpkt (&rs->buf, &rs->buf_size, 0);
13350
13351 switch (packet_ok (rs->buf,
13352 &remote_protocol_packets[PACKET_QThreadEvents]))
13353 {
13354 case PACKET_OK:
13355 if (strcmp (rs->buf, "OK") != 0)
13356 error (_("Remote refused setting thread events: %s"), rs->buf);
13357 break;
13358 case PACKET_ERROR:
13359 warning (_("Remote failure reply: %s"), rs->buf);
13360 break;
13361 case PACKET_UNKNOWN:
13362 break;
13363 }
13364}
13365
5a2468f5 13366static void
c2d11a7d 13367set_remote_cmd (char *args, int from_tty)
5a2468f5 13368{
635c7e8a 13369 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
13370}
13371
d471ea57
AC
13372static void
13373show_remote_cmd (char *args, int from_tty)
13374{
37a105a1 13375 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 13376 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
13377 struct cleanup *showlist_chain;
13378 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 13379 struct ui_out *uiout = current_uiout;
37a105a1
DJ
13380
13381 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13382 for (; list != NULL; list = list->next)
13383 if (strcmp (list->name, "Z-packet") == 0)
13384 continue;
427c3a89
DJ
13385 else if (list->type == not_set_cmd)
13386 /* Alias commands are exactly like the original, except they
13387 don't have the normal type. */
13388 continue;
13389 else
37a105a1
DJ
13390 {
13391 struct cleanup *option_chain
13392 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 13393
37a105a1
DJ
13394 ui_out_field_string (uiout, "name", list->name);
13395 ui_out_text (uiout, ": ");
427c3a89 13396 if (list->type == show_cmd)
5b9afe8a 13397 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
13398 else
13399 cmd_func (list, NULL, from_tty);
37a105a1
DJ
13400 /* Close the tuple. */
13401 do_cleanups (option_chain);
13402 }
427c3a89
DJ
13403
13404 /* Close the tuple. */
13405 do_cleanups (showlist_chain);
d471ea57 13406}
5a2468f5 13407
0f71a2f6 13408
23860348 13409/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
13410static void
13411remote_new_objfile (struct objfile *objfile)
13412{
5d93a237
TT
13413 struct remote_state *rs = get_remote_state ();
13414
13415 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 13416 remote_check_symbols ();
dc8acb97
MS
13417}
13418
00bf0b85
SS
13419/* Pull all the tracepoints defined on the target and create local
13420 data structures representing them. We don't want to create real
13421 tracepoints yet, we don't want to mess up the user's existing
13422 collection. */
13423
13424static int
ab6617cc 13425remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 13426{
00bf0b85
SS
13427 struct remote_state *rs = get_remote_state ();
13428 char *p;
d5551862 13429
00bf0b85
SS
13430 /* Ask for a first packet of tracepoint definition. */
13431 putpkt ("qTfP");
13432 getpkt (&rs->buf, &rs->buf_size, 0);
13433 p = rs->buf;
13434 while (*p && *p != 'l')
d5551862 13435 {
00bf0b85
SS
13436 parse_tracepoint_definition (p, utpp);
13437 /* Ask for another packet of tracepoint definition. */
13438 putpkt ("qTsP");
13439 getpkt (&rs->buf, &rs->buf_size, 0);
13440 p = rs->buf;
d5551862 13441 }
00bf0b85 13442 return 0;
d5551862
SS
13443}
13444
00bf0b85 13445static int
181e3713
TT
13446remote_upload_trace_state_variables (struct target_ops *self,
13447 struct uploaded_tsv **utsvp)
d5551862 13448{
00bf0b85 13449 struct remote_state *rs = get_remote_state ();
d5551862 13450 char *p;
d5551862 13451
00bf0b85
SS
13452 /* Ask for a first packet of variable definition. */
13453 putpkt ("qTfV");
d5551862
SS
13454 getpkt (&rs->buf, &rs->buf_size, 0);
13455 p = rs->buf;
00bf0b85 13456 while (*p && *p != 'l')
d5551862 13457 {
00bf0b85
SS
13458 parse_tsv_definition (p, utsvp);
13459 /* Ask for another packet of variable definition. */
13460 putpkt ("qTsV");
d5551862
SS
13461 getpkt (&rs->buf, &rs->buf_size, 0);
13462 p = rs->buf;
13463 }
00bf0b85 13464 return 0;
d5551862
SS
13465}
13466
c1e36e3e
PA
13467/* The "set/show range-stepping" show hook. */
13468
13469static void
13470show_range_stepping (struct ui_file *file, int from_tty,
13471 struct cmd_list_element *c,
13472 const char *value)
13473{
13474 fprintf_filtered (file,
13475 _("Debugger's willingness to use range stepping "
13476 "is %s.\n"), value);
13477}
13478
13479/* The "set/show range-stepping" set hook. */
13480
13481static void
13482set_range_stepping (char *ignore_args, int from_tty,
13483 struct cmd_list_element *c)
13484{
5d93a237
TT
13485 struct remote_state *rs = get_remote_state ();
13486
c1e36e3e
PA
13487 /* Whene enabling, check whether range stepping is actually
13488 supported by the target, and warn if not. */
13489 if (use_range_stepping)
13490 {
5d93a237 13491 if (rs->remote_desc != NULL)
c1e36e3e 13492 {
4082afcc 13493 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
13494 remote_vcont_probe (rs);
13495
4082afcc 13496 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
13497 && rs->supports_vCont.r)
13498 return;
13499 }
13500
13501 warning (_("Range stepping is not supported by the current target"));
13502 }
13503}
13504
c906108c 13505void
fba45db2 13506_initialize_remote (void)
c906108c 13507{
9a7071a8 13508 struct cmd_list_element *cmd;
6f937416 13509 const char *cmd_name;
ea9c271d 13510
0f71a2f6 13511 /* architecture specific data */
2bc416ba 13512 remote_gdbarch_data_handle =
23860348 13513 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
13514 remote_g_packet_data_handle =
13515 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 13516
94585166
DB
13517 remote_pspace_data
13518 = register_program_space_data_with_cleanup (NULL,
13519 remote_pspace_data_cleanup);
13520
ea9c271d
DJ
13521 /* Initialize the per-target state. At the moment there is only one
13522 of these, not one per target. Only one target is active at a
cf792862
TT
13523 time. */
13524 remote_state = new_remote_state ();
ea9c271d 13525
c906108c
SS
13526 init_remote_ops ();
13527 add_target (&remote_ops);
13528
13529 init_extended_remote_ops ();
13530 add_target (&extended_remote_ops);
cce74817 13531
dc8acb97 13532 /* Hook into new objfile notification. */
06d3b283 13533 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
13534 /* We're no longer interested in notification events of an inferior
13535 when it exits. */
13536 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 13537
c906108c
SS
13538#if 0
13539 init_remote_threadtests ();
13540#endif
13541
722247f1 13542 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 13543 /* set/show remote ... */
d471ea57 13544
1bedd215 13545 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
13546Remote protocol specific variables\n\
13547Configure various remote-protocol specific variables such as\n\
1bedd215 13548the packets being used"),
cff3e48b 13549 &remote_set_cmdlist, "set remote ",
23860348 13550 0 /* allow-unknown */, &setlist);
1bedd215 13551 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
13552Remote protocol specific variables\n\
13553Configure various remote-protocol specific variables such as\n\
1bedd215 13554the packets being used"),
cff3e48b 13555 &remote_show_cmdlist, "show remote ",
23860348 13556 0 /* allow-unknown */, &showlist);
5a2468f5 13557
1a966eab
AC
13558 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13559Compare section data on target to the exec file.\n\
95cf3b38
DT
13560Argument is a single section name (default: all loaded sections).\n\
13561To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
13562 &cmdlist);
13563
1a966eab
AC
13564 add_cmd ("packet", class_maintenance, packet_command, _("\
13565Send an arbitrary packet to a remote target.\n\
c906108c
SS
13566 maintenance packet TEXT\n\
13567If GDB is talking to an inferior via the GDB serial protocol, then\n\
13568this command sends the string TEXT to the inferior, and displays the\n\
13569response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 13570terminating `#' character and checksum."),
c906108c
SS
13571 &maintenancelist);
13572
7915a72c
AC
13573 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13574Set whether to send break if interrupted."), _("\
13575Show whether to send break if interrupted."), _("\
13576If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 13577 set_remotebreak, show_remotebreak,
e707bbc2 13578 &setlist, &showlist);
9a7071a8
JB
13579 cmd_name = "remotebreak";
13580 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13581 deprecate_cmd (cmd, "set remote interrupt-sequence");
13582 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13583 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13584 deprecate_cmd (cmd, "show remote interrupt-sequence");
13585
13586 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
13587 interrupt_sequence_modes, &interrupt_sequence_mode,
13588 _("\
9a7071a8
JB
13589Set interrupt sequence to remote target."), _("\
13590Show interrupt sequence to remote target."), _("\
13591Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13592 NULL, show_interrupt_sequence,
13593 &remote_set_cmdlist,
13594 &remote_show_cmdlist);
13595
13596 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13597 &interrupt_on_connect, _("\
13598Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13599Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13600If set, interrupt sequence is sent to remote target."),
13601 NULL, NULL,
13602 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 13603
23860348 13604 /* Install commands for configuring memory read/write packets. */
11cf8741 13605
1a966eab
AC
13606 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13607Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 13608 &setlist);
1a966eab
AC
13609 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13610Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
13611 &showlist);
13612 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
13613 set_memory_write_packet_size, _("\
13614Set the maximum number of bytes per memory-write packet.\n\
13615Specify the number of bytes in a packet or 0 (zero) for the\n\
13616default packet size. The actual limit is further reduced\n\
13617dependent on the target. Specify ``fixed'' to disable the\n\
13618further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13619 &remote_set_cmdlist);
13620 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
13621 set_memory_read_packet_size, _("\
13622Set the maximum number of bytes per memory-read packet.\n\
13623Specify the number of bytes in a packet or 0 (zero) for the\n\
13624default packet size. The actual limit is further reduced\n\
13625dependent on the target. Specify ``fixed'' to disable the\n\
13626further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13627 &remote_set_cmdlist);
13628 add_cmd ("memory-write-packet-size", no_class,
13629 show_memory_write_packet_size,
1a966eab 13630 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
13631 &remote_show_cmdlist);
13632 add_cmd ("memory-read-packet-size", no_class,
13633 show_memory_read_packet_size,
1a966eab 13634 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 13635 &remote_show_cmdlist);
c906108c 13636
b3f42336 13637 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
13638 &remote_hw_watchpoint_limit, _("\
13639Set the maximum number of target hardware watchpoints."), _("\
13640Show the maximum number of target hardware watchpoints."), _("\
13641Specify a negative limit for unlimited."),
3e43a32a
MS
13642 NULL, NULL, /* FIXME: i18n: The maximum
13643 number of target hardware
13644 watchpoints is %s. */
b3f42336 13645 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
13646 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13647 &remote_hw_watchpoint_length_limit, _("\
13648Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13649Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13650Specify a negative limit for unlimited."),
13651 NULL, NULL, /* FIXME: i18n: The maximum
13652 length (in bytes) of a target
13653 hardware watchpoint is %s. */
13654 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 13655 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
13656 &remote_hw_breakpoint_limit, _("\
13657Set the maximum number of target hardware breakpoints."), _("\
13658Show the maximum number of target hardware breakpoints."), _("\
13659Specify a negative limit for unlimited."),
3e43a32a
MS
13660 NULL, NULL, /* FIXME: i18n: The maximum
13661 number of target hardware
13662 breakpoints is %s. */
b3f42336 13663 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 13664
1b493192
PA
13665 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13666 &remote_address_size, _("\
4d28ad1e
AC
13667Set the maximum size of the address (in bits) in a memory packet."), _("\
13668Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
13669 NULL,
13670 NULL, /* FIXME: i18n: */
13671 &setlist, &showlist);
c906108c 13672
ca4f7f8b
PA
13673 init_all_packet_configs ();
13674
444abaca 13675 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 13676 "X", "binary-download", 1);
0f71a2f6 13677
444abaca 13678 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 13679 "vCont", "verbose-resume", 0);
506fb367 13680
89be2091
DJ
13681 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13682 "QPassSignals", "pass-signals", 0);
13683
82075af2
JS
13684 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
13685 "QCatchSyscalls", "catch-syscalls", 0);
13686
9b224c5e
PA
13687 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13688 "QProgramSignals", "program-signals", 0);
13689
444abaca 13690 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 13691 "qSymbol", "symbol-lookup", 0);
dc8acb97 13692
444abaca 13693 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 13694 "P", "set-register", 1);
d471ea57 13695
444abaca 13696 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 13697 "p", "fetch-register", 1);
b96ec7ac 13698
444abaca 13699 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 13700 "Z0", "software-breakpoint", 0);
d471ea57 13701
444abaca 13702 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 13703 "Z1", "hardware-breakpoint", 0);
d471ea57 13704
444abaca 13705 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 13706 "Z2", "write-watchpoint", 0);
d471ea57 13707
444abaca 13708 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 13709 "Z3", "read-watchpoint", 0);
d471ea57 13710
444abaca 13711 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 13712 "Z4", "access-watchpoint", 0);
d471ea57 13713
0876f84a
DJ
13714 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13715 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 13716
c78fa86a
GB
13717 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13718 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13719
23181151
DJ
13720 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13721 "qXfer:features:read", "target-features", 0);
13722
cfa9d6d9
DJ
13723 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13724 "qXfer:libraries:read", "library-info", 0);
13725
2268b414
JK
13726 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13727 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13728
fd79ecee
DJ
13729 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13730 "qXfer:memory-map:read", "memory-map", 0);
13731
0e7f50da
UW
13732 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13733 "qXfer:spu:read", "read-spu-object", 0);
13734
13735 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13736 "qXfer:spu:write", "write-spu-object", 0);
13737
07e059b5
VP
13738 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13739 "qXfer:osdata:read", "osdata", 0);
13740
dc146f7c
VP
13741 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13742 "qXfer:threads:read", "threads", 0);
13743
4aa995e1
PA
13744 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13745 "qXfer:siginfo:read", "read-siginfo-object", 0);
13746
13747 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13748 "qXfer:siginfo:write", "write-siginfo-object", 0);
13749
b3b9301e
PA
13750 add_packet_config_cmd
13751 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 13752 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 13753
169081d0
TG
13754 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13755 "qXfer:uib:read", "unwind-info-block", 0);
13756
444abaca 13757 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 13758 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
13759 0);
13760
711e434b
PM
13761 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13762 "qGetTIBAddr", "get-thread-information-block-address",
13763 0);
13764
40ab02ce
MS
13765 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13766 "bc", "reverse-continue", 0);
13767
13768 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13769 "bs", "reverse-step", 0);
13770
be2a5f71
DJ
13771 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13772 "qSupported", "supported-packets", 0);
13773
08388c79
DE
13774 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13775 "qSearch:memory", "search-memory", 0);
13776
bd3eecc3
PA
13777 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13778 "qTStatus", "trace-status", 0);
13779
15a201c8
GB
13780 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13781 "vFile:setfs", "hostio-setfs", 0);
13782
a6b151f1
DJ
13783 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13784 "vFile:open", "hostio-open", 0);
13785
13786 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13787 "vFile:pread", "hostio-pread", 0);
13788
13789 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13790 "vFile:pwrite", "hostio-pwrite", 0);
13791
13792 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13793 "vFile:close", "hostio-close", 0);
13794
13795 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13796 "vFile:unlink", "hostio-unlink", 0);
13797
b9e7b9c3
UW
13798 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13799 "vFile:readlink", "hostio-readlink", 0);
13800
0a93529c
GB
13801 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13802 "vFile:fstat", "hostio-fstat", 0);
13803
2d717e4f
DJ
13804 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13805 "vAttach", "attach", 0);
13806
13807 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13808 "vRun", "run", 0);
13809
a6f3e723
SL
13810 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13811 "QStartNoAckMode", "noack", 0);
13812
82f73884
PA
13813 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13814 "vKill", "kill", 0);
13815
0b16c5cf
PA
13816 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13817 "qAttached", "query-attached", 0);
13818
782b2b07 13819 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
13820 "ConditionalTracepoints",
13821 "conditional-tracepoints", 0);
3788aec7
LM
13822
13823 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13824 "ConditionalBreakpoints",
13825 "conditional-breakpoints", 0);
13826
d3ce09f5
SS
13827 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13828 "BreakpointCommands",
13829 "breakpoint-commands", 0);
13830
7a697b8d
SS
13831 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13832 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 13833
409873ef
SS
13834 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13835 "TracepointSource", "TracepointSource", 0);
13836
d914c394
SS
13837 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13838 "QAllow", "allow", 0);
13839
0fb4aa4b
PA
13840 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13841 "StaticTracepoints", "static-tracepoints", 0);
13842
1e4d1764
YQ
13843 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13844 "InstallInTrace", "install-in-trace", 0);
13845
0fb4aa4b
PA
13846 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13847 "qXfer:statictrace:read", "read-sdata-object", 0);
13848
78d85199
YQ
13849 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13850 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13851
03583c20
UW
13852 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13853 "QDisableRandomization", "disable-randomization", 0);
13854
d1feda86
YQ
13855 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13856 "QAgent", "agent", 0);
13857
f6f899bf
HAQ
13858 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13859 "QTBuffer:size", "trace-buffer-size", 0);
13860
9accd112
MM
13861 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13862 "Qbtrace:off", "disable-btrace", 0);
13863
13864 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
13865 "Qbtrace:bts", "enable-btrace-bts", 0);
13866
13867 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13868 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
13869
13870 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13871 "qXfer:btrace", "read-btrace", 0);
13872
f4abbc16
MM
13873 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13874 "qXfer:btrace-conf", "read-btrace-conf", 0);
13875
d33501a5
MM
13876 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13877 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13878
73b8c1fd
PA
13879 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13880 "multiprocess-feature", "multiprocess-feature", 0);
13881
f7e6eed5
PA
13882 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13883 "swbreak-feature", "swbreak-feature", 0);
13884
13885 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13886 "hwbreak-feature", "hwbreak-feature", 0);
13887
89245bc0
DB
13888 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13889 "fork-event-feature", "fork-event-feature", 0);
13890
13891 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13892 "vfork-event-feature", "vfork-event-feature", 0);
13893
b20a6524
MM
13894 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13895 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13896
750ce8d1
YQ
13897 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13898 "vContSupported", "verbose-resume-supported", 0);
13899
94585166
DB
13900 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13901 "exec-event-feature", "exec-event-feature", 0);
13902
de979965
PA
13903 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13904 "vCtrlC", "ctrl-c", 0);
13905
65706a29
PA
13906 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
13907 "QThreadEvents", "thread-events", 0);
13908
f2faf941
PA
13909 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
13910 "N stop reply", "no-resumed-stop-reply", 0);
13911
0b736949
DB
13912 /* Assert that we've registered "set remote foo-packet" commands
13913 for all packet configs. */
ca4f7f8b
PA
13914 {
13915 int i;
13916
13917 for (i = 0; i < PACKET_MAX; i++)
13918 {
13919 /* Ideally all configs would have a command associated. Some
13920 still don't though. */
13921 int excepted;
13922
13923 switch (i)
13924 {
13925 case PACKET_QNonStop:
ca4f7f8b
PA
13926 case PACKET_EnableDisableTracepoints_feature:
13927 case PACKET_tracenz_feature:
13928 case PACKET_DisconnectedTracing_feature:
13929 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
13930 case PACKET_qCRC:
13931 /* Additions to this list need to be well justified:
13932 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
13933 excepted = 1;
13934 break;
13935 default:
13936 excepted = 0;
13937 break;
13938 }
13939
13940 /* This catches both forgetting to add a config command, and
13941 forgetting to remove a packet from the exception list. */
13942 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13943 }
13944 }
13945
37a105a1
DJ
13946 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13947 Z sub-packet has its own set and show commands, but users may
13948 have sets to this variable in their .gdbinit files (or in their
13949 documentation). */
e9e68a56 13950 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
13951 &remote_Z_packet_detect, _("\
13952Set use of remote protocol `Z' packets"), _("\
13953Show use of remote protocol `Z' packets "), _("\
3b64bf98 13954When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 13955packets."),
e9e68a56 13956 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
13957 show_remote_protocol_Z_packet_cmd,
13958 /* FIXME: i18n: Use of remote protocol
13959 `Z' packets is %s. */
e9e68a56 13960 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 13961
a6b151f1
DJ
13962 add_prefix_cmd ("remote", class_files, remote_command, _("\
13963Manipulate files on the remote system\n\
13964Transfer files to and from the remote target system."),
13965 &remote_cmdlist, "remote ",
13966 0 /* allow-unknown */, &cmdlist);
13967
13968 add_cmd ("put", class_files, remote_put_command,
13969 _("Copy a local file to the remote system."),
13970 &remote_cmdlist);
13971
13972 add_cmd ("get", class_files, remote_get_command,
13973 _("Copy a remote file to the local system."),
13974 &remote_cmdlist);
13975
13976 add_cmd ("delete", class_files, remote_delete_command,
13977 _("Delete a remote file."),
13978 &remote_cmdlist);
13979
2d717e4f 13980 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 13981 &remote_exec_file_var, _("\
2d717e4f 13982Set the remote pathname for \"run\""), _("\
94585166
DB
13983Show the remote pathname for \"run\""), NULL,
13984 set_remote_exec_file,
13985 show_remote_exec_file,
13986 &remote_set_cmdlist,
13987 &remote_show_cmdlist);
2d717e4f 13988
c1e36e3e
PA
13989 add_setshow_boolean_cmd ("range-stepping", class_run,
13990 &use_range_stepping, _("\
13991Enable or disable range stepping."), _("\
13992Show whether target-assisted range stepping is enabled."), _("\
13993If on, and the target supports it, when stepping a source line, GDB\n\
13994tells the target to step the corresponding range of addresses itself instead\n\
13995of issuing multiple single-steps. This speeds up source level\n\
13996stepping. If off, GDB always issues single-steps, even if range\n\
13997stepping is supported by the target. The default is on."),
13998 set_range_stepping,
13999 show_range_stepping,
14000 &setlist,
14001 &showlist);
14002
449092f6
CV
14003 /* Eventually initialize fileio. See fileio.c */
14004 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 14005
ba348170 14006 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 14007 special ptids with it set to != 0. */
ba348170
PA
14008 magic_null_ptid = ptid_build (42000, -1, 1);
14009 not_sent_ptid = ptid_build (42000, -2, 1);
14010 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
14011
14012 target_buf_size = 2048;
224c3ddb 14013 target_buf = (char *) xmalloc (target_buf_size);
c906108c 14014}
10760264 14015
This page took 3.091254 seconds and 4 git commands to generate.