]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
Allow PROCESSOR_IAMCU for Intel MCU
[thirdparty/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,
73971819
PA
9338 struct bp_target_info *bp_tgt,
9339 enum remove_bp_reason reason)
c906108c 9340{
8181d85f 9341 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 9342 struct remote_state *rs = get_remote_state ();
96baa820 9343
4082afcc 9344 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9345 {
6d820c5c 9346 char *p = rs->buf;
bba74b36 9347 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 9348
28439a30
PA
9349 /* Make sure the remote is pointing at the right process, if
9350 necessary. */
9351 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9352 set_general_process ();
9353
96baa820
JM
9354 *(p++) = 'z';
9355 *(p++) = '0';
9356 *(p++) = ',';
9357
8181d85f
DJ
9358 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9359 p += hexnumstr (p, addr);
bba74b36 9360 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 9361
6d820c5c
DJ
9362 putpkt (rs->buf);
9363 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9364
6d820c5c 9365 return (rs->buf[0] == 'E');
96baa820
JM
9366 }
9367
73971819 9368 return memory_remove_breakpoint (ops, gdbarch, bp_tgt, reason);
c906108c
SS
9369}
9370
f486487f 9371static enum Z_packet_type
d471ea57
AC
9372watchpoint_to_Z_packet (int type)
9373{
9374 switch (type)
9375 {
9376 case hw_write:
bb858e6a 9377 return Z_PACKET_WRITE_WP;
d471ea57
AC
9378 break;
9379 case hw_read:
bb858e6a 9380 return Z_PACKET_READ_WP;
d471ea57
AC
9381 break;
9382 case hw_access:
bb858e6a 9383 return Z_PACKET_ACCESS_WP;
d471ea57
AC
9384 break;
9385 default:
8e65ff28 9386 internal_error (__FILE__, __LINE__,
e2e0b3e5 9387 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
9388 }
9389}
9390
3c3bea1c 9391static int
f486487f
SM
9392remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9393 enum target_hw_bp_type type, struct expression *cond)
96baa820 9394{
d01949b6 9395 struct remote_state *rs = get_remote_state ();
bba74b36 9396 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9397 char *p;
d471ea57 9398 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 9399
4082afcc 9400 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 9401 return 1;
802188a7 9402
28439a30
PA
9403 /* Make sure the remote is pointing at the right process, if
9404 necessary. */
9405 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9406 set_general_process ();
9407
bba74b36 9408 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 9409 p = strchr (rs->buf, '\0');
96baa820
JM
9410 addr = remote_address_masked (addr);
9411 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9412 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 9413
6d820c5c
DJ
9414 putpkt (rs->buf);
9415 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9416
6d820c5c 9417 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9418 {
9419 case PACKET_ERROR:
d471ea57 9420 return -1;
85d721b8
PA
9421 case PACKET_UNKNOWN:
9422 return 1;
d471ea57
AC
9423 case PACKET_OK:
9424 return 0;
9425 }
8e65ff28 9426 internal_error (__FILE__, __LINE__,
e2e0b3e5 9427 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
9428}
9429
283002cf
MR
9430static int
9431remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9432 CORE_ADDR start, int length)
9433{
9434 CORE_ADDR diff = remote_address_masked (addr - start);
9435
9436 return diff < length;
9437}
9438
d471ea57 9439
3c3bea1c 9440static int
f486487f
SM
9441remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9442 enum target_hw_bp_type type, struct expression *cond)
96baa820 9443{
d01949b6 9444 struct remote_state *rs = get_remote_state ();
bba74b36 9445 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9446 char *p;
d471ea57
AC
9447 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9448
4082afcc 9449 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 9450 return -1;
802188a7 9451
28439a30
PA
9452 /* Make sure the remote is pointing at the right process, if
9453 necessary. */
9454 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9455 set_general_process ();
9456
bba74b36 9457 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 9458 p = strchr (rs->buf, '\0');
96baa820
JM
9459 addr = remote_address_masked (addr);
9460 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9461 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
9462 putpkt (rs->buf);
9463 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9464
6d820c5c 9465 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9466 {
9467 case PACKET_ERROR:
9468 case PACKET_UNKNOWN:
9469 return -1;
9470 case PACKET_OK:
9471 return 0;
9472 }
8e65ff28 9473 internal_error (__FILE__, __LINE__,
e2e0b3e5 9474 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
9475}
9476
3c3bea1c 9477
501eef12 9478int remote_hw_watchpoint_limit = -1;
480a3f21 9479int remote_hw_watchpoint_length_limit = -1;
501eef12 9480int remote_hw_breakpoint_limit = -1;
d471ea57 9481
480a3f21 9482static int
31568a15
TT
9483remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9484 CORE_ADDR addr, int len)
480a3f21
PW
9485{
9486 if (remote_hw_watchpoint_length_limit == 0)
9487 return 0;
9488 else if (remote_hw_watchpoint_length_limit < 0)
9489 return 1;
9490 else if (len <= remote_hw_watchpoint_length_limit)
9491 return 1;
9492 else
9493 return 0;
9494}
9495
b9362cc7 9496static int
5461485a 9497remote_check_watch_resources (struct target_ops *self,
f486487f 9498 enum bptype type, int cnt, int ot)
96baa820 9499{
3c3bea1c
GS
9500 if (type == bp_hardware_breakpoint)
9501 {
9502 if (remote_hw_breakpoint_limit == 0)
9503 return 0;
501eef12
AC
9504 else if (remote_hw_breakpoint_limit < 0)
9505 return 1;
3c3bea1c
GS
9506 else if (cnt <= remote_hw_breakpoint_limit)
9507 return 1;
9508 }
9509 else
9510 {
9511 if (remote_hw_watchpoint_limit == 0)
9512 return 0;
501eef12
AC
9513 else if (remote_hw_watchpoint_limit < 0)
9514 return 1;
3c3bea1c
GS
9515 else if (ot)
9516 return -1;
9517 else if (cnt <= remote_hw_watchpoint_limit)
9518 return 1;
9519 }
9520 return -1;
9521}
9522
f7e6eed5
PA
9523/* The to_stopped_by_sw_breakpoint method of target remote. */
9524
9525static int
9526remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9527{
799a2abe 9528 struct thread_info *thread = inferior_thread ();
f7e6eed5 9529
799a2abe
PA
9530 return (thread->priv != NULL
9531 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
f7e6eed5
PA
9532}
9533
9534/* The to_supports_stopped_by_sw_breakpoint method of target
9535 remote. */
9536
9537static int
9538remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9539{
f7e6eed5
PA
9540 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9541}
9542
9543/* The to_stopped_by_hw_breakpoint method of target remote. */
9544
9545static int
9546remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9547{
799a2abe 9548 struct thread_info *thread = inferior_thread ();
f7e6eed5 9549
799a2abe
PA
9550 return (thread->priv != NULL
9551 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
f7e6eed5
PA
9552}
9553
9554/* The to_supports_stopped_by_hw_breakpoint method of target
9555 remote. */
9556
9557static int
9558remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9559{
f7e6eed5
PA
9560 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9561}
9562
b9362cc7 9563static int
6a109b6b 9564remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 9565{
799a2abe 9566 struct thread_info *thread = inferior_thread ();
ee154bee 9567
799a2abe
PA
9568 return (thread->priv != NULL
9569 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
3c3bea1c
GS
9570}
9571
4aa7a7f5
JJ
9572static int
9573remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 9574{
799a2abe 9575 struct thread_info *thread = inferior_thread ();
a744cf53 9576
799a2abe
PA
9577 if (thread->priv != NULL
9578 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
4aa7a7f5 9579 {
799a2abe
PA
9580 *addr_p = thread->priv->watch_data_address;
9581 return 1;
4aa7a7f5
JJ
9582 }
9583
799a2abe 9584 return 0;
3c3bea1c
GS
9585}
9586
9587
9588static int
23a26771 9589remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9590 struct bp_target_info *bp_tgt)
3c3bea1c 9591{
0d5ed153 9592 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9593 struct remote_state *rs;
bba74b36 9594 char *p, *endbuf;
dd61ec5c 9595 char *message;
0d5ed153 9596 int bpsize;
802188a7 9597
c8189ed1 9598 /* The length field should be set to the size of a breakpoint
8181d85f 9599 instruction, even though we aren't inserting one ourselves. */
c8189ed1 9600
0d5ed153 9601 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 9602
4082afcc 9603 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9604 return -1;
2bc416ba 9605
28439a30
PA
9606 /* Make sure the remote is pointing at the right process, if
9607 necessary. */
9608 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9609 set_general_process ();
9610
4fff2411
JZ
9611 rs = get_remote_state ();
9612 p = rs->buf;
bba74b36 9613 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 9614
96baa820
JM
9615 *(p++) = 'Z';
9616 *(p++) = '1';
9617 *(p++) = ',';
802188a7 9618
0d5ed153 9619 addr = remote_address_masked (addr);
96baa820 9620 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 9621 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 9622
efcc2da7 9623 if (remote_supports_cond_breakpoints (self))
bba74b36 9624 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9625
78eff0ec 9626 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
9627 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9628
6d820c5c
DJ
9629 putpkt (rs->buf);
9630 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9631
6d820c5c 9632 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9633 {
9634 case PACKET_ERROR:
dd61ec5c
MW
9635 if (rs->buf[1] == '.')
9636 {
9637 message = strchr (rs->buf + 2, '.');
9638 if (message)
0316657e 9639 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
9640 }
9641 return -1;
d471ea57
AC
9642 case PACKET_UNKNOWN:
9643 return -1;
9644 case PACKET_OK:
0d5ed153
MR
9645 bp_tgt->placed_address = addr;
9646 bp_tgt->placed_size = bpsize;
d471ea57
AC
9647 return 0;
9648 }
8e65ff28 9649 internal_error (__FILE__, __LINE__,
e2e0b3e5 9650 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
9651}
9652
d471ea57 9653
802188a7 9654static int
a64dc96c 9655remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9656 struct bp_target_info *bp_tgt)
96baa820 9657{
8181d85f 9658 CORE_ADDR addr;
d01949b6 9659 struct remote_state *rs = get_remote_state ();
6d820c5c 9660 char *p = rs->buf;
bba74b36 9661 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 9662
4082afcc 9663 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9664 return -1;
802188a7 9665
28439a30
PA
9666 /* Make sure the remote is pointing at the right process, if
9667 necessary. */
9668 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9669 set_general_process ();
9670
96baa820
JM
9671 *(p++) = 'z';
9672 *(p++) = '1';
9673 *(p++) = ',';
802188a7 9674
8181d85f 9675 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 9676 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9677 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 9678
6d820c5c
DJ
9679 putpkt (rs->buf);
9680 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 9681
6d820c5c 9682 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9683 {
9684 case PACKET_ERROR:
9685 case PACKET_UNKNOWN:
9686 return -1;
9687 case PACKET_OK:
9688 return 0;
9689 }
8e65ff28 9690 internal_error (__FILE__, __LINE__,
e2e0b3e5 9691 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 9692}
96baa820 9693
4a5e7a5b
PA
9694/* Verify memory using the "qCRC:" request. */
9695
9696static int
9697remote_verify_memory (struct target_ops *ops,
9698 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9699{
9700 struct remote_state *rs = get_remote_state ();
9701 unsigned long host_crc, target_crc;
9702 char *tmp;
9703
936d2992
PA
9704 /* It doesn't make sense to use qCRC if the remote target is
9705 connected but not running. */
9706 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9707 {
9708 enum packet_result result;
28439a30 9709
936d2992
PA
9710 /* Make sure the remote is pointing at the right process. */
9711 set_general_process ();
4a5e7a5b 9712
936d2992
PA
9713 /* FIXME: assumes lma can fit into long. */
9714 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9715 (long) lma, (long) size);
9716 putpkt (rs->buf);
4a5e7a5b 9717
936d2992
PA
9718 /* Be clever; compute the host_crc before waiting for target
9719 reply. */
9720 host_crc = xcrc32 (data, size, 0xffffffff);
9721
9722 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 9723
936d2992
PA
9724 result = packet_ok (rs->buf,
9725 &remote_protocol_packets[PACKET_qCRC]);
9726 if (result == PACKET_ERROR)
9727 return -1;
9728 else if (result == PACKET_OK)
9729 {
9730 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9731 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 9732
936d2992
PA
9733 return (host_crc == target_crc);
9734 }
9735 }
4a5e7a5b 9736
936d2992 9737 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
9738}
9739
c906108c
SS
9740/* compare-sections command
9741
9742 With no arguments, compares each loadable section in the exec bfd
9743 with the same memory range on the target, and reports mismatches.
4a5e7a5b 9744 Useful for verifying the image on the target against the exec file. */
e514a9d6 9745
c906108c 9746static void
fba45db2 9747compare_sections_command (char *args, int from_tty)
c906108c
SS
9748{
9749 asection *s;
c906108c 9750 struct cleanup *old_chain;
948f8e3d 9751 gdb_byte *sectdata;
ce359b09 9752 const char *sectname;
c906108c
SS
9753 bfd_size_type size;
9754 bfd_vma lma;
9755 int matched = 0;
9756 int mismatched = 0;
4a5e7a5b 9757 int res;
95cf3b38 9758 int read_only = 0;
c906108c
SS
9759
9760 if (!exec_bfd)
8a3fe4f8 9761 error (_("command cannot be used without an exec file"));
c906108c 9762
28439a30
PA
9763 /* Make sure the remote is pointing at the right process. */
9764 set_general_process ();
9765
95cf3b38
DT
9766 if (args != NULL && strcmp (args, "-r") == 0)
9767 {
9768 read_only = 1;
9769 args = NULL;
9770 }
9771
c5aa993b 9772 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
9773 {
9774 if (!(s->flags & SEC_LOAD))
0df8b418 9775 continue; /* Skip non-loadable section. */
c906108c 9776
95cf3b38
DT
9777 if (read_only && (s->flags & SEC_READONLY) == 0)
9778 continue; /* Skip writeable sections */
9779
2c500098 9780 size = bfd_get_section_size (s);
c906108c 9781 if (size == 0)
0df8b418 9782 continue; /* Skip zero-length section. */
c906108c 9783
ce359b09 9784 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 9785 if (args && strcmp (args, sectname) != 0)
0df8b418 9786 continue; /* Not the section selected by user. */
c906108c 9787
0df8b418 9788 matched = 1; /* Do this section. */
c906108c 9789 lma = s->lma;
c906108c 9790
224c3ddb 9791 sectdata = (gdb_byte *) xmalloc (size);
b8c9b27d 9792 old_chain = make_cleanup (xfree, sectdata);
c906108c 9793 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 9794
4a5e7a5b
PA
9795 res = target_verify_memory (sectdata, lma, size);
9796
9797 if (res == -1)
5af949e3 9798 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
9799 paddress (target_gdbarch (), lma),
9800 paddress (target_gdbarch (), lma + size));
c906108c 9801
5af949e3 9802 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
9803 paddress (target_gdbarch (), lma),
9804 paddress (target_gdbarch (), lma + size));
4a5e7a5b 9805 if (res)
c906108c
SS
9806 printf_filtered ("matched.\n");
9807 else
c5aa993b
JM
9808 {
9809 printf_filtered ("MIS-MATCHED!\n");
9810 mismatched++;
9811 }
c906108c
SS
9812
9813 do_cleanups (old_chain);
9814 }
9815 if (mismatched > 0)
936d2992 9816 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 9817the loaded file\n"));
c906108c 9818 if (args && !matched)
a3f17187 9819 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
9820}
9821
0e7f50da
UW
9822/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9823 into remote target. The number of bytes written to the remote
9824 target is returned, or -1 for error. */
9825
9b409511 9826static enum target_xfer_status
0e7f50da
UW
9827remote_write_qxfer (struct target_ops *ops, const char *object_name,
9828 const char *annex, const gdb_byte *writebuf,
9b409511 9829 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
9830 struct packet_config *packet)
9831{
9832 int i, buf_len;
9833 ULONGEST n;
0e7f50da
UW
9834 struct remote_state *rs = get_remote_state ();
9835 int max_size = get_memory_write_packet_size ();
9836
9837 if (packet->support == PACKET_DISABLE)
2ed4b548 9838 return TARGET_XFER_E_IO;
0e7f50da
UW
9839
9840 /* Insert header. */
9841 i = snprintf (rs->buf, max_size,
9842 "qXfer:%s:write:%s:%s:",
9843 object_name, annex ? annex : "",
9844 phex_nz (offset, sizeof offset));
9845 max_size -= (i + 1);
9846
9847 /* Escape as much data as fits into rs->buf. */
9848 buf_len = remote_escape_output
124e13d9 9849 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
9850
9851 if (putpkt_binary (rs->buf, i + buf_len) < 0
9852 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9853 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9854 return TARGET_XFER_E_IO;
0e7f50da
UW
9855
9856 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
9857
9858 *xfered_len = n;
9859 return TARGET_XFER_OK;
0e7f50da
UW
9860}
9861
0876f84a
DJ
9862/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9863 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9864 number of bytes read is returned, or 0 for EOF, or -1 for error.
9865 The number of bytes read may be less than LEN without indicating an
9866 EOF. PACKET is checked and updated to indicate whether the remote
9867 target supports this object. */
9868
9b409511 9869static enum target_xfer_status
0876f84a
DJ
9870remote_read_qxfer (struct target_ops *ops, const char *object_name,
9871 const char *annex,
9872 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 9873 ULONGEST *xfered_len,
0876f84a
DJ
9874 struct packet_config *packet)
9875{
0876f84a 9876 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
9877 LONGEST i, n, packet_len;
9878
9879 if (packet->support == PACKET_DISABLE)
2ed4b548 9880 return TARGET_XFER_E_IO;
0876f84a
DJ
9881
9882 /* Check whether we've cached an end-of-object packet that matches
9883 this request. */
8e88304f 9884 if (rs->finished_object)
0876f84a 9885 {
8e88304f
TT
9886 if (strcmp (object_name, rs->finished_object) == 0
9887 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9888 && offset == rs->finished_offset)
9b409511
YQ
9889 return TARGET_XFER_EOF;
9890
0876f84a
DJ
9891
9892 /* Otherwise, we're now reading something different. Discard
9893 the cache. */
8e88304f
TT
9894 xfree (rs->finished_object);
9895 xfree (rs->finished_annex);
9896 rs->finished_object = NULL;
9897 rs->finished_annex = NULL;
0876f84a
DJ
9898 }
9899
9900 /* Request only enough to fit in a single packet. The actual data
9901 may not, since we don't know how much of it will need to be escaped;
9902 the target is free to respond with slightly less data. We subtract
9903 five to account for the response type and the protocol frame. */
9904 n = min (get_remote_packet_size () - 5, len);
9905 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9906 object_name, annex ? annex : "",
9907 phex_nz (offset, sizeof offset),
9908 phex_nz (n, sizeof n));
9909 i = putpkt (rs->buf);
9910 if (i < 0)
2ed4b548 9911 return TARGET_XFER_E_IO;
0876f84a
DJ
9912
9913 rs->buf[0] = '\0';
9914 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9915 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9916 return TARGET_XFER_E_IO;
0876f84a
DJ
9917
9918 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9919 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9920
9921 /* 'm' means there is (or at least might be) more data after this
9922 batch. That does not make sense unless there's at least one byte
9923 of data in this reply. */
9924 if (rs->buf[0] == 'm' && packet_len == 1)
9925 error (_("Remote qXfer reply contained no data."));
9926
9927 /* Got some data. */
bc20a4af
PA
9928 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9929 packet_len - 1, readbuf, n);
0876f84a
DJ
9930
9931 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
9932 or possibly empty. If we have the final block of a non-empty
9933 object, record this fact to bypass a subsequent partial read. */
9934 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 9935 {
8e88304f
TT
9936 rs->finished_object = xstrdup (object_name);
9937 rs->finished_annex = xstrdup (annex ? annex : "");
9938 rs->finished_offset = offset + i;
0876f84a
DJ
9939 }
9940
9b409511
YQ
9941 if (i == 0)
9942 return TARGET_XFER_EOF;
9943 else
9944 {
9945 *xfered_len = i;
9946 return TARGET_XFER_OK;
9947 }
0876f84a
DJ
9948}
9949
9b409511 9950static enum target_xfer_status
4b8a223f 9951remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 9952 const char *annex, gdb_byte *readbuf,
9b409511
YQ
9953 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9954 ULONGEST *xfered_len)
c906108c 9955{
82f73884 9956 struct remote_state *rs;
c906108c 9957 int i;
6d820c5c 9958 char *p2;
1e3ff5ad 9959 char query_type;
124e13d9 9960 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 9961
e6e4e701 9962 set_remote_traceframe ();
82f73884
PA
9963 set_general_thread (inferior_ptid);
9964
9965 rs = get_remote_state ();
9966
b2182ed2 9967 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
9968 if (object == TARGET_OBJECT_MEMORY)
9969 {
2d717e4f
DJ
9970 /* If the remote target is connected but not running, we should
9971 pass this request down to a lower stratum (e.g. the executable
9972 file). */
9973 if (!target_has_execution)
9b409511 9974 return TARGET_XFER_EOF;
2d717e4f 9975
21e3b9b9 9976 if (writebuf != NULL)
124e13d9
SM
9977 return remote_write_bytes (offset, writebuf, len, unit_size,
9978 xfered_len);
21e3b9b9 9979 else
124e13d9
SM
9980 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9981 xfered_len);
21e3b9b9
DJ
9982 }
9983
0df8b418 9984 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
9985 if (object == TARGET_OBJECT_SPU)
9986 {
9987 if (readbuf)
9988 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
9989 xfered_len, &remote_protocol_packets
9990 [PACKET_qXfer_spu_read]);
0e7f50da
UW
9991 else
9992 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
9993 xfered_len, &remote_protocol_packets
9994 [PACKET_qXfer_spu_write]);
0e7f50da
UW
9995 }
9996
4aa995e1
PA
9997 /* Handle extra signal info using qxfer packets. */
9998 if (object == TARGET_OBJECT_SIGNAL_INFO)
9999 {
10000 if (readbuf)
10001 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 10002 xfered_len, &remote_protocol_packets
4aa995e1
PA
10003 [PACKET_qXfer_siginfo_read]);
10004 else
3e43a32a 10005 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 10006 writebuf, offset, len, xfered_len,
4aa995e1
PA
10007 &remote_protocol_packets
10008 [PACKET_qXfer_siginfo_write]);
10009 }
10010
0fb4aa4b
PA
10011 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10012 {
10013 if (readbuf)
3e43a32a 10014 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 10015 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
10016 &remote_protocol_packets
10017 [PACKET_qXfer_statictrace_read]);
10018 else
2ed4b548 10019 return TARGET_XFER_E_IO;
0fb4aa4b
PA
10020 }
10021
a76d924d
DJ
10022 /* Only handle flash writes. */
10023 if (writebuf != NULL)
10024 {
a76d924d
DJ
10025 switch (object)
10026 {
10027 case TARGET_OBJECT_FLASH:
9b409511
YQ
10028 return remote_flash_write (ops, offset, len, xfered_len,
10029 writebuf);
a76d924d
DJ
10030
10031 default:
2ed4b548 10032 return TARGET_XFER_E_IO;
a76d924d
DJ
10033 }
10034 }
4b8a223f 10035
1e3ff5ad
AC
10036 /* Map pre-existing objects onto letters. DO NOT do this for new
10037 objects!!! Instead specify new query packets. */
10038 switch (object)
c906108c 10039 {
1e3ff5ad
AC
10040 case TARGET_OBJECT_AVR:
10041 query_type = 'R';
10042 break;
802188a7
RM
10043
10044 case TARGET_OBJECT_AUXV:
0876f84a
DJ
10045 gdb_assert (annex == NULL);
10046 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 10047 xfered_len,
0876f84a 10048 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 10049
23181151
DJ
10050 case TARGET_OBJECT_AVAILABLE_FEATURES:
10051 return remote_read_qxfer
9b409511 10052 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
10053 &remote_protocol_packets[PACKET_qXfer_features]);
10054
cfa9d6d9
DJ
10055 case TARGET_OBJECT_LIBRARIES:
10056 return remote_read_qxfer
9b409511 10057 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
10058 &remote_protocol_packets[PACKET_qXfer_libraries]);
10059
2268b414
JK
10060 case TARGET_OBJECT_LIBRARIES_SVR4:
10061 return remote_read_qxfer
9b409511 10062 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
10063 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10064
fd79ecee
DJ
10065 case TARGET_OBJECT_MEMORY_MAP:
10066 gdb_assert (annex == NULL);
10067 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 10068 xfered_len,
fd79ecee
DJ
10069 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10070
07e059b5
VP
10071 case TARGET_OBJECT_OSDATA:
10072 /* Should only get here if we're connected. */
5d93a237 10073 gdb_assert (rs->remote_desc);
07e059b5 10074 return remote_read_qxfer
9b409511 10075 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
10076 &remote_protocol_packets[PACKET_qXfer_osdata]);
10077
dc146f7c
VP
10078 case TARGET_OBJECT_THREADS:
10079 gdb_assert (annex == NULL);
10080 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 10081 xfered_len,
dc146f7c
VP
10082 &remote_protocol_packets[PACKET_qXfer_threads]);
10083
b3b9301e
PA
10084 case TARGET_OBJECT_TRACEFRAME_INFO:
10085 gdb_assert (annex == NULL);
10086 return remote_read_qxfer
9b409511 10087 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 10088 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
10089
10090 case TARGET_OBJECT_FDPIC:
10091 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 10092 xfered_len,
78d85199 10093 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
10094
10095 case TARGET_OBJECT_OPENVMS_UIB:
10096 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 10097 xfered_len,
169081d0
TG
10098 &remote_protocol_packets[PACKET_qXfer_uib]);
10099
9accd112
MM
10100 case TARGET_OBJECT_BTRACE:
10101 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 10102 xfered_len,
9accd112
MM
10103 &remote_protocol_packets[PACKET_qXfer_btrace]);
10104
f4abbc16
MM
10105 case TARGET_OBJECT_BTRACE_CONF:
10106 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10107 len, xfered_len,
10108 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10109
c78fa86a
GB
10110 case TARGET_OBJECT_EXEC_FILE:
10111 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10112 len, xfered_len,
10113 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10114
1e3ff5ad 10115 default:
2ed4b548 10116 return TARGET_XFER_E_IO;
c906108c
SS
10117 }
10118
0df8b418 10119 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 10120 large enough let the caller deal with it. */
ea9c271d 10121 if (len < get_remote_packet_size ())
2ed4b548 10122 return TARGET_XFER_E_IO;
ea9c271d 10123 len = get_remote_packet_size ();
1e3ff5ad 10124
23860348 10125 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 10126 if (!rs->remote_desc)
8a3fe4f8 10127 error (_("remote query is only available after target open"));
c906108c 10128
1e3ff5ad 10129 gdb_assert (annex != NULL);
4b8a223f 10130 gdb_assert (readbuf != NULL);
c906108c 10131
6d820c5c 10132 p2 = rs->buf;
c906108c
SS
10133 *p2++ = 'q';
10134 *p2++ = query_type;
10135
23860348
MS
10136 /* We used one buffer char for the remote protocol q command and
10137 another for the query type. As the remote protocol encapsulation
10138 uses 4 chars plus one extra in case we are debugging
10139 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10140 string. */
c906108c 10141 i = 0;
ea9c271d 10142 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 10143 {
1e3ff5ad
AC
10144 /* Bad caller may have sent forbidden characters. */
10145 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10146 *p2++ = annex[i];
c906108c
SS
10147 i++;
10148 }
1e3ff5ad
AC
10149 *p2 = '\0';
10150 gdb_assert (annex[i] == '\0');
c906108c 10151
6d820c5c 10152 i = putpkt (rs->buf);
c5aa993b 10153 if (i < 0)
2ed4b548 10154 return TARGET_XFER_E_IO;
c906108c 10155
6d820c5c
DJ
10156 getpkt (&rs->buf, &rs->buf_size, 0);
10157 strcpy ((char *) readbuf, rs->buf);
c906108c 10158
9b409511
YQ
10159 *xfered_len = strlen ((char *) readbuf);
10160 return TARGET_XFER_OK;
c906108c
SS
10161}
10162
09c98b44
DB
10163/* Implementation of to_get_memory_xfer_limit. */
10164
10165static ULONGEST
10166remote_get_memory_xfer_limit (struct target_ops *ops)
10167{
10168 return get_memory_write_packet_size ();
10169}
10170
08388c79
DE
10171static int
10172remote_search_memory (struct target_ops* ops,
10173 CORE_ADDR start_addr, ULONGEST search_space_len,
10174 const gdb_byte *pattern, ULONGEST pattern_len,
10175 CORE_ADDR *found_addrp)
10176{
f5656ead 10177 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
10178 struct remote_state *rs = get_remote_state ();
10179 int max_size = get_memory_write_packet_size ();
10180 struct packet_config *packet =
10181 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
10182 /* Number of packet bytes used to encode the pattern;
10183 this could be more than PATTERN_LEN due to escape characters. */
08388c79 10184 int escaped_pattern_len;
0df8b418 10185 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
10186 int used_pattern_len;
10187 int i;
10188 int found;
10189 ULONGEST found_addr;
10190
10191 /* Don't go to the target if we don't have to.
10192 This is done before checking packet->support to avoid the possibility that
10193 a success for this edge case means the facility works in general. */
10194 if (pattern_len > search_space_len)
10195 return 0;
10196 if (pattern_len == 0)
10197 {
10198 *found_addrp = start_addr;
10199 return 1;
10200 }
10201
10202 /* If we already know the packet isn't supported, fall back to the simple
10203 way of searching memory. */
10204
4082afcc 10205 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
10206 {
10207 /* Target doesn't provided special support, fall back and use the
10208 standard support (copy memory and do the search here). */
10209 return simple_search_memory (ops, start_addr, search_space_len,
10210 pattern, pattern_len, found_addrp);
10211 }
10212
28439a30
PA
10213 /* Make sure the remote is pointing at the right process. */
10214 set_general_process ();
10215
08388c79
DE
10216 /* Insert header. */
10217 i = snprintf (rs->buf, max_size,
10218 "qSearch:memory:%s;%s;",
5af949e3 10219 phex_nz (start_addr, addr_size),
08388c79
DE
10220 phex_nz (search_space_len, sizeof (search_space_len)));
10221 max_size -= (i + 1);
10222
10223 /* Escape as much data as fits into rs->buf. */
10224 escaped_pattern_len =
124e13d9 10225 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
10226 &used_pattern_len, max_size);
10227
10228 /* Bail if the pattern is too large. */
10229 if (used_pattern_len != pattern_len)
9b20d036 10230 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
10231
10232 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10233 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10234 || packet_ok (rs->buf, packet) != PACKET_OK)
10235 {
10236 /* The request may not have worked because the command is not
10237 supported. If so, fall back to the simple way. */
10238 if (packet->support == PACKET_DISABLE)
10239 {
10240 return simple_search_memory (ops, start_addr, search_space_len,
10241 pattern, pattern_len, found_addrp);
10242 }
10243 return -1;
10244 }
10245
10246 if (rs->buf[0] == '0')
10247 found = 0;
10248 else if (rs->buf[0] == '1')
10249 {
10250 found = 1;
10251 if (rs->buf[1] != ',')
10e0fa18 10252 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10253 unpack_varlen_hex (rs->buf + 2, &found_addr);
10254 *found_addrp = found_addr;
10255 }
10256 else
10e0fa18 10257 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10258
10259 return found;
10260}
10261
96baa820 10262static void
a30bf1f1 10263remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 10264 struct ui_file *outbuf)
96baa820 10265{
d01949b6 10266 struct remote_state *rs = get_remote_state ();
2e9f7625 10267 char *p = rs->buf;
96baa820 10268
5d93a237 10269 if (!rs->remote_desc)
8a3fe4f8 10270 error (_("remote rcmd is only available after target open"));
96baa820 10271
23860348 10272 /* Send a NULL command across as an empty command. */
7be570e7
JM
10273 if (command == NULL)
10274 command = "";
10275
23860348 10276 /* The query prefix. */
2e9f7625
DJ
10277 strcpy (rs->buf, "qRcmd,");
10278 p = strchr (rs->buf, '\0');
96baa820 10279
3e43a32a
MS
10280 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10281 > get_remote_packet_size ())
8a3fe4f8 10282 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 10283
23860348 10284 /* Encode the actual command. */
a30bf1f1 10285 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 10286
6d820c5c 10287 if (putpkt (rs->buf) < 0)
8a3fe4f8 10288 error (_("Communication problem with target."));
96baa820
JM
10289
10290 /* get/display the response */
10291 while (1)
10292 {
2e9f7625
DJ
10293 char *buf;
10294
00bf0b85 10295 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 10296 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 10297 rs->buf[0] = '\0';
5b37825d
PW
10298 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10299 {
10300 /* Timeout. Continue to (try to) read responses.
10301 This is better than stopping with an error, assuming the stub
10302 is still executing the (long) monitor command.
10303 If needed, the user can interrupt gdb using C-c, obtaining
10304 an effect similar to stop on timeout. */
10305 continue;
10306 }
2e9f7625 10307 buf = rs->buf;
96baa820 10308 if (buf[0] == '\0')
8a3fe4f8 10309 error (_("Target does not support this command."));
96baa820
JM
10310 if (buf[0] == 'O' && buf[1] != 'K')
10311 {
23860348 10312 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
10313 continue;
10314 }
10315 if (strcmp (buf, "OK") == 0)
10316 break;
7be570e7
JM
10317 if (strlen (buf) == 3 && buf[0] == 'E'
10318 && isdigit (buf[1]) && isdigit (buf[2]))
10319 {
8a3fe4f8 10320 error (_("Protocol error with Rcmd"));
7be570e7 10321 }
96baa820
JM
10322 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10323 {
10324 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 10325
96baa820
JM
10326 fputc_unfiltered (c, outbuf);
10327 }
10328 break;
10329 }
10330}
10331
fd79ecee
DJ
10332static VEC(mem_region_s) *
10333remote_memory_map (struct target_ops *ops)
10334{
10335 VEC(mem_region_s) *result = NULL;
10336 char *text = target_read_stralloc (&current_target,
10337 TARGET_OBJECT_MEMORY_MAP, NULL);
10338
10339 if (text)
10340 {
10341 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 10342
fd79ecee
DJ
10343 result = parse_memory_map (text);
10344 do_cleanups (back_to);
10345 }
10346
10347 return result;
10348}
10349
c906108c 10350static void
fba45db2 10351packet_command (char *args, int from_tty)
c906108c 10352{
d01949b6 10353 struct remote_state *rs = get_remote_state ();
c906108c 10354
5d93a237 10355 if (!rs->remote_desc)
8a3fe4f8 10356 error (_("command can only be used with remote target"));
c906108c 10357
c5aa993b 10358 if (!args)
8a3fe4f8 10359 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
10360
10361 puts_filtered ("sending: ");
10362 print_packet (args);
10363 puts_filtered ("\n");
10364 putpkt (args);
10365
6d820c5c 10366 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 10367 puts_filtered ("received: ");
6d820c5c 10368 print_packet (rs->buf);
c906108c
SS
10369 puts_filtered ("\n");
10370}
10371
10372#if 0
23860348 10373/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 10374
a14ed312 10375static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 10376
a14ed312 10377static void threadset_test_cmd (char *cmd, int tty);
c906108c 10378
a14ed312 10379static void threadalive_test (char *cmd, int tty);
c906108c 10380
a14ed312 10381static void threadlist_test_cmd (char *cmd, int tty);
c906108c 10382
23860348 10383int get_and_display_threadinfo (threadref *ref);
c906108c 10384
a14ed312 10385static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 10386
23860348 10387static int thread_display_step (threadref *ref, void *context);
c906108c 10388
a14ed312 10389static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 10390
a14ed312 10391static void init_remote_threadtests (void);
c906108c 10392
23860348 10393#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
10394
10395static void
fba45db2 10396threadset_test_cmd (char *cmd, int tty)
c906108c
SS
10397{
10398 int sample_thread = SAMPLE_THREAD;
10399
a3f17187 10400 printf_filtered (_("Remote threadset test\n"));
79d7f229 10401 set_general_thread (sample_thread);
c906108c
SS
10402}
10403
10404
10405static void
fba45db2 10406threadalive_test (char *cmd, int tty)
c906108c
SS
10407{
10408 int sample_thread = SAMPLE_THREAD;
79d7f229 10409 int pid = ptid_get_pid (inferior_ptid);
ba348170 10410 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 10411
79d7f229 10412 if (remote_thread_alive (ptid))
c906108c
SS
10413 printf_filtered ("PASS: Thread alive test\n");
10414 else
10415 printf_filtered ("FAIL: Thread alive test\n");
10416}
10417
23860348 10418void output_threadid (char *title, threadref *ref);
c906108c
SS
10419
10420void
fba45db2 10421output_threadid (char *title, threadref *ref)
c906108c
SS
10422{
10423 char hexid[20];
10424
23860348 10425 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
10426 hexid[16] = 0;
10427 printf_filtered ("%s %s\n", title, (&hexid[0]));
10428}
10429
10430static void
fba45db2 10431threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
10432{
10433 int startflag = 1;
10434 threadref nextthread;
10435 int done, result_count;
10436 threadref threadlist[3];
10437
10438 printf_filtered ("Remote Threadlist test\n");
10439 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10440 &result_count, &threadlist[0]))
10441 printf_filtered ("FAIL: threadlist test\n");
10442 else
10443 {
10444 threadref *scan = threadlist;
10445 threadref *limit = scan + result_count;
10446
10447 while (scan < limit)
10448 output_threadid (" thread ", scan++);
10449 }
10450}
10451
10452void
fba45db2 10453display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
10454{
10455 output_threadid ("Threadid: ", &info->threadid);
10456 printf_filtered ("Name: %s\n ", info->shortname);
10457 printf_filtered ("State: %s\n", info->display);
10458 printf_filtered ("other: %s\n\n", info->more_display);
10459}
10460
10461int
fba45db2 10462get_and_display_threadinfo (threadref *ref)
c906108c
SS
10463{
10464 int result;
10465 int set;
10466 struct gdb_ext_thread_info threadinfo;
10467
10468 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10469 | TAG_MOREDISPLAY | TAG_DISPLAY;
10470 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10471 display_thread_info (&threadinfo);
10472 return result;
10473}
10474
10475static void
fba45db2 10476threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
10477{
10478 int athread = SAMPLE_THREAD;
10479 threadref thread;
10480 int set;
10481
10482 int_to_threadref (&thread, athread);
10483 printf_filtered ("Remote Threadinfo test\n");
10484 if (!get_and_display_threadinfo (&thread))
10485 printf_filtered ("FAIL cannot get thread info\n");
10486}
10487
10488static int
fba45db2 10489thread_display_step (threadref *ref, void *context)
c906108c
SS
10490{
10491 /* output_threadid(" threadstep ",ref); *//* simple test */
10492 return get_and_display_threadinfo (ref);
10493}
10494
10495static void
fba45db2 10496threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
10497{
10498 printf_filtered ("Remote Threadlist update test\n");
10499 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10500}
10501
10502static void
10503init_remote_threadtests (void)
10504{
3e43a32a
MS
10505 add_com ("tlist", class_obscure, threadlist_test_cmd,
10506 _("Fetch and print the remote list of "
10507 "thread identifiers, one pkt only"));
c906108c 10508 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 10509 _("Fetch and display info about one thread"));
c906108c 10510 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 10511 _("Test setting to a different thread"));
c906108c 10512 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 10513 _("Iterate through updating all remote thread info"));
c906108c 10514 add_com ("talive", class_obscure, threadalive_test,
1bedd215 10515 _(" Remote thread alive test "));
c906108c
SS
10516}
10517
10518#endif /* 0 */
10519
f3fb8c85
MS
10520/* Convert a thread ID to a string. Returns the string in a static
10521 buffer. */
10522
10523static char *
117de6a9 10524remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 10525{
79d7f229 10526 static char buf[64];
82f73884 10527 struct remote_state *rs = get_remote_state ();
f3fb8c85 10528
7cee1e54
PA
10529 if (ptid_equal (ptid, null_ptid))
10530 return normal_pid_to_str (ptid);
10531 else if (ptid_is_pid (ptid))
ecd0ada5
PA
10532 {
10533 /* Printing an inferior target id. */
10534
10535 /* When multi-process extensions are off, there's no way in the
10536 remote protocol to know the remote process id, if there's any
10537 at all. There's one exception --- when we're connected with
10538 target extended-remote, and we manually attached to a process
10539 with "attach PID". We don't record anywhere a flag that
10540 allows us to distinguish that case from the case of
10541 connecting with extended-remote and the stub already being
10542 attached to a process, and reporting yes to qAttached, hence
10543 no smart special casing here. */
10544 if (!remote_multi_process_p (rs))
10545 {
10546 xsnprintf (buf, sizeof buf, "Remote target");
10547 return buf;
10548 }
10549
10550 return normal_pid_to_str (ptid);
82f73884 10551 }
ecd0ada5 10552 else
79d7f229 10553 {
ecd0ada5
PA
10554 if (ptid_equal (magic_null_ptid, ptid))
10555 xsnprintf (buf, sizeof buf, "Thread <main>");
8020350c 10556 else if (remote_multi_process_p (rs))
de0d863e
DB
10557 if (ptid_get_lwp (ptid) == 0)
10558 return normal_pid_to_str (ptid);
10559 else
10560 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10561 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
10562 else
10563 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 10564 ptid_get_lwp (ptid));
79d7f229
PA
10565 return buf;
10566 }
f3fb8c85
MS
10567}
10568
38691318
KB
10569/* Get the address of the thread local variable in OBJFILE which is
10570 stored at OFFSET within the thread local storage for thread PTID. */
10571
10572static CORE_ADDR
117de6a9
PA
10573remote_get_thread_local_address (struct target_ops *ops,
10574 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 10575{
4082afcc 10576 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
10577 {
10578 struct remote_state *rs = get_remote_state ();
6d820c5c 10579 char *p = rs->buf;
82f73884 10580 char *endp = rs->buf + get_remote_packet_size ();
571dd617 10581 enum packet_result result;
38691318
KB
10582
10583 strcpy (p, "qGetTLSAddr:");
10584 p += strlen (p);
82f73884 10585 p = write_ptid (p, endp, ptid);
38691318
KB
10586 *p++ = ',';
10587 p += hexnumstr (p, offset);
10588 *p++ = ',';
10589 p += hexnumstr (p, lm);
10590 *p++ = '\0';
10591
6d820c5c
DJ
10592 putpkt (rs->buf);
10593 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
10594 result = packet_ok (rs->buf,
10595 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 10596 if (result == PACKET_OK)
38691318
KB
10597 {
10598 ULONGEST result;
10599
6d820c5c 10600 unpack_varlen_hex (rs->buf, &result);
38691318
KB
10601 return result;
10602 }
571dd617 10603 else if (result == PACKET_UNKNOWN)
109c3e39
AC
10604 throw_error (TLS_GENERIC_ERROR,
10605 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 10606 else
109c3e39
AC
10607 throw_error (TLS_GENERIC_ERROR,
10608 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
10609 }
10610 else
109c3e39
AC
10611 throw_error (TLS_GENERIC_ERROR,
10612 _("TLS not supported or disabled on this target"));
38691318
KB
10613 /* Not reached. */
10614 return 0;
10615}
10616
711e434b
PM
10617/* Provide thread local base, i.e. Thread Information Block address.
10618 Returns 1 if ptid is found and thread_local_base is non zero. */
10619
70221824 10620static int
bd7ae0f5 10621remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 10622{
4082afcc 10623 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
10624 {
10625 struct remote_state *rs = get_remote_state ();
10626 char *p = rs->buf;
10627 char *endp = rs->buf + get_remote_packet_size ();
10628 enum packet_result result;
10629
10630 strcpy (p, "qGetTIBAddr:");
10631 p += strlen (p);
10632 p = write_ptid (p, endp, ptid);
10633 *p++ = '\0';
10634
10635 putpkt (rs->buf);
10636 getpkt (&rs->buf, &rs->buf_size, 0);
10637 result = packet_ok (rs->buf,
10638 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10639 if (result == PACKET_OK)
10640 {
10641 ULONGEST result;
10642
10643 unpack_varlen_hex (rs->buf, &result);
10644 if (addr)
10645 *addr = (CORE_ADDR) result;
10646 return 1;
10647 }
10648 else if (result == PACKET_UNKNOWN)
10649 error (_("Remote target doesn't support qGetTIBAddr packet"));
10650 else
10651 error (_("Remote target failed to process qGetTIBAddr request"));
10652 }
10653 else
10654 error (_("qGetTIBAddr not supported or disabled on this target"));
10655 /* Not reached. */
10656 return 0;
10657}
10658
29709017
DJ
10659/* Support for inferring a target description based on the current
10660 architecture and the size of a 'g' packet. While the 'g' packet
10661 can have any size (since optional registers can be left off the
10662 end), some sizes are easily recognizable given knowledge of the
10663 approximate architecture. */
10664
10665struct remote_g_packet_guess
10666{
10667 int bytes;
10668 const struct target_desc *tdesc;
10669};
10670typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10671DEF_VEC_O(remote_g_packet_guess_s);
10672
10673struct remote_g_packet_data
10674{
10675 VEC(remote_g_packet_guess_s) *guesses;
10676};
10677
10678static struct gdbarch_data *remote_g_packet_data_handle;
10679
10680static void *
10681remote_g_packet_data_init (struct obstack *obstack)
10682{
10683 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10684}
10685
10686void
10687register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10688 const struct target_desc *tdesc)
10689{
10690 struct remote_g_packet_data *data
19ba03f4
SM
10691 = ((struct remote_g_packet_data *)
10692 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
10693 struct remote_g_packet_guess new_guess, *guess;
10694 int ix;
10695
10696 gdb_assert (tdesc != NULL);
10697
10698 for (ix = 0;
10699 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10700 ix++)
10701 if (guess->bytes == bytes)
10702 internal_error (__FILE__, __LINE__,
9b20d036 10703 _("Duplicate g packet description added for size %d"),
29709017
DJ
10704 bytes);
10705
10706 new_guess.bytes = bytes;
10707 new_guess.tdesc = tdesc;
10708 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10709}
10710
d962ef82
DJ
10711/* Return 1 if remote_read_description would do anything on this target
10712 and architecture, 0 otherwise. */
10713
10714static int
10715remote_read_description_p (struct target_ops *target)
10716{
10717 struct remote_g_packet_data *data
19ba03f4
SM
10718 = ((struct remote_g_packet_data *)
10719 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
10720
10721 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10722 return 1;
10723
10724 return 0;
10725}
10726
29709017
DJ
10727static const struct target_desc *
10728remote_read_description (struct target_ops *target)
10729{
10730 struct remote_g_packet_data *data
19ba03f4
SM
10731 = ((struct remote_g_packet_data *)
10732 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 10733
d962ef82
DJ
10734 /* Do not try this during initial connection, when we do not know
10735 whether there is a running but stopped thread. */
10736 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 10737 return target->beneath->to_read_description (target->beneath);
d962ef82 10738
29709017
DJ
10739 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10740 {
10741 struct remote_g_packet_guess *guess;
10742 int ix;
10743 int bytes = send_g_packet ();
10744
10745 for (ix = 0;
10746 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10747 ix++)
10748 if (guess->bytes == bytes)
10749 return guess->tdesc;
10750
10751 /* We discard the g packet. A minor optimization would be to
10752 hold on to it, and fill the register cache once we have selected
10753 an architecture, but it's too tricky to do safely. */
10754 }
10755
2117c711 10756 return target->beneath->to_read_description (target->beneath);
29709017
DJ
10757}
10758
a6b151f1
DJ
10759/* Remote file transfer support. This is host-initiated I/O, not
10760 target-initiated; for target-initiated, see remote-fileio.c. */
10761
10762/* If *LEFT is at least the length of STRING, copy STRING to
10763 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10764 decrease *LEFT. Otherwise raise an error. */
10765
10766static void
10767remote_buffer_add_string (char **buffer, int *left, char *string)
10768{
10769 int len = strlen (string);
10770
10771 if (len > *left)
10772 error (_("Packet too long for target."));
10773
10774 memcpy (*buffer, string, len);
10775 *buffer += len;
10776 *left -= len;
10777
10778 /* NUL-terminate the buffer as a convenience, if there is
10779 room. */
10780 if (*left)
10781 **buffer = '\0';
10782}
10783
10784/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10785 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10786 decrease *LEFT. Otherwise raise an error. */
10787
10788static void
10789remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10790 int len)
10791{
10792 if (2 * len > *left)
10793 error (_("Packet too long for target."));
10794
10795 bin2hex (bytes, *buffer, len);
10796 *buffer += 2 * len;
10797 *left -= 2 * len;
10798
10799 /* NUL-terminate the buffer as a convenience, if there is
10800 room. */
10801 if (*left)
10802 **buffer = '\0';
10803}
10804
10805/* If *LEFT is large enough, convert VALUE to hex and add it to
10806 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10807 decrease *LEFT. Otherwise raise an error. */
10808
10809static void
10810remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10811{
10812 int len = hexnumlen (value);
10813
10814 if (len > *left)
10815 error (_("Packet too long for target."));
10816
10817 hexnumstr (*buffer, value);
10818 *buffer += len;
10819 *left -= len;
10820
10821 /* NUL-terminate the buffer as a convenience, if there is
10822 room. */
10823 if (*left)
10824 **buffer = '\0';
10825}
10826
10827/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10828 value, *REMOTE_ERRNO to the remote error number or zero if none
10829 was included, and *ATTACHMENT to point to the start of the annex
10830 if any. The length of the packet isn't needed here; there may
10831 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10832
10833 Return 0 if the packet could be parsed, -1 if it could not. If
10834 -1 is returned, the other variables may not be initialized. */
10835
10836static int
10837remote_hostio_parse_result (char *buffer, int *retcode,
10838 int *remote_errno, char **attachment)
10839{
10840 char *p, *p2;
10841
10842 *remote_errno = 0;
10843 *attachment = NULL;
10844
10845 if (buffer[0] != 'F')
10846 return -1;
10847
10848 errno = 0;
10849 *retcode = strtol (&buffer[1], &p, 16);
10850 if (errno != 0 || p == &buffer[1])
10851 return -1;
10852
10853 /* Check for ",errno". */
10854 if (*p == ',')
10855 {
10856 errno = 0;
10857 *remote_errno = strtol (p + 1, &p2, 16);
10858 if (errno != 0 || p + 1 == p2)
10859 return -1;
10860 p = p2;
10861 }
10862
10863 /* Check for ";attachment". If there is no attachment, the
10864 packet should end here. */
10865 if (*p == ';')
10866 {
10867 *attachment = p + 1;
10868 return 0;
10869 }
10870 else if (*p == '\0')
10871 return 0;
10872 else
10873 return -1;
10874}
10875
10876/* Send a prepared I/O packet to the target and read its response.
10877 The prepared packet is in the global RS->BUF before this function
10878 is called, and the answer is there when we return.
10879
10880 COMMAND_BYTES is the length of the request to send, which may include
10881 binary data. WHICH_PACKET is the packet configuration to check
10882 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10883 is set to the error number and -1 is returned. Otherwise the value
10884 returned by the function is returned.
10885
10886 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10887 attachment is expected; an error will be reported if there's a
10888 mismatch. If one is found, *ATTACHMENT will be set to point into
10889 the packet buffer and *ATTACHMENT_LEN will be set to the
10890 attachment's length. */
10891
10892static int
10893remote_hostio_send_command (int command_bytes, int which_packet,
10894 int *remote_errno, char **attachment,
10895 int *attachment_len)
10896{
10897 struct remote_state *rs = get_remote_state ();
10898 int ret, bytes_read;
10899 char *attachment_tmp;
10900
5d93a237 10901 if (!rs->remote_desc
4082afcc 10902 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
10903 {
10904 *remote_errno = FILEIO_ENOSYS;
10905 return -1;
10906 }
10907
10908 putpkt_binary (rs->buf, command_bytes);
10909 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10910
10911 /* If it timed out, something is wrong. Don't try to parse the
10912 buffer. */
10913 if (bytes_read < 0)
10914 {
10915 *remote_errno = FILEIO_EINVAL;
10916 return -1;
10917 }
10918
10919 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10920 {
10921 case PACKET_ERROR:
10922 *remote_errno = FILEIO_EINVAL;
10923 return -1;
10924 case PACKET_UNKNOWN:
10925 *remote_errno = FILEIO_ENOSYS;
10926 return -1;
10927 case PACKET_OK:
10928 break;
10929 }
10930
10931 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10932 &attachment_tmp))
10933 {
10934 *remote_errno = FILEIO_EINVAL;
10935 return -1;
10936 }
10937
10938 /* Make sure we saw an attachment if and only if we expected one. */
10939 if ((attachment_tmp == NULL && attachment != NULL)
10940 || (attachment_tmp != NULL && attachment == NULL))
10941 {
10942 *remote_errno = FILEIO_EINVAL;
10943 return -1;
10944 }
10945
10946 /* If an attachment was found, it must point into the packet buffer;
10947 work out how many bytes there were. */
10948 if (attachment_tmp != NULL)
10949 {
10950 *attachment = attachment_tmp;
10951 *attachment_len = bytes_read - (*attachment - rs->buf);
10952 }
10953
10954 return ret;
10955}
10956
80152258
PA
10957/* Invalidate the readahead cache. */
10958
10959static void
10960readahead_cache_invalidate (void)
10961{
10962 struct remote_state *rs = get_remote_state ();
10963
10964 rs->readahead_cache.fd = -1;
10965}
10966
10967/* Invalidate the readahead cache if it is holding data for FD. */
10968
10969static void
10970readahead_cache_invalidate_fd (int fd)
10971{
10972 struct remote_state *rs = get_remote_state ();
10973
10974 if (rs->readahead_cache.fd == fd)
10975 rs->readahead_cache.fd = -1;
10976}
10977
15a201c8
GB
10978/* Set the filesystem remote_hostio functions that take FILENAME
10979 arguments will use. Return 0 on success, or -1 if an error
10980 occurs (and set *REMOTE_ERRNO). */
10981
10982static int
10983remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10984{
10985 struct remote_state *rs = get_remote_state ();
10986 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10987 char *p = rs->buf;
10988 int left = get_remote_packet_size () - 1;
10989 char arg[9];
10990 int ret;
10991
10992 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10993 return 0;
10994
10995 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10996 return 0;
10997
10998 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10999
11000 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11001 remote_buffer_add_string (&p, &left, arg);
11002
11003 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11004 remote_errno, NULL, NULL);
11005
11006 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11007 return 0;
11008
11009 if (ret == 0)
11010 rs->fs_pid = required_pid;
11011
11012 return ret;
11013}
11014
12e2a5fd 11015/* Implementation of to_fileio_open. */
a6b151f1
DJ
11016
11017static int
cd897586 11018remote_hostio_open (struct target_ops *self,
07c138c8 11019 struct inferior *inf, const char *filename,
4313b8c0
GB
11020 int flags, int mode, int warn_if_slow,
11021 int *remote_errno)
a6b151f1
DJ
11022{
11023 struct remote_state *rs = get_remote_state ();
11024 char *p = rs->buf;
11025 int left = get_remote_packet_size () - 1;
11026
4313b8c0
GB
11027 if (warn_if_slow)
11028 {
11029 static int warning_issued = 0;
11030
11031 printf_unfiltered (_("Reading %s from remote target...\n"),
11032 filename);
11033
11034 if (!warning_issued)
11035 {
11036 warning (_("File transfers from remote targets can be slow."
11037 " Use \"set sysroot\" to access files locally"
11038 " instead."));
11039 warning_issued = 1;
11040 }
11041 }
11042
15a201c8
GB
11043 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11044 return -1;
11045
a6b151f1
DJ
11046 remote_buffer_add_string (&p, &left, "vFile:open:");
11047
11048 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11049 strlen (filename));
11050 remote_buffer_add_string (&p, &left, ",");
11051
11052 remote_buffer_add_int (&p, &left, flags);
11053 remote_buffer_add_string (&p, &left, ",");
11054
11055 remote_buffer_add_int (&p, &left, mode);
11056
11057 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11058 remote_errno, NULL, NULL);
11059}
11060
12e2a5fd 11061/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
11062
11063static int
0d866f62
TT
11064remote_hostio_pwrite (struct target_ops *self,
11065 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
11066 ULONGEST offset, int *remote_errno)
11067{
11068 struct remote_state *rs = get_remote_state ();
11069 char *p = rs->buf;
11070 int left = get_remote_packet_size ();
11071 int out_len;
11072
80152258
PA
11073 readahead_cache_invalidate_fd (fd);
11074
a6b151f1
DJ
11075 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11076
11077 remote_buffer_add_int (&p, &left, fd);
11078 remote_buffer_add_string (&p, &left, ",");
11079
11080 remote_buffer_add_int (&p, &left, offset);
11081 remote_buffer_add_string (&p, &left, ",");
11082
124e13d9 11083 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
11084 get_remote_packet_size () - (p - rs->buf));
11085
11086 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11087 remote_errno, NULL, NULL);
11088}
11089
80152258
PA
11090/* Helper for the implementation of to_fileio_pread. Read the file
11091 from the remote side with vFile:pread. */
a6b151f1
DJ
11092
11093static int
80152258
PA
11094remote_hostio_pread_vFile (struct target_ops *self,
11095 int fd, gdb_byte *read_buf, int len,
11096 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
11097{
11098 struct remote_state *rs = get_remote_state ();
11099 char *p = rs->buf;
11100 char *attachment;
11101 int left = get_remote_packet_size ();
11102 int ret, attachment_len;
11103 int read_len;
11104
11105 remote_buffer_add_string (&p, &left, "vFile:pread:");
11106
11107 remote_buffer_add_int (&p, &left, fd);
11108 remote_buffer_add_string (&p, &left, ",");
11109
11110 remote_buffer_add_int (&p, &left, len);
11111 remote_buffer_add_string (&p, &left, ",");
11112
11113 remote_buffer_add_int (&p, &left, offset);
11114
11115 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11116 remote_errno, &attachment,
11117 &attachment_len);
11118
11119 if (ret < 0)
11120 return ret;
11121
bc20a4af 11122 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
11123 read_buf, len);
11124 if (read_len != ret)
11125 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11126
11127 return ret;
11128}
11129
80152258
PA
11130/* Serve pread from the readahead cache. Returns number of bytes
11131 read, or 0 if the request can't be served from the cache. */
11132
11133static int
11134remote_hostio_pread_from_cache (struct remote_state *rs,
11135 int fd, gdb_byte *read_buf, size_t len,
11136 ULONGEST offset)
11137{
11138 struct readahead_cache *cache = &rs->readahead_cache;
11139
11140 if (cache->fd == fd
11141 && cache->offset <= offset
11142 && offset < cache->offset + cache->bufsize)
11143 {
11144 ULONGEST max = cache->offset + cache->bufsize;
11145
11146 if (offset + len > max)
11147 len = max - offset;
11148
11149 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11150 return len;
11151 }
11152
11153 return 0;
11154}
11155
11156/* Implementation of to_fileio_pread. */
11157
11158static int
11159remote_hostio_pread (struct target_ops *self,
11160 int fd, gdb_byte *read_buf, int len,
11161 ULONGEST offset, int *remote_errno)
11162{
11163 int ret;
11164 struct remote_state *rs = get_remote_state ();
11165 struct readahead_cache *cache = &rs->readahead_cache;
11166
11167 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11168 if (ret > 0)
11169 {
11170 cache->hit_count++;
11171
11172 if (remote_debug)
11173 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11174 pulongest (cache->hit_count));
11175 return ret;
11176 }
11177
11178 cache->miss_count++;
11179 if (remote_debug)
11180 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11181 pulongest (cache->miss_count));
11182
11183 cache->fd = fd;
11184 cache->offset = offset;
11185 cache->bufsize = get_remote_packet_size ();
224c3ddb 11186 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258
PA
11187
11188 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11189 cache->offset, remote_errno);
11190 if (ret <= 0)
11191 {
11192 readahead_cache_invalidate_fd (fd);
11193 return ret;
11194 }
11195
11196 cache->bufsize = ret;
11197 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11198}
11199
12e2a5fd 11200/* Implementation of to_fileio_close. */
a6b151f1
DJ
11201
11202static int
df39ea25 11203remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
11204{
11205 struct remote_state *rs = get_remote_state ();
11206 char *p = rs->buf;
11207 int left = get_remote_packet_size () - 1;
11208
80152258
PA
11209 readahead_cache_invalidate_fd (fd);
11210
a6b151f1
DJ
11211 remote_buffer_add_string (&p, &left, "vFile:close:");
11212
11213 remote_buffer_add_int (&p, &left, fd);
11214
11215 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11216 remote_errno, NULL, NULL);
11217}
11218
12e2a5fd 11219/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
11220
11221static int
dbbca37d 11222remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
11223 struct inferior *inf, const char *filename,
11224 int *remote_errno)
a6b151f1
DJ
11225{
11226 struct remote_state *rs = get_remote_state ();
11227 char *p = rs->buf;
11228 int left = get_remote_packet_size () - 1;
11229
15a201c8
GB
11230 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11231 return -1;
11232
a6b151f1
DJ
11233 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11234
11235 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11236 strlen (filename));
11237
11238 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11239 remote_errno, NULL, NULL);
11240}
11241
12e2a5fd 11242/* Implementation of to_fileio_readlink. */
b9e7b9c3
UW
11243
11244static char *
fab5aa7c 11245remote_hostio_readlink (struct target_ops *self,
07c138c8
GB
11246 struct inferior *inf, const char *filename,
11247 int *remote_errno)
b9e7b9c3
UW
11248{
11249 struct remote_state *rs = get_remote_state ();
11250 char *p = rs->buf;
11251 char *attachment;
11252 int left = get_remote_packet_size ();
11253 int len, attachment_len;
11254 int read_len;
11255 char *ret;
11256
15a201c8
GB
11257 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11258 return NULL;
11259
b9e7b9c3
UW
11260 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11261
11262 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11263 strlen (filename));
11264
11265 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11266 remote_errno, &attachment,
11267 &attachment_len);
11268
11269 if (len < 0)
11270 return NULL;
11271
224c3ddb 11272 ret = (char *) xmalloc (len + 1);
b9e7b9c3 11273
bc20a4af
PA
11274 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11275 (gdb_byte *) ret, len);
b9e7b9c3
UW
11276 if (read_len != len)
11277 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11278
11279 ret[len] = '\0';
11280 return ret;
11281}
11282
12e2a5fd 11283/* Implementation of to_fileio_fstat. */
0a93529c
GB
11284
11285static int
11286remote_hostio_fstat (struct target_ops *self,
11287 int fd, struct stat *st,
11288 int *remote_errno)
11289{
11290 struct remote_state *rs = get_remote_state ();
11291 char *p = rs->buf;
11292 int left = get_remote_packet_size ();
11293 int attachment_len, ret;
11294 char *attachment;
11295 struct fio_stat fst;
11296 int read_len;
11297
464b0089
GB
11298 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11299
11300 remote_buffer_add_int (&p, &left, fd);
11301
11302 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11303 remote_errno, &attachment,
11304 &attachment_len);
11305 if (ret < 0)
0a93529c 11306 {
464b0089
GB
11307 if (*remote_errno != FILEIO_ENOSYS)
11308 return ret;
11309
0a93529c
GB
11310 /* Strictly we should return -1, ENOSYS here, but when
11311 "set sysroot remote:" was implemented in August 2008
11312 BFD's need for a stat function was sidestepped with
11313 this hack. This was not remedied until March 2015
11314 so we retain the previous behavior to avoid breaking
11315 compatibility.
11316
11317 Note that the memset is a March 2015 addition; older
11318 GDBs set st_size *and nothing else* so the structure
11319 would have garbage in all other fields. This might
11320 break something but retaining the previous behavior
11321 here would be just too wrong. */
11322
11323 memset (st, 0, sizeof (struct stat));
11324 st->st_size = INT_MAX;
11325 return 0;
11326 }
11327
0a93529c
GB
11328 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11329 (gdb_byte *) &fst, sizeof (fst));
11330
11331 if (read_len != ret)
11332 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11333
11334 if (read_len != sizeof (fst))
11335 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11336 read_len, (int) sizeof (fst));
11337
11338 remote_fileio_to_host_stat (&fst, st);
11339
11340 return 0;
11341}
11342
12e2a5fd 11343/* Implementation of to_filesystem_is_local. */
e3dd7556
GB
11344
11345static int
11346remote_filesystem_is_local (struct target_ops *self)
11347{
11348 /* Valgrind GDB presents itself as a remote target but works
11349 on the local filesystem: it does not implement remote get
11350 and users are not expected to set a sysroot. To handle
11351 this case we treat the remote filesystem as local if the
11352 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11353 does not support vFile:open. */
a3be80c3 11354 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
11355 {
11356 enum packet_support ps = packet_support (PACKET_vFile_open);
11357
11358 if (ps == PACKET_SUPPORT_UNKNOWN)
11359 {
11360 int fd, remote_errno;
11361
11362 /* Try opening a file to probe support. The supplied
11363 filename is irrelevant, we only care about whether
11364 the stub recognizes the packet or not. */
07c138c8 11365 fd = remote_hostio_open (self, NULL, "just probing",
4313b8c0 11366 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
11367 &remote_errno);
11368
11369 if (fd >= 0)
11370 remote_hostio_close (self, fd, &remote_errno);
11371
11372 ps = packet_support (PACKET_vFile_open);
11373 }
11374
11375 if (ps == PACKET_DISABLE)
11376 {
11377 static int warning_issued = 0;
11378
11379 if (!warning_issued)
11380 {
11381 warning (_("remote target does not support file"
11382 " transfer, attempting to access files"
11383 " from local filesystem."));
11384 warning_issued = 1;
11385 }
11386
11387 return 1;
11388 }
11389 }
11390
11391 return 0;
11392}
11393
a6b151f1
DJ
11394static int
11395remote_fileio_errno_to_host (int errnum)
11396{
11397 switch (errnum)
11398 {
11399 case FILEIO_EPERM:
11400 return EPERM;
11401 case FILEIO_ENOENT:
11402 return ENOENT;
11403 case FILEIO_EINTR:
11404 return EINTR;
11405 case FILEIO_EIO:
11406 return EIO;
11407 case FILEIO_EBADF:
11408 return EBADF;
11409 case FILEIO_EACCES:
11410 return EACCES;
11411 case FILEIO_EFAULT:
11412 return EFAULT;
11413 case FILEIO_EBUSY:
11414 return EBUSY;
11415 case FILEIO_EEXIST:
11416 return EEXIST;
11417 case FILEIO_ENODEV:
11418 return ENODEV;
11419 case FILEIO_ENOTDIR:
11420 return ENOTDIR;
11421 case FILEIO_EISDIR:
11422 return EISDIR;
11423 case FILEIO_EINVAL:
11424 return EINVAL;
11425 case FILEIO_ENFILE:
11426 return ENFILE;
11427 case FILEIO_EMFILE:
11428 return EMFILE;
11429 case FILEIO_EFBIG:
11430 return EFBIG;
11431 case FILEIO_ENOSPC:
11432 return ENOSPC;
11433 case FILEIO_ESPIPE:
11434 return ESPIPE;
11435 case FILEIO_EROFS:
11436 return EROFS;
11437 case FILEIO_ENOSYS:
11438 return ENOSYS;
11439 case FILEIO_ENAMETOOLONG:
11440 return ENAMETOOLONG;
11441 }
11442 return -1;
11443}
11444
11445static char *
11446remote_hostio_error (int errnum)
11447{
11448 int host_error = remote_fileio_errno_to_host (errnum);
11449
11450 if (host_error == -1)
11451 error (_("Unknown remote I/O error %d"), errnum);
11452 else
11453 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11454}
11455
a6b151f1
DJ
11456static void
11457remote_hostio_close_cleanup (void *opaque)
11458{
11459 int fd = *(int *) opaque;
11460 int remote_errno;
11461
df39ea25 11462 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
11463}
11464
11465void
11466remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11467{
11468 struct cleanup *back_to, *close_cleanup;
11469 int retcode, fd, remote_errno, bytes, io_size;
11470 FILE *file;
11471 gdb_byte *buffer;
11472 int bytes_in_buffer;
11473 int saw_eof;
11474 ULONGEST offset;
5d93a237 11475 struct remote_state *rs = get_remote_state ();
a6b151f1 11476
5d93a237 11477 if (!rs->remote_desc)
a6b151f1
DJ
11478 error (_("command can only be used with remote target"));
11479
614c279d 11480 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
11481 if (file == NULL)
11482 perror_with_name (local_file);
7c8a8b04 11483 back_to = make_cleanup_fclose (file);
a6b151f1 11484
07c138c8 11485 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 11486 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 11487 | FILEIO_O_TRUNC),
4313b8c0 11488 0700, 0, &remote_errno);
a6b151f1
DJ
11489 if (fd == -1)
11490 remote_hostio_error (remote_errno);
11491
11492 /* Send up to this many bytes at once. They won't all fit in the
11493 remote packet limit, so we'll transfer slightly fewer. */
11494 io_size = get_remote_packet_size ();
224c3ddb 11495 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11496 make_cleanup (xfree, buffer);
11497
11498 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11499
11500 bytes_in_buffer = 0;
11501 saw_eof = 0;
11502 offset = 0;
11503 while (bytes_in_buffer || !saw_eof)
11504 {
11505 if (!saw_eof)
11506 {
3e43a32a
MS
11507 bytes = fread (buffer + bytes_in_buffer, 1,
11508 io_size - bytes_in_buffer,
a6b151f1
DJ
11509 file);
11510 if (bytes == 0)
11511 {
11512 if (ferror (file))
11513 error (_("Error reading %s."), local_file);
11514 else
11515 {
11516 /* EOF. Unless there is something still in the
11517 buffer from the last iteration, we are done. */
11518 saw_eof = 1;
11519 if (bytes_in_buffer == 0)
11520 break;
11521 }
11522 }
11523 }
11524 else
11525 bytes = 0;
11526
11527 bytes += bytes_in_buffer;
11528 bytes_in_buffer = 0;
11529
0d866f62
TT
11530 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11531 fd, buffer, bytes,
3e43a32a 11532 offset, &remote_errno);
a6b151f1
DJ
11533
11534 if (retcode < 0)
11535 remote_hostio_error (remote_errno);
11536 else if (retcode == 0)
11537 error (_("Remote write of %d bytes returned 0!"), bytes);
11538 else if (retcode < bytes)
11539 {
11540 /* Short write. Save the rest of the read data for the next
11541 write. */
11542 bytes_in_buffer = bytes - retcode;
11543 memmove (buffer, buffer + retcode, bytes_in_buffer);
11544 }
11545
11546 offset += retcode;
11547 }
11548
11549 discard_cleanups (close_cleanup);
df39ea25 11550 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11551 remote_hostio_error (remote_errno);
11552
11553 if (from_tty)
11554 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11555 do_cleanups (back_to);
11556}
11557
11558void
11559remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11560{
11561 struct cleanup *back_to, *close_cleanup;
cea39f65 11562 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
11563 FILE *file;
11564 gdb_byte *buffer;
11565 ULONGEST offset;
5d93a237 11566 struct remote_state *rs = get_remote_state ();
a6b151f1 11567
5d93a237 11568 if (!rs->remote_desc)
a6b151f1
DJ
11569 error (_("command can only be used with remote target"));
11570
07c138c8 11571 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
11572 remote_file, FILEIO_O_RDONLY, 0, 0,
11573 &remote_errno);
a6b151f1
DJ
11574 if (fd == -1)
11575 remote_hostio_error (remote_errno);
11576
614c279d 11577 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
11578 if (file == NULL)
11579 perror_with_name (local_file);
7c8a8b04 11580 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
11581
11582 /* Send up to this many bytes at once. They won't all fit in the
11583 remote packet limit, so we'll transfer slightly fewer. */
11584 io_size = get_remote_packet_size ();
224c3ddb 11585 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11586 make_cleanup (xfree, buffer);
11587
11588 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11589
11590 offset = 0;
11591 while (1)
11592 {
a3be983c
TT
11593 bytes = remote_hostio_pread (find_target_at (process_stratum),
11594 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
11595 if (bytes == 0)
11596 /* Success, but no bytes, means end-of-file. */
11597 break;
11598 if (bytes == -1)
11599 remote_hostio_error (remote_errno);
11600
11601 offset += bytes;
11602
11603 bytes = fwrite (buffer, 1, bytes, file);
11604 if (bytes == 0)
11605 perror_with_name (local_file);
11606 }
11607
11608 discard_cleanups (close_cleanup);
df39ea25 11609 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11610 remote_hostio_error (remote_errno);
11611
11612 if (from_tty)
11613 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11614 do_cleanups (back_to);
11615}
11616
11617void
11618remote_file_delete (const char *remote_file, int from_tty)
11619{
11620 int retcode, remote_errno;
5d93a237 11621 struct remote_state *rs = get_remote_state ();
a6b151f1 11622
5d93a237 11623 if (!rs->remote_desc)
a6b151f1
DJ
11624 error (_("command can only be used with remote target"));
11625
dbbca37d 11626 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 11627 NULL, remote_file, &remote_errno);
a6b151f1
DJ
11628 if (retcode == -1)
11629 remote_hostio_error (remote_errno);
11630
11631 if (from_tty)
11632 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11633}
11634
11635static void
11636remote_put_command (char *args, int from_tty)
11637{
11638 struct cleanup *back_to;
11639 char **argv;
11640
d1a41061
PP
11641 if (args == NULL)
11642 error_no_arg (_("file to put"));
11643
11644 argv = gdb_buildargv (args);
a6b151f1
DJ
11645 back_to = make_cleanup_freeargv (argv);
11646 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11647 error (_("Invalid parameters to remote put"));
11648
11649 remote_file_put (argv[0], argv[1], from_tty);
11650
11651 do_cleanups (back_to);
11652}
11653
11654static void
11655remote_get_command (char *args, int from_tty)
11656{
11657 struct cleanup *back_to;
11658 char **argv;
11659
d1a41061
PP
11660 if (args == NULL)
11661 error_no_arg (_("file to get"));
11662
11663 argv = gdb_buildargv (args);
a6b151f1
DJ
11664 back_to = make_cleanup_freeargv (argv);
11665 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11666 error (_("Invalid parameters to remote get"));
11667
11668 remote_file_get (argv[0], argv[1], from_tty);
11669
11670 do_cleanups (back_to);
11671}
11672
11673static void
11674remote_delete_command (char *args, int from_tty)
11675{
11676 struct cleanup *back_to;
11677 char **argv;
11678
d1a41061
PP
11679 if (args == NULL)
11680 error_no_arg (_("file to delete"));
11681
11682 argv = gdb_buildargv (args);
a6b151f1
DJ
11683 back_to = make_cleanup_freeargv (argv);
11684 if (argv[0] == NULL || argv[1] != NULL)
11685 error (_("Invalid parameters to remote delete"));
11686
11687 remote_file_delete (argv[0], from_tty);
11688
11689 do_cleanups (back_to);
11690}
11691
11692static void
11693remote_command (char *args, int from_tty)
11694{
635c7e8a 11695 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
11696}
11697
b2175913 11698static int
19db3e69 11699remote_can_execute_reverse (struct target_ops *self)
b2175913 11700{
4082afcc
PA
11701 if (packet_support (PACKET_bs) == PACKET_ENABLE
11702 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
11703 return 1;
11704 else
11705 return 0;
b2175913
MS
11706}
11707
74531fed 11708static int
2a9a2795 11709remote_supports_non_stop (struct target_ops *self)
74531fed
PA
11710{
11711 return 1;
11712}
11713
03583c20 11714static int
2bfc0540 11715remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
11716{
11717 /* Only supported in extended mode. */
11718 return 0;
11719}
11720
8a305172 11721static int
86ce2668 11722remote_supports_multi_process (struct target_ops *self)
8a305172
PA
11723{
11724 struct remote_state *rs = get_remote_state ();
a744cf53 11725
8020350c 11726 return remote_multi_process_p (rs);
8a305172
PA
11727}
11728
70221824 11729static int
782b2b07
SS
11730remote_supports_cond_tracepoints (void)
11731{
4082afcc 11732 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
11733}
11734
3788aec7 11735static int
efcc2da7 11736remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 11737{
4082afcc 11738 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
11739}
11740
70221824 11741static int
7a697b8d
SS
11742remote_supports_fast_tracepoints (void)
11743{
4082afcc 11744 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
11745}
11746
0fb4aa4b
PA
11747static int
11748remote_supports_static_tracepoints (void)
11749{
4082afcc 11750 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
11751}
11752
1e4d1764
YQ
11753static int
11754remote_supports_install_in_trace (void)
11755{
4082afcc 11756 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
11757}
11758
d248b706 11759static int
7d178d6a 11760remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 11761{
4082afcc
PA
11762 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11763 == PACKET_ENABLE);
d248b706
KY
11764}
11765
3065dfb6 11766static int
6de37a3a 11767remote_supports_string_tracing (struct target_ops *self)
3065dfb6 11768{
4082afcc 11769 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
11770}
11771
d3ce09f5 11772static int
78eff0ec 11773remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 11774{
4082afcc 11775 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
11776}
11777
35b1e5cc 11778static void
ecae04e1 11779remote_trace_init (struct target_ops *self)
35b1e5cc
SS
11780{
11781 putpkt ("QTinit");
11782 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 11783 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11784 error (_("Target does not support this command."));
11785}
11786
11787static void free_actions_list (char **actions_list);
11788static void free_actions_list_cleanup_wrapper (void *);
11789static void
11790free_actions_list_cleanup_wrapper (void *al)
11791{
19ba03f4 11792 free_actions_list ((char **) al);
35b1e5cc
SS
11793}
11794
11795static void
11796free_actions_list (char **actions_list)
11797{
11798 int ndx;
11799
11800 if (actions_list == 0)
11801 return;
11802
11803 for (ndx = 0; actions_list[ndx]; ndx++)
11804 xfree (actions_list[ndx]);
11805
11806 xfree (actions_list);
11807}
11808
409873ef
SS
11809/* Recursive routine to walk through command list including loops, and
11810 download packets for each command. */
11811
11812static void
11813remote_download_command_source (int num, ULONGEST addr,
11814 struct command_line *cmds)
11815{
11816 struct remote_state *rs = get_remote_state ();
11817 struct command_line *cmd;
11818
11819 for (cmd = cmds; cmd; cmd = cmd->next)
11820 {
0df8b418 11821 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11822 strcpy (rs->buf, "QTDPsrc:");
11823 encode_source_string (num, addr, "cmd", cmd->line,
11824 rs->buf + strlen (rs->buf),
11825 rs->buf_size - strlen (rs->buf));
11826 putpkt (rs->buf);
11827 remote_get_noisy_reply (&target_buf, &target_buf_size);
11828 if (strcmp (target_buf, "OK"))
11829 warning (_("Target does not support source download."));
11830
11831 if (cmd->control_type == while_control
11832 || cmd->control_type == while_stepping_control)
11833 {
11834 remote_download_command_source (num, addr, *cmd->body_list);
11835
0df8b418 11836 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11837 strcpy (rs->buf, "QTDPsrc:");
11838 encode_source_string (num, addr, "cmd", "end",
11839 rs->buf + strlen (rs->buf),
11840 rs->buf_size - strlen (rs->buf));
11841 putpkt (rs->buf);
11842 remote_get_noisy_reply (&target_buf, &target_buf_size);
11843 if (strcmp (target_buf, "OK"))
11844 warning (_("Target does not support source download."));
11845 }
11846 }
11847}
11848
35b1e5cc 11849static void
548f7808 11850remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 11851{
bba74b36 11852#define BUF_SIZE 2048
e8ba3115 11853
35b1e5cc 11854 CORE_ADDR tpaddr;
409873ef 11855 char addrbuf[40];
bba74b36 11856 char buf[BUF_SIZE];
35b1e5cc
SS
11857 char **tdp_actions;
11858 char **stepping_actions;
11859 int ndx;
11860 struct cleanup *old_chain = NULL;
11861 struct agent_expr *aexpr;
11862 struct cleanup *aexpr_chain = NULL;
11863 char *pkt;
e8ba3115 11864 struct breakpoint *b = loc->owner;
d9b3f62e 11865 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 11866
dc673c81 11867 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
11868 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11869 tdp_actions);
11870 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11871 stepping_actions);
11872
11873 tpaddr = loc->address;
11874 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
11875 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11876 addrbuf, /* address */
11877 (b->enable_state == bp_enabled ? 'E' : 'D'),
11878 t->step_count, t->pass_count);
e8ba3115
YQ
11879 /* Fast tracepoints are mostly handled by the target, but we can
11880 tell the target how big of an instruction block should be moved
11881 around. */
11882 if (b->type == bp_fast_tracepoint)
11883 {
11884 /* Only test for support at download time; we may not know
11885 target capabilities at definition time. */
11886 if (remote_supports_fast_tracepoints ())
35b1e5cc 11887 {
6b940e6a
PL
11888 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11889 NULL))
bba74b36 11890 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 11891 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 11892 else
e8ba3115
YQ
11893 /* If it passed validation at definition but fails now,
11894 something is very wrong. */
11895 internal_error (__FILE__, __LINE__,
11896 _("Fast tracepoint not "
11897 "valid during download"));
35b1e5cc 11898 }
e8ba3115
YQ
11899 else
11900 /* Fast tracepoints are functionally identical to regular
11901 tracepoints, so don't take lack of support as a reason to
11902 give up on the trace run. */
11903 warning (_("Target does not support fast tracepoints, "
11904 "downloading %d as regular tracepoint"), b->number);
11905 }
11906 else if (b->type == bp_static_tracepoint)
11907 {
11908 /* Only test for support at download time; we may not know
11909 target capabilities at definition time. */
11910 if (remote_supports_static_tracepoints ())
0fb4aa4b 11911 {
e8ba3115 11912 struct static_tracepoint_marker marker;
0fb4aa4b 11913
e8ba3115
YQ
11914 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11915 strcat (buf, ":S");
0fb4aa4b 11916 else
e8ba3115 11917 error (_("Static tracepoint not valid during download"));
0fb4aa4b 11918 }
e8ba3115
YQ
11919 else
11920 /* Fast tracepoints are functionally identical to regular
11921 tracepoints, so don't take lack of support as a reason
11922 to give up on the trace run. */
11923 error (_("Target does not support static tracepoints"));
11924 }
11925 /* If the tracepoint has a conditional, make it into an agent
11926 expression and append to the definition. */
11927 if (loc->cond)
11928 {
11929 /* Only test support at download time, we may not know target
11930 capabilities at definition time. */
11931 if (remote_supports_cond_tracepoints ())
35b1e5cc 11932 {
e8ba3115
YQ
11933 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11934 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
11935 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11936 aexpr->len);
e8ba3115
YQ
11937 pkt = buf + strlen (buf);
11938 for (ndx = 0; ndx < aexpr->len; ++ndx)
11939 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11940 *pkt = '\0';
11941 do_cleanups (aexpr_chain);
35b1e5cc 11942 }
e8ba3115
YQ
11943 else
11944 warning (_("Target does not support conditional tracepoints, "
11945 "ignoring tp %d cond"), b->number);
11946 }
35b1e5cc 11947
d9b3f62e 11948 if (b->commands || *default_collect)
e8ba3115
YQ
11949 strcat (buf, "-");
11950 putpkt (buf);
11951 remote_get_noisy_reply (&target_buf, &target_buf_size);
11952 if (strcmp (target_buf, "OK"))
11953 error (_("Target does not support tracepoints."));
35b1e5cc 11954
e8ba3115
YQ
11955 /* do_single_steps (t); */
11956 if (tdp_actions)
11957 {
11958 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 11959 {
e8ba3115 11960 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11961 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11962 b->number, addrbuf, /* address */
11963 tdp_actions[ndx],
11964 ((tdp_actions[ndx + 1] || stepping_actions)
11965 ? '-' : 0));
e8ba3115
YQ
11966 putpkt (buf);
11967 remote_get_noisy_reply (&target_buf,
11968 &target_buf_size);
11969 if (strcmp (target_buf, "OK"))
11970 error (_("Error on target while setting tracepoints."));
35b1e5cc 11971 }
e8ba3115
YQ
11972 }
11973 if (stepping_actions)
11974 {
11975 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 11976 {
e8ba3115 11977 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11978 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11979 b->number, addrbuf, /* address */
11980 ((ndx == 0) ? "S" : ""),
11981 stepping_actions[ndx],
11982 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
11983 putpkt (buf);
11984 remote_get_noisy_reply (&target_buf,
11985 &target_buf_size);
11986 if (strcmp (target_buf, "OK"))
11987 error (_("Error on target while setting tracepoints."));
35b1e5cc 11988 }
e8ba3115 11989 }
409873ef 11990
4082afcc 11991 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 11992 {
f00aae0f 11993 if (b->location != NULL)
409873ef 11994 {
e8ba3115 11995 strcpy (buf, "QTDPsrc:");
f00aae0f
KS
11996 encode_source_string (b->number, loc->address, "at",
11997 event_location_to_string (b->location),
11998 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115
YQ
11999 putpkt (buf);
12000 remote_get_noisy_reply (&target_buf, &target_buf_size);
12001 if (strcmp (target_buf, "OK"))
12002 warning (_("Target does not support source download."));
409873ef 12003 }
e8ba3115
YQ
12004 if (b->cond_string)
12005 {
12006 strcpy (buf, "QTDPsrc:");
12007 encode_source_string (b->number, loc->address,
12008 "cond", b->cond_string, buf + strlen (buf),
12009 2048 - strlen (buf));
12010 putpkt (buf);
12011 remote_get_noisy_reply (&target_buf, &target_buf_size);
12012 if (strcmp (target_buf, "OK"))
12013 warning (_("Target does not support source download."));
12014 }
12015 remote_download_command_source (b->number, loc->address,
12016 breakpoint_commands (b));
35b1e5cc 12017 }
e8ba3115
YQ
12018
12019 do_cleanups (old_chain);
35b1e5cc
SS
12020}
12021
1e4d1764 12022static int
a52a8357 12023remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 12024{
1e51243a
PA
12025 struct remote_state *rs = get_remote_state ();
12026 struct trace_status *ts;
12027 int status;
12028
12029 /* Don't try to install tracepoints until we've relocated our
12030 symbols, and fetched and merged the target's tracepoint list with
12031 ours. */
12032 if (rs->starting_up)
12033 return 0;
12034
12035 ts = current_trace_status ();
8bd200f1 12036 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
12037
12038 if (status == -1 || !ts->running_known || !ts->running)
12039 return 0;
12040
12041 /* If we are in a tracing experiment, but remote stub doesn't support
12042 installing tracepoint in trace, we have to return. */
12043 if (!remote_supports_install_in_trace ())
12044 return 0;
12045
12046 return 1;
12047}
12048
12049
35b1e5cc 12050static void
559d2b81
TT
12051remote_download_trace_state_variable (struct target_ops *self,
12052 struct trace_state_variable *tsv)
35b1e5cc
SS
12053{
12054 struct remote_state *rs = get_remote_state ();
00bf0b85 12055 char *p;
35b1e5cc 12056
bba74b36
YQ
12057 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12058 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12059 tsv->builtin);
00bf0b85
SS
12060 p = rs->buf + strlen (rs->buf);
12061 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12062 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 12063 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 12064 *p++ = '\0';
35b1e5cc
SS
12065 putpkt (rs->buf);
12066 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12067 if (*target_buf == '\0')
12068 error (_("Target does not support this command."));
12069 if (strcmp (target_buf, "OK") != 0)
12070 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
12071}
12072
d248b706 12073static void
46670d57
TT
12074remote_enable_tracepoint (struct target_ops *self,
12075 struct bp_location *location)
d248b706
KY
12076{
12077 struct remote_state *rs = get_remote_state ();
12078 char addr_buf[40];
12079
12080 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12081 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12082 location->owner->number, addr_buf);
d248b706
KY
12083 putpkt (rs->buf);
12084 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12085 if (*rs->buf == '\0')
12086 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12087 if (strcmp (rs->buf, "OK") != 0)
12088 error (_("Error on target while enabling tracepoint."));
12089}
12090
12091static void
780b049c
TT
12092remote_disable_tracepoint (struct target_ops *self,
12093 struct bp_location *location)
d248b706
KY
12094{
12095 struct remote_state *rs = get_remote_state ();
12096 char addr_buf[40];
12097
12098 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12099 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12100 location->owner->number, addr_buf);
d248b706
KY
12101 putpkt (rs->buf);
12102 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12103 if (*rs->buf == '\0')
12104 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12105 if (strcmp (rs->buf, "OK") != 0)
12106 error (_("Error on target while disabling tracepoint."));
12107}
12108
35b1e5cc 12109static void
583f9a86 12110remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
12111{
12112 asection *s;
81b9b86e 12113 bfd *abfd = NULL;
35b1e5cc 12114 bfd_size_type size;
608bcef2 12115 bfd_vma vma;
35b1e5cc 12116 int anysecs = 0;
c2fa21f1 12117 int offset = 0;
35b1e5cc
SS
12118
12119 if (!exec_bfd)
12120 return; /* No information to give. */
12121
12122 strcpy (target_buf, "QTro");
9779ab84 12123 offset = strlen (target_buf);
35b1e5cc
SS
12124 for (s = exec_bfd->sections; s; s = s->next)
12125 {
12126 char tmp1[40], tmp2[40];
c2fa21f1 12127 int sec_length;
35b1e5cc
SS
12128
12129 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 12130 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
12131 (s->flags & SEC_READONLY) == 0)
12132 continue;
12133
12134 anysecs = 1;
81b9b86e 12135 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 12136 size = bfd_get_section_size (s);
608bcef2
HZ
12137 sprintf_vma (tmp1, vma);
12138 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
12139 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12140 if (offset + sec_length + 1 > target_buf_size)
12141 {
4082afcc 12142 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 12143 warning (_("\
c2fa21f1
HZ
12144Too many sections for read-only sections definition packet."));
12145 break;
12146 }
bba74b36
YQ
12147 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12148 tmp1, tmp2);
c2fa21f1 12149 offset += sec_length;
35b1e5cc
SS
12150 }
12151 if (anysecs)
12152 {
12153 putpkt (target_buf);
12154 getpkt (&target_buf, &target_buf_size, 0);
12155 }
12156}
12157
12158static void
e2d1aae3 12159remote_trace_start (struct target_ops *self)
35b1e5cc
SS
12160{
12161 putpkt ("QTStart");
12162 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12163 if (*target_buf == '\0')
12164 error (_("Target does not support this command."));
12165 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12166 error (_("Bogus reply from target: %s"), target_buf);
12167}
12168
12169static int
8bd200f1 12170remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 12171{
953b98d1 12172 /* Initialize it just to avoid a GCC false warning. */
f652de6f 12173 char *p = NULL;
0df8b418 12174 /* FIXME we need to get register block size some other way. */
00bf0b85 12175 extern int trace_regblock_size;
bd3eecc3
PA
12176 enum packet_result result;
12177
4082afcc 12178 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 12179 return -1;
a744cf53 12180
00bf0b85
SS
12181 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12182
049dc89b
JK
12183 putpkt ("qTStatus");
12184
492d29ea 12185 TRY
67f41397
JK
12186 {
12187 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12188 }
492d29ea 12189 CATCH (ex, RETURN_MASK_ERROR)
67f41397 12190 {
598d3636
JK
12191 if (ex.error != TARGET_CLOSE_ERROR)
12192 {
12193 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12194 return -1;
12195 }
12196 throw_exception (ex);
67f41397 12197 }
492d29ea 12198 END_CATCH
00bf0b85 12199
bd3eecc3
PA
12200 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12201
00bf0b85 12202 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 12203 if (result == PACKET_UNKNOWN)
00bf0b85 12204 return -1;
35b1e5cc 12205
00bf0b85 12206 /* We're working with a live target. */
f5911ea1 12207 ts->filename = NULL;
00bf0b85 12208
00bf0b85 12209 if (*p++ != 'T')
35b1e5cc
SS
12210 error (_("Bogus trace status reply from target: %s"), target_buf);
12211
84cebc4a
YQ
12212 /* Function 'parse_trace_status' sets default value of each field of
12213 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
12214 parse_trace_status (p, ts);
12215
12216 return ts->running;
35b1e5cc
SS
12217}
12218
70221824 12219static void
db90e85c 12220remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
12221 struct uploaded_tp *utp)
12222{
12223 struct remote_state *rs = get_remote_state ();
f196051f
SS
12224 char *reply;
12225 struct bp_location *loc;
12226 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 12227 size_t size = get_remote_packet_size ();
f196051f
SS
12228
12229 if (tp)
12230 {
12231 tp->base.hit_count = 0;
12232 tp->traceframe_usage = 0;
12233 for (loc = tp->base.loc; loc; loc = loc->next)
12234 {
12235 /* If the tracepoint was never downloaded, don't go asking for
12236 any status. */
12237 if (tp->number_on_target == 0)
12238 continue;
bba74b36
YQ
12239 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12240 phex_nz (loc->address, 0));
f196051f
SS
12241 putpkt (rs->buf);
12242 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12243 if (reply && *reply)
12244 {
12245 if (*reply == 'V')
12246 parse_tracepoint_status (reply + 1, bp, utp);
12247 }
12248 }
12249 }
12250 else if (utp)
12251 {
12252 utp->hit_count = 0;
12253 utp->traceframe_usage = 0;
bba74b36
YQ
12254 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12255 phex_nz (utp->addr, 0));
f196051f
SS
12256 putpkt (rs->buf);
12257 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12258 if (reply && *reply)
12259 {
12260 if (*reply == 'V')
12261 parse_tracepoint_status (reply + 1, bp, utp);
12262 }
12263 }
12264}
12265
35b1e5cc 12266static void
74499f1b 12267remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
12268{
12269 putpkt ("QTStop");
12270 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12271 if (*target_buf == '\0')
12272 error (_("Target does not support this command."));
12273 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12274 error (_("Bogus reply from target: %s"), target_buf);
12275}
12276
12277static int
bd4c6793
TT
12278remote_trace_find (struct target_ops *self,
12279 enum trace_find_type type, int num,
cc5925ad 12280 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
12281 int *tpp)
12282{
12283 struct remote_state *rs = get_remote_state ();
bba74b36 12284 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
12285 char *p, *reply;
12286 int target_frameno = -1, target_tracept = -1;
12287
e6e4e701
PA
12288 /* Lookups other than by absolute frame number depend on the current
12289 trace selected, so make sure it is correct on the remote end
12290 first. */
12291 if (type != tfind_number)
12292 set_remote_traceframe ();
12293
35b1e5cc
SS
12294 p = rs->buf;
12295 strcpy (p, "QTFrame:");
12296 p = strchr (p, '\0');
12297 switch (type)
12298 {
12299 case tfind_number:
bba74b36 12300 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
12301 break;
12302 case tfind_pc:
bba74b36 12303 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
12304 break;
12305 case tfind_tp:
bba74b36 12306 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
12307 break;
12308 case tfind_range:
bba74b36
YQ
12309 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12310 phex_nz (addr2, 0));
35b1e5cc
SS
12311 break;
12312 case tfind_outside:
bba74b36
YQ
12313 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12314 phex_nz (addr2, 0));
35b1e5cc
SS
12315 break;
12316 default:
9b20d036 12317 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
12318 }
12319
12320 putpkt (rs->buf);
2f65bcb7 12321 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
12322 if (*reply == '\0')
12323 error (_("Target does not support this command."));
35b1e5cc
SS
12324
12325 while (reply && *reply)
12326 switch (*reply)
12327 {
12328 case 'F':
f197e0f1
VP
12329 p = ++reply;
12330 target_frameno = (int) strtol (p, &reply, 16);
12331 if (reply == p)
12332 error (_("Unable to parse trace frame number"));
e6e4e701
PA
12333 /* Don't update our remote traceframe number cache on failure
12334 to select a remote traceframe. */
f197e0f1
VP
12335 if (target_frameno == -1)
12336 return -1;
35b1e5cc
SS
12337 break;
12338 case 'T':
f197e0f1
VP
12339 p = ++reply;
12340 target_tracept = (int) strtol (p, &reply, 16);
12341 if (reply == p)
12342 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
12343 break;
12344 case 'O': /* "OK"? */
12345 if (reply[1] == 'K' && reply[2] == '\0')
12346 reply += 2;
12347 else
12348 error (_("Bogus reply from target: %s"), reply);
12349 break;
12350 default:
12351 error (_("Bogus reply from target: %s"), reply);
12352 }
12353 if (tpp)
12354 *tpp = target_tracept;
e6e4e701 12355
262e1174 12356 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
12357 return target_frameno;
12358}
12359
12360static int
4011015b
TT
12361remote_get_trace_state_variable_value (struct target_ops *self,
12362 int tsvnum, LONGEST *val)
35b1e5cc
SS
12363{
12364 struct remote_state *rs = get_remote_state ();
12365 char *reply;
12366 ULONGEST uval;
12367
e6e4e701
PA
12368 set_remote_traceframe ();
12369
bba74b36 12370 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
12371 putpkt (rs->buf);
12372 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12373 if (reply && *reply)
12374 {
12375 if (*reply == 'V')
12376 {
12377 unpack_varlen_hex (reply + 1, &uval);
12378 *val = (LONGEST) uval;
12379 return 1;
12380 }
12381 }
12382 return 0;
12383}
12384
00bf0b85 12385static int
dc3decaf 12386remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
12387{
12388 struct remote_state *rs = get_remote_state ();
12389 char *p, *reply;
12390
12391 p = rs->buf;
12392 strcpy (p, "QTSave:");
12393 p += strlen (p);
12394 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12395 error (_("Remote file name too long for trace save packet"));
9f1b45b0 12396 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
12397 *p++ = '\0';
12398 putpkt (rs->buf);
ad91cd99 12399 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 12400 if (*reply == '\0')
ad91cd99
PA
12401 error (_("Target does not support this command."));
12402 if (strcmp (reply, "OK") != 0)
12403 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
12404 return 0;
12405}
12406
12407/* This is basically a memory transfer, but needs to be its own packet
12408 because we don't know how the target actually organizes its trace
12409 memory, plus we want to be able to ask for as much as possible, but
12410 not be unhappy if we don't get as much as we ask for. */
12411
12412static LONGEST
88ee6f45
TT
12413remote_get_raw_trace_data (struct target_ops *self,
12414 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
12415{
12416 struct remote_state *rs = get_remote_state ();
12417 char *reply;
12418 char *p;
12419 int rslt;
12420
12421 p = rs->buf;
12422 strcpy (p, "qTBuffer:");
12423 p += strlen (p);
12424 p += hexnumstr (p, offset);
12425 *p++ = ',';
12426 p += hexnumstr (p, len);
12427 *p++ = '\0';
12428
12429 putpkt (rs->buf);
12430 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12431 if (reply && *reply)
12432 {
12433 /* 'l' by itself means we're at the end of the buffer and
12434 there is nothing more to get. */
12435 if (*reply == 'l')
12436 return 0;
12437
12438 /* Convert the reply into binary. Limit the number of bytes to
12439 convert according to our passed-in buffer size, rather than
12440 what was returned in the packet; if the target is
12441 unexpectedly generous and gives us a bigger reply than we
12442 asked for, we don't want to crash. */
12443 rslt = hex2bin (target_buf, buf, len);
12444 return rslt;
12445 }
12446
12447 /* Something went wrong, flag as an error. */
12448 return -1;
12449}
12450
35b1e5cc 12451static void
37b25738 12452remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
12453{
12454 struct remote_state *rs = get_remote_state ();
12455
4082afcc 12456 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 12457 {
ad91cd99
PA
12458 char *reply;
12459
bba74b36 12460 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 12461 putpkt (rs->buf);
ad91cd99
PA
12462 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12463 if (*reply == '\0')
33da3f1c 12464 error (_("Target does not support this command."));
ad91cd99
PA
12465 if (strcmp (reply, "OK") != 0)
12466 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
12467 }
12468 else if (val)
12469 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
12470}
12471
dc146f7c
VP
12472static int
12473remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12474{
12475 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 12476
fe978cb0
PA
12477 if (info && info->priv)
12478 return info->priv->core;
dc146f7c
VP
12479 return -1;
12480}
12481
4daf5ac0 12482static void
736d5b1f 12483remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
12484{
12485 struct remote_state *rs = get_remote_state ();
ad91cd99 12486 char *reply;
4daf5ac0 12487
bba74b36 12488 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 12489 putpkt (rs->buf);
ad91cd99
PA
12490 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12491 if (*reply == '\0')
4daf5ac0 12492 error (_("Target does not support this command."));
ad91cd99
PA
12493 if (strcmp (reply, "OK") != 0)
12494 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
12495}
12496
b3b9301e 12497static struct traceframe_info *
a893e81f 12498remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
12499{
12500 char *text;
12501
12502 text = target_read_stralloc (&current_target,
12503 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12504 if (text != NULL)
12505 {
12506 struct traceframe_info *info;
12507 struct cleanup *back_to = make_cleanup (xfree, text);
12508
12509 info = parse_traceframe_info (text);
12510 do_cleanups (back_to);
12511 return info;
12512 }
12513
12514 return NULL;
12515}
12516
405f8e94
SS
12517/* Handle the qTMinFTPILen packet. Returns the minimum length of
12518 instruction on which a fast tracepoint may be placed. Returns -1
12519 if the packet is not supported, and 0 if the minimum instruction
12520 length is unknown. */
12521
12522static int
0e67620a 12523remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
12524{
12525 struct remote_state *rs = get_remote_state ();
12526 char *reply;
12527
e886a173
PA
12528 /* If we're not debugging a process yet, the IPA can't be
12529 loaded. */
12530 if (!target_has_execution)
12531 return 0;
12532
12533 /* Make sure the remote is pointing at the right process. */
12534 set_general_process ();
12535
bba74b36 12536 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
12537 putpkt (rs->buf);
12538 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12539 if (*reply == '\0')
12540 return -1;
12541 else
12542 {
12543 ULONGEST min_insn_len;
12544
12545 unpack_varlen_hex (reply, &min_insn_len);
12546
12547 return (int) min_insn_len;
12548 }
12549}
12550
f6f899bf 12551static void
4da384be 12552remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 12553{
4082afcc 12554 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
12555 {
12556 struct remote_state *rs = get_remote_state ();
12557 char *buf = rs->buf;
12558 char *endbuf = rs->buf + get_remote_packet_size ();
12559 enum packet_result result;
12560
12561 gdb_assert (val >= 0 || val == -1);
12562 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12563 /* Send -1 as literal "-1" to avoid host size dependency. */
12564 if (val < 0)
12565 {
12566 *buf++ = '-';
12567 buf += hexnumstr (buf, (ULONGEST) -val);
12568 }
12569 else
12570 buf += hexnumstr (buf, (ULONGEST) val);
12571
12572 putpkt (rs->buf);
12573 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12574 result = packet_ok (rs->buf,
12575 &remote_protocol_packets[PACKET_QTBuffer_size]);
12576
12577 if (result != PACKET_OK)
12578 warning (_("Bogus reply from target: %s"), rs->buf);
12579 }
12580}
12581
f196051f 12582static int
d9e68a2c
TT
12583remote_set_trace_notes (struct target_ops *self,
12584 const char *user, const char *notes,
ca623f82 12585 const char *stop_notes)
f196051f
SS
12586{
12587 struct remote_state *rs = get_remote_state ();
12588 char *reply;
12589 char *buf = rs->buf;
12590 char *endbuf = rs->buf + get_remote_packet_size ();
12591 int nbytes;
12592
12593 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12594 if (user)
12595 {
12596 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 12597 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
12598 buf += 2 * nbytes;
12599 *buf++ = ';';
12600 }
12601 if (notes)
12602 {
12603 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 12604 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
12605 buf += 2 * nbytes;
12606 *buf++ = ';';
12607 }
12608 if (stop_notes)
12609 {
12610 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 12611 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
12612 buf += 2 * nbytes;
12613 *buf++ = ';';
12614 }
12615 /* Ensure the buffer is terminated. */
12616 *buf = '\0';
12617
12618 putpkt (rs->buf);
12619 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12620 if (*reply == '\0')
12621 return 0;
12622
12623 if (strcmp (reply, "OK") != 0)
12624 error (_("Bogus reply from target: %s"), reply);
12625
12626 return 1;
12627}
12628
d1feda86 12629static int
2c152180 12630remote_use_agent (struct target_ops *self, int use)
d1feda86 12631{
4082afcc 12632 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
12633 {
12634 struct remote_state *rs = get_remote_state ();
12635
12636 /* If the stub supports QAgent. */
bba74b36 12637 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
12638 putpkt (rs->buf);
12639 getpkt (&rs->buf, &rs->buf_size, 0);
12640
12641 if (strcmp (rs->buf, "OK") == 0)
12642 {
12643 use_agent = use;
12644 return 1;
12645 }
12646 }
12647
12648 return 0;
12649}
12650
12651static int
fe38f897 12652remote_can_use_agent (struct target_ops *self)
d1feda86 12653{
4082afcc 12654 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
12655}
12656
9accd112
MM
12657struct btrace_target_info
12658{
12659 /* The ptid of the traced thread. */
12660 ptid_t ptid;
f4abbc16
MM
12661
12662 /* The obtained branch trace configuration. */
12663 struct btrace_config conf;
9accd112
MM
12664};
12665
f4abbc16
MM
12666/* Reset our idea of our target's btrace configuration. */
12667
12668static void
12669remote_btrace_reset (void)
12670{
12671 struct remote_state *rs = get_remote_state ();
12672
12673 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12674}
12675
9accd112
MM
12676/* Check whether the target supports branch tracing. */
12677
12678static int
043c3577 12679remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 12680{
4082afcc 12681 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 12682 return 0;
4082afcc 12683 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
12684 return 0;
12685
043c3577
MM
12686 switch (format)
12687 {
12688 case BTRACE_FORMAT_NONE:
12689 return 0;
12690
12691 case BTRACE_FORMAT_BTS:
12692 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
b20a6524
MM
12693
12694 case BTRACE_FORMAT_PT:
12695 /* The trace is decoded on the host. Even if our target supports it,
12696 we still need to have libipt to decode the trace. */
12697#if defined (HAVE_LIBIPT)
12698 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12699#else /* !defined (HAVE_LIBIPT) */
12700 return 0;
12701#endif /* !defined (HAVE_LIBIPT) */
043c3577
MM
12702 }
12703
12704 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
12705}
12706
f4abbc16
MM
12707/* Synchronize the configuration with the target. */
12708
12709static void
12710btrace_sync_conf (const struct btrace_config *conf)
12711{
d33501a5
MM
12712 struct packet_config *packet;
12713 struct remote_state *rs;
12714 char *buf, *pos, *endbuf;
12715
12716 rs = get_remote_state ();
12717 buf = rs->buf;
12718 endbuf = buf + get_remote_packet_size ();
12719
12720 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12721 if (packet_config_support (packet) == PACKET_ENABLE
12722 && conf->bts.size != rs->btrace_config.bts.size)
12723 {
12724 pos = buf;
12725 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12726 conf->bts.size);
12727
12728 putpkt (buf);
12729 getpkt (&buf, &rs->buf_size, 0);
12730
12731 if (packet_ok (buf, packet) == PACKET_ERROR)
12732 {
12733 if (buf[0] == 'E' && buf[1] == '.')
12734 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12735 else
12736 error (_("Failed to configure the BTS buffer size."));
12737 }
12738
12739 rs->btrace_config.bts.size = conf->bts.size;
12740 }
b20a6524
MM
12741
12742 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12743 if (packet_config_support (packet) == PACKET_ENABLE
12744 && conf->pt.size != rs->btrace_config.pt.size)
12745 {
12746 pos = buf;
12747 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12748 conf->pt.size);
12749
12750 putpkt (buf);
12751 getpkt (&buf, &rs->buf_size, 0);
12752
12753 if (packet_ok (buf, packet) == PACKET_ERROR)
12754 {
12755 if (buf[0] == 'E' && buf[1] == '.')
12756 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12757 else
12758 error (_("Failed to configure the trace buffer size."));
12759 }
12760
12761 rs->btrace_config.pt.size = conf->pt.size;
12762 }
f4abbc16
MM
12763}
12764
12765/* Read the current thread's btrace configuration from the target and
12766 store it into CONF. */
12767
12768static void
12769btrace_read_config (struct btrace_config *conf)
12770{
12771 char *xml;
12772
12773 xml = target_read_stralloc (&current_target,
b20a6524 12774 TARGET_OBJECT_BTRACE_CONF, "");
f4abbc16
MM
12775 if (xml != NULL)
12776 {
12777 struct cleanup *cleanup;
12778
12779 cleanup = make_cleanup (xfree, xml);
12780 parse_xml_btrace_conf (conf, xml);
12781 do_cleanups (cleanup);
12782 }
12783}
12784
c0272db5
TW
12785/* Maybe reopen target btrace. */
12786
12787static void
12788remote_btrace_maybe_reopen (void)
12789{
12790 struct remote_state *rs = get_remote_state ();
12791 struct cleanup *cleanup;
12792 struct thread_info *tp;
12793 int btrace_target_pushed = 0;
12794 int warned = 0;
12795
12796 cleanup = make_cleanup_restore_current_thread ();
12797 ALL_NON_EXITED_THREADS (tp)
12798 {
12799 set_general_thread (tp->ptid);
12800
12801 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
12802 btrace_read_config (&rs->btrace_config);
12803
12804 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
12805 continue;
12806
12807#if !defined (HAVE_LIBIPT)
12808 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
12809 {
12810 if (!warned)
12811 {
12812 warned = 1;
12813 warning (_("GDB does not support Intel Processor Trace. "
12814 "\"record\" will not work in this session."));
12815 }
12816
12817 continue;
12818 }
12819#endif /* !defined (HAVE_LIBIPT) */
12820
12821 /* Push target, once, but before anything else happens. This way our
12822 changes to the threads will be cleaned up by unpushing the target
12823 in case btrace_read_config () throws. */
12824 if (!btrace_target_pushed)
12825 {
12826 btrace_target_pushed = 1;
12827 record_btrace_push_target ();
12828 printf_filtered (_("Target is recording using %s.\n"),
12829 btrace_format_string (rs->btrace_config.format));
12830 }
12831
12832 tp->btrace.target = XCNEW (struct btrace_target_info);
12833 tp->btrace.target->ptid = tp->ptid;
12834 tp->btrace.target->conf = rs->btrace_config;
12835 }
12836 do_cleanups (cleanup);
12837}
12838
9accd112
MM
12839/* Enable branch tracing. */
12840
12841static struct btrace_target_info *
f4abbc16
MM
12842remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12843 const struct btrace_config *conf)
9accd112
MM
12844{
12845 struct btrace_target_info *tinfo = NULL;
b20a6524 12846 struct packet_config *packet = NULL;
9accd112
MM
12847 struct remote_state *rs = get_remote_state ();
12848 char *buf = rs->buf;
12849 char *endbuf = rs->buf + get_remote_packet_size ();
12850
b20a6524
MM
12851 switch (conf->format)
12852 {
12853 case BTRACE_FORMAT_BTS:
12854 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12855 break;
12856
12857 case BTRACE_FORMAT_PT:
12858 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12859 break;
12860 }
12861
12862 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12863 error (_("Target does not support branch tracing."));
12864
f4abbc16
MM
12865 btrace_sync_conf (conf);
12866
9accd112
MM
12867 set_general_thread (ptid);
12868
12869 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12870 putpkt (rs->buf);
12871 getpkt (&rs->buf, &rs->buf_size, 0);
12872
12873 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12874 {
12875 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12876 error (_("Could not enable branch tracing for %s: %s"),
12877 target_pid_to_str (ptid), rs->buf + 2);
12878 else
12879 error (_("Could not enable branch tracing for %s."),
12880 target_pid_to_str (ptid));
12881 }
12882
8d749320 12883 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
12884 tinfo->ptid = ptid;
12885
f4abbc16
MM
12886 /* If we fail to read the configuration, we lose some information, but the
12887 tracing itself is not impacted. */
492d29ea
PA
12888 TRY
12889 {
12890 btrace_read_config (&tinfo->conf);
12891 }
12892 CATCH (err, RETURN_MASK_ERROR)
12893 {
12894 if (err.message != NULL)
12895 warning ("%s", err.message);
12896 }
12897 END_CATCH
f4abbc16 12898
9accd112
MM
12899 return tinfo;
12900}
12901
12902/* Disable branch tracing. */
12903
12904static void
25e95349
TT
12905remote_disable_btrace (struct target_ops *self,
12906 struct btrace_target_info *tinfo)
9accd112
MM
12907{
12908 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12909 struct remote_state *rs = get_remote_state ();
12910 char *buf = rs->buf;
12911 char *endbuf = rs->buf + get_remote_packet_size ();
12912
4082afcc 12913 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12914 error (_("Target does not support branch tracing."));
12915
12916 set_general_thread (tinfo->ptid);
12917
12918 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12919 putpkt (rs->buf);
12920 getpkt (&rs->buf, &rs->buf_size, 0);
12921
12922 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12923 {
12924 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12925 error (_("Could not disable branch tracing for %s: %s"),
12926 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12927 else
12928 error (_("Could not disable branch tracing for %s."),
12929 target_pid_to_str (tinfo->ptid));
12930 }
12931
12932 xfree (tinfo);
12933}
12934
12935/* Teardown branch tracing. */
12936
12937static void
1777056d
TT
12938remote_teardown_btrace (struct target_ops *self,
12939 struct btrace_target_info *tinfo)
9accd112
MM
12940{
12941 /* We must not talk to the target during teardown. */
12942 xfree (tinfo);
12943}
12944
12945/* Read the branch trace. */
12946
969c39fb 12947static enum btrace_error
39c49f83 12948remote_read_btrace (struct target_ops *self,
734b0e4b 12949 struct btrace_data *btrace,
969c39fb 12950 struct btrace_target_info *tinfo,
9accd112
MM
12951 enum btrace_read_type type)
12952{
12953 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
969c39fb 12954 struct cleanup *cleanup;
9accd112
MM
12955 const char *annex;
12956 char *xml;
12957
4082afcc 12958 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12959 error (_("Target does not support branch tracing."));
12960
12961#if !defined(HAVE_LIBEXPAT)
12962 error (_("Cannot process branch tracing result. XML parsing not supported."));
12963#endif
12964
12965 switch (type)
12966 {
864089d2 12967 case BTRACE_READ_ALL:
9accd112
MM
12968 annex = "all";
12969 break;
864089d2 12970 case BTRACE_READ_NEW:
9accd112
MM
12971 annex = "new";
12972 break;
969c39fb
MM
12973 case BTRACE_READ_DELTA:
12974 annex = "delta";
12975 break;
9accd112
MM
12976 default:
12977 internal_error (__FILE__, __LINE__,
12978 _("Bad branch tracing read type: %u."),
12979 (unsigned int) type);
12980 }
12981
12982 xml = target_read_stralloc (&current_target,
b20a6524 12983 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
12984 if (xml == NULL)
12985 return BTRACE_ERR_UNKNOWN;
9accd112 12986
969c39fb 12987 cleanup = make_cleanup (xfree, xml);
734b0e4b 12988 parse_xml_btrace (btrace, xml);
969c39fb 12989 do_cleanups (cleanup);
9accd112 12990
969c39fb 12991 return BTRACE_ERR_NONE;
9accd112
MM
12992}
12993
f4abbc16
MM
12994static const struct btrace_config *
12995remote_btrace_conf (struct target_ops *self,
12996 const struct btrace_target_info *tinfo)
12997{
12998 return &tinfo->conf;
12999}
13000
ced63ec0 13001static int
5436ff03 13002remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 13003{
4082afcc
PA
13004 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13005 == PACKET_ENABLE);
ced63ec0
GB
13006}
13007
9dd130a0
TT
13008/* Implementation of to_load. */
13009
13010static void
9cbe5fff 13011remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
13012{
13013 generic_load (name, from_tty);
13014}
13015
c78fa86a
GB
13016/* Accepts an integer PID; returns a string representing a file that
13017 can be opened on the remote side to get the symbols for the child
13018 process. Returns NULL if the operation is not supported. */
13019
13020static char *
13021remote_pid_to_exec_file (struct target_ops *self, int pid)
13022{
13023 static char *filename = NULL;
835205d0
GB
13024 struct inferior *inf;
13025 char *annex = NULL;
c78fa86a
GB
13026
13027 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13028 return NULL;
13029
13030 if (filename != NULL)
13031 xfree (filename);
13032
835205d0
GB
13033 inf = find_inferior_pid (pid);
13034 if (inf == NULL)
13035 internal_error (__FILE__, __LINE__,
13036 _("not currently attached to process %d"), pid);
13037
13038 if (!inf->fake_pid_p)
13039 {
13040 const int annex_size = 9;
13041
224c3ddb 13042 annex = (char *) alloca (annex_size);
835205d0
GB
13043 xsnprintf (annex, annex_size, "%x", pid);
13044 }
13045
c78fa86a
GB
13046 filename = target_read_stralloc (&current_target,
13047 TARGET_OBJECT_EXEC_FILE, annex);
13048
13049 return filename;
13050}
13051
750ce8d1
YQ
13052/* Implement the to_can_do_single_step target_ops method. */
13053
13054static int
13055remote_can_do_single_step (struct target_ops *ops)
13056{
13057 /* We can only tell whether target supports single step or not by
13058 supported s and S vCont actions if the stub supports vContSupported
13059 feature. If the stub doesn't support vContSupported feature,
13060 we have conservatively to think target doesn't supports single
13061 step. */
13062 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13063 {
13064 struct remote_state *rs = get_remote_state ();
13065
13066 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13067 remote_vcont_probe (rs);
13068
13069 return rs->supports_vCont.s && rs->supports_vCont.S;
13070 }
13071 else
13072 return 0;
13073}
13074
3a00c802
PA
13075/* Implementation of the to_execution_direction method for the remote
13076 target. */
13077
13078static enum exec_direction_kind
13079remote_execution_direction (struct target_ops *self)
13080{
13081 struct remote_state *rs = get_remote_state ();
13082
13083 return rs->last_resume_exec_dir;
13084}
13085
c906108c 13086static void
fba45db2 13087init_remote_ops (void)
c906108c 13088{
c5aa993b 13089 remote_ops.to_shortname = "remote";
c906108c 13090 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 13091 remote_ops.to_doc =
c906108c 13092 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
13093Specify the serial device it is connected to\n\
13094(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
13095 remote_ops.to_open = remote_open;
13096 remote_ops.to_close = remote_close;
c906108c 13097 remote_ops.to_detach = remote_detach;
6ad8ae5c 13098 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 13099 remote_ops.to_resume = remote_resume;
c906108c
SS
13100 remote_ops.to_wait = remote_wait;
13101 remote_ops.to_fetch_registers = remote_fetch_registers;
13102 remote_ops.to_store_registers = remote_store_registers;
13103 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 13104 remote_ops.to_files_info = remote_files_info;
c906108c
SS
13105 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13106 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
13107 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13108 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13109 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13110 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
13111 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13112 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
13113 remote_ops.to_watchpoint_addr_within_range =
13114 remote_watchpoint_addr_within_range;
3c3bea1c
GS
13115 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13116 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13117 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
13118 remote_ops.to_region_ok_for_hw_watchpoint
13119 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
13120 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13121 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 13122 remote_ops.to_kill = remote_kill;
9dd130a0 13123 remote_ops.to_load = remote_load;
c906108c 13124 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 13125 remote_ops.to_pass_signals = remote_pass_signals;
82075af2 13126 remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
9b224c5e 13127 remote_ops.to_program_signals = remote_program_signals;
c906108c 13128 remote_ops.to_thread_alive = remote_thread_alive;
79efa585 13129 remote_ops.to_thread_name = remote_thread_name;
e8032dde 13130 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 13131 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 13132 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 13133 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 13134 remote_ops.to_stop = remote_stop;
bfedc46a 13135 remote_ops.to_interrupt = remote_interrupt;
93692b58 13136 remote_ops.to_pass_ctrlc = remote_pass_ctrlc;
4b8a223f 13137 remote_ops.to_xfer_partial = remote_xfer_partial;
09c98b44 13138 remote_ops.to_get_memory_xfer_limit = remote_get_memory_xfer_limit;
96baa820 13139 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 13140 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 13141 remote_ops.to_log_command = serial_log_command;
38691318 13142 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 13143 remote_ops.to_stratum = process_stratum;
c35b1492
PA
13144 remote_ops.to_has_all_memory = default_child_has_all_memory;
13145 remote_ops.to_has_memory = default_child_has_memory;
13146 remote_ops.to_has_stack = default_child_has_stack;
13147 remote_ops.to_has_registers = default_child_has_registers;
13148 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 13149 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 13150 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 13151 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 13152 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
13153 remote_ops.to_flash_erase = remote_flash_erase;
13154 remote_ops.to_flash_done = remote_flash_done;
29709017 13155 remote_ops.to_read_description = remote_read_description;
08388c79 13156 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
13157 remote_ops.to_can_async_p = remote_can_async_p;
13158 remote_ops.to_is_async_p = remote_is_async_p;
13159 remote_ops.to_async = remote_async;
65706a29 13160 remote_ops.to_thread_events = remote_thread_events;
750ce8d1 13161 remote_ops.to_can_do_single_step = remote_can_do_single_step;
75c99385
PA
13162 remote_ops.to_terminal_inferior = remote_terminal_inferior;
13163 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 13164 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 13165 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
13166 remote_ops.to_supports_disable_randomization
13167 = remote_supports_disable_randomization;
4bd7dc42 13168 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
13169 remote_ops.to_fileio_open = remote_hostio_open;
13170 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13171 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 13172 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
13173 remote_ops.to_fileio_close = remote_hostio_close;
13174 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 13175 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 13176 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 13177 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 13178 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 13179 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
13180 remote_ops.to_trace_init = remote_trace_init;
13181 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 13182 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
13183 remote_ops.to_download_trace_state_variable
13184 = remote_download_trace_state_variable;
d248b706
KY
13185 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13186 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
13187 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13188 remote_ops.to_trace_start = remote_trace_start;
13189 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 13190 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
13191 remote_ops.to_trace_stop = remote_trace_stop;
13192 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
13193 remote_ops.to_get_trace_state_variable_value
13194 = remote_get_trace_state_variable_value;
00bf0b85
SS
13195 remote_ops.to_save_trace_data = remote_save_trace_data;
13196 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
13197 remote_ops.to_upload_trace_state_variables
13198 = remote_upload_trace_state_variables;
00bf0b85 13199 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 13200 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 13201 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 13202 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 13203 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 13204 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 13205 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 13206 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 13207 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 13208 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
13209 remote_ops.to_static_tracepoint_marker_at
13210 = remote_static_tracepoint_marker_at;
13211 remote_ops.to_static_tracepoint_markers_by_strid
13212 = remote_static_tracepoint_markers_by_strid;
b3b9301e 13213 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
13214 remote_ops.to_use_agent = remote_use_agent;
13215 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
13216 remote_ops.to_supports_btrace = remote_supports_btrace;
13217 remote_ops.to_enable_btrace = remote_enable_btrace;
13218 remote_ops.to_disable_btrace = remote_disable_btrace;
13219 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13220 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 13221 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
13222 remote_ops.to_augmented_libraries_svr4_read =
13223 remote_augmented_libraries_svr4_read;
8020350c
DB
13224 remote_ops.to_follow_fork = remote_follow_fork;
13225 remote_ops.to_follow_exec = remote_follow_exec;
13226 remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13227 remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13228 remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13229 remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13230 remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13231 remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
3a00c802 13232 remote_ops.to_execution_direction = remote_execution_direction;
c906108c
SS
13233}
13234
13235/* Set up the extended remote vector by making a copy of the standard
13236 remote vector and adding to it. */
13237
13238static void
fba45db2 13239init_extended_remote_ops (void)
c906108c
SS
13240{
13241 extended_remote_ops = remote_ops;
13242
0f71a2f6 13243 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 13244 extended_remote_ops.to_longname =
c906108c 13245 "Extended remote serial target in gdb-specific protocol";
c5aa993b 13246 extended_remote_ops.to_doc =
c906108c 13247 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
13248Specify the serial device it is connected to (e.g. /dev/ttya).";
13249 extended_remote_ops.to_open = extended_remote_open;
c906108c 13250 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
2d717e4f
DJ
13251 extended_remote_ops.to_detach = extended_remote_detach;
13252 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 13253 extended_remote_ops.to_post_attach = extended_remote_post_attach;
03583c20
UW
13254 extended_remote_ops.to_supports_disable_randomization
13255 = extended_remote_supports_disable_randomization;
0f71a2f6
JM
13256}
13257
6426a772 13258static int
6a109b6b 13259remote_can_async_p (struct target_ops *ops)
6426a772 13260{
5d93a237
TT
13261 struct remote_state *rs = get_remote_state ();
13262
c6ebd6cf 13263 if (!target_async_permitted)
75c99385
PA
13264 /* We only enable async when the user specifically asks for it. */
13265 return 0;
13266
23860348 13267 /* We're async whenever the serial device is. */
5d93a237 13268 return serial_can_async_p (rs->remote_desc);
6426a772
JM
13269}
13270
13271static int
6a109b6b 13272remote_is_async_p (struct target_ops *ops)
6426a772 13273{
5d93a237
TT
13274 struct remote_state *rs = get_remote_state ();
13275
c6ebd6cf 13276 if (!target_async_permitted)
75c99385
PA
13277 /* We only enable async when the user specifically asks for it. */
13278 return 0;
13279
23860348 13280 /* We're async whenever the serial device is. */
5d93a237 13281 return serial_is_async_p (rs->remote_desc);
6426a772
JM
13282}
13283
2acceee2
JM
13284/* Pass the SERIAL event on and up to the client. One day this code
13285 will be able to delay notifying the client of an event until the
23860348 13286 point where an entire packet has been received. */
2acceee2 13287
2acceee2
JM
13288static serial_event_ftype remote_async_serial_handler;
13289
6426a772 13290static void
819cc324 13291remote_async_serial_handler (struct serial *scb, void *context)
6426a772 13292{
2acceee2
JM
13293 /* Don't propogate error information up to the client. Instead let
13294 the client find out about the error by querying the target. */
6a3753b3 13295 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
13296}
13297
74531fed
PA
13298static void
13299remote_async_inferior_event_handler (gdb_client_data data)
13300{
13301 inferior_event_handler (INF_REG_EVENT, NULL);
13302}
13303
2acceee2 13304static void
6a3753b3 13305remote_async (struct target_ops *ops, int enable)
2acceee2 13306{
5d93a237
TT
13307 struct remote_state *rs = get_remote_state ();
13308
6a3753b3 13309 if (enable)
2acceee2 13310 {
88b496c3 13311 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
13312
13313 /* If there are pending events in the stop reply queue tell the
13314 event loop to process them. */
13315 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13316 mark_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13317 /* For simplicity, below we clear the pending events token
13318 without remembering whether it is marked, so here we always
13319 mark it. If there's actually no pending notification to
13320 process, this ends up being a no-op (other than a spurious
13321 event-loop wakeup). */
13322 if (target_is_non_stop_p ())
13323 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
13324 }
13325 else
b7d2e916
PA
13326 {
13327 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
13328 /* If the core is disabling async, it doesn't want to be
13329 disturbed with target events. Clear all async event sources
13330 too. */
b7d2e916 13331 clear_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13332 if (target_is_non_stop_p ())
13333 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 13334 }
6426a772
JM
13335}
13336
65706a29
PA
13337/* Implementation of the to_thread_events method. */
13338
13339static void
13340remote_thread_events (struct target_ops *ops, int enable)
13341{
13342 struct remote_state *rs = get_remote_state ();
13343 size_t size = get_remote_packet_size ();
65706a29
PA
13344
13345 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13346 return;
13347
13348 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13349 putpkt (rs->buf);
13350 getpkt (&rs->buf, &rs->buf_size, 0);
13351
13352 switch (packet_ok (rs->buf,
13353 &remote_protocol_packets[PACKET_QThreadEvents]))
13354 {
13355 case PACKET_OK:
13356 if (strcmp (rs->buf, "OK") != 0)
13357 error (_("Remote refused setting thread events: %s"), rs->buf);
13358 break;
13359 case PACKET_ERROR:
13360 warning (_("Remote failure reply: %s"), rs->buf);
13361 break;
13362 case PACKET_UNKNOWN:
13363 break;
13364 }
13365}
13366
5a2468f5 13367static void
c2d11a7d 13368set_remote_cmd (char *args, int from_tty)
5a2468f5 13369{
635c7e8a 13370 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
13371}
13372
d471ea57
AC
13373static void
13374show_remote_cmd (char *args, int from_tty)
13375{
37a105a1 13376 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 13377 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
13378 struct cleanup *showlist_chain;
13379 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 13380 struct ui_out *uiout = current_uiout;
37a105a1
DJ
13381
13382 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13383 for (; list != NULL; list = list->next)
13384 if (strcmp (list->name, "Z-packet") == 0)
13385 continue;
427c3a89
DJ
13386 else if (list->type == not_set_cmd)
13387 /* Alias commands are exactly like the original, except they
13388 don't have the normal type. */
13389 continue;
13390 else
37a105a1
DJ
13391 {
13392 struct cleanup *option_chain
13393 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 13394
37a105a1
DJ
13395 ui_out_field_string (uiout, "name", list->name);
13396 ui_out_text (uiout, ": ");
427c3a89 13397 if (list->type == show_cmd)
5b9afe8a 13398 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
13399 else
13400 cmd_func (list, NULL, from_tty);
37a105a1
DJ
13401 /* Close the tuple. */
13402 do_cleanups (option_chain);
13403 }
427c3a89
DJ
13404
13405 /* Close the tuple. */
13406 do_cleanups (showlist_chain);
d471ea57 13407}
5a2468f5 13408
0f71a2f6 13409
23860348 13410/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
13411static void
13412remote_new_objfile (struct objfile *objfile)
13413{
5d93a237
TT
13414 struct remote_state *rs = get_remote_state ();
13415
13416 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 13417 remote_check_symbols ();
dc8acb97
MS
13418}
13419
00bf0b85
SS
13420/* Pull all the tracepoints defined on the target and create local
13421 data structures representing them. We don't want to create real
13422 tracepoints yet, we don't want to mess up the user's existing
13423 collection. */
13424
13425static int
ab6617cc 13426remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 13427{
00bf0b85
SS
13428 struct remote_state *rs = get_remote_state ();
13429 char *p;
d5551862 13430
00bf0b85
SS
13431 /* Ask for a first packet of tracepoint definition. */
13432 putpkt ("qTfP");
13433 getpkt (&rs->buf, &rs->buf_size, 0);
13434 p = rs->buf;
13435 while (*p && *p != 'l')
d5551862 13436 {
00bf0b85
SS
13437 parse_tracepoint_definition (p, utpp);
13438 /* Ask for another packet of tracepoint definition. */
13439 putpkt ("qTsP");
13440 getpkt (&rs->buf, &rs->buf_size, 0);
13441 p = rs->buf;
d5551862 13442 }
00bf0b85 13443 return 0;
d5551862
SS
13444}
13445
00bf0b85 13446static int
181e3713
TT
13447remote_upload_trace_state_variables (struct target_ops *self,
13448 struct uploaded_tsv **utsvp)
d5551862 13449{
00bf0b85 13450 struct remote_state *rs = get_remote_state ();
d5551862 13451 char *p;
d5551862 13452
00bf0b85
SS
13453 /* Ask for a first packet of variable definition. */
13454 putpkt ("qTfV");
d5551862
SS
13455 getpkt (&rs->buf, &rs->buf_size, 0);
13456 p = rs->buf;
00bf0b85 13457 while (*p && *p != 'l')
d5551862 13458 {
00bf0b85
SS
13459 parse_tsv_definition (p, utsvp);
13460 /* Ask for another packet of variable definition. */
13461 putpkt ("qTsV");
d5551862
SS
13462 getpkt (&rs->buf, &rs->buf_size, 0);
13463 p = rs->buf;
13464 }
00bf0b85 13465 return 0;
d5551862
SS
13466}
13467
c1e36e3e
PA
13468/* The "set/show range-stepping" show hook. */
13469
13470static void
13471show_range_stepping (struct ui_file *file, int from_tty,
13472 struct cmd_list_element *c,
13473 const char *value)
13474{
13475 fprintf_filtered (file,
13476 _("Debugger's willingness to use range stepping "
13477 "is %s.\n"), value);
13478}
13479
13480/* The "set/show range-stepping" set hook. */
13481
13482static void
13483set_range_stepping (char *ignore_args, int from_tty,
13484 struct cmd_list_element *c)
13485{
5d93a237
TT
13486 struct remote_state *rs = get_remote_state ();
13487
c1e36e3e
PA
13488 /* Whene enabling, check whether range stepping is actually
13489 supported by the target, and warn if not. */
13490 if (use_range_stepping)
13491 {
5d93a237 13492 if (rs->remote_desc != NULL)
c1e36e3e 13493 {
4082afcc 13494 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
13495 remote_vcont_probe (rs);
13496
4082afcc 13497 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
13498 && rs->supports_vCont.r)
13499 return;
13500 }
13501
13502 warning (_("Range stepping is not supported by the current target"));
13503 }
13504}
13505
c906108c 13506void
fba45db2 13507_initialize_remote (void)
c906108c 13508{
9a7071a8 13509 struct cmd_list_element *cmd;
6f937416 13510 const char *cmd_name;
ea9c271d 13511
0f71a2f6 13512 /* architecture specific data */
2bc416ba 13513 remote_gdbarch_data_handle =
23860348 13514 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
13515 remote_g_packet_data_handle =
13516 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 13517
94585166
DB
13518 remote_pspace_data
13519 = register_program_space_data_with_cleanup (NULL,
13520 remote_pspace_data_cleanup);
13521
ea9c271d
DJ
13522 /* Initialize the per-target state. At the moment there is only one
13523 of these, not one per target. Only one target is active at a
cf792862
TT
13524 time. */
13525 remote_state = new_remote_state ();
ea9c271d 13526
c906108c
SS
13527 init_remote_ops ();
13528 add_target (&remote_ops);
13529
13530 init_extended_remote_ops ();
13531 add_target (&extended_remote_ops);
cce74817 13532
dc8acb97 13533 /* Hook into new objfile notification. */
06d3b283 13534 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
13535 /* We're no longer interested in notification events of an inferior
13536 when it exits. */
13537 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 13538
c906108c
SS
13539#if 0
13540 init_remote_threadtests ();
13541#endif
13542
722247f1 13543 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 13544 /* set/show remote ... */
d471ea57 13545
1bedd215 13546 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
13547Remote protocol specific variables\n\
13548Configure various remote-protocol specific variables such as\n\
1bedd215 13549the packets being used"),
cff3e48b 13550 &remote_set_cmdlist, "set remote ",
23860348 13551 0 /* allow-unknown */, &setlist);
1bedd215 13552 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
13553Remote protocol specific variables\n\
13554Configure various remote-protocol specific variables such as\n\
1bedd215 13555the packets being used"),
cff3e48b 13556 &remote_show_cmdlist, "show remote ",
23860348 13557 0 /* allow-unknown */, &showlist);
5a2468f5 13558
1a966eab
AC
13559 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13560Compare section data on target to the exec file.\n\
95cf3b38
DT
13561Argument is a single section name (default: all loaded sections).\n\
13562To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
13563 &cmdlist);
13564
1a966eab
AC
13565 add_cmd ("packet", class_maintenance, packet_command, _("\
13566Send an arbitrary packet to a remote target.\n\
c906108c
SS
13567 maintenance packet TEXT\n\
13568If GDB is talking to an inferior via the GDB serial protocol, then\n\
13569this command sends the string TEXT to the inferior, and displays the\n\
13570response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 13571terminating `#' character and checksum."),
c906108c
SS
13572 &maintenancelist);
13573
7915a72c
AC
13574 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13575Set whether to send break if interrupted."), _("\
13576Show whether to send break if interrupted."), _("\
13577If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 13578 set_remotebreak, show_remotebreak,
e707bbc2 13579 &setlist, &showlist);
9a7071a8
JB
13580 cmd_name = "remotebreak";
13581 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13582 deprecate_cmd (cmd, "set remote interrupt-sequence");
13583 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13584 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13585 deprecate_cmd (cmd, "show remote interrupt-sequence");
13586
13587 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
13588 interrupt_sequence_modes, &interrupt_sequence_mode,
13589 _("\
9a7071a8
JB
13590Set interrupt sequence to remote target."), _("\
13591Show interrupt sequence to remote target."), _("\
13592Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13593 NULL, show_interrupt_sequence,
13594 &remote_set_cmdlist,
13595 &remote_show_cmdlist);
13596
13597 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13598 &interrupt_on_connect, _("\
13599Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13600Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13601If set, interrupt sequence is sent to remote target."),
13602 NULL, NULL,
13603 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 13604
23860348 13605 /* Install commands for configuring memory read/write packets. */
11cf8741 13606
1a966eab
AC
13607 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13608Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 13609 &setlist);
1a966eab
AC
13610 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13611Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
13612 &showlist);
13613 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
13614 set_memory_write_packet_size, _("\
13615Set the maximum number of bytes per memory-write packet.\n\
13616Specify the number of bytes in a packet or 0 (zero) for the\n\
13617default packet size. The actual limit is further reduced\n\
13618dependent on the target. Specify ``fixed'' to disable the\n\
13619further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13620 &remote_set_cmdlist);
13621 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
13622 set_memory_read_packet_size, _("\
13623Set the maximum number of bytes per memory-read packet.\n\
13624Specify the number of bytes in a packet or 0 (zero) for the\n\
13625default packet size. The actual limit is further reduced\n\
13626dependent on the target. Specify ``fixed'' to disable the\n\
13627further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13628 &remote_set_cmdlist);
13629 add_cmd ("memory-write-packet-size", no_class,
13630 show_memory_write_packet_size,
1a966eab 13631 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
13632 &remote_show_cmdlist);
13633 add_cmd ("memory-read-packet-size", no_class,
13634 show_memory_read_packet_size,
1a966eab 13635 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 13636 &remote_show_cmdlist);
c906108c 13637
b3f42336 13638 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
13639 &remote_hw_watchpoint_limit, _("\
13640Set the maximum number of target hardware watchpoints."), _("\
13641Show the maximum number of target hardware watchpoints."), _("\
13642Specify a negative limit for unlimited."),
3e43a32a
MS
13643 NULL, NULL, /* FIXME: i18n: The maximum
13644 number of target hardware
13645 watchpoints is %s. */
b3f42336 13646 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
13647 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13648 &remote_hw_watchpoint_length_limit, _("\
13649Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13650Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13651Specify a negative limit for unlimited."),
13652 NULL, NULL, /* FIXME: i18n: The maximum
13653 length (in bytes) of a target
13654 hardware watchpoint is %s. */
13655 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 13656 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
13657 &remote_hw_breakpoint_limit, _("\
13658Set the maximum number of target hardware breakpoints."), _("\
13659Show the maximum number of target hardware breakpoints."), _("\
13660Specify a negative limit for unlimited."),
3e43a32a
MS
13661 NULL, NULL, /* FIXME: i18n: The maximum
13662 number of target hardware
13663 breakpoints is %s. */
b3f42336 13664 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 13665
1b493192
PA
13666 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13667 &remote_address_size, _("\
4d28ad1e
AC
13668Set the maximum size of the address (in bits) in a memory packet."), _("\
13669Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
13670 NULL,
13671 NULL, /* FIXME: i18n: */
13672 &setlist, &showlist);
c906108c 13673
ca4f7f8b
PA
13674 init_all_packet_configs ();
13675
444abaca 13676 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 13677 "X", "binary-download", 1);
0f71a2f6 13678
444abaca 13679 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 13680 "vCont", "verbose-resume", 0);
506fb367 13681
89be2091
DJ
13682 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13683 "QPassSignals", "pass-signals", 0);
13684
82075af2
JS
13685 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
13686 "QCatchSyscalls", "catch-syscalls", 0);
13687
9b224c5e
PA
13688 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13689 "QProgramSignals", "program-signals", 0);
13690
444abaca 13691 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 13692 "qSymbol", "symbol-lookup", 0);
dc8acb97 13693
444abaca 13694 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 13695 "P", "set-register", 1);
d471ea57 13696
444abaca 13697 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 13698 "p", "fetch-register", 1);
b96ec7ac 13699
444abaca 13700 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 13701 "Z0", "software-breakpoint", 0);
d471ea57 13702
444abaca 13703 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 13704 "Z1", "hardware-breakpoint", 0);
d471ea57 13705
444abaca 13706 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 13707 "Z2", "write-watchpoint", 0);
d471ea57 13708
444abaca 13709 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 13710 "Z3", "read-watchpoint", 0);
d471ea57 13711
444abaca 13712 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 13713 "Z4", "access-watchpoint", 0);
d471ea57 13714
0876f84a
DJ
13715 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13716 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 13717
c78fa86a
GB
13718 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13719 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13720
23181151
DJ
13721 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13722 "qXfer:features:read", "target-features", 0);
13723
cfa9d6d9
DJ
13724 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13725 "qXfer:libraries:read", "library-info", 0);
13726
2268b414
JK
13727 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13728 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13729
fd79ecee
DJ
13730 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13731 "qXfer:memory-map:read", "memory-map", 0);
13732
0e7f50da
UW
13733 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13734 "qXfer:spu:read", "read-spu-object", 0);
13735
13736 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13737 "qXfer:spu:write", "write-spu-object", 0);
13738
07e059b5
VP
13739 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13740 "qXfer:osdata:read", "osdata", 0);
13741
dc146f7c
VP
13742 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13743 "qXfer:threads:read", "threads", 0);
13744
4aa995e1
PA
13745 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13746 "qXfer:siginfo:read", "read-siginfo-object", 0);
13747
13748 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13749 "qXfer:siginfo:write", "write-siginfo-object", 0);
13750
b3b9301e
PA
13751 add_packet_config_cmd
13752 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 13753 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 13754
169081d0
TG
13755 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13756 "qXfer:uib:read", "unwind-info-block", 0);
13757
444abaca 13758 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 13759 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
13760 0);
13761
711e434b
PM
13762 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13763 "qGetTIBAddr", "get-thread-information-block-address",
13764 0);
13765
40ab02ce
MS
13766 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13767 "bc", "reverse-continue", 0);
13768
13769 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13770 "bs", "reverse-step", 0);
13771
be2a5f71
DJ
13772 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13773 "qSupported", "supported-packets", 0);
13774
08388c79
DE
13775 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13776 "qSearch:memory", "search-memory", 0);
13777
bd3eecc3
PA
13778 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13779 "qTStatus", "trace-status", 0);
13780
15a201c8
GB
13781 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13782 "vFile:setfs", "hostio-setfs", 0);
13783
a6b151f1
DJ
13784 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13785 "vFile:open", "hostio-open", 0);
13786
13787 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13788 "vFile:pread", "hostio-pread", 0);
13789
13790 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13791 "vFile:pwrite", "hostio-pwrite", 0);
13792
13793 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13794 "vFile:close", "hostio-close", 0);
13795
13796 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13797 "vFile:unlink", "hostio-unlink", 0);
13798
b9e7b9c3
UW
13799 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13800 "vFile:readlink", "hostio-readlink", 0);
13801
0a93529c
GB
13802 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13803 "vFile:fstat", "hostio-fstat", 0);
13804
2d717e4f
DJ
13805 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13806 "vAttach", "attach", 0);
13807
13808 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13809 "vRun", "run", 0);
13810
a6f3e723
SL
13811 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13812 "QStartNoAckMode", "noack", 0);
13813
82f73884
PA
13814 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13815 "vKill", "kill", 0);
13816
0b16c5cf
PA
13817 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13818 "qAttached", "query-attached", 0);
13819
782b2b07 13820 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
13821 "ConditionalTracepoints",
13822 "conditional-tracepoints", 0);
3788aec7
LM
13823
13824 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13825 "ConditionalBreakpoints",
13826 "conditional-breakpoints", 0);
13827
d3ce09f5
SS
13828 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13829 "BreakpointCommands",
13830 "breakpoint-commands", 0);
13831
7a697b8d
SS
13832 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13833 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 13834
409873ef
SS
13835 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13836 "TracepointSource", "TracepointSource", 0);
13837
d914c394
SS
13838 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13839 "QAllow", "allow", 0);
13840
0fb4aa4b
PA
13841 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13842 "StaticTracepoints", "static-tracepoints", 0);
13843
1e4d1764
YQ
13844 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13845 "InstallInTrace", "install-in-trace", 0);
13846
0fb4aa4b
PA
13847 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13848 "qXfer:statictrace:read", "read-sdata-object", 0);
13849
78d85199
YQ
13850 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13851 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13852
03583c20
UW
13853 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13854 "QDisableRandomization", "disable-randomization", 0);
13855
d1feda86
YQ
13856 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13857 "QAgent", "agent", 0);
13858
f6f899bf
HAQ
13859 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13860 "QTBuffer:size", "trace-buffer-size", 0);
13861
9accd112
MM
13862 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13863 "Qbtrace:off", "disable-btrace", 0);
13864
13865 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
13866 "Qbtrace:bts", "enable-btrace-bts", 0);
13867
13868 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13869 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
13870
13871 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13872 "qXfer:btrace", "read-btrace", 0);
13873
f4abbc16
MM
13874 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13875 "qXfer:btrace-conf", "read-btrace-conf", 0);
13876
d33501a5
MM
13877 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13878 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13879
73b8c1fd
PA
13880 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13881 "multiprocess-feature", "multiprocess-feature", 0);
13882
f7e6eed5
PA
13883 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13884 "swbreak-feature", "swbreak-feature", 0);
13885
13886 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13887 "hwbreak-feature", "hwbreak-feature", 0);
13888
89245bc0
DB
13889 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13890 "fork-event-feature", "fork-event-feature", 0);
13891
13892 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13893 "vfork-event-feature", "vfork-event-feature", 0);
13894
b20a6524
MM
13895 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13896 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13897
750ce8d1
YQ
13898 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13899 "vContSupported", "verbose-resume-supported", 0);
13900
94585166
DB
13901 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13902 "exec-event-feature", "exec-event-feature", 0);
13903
de979965
PA
13904 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13905 "vCtrlC", "ctrl-c", 0);
13906
65706a29
PA
13907 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
13908 "QThreadEvents", "thread-events", 0);
13909
f2faf941
PA
13910 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
13911 "N stop reply", "no-resumed-stop-reply", 0);
13912
0b736949
DB
13913 /* Assert that we've registered "set remote foo-packet" commands
13914 for all packet configs. */
ca4f7f8b
PA
13915 {
13916 int i;
13917
13918 for (i = 0; i < PACKET_MAX; i++)
13919 {
13920 /* Ideally all configs would have a command associated. Some
13921 still don't though. */
13922 int excepted;
13923
13924 switch (i)
13925 {
13926 case PACKET_QNonStop:
ca4f7f8b
PA
13927 case PACKET_EnableDisableTracepoints_feature:
13928 case PACKET_tracenz_feature:
13929 case PACKET_DisconnectedTracing_feature:
13930 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
13931 case PACKET_qCRC:
13932 /* Additions to this list need to be well justified:
13933 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
13934 excepted = 1;
13935 break;
13936 default:
13937 excepted = 0;
13938 break;
13939 }
13940
13941 /* This catches both forgetting to add a config command, and
13942 forgetting to remove a packet from the exception list. */
13943 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13944 }
13945 }
13946
37a105a1
DJ
13947 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13948 Z sub-packet has its own set and show commands, but users may
13949 have sets to this variable in their .gdbinit files (or in their
13950 documentation). */
e9e68a56 13951 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
13952 &remote_Z_packet_detect, _("\
13953Set use of remote protocol `Z' packets"), _("\
13954Show use of remote protocol `Z' packets "), _("\
3b64bf98 13955When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 13956packets."),
e9e68a56 13957 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
13958 show_remote_protocol_Z_packet_cmd,
13959 /* FIXME: i18n: Use of remote protocol
13960 `Z' packets is %s. */
e9e68a56 13961 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 13962
a6b151f1
DJ
13963 add_prefix_cmd ("remote", class_files, remote_command, _("\
13964Manipulate files on the remote system\n\
13965Transfer files to and from the remote target system."),
13966 &remote_cmdlist, "remote ",
13967 0 /* allow-unknown */, &cmdlist);
13968
13969 add_cmd ("put", class_files, remote_put_command,
13970 _("Copy a local file to the remote system."),
13971 &remote_cmdlist);
13972
13973 add_cmd ("get", class_files, remote_get_command,
13974 _("Copy a remote file to the local system."),
13975 &remote_cmdlist);
13976
13977 add_cmd ("delete", class_files, remote_delete_command,
13978 _("Delete a remote file."),
13979 &remote_cmdlist);
13980
2d717e4f 13981 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 13982 &remote_exec_file_var, _("\
2d717e4f 13983Set the remote pathname for \"run\""), _("\
94585166
DB
13984Show the remote pathname for \"run\""), NULL,
13985 set_remote_exec_file,
13986 show_remote_exec_file,
13987 &remote_set_cmdlist,
13988 &remote_show_cmdlist);
2d717e4f 13989
c1e36e3e
PA
13990 add_setshow_boolean_cmd ("range-stepping", class_run,
13991 &use_range_stepping, _("\
13992Enable or disable range stepping."), _("\
13993Show whether target-assisted range stepping is enabled."), _("\
13994If on, and the target supports it, when stepping a source line, GDB\n\
13995tells the target to step the corresponding range of addresses itself instead\n\
13996of issuing multiple single-steps. This speeds up source level\n\
13997stepping. If off, GDB always issues single-steps, even if range\n\
13998stepping is supported by the target. The default is on."),
13999 set_range_stepping,
14000 show_range_stepping,
14001 &setlist,
14002 &showlist);
14003
449092f6
CV
14004 /* Eventually initialize fileio. See fileio.c */
14005 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 14006
ba348170 14007 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 14008 special ptids with it set to != 0. */
ba348170
PA
14009 magic_null_ptid = ptid_build (42000, -1, 1);
14010 not_sent_ptid = ptid_build (42000, -2, 1);
14011 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
14012
14013 target_buf_size = 2048;
224c3ddb 14014 target_buf = (char *) xmalloc (target_buf_size);
c906108c 14015}
10760264 14016