Factor remote_read_bytes.
[deliverable/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
ecd75fc8 3 Copyright (C) 1988-2014 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"
0e9f083f 23#include <string.h>
c906108c
SS
24#include <ctype.h>
25#include <fcntl.h>
c906108c
SS
26#include "inferior.h"
27#include "bfd.h"
28#include "symfile.h"
60250e8b 29#include "exceptions.h"
c906108c 30#include "target.h"
c5aa993b 31/*#include "terminal.h" */
c906108c
SS
32#include "gdbcmd.h"
33#include "objfiles.h"
34#include "gdb-stabs.h"
35#include "gdbthread.h"
c2c6d25f 36#include "remote.h"
722247f1 37#include "remote-notif.h"
4e052eda 38#include "regcache.h"
fd0407d6 39#include "value.h"
1ff9c3d6 40#include "gdb_assert.h"
6867ae3e 41#include "observer.h"
a77053c2 42#include "solib.h"
37a105a1
DJ
43#include "cli/cli-decode.h"
44#include "cli/cli-setshow.h"
424163ea 45#include "target-descriptions.h"
a4453b7e 46#include "gdb_bfd.h"
614c279d 47#include "filestuff.h"
9c3d6531 48#include "rsp-low.h"
c906108c 49
9846de1b 50#include <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"
35b1e5cc 73
0df8b418 74/* Temp hacks for tracepoint encoding migration. */
35b1e5cc
SS
75static char *target_buf;
76static long target_buf_size;
35b1e5cc 77
6765f3e5
DJ
78/* The size to align memory write packets, when practical. The protocol
79 does not guarantee any alignment, and gdb will generate short
80 writes and unaligned writes, but even as a best-effort attempt this
81 can improve bulk transfers. For instance, if a write is misaligned
82 relative to the target's data bus, the stub may need to make an extra
83 round trip fetching data from the target. This doesn't make a
84 huge difference, but it's easy to do, so we try to be helpful.
85
86 The alignment chosen is arbitrary; usually data bus width is
87 important here, not the possibly larger cache line size. */
88enum { REMOTE_ALIGN_WRITES = 16 };
89
23860348 90/* Prototypes for local functions. */
934b9bac 91static void async_cleanup_sigint_signal_handler (void *dummy);
6d820c5c 92static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
74531fed 93static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
fee9eda9 94 int forever, int *is_notif);
6426a772 95
934b9bac
JK
96static void async_handle_remote_sigint (int);
97static void async_handle_remote_sigint_twice (int);
43ff13b4 98
a14ed312 99static void remote_files_info (struct target_ops *ignore);
c906108c 100
f32dbf8c
MM
101static void remote_prepare_to_store (struct target_ops *self,
102 struct regcache *regcache);
c906108c 103
a14ed312 104static void remote_open (char *name, int from_tty);
c906108c 105
a14ed312 106static void extended_remote_open (char *name, int from_tty);
c906108c 107
75c99385 108static void remote_open_1 (char *, int, struct target_ops *, int extended_p);
c906108c 109
de90e03d 110static void remote_close (struct target_ops *self);
c906108c 111
136d6dae 112static void remote_mourn (struct target_ops *ops);
c906108c 113
a14ed312 114static void extended_remote_restart (void);
c906108c 115
136d6dae 116static void extended_remote_mourn (struct target_ops *);
c906108c 117
a14ed312 118static void remote_mourn_1 (struct target_ops *);
c906108c 119
6d820c5c 120static void remote_send (char **buf, long *sizeof_buf_p);
c906108c 121
a14ed312 122static int readchar (int timeout);
c906108c 123
c33e31fd
PA
124static void remote_serial_write (const char *str, int len);
125
7d85a9c0 126static void remote_kill (struct target_ops *ops);
c906108c 127
6a109b6b 128static int remote_can_async_p (struct target_ops *);
75c99385 129
6a109b6b 130static int remote_is_async_p (struct target_ops *);
75c99385 131
6a109b6b
TT
132static void remote_async (struct target_ops *ops,
133 void (*callback) (enum inferior_event_type event_type,
134 void *context),
135 void *context);
75c99385 136
934b9bac 137static void sync_remote_interrupt_twice (int signo);
7a292a7a 138
a14ed312 139static void interrupt_query (void);
c906108c 140
79d7f229
PA
141static void set_general_thread (struct ptid ptid);
142static void set_continue_thread (struct ptid ptid);
c906108c 143
a14ed312 144static void get_offsets (void);
c906108c 145
6d820c5c
DJ
146static void skip_frame (void);
147
148static long read_frame (char **buf_p, long *sizeof_buf);
c906108c 149
a14ed312 150static int hexnumlen (ULONGEST num);
c906108c 151
a14ed312 152static void init_remote_ops (void);
c906108c 153
a14ed312 154static void init_extended_remote_ops (void);
c906108c 155
1eab8a48 156static void remote_stop (struct target_ops *self, ptid_t);
c906108c 157
a14ed312 158static int stubhex (int ch);
c906108c 159
a14ed312 160static int hexnumstr (char *, ULONGEST);
c906108c 161
a14ed312 162static int hexnumnstr (char *, ULONGEST, int);
2df3850c 163
a14ed312 164static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 165
a14ed312 166static void print_packet (char *);
c906108c 167
a14ed312 168static void compare_sections_command (char *, int);
c906108c 169
a14ed312 170static void packet_command (char *, int);
c906108c 171
a14ed312 172static int stub_unpack_int (char *buff, int fieldlength);
c906108c 173
39f77062 174static ptid_t remote_current_thread (ptid_t oldptid);
c906108c 175
a14ed312 176static void remote_find_new_threads (void);
c906108c 177
a14ed312 178static int putpkt_binary (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
d471ea57 186static void update_packet_config (struct packet_config *config);
5a2468f5 187
bb572ddd
DJ
188static void set_remote_protocol_packet_cmd (char *args, int from_tty,
189 struct cmd_list_element *c);
190
191static void show_remote_protocol_packet_cmd (struct ui_file *file,
192 int from_tty,
193 struct cmd_list_element *c,
194 const char *value);
195
82f73884
PA
196static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
197static ptid_t read_ptid (char *buf, char **obuf);
198
c378d69d 199static void remote_set_permissions (struct target_ops *self);
d914c394 200
d5551862 201struct remote_state;
8bd200f1
TT
202static int remote_get_trace_status (struct target_ops *self,
203 struct trace_status *ts);
d5551862 204
ab6617cc
TT
205static int remote_upload_tracepoints (struct target_ops *self,
206 struct uploaded_tp **utpp);
00bf0b85 207
181e3713
TT
208static int remote_upload_trace_state_variables (struct target_ops *self,
209 struct uploaded_tsv **utsvp);
00bf0b85 210
c8d104ad
PA
211static void remote_query_supported (void);
212
36d25514 213static void remote_check_symbols (void);
c8d104ad 214
a14ed312 215void _initialize_remote (void);
c906108c 216
74531fed 217struct stop_reply;
74531fed 218static void stop_reply_xfree (struct stop_reply *);
722247f1 219static void remote_parse_stop_reply (char *, struct stop_reply *);
74531fed 220static void push_stop_reply (struct stop_reply *);
bcc75809 221static void discard_pending_stop_replies_in_queue (struct remote_state *);
74531fed
PA
222static int peek_stop_reply (ptid_t ptid);
223
224static void remote_async_inferior_event_handler (gdb_client_data);
74531fed 225
e3594fd1 226static void remote_terminal_ours (struct target_ops *self);
d3fd5342 227
d962ef82
DJ
228static int remote_read_description_p (struct target_ops *target);
229
176a6961 230static void remote_console_output (char *msg);
dde08ee1 231
efcc2da7 232static int remote_supports_cond_breakpoints (struct target_ops *self);
b775012e 233
78eff0ec 234static int remote_can_run_breakpoint_commands (struct target_ops *self);
d3ce09f5 235
a6b151f1
DJ
236/* For "remote". */
237
238static struct cmd_list_element *remote_cmdlist;
239
bb572ddd
DJ
240/* For "set remote" and "show remote". */
241
242static struct cmd_list_element *remote_set_cmdlist;
243static struct cmd_list_element *remote_show_cmdlist;
244
d458bd84
PA
245/* Stub vCont actions support.
246
247 Each field is a boolean flag indicating whether the stub reports
248 support for the corresponding action. */
249
250struct vCont_action_support
251{
252 /* vCont;t */
253 int t;
c1e36e3e
PA
254
255 /* vCont;r */
256 int r;
d458bd84
PA
257};
258
c1e36e3e
PA
259/* Controls whether GDB is willing to use range stepping. */
260
261static int use_range_stepping = 1;
262
0d031856
TT
263#define OPAQUETHREADBYTES 8
264
265/* a 64 bit opaque identifier */
266typedef unsigned char threadref[OPAQUETHREADBYTES];
267
268/* About this many threadisds fit in a packet. */
269
270#define MAXTHREADLISTRESULTS 32
271
ea9c271d
DJ
272/* Description of the remote protocol state for the currently
273 connected target. This is per-target state, and independent of the
274 selected architecture. */
275
276struct remote_state
277{
278 /* A buffer to use for incoming packets, and its current size. The
279 buffer is grown dynamically for larger incoming packets.
280 Outgoing packets may also be constructed in this buffer.
281 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
282 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
283 packets. */
284 char *buf;
285 long buf_size;
be2a5f71 286
1e51243a
PA
287 /* True if we're going through initial connection setup (finding out
288 about the remote side's threads, relocating symbols, etc.). */
289 int starting_up;
290
be2a5f71
DJ
291 /* If we negotiated packet size explicitly (and thus can bypass
292 heuristics for the largest packet size that will not overflow
293 a buffer in the stub), this will be set to that packet size.
294 Otherwise zero, meaning to use the guessed size. */
295 long explicit_packet_size;
2d717e4f
DJ
296
297 /* remote_wait is normally called when the target is running and
298 waits for a stop reply packet. But sometimes we need to call it
299 when the target is already stopped. We can send a "?" packet
300 and have remote_wait read the response. Or, if we already have
301 the response, we can stash it in BUF and tell remote_wait to
302 skip calling getpkt. This flag is set when BUF contains a
303 stop reply packet and the target is not waiting. */
304 int cached_wait_status;
a6f3e723
SL
305
306 /* True, if in no ack mode. That is, neither GDB nor the stub will
307 expect acks from each other. The connection is assumed to be
308 reliable. */
309 int noack_mode;
82f73884
PA
310
311 /* True if we're connected in extended remote mode. */
312 int extended;
313
314 /* True if the stub reported support for multi-process
315 extensions. */
316 int multi_process_aware;
e24a49d8
PA
317
318 /* True if we resumed the target and we're waiting for the target to
319 stop. In the mean time, we can't start another command/query.
320 The remote server wouldn't be ready to process it, so we'd
321 timeout waiting for a reply that would never come and eventually
322 we'd close the connection. This can happen in asynchronous mode
323 because we allow GDB commands while the target is running. */
324 int waiting_for_stop_reply;
74531fed
PA
325
326 /* True if the stub reports support for non-stop mode. */
327 int non_stop_aware;
328
d458bd84
PA
329 /* The status of the stub support for the various vCont actions. */
330 struct vCont_action_support supports_vCont;
782b2b07
SS
331
332 /* True if the stub reports support for conditional tracepoints. */
333 int cond_tracepoints;
3a29589a 334
3788aec7
LM
335 /* True if the stub reports support for target-side breakpoint
336 conditions. */
337 int cond_breakpoints;
338
d3ce09f5
SS
339 /* True if the stub reports support for target-side breakpoint
340 commands. */
341 int breakpoint_commands;
342
7a697b8d
SS
343 /* True if the stub reports support for fast tracepoints. */
344 int fast_tracepoints;
345
0fb4aa4b
PA
346 /* True if the stub reports support for static tracepoints. */
347 int static_tracepoints;
348
1e4d1764
YQ
349 /* True if the stub reports support for installing tracepoint while
350 tracing. */
351 int install_in_trace;
352
d5551862
SS
353 /* True if the stub can continue running a trace while GDB is
354 disconnected. */
355 int disconnected_tracing;
356
d248b706
KY
357 /* True if the stub reports support for enabling and disabling
358 tracepoints while a trace experiment is running. */
359 int enable_disable_tracepoints;
360
3065dfb6
SS
361 /* True if the stub can collect strings using tracenz bytecode. */
362 int string_tracing;
363
ced63ec0
GB
364 /* True if the stub supports qXfer:libraries-svr4:read with a
365 non-empty annex. */
366 int augmented_libraries_svr4_read;
367
3a29589a
DJ
368 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
369 responded to that. */
370 int ctrlc_pending_p;
5d93a237
TT
371
372 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
373 remote_open knows that we don't have a file open when the program
374 starts. */
375 struct serial *remote_desc;
47f8a51d
TT
376
377 /* These are the threads which we last sent to the remote system. The
378 TID member will be -1 for all or -2 for not sent yet. */
379 ptid_t general_thread;
380 ptid_t continue_thread;
262e1174
TT
381
382 /* This is the traceframe which we last selected on the remote system.
383 It will be -1 if no traceframe is selected. */
384 int remote_traceframe_number;
747dc59d
TT
385
386 char *last_pass_packet;
5e4a05c4
TT
387
388 /* The last QProgramSignals packet sent to the target. We bypass
389 sending a new program signals list down to the target if the new
390 packet is exactly the same as the last we sent. IOW, we only let
391 the target know about program signals list changes. */
392 char *last_program_signals_packet;
b73be471
TT
393
394 enum gdb_signal last_sent_signal;
280ceea3
TT
395
396 int last_sent_step;
8e88304f
TT
397
398 char *finished_object;
399 char *finished_annex;
400 ULONGEST finished_offset;
b80fafe3
TT
401
402 /* Should we try the 'ThreadInfo' query packet?
403
404 This variable (NOT available to the user: auto-detect only!)
405 determines whether GDB will use the new, simpler "ThreadInfo"
406 query or the older, more complex syntax for thread queries.
407 This is an auto-detect variable (set to true at each connect,
408 and set to false when the target fails to recognize it). */
409 int use_threadinfo_query;
410 int use_threadextra_query;
88b496c3
TT
411
412 void (*async_client_callback) (enum inferior_event_type event_type,
413 void *context);
414 void *async_client_context;
ee154bee
TT
415
416 /* This is set to the data address of the access causing the target
417 to stop for a watchpoint. */
418 CORE_ADDR remote_watch_data_address;
419
420 /* This is non-zero if target stopped for a watchpoint. */
421 int remote_stopped_by_watchpoint_p;
0d031856
TT
422
423 threadref echo_nextthread;
424 threadref nextthread;
425 threadref resultthreadlist[MAXTHREADLISTRESULTS];
5965e028
YQ
426
427 /* The state of remote notification. */
428 struct remote_notif_state *notif_state;
ea9c271d
DJ
429};
430
dc146f7c
VP
431/* Private data that we'll store in (struct thread_info)->private. */
432struct private_thread_info
433{
434 char *extra;
435 int core;
436};
437
438static void
439free_private_thread_info (struct private_thread_info *info)
440{
441 xfree (info->extra);
442 xfree (info);
443}
444
82f73884
PA
445/* Returns true if the multi-process extensions are in effect. */
446static int
447remote_multi_process_p (struct remote_state *rs)
448{
901f9912 449 return rs->multi_process_aware;
82f73884
PA
450}
451
ea9c271d
DJ
452/* This data could be associated with a target, but we do not always
453 have access to the current target when we need it, so for now it is
454 static. This will be fine for as long as only one target is in use
455 at a time. */
cf792862 456static struct remote_state *remote_state;
ea9c271d
DJ
457
458static struct remote_state *
0b83947e 459get_remote_state_raw (void)
ea9c271d 460{
cf792862
TT
461 return remote_state;
462}
463
464/* Allocate a new struct remote_state with xmalloc, initialize it, and
465 return it. */
466
467static struct remote_state *
468new_remote_state (void)
469{
470 struct remote_state *result = XCNEW (struct remote_state);
471
472 /* The default buffer size is unimportant; it will be expanded
473 whenever a larger buffer is needed. */
474 result->buf_size = 400;
475 result->buf = xmalloc (result->buf_size);
262e1174 476 result->remote_traceframe_number = -1;
b73be471 477 result->last_sent_signal = GDB_SIGNAL_0;
cf792862
TT
478
479 return result;
ea9c271d
DJ
480}
481
482/* Description of the remote protocol for a given architecture. */
d01949b6 483
ad10f812
AC
484struct packet_reg
485{
486 long offset; /* Offset into G packet. */
487 long regnum; /* GDB's internal register number. */
488 LONGEST pnum; /* Remote protocol register number. */
b323314b 489 int in_g_packet; /* Always part of G packet. */
f5656ead 490 /* long size in bytes; == register_size (target_gdbarch (), regnum);
23860348 491 at present. */
f5656ead 492 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
c9f4d572 493 at present. */
ad10f812
AC
494};
495
ea9c271d 496struct remote_arch_state
d01949b6 497{
ad10f812
AC
498 /* Description of the remote protocol registers. */
499 long sizeof_g_packet;
b323314b
AC
500
501 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 502 (making an array gdbarch_num_regs in size). */
b323314b 503 struct packet_reg *regs;
ad10f812 504
d01949b6
AC
505 /* This is the size (in chars) of the first response to the ``g''
506 packet. It is used as a heuristic when determining the maximum
507 size of memory-read and memory-write packets. A target will
508 typically only reserve a buffer large enough to hold the ``g''
509 packet. The size does not include packet overhead (headers and
23860348 510 trailers). */
d01949b6
AC
511 long actual_register_packet_size;
512
513 /* This is the maximum size (in chars) of a non read/write packet.
23860348 514 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
515 long remote_packet_size;
516};
517
35b1e5cc
SS
518/* Utility: generate error from an incoming stub packet. */
519static void
520trace_error (char *buf)
521{
522 if (*buf++ != 'E')
523 return; /* not an error msg */
524 switch (*buf)
525 {
526 case '1': /* malformed packet error */
527 if (*++buf == '0') /* general case: */
528 error (_("remote.c: error in outgoing packet."));
529 else
530 error (_("remote.c: error in outgoing packet at field #%ld."),
531 strtol (buf, NULL, 16));
35b1e5cc
SS
532 default:
533 error (_("Target returns error code '%s'."), buf);
534 }
535}
536
537/* Utility: wait for reply from stub, while accepting "O" packets. */
538static char *
539remote_get_noisy_reply (char **buf_p,
540 long *sizeof_buf)
541{
542 do /* Loop on reply from remote stub. */
543 {
544 char *buf;
a744cf53 545
0df8b418 546 QUIT; /* Allow user to bail out with ^C. */
35b1e5cc
SS
547 getpkt (buf_p, sizeof_buf, 0);
548 buf = *buf_p;
ad91cd99 549 if (buf[0] == 'E')
35b1e5cc 550 trace_error (buf);
dde08ee1
PA
551 else if (strncmp (buf, "qRelocInsn:", strlen ("qRelocInsn:")) == 0)
552 {
553 ULONGEST ul;
554 CORE_ADDR from, to, org_to;
555 char *p, *pp;
556 int adjusted_size = 0;
557 volatile struct gdb_exception ex;
558
559 p = buf + strlen ("qRelocInsn:");
560 pp = unpack_varlen_hex (p, &ul);
561 if (*pp != ';')
cb91c06a 562 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
563 from = ul;
564
565 p = pp + 1;
a9cbf802 566 unpack_varlen_hex (p, &ul);
dde08ee1
PA
567 to = ul;
568
569 org_to = to;
570
571 TRY_CATCH (ex, RETURN_MASK_ALL)
572 {
f5656ead 573 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
dde08ee1
PA
574 }
575 if (ex.reason >= 0)
576 {
577 adjusted_size = to - org_to;
578
bba74b36 579 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
580 putpkt (buf);
581 }
582 else if (ex.reason < 0 && ex.error == MEMORY_ERROR)
583 {
584 /* Propagate memory errors silently back to the target.
585 The stub may have limited the range of addresses we
586 can write to, for example. */
587 putpkt ("E01");
588 }
589 else
590 {
591 /* Something unexpectedly bad happened. Be verbose so
592 we can tell what, and propagate the error back to the
593 stub, so it doesn't get stuck waiting for a
594 response. */
595 exception_fprintf (gdb_stderr, ex,
596 _("warning: relocating instruction: "));
597 putpkt ("E01");
598 }
599 }
ad91cd99 600 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
601 remote_console_output (buf + 1); /* 'O' message from stub */
602 else
0df8b418 603 return buf; /* Here's the actual reply. */
35b1e5cc
SS
604 }
605 while (1);
606}
3c3bea1c 607
d01949b6
AC
608/* Handle for retreving the remote protocol data from gdbarch. */
609static struct gdbarch_data *remote_gdbarch_data_handle;
610
ea9c271d
DJ
611static struct remote_arch_state *
612get_remote_arch_state (void)
d01949b6 613{
f5656ead 614 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
d01949b6
AC
615}
616
0b83947e
DJ
617/* Fetch the global remote target state. */
618
619static struct remote_state *
620get_remote_state (void)
621{
622 /* Make sure that the remote architecture state has been
623 initialized, because doing so might reallocate rs->buf. Any
624 function which calls getpkt also needs to be mindful of changes
625 to rs->buf, but this call limits the number of places which run
626 into trouble. */
627 get_remote_arch_state ();
628
629 return get_remote_state_raw ();
630}
631
74ca34ce
DJ
632static int
633compare_pnums (const void *lhs_, const void *rhs_)
634{
635 const struct packet_reg * const *lhs = lhs_;
636 const struct packet_reg * const *rhs = rhs_;
637
638 if ((*lhs)->pnum < (*rhs)->pnum)
639 return -1;
640 else if ((*lhs)->pnum == (*rhs)->pnum)
641 return 0;
642 else
643 return 1;
644}
645
c21236dc
PA
646static int
647map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 648{
74ca34ce 649 int regnum, num_remote_regs, offset;
74ca34ce 650 struct packet_reg **remote_regs;
ea9c271d 651
4a22f64d 652 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 653 {
c21236dc 654 struct packet_reg *r = &regs[regnum];
baef701f 655
4a22f64d 656 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
657 /* Do not try to fetch zero-sized (placeholder) registers. */
658 r->pnum = -1;
659 else
660 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
661
b323314b 662 r->regnum = regnum;
74ca34ce
DJ
663 }
664
665 /* Define the g/G packet format as the contents of each register
666 with a remote protocol number, in order of ascending protocol
667 number. */
668
4a22f64d 669 remote_regs = alloca (gdbarch_num_regs (gdbarch)
c21236dc 670 * sizeof (struct packet_reg *));
f57d151a 671 for (num_remote_regs = 0, regnum = 0;
4a22f64d 672 regnum < gdbarch_num_regs (gdbarch);
f57d151a 673 regnum++)
c21236dc
PA
674 if (regs[regnum].pnum != -1)
675 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 676
74ca34ce
DJ
677 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
678 compare_pnums);
679
680 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
681 {
682 remote_regs[regnum]->in_g_packet = 1;
683 remote_regs[regnum]->offset = offset;
4a22f64d 684 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
685 }
686
c21236dc
PA
687 return offset;
688}
689
690/* Given the architecture described by GDBARCH, return the remote
691 protocol register's number and the register's offset in the g/G
692 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
693 If the target does not have a mapping for REGNUM, return false,
694 otherwise, return true. */
695
696int
697remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
698 int *pnum, int *poffset)
699{
700 int sizeof_g_packet;
701 struct packet_reg *regs;
702 struct cleanup *old_chain;
703
704 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
705
706 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
707 old_chain = make_cleanup (xfree, regs);
708
709 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
710
711 *pnum = regs[regnum].pnum;
712 *poffset = regs[regnum].offset;
713
714 do_cleanups (old_chain);
715
716 return *pnum != -1;
717}
718
719static void *
720init_remote_state (struct gdbarch *gdbarch)
721{
722 struct remote_state *rs = get_remote_state_raw ();
723 struct remote_arch_state *rsa;
724
725 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
726
727 /* Use the architecture to build a regnum<->pnum table, which will be
728 1:1 unless a feature set specifies otherwise. */
729 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
730 gdbarch_num_regs (gdbarch),
731 struct packet_reg);
732
74ca34ce
DJ
733 /* Record the maximum possible size of the g packet - it may turn out
734 to be smaller. */
c21236dc 735 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 736
0df8b418 737 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
738 remote stubs have a hardwired buffer size of 400 bytes
739 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
740 as the maximum packet-size to ensure that the packet and an extra
741 NUL character can always fit in the buffer. This stops GDB
742 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
743 already a full buffer (As of 1999-12-04 that was most stubs). */
744 rsa->remote_packet_size = 400 - 1;
d01949b6 745
ea9c271d
DJ
746 /* This one is filled in when a ``g'' packet is received. */
747 rsa->actual_register_packet_size = 0;
748
749 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
750 default, adjust the size accordingly. Remember that each byte is
751 encoded as two characters. 32 is the overhead for the packet
752 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 753 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 754 little. */
ea9c271d
DJ
755 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
756 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 757
ea9c271d
DJ
758 /* Make sure that the packet buffer is plenty big enough for
759 this architecture. */
760 if (rs->buf_size < rsa->remote_packet_size)
761 {
762 rs->buf_size = 2 * rsa->remote_packet_size;
7fca722e 763 rs->buf = xrealloc (rs->buf, rs->buf_size);
ea9c271d 764 }
6d820c5c 765
ea9c271d
DJ
766 return rsa;
767}
768
769/* Return the current allowed size of a remote packet. This is
770 inferred from the current architecture, and should be used to
771 limit the length of outgoing packets. */
772static long
773get_remote_packet_size (void)
774{
be2a5f71 775 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
776 struct remote_arch_state *rsa = get_remote_arch_state ();
777
be2a5f71
DJ
778 if (rs->explicit_packet_size)
779 return rs->explicit_packet_size;
780
ea9c271d 781 return rsa->remote_packet_size;
d01949b6
AC
782}
783
ad10f812 784static struct packet_reg *
ea9c271d 785packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 786{
f5656ead 787 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
b323314b
AC
788 return NULL;
789 else
ad10f812 790 {
ea9c271d 791 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 792
b323314b
AC
793 gdb_assert (r->regnum == regnum);
794 return r;
ad10f812 795 }
ad10f812
AC
796}
797
798static struct packet_reg *
ea9c271d 799packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 800{
b323314b 801 int i;
a744cf53 802
f5656ead 803 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
ad10f812 804 {
ea9c271d 805 struct packet_reg *r = &rsa->regs[i];
a744cf53 806
b323314b
AC
807 if (r->pnum == pnum)
808 return r;
ad10f812
AC
809 }
810 return NULL;
d01949b6
AC
811}
812
c906108c
SS
813static struct target_ops remote_ops;
814
815static struct target_ops extended_remote_ops;
816
6426a772
JM
817/* FIXME: cagney/1999-09-23: Even though getpkt was called with
818 ``forever'' still use the normal timeout mechanism. This is
819 currently used by the ASYNC code to guarentee that target reads
820 during the initial connect always time-out. Once getpkt has been
821 modified to return a timeout indication and, in turn
822 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 823 this can go away. */
6426a772
JM
824static int wait_forever_enabled_p = 1;
825
9a7071a8
JB
826/* Allow the user to specify what sequence to send to the remote
827 when he requests a program interruption: Although ^C is usually
828 what remote systems expect (this is the default, here), it is
829 sometimes preferable to send a break. On other systems such
830 as the Linux kernel, a break followed by g, which is Magic SysRq g
831 is required in order to interrupt the execution. */
832const char interrupt_sequence_control_c[] = "Ctrl-C";
833const char interrupt_sequence_break[] = "BREAK";
834const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 835static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
836 {
837 interrupt_sequence_control_c,
838 interrupt_sequence_break,
839 interrupt_sequence_break_g,
840 NULL
841 };
842static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
843
844static void
845show_interrupt_sequence (struct ui_file *file, int from_tty,
846 struct cmd_list_element *c,
847 const char *value)
848{
849 if (interrupt_sequence_mode == interrupt_sequence_control_c)
850 fprintf_filtered (file,
851 _("Send the ASCII ETX character (Ctrl-c) "
852 "to the remote target to interrupt the "
853 "execution of the program.\n"));
854 else if (interrupt_sequence_mode == interrupt_sequence_break)
855 fprintf_filtered (file,
856 _("send a break signal to the remote target "
857 "to interrupt the execution of the program.\n"));
858 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
859 fprintf_filtered (file,
860 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
861 "the remote target to interrupt the execution "
862 "of Linux kernel.\n"));
863 else
864 internal_error (__FILE__, __LINE__,
865 _("Invalid value for interrupt_sequence_mode: %s."),
866 interrupt_sequence_mode);
867}
6426a772 868
9a7071a8
JB
869/* This boolean variable specifies whether interrupt_sequence is sent
870 to the remote target when gdb connects to it.
871 This is mostly needed when you debug the Linux kernel: The Linux kernel
872 expects BREAK g which is Magic SysRq g for connecting gdb. */
873static int interrupt_on_connect = 0;
c906108c 874
9a7071a8
JB
875/* This variable is used to implement the "set/show remotebreak" commands.
876 Since these commands are now deprecated in favor of "set/show remote
877 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
878static int remote_break;
879
9a7071a8
JB
880static void
881set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
882{
883 if (remote_break)
884 interrupt_sequence_mode = interrupt_sequence_break;
885 else
886 interrupt_sequence_mode = interrupt_sequence_control_c;
887}
888
889static void
890show_remotebreak (struct ui_file *file, int from_tty,
891 struct cmd_list_element *c,
892 const char *value)
893{
894}
895
c906108c
SS
896/* This variable sets the number of bits in an address that are to be
897 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 898 leading zeros, the entire address would be sent. This variable
c906108c
SS
899 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
900 initial implementation of remote.c restricted the address sent in
901 memory packets to ``host::sizeof long'' bytes - (typically 32
902 bits). Consequently, for 64 bit targets, the upper 32 bits of an
903 address was never sent. Since fixing this bug may cause a break in
904 some remote targets this variable is principly provided to
23860348 905 facilitate backward compatibility. */
c906108c 906
883b9c6c 907static unsigned int remote_address_size;
c906108c 908
75c99385
PA
909/* Temporary to track who currently owns the terminal. See
910 remote_terminal_* for more details. */
6426a772
JM
911
912static int remote_async_terminal_ours_p;
913
2d717e4f
DJ
914/* The executable file to use for "run" on the remote side. */
915
916static char *remote_exec_file = "";
917
11cf8741 918\f
11cf8741 919/* User configurable variables for the number of characters in a
ea9c271d
DJ
920 memory read/write packet. MIN (rsa->remote_packet_size,
921 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 922 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
923 (speed up transfers). The variables ``preferred_*'' (the user
924 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 925 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
926
927struct memory_packet_config
928{
929 char *name;
930 long size;
931 int fixed_p;
932};
933
934/* Compute the current size of a read/write packet. Since this makes
935 use of ``actual_register_packet_size'' the computation is dynamic. */
936
937static long
938get_memory_packet_size (struct memory_packet_config *config)
939{
d01949b6 940 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
941 struct remote_arch_state *rsa = get_remote_arch_state ();
942
11cf8741
JM
943 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
944 law?) that some hosts don't cope very well with large alloca()
945 calls. Eventually the alloca() code will be replaced by calls to
946 xmalloc() and make_cleanups() allowing this restriction to either
23860348 947 be lifted or removed. */
11cf8741
JM
948#ifndef MAX_REMOTE_PACKET_SIZE
949#define MAX_REMOTE_PACKET_SIZE 16384
950#endif
3de11b2e 951 /* NOTE: 20 ensures we can write at least one byte. */
11cf8741 952#ifndef MIN_REMOTE_PACKET_SIZE
3de11b2e 953#define MIN_REMOTE_PACKET_SIZE 20
11cf8741
JM
954#endif
955 long what_they_get;
956 if (config->fixed_p)
957 {
958 if (config->size <= 0)
959 what_they_get = MAX_REMOTE_PACKET_SIZE;
960 else
961 what_they_get = config->size;
962 }
963 else
964 {
ea9c271d 965 what_they_get = get_remote_packet_size ();
23860348 966 /* Limit the packet to the size specified by the user. */
11cf8741
JM
967 if (config->size > 0
968 && what_they_get > config->size)
969 what_they_get = config->size;
be2a5f71
DJ
970
971 /* Limit it to the size of the targets ``g'' response unless we have
972 permission from the stub to use a larger packet size. */
973 if (rs->explicit_packet_size == 0
974 && rsa->actual_register_packet_size > 0
975 && what_they_get > rsa->actual_register_packet_size)
976 what_they_get = rsa->actual_register_packet_size;
11cf8741
JM
977 }
978 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
979 what_they_get = MAX_REMOTE_PACKET_SIZE;
980 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
981 what_they_get = MIN_REMOTE_PACKET_SIZE;
6d820c5c
DJ
982
983 /* Make sure there is room in the global buffer for this packet
984 (including its trailing NUL byte). */
985 if (rs->buf_size < what_they_get + 1)
986 {
987 rs->buf_size = 2 * what_they_get;
988 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
989 }
990
11cf8741
JM
991 return what_they_get;
992}
993
0df8b418 994/* Update the size of a read/write packet. If they user wants
23860348 995 something really big then do a sanity check. */
11cf8741
JM
996
997static void
998set_memory_packet_size (char *args, struct memory_packet_config *config)
999{
1000 int fixed_p = config->fixed_p;
1001 long size = config->size;
a744cf53 1002
11cf8741 1003 if (args == NULL)
8a3fe4f8 1004 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1005 else if (strcmp (args, "hard") == 0
1006 || strcmp (args, "fixed") == 0)
1007 fixed_p = 1;
1008 else if (strcmp (args, "soft") == 0
1009 || strcmp (args, "limit") == 0)
1010 fixed_p = 0;
1011 else
1012 {
1013 char *end;
a744cf53 1014
11cf8741
JM
1015 size = strtoul (args, &end, 0);
1016 if (args == end)
8a3fe4f8 1017 error (_("Invalid %s (bad syntax)."), config->name);
11cf8741
JM
1018#if 0
1019 /* Instead of explicitly capping the size of a packet to
1020 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
1021 instead allowed to set the size to something arbitrarily
23860348 1022 large. */
11cf8741 1023 if (size > MAX_REMOTE_PACKET_SIZE)
8a3fe4f8 1024 error (_("Invalid %s (too large)."), config->name);
11cf8741
JM
1025#endif
1026 }
23860348 1027 /* Extra checks? */
11cf8741
JM
1028 if (fixed_p && !config->fixed_p)
1029 {
e2e0b3e5
AC
1030 if (! query (_("The target may not be able to correctly handle a %s\n"
1031 "of %ld bytes. Change the packet size? "),
11cf8741 1032 config->name, size))
8a3fe4f8 1033 error (_("Packet size not changed."));
11cf8741 1034 }
23860348 1035 /* Update the config. */
11cf8741
JM
1036 config->fixed_p = fixed_p;
1037 config->size = size;
1038}
1039
1040static void
1041show_memory_packet_size (struct memory_packet_config *config)
1042{
a3f17187 1043 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1044 if (config->fixed_p)
a3f17187 1045 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
1046 get_memory_packet_size (config));
1047 else
a3f17187 1048 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
1049 get_memory_packet_size (config));
1050}
1051
1052static struct memory_packet_config memory_write_packet_config =
1053{
1054 "memory-write-packet-size",
1055};
1056
1057static void
1058set_memory_write_packet_size (char *args, int from_tty)
1059{
1060 set_memory_packet_size (args, &memory_write_packet_config);
1061}
1062
1063static void
1064show_memory_write_packet_size (char *args, int from_tty)
1065{
1066 show_memory_packet_size (&memory_write_packet_config);
1067}
1068
1069static long
1070get_memory_write_packet_size (void)
1071{
1072 return get_memory_packet_size (&memory_write_packet_config);
1073}
1074
1075static struct memory_packet_config memory_read_packet_config =
1076{
1077 "memory-read-packet-size",
1078};
1079
1080static void
1081set_memory_read_packet_size (char *args, int from_tty)
1082{
1083 set_memory_packet_size (args, &memory_read_packet_config);
1084}
1085
1086static void
1087show_memory_read_packet_size (char *args, int from_tty)
1088{
1089 show_memory_packet_size (&memory_read_packet_config);
1090}
1091
1092static long
1093get_memory_read_packet_size (void)
1094{
1095 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1096
11cf8741
JM
1097 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1098 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1099 increased beyond this. */
1100 if (size > get_remote_packet_size ())
1101 size = get_remote_packet_size ();
11cf8741
JM
1102 return size;
1103}
1104
11cf8741 1105\f
5a2468f5 1106/* Generic configuration support for packets the stub optionally
0df8b418 1107 supports. Allows the user to specify the use of the packet as well
23860348 1108 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1109
1110enum packet_support
1111 {
1112 PACKET_SUPPORT_UNKNOWN = 0,
1113 PACKET_ENABLE,
1114 PACKET_DISABLE
1115 };
1116
5a2468f5
JM
1117struct packet_config
1118 {
bb572ddd
DJ
1119 const char *name;
1120 const char *title;
7f19b9a2 1121 enum auto_boolean detect;
5a2468f5
JM
1122 enum packet_support support;
1123 };
1124
d471ea57 1125/* Analyze a packet's return value and update the packet config
23860348 1126 accordingly. */
d471ea57
AC
1127
1128enum packet_result
1129{
1130 PACKET_ERROR,
1131 PACKET_OK,
1132 PACKET_UNKNOWN
1133};
1134
5a2468f5 1135static void
d471ea57 1136update_packet_config (struct packet_config *config)
5a2468f5 1137{
d471ea57
AC
1138 switch (config->detect)
1139 {
7f19b9a2 1140 case AUTO_BOOLEAN_TRUE:
d471ea57
AC
1141 config->support = PACKET_ENABLE;
1142 break;
7f19b9a2 1143 case AUTO_BOOLEAN_FALSE:
d471ea57
AC
1144 config->support = PACKET_DISABLE;
1145 break;
7f19b9a2 1146 case AUTO_BOOLEAN_AUTO:
d471ea57
AC
1147 config->support = PACKET_SUPPORT_UNKNOWN;
1148 break;
1149 }
5a2468f5
JM
1150}
1151
1152static void
fba45db2 1153show_packet_config_cmd (struct packet_config *config)
5a2468f5
JM
1154{
1155 char *support = "internal-error";
a744cf53 1156
5a2468f5
JM
1157 switch (config->support)
1158 {
1159 case PACKET_ENABLE:
1160 support = "enabled";
1161 break;
1162 case PACKET_DISABLE:
1163 support = "disabled";
1164 break;
1165 case PACKET_SUPPORT_UNKNOWN:
1166 support = "unknown";
1167 break;
1168 }
1169 switch (config->detect)
1170 {
7f19b9a2 1171 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1172 printf_filtered (_("Support for the `%s' packet "
1173 "is auto-detected, currently %s.\n"),
37a105a1 1174 config->name, support);
5a2468f5 1175 break;
7f19b9a2
AC
1176 case AUTO_BOOLEAN_TRUE:
1177 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1178 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1179 config->name, support);
8e248173 1180 break;
5a2468f5
JM
1181 }
1182}
1183
1184static void
bb572ddd
DJ
1185add_packet_config_cmd (struct packet_config *config, const char *name,
1186 const char *title, int legacy)
d471ea57 1187{
5a2468f5
JM
1188 char *set_doc;
1189 char *show_doc;
d471ea57 1190 char *cmd_name;
3ed07be4 1191
5a2468f5
JM
1192 config->name = name;
1193 config->title = title;
7f19b9a2 1194 config->detect = AUTO_BOOLEAN_AUTO;
8e248173 1195 config->support = PACKET_SUPPORT_UNKNOWN;
b435e160
AC
1196 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1197 name, title);
3e43a32a
MS
1198 show_doc = xstrprintf ("Show current use of remote "
1199 "protocol `%s' (%s) packet",
b435e160 1200 name, title);
d471ea57 1201 /* set/show TITLE-packet {auto,on,off} */
b435e160 1202 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1203 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1204 &config->detect, set_doc,
1205 show_doc, NULL, /* help_doc */
bb572ddd
DJ
1206 set_remote_protocol_packet_cmd,
1207 show_remote_protocol_packet_cmd,
1208 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1209 /* The command code copies the documentation strings. */
1210 xfree (set_doc);
1211 xfree (show_doc);
23860348 1212 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1213 if (legacy)
1214 {
1215 char *legacy_name;
a744cf53 1216
b435e160 1217 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1218 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1219 &remote_set_cmdlist);
d471ea57 1220 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1221 &remote_show_cmdlist);
d471ea57 1222 }
5a2468f5
JM
1223}
1224
d471ea57 1225static enum packet_result
a76d924d 1226packet_check_result (const char *buf)
5a2468f5 1227{
d471ea57 1228 if (buf[0] != '\0')
5a2468f5 1229 {
d471ea57 1230 /* The stub recognized the packet request. Check that the
23860348 1231 operation succeeded. */
a76d924d
DJ
1232 if (buf[0] == 'E'
1233 && isxdigit (buf[1]) && isxdigit (buf[2])
1234 && buf[3] == '\0')
1235 /* "Enn" - definitly an error. */
1236 return PACKET_ERROR;
1237
1238 /* Always treat "E." as an error. This will be used for
1239 more verbose error messages, such as E.memtypes. */
1240 if (buf[0] == 'E' && buf[1] == '.')
1241 return PACKET_ERROR;
1242
1243 /* The packet may or may not be OK. Just assume it is. */
1244 return PACKET_OK;
1245 }
1246 else
1247 /* The stub does not support the packet. */
1248 return PACKET_UNKNOWN;
1249}
1250
1251static enum packet_result
1252packet_ok (const char *buf, struct packet_config *config)
1253{
1254 enum packet_result result;
1255
1256 result = packet_check_result (buf);
1257 switch (result)
1258 {
1259 case PACKET_OK:
1260 case PACKET_ERROR:
1261 /* The stub recognized the packet request. */
d471ea57
AC
1262 switch (config->support)
1263 {
1264 case PACKET_SUPPORT_UNKNOWN:
1265 if (remote_debug)
1266 fprintf_unfiltered (gdb_stdlog,
1267 "Packet %s (%s) is supported\n",
1268 config->name, config->title);
1269 config->support = PACKET_ENABLE;
1270 break;
1271 case PACKET_DISABLE:
8e65ff28 1272 internal_error (__FILE__, __LINE__,
e2e0b3e5 1273 _("packet_ok: attempt to use a disabled packet"));
d471ea57
AC
1274 break;
1275 case PACKET_ENABLE:
1276 break;
1277 }
a76d924d
DJ
1278 break;
1279 case PACKET_UNKNOWN:
23860348 1280 /* The stub does not support the packet. */
d471ea57
AC
1281 switch (config->support)
1282 {
1283 case PACKET_ENABLE:
7f19b9a2 1284 if (config->detect == AUTO_BOOLEAN_AUTO)
d471ea57 1285 /* If the stub previously indicated that the packet was
23860348 1286 supported then there is a protocol error.. */
8a3fe4f8 1287 error (_("Protocol error: %s (%s) conflicting enabled responses."),
d471ea57
AC
1288 config->name, config->title);
1289 else
23860348 1290 /* The user set it wrong. */
8a3fe4f8 1291 error (_("Enabled packet %s (%s) not recognized by stub"),
d471ea57
AC
1292 config->name, config->title);
1293 break;
1294 case PACKET_SUPPORT_UNKNOWN:
1295 if (remote_debug)
1296 fprintf_unfiltered (gdb_stdlog,
1297 "Packet %s (%s) is NOT supported\n",
1298 config->name, config->title);
1299 config->support = PACKET_DISABLE;
1300 break;
1301 case PACKET_DISABLE:
1302 break;
1303 }
a76d924d 1304 break;
5a2468f5 1305 }
a76d924d
DJ
1306
1307 return result;
5a2468f5
JM
1308}
1309
444abaca
DJ
1310enum {
1311 PACKET_vCont = 0,
1312 PACKET_X,
1313 PACKET_qSymbol,
1314 PACKET_P,
1315 PACKET_p,
1316 PACKET_Z0,
1317 PACKET_Z1,
1318 PACKET_Z2,
1319 PACKET_Z3,
1320 PACKET_Z4,
a6b151f1
DJ
1321 PACKET_vFile_open,
1322 PACKET_vFile_pread,
1323 PACKET_vFile_pwrite,
1324 PACKET_vFile_close,
1325 PACKET_vFile_unlink,
b9e7b9c3 1326 PACKET_vFile_readlink,
0876f84a 1327 PACKET_qXfer_auxv,
23181151 1328 PACKET_qXfer_features,
cfa9d6d9 1329 PACKET_qXfer_libraries,
2268b414 1330 PACKET_qXfer_libraries_svr4,
fd79ecee 1331 PACKET_qXfer_memory_map,
0e7f50da
UW
1332 PACKET_qXfer_spu_read,
1333 PACKET_qXfer_spu_write,
07e059b5 1334 PACKET_qXfer_osdata,
dc146f7c 1335 PACKET_qXfer_threads,
0fb4aa4b 1336 PACKET_qXfer_statictrace_read,
b3b9301e 1337 PACKET_qXfer_traceframe_info,
169081d0 1338 PACKET_qXfer_uib,
711e434b 1339 PACKET_qGetTIBAddr,
444abaca 1340 PACKET_qGetTLSAddr,
be2a5f71 1341 PACKET_qSupported,
bd3eecc3 1342 PACKET_qTStatus,
89be2091 1343 PACKET_QPassSignals,
9b224c5e 1344 PACKET_QProgramSignals,
08388c79 1345 PACKET_qSearch_memory,
2d717e4f
DJ
1346 PACKET_vAttach,
1347 PACKET_vRun,
a6f3e723 1348 PACKET_QStartNoAckMode,
82f73884 1349 PACKET_vKill,
4aa995e1
PA
1350 PACKET_qXfer_siginfo_read,
1351 PACKET_qXfer_siginfo_write,
0b16c5cf 1352 PACKET_qAttached,
782b2b07 1353 PACKET_ConditionalTracepoints,
3788aec7 1354 PACKET_ConditionalBreakpoints,
d3ce09f5 1355 PACKET_BreakpointCommands,
7a697b8d 1356 PACKET_FastTracepoints,
0fb4aa4b 1357 PACKET_StaticTracepoints,
1e4d1764 1358 PACKET_InstallInTrace,
40ab02ce
MS
1359 PACKET_bc,
1360 PACKET_bs,
409873ef 1361 PACKET_TracepointSource,
d914c394 1362 PACKET_QAllow,
78d85199 1363 PACKET_qXfer_fdpic,
03583c20 1364 PACKET_QDisableRandomization,
d1feda86 1365 PACKET_QAgent,
f6f899bf 1366 PACKET_QTBuffer_size,
9accd112
MM
1367 PACKET_Qbtrace_off,
1368 PACKET_Qbtrace_bts,
1369 PACKET_qXfer_btrace,
444abaca
DJ
1370 PACKET_MAX
1371};
506fb367 1372
444abaca 1373static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97
MS
1374
1375static void
444abaca
DJ
1376set_remote_protocol_packet_cmd (char *args, int from_tty,
1377 struct cmd_list_element *c)
dc8acb97 1378{
444abaca 1379 struct packet_config *packet;
dc8acb97 1380
444abaca
DJ
1381 for (packet = remote_protocol_packets;
1382 packet < &remote_protocol_packets[PACKET_MAX];
1383 packet++)
1384 {
1385 if (&packet->detect == c->var)
1386 {
1387 update_packet_config (packet);
1388 return;
1389 }
1390 }
9b20d036 1391 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1392 c->name);
dc8acb97
MS
1393}
1394
5a2468f5 1395static void
444abaca
DJ
1396show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1397 struct cmd_list_element *c,
1398 const char *value)
5a2468f5 1399{
444abaca 1400 struct packet_config *packet;
5a2468f5 1401
444abaca
DJ
1402 for (packet = remote_protocol_packets;
1403 packet < &remote_protocol_packets[PACKET_MAX];
1404 packet++)
1405 {
1406 if (&packet->detect == c->var)
1407 {
1408 show_packet_config_cmd (packet);
1409 return;
1410 }
1411 }
9b20d036 1412 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1413 c->name);
5a2468f5
JM
1414}
1415
d471ea57
AC
1416/* Should we try one of the 'Z' requests? */
1417
1418enum Z_packet_type
1419{
1420 Z_PACKET_SOFTWARE_BP,
1421 Z_PACKET_HARDWARE_BP,
1422 Z_PACKET_WRITE_WP,
1423 Z_PACKET_READ_WP,
1424 Z_PACKET_ACCESS_WP,
1425 NR_Z_PACKET_TYPES
1426};
96baa820 1427
d471ea57 1428/* For compatibility with older distributions. Provide a ``set remote
23860348 1429 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1430
7f19b9a2 1431static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1432
1433static void
fba45db2
KB
1434set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1435 struct cmd_list_element *c)
96baa820 1436{
d471ea57 1437 int i;
a744cf53 1438
d471ea57
AC
1439 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1440 {
444abaca
DJ
1441 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1442 update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1443 }
96baa820
JM
1444}
1445
1446static void
08546159
AC
1447show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1448 struct cmd_list_element *c,
1449 const char *value)
96baa820 1450{
d471ea57 1451 int i;
a744cf53 1452
d471ea57
AC
1453 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1454 {
444abaca 1455 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1456 }
96baa820
JM
1457}
1458
23860348 1459/* Tokens for use by the asynchronous signal handlers for SIGINT. */
934b9bac
JK
1460static struct async_signal_handler *async_sigint_remote_twice_token;
1461static struct async_signal_handler *async_sigint_remote_token;
43ff13b4 1462
74531fed
PA
1463\f
1464/* Asynchronous signal handle registered as event loop source for
1465 when we have pending events ready to be passed to the core. */
1466
1467static struct async_event_handler *remote_async_inferior_event_token;
1468
c906108c
SS
1469\f
1470
79d7f229
PA
1471static ptid_t magic_null_ptid;
1472static ptid_t not_sent_ptid;
1473static ptid_t any_thread_ptid;
1474
0b16c5cf
PA
1475/* Find out if the stub attached to PID (and hence GDB should offer to
1476 detach instead of killing it when bailing out). */
1477
1478static int
1479remote_query_attached (int pid)
1480{
1481 struct remote_state *rs = get_remote_state ();
bba74b36 1482 size_t size = get_remote_packet_size ();
0b16c5cf
PA
1483
1484 if (remote_protocol_packets[PACKET_qAttached].support == PACKET_DISABLE)
1485 return 0;
1486
1487 if (remote_multi_process_p (rs))
bba74b36 1488 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1489 else
bba74b36 1490 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1491
1492 putpkt (rs->buf);
1493 getpkt (&rs->buf, &rs->buf_size, 0);
1494
1495 switch (packet_ok (rs->buf,
1554e9be 1496 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1497 {
1498 case PACKET_OK:
1499 if (strcmp (rs->buf, "1") == 0)
1500 return 1;
1501 break;
1502 case PACKET_ERROR:
1503 warning (_("Remote failure reply: %s"), rs->buf);
1504 break;
1505 case PACKET_UNKNOWN:
1506 break;
1507 }
1508
1509 return 0;
1510}
1511
49c62f2e
PA
1512/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1513 has been invented by GDB, instead of reported by the target. Since
1514 we can be connected to a remote system before before knowing about
1515 any inferior, mark the target with execution when we find the first
1516 inferior. If ATTACHED is 1, then we had just attached to this
1517 inferior. If it is 0, then we just created this inferior. If it
1518 is -1, then try querying the remote stub to find out if it had
1519 attached to the inferior or not. */
1941c569
PA
1520
1521static struct inferior *
49c62f2e 1522remote_add_inferior (int fake_pid_p, int pid, int attached)
1941c569 1523{
1941c569
PA
1524 struct inferior *inf;
1525
0b16c5cf
PA
1526 /* Check whether this process we're learning about is to be
1527 considered attached, or if is to be considered to have been
1528 spawned by the stub. */
1529 if (attached == -1)
1530 attached = remote_query_attached (pid);
1531
f5656ead 1532 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1533 {
1534 /* If the target shares code across all inferiors, then every
1535 attach adds a new inferior. */
1536 inf = add_inferior (pid);
1537
1538 /* ... and every inferior is bound to the same program space.
1539 However, each inferior may still have its own address
1540 space. */
1541 inf->aspace = maybe_new_address_space ();
1542 inf->pspace = current_program_space;
1543 }
1544 else
1545 {
1546 /* In the traditional debugging scenario, there's a 1-1 match
1547 between program/address spaces. We simply bind the inferior
1548 to the program space's address space. */
1549 inf = current_inferior ();
1550 inferior_appeared (inf, pid);
1551 }
1941c569 1552
0b16c5cf 1553 inf->attach_flag = attached;
49c62f2e 1554 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1555
1941c569
PA
1556 return inf;
1557}
1558
1559/* Add thread PTID to GDB's thread list. Tag it as executing/running
1560 according to RUNNING. */
1561
c906108c 1562static void
1941c569 1563remote_add_thread (ptid_t ptid, int running)
c906108c 1564{
b7ea362b
PA
1565 struct remote_state *rs = get_remote_state ();
1566
1567 /* GDB historically didn't pull threads in the initial connection
1568 setup. If the remote target doesn't even have a concept of
1569 threads (e.g., a bare-metal target), even if internally we
1570 consider that a single-threaded target, mentioning a new thread
1571 might be confusing to the user. Be silent then, preserving the
1572 age old behavior. */
1573 if (rs->starting_up)
1574 add_thread_silent (ptid);
1575 else
1576 add_thread (ptid);
1941c569
PA
1577
1578 set_executing (ptid, running);
1579 set_running (ptid, running);
1580}
1581
1582/* Come here when we learn about a thread id from the remote target.
1583 It may be the first time we hear about such thread, so take the
1584 opportunity to add it to GDB's thread list. In case this is the
1585 first time we're noticing its corresponding inferior, add it to
1586 GDB's inferior list as well. */
1587
1588static void
1589remote_notice_new_inferior (ptid_t currthread, int running)
1590{
c906108c
SS
1591 /* If this is a new thread, add it to GDB's thread list.
1592 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1593
1594 if (in_thread_list (currthread) && is_exited (currthread))
1595 {
1596 /* We're seeing an event on a thread id we knew had exited.
1597 This has to be a new thread reusing the old id. Add it. */
1941c569 1598 remote_add_thread (currthread, running);
82f73884
PA
1599 return;
1600 }
1601
79d7f229 1602 if (!in_thread_list (currthread))
c0a2216e 1603 {
1941c569 1604 struct inferior *inf = NULL;
bad34192 1605 int pid = ptid_get_pid (currthread);
1941c569 1606
bad34192
PA
1607 if (ptid_is_pid (inferior_ptid)
1608 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1609 {
1610 /* inferior_ptid has no thread member yet. This can happen
1611 with the vAttach -> remote_wait,"TAAthread:" path if the
1612 stub doesn't support qC. This is the first stop reported
1613 after an attach, so this is the main thread. Update the
1614 ptid in the thread list. */
bad34192
PA
1615 if (in_thread_list (pid_to_ptid (pid)))
1616 thread_change_ptid (inferior_ptid, currthread);
1617 else
1618 {
1619 remote_add_thread (currthread, running);
1620 inferior_ptid = currthread;
1621 }
dc146f7c 1622 return;
c0a2216e 1623 }
82f73884
PA
1624
1625 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1626 {
1627 /* inferior_ptid is not set yet. This can happen with the
1628 vRun -> remote_wait,"TAAthread:" path if the stub
1629 doesn't support qC. This is the first stop reported
1630 after an attach, so this is the main thread. Update the
1631 ptid in the thread list. */
dc146f7c 1632 thread_change_ptid (inferior_ptid, currthread);
82f73884 1633 return;
c0a2216e 1634 }
82f73884 1635
29c87f7f
PA
1636 /* When connecting to a target remote, or to a target
1637 extended-remote which already was debugging an inferior, we
1638 may not know about it yet. Add it before adding its child
1639 thread, so notifications are emitted in a sensible order. */
1640 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1641 {
1642 struct remote_state *rs = get_remote_state ();
1643 int fake_pid_p = !remote_multi_process_p (rs);
1644
1645 inf = remote_add_inferior (fake_pid_p,
1646 ptid_get_pid (currthread), -1);
1647 }
29c87f7f 1648
82f73884 1649 /* This is really a new thread. Add it. */
1941c569
PA
1650 remote_add_thread (currthread, running);
1651
1652 /* If we found a new inferior, let the common code do whatever
1653 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1654 breakpoints), unless we're just setting up an all-stop
1655 connection. */
1941c569 1656 if (inf != NULL)
b7ea362b
PA
1657 {
1658 struct remote_state *rs = get_remote_state ();
1659
1660 if (non_stop || !rs->starting_up)
1661 notice_new_inferior (currthread, running, 0);
1662 }
c0a2216e 1663 }
c906108c
SS
1664}
1665
dc146f7c
VP
1666/* Return the private thread data, creating it if necessary. */
1667
70221824 1668static struct private_thread_info *
dc146f7c
VP
1669demand_private_info (ptid_t ptid)
1670{
1671 struct thread_info *info = find_thread_ptid (ptid);
1672
1673 gdb_assert (info);
1674
1675 if (!info->private)
1676 {
1677 info->private = xmalloc (sizeof (*(info->private)));
1678 info->private_dtor = free_private_thread_info;
1679 info->private->core = -1;
1680 info->private->extra = 0;
1681 }
1682
1683 return info->private;
1684}
1685
74531fed
PA
1686/* Call this function as a result of
1687 1) A halt indication (T packet) containing a thread id
1688 2) A direct query of currthread
0df8b418 1689 3) Successful execution of set thread */
74531fed
PA
1690
1691static void
47f8a51d 1692record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1693{
47f8a51d 1694 rs->general_thread = currthread;
74531fed
PA
1695}
1696
89be2091
DJ
1697/* If 'QPassSignals' is supported, tell the remote stub what signals
1698 it can simply pass through to the inferior without reporting. */
1699
1700static void
94bedb42
TT
1701remote_pass_signals (struct target_ops *self,
1702 int numsigs, unsigned char *pass_signals)
89be2091
DJ
1703{
1704 if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1705 {
1706 char *pass_packet, *p;
89be2091 1707 int count = 0, i;
747dc59d 1708 struct remote_state *rs = get_remote_state ();
89be2091
DJ
1709
1710 gdb_assert (numsigs < 256);
1711 for (i = 0; i < numsigs; i++)
1712 {
2455069d 1713 if (pass_signals[i])
89be2091
DJ
1714 count++;
1715 }
1716 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1717 strcpy (pass_packet, "QPassSignals:");
1718 p = pass_packet + strlen (pass_packet);
1719 for (i = 0; i < numsigs; i++)
1720 {
2455069d 1721 if (pass_signals[i])
89be2091
DJ
1722 {
1723 if (i >= 16)
1724 *p++ = tohex (i >> 4);
1725 *p++ = tohex (i & 15);
1726 if (count)
1727 *p++ = ';';
1728 else
1729 break;
1730 count--;
1731 }
1732 }
1733 *p = 0;
747dc59d 1734 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 1735 {
89be2091
DJ
1736 putpkt (pass_packet);
1737 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1738 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
1739 if (rs->last_pass_packet)
1740 xfree (rs->last_pass_packet);
1741 rs->last_pass_packet = pass_packet;
89be2091
DJ
1742 }
1743 else
1744 xfree (pass_packet);
1745 }
1746}
1747
9b224c5e
PA
1748/* If 'QProgramSignals' is supported, tell the remote stub what
1749 signals it should pass through to the inferior when detaching. */
1750
1751static void
daf5e9b6
TT
1752remote_program_signals (struct target_ops *self,
1753 int numsigs, unsigned char *signals)
9b224c5e
PA
1754{
1755 if (remote_protocol_packets[PACKET_QProgramSignals].support != PACKET_DISABLE)
1756 {
1757 char *packet, *p;
1758 int count = 0, i;
5e4a05c4 1759 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
1760
1761 gdb_assert (numsigs < 256);
1762 for (i = 0; i < numsigs; i++)
1763 {
1764 if (signals[i])
1765 count++;
1766 }
1767 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1768 strcpy (packet, "QProgramSignals:");
1769 p = packet + strlen (packet);
1770 for (i = 0; i < numsigs; i++)
1771 {
1772 if (signal_pass_state (i))
1773 {
1774 if (i >= 16)
1775 *p++ = tohex (i >> 4);
1776 *p++ = tohex (i & 15);
1777 if (count)
1778 *p++ = ';';
1779 else
1780 break;
1781 count--;
1782 }
1783 }
1784 *p = 0;
5e4a05c4
TT
1785 if (!rs->last_program_signals_packet
1786 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 1787 {
9b224c5e
PA
1788 putpkt (packet);
1789 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1790 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
1791 xfree (rs->last_program_signals_packet);
1792 rs->last_program_signals_packet = packet;
9b224c5e
PA
1793 }
1794 else
1795 xfree (packet);
1796 }
1797}
1798
79d7f229
PA
1799/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1800 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1801 thread. If GEN is set, set the general thread, if not, then set
1802 the step/continue thread. */
c906108c 1803static void
79d7f229 1804set_thread (struct ptid ptid, int gen)
c906108c 1805{
d01949b6 1806 struct remote_state *rs = get_remote_state ();
47f8a51d 1807 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 1808 char *buf = rs->buf;
79d7f229 1809 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 1810
79d7f229 1811 if (ptid_equal (state, ptid))
c906108c
SS
1812 return;
1813
79d7f229
PA
1814 *buf++ = 'H';
1815 *buf++ = gen ? 'g' : 'c';
1816 if (ptid_equal (ptid, magic_null_ptid))
1817 xsnprintf (buf, endbuf - buf, "0");
1818 else if (ptid_equal (ptid, any_thread_ptid))
1819 xsnprintf (buf, endbuf - buf, "0");
1820 else if (ptid_equal (ptid, minus_one_ptid))
1821 xsnprintf (buf, endbuf - buf, "-1");
1822 else
82f73884 1823 write_ptid (buf, endbuf, ptid);
79d7f229 1824 putpkt (rs->buf);
6d820c5c 1825 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 1826 if (gen)
47f8a51d 1827 rs->general_thread = ptid;
c906108c 1828 else
47f8a51d 1829 rs->continue_thread = ptid;
c906108c 1830}
79d7f229
PA
1831
1832static void
1833set_general_thread (struct ptid ptid)
1834{
1835 set_thread (ptid, 1);
1836}
1837
1838static void
1839set_continue_thread (struct ptid ptid)
1840{
1841 set_thread (ptid, 0);
1842}
1843
3c9c4b83
PA
1844/* Change the remote current process. Which thread within the process
1845 ends up selected isn't important, as long as it is the same process
1846 as what INFERIOR_PTID points to.
1847
1848 This comes from that fact that there is no explicit notion of
1849 "selected process" in the protocol. The selected process for
1850 general operations is the process the selected general thread
1851 belongs to. */
1852
1853static void
1854set_general_process (void)
1855{
1856 struct remote_state *rs = get_remote_state ();
1857
1858 /* If the remote can't handle multiple processes, don't bother. */
901f9912 1859 if (!rs->extended || !remote_multi_process_p (rs))
3c9c4b83
PA
1860 return;
1861
1862 /* We only need to change the remote current thread if it's pointing
1863 at some other process. */
47f8a51d 1864 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
1865 set_general_thread (inferior_ptid);
1866}
1867
c906108c 1868\f
79d7f229
PA
1869/* Return nonzero if the thread PTID is still alive on the remote
1870 system. */
c906108c
SS
1871
1872static int
28439f5e 1873remote_thread_alive (struct target_ops *ops, ptid_t ptid)
c906108c 1874{
6d820c5c 1875 struct remote_state *rs = get_remote_state ();
82f73884 1876 char *p, *endp;
c906108c 1877
c0a2216e
PA
1878 if (ptid_equal (ptid, magic_null_ptid))
1879 /* The main thread is always alive. */
1880 return 1;
1881
ba348170 1882 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
1883 /* The main thread is always alive. This can happen after a
1884 vAttach, if the remote side doesn't support
1885 multi-threading. */
1886 return 1;
1887
82f73884
PA
1888 p = rs->buf;
1889 endp = rs->buf + get_remote_packet_size ();
1890
1891 *p++ = 'T';
1892 write_ptid (p, endp, ptid);
1893
2e9f7625 1894 putpkt (rs->buf);
6d820c5c 1895 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 1896 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
1897}
1898
1899/* About these extended threadlist and threadinfo packets. They are
1900 variable length packets but, the fields within them are often fixed
1901 length. They are redundent enough to send over UDP as is the
1902 remote protocol in general. There is a matching unit test module
1903 in libstub. */
1904
23860348 1905/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 1906 libstub protocol encoding, and remote.c. It is not particularly
23860348 1907 changable. */
cce74817
JM
1908
1909/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 1910 Plan to fix this. */
cce74817 1911
23860348 1912typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 1913
9d1f7ab2 1914/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 1915 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
1916
1917struct gdb_ext_thread_info
c5aa993b 1918 {
23860348 1919 threadref threadid; /* External form of thread reference. */
2bc416ba 1920 int active; /* Has state interesting to GDB?
23860348 1921 regs, stack. */
2bc416ba 1922 char display[256]; /* Brief state display, name,
cedea757 1923 blocked/suspended. */
23860348 1924 char shortname[32]; /* To be used to name threads. */
2bc416ba 1925 char more_display[256]; /* Long info, statistics, queue depth,
23860348 1926 whatever. */
c5aa993b 1927 };
cce74817
JM
1928
1929/* The volume of remote transfers can be limited by submitting
1930 a mask containing bits specifying the desired information.
1931 Use a union of these values as the 'selection' parameter to
0df8b418 1932 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
1933
1934#define TAG_THREADID 1
1935#define TAG_EXISTS 2
1936#define TAG_DISPLAY 4
1937#define TAG_THREADNAME 8
c5aa993b 1938#define TAG_MOREDISPLAY 16
cce74817 1939
23860348 1940#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 1941
a14ed312 1942static char *unpack_nibble (char *buf, int *val);
cce74817 1943
a14ed312 1944static char *unpack_byte (char *buf, int *value);
cce74817 1945
a14ed312 1946static char *pack_int (char *buf, int value);
cce74817 1947
a14ed312 1948static char *unpack_int (char *buf, int *value);
cce74817 1949
a14ed312 1950static char *unpack_string (char *src, char *dest, int length);
cce74817 1951
23860348 1952static char *pack_threadid (char *pkt, threadref *id);
cce74817 1953
23860348 1954static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 1955
23860348 1956void int_to_threadref (threadref *id, int value);
cce74817 1957
23860348 1958static int threadref_to_int (threadref *ref);
cce74817 1959
23860348 1960static void copy_threadref (threadref *dest, threadref *src);
cce74817 1961
23860348 1962static int threadmatch (threadref *dest, threadref *src);
cce74817 1963
2bc416ba 1964static char *pack_threadinfo_request (char *pkt, int mode,
23860348 1965 threadref *id);
cce74817 1966
a14ed312 1967static int remote_unpack_thread_info_response (char *pkt,
23860348 1968 threadref *expectedref,
a14ed312
KB
1969 struct gdb_ext_thread_info
1970 *info);
cce74817
JM
1971
1972
2bc416ba 1973static int remote_get_threadinfo (threadref *threadid,
23860348 1974 int fieldset, /*TAG mask */
a14ed312 1975 struct gdb_ext_thread_info *info);
cce74817 1976
a14ed312
KB
1977static char *pack_threadlist_request (char *pkt, int startflag,
1978 int threadcount,
23860348 1979 threadref *nextthread);
cce74817 1980
a14ed312
KB
1981static int parse_threadlist_response (char *pkt,
1982 int result_limit,
23860348 1983 threadref *original_echo,
2bc416ba 1984 threadref *resultlist,
23860348 1985 int *doneflag);
cce74817 1986
a14ed312 1987static int remote_get_threadlist (int startflag,
23860348 1988 threadref *nextthread,
a14ed312
KB
1989 int result_limit,
1990 int *done,
2bc416ba 1991 int *result_count,
23860348 1992 threadref *threadlist);
cce74817 1993
23860348 1994typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 1995
a14ed312
KB
1996static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1997 void *context, int looplimit);
cce74817 1998
23860348 1999static int remote_newthread_step (threadref *ref, void *context);
cce74817 2000
82f73884
PA
2001
2002/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2003 buffer we're allowed to write to. Returns
2004 BUF+CHARACTERS_WRITTEN. */
2005
2006static char *
2007write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2008{
2009 int pid, tid;
2010 struct remote_state *rs = get_remote_state ();
2011
2012 if (remote_multi_process_p (rs))
2013 {
2014 pid = ptid_get_pid (ptid);
2015 if (pid < 0)
2016 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2017 else
2018 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2019 }
ba348170 2020 tid = ptid_get_lwp (ptid);
82f73884
PA
2021 if (tid < 0)
2022 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2023 else
2024 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2025
2026 return buf;
2027}
2028
2029/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2030 passed the last parsed char. Returns null_ptid on error. */
2031
2032static ptid_t
2033read_ptid (char *buf, char **obuf)
2034{
2035 char *p = buf;
2036 char *pp;
2037 ULONGEST pid = 0, tid = 0;
82f73884
PA
2038
2039 if (*p == 'p')
2040 {
2041 /* Multi-process ptid. */
2042 pp = unpack_varlen_hex (p + 1, &pid);
2043 if (*pp != '.')
b37520b6 2044 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2045
2046 p = pp;
2047 pp = unpack_varlen_hex (p + 1, &tid);
2048 if (obuf)
2049 *obuf = pp;
ba348170 2050 return ptid_build (pid, tid, 0);
82f73884
PA
2051 }
2052
2053 /* No multi-process. Just a tid. */
2054 pp = unpack_varlen_hex (p, &tid);
2055
2056 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2057 what's in inferior_ptid, unless it's null at this point. If so,
2058 then since there's no way to know the pid of the reported
2059 threads, use the magic number. */
2060 if (ptid_equal (inferior_ptid, null_ptid))
2061 pid = ptid_get_pid (magic_null_ptid);
2062 else
2063 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2064
2065 if (obuf)
2066 *obuf = pp;
ba348170 2067 return ptid_build (pid, tid, 0);
82f73884
PA
2068}
2069
c906108c 2070static int
fba45db2 2071stubhex (int ch)
c906108c
SS
2072{
2073 if (ch >= 'a' && ch <= 'f')
2074 return ch - 'a' + 10;
2075 if (ch >= '0' && ch <= '9')
2076 return ch - '0';
2077 if (ch >= 'A' && ch <= 'F')
2078 return ch - 'A' + 10;
2079 return -1;
2080}
2081
2082static int
fba45db2 2083stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2084{
2085 int nibble;
2086 int retval = 0;
2087
2088 while (fieldlength)
2089 {
2090 nibble = stubhex (*buff++);
2091 retval |= nibble;
2092 fieldlength--;
2093 if (fieldlength)
2094 retval = retval << 4;
2095 }
2096 return retval;
2097}
2098
c906108c 2099static char *
fba45db2 2100unpack_nibble (char *buf, int *val)
c906108c 2101{
b7589f7d 2102 *val = fromhex (*buf++);
c906108c
SS
2103 return buf;
2104}
2105
c906108c 2106static char *
fba45db2 2107unpack_byte (char *buf, int *value)
c906108c
SS
2108{
2109 *value = stub_unpack_int (buf, 2);
2110 return buf + 2;
2111}
2112
2113static char *
fba45db2 2114pack_int (char *buf, int value)
c906108c
SS
2115{
2116 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2117 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2118 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2119 buf = pack_hex_byte (buf, (value & 0xff));
2120 return buf;
2121}
2122
2123static char *
fba45db2 2124unpack_int (char *buf, int *value)
c906108c
SS
2125{
2126 *value = stub_unpack_int (buf, 8);
2127 return buf + 8;
2128}
2129
23860348 2130#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2131static char *pack_string (char *pkt, char *string);
c906108c
SS
2132
2133static char *
fba45db2 2134pack_string (char *pkt, char *string)
c906108c
SS
2135{
2136 char ch;
2137 int len;
2138
2139 len = strlen (string);
2140 if (len > 200)
23860348 2141 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2142 pkt = pack_hex_byte (pkt, len);
2143 while (len-- > 0)
2144 {
2145 ch = *string++;
2146 if ((ch == '\0') || (ch == '#'))
23860348 2147 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2148 *pkt++ = ch;
2149 }
2150 return pkt;
2151}
2152#endif /* 0 (unused) */
2153
2154static char *
fba45db2 2155unpack_string (char *src, char *dest, int length)
c906108c
SS
2156{
2157 while (length--)
2158 *dest++ = *src++;
2159 *dest = '\0';
2160 return src;
2161}
2162
2163static char *
fba45db2 2164pack_threadid (char *pkt, threadref *id)
c906108c
SS
2165{
2166 char *limit;
2167 unsigned char *altid;
2168
2169 altid = (unsigned char *) id;
2170 limit = pkt + BUF_THREAD_ID_SIZE;
2171 while (pkt < limit)
2172 pkt = pack_hex_byte (pkt, *altid++);
2173 return pkt;
2174}
2175
2176
2177static char *
fba45db2 2178unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2179{
2180 char *altref;
2181 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2182 int x, y;
2183
2184 altref = (char *) id;
2185
2186 while (inbuf < limit)
2187 {
2188 x = stubhex (*inbuf++);
2189 y = stubhex (*inbuf++);
2190 *altref++ = (x << 4) | y;
2191 }
2192 return inbuf;
2193}
2194
2195/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2196 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2197 to use 64bit thread references internally. This is an adapter
2198 function. */
2199
2200void
fba45db2 2201int_to_threadref (threadref *id, int value)
c906108c
SS
2202{
2203 unsigned char *scan;
2204
2205 scan = (unsigned char *) id;
2206 {
2207 int i = 4;
2208 while (i--)
2209 *scan++ = 0;
2210 }
2211 *scan++ = (value >> 24) & 0xff;
2212 *scan++ = (value >> 16) & 0xff;
2213 *scan++ = (value >> 8) & 0xff;
2214 *scan++ = (value & 0xff);
2215}
2216
2217static int
fba45db2 2218threadref_to_int (threadref *ref)
c906108c
SS
2219{
2220 int i, value = 0;
2221 unsigned char *scan;
2222
cfd77fa1 2223 scan = *ref;
c906108c
SS
2224 scan += 4;
2225 i = 4;
2226 while (i-- > 0)
2227 value = (value << 8) | ((*scan++) & 0xff);
2228 return value;
2229}
2230
2231static void
fba45db2 2232copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2233{
2234 int i;
2235 unsigned char *csrc, *cdest;
2236
2237 csrc = (unsigned char *) src;
2238 cdest = (unsigned char *) dest;
2239 i = 8;
2240 while (i--)
2241 *cdest++ = *csrc++;
2242}
2243
2244static int
fba45db2 2245threadmatch (threadref *dest, threadref *src)
c906108c 2246{
23860348 2247 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2248#if 0
2249 unsigned char *srcp, *destp;
2250 int i, result;
2251 srcp = (char *) src;
2252 destp = (char *) dest;
2253
2254 result = 1;
2255 while (i-- > 0)
2256 result &= (*srcp++ == *destp++) ? 1 : 0;
2257 return result;
2258#endif
2259 return 1;
2260}
2261
2262/*
c5aa993b
JM
2263 threadid:1, # always request threadid
2264 context_exists:2,
2265 display:4,
2266 unique_name:8,
2267 more_display:16
2268 */
c906108c
SS
2269
2270/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2271
2272static char *
fba45db2 2273pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2274{
23860348
MS
2275 *pkt++ = 'q'; /* Info Query */
2276 *pkt++ = 'P'; /* process or thread info */
2277 pkt = pack_int (pkt, mode); /* mode */
c906108c 2278 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2279 *pkt = '\0'; /* terminate */
c906108c
SS
2280 return pkt;
2281}
2282
23860348 2283/* These values tag the fields in a thread info response packet. */
c906108c 2284/* Tagging the fields allows us to request specific fields and to
23860348 2285 add more fields as time goes by. */
c906108c 2286
23860348 2287#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2288#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2289 fetch registers and its stack? */
c5aa993b 2290#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2291#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2292#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2293 the process. */
c906108c
SS
2294
2295static int
fba45db2
KB
2296remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2297 struct gdb_ext_thread_info *info)
c906108c 2298{
d01949b6 2299 struct remote_state *rs = get_remote_state ();
c906108c 2300 int mask, length;
cfd77fa1 2301 int tag;
c906108c 2302 threadref ref;
6d820c5c 2303 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2304 int retval = 1;
2305
23860348 2306 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2307 info->active = 0;
2308 info->display[0] = '\0';
2309 info->shortname[0] = '\0';
2310 info->more_display[0] = '\0';
2311
23860348
MS
2312 /* Assume the characters indicating the packet type have been
2313 stripped. */
c906108c
SS
2314 pkt = unpack_int (pkt, &mask); /* arg mask */
2315 pkt = unpack_threadid (pkt, &ref);
2316
2317 if (mask == 0)
8a3fe4f8 2318 warning (_("Incomplete response to threadinfo request."));
c906108c 2319 if (!threadmatch (&ref, expectedref))
23860348 2320 { /* This is an answer to a different request. */
8a3fe4f8 2321 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2322 return 0;
2323 }
2324 copy_threadref (&info->threadid, &ref);
2325
23860348 2326 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2327
23860348
MS
2328 /* Packets are terminated with nulls. */
2329 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2330 {
2331 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2332 pkt = unpack_byte (pkt, &length); /* length */
2333 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2334 {
8a3fe4f8 2335 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2336 retval = 0;
2337 break;
2338 }
2339 if (tag == TAG_THREADID)
2340 {
2341 if (length != 16)
2342 {
8a3fe4f8 2343 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2344 retval = 0;
2345 break;
2346 }
2347 pkt = unpack_threadid (pkt, &ref);
2348 mask = mask & ~TAG_THREADID;
2349 continue;
2350 }
2351 if (tag == TAG_EXISTS)
2352 {
2353 info->active = stub_unpack_int (pkt, length);
2354 pkt += length;
2355 mask = mask & ~(TAG_EXISTS);
2356 if (length > 8)
2357 {
8a3fe4f8 2358 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2359 retval = 0;
2360 break;
2361 }
2362 continue;
2363 }
2364 if (tag == TAG_THREADNAME)
2365 {
2366 pkt = unpack_string (pkt, &info->shortname[0], length);
2367 mask = mask & ~TAG_THREADNAME;
2368 continue;
2369 }
2370 if (tag == TAG_DISPLAY)
2371 {
2372 pkt = unpack_string (pkt, &info->display[0], length);
2373 mask = mask & ~TAG_DISPLAY;
2374 continue;
2375 }
2376 if (tag == TAG_MOREDISPLAY)
2377 {
2378 pkt = unpack_string (pkt, &info->more_display[0], length);
2379 mask = mask & ~TAG_MOREDISPLAY;
2380 continue;
2381 }
8a3fe4f8 2382 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2383 break; /* Not a tag we know about. */
c906108c
SS
2384 }
2385 return retval;
2386}
2387
2388static int
fba45db2
KB
2389remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2390 struct gdb_ext_thread_info *info)
c906108c 2391{
d01949b6 2392 struct remote_state *rs = get_remote_state ();
c906108c 2393 int result;
c906108c 2394
2e9f7625
DJ
2395 pack_threadinfo_request (rs->buf, fieldset, threadid);
2396 putpkt (rs->buf);
6d820c5c 2397 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2398
2399 if (rs->buf[0] == '\0')
2400 return 0;
2401
2e9f7625 2402 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2403 threadid, info);
c906108c
SS
2404 return result;
2405}
2406
c906108c
SS
2407/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2408
2409static char *
fba45db2
KB
2410pack_threadlist_request (char *pkt, int startflag, int threadcount,
2411 threadref *nextthread)
c906108c
SS
2412{
2413 *pkt++ = 'q'; /* info query packet */
2414 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2415 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2416 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2417 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2418 *pkt = '\0';
2419 return pkt;
2420}
2421
2422/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2423
2424static int
fba45db2
KB
2425parse_threadlist_response (char *pkt, int result_limit,
2426 threadref *original_echo, threadref *resultlist,
2427 int *doneflag)
c906108c 2428{
d01949b6 2429 struct remote_state *rs = get_remote_state ();
c906108c
SS
2430 char *limit;
2431 int count, resultcount, done;
2432
2433 resultcount = 0;
2434 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2435 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2436 /* done parse past here */
c906108c
SS
2437 pkt = unpack_byte (pkt, &count); /* count field */
2438 pkt = unpack_nibble (pkt, &done);
2439 /* The first threadid is the argument threadid. */
2440 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2441 while ((count-- > 0) && (pkt < limit))
2442 {
2443 pkt = unpack_threadid (pkt, resultlist++);
2444 if (resultcount++ >= result_limit)
2445 break;
2446 }
2447 if (doneflag)
2448 *doneflag = done;
2449 return resultcount;
2450}
2451
2452static int
fba45db2
KB
2453remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2454 int *done, int *result_count, threadref *threadlist)
c906108c 2455{
d01949b6 2456 struct remote_state *rs = get_remote_state ();
c906108c
SS
2457 int result = 1;
2458
23860348 2459 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2460 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2461 >= get_remote_packet_size ())
ea9c271d 2462 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2463
6d820c5c
DJ
2464 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2465 putpkt (rs->buf);
2466 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2467
d8f2712d 2468 if (*rs->buf == '\0')
21bce120 2469 return 0;
d8f2712d
VP
2470 else
2471 *result_count =
0d031856
TT
2472 parse_threadlist_response (rs->buf + 2, result_limit,
2473 &rs->echo_nextthread, threadlist, done);
c906108c 2474
0d031856 2475 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2476 {
23860348
MS
2477 /* FIXME: This is a good reason to drop the packet. */
2478 /* Possably, there is a duplicate response. */
c906108c
SS
2479 /* Possabilities :
2480 retransmit immediatly - race conditions
2481 retransmit after timeout - yes
2482 exit
2483 wait for packet, then exit
2484 */
8a3fe4f8 2485 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2486 return 0; /* I choose simply exiting. */
c906108c
SS
2487 }
2488 if (*result_count <= 0)
2489 {
2490 if (*done != 1)
2491 {
8a3fe4f8 2492 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2493 result = 0;
2494 }
2495 return result; /* break; */
2496 }
2497 if (*result_count > result_limit)
2498 {
2499 *result_count = 0;
8a3fe4f8 2500 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2501 return 0;
2502 }
2503 return result;
2504}
2505
23860348
MS
2506/* This is the interface between remote and threads, remotes upper
2507 interface. */
c906108c
SS
2508
2509/* remote_find_new_threads retrieves the thread list and for each
2510 thread in the list, looks up the thread in GDB's internal list,
79d7f229 2511 adding the thread if it does not already exist. This involves
c906108c
SS
2512 getting partial thread lists from the remote target so, polling the
2513 quit_flag is required. */
2514
2515
c906108c 2516static int
fba45db2
KB
2517remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2518 int looplimit)
c906108c 2519{
0d031856 2520 struct remote_state *rs = get_remote_state ();
c906108c
SS
2521 int done, i, result_count;
2522 int startflag = 1;
2523 int result = 1;
2524 int loopcount = 0;
c906108c
SS
2525
2526 done = 0;
2527 while (!done)
2528 {
2529 if (loopcount++ > looplimit)
2530 {
2531 result = 0;
8a3fe4f8 2532 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2533 break;
2534 }
0d031856
TT
2535 if (!remote_get_threadlist (startflag, &rs->nextthread,
2536 MAXTHREADLISTRESULTS,
2537 &done, &result_count, rs->resultthreadlist))
c906108c
SS
2538 {
2539 result = 0;
2540 break;
2541 }
23860348 2542 /* Clear for later iterations. */
c906108c
SS
2543 startflag = 0;
2544 /* Setup to resume next batch of thread references, set nextthread. */
2545 if (result_count >= 1)
0d031856
TT
2546 copy_threadref (&rs->nextthread,
2547 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2548 i = 0;
2549 while (result_count--)
0d031856 2550 if (!(result = (*stepfunction) (&rs->resultthreadlist[i++], context)))
c906108c
SS
2551 break;
2552 }
2553 return result;
2554}
2555
2556static int
fba45db2 2557remote_newthread_step (threadref *ref, void *context)
c906108c 2558{
79d7f229 2559 int pid = ptid_get_pid (inferior_ptid);
ba348170 2560 ptid_t ptid = ptid_build (pid, threadref_to_int (ref), 0);
39f77062
KB
2561
2562 if (!in_thread_list (ptid))
2563 add_thread (ptid);
c906108c
SS
2564 return 1; /* continue iterator */
2565}
2566
2567#define CRAZY_MAX_THREADS 1000
2568
39f77062
KB
2569static ptid_t
2570remote_current_thread (ptid_t oldpid)
c906108c 2571{
d01949b6 2572 struct remote_state *rs = get_remote_state ();
c906108c
SS
2573
2574 putpkt ("qC");
6d820c5c 2575 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2576 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
82f73884 2577 return read_ptid (&rs->buf[2], NULL);
c906108c
SS
2578 else
2579 return oldpid;
2580}
2581
802188a7
RM
2582/* Find new threads for info threads command.
2583 * Original version, using John Metzler's thread protocol.
9d1f7ab2 2584 */
cce74817
JM
2585
2586static void
fba45db2 2587remote_find_new_threads (void)
c906108c 2588{
c5aa993b
JM
2589 remote_threadlist_iterator (remote_newthread_step, 0,
2590 CRAZY_MAX_THREADS);
c906108c
SS
2591}
2592
dc146f7c
VP
2593#if defined(HAVE_LIBEXPAT)
2594
2595typedef struct thread_item
2596{
2597 ptid_t ptid;
2598 char *extra;
2599 int core;
2600} thread_item_t;
2601DEF_VEC_O(thread_item_t);
2602
2603struct threads_parsing_context
2604{
2605 VEC (thread_item_t) *items;
2606};
2607
2608static void
2609start_thread (struct gdb_xml_parser *parser,
2610 const struct gdb_xml_element *element,
2611 void *user_data, VEC(gdb_xml_value_s) *attributes)
2612{
2613 struct threads_parsing_context *data = user_data;
2614
2615 struct thread_item item;
2616 char *id;
3d2c1d41 2617 struct gdb_xml_value *attr;
dc146f7c 2618
3d2c1d41 2619 id = xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
2620 item.ptid = read_ptid (id, NULL);
2621
3d2c1d41
PA
2622 attr = xml_find_attribute (attributes, "core");
2623 if (attr != NULL)
2624 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
2625 else
2626 item.core = -1;
2627
2628 item.extra = 0;
2629
2630 VEC_safe_push (thread_item_t, data->items, &item);
2631}
2632
2633static void
2634end_thread (struct gdb_xml_parser *parser,
2635 const struct gdb_xml_element *element,
2636 void *user_data, const char *body_text)
2637{
2638 struct threads_parsing_context *data = user_data;
2639
2640 if (body_text && *body_text)
2ae2a0b7 2641 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
2642}
2643
2644const struct gdb_xml_attribute thread_attributes[] = {
2645 { "id", GDB_XML_AF_NONE, NULL, NULL },
2646 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2647 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2648};
2649
2650const struct gdb_xml_element thread_children[] = {
2651 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2652};
2653
2654const struct gdb_xml_element threads_children[] = {
2655 { "thread", thread_attributes, thread_children,
2656 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2657 start_thread, end_thread },
2658 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2659};
2660
2661const struct gdb_xml_element threads_elements[] = {
2662 { "threads", NULL, threads_children,
2663 GDB_XML_EF_NONE, NULL, NULL },
2664 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2665};
2666
02357a4a
PA
2667/* Discard the contents of the constructed thread info context. */
2668
2669static void
2670clear_threads_parsing_context (void *p)
2671{
2672 struct threads_parsing_context *context = p;
2673 int i;
2674 struct thread_item *item;
2675
2676 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2677 xfree (item->extra);
2678
2679 VEC_free (thread_item_t, context->items);
2680}
2681
dc146f7c
VP
2682#endif
2683
9d1f7ab2
MS
2684/*
2685 * Find all threads for info threads command.
2686 * Uses new thread protocol contributed by Cisco.
2687 * Falls back and attempts to use the older method (above)
2688 * if the target doesn't respond to the new method.
2689 */
2690
0f71a2f6 2691static void
28439f5e 2692remote_threads_info (struct target_ops *ops)
0f71a2f6 2693{
d01949b6 2694 struct remote_state *rs = get_remote_state ();
085dd6e6 2695 char *bufp;
79d7f229 2696 ptid_t new_thread;
0f71a2f6 2697
5d93a237 2698 if (rs->remote_desc == 0) /* paranoia */
8a3fe4f8 2699 error (_("Command can only be used when connected to the remote target."));
0f71a2f6 2700
dc146f7c
VP
2701#if defined(HAVE_LIBEXPAT)
2702 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2703 {
2704 char *xml = target_read_stralloc (&current_target,
2705 TARGET_OBJECT_THREADS, NULL);
2706
2707 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 2708
dc146f7c
VP
2709 if (xml && *xml)
2710 {
dc146f7c 2711 struct threads_parsing_context context;
dc146f7c 2712
efc0eabd
PA
2713 context.items = NULL;
2714 make_cleanup (clear_threads_parsing_context, &context);
dc146f7c 2715
efc0eabd
PA
2716 if (gdb_xml_parse_quick (_("threads"), "threads.dtd",
2717 threads_elements, xml, &context) == 0)
dc146f7c
VP
2718 {
2719 int i;
2720 struct thread_item *item;
2721
3e43a32a
MS
2722 for (i = 0;
2723 VEC_iterate (thread_item_t, context.items, i, item);
2724 ++i)
dc146f7c
VP
2725 {
2726 if (!ptid_equal (item->ptid, null_ptid))
2727 {
2728 struct private_thread_info *info;
2729 /* In non-stop mode, we assume new found threads
2730 are running until proven otherwise with a
2731 stop reply. In all-stop, we can only get
2732 here if all threads are stopped. */
2733 int running = non_stop ? 1 : 0;
2734
2735 remote_notice_new_inferior (item->ptid, running);
2736
2737 info = demand_private_info (item->ptid);
2738 info->core = item->core;
2739 info->extra = item->extra;
02357a4a 2740 item->extra = NULL;
dc146f7c 2741 }
dc146f7c
VP
2742 }
2743 }
dc146f7c
VP
2744 }
2745
2746 do_cleanups (back_to);
2747 return;
2748 }
2749#endif
2750
b80fafe3 2751 if (rs->use_threadinfo_query)
9d1f7ab2
MS
2752 {
2753 putpkt ("qfThreadInfo");
6d820c5c 2754 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2755 bufp = rs->buf;
9d1f7ab2 2756 if (bufp[0] != '\0') /* q packet recognized */
802188a7 2757 {
44d594fd
PA
2758 struct cleanup *old_chain;
2759 char *saved_reply;
2760
2761 /* remote_notice_new_inferior (in the loop below) may make
2762 new RSP calls, which clobber rs->buf. Work with a
2763 copy. */
2764 bufp = saved_reply = xstrdup (rs->buf);
2765 old_chain = make_cleanup (free_current_contents, &saved_reply);
2766
9d1f7ab2
MS
2767 while (*bufp++ == 'm') /* reply contains one or more TID */
2768 {
2769 do
2770 {
82f73884 2771 new_thread = read_ptid (bufp, &bufp);
1941c569 2772 if (!ptid_equal (new_thread, null_ptid))
82f73884 2773 {
74531fed 2774 /* In non-stop mode, we assume new found threads
1941c569 2775 are running until proven otherwise with a
74531fed
PA
2776 stop reply. In all-stop, we can only get
2777 here if all threads are stopped. */
1941c569
PA
2778 int running = non_stop ? 1 : 0;
2779
2780 remote_notice_new_inferior (new_thread, running);
82f73884 2781 }
9d1f7ab2
MS
2782 }
2783 while (*bufp++ == ','); /* comma-separated list */
44d594fd 2784 free_current_contents (&saved_reply);
9d1f7ab2 2785 putpkt ("qsThreadInfo");
6d820c5c 2786 getpkt (&rs->buf, &rs->buf_size, 0);
44d594fd 2787 bufp = saved_reply = xstrdup (rs->buf);
9d1f7ab2 2788 }
44d594fd 2789 do_cleanups (old_chain);
9d1f7ab2
MS
2790 return; /* done */
2791 }
2792 }
2793
74531fed
PA
2794 /* Only qfThreadInfo is supported in non-stop mode. */
2795 if (non_stop)
2796 return;
2797
23860348 2798 /* Else fall back to old method based on jmetzler protocol. */
b80fafe3 2799 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
2800 remote_find_new_threads ();
2801 return;
2802}
2803
802188a7 2804/*
9d1f7ab2
MS
2805 * Collect a descriptive string about the given thread.
2806 * The target may say anything it wants to about the thread
2807 * (typically info about its blocked / runnable state, name, etc.).
2808 * This string will appear in the info threads display.
802188a7 2809 *
9d1f7ab2
MS
2810 * Optional: targets are not required to implement this function.
2811 */
2812
2813static char *
c15906d8 2814remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 2815{
d01949b6 2816 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
2817 int result;
2818 int set;
2819 threadref id;
2820 struct gdb_ext_thread_info threadinfo;
23860348 2821 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
2822 int n = 0; /* position in display_buf */
2823
5d93a237 2824 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 2825 internal_error (__FILE__, __LINE__,
e2e0b3e5 2826 _("remote_threads_extra_info"));
9d1f7ab2 2827
60e569b9 2828 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 2829 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
2830 /* This is the main thread which was added by GDB. The remote
2831 server doesn't know about it. */
2832 return NULL;
2833
dc146f7c
VP
2834 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2835 {
2836 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 2837
dc146f7c
VP
2838 if (info && info->private)
2839 return info->private->extra;
2840 else
2841 return NULL;
2842 }
2843
b80fafe3 2844 if (rs->use_threadextra_query)
9d1f7ab2 2845 {
82f73884
PA
2846 char *b = rs->buf;
2847 char *endb = rs->buf + get_remote_packet_size ();
2848
2849 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2850 b += strlen (b);
2851 write_ptid (b, endb, tp->ptid);
2852
2e9f7625 2853 putpkt (rs->buf);
6d820c5c 2854 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2855 if (rs->buf[0] != 0)
9d1f7ab2 2856 {
2e9f7625
DJ
2857 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2858 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 2859 display_buf [result] = '\0';
9d1f7ab2
MS
2860 return display_buf;
2861 }
0f71a2f6 2862 }
9d1f7ab2
MS
2863
2864 /* If the above query fails, fall back to the old method. */
b80fafe3 2865 rs->use_threadextra_query = 0;
9d1f7ab2
MS
2866 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2867 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 2868 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
2869 if (remote_get_threadinfo (&id, set, &threadinfo))
2870 if (threadinfo.active)
0f71a2f6 2871 {
9d1f7ab2 2872 if (*threadinfo.shortname)
2bc416ba 2873 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 2874 " Name: %s,", threadinfo.shortname);
9d1f7ab2 2875 if (*threadinfo.display)
2bc416ba 2876 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 2877 " State: %s,", threadinfo.display);
9d1f7ab2 2878 if (*threadinfo.more_display)
2bc416ba 2879 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 2880 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
2881
2882 if (n > 0)
c5aa993b 2883 {
23860348 2884 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
2885 if (',' == display_buf[n-1])
2886 display_buf[n-1] = ' ';
2887 return display_buf;
c5aa993b 2888 }
0f71a2f6 2889 }
9d1f7ab2 2890 return NULL;
0f71a2f6 2891}
c906108c 2892\f
c5aa993b 2893
0fb4aa4b 2894static int
61fc905d 2895remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
2896 struct static_tracepoint_marker *marker)
2897{
2898 struct remote_state *rs = get_remote_state ();
2899 char *p = rs->buf;
2900
bba74b36 2901 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
2902 p += strlen (p);
2903 p += hexnumstr (p, addr);
2904 putpkt (rs->buf);
2905 getpkt (&rs->buf, &rs->buf_size, 0);
2906 p = rs->buf;
2907
2908 if (*p == 'E')
2909 error (_("Remote failure reply: %s"), p);
2910
2911 if (*p++ == 'm')
2912 {
2913 parse_static_tracepoint_marker_definition (p, &p, marker);
2914 return 1;
2915 }
2916
2917 return 0;
2918}
2919
0fb4aa4b 2920static VEC(static_tracepoint_marker_p) *
c686c57f
TT
2921remote_static_tracepoint_markers_by_strid (struct target_ops *self,
2922 const char *strid)
0fb4aa4b
PA
2923{
2924 struct remote_state *rs = get_remote_state ();
2925 VEC(static_tracepoint_marker_p) *markers = NULL;
2926 struct static_tracepoint_marker *marker = NULL;
2927 struct cleanup *old_chain;
2928 char *p;
2929
2930 /* Ask for a first packet of static tracepoint marker
2931 definition. */
2932 putpkt ("qTfSTM");
2933 getpkt (&rs->buf, &rs->buf_size, 0);
2934 p = rs->buf;
2935 if (*p == 'E')
2936 error (_("Remote failure reply: %s"), p);
2937
2938 old_chain = make_cleanup (free_current_marker, &marker);
2939
2940 while (*p++ == 'm')
2941 {
2942 if (marker == NULL)
2943 marker = XCNEW (struct static_tracepoint_marker);
2944
2945 do
2946 {
2947 parse_static_tracepoint_marker_definition (p, &p, marker);
2948
2949 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
2950 {
2951 VEC_safe_push (static_tracepoint_marker_p,
2952 markers, marker);
2953 marker = NULL;
2954 }
2955 else
2956 {
2957 release_static_tracepoint_marker (marker);
2958 memset (marker, 0, sizeof (*marker));
2959 }
2960 }
2961 while (*p++ == ','); /* comma-separated list */
2962 /* Ask for another packet of static tracepoint definition. */
2963 putpkt ("qTsSTM");
2964 getpkt (&rs->buf, &rs->buf_size, 0);
2965 p = rs->buf;
2966 }
2967
2968 do_cleanups (old_chain);
2969 return markers;
2970}
2971
2972\f
10760264
JB
2973/* Implement the to_get_ada_task_ptid function for the remote targets. */
2974
2975static ptid_t
1e6b91a4 2976remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 2977{
ba348170 2978 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
2979}
2980\f
2981
24b06219 2982/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
2983
2984static void
fba45db2 2985extended_remote_restart (void)
c906108c 2986{
d01949b6 2987 struct remote_state *rs = get_remote_state ();
c906108c
SS
2988
2989 /* Send the restart command; for reasons I don't understand the
2990 remote side really expects a number after the "R". */
ea9c271d 2991 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 2992 putpkt (rs->buf);
c906108c 2993
ad9a8f3f 2994 remote_fileio_reset ();
c906108c
SS
2995}
2996\f
2997/* Clean up connection to a remote debugger. */
2998
c906108c 2999static void
de90e03d 3000remote_close (struct target_ops *self)
c906108c 3001{
5d93a237
TT
3002 struct remote_state *rs = get_remote_state ();
3003
3004 if (rs->remote_desc == NULL)
d3fd5342
PA
3005 return; /* already closed */
3006
3007 /* Make sure we leave stdin registered in the event loop, and we
3008 don't leave the async SIGINT signal handler installed. */
e3594fd1 3009 remote_terminal_ours (self);
ce5ce7ed 3010
5d93a237
TT
3011 serial_close (rs->remote_desc);
3012 rs->remote_desc = NULL;
ce5ce7ed
PA
3013
3014 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3015 of all the inferiors and their threads we were controlling.
3016 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3017 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3018 inferior_ptid = null_ptid;
f67fd822 3019 discard_all_inferiors ();
ce5ce7ed 3020
f48ff2a7
YQ
3021 /* We are closing the remote target, so we should discard
3022 everything of this target. */
bcc75809 3023 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3024
3025 if (remote_async_inferior_event_token)
3026 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3027
5965e028 3028 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3029
3030 trace_reset_local_state ();
c906108c
SS
3031}
3032
23860348 3033/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3034
3035static void
fba45db2 3036get_offsets (void)
c906108c 3037{
d01949b6 3038 struct remote_state *rs = get_remote_state ();
2e9f7625 3039 char *buf;
085dd6e6 3040 char *ptr;
31d99776
DJ
3041 int lose, num_segments = 0, do_sections, do_segments;
3042 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3043 struct section_offsets *offs;
31d99776
DJ
3044 struct symfile_segment_data *data;
3045
3046 if (symfile_objfile == NULL)
3047 return;
c906108c
SS
3048
3049 putpkt ("qOffsets");
6d820c5c 3050 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3051 buf = rs->buf;
c906108c
SS
3052
3053 if (buf[0] == '\000')
3054 return; /* Return silently. Stub doesn't support
23860348 3055 this command. */
c906108c
SS
3056 if (buf[0] == 'E')
3057 {
8a3fe4f8 3058 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3059 return;
3060 }
3061
3062 /* Pick up each field in turn. This used to be done with scanf, but
3063 scanf will make trouble if CORE_ADDR size doesn't match
3064 conversion directives correctly. The following code will work
3065 with any size of CORE_ADDR. */
3066 text_addr = data_addr = bss_addr = 0;
3067 ptr = buf;
3068 lose = 0;
3069
3070 if (strncmp (ptr, "Text=", 5) == 0)
3071 {
3072 ptr += 5;
3073 /* Don't use strtol, could lose on big values. */
3074 while (*ptr && *ptr != ';')
3075 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3076
31d99776
DJ
3077 if (strncmp (ptr, ";Data=", 6) == 0)
3078 {
3079 ptr += 6;
3080 while (*ptr && *ptr != ';')
3081 data_addr = (data_addr << 4) + fromhex (*ptr++);
3082 }
3083 else
3084 lose = 1;
3085
3086 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
3087 {
3088 ptr += 5;
3089 while (*ptr && *ptr != ';')
3090 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3091
31d99776
DJ
3092 if (bss_addr != data_addr)
3093 warning (_("Target reported unsupported offsets: %s"), buf);
3094 }
3095 else
3096 lose = 1;
3097 }
3098 else if (strncmp (ptr, "TextSeg=", 8) == 0)
c906108c 3099 {
31d99776
DJ
3100 ptr += 8;
3101 /* Don't use strtol, could lose on big values. */
c906108c 3102 while (*ptr && *ptr != ';')
31d99776
DJ
3103 text_addr = (text_addr << 4) + fromhex (*ptr++);
3104 num_segments = 1;
3105
3106 if (strncmp (ptr, ";DataSeg=", 9) == 0)
3107 {
3108 ptr += 9;
3109 while (*ptr && *ptr != ';')
3110 data_addr = (data_addr << 4) + fromhex (*ptr++);
3111 num_segments++;
3112 }
c906108c
SS
3113 }
3114 else
3115 lose = 1;
3116
3117 if (lose)
8a3fe4f8 3118 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3119 else if (*ptr != '\0')
3120 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3121
802188a7 3122 offs = ((struct section_offsets *)
a39a16c4 3123 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3124 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3125 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3126
31d99776
DJ
3127 data = get_symfile_segment_data (symfile_objfile->obfd);
3128 do_segments = (data != NULL);
3129 do_sections = num_segments == 0;
c906108c 3130
28c32713 3131 if (num_segments > 0)
31d99776 3132 {
31d99776
DJ
3133 segments[0] = text_addr;
3134 segments[1] = data_addr;
3135 }
28c32713
JB
3136 /* If we have two segments, we can still try to relocate everything
3137 by assuming that the .text and .data offsets apply to the whole
3138 text and data segments. Convert the offsets given in the packet
3139 to base addresses for symfile_map_offsets_to_segments. */
3140 else if (data && data->num_segments == 2)
3141 {
3142 segments[0] = data->segment_bases[0] + text_addr;
3143 segments[1] = data->segment_bases[1] + data_addr;
3144 num_segments = 2;
3145 }
8d385431
DJ
3146 /* If the object file has only one segment, assume that it is text
3147 rather than data; main programs with no writable data are rare,
3148 but programs with no code are useless. Of course the code might
3149 have ended up in the data segment... to detect that we would need
3150 the permissions here. */
3151 else if (data && data->num_segments == 1)
3152 {
3153 segments[0] = data->segment_bases[0] + text_addr;
3154 num_segments = 1;
3155 }
28c32713
JB
3156 /* There's no way to relocate by segment. */
3157 else
3158 do_segments = 0;
31d99776
DJ
3159
3160 if (do_segments)
3161 {
3162 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3163 offs, num_segments, segments);
3164
3165 if (ret == 0 && !do_sections)
3e43a32a
MS
3166 error (_("Can not handle qOffsets TextSeg "
3167 "response with this symbol file"));
31d99776
DJ
3168
3169 if (ret > 0)
3170 do_sections = 0;
3171 }
c906108c 3172
9ef895d6
DJ
3173 if (data)
3174 free_symfile_segment_data (data);
31d99776
DJ
3175
3176 if (do_sections)
3177 {
3178 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3179
3e43a32a
MS
3180 /* This is a temporary kludge to force data and bss to use the
3181 same offsets because that's what nlmconv does now. The real
3182 solution requires changes to the stub and remote.c that I
3183 don't have time to do right now. */
31d99776
DJ
3184
3185 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3186 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3187 }
c906108c
SS
3188
3189 objfile_relocate (symfile_objfile, offs);
3190}
3191
74531fed
PA
3192/* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3193 threads we know are stopped already. This is used during the
3194 initial remote connection in non-stop mode --- threads that are
3195 reported as already being stopped are left stopped. */
3196
3197static int
3198set_stop_requested_callback (struct thread_info *thread, void *data)
3199{
3200 /* If we have a stop reply for this thread, it must be stopped. */
3201 if (peek_stop_reply (thread->ptid))
3202 set_stop_requested (thread->ptid, 1);
3203
3204 return 0;
3205}
3206
9a7071a8
JB
3207/* Send interrupt_sequence to remote target. */
3208static void
eeae04df 3209send_interrupt_sequence (void)
9a7071a8 3210{
5d93a237
TT
3211 struct remote_state *rs = get_remote_state ();
3212
9a7071a8 3213 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3214 remote_serial_write ("\x03", 1);
9a7071a8 3215 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3216 serial_send_break (rs->remote_desc);
9a7071a8
JB
3217 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3218 {
5d93a237 3219 serial_send_break (rs->remote_desc);
c33e31fd 3220 remote_serial_write ("g", 1);
9a7071a8
JB
3221 }
3222 else
3223 internal_error (__FILE__, __LINE__,
3224 _("Invalid value for interrupt_sequence_mode: %s."),
3225 interrupt_sequence_mode);
3226}
3227
3405876a
PA
3228
3229/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3230 and extract the PTID. Returns NULL_PTID if not found. */
3231
3232static ptid_t
3233stop_reply_extract_thread (char *stop_reply)
3234{
3235 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3236 {
3237 char *p;
3238
3239 /* Txx r:val ; r:val (...) */
3240 p = &stop_reply[3];
3241
3242 /* Look for "register" named "thread". */
3243 while (*p != '\0')
3244 {
3245 char *p1;
3246
3247 p1 = strchr (p, ':');
3248 if (p1 == NULL)
3249 return null_ptid;
3250
3251 if (strncmp (p, "thread", p1 - p) == 0)
3252 return read_ptid (++p1, &p);
3253
3254 p1 = strchr (p, ';');
3255 if (p1 == NULL)
3256 return null_ptid;
3257 p1++;
3258
3259 p = p1;
3260 }
3261 }
3262
3263 return null_ptid;
3264}
3265
b7ea362b
PA
3266/* Determine the remote side's current thread. If we have a stop
3267 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3268 "thread" register we can extract the current thread from. If not,
3269 ask the remote which is the current thread with qC. The former
3270 method avoids a roundtrip. */
3271
3272static ptid_t
3273get_current_thread (char *wait_status)
3274{
3275 ptid_t ptid;
3276
3277 /* Note we don't use remote_parse_stop_reply as that makes use of
3278 the target architecture, which we haven't yet fully determined at
3279 this point. */
3280 if (wait_status != NULL)
3281 ptid = stop_reply_extract_thread (wait_status);
3282 if (ptid_equal (ptid, null_ptid))
3283 ptid = remote_current_thread (inferior_ptid);
3284
3285 return ptid;
3286}
3287
49c62f2e
PA
3288/* Query the remote target for which is the current thread/process,
3289 add it to our tables, and update INFERIOR_PTID. The caller is
3290 responsible for setting the state such that the remote end is ready
3405876a
PA
3291 to return the current thread.
3292
3293 This function is called after handling the '?' or 'vRun' packets,
3294 whose response is a stop reply from which we can also try
3295 extracting the thread. If the target doesn't support the explicit
3296 qC query, we infer the current thread from that stop reply, passed
3297 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3298
3299static void
3405876a 3300add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3301{
3302 struct remote_state *rs = get_remote_state ();
3303 int fake_pid_p = 0;
3405876a 3304 ptid_t ptid = null_ptid;
49c62f2e
PA
3305
3306 inferior_ptid = null_ptid;
3307
b7ea362b
PA
3308 /* Now, if we have thread information, update inferior_ptid. */
3309 ptid = get_current_thread (wait_status);
3405876a 3310
49c62f2e
PA
3311 if (!ptid_equal (ptid, null_ptid))
3312 {
3313 if (!remote_multi_process_p (rs))
3314 fake_pid_p = 1;
3315
3316 inferior_ptid = ptid;
3317 }
3318 else
3319 {
3320 /* Without this, some commands which require an active target
3321 (such as kill) won't work. This variable serves (at least)
3322 double duty as both the pid of the target process (if it has
3323 such), and as a flag indicating that a target is active. */
3324 inferior_ptid = magic_null_ptid;
3325 fake_pid_p = 1;
3326 }
3327
3328 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1);
3329
3330 /* Add the main thread. */
3331 add_thread_silent (inferior_ptid);
3332}
3333
9cbc821d 3334static void
04bd08de 3335remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 3336{
c8d104ad
PA
3337 struct remote_state *rs = get_remote_state ();
3338 struct packet_config *noack_config;
2d717e4f 3339 char *wait_status = NULL;
8621d6a9 3340
23860348 3341 immediate_quit++; /* Allow user to interrupt it. */
522002f9 3342 QUIT;
c906108c 3343
9a7071a8
JB
3344 if (interrupt_on_connect)
3345 send_interrupt_sequence ();
3346
57e12211 3347 /* Ack any packet which the remote side has already sent. */
5d93a237 3348 serial_write (rs->remote_desc, "+", 1);
57e12211 3349
1e51243a
PA
3350 /* Signal other parts that we're going through the initial setup,
3351 and so things may not be stable yet. */
3352 rs->starting_up = 1;
3353
c8d104ad
PA
3354 /* The first packet we send to the target is the optional "supported
3355 packets" request. If the target can answer this, it will tell us
3356 which later probes to skip. */
3357 remote_query_supported ();
3358
d914c394
SS
3359 /* If the stub wants to get a QAllow, compose one and send it. */
3360 if (remote_protocol_packets[PACKET_QAllow].support != PACKET_DISABLE)
c378d69d 3361 remote_set_permissions (target);
d914c394 3362
c8d104ad
PA
3363 /* Next, we possibly activate noack mode.
3364
3365 If the QStartNoAckMode packet configuration is set to AUTO,
3366 enable noack mode if the stub reported a wish for it with
3367 qSupported.
3368
3369 If set to TRUE, then enable noack mode even if the stub didn't
3370 report it in qSupported. If the stub doesn't reply OK, the
3371 session ends with an error.
3372
3373 If FALSE, then don't activate noack mode, regardless of what the
3374 stub claimed should be the default with qSupported. */
3375
3376 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3377
3378 if (noack_config->detect == AUTO_BOOLEAN_TRUE
3379 || (noack_config->detect == AUTO_BOOLEAN_AUTO
3380 && noack_config->support == PACKET_ENABLE))
3381 {
3382 putpkt ("QStartNoAckMode");
3383 getpkt (&rs->buf, &rs->buf_size, 0);
3384 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3385 rs->noack_mode = 1;
3386 }
3387
04bd08de 3388 if (extended_p)
5fe04517
PA
3389 {
3390 /* Tell the remote that we are using the extended protocol. */
3391 putpkt ("!");
3392 getpkt (&rs->buf, &rs->buf_size, 0);
3393 }
3394
9b224c5e
PA
3395 /* Let the target know which signals it is allowed to pass down to
3396 the program. */
3397 update_signals_program_target ();
3398
d962ef82
DJ
3399 /* Next, if the target can specify a description, read it. We do
3400 this before anything involving memory or registers. */
3401 target_find_description ();
3402
6c95b8df
PA
3403 /* Next, now that we know something about the target, update the
3404 address spaces in the program spaces. */
3405 update_address_spaces ();
3406
50c71eaf
PA
3407 /* On OSs where the list of libraries is global to all
3408 processes, we fetch them early. */
f5656ead 3409 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 3410 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 3411
74531fed
PA
3412 if (non_stop)
3413 {
3414 if (!rs->non_stop_aware)
3e43a32a
MS
3415 error (_("Non-stop mode requested, but remote "
3416 "does not support non-stop"));
74531fed
PA
3417
3418 putpkt ("QNonStop:1");
3419 getpkt (&rs->buf, &rs->buf_size, 0);
3420
3421 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3422 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
3423
3424 /* Find about threads and processes the stub is already
3425 controlling. We default to adding them in the running state.
3426 The '?' query below will then tell us about which threads are
3427 stopped. */
04bd08de 3428 remote_threads_info (target);
74531fed
PA
3429 }
3430 else if (rs->non_stop_aware)
3431 {
3432 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 3433 Request it explicitly. */
74531fed
PA
3434 putpkt ("QNonStop:0");
3435 getpkt (&rs->buf, &rs->buf_size, 0);
3436
3437 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3438 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
3439 }
3440
a0743c90
YQ
3441 /* Upload TSVs regardless of whether the target is running or not. The
3442 remote stub, such as GDBserver, may have some predefined or builtin
3443 TSVs, even if the target is not running. */
8bd200f1 3444 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
3445 {
3446 struct uploaded_tsv *uploaded_tsvs = NULL;
3447
181e3713 3448 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
3449 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3450 }
3451
2d717e4f
DJ
3452 /* Check whether the target is running now. */
3453 putpkt ("?");
3454 getpkt (&rs->buf, &rs->buf_size, 0);
3455
74531fed 3456 if (!non_stop)
2d717e4f 3457 {
e714e1bf
UW
3458 ptid_t ptid;
3459 int fake_pid_p = 0;
3460 struct inferior *inf;
3461
74531fed 3462 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 3463 {
04bd08de 3464 if (!extended_p)
74531fed 3465 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
3466
3467 /* We're connected, but not running. Drop out before we
3468 call start_remote. */
e278ad5b 3469 rs->starting_up = 0;
c35b1492 3470 return;
2d717e4f
DJ
3471 }
3472 else
74531fed 3473 {
74531fed
PA
3474 /* Save the reply for later. */
3475 wait_status = alloca (strlen (rs->buf) + 1);
3476 strcpy (wait_status, rs->buf);
3477 }
3478
b7ea362b
PA
3479 /* Fetch thread list. */
3480 target_find_new_threads ();
3481
74531fed
PA
3482 /* Let the stub know that we want it to return the thread. */
3483 set_continue_thread (minus_one_ptid);
3484
b7ea362b
PA
3485 if (thread_count () == 0)
3486 {
3487 /* Target has no concept of threads at all. GDB treats
3488 non-threaded target as single-threaded; add a main
3489 thread. */
3490 add_current_inferior_and_thread (wait_status);
3491 }
3492 else
3493 {
3494 /* We have thread information; select the thread the target
3495 says should be current. If we're reconnecting to a
3496 multi-threaded program, this will ideally be the thread
3497 that last reported an event before GDB disconnected. */
3498 inferior_ptid = get_current_thread (wait_status);
3499 if (ptid_equal (inferior_ptid, null_ptid))
3500 {
3501 /* Odd... The target was able to list threads, but not
3502 tell us which thread was current (no "thread"
3503 register in T stop reply?). Just pick the first
3504 thread in the thread list then. */
3505 inferior_ptid = thread_list->ptid;
3506 }
3507 }
74531fed 3508
6e586cc5
YQ
3509 /* init_wait_for_inferior should be called before get_offsets in order
3510 to manage `inserted' flag in bp loc in a correct state.
3511 breakpoint_init_inferior, called from init_wait_for_inferior, set
3512 `inserted' flag to 0, while before breakpoint_re_set, called from
3513 start_remote, set `inserted' flag to 1. In the initialization of
3514 inferior, breakpoint_init_inferior should be called first, and then
3515 breakpoint_re_set can be called. If this order is broken, state of
3516 `inserted' flag is wrong, and cause some problems on breakpoint
3517 manipulation. */
3518 init_wait_for_inferior ();
3519
74531fed
PA
3520 get_offsets (); /* Get text, data & bss offsets. */
3521
d962ef82
DJ
3522 /* If we could not find a description using qXfer, and we know
3523 how to do it some other way, try again. This is not
3524 supported for non-stop; it could be, but it is tricky if
3525 there are no stopped threads when we connect. */
04bd08de 3526 if (remote_read_description_p (target)
f5656ead 3527 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
3528 {
3529 target_clear_description ();
3530 target_find_description ();
3531 }
3532
74531fed
PA
3533 /* Use the previously fetched status. */
3534 gdb_assert (wait_status != NULL);
3535 strcpy (rs->buf, wait_status);
3536 rs->cached_wait_status = 1;
3537
3538 immediate_quit--;
04bd08de 3539 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
3540 }
3541 else
3542 {
68c97600
PA
3543 /* Clear WFI global state. Do this before finding about new
3544 threads and inferiors, and setting the current inferior.
3545 Otherwise we would clear the proceed status of the current
3546 inferior when we want its stop_soon state to be preserved
3547 (see notice_new_inferior). */
3548 init_wait_for_inferior ();
3549
74531fed
PA
3550 /* In non-stop, we will either get an "OK", meaning that there
3551 are no stopped threads at this time; or, a regular stop
3552 reply. In the latter case, there may be more than one thread
3553 stopped --- we pull them all out using the vStopped
3554 mechanism. */
3555 if (strcmp (rs->buf, "OK") != 0)
3556 {
722247f1 3557 struct notif_client *notif = &notif_client_stop;
2d717e4f 3558
722247f1
YQ
3559 /* remote_notif_get_pending_replies acks this one, and gets
3560 the rest out. */
f48ff2a7 3561 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
3562 = remote_notif_parse (notif, rs->buf);
3563 remote_notif_get_pending_events (notif);
c906108c 3564
74531fed
PA
3565 /* Make sure that threads that were stopped remain
3566 stopped. */
3567 iterate_over_threads (set_stop_requested_callback, NULL);
3568 }
2d717e4f 3569
74531fed
PA
3570 if (target_can_async_p ())
3571 target_async (inferior_event_handler, 0);
c906108c 3572
74531fed
PA
3573 if (thread_count () == 0)
3574 {
04bd08de 3575 if (!extended_p)
74531fed 3576 error (_("The target is not running (try extended-remote?)"));
82f73884 3577
c35b1492
PA
3578 /* We're connected, but not running. Drop out before we
3579 call start_remote. */
e278ad5b 3580 rs->starting_up = 0;
c35b1492
PA
3581 return;
3582 }
74531fed
PA
3583
3584 /* Let the stub know that we want it to return the thread. */
c0a2216e 3585
74531fed
PA
3586 /* Force the stub to choose a thread. */
3587 set_general_thread (null_ptid);
c906108c 3588
74531fed
PA
3589 /* Query it. */
3590 inferior_ptid = remote_current_thread (minus_one_ptid);
3591 if (ptid_equal (inferior_ptid, minus_one_ptid))
3592 error (_("remote didn't report the current thread in non-stop mode"));
c906108c 3593
74531fed
PA
3594 get_offsets (); /* Get text, data & bss offsets. */
3595
3596 /* In non-stop mode, any cached wait status will be stored in
3597 the stop reply queue. */
3598 gdb_assert (wait_status == NULL);
f0223081 3599
2455069d 3600 /* Report all signals during attach/startup. */
94bedb42 3601 remote_pass_signals (target, 0, NULL);
74531fed 3602 }
c8d104ad 3603
c8d104ad
PA
3604 /* If we connected to a live target, do some additional setup. */
3605 if (target_has_execution)
3606 {
f4ccffad 3607 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 3608 remote_check_symbols ();
c8d104ad 3609 }
50c71eaf 3610
d5551862
SS
3611 /* Possibly the target has been engaged in a trace run started
3612 previously; find out where things are at. */
8bd200f1 3613 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 3614 {
00bf0b85 3615 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 3616
00bf0b85
SS
3617 if (current_trace_status ()->running)
3618 printf_filtered (_("Trace is already running on the target.\n"));
3619
ab6617cc 3620 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
3621
3622 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
3623 }
3624
1e51243a
PA
3625 /* The thread and inferior lists are now synchronized with the
3626 target, our symbols have been relocated, and we're merged the
3627 target's tracepoints with ours. We're done with basic start
3628 up. */
3629 rs->starting_up = 0;
3630
2567c7d9 3631 /* If breakpoints are global, insert them now. */
f5656ead 3632 if (gdbarch_has_global_breakpoints (target_gdbarch ())
50c71eaf
PA
3633 && breakpoints_always_inserted_mode ())
3634 insert_breakpoints ();
c906108c
SS
3635}
3636
3637/* Open a connection to a remote debugger.
3638 NAME is the filename used for communication. */
3639
3640static void
fba45db2 3641remote_open (char *name, int from_tty)
c906108c 3642{
75c99385 3643 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
3644}
3645
c906108c
SS
3646/* Open a connection to a remote debugger using the extended
3647 remote gdb protocol. NAME is the filename used for communication. */
3648
3649static void
fba45db2 3650extended_remote_open (char *name, int from_tty)
c906108c 3651{
75c99385 3652 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
3653}
3654
c906108c
SS
3655/* Generic code for opening a connection to a remote target. */
3656
d471ea57
AC
3657static void
3658init_all_packet_configs (void)
3659{
3660 int i;
a744cf53 3661
444abaca
DJ
3662 for (i = 0; i < PACKET_MAX; i++)
3663 update_packet_config (&remote_protocol_packets[i]);
d471ea57
AC
3664}
3665
23860348 3666/* Symbol look-up. */
dc8acb97
MS
3667
3668static void
36d25514 3669remote_check_symbols (void)
dc8acb97 3670{
d01949b6 3671 struct remote_state *rs = get_remote_state ();
dc8acb97 3672 char *msg, *reply, *tmp;
3b7344d5 3673 struct bound_minimal_symbol sym;
dc8acb97
MS
3674 int end;
3675
63154eca
PA
3676 /* The remote side has no concept of inferiors that aren't running
3677 yet, it only knows about running processes. If we're connected
3678 but our current inferior is not running, we should not invite the
3679 remote target to request symbol lookups related to its
3680 (unrelated) current process. */
3681 if (!target_has_execution)
3682 return;
3683
444abaca 3684 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
dc8acb97
MS
3685 return;
3686
63154eca
PA
3687 /* Make sure the remote is pointing at the right process. Note
3688 there's no way to select "no process". */
3c9c4b83
PA
3689 set_general_process ();
3690
6d820c5c
DJ
3691 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3692 because we need both at the same time. */
ea9c271d 3693 msg = alloca (get_remote_packet_size ());
6d820c5c 3694
23860348 3695 /* Invite target to request symbol lookups. */
dc8acb97
MS
3696
3697 putpkt ("qSymbol::");
6d820c5c
DJ
3698 getpkt (&rs->buf, &rs->buf_size, 0);
3699 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2e9f7625 3700 reply = rs->buf;
dc8acb97
MS
3701
3702 while (strncmp (reply, "qSymbol:", 8) == 0)
3703 {
77e371c0
TT
3704 struct bound_minimal_symbol sym;
3705
dc8acb97 3706 tmp = &reply[8];
cfd77fa1 3707 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
3708 msg[end] = '\0';
3709 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 3710 if (sym.minsym == NULL)
ea9c271d 3711 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 3712 else
2bbe3cc1 3713 {
f5656ead 3714 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 3715 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
3716
3717 /* If this is a function address, return the start of code
3718 instead of any data function descriptor. */
f5656ead 3719 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
3720 sym_addr,
3721 &current_target);
3722
3723 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 3724 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
3725 }
3726
dc8acb97 3727 putpkt (msg);
6d820c5c 3728 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3729 reply = rs->buf;
dc8acb97
MS
3730 }
3731}
3732
9db8d71f
DJ
3733static struct serial *
3734remote_serial_open (char *name)
3735{
3736 static int udp_warning = 0;
3737
3738 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3739 of in ser-tcp.c, because it is the remote protocol assuming that the
3740 serial connection is reliable and not the serial connection promising
3741 to be. */
3742 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
3743 {
3e43a32a
MS
3744 warning (_("The remote protocol may be unreliable over UDP.\n"
3745 "Some events may be lost, rendering further debugging "
3746 "impossible."));
9db8d71f
DJ
3747 udp_warning = 1;
3748 }
3749
3750 return serial_open (name);
3751}
3752
d914c394
SS
3753/* Inform the target of our permission settings. The permission flags
3754 work without this, but if the target knows the settings, it can do
3755 a couple things. First, it can add its own check, to catch cases
3756 that somehow manage to get by the permissions checks in target
3757 methods. Second, if the target is wired to disallow particular
3758 settings (for instance, a system in the field that is not set up to
3759 be able to stop at a breakpoint), it can object to any unavailable
3760 permissions. */
3761
3762void
c378d69d 3763remote_set_permissions (struct target_ops *self)
d914c394
SS
3764{
3765 struct remote_state *rs = get_remote_state ();
3766
bba74b36
YQ
3767 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3768 "WriteReg:%x;WriteMem:%x;"
3769 "InsertBreak:%x;InsertTrace:%x;"
3770 "InsertFastTrace:%x;Stop:%x",
3771 may_write_registers, may_write_memory,
3772 may_insert_breakpoints, may_insert_tracepoints,
3773 may_insert_fast_tracepoints, may_stop);
d914c394
SS
3774 putpkt (rs->buf);
3775 getpkt (&rs->buf, &rs->buf_size, 0);
3776
3777 /* If the target didn't like the packet, warn the user. Do not try
3778 to undo the user's settings, that would just be maddening. */
3779 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 3780 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
3781}
3782
be2a5f71
DJ
3783/* This type describes each known response to the qSupported
3784 packet. */
3785struct protocol_feature
3786{
3787 /* The name of this protocol feature. */
3788 const char *name;
3789
3790 /* The default for this protocol feature. */
3791 enum packet_support default_support;
3792
3793 /* The function to call when this feature is reported, or after
3794 qSupported processing if the feature is not supported.
3795 The first argument points to this structure. The second
3796 argument indicates whether the packet requested support be
3797 enabled, disabled, or probed (or the default, if this function
3798 is being called at the end of processing and this feature was
3799 not reported). The third argument may be NULL; if not NULL, it
3800 is a NUL-terminated string taken from the packet following
3801 this feature's name and an equals sign. */
3802 void (*func) (const struct protocol_feature *, enum packet_support,
3803 const char *);
3804
3805 /* The corresponding packet for this feature. Only used if
3806 FUNC is remote_supported_packet. */
3807 int packet;
3808};
3809
be2a5f71
DJ
3810static void
3811remote_supported_packet (const struct protocol_feature *feature,
3812 enum packet_support support,
3813 const char *argument)
3814{
3815 if (argument)
3816 {
3817 warning (_("Remote qSupported response supplied an unexpected value for"
3818 " \"%s\"."), feature->name);
3819 return;
3820 }
3821
3822 if (remote_protocol_packets[feature->packet].support
3823 == PACKET_SUPPORT_UNKNOWN)
3824 remote_protocol_packets[feature->packet].support = support;
3825}
be2a5f71
DJ
3826
3827static void
3828remote_packet_size (const struct protocol_feature *feature,
3829 enum packet_support support, const char *value)
3830{
3831 struct remote_state *rs = get_remote_state ();
3832
3833 int packet_size;
3834 char *value_end;
3835
3836 if (support != PACKET_ENABLE)
3837 return;
3838
3839 if (value == NULL || *value == '\0')
3840 {
3841 warning (_("Remote target reported \"%s\" without a size."),
3842 feature->name);
3843 return;
3844 }
3845
3846 errno = 0;
3847 packet_size = strtol (value, &value_end, 16);
3848 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3849 {
3850 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3851 feature->name, value);
3852 return;
3853 }
3854
3855 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3856 {
3857 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3858 packet_size, MAX_REMOTE_PACKET_SIZE);
3859 packet_size = MAX_REMOTE_PACKET_SIZE;
3860 }
3861
3862 /* Record the new maximum packet size. */
3863 rs->explicit_packet_size = packet_size;
3864}
3865
82f73884
PA
3866static void
3867remote_multi_process_feature (const struct protocol_feature *feature,
3868 enum packet_support support, const char *value)
3869{
3870 struct remote_state *rs = get_remote_state ();
a744cf53 3871
82f73884
PA
3872 rs->multi_process_aware = (support == PACKET_ENABLE);
3873}
3874
74531fed
PA
3875static void
3876remote_non_stop_feature (const struct protocol_feature *feature,
3877 enum packet_support support, const char *value)
3878{
3879 struct remote_state *rs = get_remote_state ();
a744cf53 3880
74531fed
PA
3881 rs->non_stop_aware = (support == PACKET_ENABLE);
3882}
3883
782b2b07
SS
3884static void
3885remote_cond_tracepoint_feature (const struct protocol_feature *feature,
3886 enum packet_support support,
3887 const char *value)
3888{
3889 struct remote_state *rs = get_remote_state ();
a744cf53 3890
782b2b07
SS
3891 rs->cond_tracepoints = (support == PACKET_ENABLE);
3892}
3893
3788aec7
LM
3894static void
3895remote_cond_breakpoint_feature (const struct protocol_feature *feature,
3896 enum packet_support support,
3897 const char *value)
3898{
3899 struct remote_state *rs = get_remote_state ();
3900
3901 rs->cond_breakpoints = (support == PACKET_ENABLE);
3902}
3903
d3ce09f5
SS
3904static void
3905remote_breakpoint_commands_feature (const struct protocol_feature *feature,
3906 enum packet_support support,
3907 const char *value)
3908{
3909 struct remote_state *rs = get_remote_state ();
3910
3911 rs->breakpoint_commands = (support == PACKET_ENABLE);
3912}
3913
7a697b8d
SS
3914static void
3915remote_fast_tracepoint_feature (const struct protocol_feature *feature,
3916 enum packet_support support,
3917 const char *value)
3918{
3919 struct remote_state *rs = get_remote_state ();
a744cf53 3920
7a697b8d
SS
3921 rs->fast_tracepoints = (support == PACKET_ENABLE);
3922}
3923
0fb4aa4b
PA
3924static void
3925remote_static_tracepoint_feature (const struct protocol_feature *feature,
3926 enum packet_support support,
3927 const char *value)
3928{
3929 struct remote_state *rs = get_remote_state ();
3930
3931 rs->static_tracepoints = (support == PACKET_ENABLE);
3932}
3933
1e4d1764
YQ
3934static void
3935remote_install_in_trace_feature (const struct protocol_feature *feature,
3936 enum packet_support support,
3937 const char *value)
3938{
3939 struct remote_state *rs = get_remote_state ();
3940
3941 rs->install_in_trace = (support == PACKET_ENABLE);
3942}
3943
d5551862
SS
3944static void
3945remote_disconnected_tracing_feature (const struct protocol_feature *feature,
3946 enum packet_support support,
3947 const char *value)
3948{
3949 struct remote_state *rs = get_remote_state ();
a744cf53 3950
d5551862
SS
3951 rs->disconnected_tracing = (support == PACKET_ENABLE);
3952}
3953
d248b706
KY
3954static void
3955remote_enable_disable_tracepoint_feature (const struct protocol_feature *feature,
3956 enum packet_support support,
3957 const char *value)
3958{
3959 struct remote_state *rs = get_remote_state ();
3960
3961 rs->enable_disable_tracepoints = (support == PACKET_ENABLE);
3962}
3963
3065dfb6
SS
3964static void
3965remote_string_tracing_feature (const struct protocol_feature *feature,
3966 enum packet_support support,
3967 const char *value)
3968{
3969 struct remote_state *rs = get_remote_state ();
3970
3971 rs->string_tracing = (support == PACKET_ENABLE);
3972}
3973
ced63ec0
GB
3974static void
3975remote_augmented_libraries_svr4_read_feature
3976 (const struct protocol_feature *feature,
3977 enum packet_support support, const char *value)
3978{
3979 struct remote_state *rs = get_remote_state ();
3980
3981 rs->augmented_libraries_svr4_read = (support == PACKET_ENABLE);
3982}
3983
dc473cfb 3984static const struct protocol_feature remote_protocol_features[] = {
0876f84a 3985 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 3986 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 3987 PACKET_qXfer_auxv },
23181151
DJ
3988 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3989 PACKET_qXfer_features },
cfa9d6d9
DJ
3990 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3991 PACKET_qXfer_libraries },
2268b414
JK
3992 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
3993 PACKET_qXfer_libraries_svr4 },
ced63ec0
GB
3994 { "augmented-libraries-svr4-read", PACKET_DISABLE,
3995 remote_augmented_libraries_svr4_read_feature, -1 },
fd79ecee 3996 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 3997 PACKET_qXfer_memory_map },
4de6483e
UW
3998 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3999 PACKET_qXfer_spu_read },
4000 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4001 PACKET_qXfer_spu_write },
07e059b5
VP
4002 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4003 PACKET_qXfer_osdata },
dc146f7c
VP
4004 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4005 PACKET_qXfer_threads },
b3b9301e
PA
4006 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4007 PACKET_qXfer_traceframe_info },
89be2091
DJ
4008 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4009 PACKET_QPassSignals },
9b224c5e
PA
4010 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4011 PACKET_QProgramSignals },
a6f3e723
SL
4012 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4013 PACKET_QStartNoAckMode },
82f73884 4014 { "multiprocess", PACKET_DISABLE, remote_multi_process_feature, -1 },
74531fed 4015 { "QNonStop", PACKET_DISABLE, remote_non_stop_feature, -1 },
4aa995e1
PA
4016 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4017 PACKET_qXfer_siginfo_read },
4018 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4019 PACKET_qXfer_siginfo_write },
782b2b07
SS
4020 { "ConditionalTracepoints", PACKET_DISABLE, remote_cond_tracepoint_feature,
4021 PACKET_ConditionalTracepoints },
3788aec7
LM
4022 { "ConditionalBreakpoints", PACKET_DISABLE, remote_cond_breakpoint_feature,
4023 PACKET_ConditionalBreakpoints },
d3ce09f5
SS
4024 { "BreakpointCommands", PACKET_DISABLE, remote_breakpoint_commands_feature,
4025 PACKET_BreakpointCommands },
7a697b8d
SS
4026 { "FastTracepoints", PACKET_DISABLE, remote_fast_tracepoint_feature,
4027 PACKET_FastTracepoints },
0fb4aa4b
PA
4028 { "StaticTracepoints", PACKET_DISABLE, remote_static_tracepoint_feature,
4029 PACKET_StaticTracepoints },
1e4d1764
YQ
4030 {"InstallInTrace", PACKET_DISABLE, remote_install_in_trace_feature,
4031 PACKET_InstallInTrace},
d5551862
SS
4032 { "DisconnectedTracing", PACKET_DISABLE, remote_disconnected_tracing_feature,
4033 -1 },
40ab02ce
MS
4034 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4035 PACKET_bc },
4036 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4037 PACKET_bs },
409873ef
SS
4038 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4039 PACKET_TracepointSource },
d914c394
SS
4040 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4041 PACKET_QAllow },
d248b706
KY
4042 { "EnableDisableTracepoints", PACKET_DISABLE,
4043 remote_enable_disable_tracepoint_feature, -1 },
78d85199
YQ
4044 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4045 PACKET_qXfer_fdpic },
169081d0
TG
4046 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4047 PACKET_qXfer_uib },
03583c20
UW
4048 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4049 PACKET_QDisableRandomization },
d1feda86 4050 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4051 { "QTBuffer:size", PACKET_DISABLE,
4052 remote_supported_packet, PACKET_QTBuffer_size},
3065dfb6
SS
4053 { "tracenz", PACKET_DISABLE,
4054 remote_string_tracing_feature, -1 },
9accd112
MM
4055 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4056 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4057 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4058 PACKET_qXfer_btrace }
be2a5f71
DJ
4059};
4060
c8d5aac9
L
4061static char *remote_support_xml;
4062
4063/* Register string appended to "xmlRegisters=" in qSupported query. */
4064
4065void
6e39997a 4066register_remote_support_xml (const char *xml)
c8d5aac9
L
4067{
4068#if defined(HAVE_LIBEXPAT)
4069 if (remote_support_xml == NULL)
c4f7c687 4070 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4071 else
4072 {
4073 char *copy = xstrdup (remote_support_xml + 13);
4074 char *p = strtok (copy, ",");
4075
4076 do
4077 {
4078 if (strcmp (p, xml) == 0)
4079 {
4080 /* already there */
4081 xfree (copy);
4082 return;
4083 }
4084 }
4085 while ((p = strtok (NULL, ",")) != NULL);
4086 xfree (copy);
4087
94b0dee1
PA
4088 remote_support_xml = reconcat (remote_support_xml,
4089 remote_support_xml, ",", xml,
4090 (char *) NULL);
c8d5aac9
L
4091 }
4092#endif
4093}
4094
4095static char *
4096remote_query_supported_append (char *msg, const char *append)
4097{
4098 if (msg)
94b0dee1 4099 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4100 else
4101 return xstrdup (append);
4102}
4103
be2a5f71
DJ
4104static void
4105remote_query_supported (void)
4106{
4107 struct remote_state *rs = get_remote_state ();
4108 char *next;
4109 int i;
4110 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4111
4112 /* The packet support flags are handled differently for this packet
4113 than for most others. We treat an error, a disabled packet, and
4114 an empty response identically: any features which must be reported
4115 to be used will be automatically disabled. An empty buffer
4116 accomplishes this, since that is also the representation for a list
4117 containing no features. */
4118
4119 rs->buf[0] = 0;
4120 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
4121 {
c8d5aac9 4122 char *q = NULL;
94b0dee1 4123 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4124
901f9912 4125 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9
L
4126
4127 if (remote_support_xml)
4128 q = remote_query_supported_append (q, remote_support_xml);
4129
dde08ee1
PA
4130 q = remote_query_supported_append (q, "qRelocInsn+");
4131
4132 q = reconcat (q, "qSupported:", q, (char *) NULL);
4133 putpkt (q);
82f73884 4134
94b0dee1
PA
4135 do_cleanups (old_chain);
4136
be2a5f71
DJ
4137 getpkt (&rs->buf, &rs->buf_size, 0);
4138
4139 /* If an error occured, warn, but do not return - just reset the
4140 buffer to empty and go on to disable features. */
4141 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4142 == PACKET_ERROR)
4143 {
4144 warning (_("Remote failure reply: %s"), rs->buf);
4145 rs->buf[0] = 0;
4146 }
4147 }
4148
4149 memset (seen, 0, sizeof (seen));
4150
4151 next = rs->buf;
4152 while (*next)
4153 {
4154 enum packet_support is_supported;
4155 char *p, *end, *name_end, *value;
4156
4157 /* First separate out this item from the rest of the packet. If
4158 there's another item after this, we overwrite the separator
4159 (terminated strings are much easier to work with). */
4160 p = next;
4161 end = strchr (p, ';');
4162 if (end == NULL)
4163 {
4164 end = p + strlen (p);
4165 next = end;
4166 }
4167 else
4168 {
89be2091
DJ
4169 *end = '\0';
4170 next = end + 1;
4171
be2a5f71
DJ
4172 if (end == p)
4173 {
4174 warning (_("empty item in \"qSupported\" response"));
4175 continue;
4176 }
be2a5f71
DJ
4177 }
4178
4179 name_end = strchr (p, '=');
4180 if (name_end)
4181 {
4182 /* This is a name=value entry. */
4183 is_supported = PACKET_ENABLE;
4184 value = name_end + 1;
4185 *name_end = '\0';
4186 }
4187 else
4188 {
4189 value = NULL;
4190 switch (end[-1])
4191 {
4192 case '+':
4193 is_supported = PACKET_ENABLE;
4194 break;
4195
4196 case '-':
4197 is_supported = PACKET_DISABLE;
4198 break;
4199
4200 case '?':
4201 is_supported = PACKET_SUPPORT_UNKNOWN;
4202 break;
4203
4204 default:
3e43a32a
MS
4205 warning (_("unrecognized item \"%s\" "
4206 "in \"qSupported\" response"), p);
be2a5f71
DJ
4207 continue;
4208 }
4209 end[-1] = '\0';
4210 }
4211
4212 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4213 if (strcmp (remote_protocol_features[i].name, p) == 0)
4214 {
4215 const struct protocol_feature *feature;
4216
4217 seen[i] = 1;
4218 feature = &remote_protocol_features[i];
4219 feature->func (feature, is_supported, value);
4220 break;
4221 }
4222 }
4223
4224 /* If we increased the packet size, make sure to increase the global
4225 buffer size also. We delay this until after parsing the entire
4226 qSupported packet, because this is the same buffer we were
4227 parsing. */
4228 if (rs->buf_size < rs->explicit_packet_size)
4229 {
4230 rs->buf_size = rs->explicit_packet_size;
4231 rs->buf = xrealloc (rs->buf, rs->buf_size);
4232 }
4233
4234 /* Handle the defaults for unmentioned features. */
4235 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4236 if (!seen[i])
4237 {
4238 const struct protocol_feature *feature;
4239
4240 feature = &remote_protocol_features[i];
4241 feature->func (feature, feature->default_support, NULL);
4242 }
4243}
4244
78a095c3
JK
4245/* Remove any of the remote.c targets from target stack. Upper targets depend
4246 on it so remove them first. */
4247
4248static void
4249remote_unpush_target (void)
4250{
4251 pop_all_targets_above (process_stratum - 1);
4252}
be2a5f71 4253
c906108c 4254static void
3e43a32a
MS
4255remote_open_1 (char *name, int from_tty,
4256 struct target_ops *target, int extended_p)
c906108c 4257{
d01949b6 4258 struct remote_state *rs = get_remote_state ();
a6f3e723 4259
c906108c 4260 if (name == 0)
8a3fe4f8 4261 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4262 "serial device is attached to the remote system\n"
8a3fe4f8 4263 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4264
23860348 4265 /* See FIXME above. */
c6ebd6cf 4266 if (!target_async_permitted)
92d1e331 4267 wait_forever_enabled_p = 1;
6426a772 4268
2d717e4f 4269 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4270 Ask this question first, before target_preopen has a chance to kill
4271 anything. */
5d93a237 4272 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4273 {
78a095c3
JK
4274 if (from_tty
4275 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4276 error (_("Still connected."));
4277 }
4278
78a095c3 4279 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4280 target_preopen (from_tty);
4281
89be2091 4282 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4283 xfree (rs->last_pass_packet);
4284 rs->last_pass_packet = NULL;
89be2091 4285
9b224c5e
PA
4286 /* Make sure we send the program signals list the next time we
4287 resume. */
5e4a05c4
TT
4288 xfree (rs->last_program_signals_packet);
4289 rs->last_program_signals_packet = NULL;
9b224c5e 4290
ad9a8f3f 4291 remote_fileio_reset ();
1dd41f16
NS
4292 reopen_exec_file ();
4293 reread_symbols ();
4294
5d93a237
TT
4295 rs->remote_desc = remote_serial_open (name);
4296 if (!rs->remote_desc)
c906108c
SS
4297 perror_with_name (name);
4298
4299 if (baud_rate != -1)
4300 {
5d93a237 4301 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4302 {
9b74d5d3
KB
4303 /* The requested speed could not be set. Error out to
4304 top level after closing remote_desc. Take care to
4305 set remote_desc to NULL to avoid closing remote_desc
4306 more than once. */
5d93a237
TT
4307 serial_close (rs->remote_desc);
4308 rs->remote_desc = NULL;
c906108c
SS
4309 perror_with_name (name);
4310 }
4311 }
4312
5d93a237 4313 serial_raw (rs->remote_desc);
c906108c
SS
4314
4315 /* If there is something sitting in the buffer we might take it as a
4316 response to a command, which would be bad. */
5d93a237 4317 serial_flush_input (rs->remote_desc);
c906108c
SS
4318
4319 if (from_tty)
4320 {
4321 puts_filtered ("Remote debugging using ");
4322 puts_filtered (name);
4323 puts_filtered ("\n");
4324 }
23860348 4325 push_target (target); /* Switch to using remote target now. */
c906108c 4326
74531fed
PA
4327 /* Register extra event sources in the event loop. */
4328 remote_async_inferior_event_token
4329 = create_async_event_handler (remote_async_inferior_event_handler,
4330 NULL);
5965e028 4331 rs->notif_state = remote_notif_state_allocate ();
74531fed 4332
be2a5f71
DJ
4333 /* Reset the target state; these things will be queried either by
4334 remote_query_supported or as they are needed. */
d471ea57 4335 init_all_packet_configs ();
74531fed 4336 rs->cached_wait_status = 0;
be2a5f71 4337 rs->explicit_packet_size = 0;
a6f3e723 4338 rs->noack_mode = 0;
82f73884
PA
4339 rs->multi_process_aware = 0;
4340 rs->extended = extended_p;
74531fed 4341 rs->non_stop_aware = 0;
e24a49d8 4342 rs->waiting_for_stop_reply = 0;
3a29589a 4343 rs->ctrlc_pending_p = 0;
802188a7 4344
47f8a51d
TT
4345 rs->general_thread = not_sent_ptid;
4346 rs->continue_thread = not_sent_ptid;
262e1174 4347 rs->remote_traceframe_number = -1;
c906108c 4348
9d1f7ab2 4349 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
4350 rs->use_threadinfo_query = 1;
4351 rs->use_threadextra_query = 1;
9d1f7ab2 4352
c6ebd6cf 4353 if (target_async_permitted)
92d1e331 4354 {
23860348 4355 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4356 remote_async_terminal_ours_p = 1;
4357
4358 /* FIXME: cagney/1999-09-23: During the initial connection it is
4359 assumed that the target is already ready and able to respond to
0df8b418 4360 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4361 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4362 around this. Eventually a mechanism that allows
92d1e331 4363 wait_for_inferior() to expect/get timeouts will be
23860348 4364 implemented. */
92d1e331
DJ
4365 wait_forever_enabled_p = 0;
4366 }
4367
23860348 4368 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4369 no_shared_libraries (NULL, 0);
f78f6cf1 4370
74531fed
PA
4371 /* Start afresh. */
4372 init_thread_list ();
4373
36918e70 4374 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4375 target (we'd otherwise be in an inconsistent state) and then
4376 propogate the error on up the exception chain. This ensures that
4377 the caller doesn't stumble along blindly assuming that the
4378 function succeeded. The CLI doesn't have this problem but other
4379 UI's, such as MI do.
36918e70
AC
4380
4381 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4382 this function should return an error indication letting the
ce2826aa 4383 caller restore the previous state. Unfortunately the command
36918e70
AC
4384 ``target remote'' is directly wired to this function making that
4385 impossible. On a positive note, the CLI side of this problem has
4386 been fixed - the function set_cmd_context() makes it possible for
4387 all the ``target ....'' commands to share a common callback
4388 function. See cli-dump.c. */
109c3e39 4389 {
04bd08de 4390 volatile struct gdb_exception ex;
2d717e4f 4391
04bd08de
TT
4392 TRY_CATCH (ex, RETURN_MASK_ALL)
4393 {
4394 remote_start_remote (from_tty, target, extended_p);
4395 }
109c3e39
AC
4396 if (ex.reason < 0)
4397 {
c8d104ad
PA
4398 /* Pop the partially set up target - unless something else did
4399 already before throwing the exception. */
5d93a237 4400 if (rs->remote_desc != NULL)
78a095c3 4401 remote_unpush_target ();
c6ebd6cf 4402 if (target_async_permitted)
109c3e39
AC
4403 wait_forever_enabled_p = 1;
4404 throw_exception (ex);
4405 }
4406 }
c906108c 4407
c6ebd6cf 4408 if (target_async_permitted)
92d1e331 4409 wait_forever_enabled_p = 1;
43ff13b4
JM
4410}
4411
c906108c
SS
4412/* This takes a program previously attached to and detaches it. After
4413 this is done, GDB can be used to debug some other program. We
4414 better not have left any breakpoints in the target program or it'll
4415 die when it hits one. */
4416
4417static void
52554a0e 4418remote_detach_1 (const char *args, int from_tty, int extended)
c906108c 4419{
82f73884 4420 int pid = ptid_get_pid (inferior_ptid);
d01949b6 4421 struct remote_state *rs = get_remote_state ();
c906108c
SS
4422
4423 if (args)
8a3fe4f8 4424 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 4425
2d717e4f
DJ
4426 if (!target_has_execution)
4427 error (_("No process to detach from."));
4428
7cee1e54
PA
4429 if (from_tty)
4430 {
4431 char *exec_file = get_exec_file (0);
4432 if (exec_file == NULL)
4433 exec_file = "";
4434 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4435 target_pid_to_str (pid_to_ptid (pid)));
4436 gdb_flush (gdb_stdout);
4437 }
4438
c906108c 4439 /* Tell the remote target to detach. */
82f73884 4440 if (remote_multi_process_p (rs))
bba74b36 4441 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
82f73884
PA
4442 else
4443 strcpy (rs->buf, "D");
4444
4ddda9b5
PA
4445 putpkt (rs->buf);
4446 getpkt (&rs->buf, &rs->buf_size, 0);
4447
82f73884
PA
4448 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4449 ;
4450 else if (rs->buf[0] == '\0')
4451 error (_("Remote doesn't know how to detach"));
4452 else
4ddda9b5 4453 error (_("Can't detach process."));
c906108c 4454
7cee1e54
PA
4455 if (from_tty && !extended)
4456 puts_filtered (_("Ending remote debugging.\n"));
82f73884 4457
82f73884 4458 target_mourn_inferior ();
2d717e4f
DJ
4459}
4460
4461static void
52554a0e 4462remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f
DJ
4463{
4464 remote_detach_1 (args, from_tty, 0);
4465}
4466
4467static void
52554a0e 4468extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f
DJ
4469{
4470 remote_detach_1 (args, from_tty, 1);
c906108c
SS
4471}
4472
6ad8ae5c
DJ
4473/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4474
43ff13b4 4475static void
597320e7 4476remote_disconnect (struct target_ops *target, char *args, int from_tty)
43ff13b4 4477{
43ff13b4 4478 if (args)
2d717e4f 4479 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 4480
2d717e4f
DJ
4481 /* Make sure we unpush even the extended remote targets; mourn
4482 won't do it. So call remote_mourn_1 directly instead of
4483 target_mourn_inferior. */
4484 remote_mourn_1 (target);
4485
43ff13b4
JM
4486 if (from_tty)
4487 puts_filtered ("Ending remote debugging.\n");
4488}
4489
2d717e4f
DJ
4490/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4491 be chatty about it. */
4492
4493static void
4494extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
4495{
4496 struct remote_state *rs = get_remote_state ();
be86555c 4497 int pid;
96ef3384 4498 char *wait_status = NULL;
2d717e4f 4499
74164c56 4500 pid = parse_pid_to_attach (args);
2d717e4f 4501
74164c56
JK
4502 /* Remote PID can be freely equal to getpid, do not check it here the same
4503 way as in other targets. */
2d717e4f
DJ
4504
4505 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4506 error (_("This target does not support attaching to a process"));
4507
7cee1e54
PA
4508 if (from_tty)
4509 {
4510 char *exec_file = get_exec_file (0);
4511
4512 if (exec_file)
4513 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4514 target_pid_to_str (pid_to_ptid (pid)));
4515 else
4516 printf_unfiltered (_("Attaching to %s\n"),
4517 target_pid_to_str (pid_to_ptid (pid)));
4518
4519 gdb_flush (gdb_stdout);
4520 }
4521
bba74b36 4522 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
4523 putpkt (rs->buf);
4524 getpkt (&rs->buf, &rs->buf_size, 0);
4525
3e43a32a
MS
4526 if (packet_ok (rs->buf,
4527 &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
2d717e4f 4528 {
74531fed
PA
4529 if (!non_stop)
4530 {
4531 /* Save the reply for later. */
4532 wait_status = alloca (strlen (rs->buf) + 1);
4533 strcpy (wait_status, rs->buf);
4534 }
4535 else if (strcmp (rs->buf, "OK") != 0)
4536 error (_("Attaching to %s failed with: %s"),
4537 target_pid_to_str (pid_to_ptid (pid)),
4538 rs->buf);
2d717e4f
DJ
4539 }
4540 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4541 error (_("This target does not support attaching to a process"));
4542 else
4543 error (_("Attaching to %s failed"),
4544 target_pid_to_str (pid_to_ptid (pid)));
4545
49c62f2e 4546 set_current_inferior (remote_add_inferior (0, pid, 1));
bad34192 4547
2d717e4f 4548 inferior_ptid = pid_to_ptid (pid);
79d7f229 4549
bad34192
PA
4550 if (non_stop)
4551 {
4552 struct thread_info *thread;
79d7f229 4553
bad34192
PA
4554 /* Get list of threads. */
4555 remote_threads_info (target);
82f73884 4556
bad34192
PA
4557 thread = first_thread_of_process (pid);
4558 if (thread)
4559 inferior_ptid = thread->ptid;
4560 else
4561 inferior_ptid = pid_to_ptid (pid);
4562
4563 /* Invalidate our notion of the remote current thread. */
47f8a51d 4564 record_currthread (rs, minus_one_ptid);
bad34192 4565 }
74531fed 4566 else
bad34192
PA
4567 {
4568 /* Now, if we have thread information, update inferior_ptid. */
4569 inferior_ptid = remote_current_thread (inferior_ptid);
4570
4571 /* Add the main thread to the thread list. */
4572 add_thread_silent (inferior_ptid);
4573 }
c0a2216e 4574
96ef3384
UW
4575 /* Next, if the target can specify a description, read it. We do
4576 this before anything involving memory or registers. */
4577 target_find_description ();
4578
74531fed
PA
4579 if (!non_stop)
4580 {
4581 /* Use the previously fetched status. */
4582 gdb_assert (wait_status != NULL);
4583
4584 if (target_can_async_p ())
4585 {
722247f1
YQ
4586 struct notif_event *reply
4587 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 4588
722247f1 4589 push_stop_reply ((struct stop_reply *) reply);
74531fed
PA
4590
4591 target_async (inferior_event_handler, 0);
4592 }
4593 else
4594 {
4595 gdb_assert (wait_status != NULL);
4596 strcpy (rs->buf, wait_status);
4597 rs->cached_wait_status = 1;
4598 }
4599 }
4600 else
4601 gdb_assert (wait_status == NULL);
2d717e4f
DJ
4602}
4603
4604static void
136d6dae 4605extended_remote_attach (struct target_ops *ops, char *args, int from_tty)
2d717e4f 4606{
136d6dae 4607 extended_remote_attach_1 (ops, args, from_tty);
2d717e4f
DJ
4608}
4609
c906108c 4610\f
506fb367
DJ
4611/* Check for the availability of vCont. This function should also check
4612 the response. */
c906108c
SS
4613
4614static void
6d820c5c 4615remote_vcont_probe (struct remote_state *rs)
c906108c 4616{
2e9f7625 4617 char *buf;
6d820c5c 4618
2e9f7625
DJ
4619 strcpy (rs->buf, "vCont?");
4620 putpkt (rs->buf);
6d820c5c 4621 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4622 buf = rs->buf;
c906108c 4623
506fb367
DJ
4624 /* Make sure that the features we assume are supported. */
4625 if (strncmp (buf, "vCont", 5) == 0)
4626 {
4627 char *p = &buf[5];
4628 int support_s, support_S, support_c, support_C;
4629
4630 support_s = 0;
4631 support_S = 0;
4632 support_c = 0;
4633 support_C = 0;
d458bd84 4634 rs->supports_vCont.t = 0;
c1e36e3e 4635 rs->supports_vCont.r = 0;
506fb367
DJ
4636 while (p && *p == ';')
4637 {
4638 p++;
4639 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4640 support_s = 1;
4641 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4642 support_S = 1;
4643 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4644 support_c = 1;
4645 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4646 support_C = 1;
74531fed 4647 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 4648 rs->supports_vCont.t = 1;
c1e36e3e
PA
4649 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4650 rs->supports_vCont.r = 1;
506fb367
DJ
4651
4652 p = strchr (p, ';');
4653 }
c906108c 4654
506fb367
DJ
4655 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4656 BUF will make packet_ok disable the packet. */
4657 if (!support_s || !support_S || !support_c || !support_C)
4658 buf[0] = 0;
4659 }
c906108c 4660
444abaca 4661 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 4662}
c906108c 4663
0d8f58ca
PA
4664/* Helper function for building "vCont" resumptions. Write a
4665 resumption to P. ENDP points to one-passed-the-end of the buffer
4666 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4667 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4668 resumed thread should be single-stepped and/or signalled. If PTID
4669 equals minus_one_ptid, then all threads are resumed; if PTID
4670 represents a process, then all threads of the process are resumed;
4671 the thread to be stepped and/or signalled is given in the global
4672 INFERIOR_PTID. */
4673
4674static char *
4675append_resumption (char *p, char *endp,
2ea28649 4676 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
4677{
4678 struct remote_state *rs = get_remote_state ();
4679
a493e3e2 4680 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 4681 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
4682 else if (step
4683 /* GDB is willing to range step. */
4684 && use_range_stepping
4685 /* Target supports range stepping. */
4686 && rs->supports_vCont.r
4687 /* We don't currently support range stepping multiple
4688 threads with a wildcard (though the protocol allows it,
4689 so stubs shouldn't make an active effort to forbid
4690 it). */
4691 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4692 {
4693 struct thread_info *tp;
4694
4695 if (ptid_equal (ptid, minus_one_ptid))
4696 {
4697 /* If we don't know about the target thread's tid, then
4698 we're resuming magic_null_ptid (see caller). */
4699 tp = find_thread_ptid (magic_null_ptid);
4700 }
4701 else
4702 tp = find_thread_ptid (ptid);
4703 gdb_assert (tp != NULL);
4704
4705 if (tp->control.may_range_step)
4706 {
4707 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4708
4709 p += xsnprintf (p, endp - p, ";r%s,%s",
4710 phex_nz (tp->control.step_range_start,
4711 addr_size),
4712 phex_nz (tp->control.step_range_end,
4713 addr_size));
4714 }
4715 else
4716 p += xsnprintf (p, endp - p, ";s");
4717 }
0d8f58ca
PA
4718 else if (step)
4719 p += xsnprintf (p, endp - p, ";s");
a493e3e2 4720 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
4721 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4722 else
4723 p += xsnprintf (p, endp - p, ";c");
4724
4725 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4726 {
4727 ptid_t nptid;
4728
4729 /* All (-1) threads of process. */
ba348170 4730 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
4731
4732 p += xsnprintf (p, endp - p, ":");
4733 p = write_ptid (p, endp, nptid);
4734 }
4735 else if (!ptid_equal (ptid, minus_one_ptid))
4736 {
4737 p += xsnprintf (p, endp - p, ":");
4738 p = write_ptid (p, endp, ptid);
4739 }
4740
4741 return p;
4742}
4743
e5ef252a
PA
4744/* Append a vCont continue-with-signal action for threads that have a
4745 non-zero stop signal. */
4746
4747static char *
4748append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4749{
4750 struct thread_info *thread;
4751
4752 ALL_THREADS (thread)
4753 if (ptid_match (thread->ptid, ptid)
4754 && !ptid_equal (inferior_ptid, thread->ptid)
4755 && thread->suspend.stop_signal != GDB_SIGNAL_0
4756 && signal_pass_state (thread->suspend.stop_signal))
4757 {
4758 p = append_resumption (p, endp, thread->ptid,
4759 0, thread->suspend.stop_signal);
4760 thread->suspend.stop_signal = GDB_SIGNAL_0;
4761 }
4762
4763 return p;
4764}
4765
506fb367
DJ
4766/* Resume the remote inferior by using a "vCont" packet. The thread
4767 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
4768 resumed thread should be single-stepped and/or signalled. If PTID
4769 equals minus_one_ptid, then all threads are resumed; the thread to
4770 be stepped and/or signalled is given in the global INFERIOR_PTID.
4771 This function returns non-zero iff it resumes the inferior.
44eaed12 4772
506fb367
DJ
4773 This function issues a strict subset of all possible vCont commands at the
4774 moment. */
44eaed12 4775
506fb367 4776static int
2ea28649 4777remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
4778{
4779 struct remote_state *rs = get_remote_state ();
82f73884
PA
4780 char *p;
4781 char *endp;
44eaed12 4782
444abaca 4783 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
6d820c5c 4784 remote_vcont_probe (rs);
44eaed12 4785
444abaca 4786 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
6d820c5c 4787 return 0;
44eaed12 4788
82f73884
PA
4789 p = rs->buf;
4790 endp = rs->buf + get_remote_packet_size ();
4791
506fb367
DJ
4792 /* If we could generate a wider range of packets, we'd have to worry
4793 about overflowing BUF. Should there be a generic
4794 "multi-part-packet" packet? */
4795
0d8f58ca
PA
4796 p += xsnprintf (p, endp - p, "vCont");
4797
79d7f229 4798 if (ptid_equal (ptid, magic_null_ptid))
c906108c 4799 {
79d7f229
PA
4800 /* MAGIC_NULL_PTID means that we don't have any active threads,
4801 so we don't have any TID numbers the inferior will
4802 understand. Make sure to only send forms that do not specify
4803 a TID. */
a9cbf802 4804 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 4805 }
0d8f58ca 4806 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 4807 {
0d8f58ca
PA
4808 /* Resume all threads (of all processes, or of a single
4809 process), with preference for INFERIOR_PTID. This assumes
4810 inferior_ptid belongs to the set of all threads we are about
4811 to resume. */
a493e3e2 4812 if (step || siggnal != GDB_SIGNAL_0)
82f73884 4813 {
0d8f58ca
PA
4814 /* Step inferior_ptid, with or without signal. */
4815 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 4816 }
0d8f58ca 4817
e5ef252a
PA
4818 /* Also pass down any pending signaled resumption for other
4819 threads not the current. */
4820 p = append_pending_thread_resumptions (p, endp, ptid);
4821
0d8f58ca 4822 /* And continue others without a signal. */
a493e3e2 4823 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
4824 }
4825 else
506fb367
DJ
4826 {
4827 /* Scheduler locking; resume only PTID. */
a9cbf802 4828 append_resumption (p, endp, ptid, step, siggnal);
506fb367 4829 }
c906108c 4830
82f73884
PA
4831 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4832 putpkt (rs->buf);
506fb367 4833
74531fed
PA
4834 if (non_stop)
4835 {
4836 /* In non-stop, the stub replies to vCont with "OK". The stop
4837 reply will be reported asynchronously by means of a `%Stop'
4838 notification. */
4839 getpkt (&rs->buf, &rs->buf_size, 0);
4840 if (strcmp (rs->buf, "OK") != 0)
4841 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4842 }
4843
506fb367 4844 return 1;
c906108c 4845}
43ff13b4 4846
506fb367
DJ
4847/* Tell the remote machine to resume. */
4848
43ff13b4 4849static void
28439f5e 4850remote_resume (struct target_ops *ops,
2ea28649 4851 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 4852{
d01949b6 4853 struct remote_state *rs = get_remote_state ();
2e9f7625 4854 char *buf;
43ff13b4 4855
722247f1
YQ
4856 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
4857 (explained in remote-notif.c:handle_notification) so
4858 remote_notif_process is not called. We need find a place where
4859 it is safe to start a 'vNotif' sequence. It is good to do it
4860 before resuming inferior, because inferior was stopped and no RSP
4861 traffic at that moment. */
4862 if (!non_stop)
5965e028 4863 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 4864
b73be471 4865 rs->last_sent_signal = siggnal;
280ceea3 4866 rs->last_sent_step = step;
43ff13b4 4867
506fb367 4868 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
4869 /* No reverse support (yet) for vCont. */
4870 if (execution_direction != EXEC_REVERSE)
4871 if (remote_vcont_resume (ptid, step, siggnal))
4872 goto done;
506fb367 4873
79d7f229
PA
4874 /* All other supported resume packets do use Hc, so set the continue
4875 thread. */
4876 if (ptid_equal (ptid, minus_one_ptid))
4877 set_continue_thread (any_thread_ptid);
506fb367 4878 else
79d7f229 4879 set_continue_thread (ptid);
506fb367 4880
2e9f7625 4881 buf = rs->buf;
b2175913
MS
4882 if (execution_direction == EXEC_REVERSE)
4883 {
4884 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 4885 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 4886 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 4887 siggnal);
40ab02ce
MS
4888
4889 if (step
4890 && remote_protocol_packets[PACKET_bs].support == PACKET_DISABLE)
4891 error (_("Remote reverse-step not supported."));
4892 if (!step
4893 && remote_protocol_packets[PACKET_bc].support == PACKET_DISABLE)
08c93ed9 4894 error (_("Remote reverse-continue not supported."));
40ab02ce 4895
b2175913
MS
4896 strcpy (buf, step ? "bs" : "bc");
4897 }
a493e3e2 4898 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
4899 {
4900 buf[0] = step ? 'S' : 'C';
c5aa993b 4901 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 4902 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
4903 buf[3] = '\0';
4904 }
4905 else
c5aa993b 4906 strcpy (buf, step ? "s" : "c");
506fb367 4907
44eaed12 4908 putpkt (buf);
43ff13b4 4909
75c99385 4910 done:
2acceee2 4911 /* We are about to start executing the inferior, let's register it
0df8b418
MS
4912 with the event loop. NOTE: this is the one place where all the
4913 execution commands end up. We could alternatively do this in each
23860348 4914 of the execution commands in infcmd.c. */
2acceee2
JM
4915 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4916 into infcmd.c in order to allow inferior function calls to work
23860348 4917 NOT asynchronously. */
362646f5 4918 if (target_can_async_p ())
2acceee2 4919 target_async (inferior_event_handler, 0);
e24a49d8
PA
4920
4921 /* We've just told the target to resume. The remote server will
4922 wait for the inferior to stop, and then send a stop reply. In
4923 the mean time, we can't start another command/query ourselves
74531fed
PA
4924 because the stub wouldn't be ready to process it. This applies
4925 only to the base all-stop protocol, however. In non-stop (which
4926 only supports vCont), the stub replies with an "OK", and is
4927 immediate able to process further serial input. */
4928 if (!non_stop)
4929 rs->waiting_for_stop_reply = 1;
43ff13b4 4930}
c906108c 4931\f
43ff13b4
JM
4932
4933/* Set up the signal handler for SIGINT, while the target is
23860348 4934 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 4935static void
934b9bac 4936async_initialize_sigint_signal_handler (void)
43ff13b4 4937{
934b9bac 4938 signal (SIGINT, async_handle_remote_sigint);
43ff13b4
JM
4939}
4940
23860348 4941/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 4942static void
934b9bac 4943async_handle_remote_sigint (int sig)
43ff13b4 4944{
934b9bac
JK
4945 signal (sig, async_handle_remote_sigint_twice);
4946 mark_async_signal_handler (async_sigint_remote_token);
43ff13b4
JM
4947}
4948
4949/* Signal handler for SIGINT, installed after SIGINT has already been
4950 sent once. It will take effect the second time that the user sends
23860348 4951 a ^C. */
43ff13b4 4952static void
934b9bac 4953async_handle_remote_sigint_twice (int sig)
43ff13b4 4954{
934b9bac
JK
4955 signal (sig, async_handle_remote_sigint);
4956 mark_async_signal_handler (async_sigint_remote_twice_token);
43ff13b4
JM
4957}
4958
6426a772 4959/* Perform the real interruption of the target execution, in response
23860348 4960 to a ^C. */
c5aa993b 4961static void
fba45db2 4962async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
4963{
4964 if (remote_debug)
248fd3bf 4965 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
43ff13b4 4966
94cc34af 4967 target_stop (inferior_ptid);
43ff13b4
JM
4968}
4969
0df8b418 4970/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 4971 up on the target alltogether. */
47e1ce27 4972static void
fba45db2 4973async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 4974{
2df3850c 4975 if (remote_debug)
248fd3bf 4976 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
b803fb0f
DJ
4977
4978 interrupt_query ();
43ff13b4
JM
4979}
4980
4981/* Reinstall the usual SIGINT handlers, after the target has
23860348 4982 stopped. */
6426a772 4983static void
934b9bac 4984async_cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
4985{
4986 signal (SIGINT, handle_sigint);
43ff13b4
JM
4987}
4988
c906108c
SS
4989/* Send ^C to target to halt it. Target will respond, and send us a
4990 packet. */
507f3c78 4991static void (*ofunc) (int);
c906108c 4992
0df8b418
MS
4993/* The command line interface's stop routine. This function is installed
4994 as a signal handler for SIGINT. The first time a user requests a
4995 stop, we call remote_stop to send a break or ^C. If there is no
7a292a7a 4996 response from the target (it didn't stop when the user requested it),
23860348 4997 we ask the user if he'd like to detach from the target. */
c906108c 4998static void
934b9bac 4999sync_remote_interrupt (int signo)
c906108c 5000{
23860348 5001 /* If this doesn't work, try more severe steps. */
934b9bac 5002 signal (signo, sync_remote_interrupt_twice);
7a292a7a 5003
934b9bac 5004 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
7a292a7a
SS
5005}
5006
5007/* The user typed ^C twice. */
5008
5009static void
934b9bac 5010sync_remote_interrupt_twice (int signo)
7a292a7a
SS
5011{
5012 signal (signo, ofunc);
934b9bac
JK
5013 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5014 signal (signo, sync_remote_interrupt);
c906108c 5015}
7a292a7a 5016
74531fed
PA
5017/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5018 thread, all threads of a remote process, or all threads of all
5019 processes. */
5020
5021static void
5022remote_stop_ns (ptid_t ptid)
5023{
5024 struct remote_state *rs = get_remote_state ();
5025 char *p = rs->buf;
5026 char *endp = rs->buf + get_remote_packet_size ();
74531fed
PA
5027
5028 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
5029 remote_vcont_probe (rs);
5030
d458bd84 5031 if (!rs->supports_vCont.t)
74531fed
PA
5032 error (_("Remote server does not support stopping threads"));
5033
f91d3df5
PA
5034 if (ptid_equal (ptid, minus_one_ptid)
5035 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5036 p += xsnprintf (p, endp - p, "vCont;t");
5037 else
5038 {
5039 ptid_t nptid;
5040
74531fed
PA
5041 p += xsnprintf (p, endp - p, "vCont;t:");
5042
5043 if (ptid_is_pid (ptid))
5044 /* All (-1) threads of process. */
ba348170 5045 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
5046 else
5047 {
5048 /* Small optimization: if we already have a stop reply for
5049 this thread, no use in telling the stub we want this
5050 stopped. */
5051 if (peek_stop_reply (ptid))
5052 return;
5053
5054 nptid = ptid;
5055 }
5056
a9cbf802 5057 write_ptid (p, endp, nptid);
74531fed
PA
5058 }
5059
5060 /* In non-stop, we get an immediate OK reply. The stop reply will
5061 come in asynchronously by notification. */
5062 putpkt (rs->buf);
5063 getpkt (&rs->buf, &rs->buf_size, 0);
5064 if (strcmp (rs->buf, "OK") != 0)
5065 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5066}
5067
5068/* All-stop version of target_stop. Sends a break or a ^C to stop the
5069 remote target. It is undefined which thread of which process
5070 reports the stop. */
5071
5072static void
5073remote_stop_as (ptid_t ptid)
5074{
5075 struct remote_state *rs = get_remote_state ();
5076
3a29589a
DJ
5077 rs->ctrlc_pending_p = 1;
5078
74531fed
PA
5079 /* If the inferior is stopped already, but the core didn't know
5080 about it yet, just ignore the request. The cached wait status
5081 will be collected in remote_wait. */
5082 if (rs->cached_wait_status)
5083 return;
5084
9a7071a8
JB
5085 /* Send interrupt_sequence to remote target. */
5086 send_interrupt_sequence ();
74531fed
PA
5087}
5088
0df8b418 5089/* This is the generic stop called via the target vector. When a target
7a292a7a 5090 interrupt is requested, either by the command line or the GUI, we
23860348 5091 will eventually end up here. */
74531fed 5092
c906108c 5093static void
1eab8a48 5094remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5095{
7a292a7a 5096 if (remote_debug)
0f71a2f6 5097 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5098
74531fed
PA
5099 if (non_stop)
5100 remote_stop_ns (ptid);
c906108c 5101 else
74531fed 5102 remote_stop_as (ptid);
c906108c
SS
5103}
5104
5105/* Ask the user what to do when an interrupt is received. */
5106
5107static void
fba45db2 5108interrupt_query (void)
c906108c
SS
5109{
5110 target_terminal_ours ();
5111
74531fed 5112 if (target_can_async_p ())
c906108c 5113 {
74531fed 5114 signal (SIGINT, handle_sigint);
039e3c22 5115 quit ();
c906108c 5116 }
74531fed
PA
5117 else
5118 {
9e2f0ad4
HZ
5119 if (query (_("Interrupted while waiting for the program.\n\
5120Give up (and stop debugging it)? ")))
74531fed 5121 {
78a095c3 5122 remote_unpush_target ();
039e3c22 5123 quit ();
74531fed
PA
5124 }
5125 }
c906108c
SS
5126
5127 target_terminal_inferior ();
5128}
5129
6426a772
JM
5130/* Enable/disable target terminal ownership. Most targets can use
5131 terminal groups to control terminal ownership. Remote targets are
5132 different in that explicit transfer of ownership to/from GDB/target
23860348 5133 is required. */
6426a772
JM
5134
5135static void
d2f640d4 5136remote_terminal_inferior (struct target_ops *self)
6426a772 5137{
c6ebd6cf 5138 if (!target_async_permitted)
75c99385
PA
5139 /* Nothing to do. */
5140 return;
5141
d9d2d8b6
PA
5142 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5143 idempotent. The event-loop GDB talking to an asynchronous target
5144 with a synchronous command calls this function from both
5145 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5146 transfer the terminal to the target when it shouldn't this guard
5147 can go away. */
6426a772
JM
5148 if (!remote_async_terminal_ours_p)
5149 return;
5150 delete_file_handler (input_fd);
5151 remote_async_terminal_ours_p = 0;
934b9bac 5152 async_initialize_sigint_signal_handler ();
6426a772
JM
5153 /* NOTE: At this point we could also register our selves as the
5154 recipient of all input. Any characters typed could then be
23860348 5155 passed on down to the target. */
6426a772
JM
5156}
5157
5158static void
e3594fd1 5159remote_terminal_ours (struct target_ops *self)
6426a772 5160{
c6ebd6cf 5161 if (!target_async_permitted)
75c99385
PA
5162 /* Nothing to do. */
5163 return;
5164
5165 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5166 if (remote_async_terminal_ours_p)
5167 return;
934b9bac 5168 async_cleanup_sigint_signal_handler (NULL);
6426a772
JM
5169 add_file_handler (input_fd, stdin_event_handler, 0);
5170 remote_async_terminal_ours_p = 1;
5171}
5172
176a6961 5173static void
917317f4 5174remote_console_output (char *msg)
c906108c
SS
5175{
5176 char *p;
5177
c5aa993b 5178 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5179 {
5180 char tb[2];
5181 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5182
c906108c
SS
5183 tb[0] = c;
5184 tb[1] = 0;
43ff13b4 5185 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5186 }
00db5b94
PA
5187 gdb_flush (gdb_stdtarg);
5188}
74531fed
PA
5189
5190typedef struct cached_reg
5191{
5192 int num;
5193 gdb_byte data[MAX_REGISTER_SIZE];
5194} cached_reg_t;
5195
5196DEF_VEC_O(cached_reg_t);
5197
722247f1 5198typedef struct stop_reply
74531fed 5199{
722247f1 5200 struct notif_event base;
74531fed 5201
722247f1 5202 /* The identifier of the thread about this event */
74531fed
PA
5203 ptid_t ptid;
5204
340e3c99 5205 /* The remote state this event is associated with. When the remote
bcc75809
YQ
5206 connection, represented by a remote_state object, is closed,
5207 all the associated stop_reply events should be released. */
5208 struct remote_state *rs;
5209
74531fed
PA
5210 struct target_waitstatus ws;
5211
15148d6a
PA
5212 /* Expedited registers. This makes remote debugging a bit more
5213 efficient for those targets that provide critical registers as
5214 part of their normal status mechanism (as another roundtrip to
5215 fetch them is avoided). */
74531fed
PA
5216 VEC(cached_reg_t) *regcache;
5217
5218 int stopped_by_watchpoint_p;
5219 CORE_ADDR watch_data_address;
5220
dc146f7c 5221 int core;
722247f1 5222} *stop_reply_p;
a744cf53 5223
722247f1
YQ
5224DECLARE_QUEUE_P (stop_reply_p);
5225DEFINE_QUEUE_P (stop_reply_p);
5226/* The list of already fetched and acknowledged stop events. This
5227 queue is used for notification Stop, and other notifications
5228 don't need queue for their events, because the notification events
5229 of Stop can't be consumed immediately, so that events should be
5230 queued first, and be consumed by remote_wait_{ns,as} one per
5231 time. Other notifications can consume their events immediately,
5232 so queue is not needed for them. */
5233static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
5234
5235static void
5236stop_reply_xfree (struct stop_reply *r)
5237{
f48ff2a7 5238 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
5239}
5240
722247f1
YQ
5241static void
5242remote_notif_stop_parse (struct notif_client *self, char *buf,
5243 struct notif_event *event)
5244{
5245 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5246}
5247
5248static void
5249remote_notif_stop_ack (struct notif_client *self, char *buf,
5250 struct notif_event *event)
5251{
5252 struct stop_reply *stop_reply = (struct stop_reply *) event;
5253
5254 /* acknowledge */
5255 putpkt ((char *) self->ack_command);
5256
5257 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5258 /* We got an unknown stop reply. */
5259 error (_("Unknown stop reply"));
5260
5261 push_stop_reply (stop_reply);
5262}
5263
5264static int
5265remote_notif_stop_can_get_pending_events (struct notif_client *self)
5266{
5267 /* We can't get pending events in remote_notif_process for
5268 notification stop, and we have to do this in remote_wait_ns
5269 instead. If we fetch all queued events from stub, remote stub
5270 may exit and we have no chance to process them back in
5271 remote_wait_ns. */
5272 mark_async_event_handler (remote_async_inferior_event_token);
5273 return 0;
5274}
5275
5276static void
5277stop_reply_dtr (struct notif_event *event)
5278{
5279 struct stop_reply *r = (struct stop_reply *) event;
5280
5281 VEC_free (cached_reg_t, r->regcache);
5282}
5283
5284static struct notif_event *
5285remote_notif_stop_alloc_reply (void)
5286{
5287 struct notif_event *r
70ba0933 5288 = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
5289
5290 r->dtr = stop_reply_dtr;
5291
5292 return r;
5293}
5294
5295/* A client of notification Stop. */
5296
5297struct notif_client notif_client_stop =
5298{
5299 "Stop",
5300 "vStopped",
5301 remote_notif_stop_parse,
5302 remote_notif_stop_ack,
5303 remote_notif_stop_can_get_pending_events,
5304 remote_notif_stop_alloc_reply,
f48ff2a7 5305 REMOTE_NOTIF_STOP,
722247f1
YQ
5306};
5307
5308/* A parameter to pass data in and out. */
5309
5310struct queue_iter_param
5311{
5312 void *input;
5313 struct stop_reply *output;
5314};
5315
f48ff2a7
YQ
5316/* Remove stop replies in the queue if its pid is equal to the given
5317 inferior's pid. */
722247f1
YQ
5318
5319static int
f48ff2a7
YQ
5320remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5321 QUEUE_ITER (stop_reply_p) *iter,
5322 stop_reply_p event,
5323 void *data)
722247f1
YQ
5324{
5325 struct queue_iter_param *param = data;
5326 struct inferior *inf = param->input;
5327
f48ff2a7 5328 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
5329 {
5330 stop_reply_xfree (event);
5331 QUEUE_remove_elem (stop_reply_p, q, iter);
5332 }
5333
5334 return 1;
5335}
5336
f48ff2a7 5337/* Discard all pending stop replies of inferior INF. */
c906108c 5338
74531fed 5339static void
5f4cf0bb 5340discard_pending_stop_replies (struct inferior *inf)
c906108c 5341{
722247f1
YQ
5342 int i;
5343 struct queue_iter_param param;
f48ff2a7
YQ
5344 struct stop_reply *reply;
5345 struct remote_state *rs = get_remote_state ();
5346 struct remote_notif_state *rns = rs->notif_state;
5347
5348 /* This function can be notified when an inferior exists. When the
5349 target is not remote, the notification state is NULL. */
5350 if (rs->remote_desc == NULL)
5351 return;
5352
5353 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 5354
74531fed 5355 /* Discard the in-flight notification. */
f48ff2a7 5356 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 5357 {
722247f1 5358 stop_reply_xfree (reply);
f48ff2a7 5359 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 5360 }
c906108c 5361
722247f1
YQ
5362 param.input = inf;
5363 param.output = NULL;
74531fed
PA
5364 /* Discard the stop replies we have already pulled with
5365 vStopped. */
722247f1 5366 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
5367 remove_stop_reply_for_inferior, &param);
5368}
5369
bcc75809
YQ
5370/* If its remote state is equal to the given remote state,
5371 remove EVENT from the stop reply queue. */
5372
5373static int
5374remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5375 QUEUE_ITER (stop_reply_p) *iter,
5376 stop_reply_p event,
5377 void *data)
5378{
5379 struct queue_iter_param *param = data;
5380 struct remote_state *rs = param->input;
5381
5382 if (event->rs == rs)
5383 {
5384 stop_reply_xfree (event);
5385 QUEUE_remove_elem (stop_reply_p, q, iter);
5386 }
5387
5388 return 1;
5389}
5390
5391/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
5392
5393static void
bcc75809 5394discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
5395{
5396 struct queue_iter_param param;
5397
bcc75809 5398 param.input = rs;
f48ff2a7
YQ
5399 param.output = NULL;
5400 /* Discard the stop replies we have already pulled with
5401 vStopped. */
5402 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 5403 remove_stop_reply_of_remote_state, &param);
722247f1 5404}
74531fed 5405
722247f1
YQ
5406/* A parameter to pass data in and out. */
5407
5408static int
5409remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5410 QUEUE_ITER (stop_reply_p) *iter,
5411 stop_reply_p event,
5412 void *data)
5413{
5414 struct queue_iter_param *param = data;
5415 ptid_t *ptid = param->input;
5416
5417 if (ptid_match (event->ptid, *ptid))
5418 {
5419 param->output = event;
5420 QUEUE_remove_elem (stop_reply_p, q, iter);
5421 return 0;
c8e38a49 5422 }
722247f1
YQ
5423
5424 return 1;
74531fed 5425}
43ff13b4 5426
722247f1
YQ
5427/* Remove the first reply in 'stop_reply_queue' which matches
5428 PTID. */
2e9f7625 5429
722247f1
YQ
5430static struct stop_reply *
5431remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 5432{
722247f1
YQ
5433 struct queue_iter_param param;
5434
5435 param.input = &ptid;
5436 param.output = NULL;
5437
5438 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5439 remote_notif_remove_once_on_match, &param);
5440 if (notif_debug)
5441 fprintf_unfiltered (gdb_stdlog,
5442 "notif: discard queued event: 'Stop' in %s\n",
5443 target_pid_to_str (ptid));
a744cf53 5444
722247f1 5445 return param.output;
74531fed 5446}
75c99385 5447
74531fed
PA
5448/* Look for a queued stop reply belonging to PTID. If one is found,
5449 remove it from the queue, and return it. Returns NULL if none is
5450 found. If there are still queued events left to process, tell the
5451 event loop to get back to target_wait soon. */
e24a49d8 5452
74531fed
PA
5453static struct stop_reply *
5454queued_stop_reply (ptid_t ptid)
5455{
722247f1 5456 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 5457
722247f1 5458 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
5459 /* There's still at least an event left. */
5460 mark_async_event_handler (remote_async_inferior_event_token);
5461
722247f1 5462 return r;
74531fed
PA
5463}
5464
5465/* Push a fully parsed stop reply in the stop reply queue. Since we
5466 know that we now have at least one queued event left to pass to the
5467 core side, tell the event loop to get back to target_wait soon. */
5468
5469static void
5470push_stop_reply (struct stop_reply *new_event)
5471{
722247f1 5472 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 5473
722247f1
YQ
5474 if (notif_debug)
5475 fprintf_unfiltered (gdb_stdlog,
5476 "notif: push 'Stop' %s to queue %d\n",
5477 target_pid_to_str (new_event->ptid),
5478 QUEUE_length (stop_reply_p,
5479 stop_reply_queue));
74531fed
PA
5480
5481 mark_async_event_handler (remote_async_inferior_event_token);
5482}
5483
722247f1
YQ
5484static int
5485stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5486 QUEUE_ITER (stop_reply_p) *iter,
5487 struct stop_reply *event,
5488 void *data)
5489{
5490 ptid_t *ptid = data;
5491
5492 return !(ptid_equal (*ptid, event->ptid)
5493 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5494}
5495
74531fed
PA
5496/* Returns true if we have a stop reply for PTID. */
5497
5498static int
5499peek_stop_reply (ptid_t ptid)
5500{
722247f1
YQ
5501 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5502 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
5503}
5504
5505/* Parse the stop reply in BUF. Either the function succeeds, and the
5506 result is stored in EVENT, or throws an error. */
5507
5508static void
5509remote_parse_stop_reply (char *buf, struct stop_reply *event)
5510{
5511 struct remote_arch_state *rsa = get_remote_arch_state ();
5512 ULONGEST addr;
5513 char *p;
5514
5515 event->ptid = null_ptid;
bcc75809 5516 event->rs = get_remote_state ();
74531fed
PA
5517 event->ws.kind = TARGET_WAITKIND_IGNORE;
5518 event->ws.value.integer = 0;
74531fed
PA
5519 event->stopped_by_watchpoint_p = 0;
5520 event->regcache = NULL;
dc146f7c 5521 event->core = -1;
74531fed
PA
5522
5523 switch (buf[0])
5524 {
5525 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
5526 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5527 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5528 ss = signal number
5529 n... = register number
5530 r... = register contents
5531 */
5532
5533 p = &buf[3]; /* after Txx */
5534 while (*p)
5535 {
5536 char *p1;
5537 char *p_temp;
5538 int fieldsize;
5539 LONGEST pnum = 0;
43ff13b4 5540
cea39f65
MS
5541 /* If the packet contains a register number, save it in
5542 pnum and set p1 to point to the character following it.
5543 Otherwise p1 points to p. */
3c3bea1c 5544
cea39f65
MS
5545 /* If this packet is an awatch packet, don't parse the 'a'
5546 as a register number. */
c8e38a49 5547
dc146f7c
VP
5548 if (strncmp (p, "awatch", strlen("awatch")) != 0
5549 && strncmp (p, "core", strlen ("core") != 0))
cea39f65
MS
5550 {
5551 /* Read the ``P'' register number. */
5552 pnum = strtol (p, &p_temp, 16);
5553 p1 = p_temp;
5554 }
5555 else
5556 p1 = p;
802188a7 5557
cea39f65
MS
5558 if (p1 == p) /* No register number present here. */
5559 {
5560 p1 = strchr (p, ':');
5561 if (p1 == NULL)
5562 error (_("Malformed packet(a) (missing colon): %s\n\
c8e38a49 5563Packet: '%s'\n"),
cea39f65
MS
5564 p, buf);
5565 if (strncmp (p, "thread", p1 - p) == 0)
5566 event->ptid = read_ptid (++p1, &p);
5567 else if ((strncmp (p, "watch", p1 - p) == 0)
5568 || (strncmp (p, "rwatch", p1 - p) == 0)
5569 || (strncmp (p, "awatch", p1 - p) == 0))
5570 {
5571 event->stopped_by_watchpoint_p = 1;
5572 p = unpack_varlen_hex (++p1, &addr);
5573 event->watch_data_address = (CORE_ADDR) addr;
5574 }
5575 else if (strncmp (p, "library", p1 - p) == 0)
5576 {
5577 p1++;
5578 p_temp = p1;
5579 while (*p_temp && *p_temp != ';')
5580 p_temp++;
c8e38a49 5581
5b5596ff 5582 event->ws.kind = TARGET_WAITKIND_LOADED;
cea39f65
MS
5583 p = p_temp;
5584 }
5585 else if (strncmp (p, "replaylog", p1 - p) == 0)
5586 {
5b5596ff
PA
5587 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5588 /* p1 will indicate "begin" or "end", but it makes
5589 no difference for now, so ignore it. */
cea39f65
MS
5590 p_temp = strchr (p1 + 1, ';');
5591 if (p_temp)
c8e38a49 5592 p = p_temp;
cea39f65 5593 }
dc146f7c
VP
5594 else if (strncmp (p, "core", p1 - p) == 0)
5595 {
5596 ULONGEST c;
a744cf53 5597
dc146f7c
VP
5598 p = unpack_varlen_hex (++p1, &c);
5599 event->core = c;
5600 }
cea39f65
MS
5601 else
5602 {
5603 /* Silently skip unknown optional info. */
5604 p_temp = strchr (p1 + 1, ';');
5605 if (p_temp)
5606 p = p_temp;
5607 }
5608 }
5609 else
5610 {
5611 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5612 cached_reg_t cached_reg;
74531fed 5613
cea39f65 5614 p = p1;
75c99385 5615
cea39f65
MS
5616 if (*p != ':')
5617 error (_("Malformed packet(b) (missing colon): %s\n\
8a3fe4f8 5618Packet: '%s'\n"),
cea39f65
MS
5619 p, buf);
5620 ++p;
43ff13b4 5621
cea39f65
MS
5622 if (reg == NULL)
5623 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 5624Packet: '%s'\n"),
7c47795c 5625 hex_string (pnum), p, buf);
c8e38a49 5626
cea39f65 5627 cached_reg.num = reg->regnum;
4100683b 5628
cea39f65 5629 fieldsize = hex2bin (p, cached_reg.data,
f5656ead 5630 register_size (target_gdbarch (),
cea39f65
MS
5631 reg->regnum));
5632 p += 2 * fieldsize;
f5656ead 5633 if (fieldsize < register_size (target_gdbarch (),
cea39f65
MS
5634 reg->regnum))
5635 warning (_("Remote reply is too short: %s"), buf);
74531fed 5636
cea39f65
MS
5637 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5638 }
c8e38a49 5639
cea39f65
MS
5640 if (*p != ';')
5641 error (_("Remote register badly formatted: %s\nhere: %s"),
5642 buf, p);
5643 ++p;
5644 }
5b5596ff
PA
5645
5646 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
5647 break;
5648
c8e38a49
PA
5649 /* fall through */
5650 case 'S': /* Old style status, just signal only. */
3a09da41
PA
5651 {
5652 int sig;
5653
5654 event->ws.kind = TARGET_WAITKIND_STOPPED;
5655 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
5656 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
5657 event->ws.value.sig = (enum gdb_signal) sig;
5658 else
5659 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5660 }
c8e38a49
PA
5661 break;
5662 case 'W': /* Target exited. */
5663 case 'X':
5664 {
5665 char *p;
5666 int pid;
5667 ULONGEST value;
82f73884 5668
c8e38a49
PA
5669 /* GDB used to accept only 2 hex chars here. Stubs should
5670 only send more if they detect GDB supports multi-process
5671 support. */
5672 p = unpack_varlen_hex (&buf[1], &value);
82f73884 5673
c8e38a49
PA
5674 if (buf[0] == 'W')
5675 {
5676 /* The remote process exited. */
74531fed
PA
5677 event->ws.kind = TARGET_WAITKIND_EXITED;
5678 event->ws.value.integer = value;
c8e38a49
PA
5679 }
5680 else
5681 {
5682 /* The remote process exited with a signal. */
74531fed 5683 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
5684 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
5685 event->ws.value.sig = (enum gdb_signal) value;
5686 else
5687 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 5688 }
82f73884 5689
c8e38a49
PA
5690 /* If no process is specified, assume inferior_ptid. */
5691 pid = ptid_get_pid (inferior_ptid);
5692 if (*p == '\0')
5693 ;
5694 else if (*p == ';')
5695 {
5696 p++;
5697
5698 if (p == '\0')
82f73884 5699 ;
c8e38a49
PA
5700 else if (strncmp (p,
5701 "process:", sizeof ("process:") - 1) == 0)
82f73884 5702 {
c8e38a49 5703 ULONGEST upid;
a744cf53 5704
c8e38a49
PA
5705 p += sizeof ("process:") - 1;
5706 unpack_varlen_hex (p, &upid);
5707 pid = upid;
82f73884
PA
5708 }
5709 else
5710 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 5711 }
c8e38a49
PA
5712 else
5713 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
5714 event->ptid = pid_to_ptid (pid);
5715 }
5716 break;
5717 }
5718
5719 if (non_stop && ptid_equal (event->ptid, null_ptid))
5720 error (_("No process or thread specified in stop reply: %s"), buf);
5721}
5722
722247f1
YQ
5723/* When the stub wants to tell GDB about a new notification reply, it
5724 sends a notification (%Stop, for example). Those can come it at
5725 any time, hence, we have to make sure that any pending
5726 putpkt/getpkt sequence we're making is finished, before querying
5727 the stub for more events with the corresponding ack command
5728 (vStopped, for example). E.g., if we started a vStopped sequence
5729 immediately upon receiving the notification, something like this
5730 could happen:
74531fed
PA
5731
5732 1.1) --> Hg 1
5733 1.2) <-- OK
5734 1.3) --> g
5735 1.4) <-- %Stop
5736 1.5) --> vStopped
5737 1.6) <-- (registers reply to step #1.3)
5738
5739 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5740 query.
5741
796cb314 5742 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
5743 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5744 doing whatever we were doing:
5745
5746 2.1) --> Hg 1
5747 2.2) <-- OK
5748 2.3) --> g
5749 2.4) <-- %Stop
5750 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5751 2.5) <-- (registers reply to step #2.3)
5752
5753 Eventualy after step #2.5, we return to the event loop, which
5754 notices there's an event on the
5755 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5756 associated callback --- the function below. At this point, we're
5757 always safe to start a vStopped sequence. :
5758
5759 2.6) --> vStopped
5760 2.7) <-- T05 thread:2
5761 2.8) --> vStopped
5762 2.9) --> OK
5763*/
5764
722247f1
YQ
5765void
5766remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
5767{
5768 struct remote_state *rs = get_remote_state ();
74531fed 5769
f48ff2a7 5770 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 5771 {
722247f1
YQ
5772 if (notif_debug)
5773 fprintf_unfiltered (gdb_stdlog,
5774 "notif: process: '%s' ack pending event\n",
5775 nc->name);
74531fed 5776
722247f1 5777 /* acknowledge */
f48ff2a7
YQ
5778 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
5779 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
5780
5781 while (1)
5782 {
5783 getpkt (&rs->buf, &rs->buf_size, 0);
5784 if (strcmp (rs->buf, "OK") == 0)
5785 break;
5786 else
722247f1 5787 remote_notif_ack (nc, rs->buf);
74531fed
PA
5788 }
5789 }
722247f1
YQ
5790 else
5791 {
5792 if (notif_debug)
5793 fprintf_unfiltered (gdb_stdlog,
5794 "notif: process: '%s' no pending reply\n",
5795 nc->name);
5796 }
74531fed
PA
5797}
5798
74531fed
PA
5799/* Called when it is decided that STOP_REPLY holds the info of the
5800 event that is to be returned to the core. This function always
5801 destroys STOP_REPLY. */
5802
5803static ptid_t
5804process_stop_reply (struct stop_reply *stop_reply,
5805 struct target_waitstatus *status)
5806{
5807 ptid_t ptid;
5808
5809 *status = stop_reply->ws;
5810 ptid = stop_reply->ptid;
5811
5812 /* If no thread/process was reported by the stub, assume the current
5813 inferior. */
5814 if (ptid_equal (ptid, null_ptid))
5815 ptid = inferior_ptid;
5816
5f3563ea
PA
5817 if (status->kind != TARGET_WAITKIND_EXITED
5818 && status->kind != TARGET_WAITKIND_SIGNALLED)
74531fed 5819 {
ee154bee
TT
5820 struct remote_state *rs = get_remote_state ();
5821
5f3563ea
PA
5822 /* Expedited registers. */
5823 if (stop_reply->regcache)
5824 {
217f1f79 5825 struct regcache *regcache
f5656ead 5826 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
5827 cached_reg_t *reg;
5828 int ix;
5829
5830 for (ix = 0;
5831 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5832 ix++)
217f1f79 5833 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
5834 VEC_free (cached_reg_t, stop_reply->regcache);
5835 }
74531fed 5836
ee154bee
TT
5837 rs->remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
5838 rs->remote_watch_data_address = stop_reply->watch_data_address;
1941c569
PA
5839
5840 remote_notice_new_inferior (ptid, 0);
dc146f7c 5841 demand_private_info (ptid)->core = stop_reply->core;
74531fed
PA
5842 }
5843
74531fed
PA
5844 stop_reply_xfree (stop_reply);
5845 return ptid;
5846}
5847
5848/* The non-stop mode version of target_wait. */
5849
5850static ptid_t
47608cb1 5851remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
5852{
5853 struct remote_state *rs = get_remote_state ();
74531fed
PA
5854 struct stop_reply *stop_reply;
5855 int ret;
fee9eda9 5856 int is_notif = 0;
74531fed
PA
5857
5858 /* If in non-stop mode, get out of getpkt even if a
5859 notification is received. */
5860
5861 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 5862 0 /* forever */, &is_notif);
74531fed
PA
5863 while (1)
5864 {
fee9eda9 5865 if (ret != -1 && !is_notif)
74531fed
PA
5866 switch (rs->buf[0])
5867 {
5868 case 'E': /* Error of some sort. */
5869 /* We're out of sync with the target now. Did it continue
5870 or not? We can't tell which thread it was in non-stop,
5871 so just ignore this. */
5872 warning (_("Remote failure reply: %s"), rs->buf);
5873 break;
5874 case 'O': /* Console output. */
5875 remote_console_output (rs->buf + 1);
5876 break;
5877 default:
5878 warning (_("Invalid remote reply: %s"), rs->buf);
5879 break;
5880 }
5881
5882 /* Acknowledge a pending stop reply that may have arrived in the
5883 mean time. */
f48ff2a7 5884 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 5885 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
5886
5887 /* If indeed we noticed a stop reply, we're done. */
5888 stop_reply = queued_stop_reply (ptid);
5889 if (stop_reply != NULL)
5890 return process_stop_reply (stop_reply, status);
5891
47608cb1 5892 /* Still no event. If we're just polling for an event, then
74531fed 5893 return to the event loop. */
47608cb1 5894 if (options & TARGET_WNOHANG)
74531fed
PA
5895 {
5896 status->kind = TARGET_WAITKIND_IGNORE;
5897 return minus_one_ptid;
5898 }
5899
47608cb1 5900 /* Otherwise do a blocking wait. */
74531fed 5901 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 5902 1 /* forever */, &is_notif);
74531fed
PA
5903 }
5904}
5905
5906/* Wait until the remote machine stops, then return, storing status in
5907 STATUS just as `wait' would. */
5908
5909static ptid_t
47608cb1 5910remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
5911{
5912 struct remote_state *rs = get_remote_state ();
74531fed 5913 ptid_t event_ptid = null_ptid;
cea39f65 5914 char *buf;
74531fed
PA
5915 struct stop_reply *stop_reply;
5916
47608cb1
PA
5917 again:
5918
74531fed
PA
5919 status->kind = TARGET_WAITKIND_IGNORE;
5920 status->value.integer = 0;
5921
5922 stop_reply = queued_stop_reply (ptid);
5923 if (stop_reply != NULL)
5924 return process_stop_reply (stop_reply, status);
5925
5926 if (rs->cached_wait_status)
5927 /* Use the cached wait status, but only once. */
5928 rs->cached_wait_status = 0;
5929 else
5930 {
5931 int ret;
722247f1 5932 int is_notif;
74531fed
PA
5933
5934 if (!target_is_async_p ())
5935 {
934b9bac 5936 ofunc = signal (SIGINT, sync_remote_interrupt);
74531fed
PA
5937 /* If the user hit C-c before this packet, or between packets,
5938 pretend that it was hit right here. */
522002f9 5939 if (check_quit_flag ())
74531fed 5940 {
522002f9 5941 clear_quit_flag ();
934b9bac 5942 sync_remote_interrupt (SIGINT);
74531fed
PA
5943 }
5944 }
5945
5946 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5947 _never_ wait for ever -> test on target_is_async_p().
5948 However, before we do that we need to ensure that the caller
5949 knows how to take the target into/out of async mode. */
722247f1
YQ
5950 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5951 wait_forever_enabled_p, &is_notif);
5952
5e1b953b
SDJ
5953 if (!target_is_async_p ())
5954 signal (SIGINT, ofunc);
5955
722247f1
YQ
5956 /* GDB gets a notification. Return to core as this event is
5957 not interesting. */
5958 if (ret != -1 && is_notif)
5959 return minus_one_ptid;
74531fed
PA
5960 }
5961
5962 buf = rs->buf;
5963
ee154bee 5964 rs->remote_stopped_by_watchpoint_p = 0;
74531fed
PA
5965
5966 /* We got something. */
5967 rs->waiting_for_stop_reply = 0;
5968
3a29589a
DJ
5969 /* Assume that the target has acknowledged Ctrl-C unless we receive
5970 an 'F' or 'O' packet. */
5971 if (buf[0] != 'F' && buf[0] != 'O')
5972 rs->ctrlc_pending_p = 0;
5973
74531fed
PA
5974 switch (buf[0])
5975 {
5976 case 'E': /* Error of some sort. */
5977 /* We're out of sync with the target now. Did it continue or
5978 not? Not is more likely, so report a stop. */
5979 warning (_("Remote failure reply: %s"), buf);
5980 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 5981 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
5982 break;
5983 case 'F': /* File-I/O request. */
3a29589a
DJ
5984 remote_fileio_request (buf, rs->ctrlc_pending_p);
5985 rs->ctrlc_pending_p = 0;
74531fed
PA
5986 break;
5987 case 'T': case 'S': case 'X': case 'W':
5988 {
722247f1
YQ
5989 struct stop_reply *stop_reply
5990 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
5991 rs->buf);
74531fed 5992
74531fed 5993 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
5994 break;
5995 }
5996 case 'O': /* Console output. */
5997 remote_console_output (buf + 1);
e24a49d8 5998
c8e38a49
PA
5999 /* The target didn't really stop; keep waiting. */
6000 rs->waiting_for_stop_reply = 1;
e24a49d8 6001
c8e38a49
PA
6002 break;
6003 case '\0':
b73be471 6004 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
6005 {
6006 /* Zero length reply means that we tried 'S' or 'C' and the
6007 remote system doesn't support it. */
6008 target_terminal_ours_for_output ();
6009 printf_filtered
6010 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
6011 gdb_signal_to_name (rs->last_sent_signal));
6012 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
6013 target_terminal_inferior ();
6014
280ceea3 6015 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49
PA
6016 putpkt ((char *) buf);
6017
6018 /* We just told the target to resume, so a stop reply is in
6019 order. */
e24a49d8 6020 rs->waiting_for_stop_reply = 1;
c8e38a49 6021 break;
43ff13b4 6022 }
c8e38a49
PA
6023 /* else fallthrough */
6024 default:
6025 warning (_("Invalid remote reply: %s"), buf);
6026 /* Keep waiting. */
6027 rs->waiting_for_stop_reply = 1;
6028 break;
43ff13b4 6029 }
c8e38a49 6030
c8e38a49 6031 if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
6032 {
6033 /* Nothing interesting happened. If we're doing a non-blocking
6034 poll, we're done. Otherwise, go back to waiting. */
6035 if (options & TARGET_WNOHANG)
6036 return minus_one_ptid;
6037 else
6038 goto again;
6039 }
74531fed
PA
6040 else if (status->kind != TARGET_WAITKIND_EXITED
6041 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
6042 {
6043 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 6044 record_currthread (rs, event_ptid);
82f73884
PA
6045 else
6046 event_ptid = inferior_ptid;
43ff13b4 6047 }
74531fed
PA
6048 else
6049 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 6050 record_currthread (rs, minus_one_ptid);
79d7f229 6051
82f73884 6052 return event_ptid;
43ff13b4
JM
6053}
6054
74531fed
PA
6055/* Wait until the remote machine stops, then return, storing status in
6056 STATUS just as `wait' would. */
6057
c8e38a49 6058static ptid_t
117de6a9 6059remote_wait (struct target_ops *ops,
47608cb1 6060 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
6061{
6062 ptid_t event_ptid;
6063
74531fed 6064 if (non_stop)
47608cb1 6065 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 6066 else
47608cb1 6067 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 6068
74531fed 6069 if (target_can_async_p ())
c8e38a49 6070 {
74531fed
PA
6071 /* If there are are events left in the queue tell the event loop
6072 to return here. */
722247f1 6073 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 6074 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 6075 }
c8e38a49
PA
6076
6077 return event_ptid;
6078}
6079
74ca34ce 6080/* Fetch a single register using a 'p' packet. */
c906108c 6081
b96ec7ac 6082static int
56be3814 6083fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
6084{
6085 struct remote_state *rs = get_remote_state ();
2e9f7625 6086 char *buf, *p;
b96ec7ac
AC
6087 char regp[MAX_REGISTER_SIZE];
6088 int i;
6089
74ca34ce
DJ
6090 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
6091 return 0;
6092
6093 if (reg->pnum == -1)
6094 return 0;
6095
2e9f7625 6096 p = rs->buf;
fcad0fa4 6097 *p++ = 'p';
74ca34ce 6098 p += hexnumstr (p, reg->pnum);
fcad0fa4 6099 *p++ = '\0';
1f4437a4
MS
6100 putpkt (rs->buf);
6101 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 6102
2e9f7625
DJ
6103 buf = rs->buf;
6104
74ca34ce
DJ
6105 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6106 {
6107 case PACKET_OK:
6108 break;
6109 case PACKET_UNKNOWN:
6110 return 0;
6111 case PACKET_ERROR:
27a9c0bf
MS
6112 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6113 gdbarch_register_name (get_regcache_arch (regcache),
6114 reg->regnum),
6115 buf);
74ca34ce 6116 }
3f9a994c
JB
6117
6118 /* If this register is unfetchable, tell the regcache. */
6119 if (buf[0] == 'x')
8480adf2 6120 {
56be3814 6121 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 6122 return 1;
b96ec7ac 6123 }
b96ec7ac 6124
3f9a994c
JB
6125 /* Otherwise, parse and supply the value. */
6126 p = buf;
6127 i = 0;
6128 while (p[0] != 0)
6129 {
6130 if (p[1] == 0)
74ca34ce 6131 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
6132
6133 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6134 p += 2;
6135 }
56be3814 6136 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 6137 return 1;
b96ec7ac
AC
6138}
6139
74ca34ce
DJ
6140/* Fetch the registers included in the target's 'g' packet. */
6141
29709017
DJ
6142static int
6143send_g_packet (void)
c906108c 6144{
d01949b6 6145 struct remote_state *rs = get_remote_state ();
cea39f65 6146 int buf_len;
c906108c 6147
bba74b36 6148 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 6149 remote_send (&rs->buf, &rs->buf_size);
c906108c 6150
29709017
DJ
6151 /* We can get out of synch in various cases. If the first character
6152 in the buffer is not a hex character, assume that has happened
6153 and try to fetch another packet to read. */
6154 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6155 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6156 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6157 && rs->buf[0] != 'x') /* New: unavailable register value. */
6158 {
6159 if (remote_debug)
6160 fprintf_unfiltered (gdb_stdlog,
6161 "Bad register packet; fetching a new packet\n");
6162 getpkt (&rs->buf, &rs->buf_size, 0);
6163 }
6164
74ca34ce
DJ
6165 buf_len = strlen (rs->buf);
6166
6167 /* Sanity check the received packet. */
6168 if (buf_len % 2 != 0)
6169 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
6170
6171 return buf_len / 2;
6172}
6173
6174static void
56be3814 6175process_g_packet (struct regcache *regcache)
29709017 6176{
4a22f64d 6177 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
6178 struct remote_state *rs = get_remote_state ();
6179 struct remote_arch_state *rsa = get_remote_arch_state ();
6180 int i, buf_len;
6181 char *p;
6182 char *regs;
6183
6184 buf_len = strlen (rs->buf);
6185
6186 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
6187 if (buf_len > 2 * rsa->sizeof_g_packet)
6188 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6189
6190 /* Save the size of the packet sent to us by the target. It is used
6191 as a heuristic when determining the max size of packets that the
6192 target can safely receive. */
6193 if (rsa->actual_register_packet_size == 0)
6194 rsa->actual_register_packet_size = buf_len;
6195
6196 /* If this is smaller than we guessed the 'g' packet would be,
6197 update our records. A 'g' reply that doesn't include a register's
6198 value implies either that the register is not available, or that
6199 the 'p' packet must be used. */
6200 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 6201 {
74ca34ce
DJ
6202 rsa->sizeof_g_packet = buf_len / 2;
6203
4a22f64d 6204 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 6205 {
74ca34ce
DJ
6206 if (rsa->regs[i].pnum == -1)
6207 continue;
6208
6209 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6210 rsa->regs[i].in_g_packet = 0;
b96ec7ac 6211 else
74ca34ce 6212 rsa->regs[i].in_g_packet = 1;
b96ec7ac 6213 }
74ca34ce 6214 }
b323314b 6215
74ca34ce 6216 regs = alloca (rsa->sizeof_g_packet);
c906108c
SS
6217
6218 /* Unimplemented registers read as all bits zero. */
ea9c271d 6219 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 6220
c906108c
SS
6221 /* Reply describes registers byte by byte, each byte encoded as two
6222 hex characters. Suck them all up, then supply them to the
6223 register cacheing/storage mechanism. */
6224
74ca34ce 6225 p = rs->buf;
ea9c271d 6226 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 6227 {
74ca34ce
DJ
6228 if (p[0] == 0 || p[1] == 0)
6229 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6230 internal_error (__FILE__, __LINE__,
9b20d036 6231 _("unexpected end of 'g' packet reply"));
74ca34ce 6232
c906108c 6233 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 6234 regs[i] = 0; /* 'x' */
c906108c
SS
6235 else
6236 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6237 p += 2;
6238 }
6239
a744cf53
MS
6240 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6241 {
6242 struct packet_reg *r = &rsa->regs[i];
6243
6244 if (r->in_g_packet)
6245 {
6246 if (r->offset * 2 >= strlen (rs->buf))
6247 /* This shouldn't happen - we adjusted in_g_packet above. */
6248 internal_error (__FILE__, __LINE__,
9b20d036 6249 _("unexpected end of 'g' packet reply"));
a744cf53
MS
6250 else if (rs->buf[r->offset * 2] == 'x')
6251 {
6252 gdb_assert (r->offset * 2 < strlen (rs->buf));
6253 /* The register isn't available, mark it as such (at
6254 the same time setting the value to zero). */
6255 regcache_raw_supply (regcache, r->regnum, NULL);
6256 }
6257 else
6258 regcache_raw_supply (regcache, r->regnum,
6259 regs + r->offset);
6260 }
6261 }
c906108c
SS
6262}
6263
29709017 6264static void
56be3814 6265fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
6266{
6267 send_g_packet ();
56be3814 6268 process_g_packet (regcache);
29709017
DJ
6269}
6270
e6e4e701
PA
6271/* Make the remote selected traceframe match GDB's selected
6272 traceframe. */
6273
6274static void
6275set_remote_traceframe (void)
6276{
6277 int newnum;
262e1174 6278 struct remote_state *rs = get_remote_state ();
e6e4e701 6279
262e1174 6280 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
6281 return;
6282
6283 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 6284 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
6285
6286 newnum = target_trace_find (tfind_number,
6287 get_traceframe_number (), 0, 0, NULL);
6288
6289 /* Should not happen. If it does, all bets are off. */
6290 if (newnum != get_traceframe_number ())
6291 warning (_("could not set remote traceframe"));
6292}
6293
74ca34ce 6294static void
28439f5e
PA
6295remote_fetch_registers (struct target_ops *ops,
6296 struct regcache *regcache, int regnum)
74ca34ce 6297{
74ca34ce
DJ
6298 struct remote_arch_state *rsa = get_remote_arch_state ();
6299 int i;
6300
e6e4e701 6301 set_remote_traceframe ();
79d7f229 6302 set_general_thread (inferior_ptid);
74ca34ce
DJ
6303
6304 if (regnum >= 0)
6305 {
6306 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6307
74ca34ce
DJ
6308 gdb_assert (reg != NULL);
6309
6310 /* If this register might be in the 'g' packet, try that first -
6311 we are likely to read more than one register. If this is the
6312 first 'g' packet, we might be overly optimistic about its
6313 contents, so fall back to 'p'. */
6314 if (reg->in_g_packet)
6315 {
56be3814 6316 fetch_registers_using_g (regcache);
74ca34ce
DJ
6317 if (reg->in_g_packet)
6318 return;
6319 }
6320
56be3814 6321 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
6322 return;
6323
6324 /* This register is not available. */
56be3814 6325 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
6326
6327 return;
6328 }
6329
56be3814 6330 fetch_registers_using_g (regcache);
74ca34ce 6331
4a22f64d 6332 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6333 if (!rsa->regs[i].in_g_packet)
56be3814 6334 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
6335 {
6336 /* This register is not available. */
56be3814 6337 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
6338 }
6339}
6340
c906108c
SS
6341/* Prepare to store registers. Since we may send them all (using a
6342 'G' request), we have to read out the ones we don't want to change
6343 first. */
6344
c5aa993b 6345static void
f32dbf8c 6346remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 6347{
ea9c271d 6348 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 6349 int i;
cfd77fa1 6350 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 6351
c906108c 6352 /* Make sure the entire registers array is valid. */
444abaca 6353 switch (remote_protocol_packets[PACKET_P].support)
5a2468f5
JM
6354 {
6355 case PACKET_DISABLE:
6356 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 6357 /* Make sure all the necessary registers are cached. */
4a22f64d 6358 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 6359 if (rsa->regs[i].in_g_packet)
316f2060 6360 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
6361 break;
6362 case PACKET_ENABLE:
6363 break;
6364 }
6365}
6366
ad10f812 6367/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 6368 packet was not recognized. */
5a2468f5
JM
6369
6370static int
1f4437a4
MS
6371store_register_using_P (const struct regcache *regcache,
6372 struct packet_reg *reg)
5a2468f5 6373{
4a22f64d 6374 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 6375 struct remote_state *rs = get_remote_state ();
5a2468f5 6376 /* Try storing a single register. */
6d820c5c 6377 char *buf = rs->buf;
cfd77fa1 6378 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 6379 char *p;
5a2468f5 6380
74ca34ce
DJ
6381 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
6382 return 0;
6383
6384 if (reg->pnum == -1)
6385 return 0;
6386
ea9c271d 6387 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 6388 p = buf + strlen (buf);
56be3814 6389 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 6390 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
6391 putpkt (rs->buf);
6392 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 6393
74ca34ce
DJ
6394 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6395 {
6396 case PACKET_OK:
6397 return 1;
6398 case PACKET_ERROR:
27a9c0bf
MS
6399 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6400 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
6401 case PACKET_UNKNOWN:
6402 return 0;
6403 default:
6404 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6405 }
c906108c
SS
6406}
6407
23860348
MS
6408/* Store register REGNUM, or all registers if REGNUM == -1, from the
6409 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
6410
6411static void
56be3814 6412store_registers_using_G (const struct regcache *regcache)
c906108c 6413{
d01949b6 6414 struct remote_state *rs = get_remote_state ();
ea9c271d 6415 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 6416 gdb_byte *regs;
c906108c
SS
6417 char *p;
6418
193cb69f
AC
6419 /* Extract all the registers in the regcache copying them into a
6420 local buffer. */
6421 {
b323314b 6422 int i;
a744cf53 6423
ea9c271d
DJ
6424 regs = alloca (rsa->sizeof_g_packet);
6425 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 6426 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 6427 {
ea9c271d 6428 struct packet_reg *r = &rsa->regs[i];
a744cf53 6429
b323314b 6430 if (r->in_g_packet)
56be3814 6431 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
6432 }
6433 }
c906108c
SS
6434
6435 /* Command describes registers byte by byte,
6436 each byte encoded as two hex characters. */
6d820c5c 6437 p = rs->buf;
193cb69f 6438 *p++ = 'G';
74ca34ce
DJ
6439 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6440 updated. */
6441 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
6442 putpkt (rs->buf);
6443 getpkt (&rs->buf, &rs->buf_size, 0);
6444 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
6445 error (_("Could not write registers; remote failure reply '%s'"),
6446 rs->buf);
c906108c 6447}
74ca34ce
DJ
6448
6449/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6450 of the register cache buffer. FIXME: ignores errors. */
6451
6452static void
28439f5e
PA
6453remote_store_registers (struct target_ops *ops,
6454 struct regcache *regcache, int regnum)
74ca34ce 6455{
74ca34ce
DJ
6456 struct remote_arch_state *rsa = get_remote_arch_state ();
6457 int i;
6458
e6e4e701 6459 set_remote_traceframe ();
79d7f229 6460 set_general_thread (inferior_ptid);
74ca34ce
DJ
6461
6462 if (regnum >= 0)
6463 {
6464 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6465
74ca34ce
DJ
6466 gdb_assert (reg != NULL);
6467
6468 /* Always prefer to store registers using the 'P' packet if
6469 possible; we often change only a small number of registers.
6470 Sometimes we change a larger number; we'd need help from a
6471 higher layer to know to use 'G'. */
56be3814 6472 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
6473 return;
6474
6475 /* For now, don't complain if we have no way to write the
6476 register. GDB loses track of unavailable registers too
6477 easily. Some day, this may be an error. We don't have
0df8b418 6478 any way to read the register, either... */
74ca34ce
DJ
6479 if (!reg->in_g_packet)
6480 return;
6481
56be3814 6482 store_registers_using_G (regcache);
74ca34ce
DJ
6483 return;
6484 }
6485
56be3814 6486 store_registers_using_G (regcache);
74ca34ce 6487
4a22f64d 6488 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6489 if (!rsa->regs[i].in_g_packet)
56be3814 6490 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
6491 /* See above for why we do not issue an error here. */
6492 continue;
6493}
c906108c
SS
6494\f
6495
6496/* Return the number of hex digits in num. */
6497
6498static int
fba45db2 6499hexnumlen (ULONGEST num)
c906108c
SS
6500{
6501 int i;
6502
6503 for (i = 0; num != 0; i++)
6504 num >>= 4;
6505
6506 return max (i, 1);
6507}
6508
2df3850c 6509/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
6510
6511static int
fba45db2 6512hexnumstr (char *buf, ULONGEST num)
c906108c 6513{
c906108c 6514 int len = hexnumlen (num);
a744cf53 6515
2df3850c
JM
6516 return hexnumnstr (buf, num, len);
6517}
6518
c906108c 6519
2df3850c 6520/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 6521
2df3850c 6522static int
fba45db2 6523hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
6524{
6525 int i;
6526
6527 buf[width] = '\0';
6528
6529 for (i = width - 1; i >= 0; i--)
c906108c 6530 {
c5aa993b 6531 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
6532 num >>= 4;
6533 }
6534
2df3850c 6535 return width;
c906108c
SS
6536}
6537
23860348 6538/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
6539
6540static CORE_ADDR
fba45db2 6541remote_address_masked (CORE_ADDR addr)
c906108c 6542{
883b9c6c 6543 unsigned int address_size = remote_address_size;
a744cf53 6544
911c95a5
UW
6545 /* If "remoteaddresssize" was not set, default to target address size. */
6546 if (!address_size)
f5656ead 6547 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
6548
6549 if (address_size > 0
6550 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
6551 {
6552 /* Only create a mask when that mask can safely be constructed
23860348 6553 in a ULONGEST variable. */
c906108c 6554 ULONGEST mask = 1;
a744cf53 6555
911c95a5 6556 mask = (mask << address_size) - 1;
c906108c
SS
6557 addr &= mask;
6558 }
6559 return addr;
6560}
6561
6562/* Determine whether the remote target supports binary downloading.
6563 This is accomplished by sending a no-op memory write of zero length
6564 to the target at the specified address. It does not suffice to send
23860348
MS
6565 the whole packet, since many stubs strip the eighth bit and
6566 subsequently compute a wrong checksum, which causes real havoc with
6567 remote_write_bytes.
7a292a7a 6568
96baa820 6569 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 6570 clean. In cases like this, the user should clear "remote
23860348 6571 X-packet". */
96baa820 6572
c906108c 6573static void
fba45db2 6574check_binary_download (CORE_ADDR addr)
c906108c 6575{
d01949b6 6576 struct remote_state *rs = get_remote_state ();
24b06219 6577
444abaca 6578 switch (remote_protocol_packets[PACKET_X].support)
c906108c 6579 {
96baa820
JM
6580 case PACKET_DISABLE:
6581 break;
6582 case PACKET_ENABLE:
6583 break;
6584 case PACKET_SUPPORT_UNKNOWN:
6585 {
96baa820 6586 char *p;
802188a7 6587
2e9f7625 6588 p = rs->buf;
96baa820
JM
6589 *p++ = 'X';
6590 p += hexnumstr (p, (ULONGEST) addr);
6591 *p++ = ',';
6592 p += hexnumstr (p, (ULONGEST) 0);
6593 *p++ = ':';
6594 *p = '\0';
802188a7 6595
2e9f7625 6596 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 6597 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 6598
2e9f7625 6599 if (rs->buf[0] == '\0')
96baa820
JM
6600 {
6601 if (remote_debug)
6602 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
6603 "binary downloading NOT "
6604 "supported by target\n");
444abaca 6605 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
6606 }
6607 else
6608 {
6609 if (remote_debug)
6610 fprintf_unfiltered (gdb_stdlog,
64b9b334 6611 "binary downloading supported by target\n");
444abaca 6612 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
6613 }
6614 break;
6615 }
c906108c
SS
6616 }
6617}
6618
6619/* Write memory data directly to the remote machine.
6620 This does not inform the data cache; the data cache uses this.
a76d924d 6621 HEADER is the starting part of the packet.
c906108c
SS
6622 MEMADDR is the address in the remote memory space.
6623 MYADDR is the address of the buffer in our space.
6624 LEN is the number of bytes.
a76d924d
DJ
6625 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6626 should send data as binary ('X'), or hex-encoded ('M').
6627
6628 The function creates packet of the form
6629 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6630
6631 where encoding of <DATA> is termined by PACKET_FORMAT.
6632
6633 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6634 are omitted.
6635
9b409511
YQ
6636 Return the transferred status, error or OK (an
6637 'enum target_xfer_status' value). Save the number of bytes
6638 transferred in *XFERED_LEN. Only transfer a single packet. */
c906108c 6639
9b409511 6640static enum target_xfer_status
a76d924d 6641remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
5d6df423 6642 const gdb_byte *myaddr, ULONGEST len,
9b409511
YQ
6643 ULONGEST *xfered_len, char packet_format,
6644 int use_length)
c906108c 6645{
6d820c5c 6646 struct remote_state *rs = get_remote_state ();
cfd77fa1 6647 char *p;
a76d924d
DJ
6648 char *plen = NULL;
6649 int plenlen = 0;
917317f4
JM
6650 int todo;
6651 int nr_bytes;
a257b5bb 6652 int payload_size;
6765f3e5 6653 int payload_length;
a76d924d
DJ
6654 int header_length;
6655
6656 if (packet_format != 'X' && packet_format != 'M')
6657 internal_error (__FILE__, __LINE__,
9b20d036 6658 _("remote_write_bytes_aux: bad packet format"));
c906108c 6659
5d6df423 6660 if (len == 0)
9b409511 6661 return TARGET_XFER_EOF;
b2182ed2 6662
3de11b2e 6663 payload_size = get_memory_write_packet_size ();
2bc416ba 6664
6d820c5c
DJ
6665 /* The packet buffer will be large enough for the payload;
6666 get_memory_packet_size ensures this. */
a76d924d 6667 rs->buf[0] = '\0';
c906108c 6668
a257b5bb 6669 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
6670 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6671
a76d924d
DJ
6672 payload_size -= strlen ("$,:#NN");
6673 if (!use_length)
0df8b418 6674 /* The comma won't be used. */
a76d924d
DJ
6675 payload_size += 1;
6676 header_length = strlen (header);
6677 payload_size -= header_length;
3de11b2e 6678 payload_size -= hexnumlen (memaddr);
c906108c 6679
a76d924d 6680 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 6681
a76d924d
DJ
6682 strcat (rs->buf, header);
6683 p = rs->buf + strlen (header);
6684
6685 /* Compute a best guess of the number of bytes actually transfered. */
6686 if (packet_format == 'X')
c906108c 6687 {
23860348 6688 /* Best guess at number of bytes that will fit. */
a257b5bb 6689 todo = min (len, payload_size);
a76d924d
DJ
6690 if (use_length)
6691 payload_size -= hexnumlen (todo);
3de11b2e 6692 todo = min (todo, payload_size);
a76d924d
DJ
6693 }
6694 else
6695 {
23860348 6696 /* Num bytes that will fit. */
a257b5bb 6697 todo = min (len, payload_size / 2);
a76d924d
DJ
6698 if (use_length)
6699 payload_size -= hexnumlen (todo);
3de11b2e 6700 todo = min (todo, payload_size / 2);
917317f4 6701 }
a76d924d 6702
3de11b2e
NS
6703 if (todo <= 0)
6704 internal_error (__FILE__, __LINE__,
405f8e94 6705 _("minimum packet size too small to write data"));
802188a7 6706
6765f3e5
DJ
6707 /* If we already need another packet, then try to align the end
6708 of this packet to a useful boundary. */
6709 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6710 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6711
a257b5bb 6712 /* Append "<memaddr>". */
917317f4
JM
6713 memaddr = remote_address_masked (memaddr);
6714 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 6715
a76d924d
DJ
6716 if (use_length)
6717 {
6718 /* Append ",". */
6719 *p++ = ',';
802188a7 6720
a76d924d
DJ
6721 /* Append <len>. Retain the location/size of <len>. It may need to
6722 be adjusted once the packet body has been created. */
6723 plen = p;
6724 plenlen = hexnumstr (p, (ULONGEST) todo);
6725 p += plenlen;
6726 }
a257b5bb
AC
6727
6728 /* Append ":". */
917317f4
JM
6729 *p++ = ':';
6730 *p = '\0';
802188a7 6731
a257b5bb 6732 /* Append the packet body. */
a76d924d 6733 if (packet_format == 'X')
917317f4 6734 {
917317f4
JM
6735 /* Binary mode. Send target system values byte by byte, in
6736 increasing byte addresses. Only escape certain critical
6737 characters. */
bc20a4af
PA
6738 payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
6739 &nr_bytes, payload_size);
6765f3e5
DJ
6740
6741 /* If not all TODO bytes fit, then we'll need another packet. Make
9b7194bc
DJ
6742 a second try to keep the end of the packet aligned. Don't do
6743 this if the packet is tiny. */
6744 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6765f3e5
DJ
6745 {
6746 int new_nr_bytes;
6747
6748 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6749 - memaddr);
6750 if (new_nr_bytes != nr_bytes)
6751 payload_length = remote_escape_output (myaddr, new_nr_bytes,
bc20a4af 6752 (gdb_byte *) p, &nr_bytes,
6765f3e5
DJ
6753 payload_size);
6754 }
6755
6756 p += payload_length;
a76d924d 6757 if (use_length && nr_bytes < todo)
c906108c 6758 {
802188a7 6759 /* Escape chars have filled up the buffer prematurely,
917317f4
JM
6760 and we have actually sent fewer bytes than planned.
6761 Fix-up the length field of the packet. Use the same
6762 number of characters as before. */
917317f4
JM
6763 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6764 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 6765 }
a76d924d
DJ
6766 }
6767 else
6768 {
917317f4
JM
6769 /* Normal mode: Send target system values byte by byte, in
6770 increasing byte addresses. Each byte is encoded as a two hex
6771 value. */
2644f393 6772 nr_bytes = bin2hex (myaddr, p, todo);
aa6c0017 6773 p += 2 * nr_bytes;
c906108c 6774 }
802188a7 6775
2e9f7625 6776 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 6777 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 6778
2e9f7625 6779 if (rs->buf[0] == 'E')
00d84524 6780 return TARGET_XFER_E_IO;
802188a7 6781
23860348
MS
6782 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6783 fewer bytes than we'd planned. */
9b409511
YQ
6784 *xfered_len = (ULONGEST) nr_bytes;
6785 return TARGET_XFER_OK;
c906108c
SS
6786}
6787
a76d924d
DJ
6788/* Write memory data directly to the remote machine.
6789 This does not inform the data cache; the data cache uses this.
6790 MEMADDR is the address in the remote memory space.
6791 MYADDR is the address of the buffer in our space.
6792 LEN is the number of bytes.
6793
9b409511
YQ
6794 Return the transferred status, error or OK (an
6795 'enum target_xfer_status' value). Save the number of bytes
6796 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 6797
9b409511
YQ
6798static enum target_xfer_status
6799remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
6800 ULONGEST *xfered_len)
a76d924d
DJ
6801{
6802 char *packet_format = 0;
6803
6804 /* Check whether the target supports binary download. */
6805 check_binary_download (memaddr);
6806
6807 switch (remote_protocol_packets[PACKET_X].support)
6808 {
6809 case PACKET_ENABLE:
6810 packet_format = "X";
6811 break;
6812 case PACKET_DISABLE:
6813 packet_format = "M";
6814 break;
6815 case PACKET_SUPPORT_UNKNOWN:
6816 internal_error (__FILE__, __LINE__,
6817 _("remote_write_bytes: bad internal state"));
6818 default:
6819 internal_error (__FILE__, __LINE__, _("bad switch"));
6820 }
6821
6822 return remote_write_bytes_aux (packet_format,
9b409511
YQ
6823 memaddr, myaddr, len, xfered_len,
6824 packet_format[0], 1);
a76d924d
DJ
6825}
6826
9217e74e
YQ
6827/* Read memory data directly from the remote machine.
6828 This does not use the data cache; the data cache uses this.
6829 MEMADDR is the address in the remote memory space.
6830 MYADDR is the address of the buffer in our space.
6831 LEN is the number of bytes.
6832
6833 Return the transferred status, error or OK (an
6834 'enum target_xfer_status' value). Save the number of bytes
6835 transferred in *XFERED_LEN. */
6836
6837static enum target_xfer_status
6838remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len,
6839 ULONGEST *xfered_len)
6840{
6841 struct remote_state *rs = get_remote_state ();
6842 int max_buf_size; /* Max size of packet output buffer. */
6843 char *p;
6844 int todo;
6845 int i;
6846
6847 max_buf_size = get_memory_read_packet_size ();
6848 /* The packet buffer will be large enough for the payload;
6849 get_memory_packet_size ensures this. */
6850
6851 /* Number if bytes that will fit. */
6852 todo = min (len, max_buf_size / 2);
6853
6854 /* Construct "m"<memaddr>","<len>". */
6855 memaddr = remote_address_masked (memaddr);
6856 p = rs->buf;
6857 *p++ = 'm';
6858 p += hexnumstr (p, (ULONGEST) memaddr);
6859 *p++ = ',';
6860 p += hexnumstr (p, (ULONGEST) todo);
6861 *p = '\0';
6862 putpkt (rs->buf);
6863 getpkt (&rs->buf, &rs->buf_size, 0);
6864 if (rs->buf[0] == 'E'
6865 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6866 && rs->buf[3] == '\0')
6867 return TARGET_XFER_E_IO;
6868 /* Reply describes memory byte by byte, each byte encoded as two hex
6869 characters. */
6870 p = rs->buf;
6871 i = hex2bin (p, myaddr, todo);
6872 /* Return what we have. Let higher layers handle partial reads. */
6873 *xfered_len = (ULONGEST) i;
6874 return TARGET_XFER_OK;
6875}
6876
8acf9577
YQ
6877/* Read memory from the live target, even if currently inspecting a
6878 traceframe. The return is the same as that of target_read. */
6879
6880static enum target_xfer_status
6881target_read_live_memory (enum target_object object,
6882 ULONGEST memaddr, gdb_byte *myaddr, ULONGEST len,
6883 ULONGEST *xfered_len)
6884{
6885 enum target_xfer_status ret;
6886 struct cleanup *cleanup;
6887
6888 /* Switch momentarily out of tfind mode so to access live memory.
6889 Note that this must not clear global state, such as the frame
6890 cache, which must still remain valid for the previous traceframe.
6891 We may be _building_ the frame cache at this point. */
6892 cleanup = make_cleanup_restore_traceframe_number ();
6893 set_traceframe_number (-1);
6894
6895 ret = target_xfer_partial (current_target.beneath, object, NULL,
6896 myaddr, NULL, memaddr, len, xfered_len);
6897
6898 do_cleanups (cleanup);
6899 return ret;
6900}
6901
6902/* Using the set of read-only target sections of OPS, read live
6903 read-only memory. Note that the actual reads start from the
6904 top-most target again.
6905
6906 For interface/parameters/return description see target.h,
6907 to_xfer_partial. */
6908
6909static enum target_xfer_status
6910memory_xfer_live_readonly_partial (struct target_ops *ops,
6911 enum target_object object,
6912 gdb_byte *readbuf, ULONGEST memaddr,
6913 ULONGEST len, ULONGEST *xfered_len)
6914{
6915 struct target_section *secp;
6916 struct target_section_table *table;
6917
6918 secp = target_section_by_addr (ops, memaddr);
6919 if (secp != NULL
6920 && (bfd_get_section_flags (secp->the_bfd_section->owner,
6921 secp->the_bfd_section)
6922 & SEC_READONLY))
6923 {
6924 struct target_section *p;
6925 ULONGEST memend = memaddr + len;
6926
6927 table = target_get_section_table (ops);
6928
6929 for (p = table->sections; p < table->sections_end; p++)
6930 {
6931 if (memaddr >= p->addr)
6932 {
6933 if (memend <= p->endaddr)
6934 {
6935 /* Entire transfer is within this section. */
6936 return target_read_live_memory (object, memaddr,
6937 readbuf, len, xfered_len);
6938 }
6939 else if (memaddr >= p->endaddr)
6940 {
6941 /* This section ends before the transfer starts. */
6942 continue;
6943 }
6944 else
6945 {
6946 /* This section overlaps the transfer. Just do half. */
6947 len = p->endaddr - memaddr;
6948 return target_read_live_memory (object, memaddr,
6949 readbuf, len, xfered_len);
6950 }
6951 }
6952 }
6953 }
6954
6955 return TARGET_XFER_EOF;
6956}
6957
9217e74e
YQ
6958/* Similar to remote_read_bytes_1, but it reads from the remote stub
6959 first if the requested memory is unavailable in traceframe.
6960 Otherwise, fall back to remote_read_bytes_1. */
c906108c 6961
9b409511 6962static enum target_xfer_status
8acf9577
YQ
6963remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
6964 gdb_byte *myaddr, ULONGEST len, ULONGEST *xfered_len)
c906108c 6965{
6b6aa828 6966 if (len == 0)
b2182ed2
DJ
6967 return 0;
6968
8acf9577
YQ
6969 if (get_traceframe_number () != -1)
6970 {
6971 VEC(mem_range_s) *available;
6972
6973 /* If we fail to get the set of available memory, then the
6974 target does not support querying traceframe info, and so we
6975 attempt reading from the traceframe anyway (assuming the
6976 target implements the old QTro packet then). */
6977 if (traceframe_available_memory (&available, memaddr, len))
6978 {
6979 struct cleanup *old_chain;
6980
6981 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
6982
6983 if (VEC_empty (mem_range_s, available)
6984 || VEC_index (mem_range_s, available, 0)->start != memaddr)
6985 {
6986 enum target_xfer_status res;
6987
6988 /* Don't read into the traceframe's available
6989 memory. */
6990 if (!VEC_empty (mem_range_s, available))
6991 {
6992 LONGEST oldlen = len;
6993
6994 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
6995 gdb_assert (len <= oldlen);
6996 }
6997
6998 do_cleanups (old_chain);
6999
7000 /* This goes through the topmost target again. */
7001 res = memory_xfer_live_readonly_partial (ops,
7002 TARGET_OBJECT_MEMORY,
7003 myaddr, memaddr,
7004 len, xfered_len);
7005 if (res == TARGET_XFER_OK)
7006 return TARGET_XFER_OK;
7007 else
7008 {
7009 /* No use trying further, we know some memory starting
7010 at MEMADDR isn't available. */
7011 *xfered_len = len;
7012 return TARGET_XFER_UNAVAILABLE;
7013 }
7014 }
7015
7016 /* Don't try to read more than how much is available, in
7017 case the target implements the deprecated QTro packet to
7018 cater for older GDBs (the target's knowledge of read-only
7019 sections may be outdated by now). */
7020 len = VEC_index (mem_range_s, available, 0)->length;
7021
7022 do_cleanups (old_chain);
7023 }
7024 }
7025
9217e74e 7026 return remote_read_bytes_1 (memaddr, myaddr, len, xfered_len);
c906108c 7027}
74531fed 7028
c906108c 7029\f
c906108c 7030
a76d924d
DJ
7031/* Sends a packet with content determined by the printf format string
7032 FORMAT and the remaining arguments, then gets the reply. Returns
7033 whether the packet was a success, a failure, or unknown. */
7034
2c0b251b 7035static enum packet_result
a76d924d
DJ
7036remote_send_printf (const char *format, ...)
7037{
7038 struct remote_state *rs = get_remote_state ();
7039 int max_size = get_remote_packet_size ();
a76d924d 7040 va_list ap;
a744cf53 7041
a76d924d
DJ
7042 va_start (ap, format);
7043
7044 rs->buf[0] = '\0';
7045 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 7046 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
7047
7048 if (putpkt (rs->buf) < 0)
7049 error (_("Communication problem with target."));
7050
7051 rs->buf[0] = '\0';
7052 getpkt (&rs->buf, &rs->buf_size, 0);
7053
7054 return packet_check_result (rs->buf);
7055}
7056
7057static void
7058restore_remote_timeout (void *p)
7059{
7060 int value = *(int *)p;
a744cf53 7061
a76d924d
DJ
7062 remote_timeout = value;
7063}
7064
7065/* Flash writing can take quite some time. We'll set
7066 effectively infinite timeout for flash operations.
7067 In future, we'll need to decide on a better approach. */
7068static const int remote_flash_timeout = 1000;
7069
7070static void
7071remote_flash_erase (struct target_ops *ops,
7072 ULONGEST address, LONGEST length)
7073{
f5656ead 7074 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
7075 int saved_remote_timeout = remote_timeout;
7076 enum packet_result ret;
a76d924d
DJ
7077 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7078 &saved_remote_timeout);
a744cf53 7079
a76d924d
DJ
7080 remote_timeout = remote_flash_timeout;
7081
7082 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 7083 phex (address, addr_size),
a76d924d
DJ
7084 phex (length, 4));
7085 switch (ret)
7086 {
7087 case PACKET_UNKNOWN:
7088 error (_("Remote target does not support flash erase"));
7089 case PACKET_ERROR:
7090 error (_("Error erasing flash with vFlashErase packet"));
7091 default:
7092 break;
7093 }
7094
7095 do_cleanups (back_to);
7096}
7097
9b409511
YQ
7098static enum target_xfer_status
7099remote_flash_write (struct target_ops *ops, ULONGEST address,
7100 ULONGEST length, ULONGEST *xfered_len,
7101 const gdb_byte *data)
a76d924d
DJ
7102{
7103 int saved_remote_timeout = remote_timeout;
9b409511 7104 enum target_xfer_status ret;
a76d924d 7105 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 7106 &saved_remote_timeout);
a76d924d
DJ
7107
7108 remote_timeout = remote_flash_timeout;
9b409511
YQ
7109 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length,
7110 xfered_len,'X', 0);
a76d924d
DJ
7111 do_cleanups (back_to);
7112
7113 return ret;
7114}
7115
7116static void
7117remote_flash_done (struct target_ops *ops)
7118{
7119 int saved_remote_timeout = remote_timeout;
7120 int ret;
7121 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7122 &saved_remote_timeout);
7123
7124 remote_timeout = remote_flash_timeout;
7125 ret = remote_send_printf ("vFlashDone");
7126 do_cleanups (back_to);
7127
7128 switch (ret)
7129 {
7130 case PACKET_UNKNOWN:
7131 error (_("Remote target does not support vFlashDone"));
7132 case PACKET_ERROR:
7133 error (_("Error finishing flash operation"));
7134 default:
7135 break;
7136 }
7137}
7138
c906108c 7139static void
fba45db2 7140remote_files_info (struct target_ops *ignore)
c906108c
SS
7141{
7142 puts_filtered ("Debugging a target over a serial line.\n");
7143}
7144\f
7145/* Stuff for dealing with the packets which are part of this protocol.
7146 See comment at top of file for details. */
7147
1927e618
PA
7148/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7149 error to higher layers. Called when a serial error is detected.
7150 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
7151 the system error message for errno at function entry and final dot
7152 for output compatibility with throw_perror_with_name. */
1927e618
PA
7153
7154static void
7155unpush_and_perror (const char *string)
7156{
d6cb50a2 7157 int saved_errno = errno;
1927e618
PA
7158
7159 remote_unpush_target ();
d6cb50a2
JK
7160 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7161 safe_strerror (saved_errno));
1927e618
PA
7162}
7163
0876f84a 7164/* Read a single character from the remote end. */
c906108c
SS
7165
7166static int
fba45db2 7167readchar (int timeout)
c906108c
SS
7168{
7169 int ch;
5d93a237 7170 struct remote_state *rs = get_remote_state ();
c906108c 7171
5d93a237 7172 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 7173
2acceee2 7174 if (ch >= 0)
0876f84a 7175 return ch;
2acceee2
JM
7176
7177 switch ((enum serial_rc) ch)
c906108c
SS
7178 {
7179 case SERIAL_EOF:
78a095c3 7180 remote_unpush_target ();
598d3636 7181 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 7182 /* no return */
c906108c 7183 case SERIAL_ERROR:
1927e618
PA
7184 unpush_and_perror (_("Remote communication error. "
7185 "Target disconnected."));
2acceee2 7186 /* no return */
c906108c 7187 case SERIAL_TIMEOUT:
2acceee2 7188 break;
c906108c 7189 }
2acceee2 7190 return ch;
c906108c
SS
7191}
7192
c33e31fd
PA
7193/* Wrapper for serial_write that closes the target and throws if
7194 writing fails. */
7195
7196static void
7197remote_serial_write (const char *str, int len)
7198{
5d93a237
TT
7199 struct remote_state *rs = get_remote_state ();
7200
7201 if (serial_write (rs->remote_desc, str, len))
c33e31fd 7202 {
1927e618
PA
7203 unpush_and_perror (_("Remote communication error. "
7204 "Target disconnected."));
c33e31fd
PA
7205 }
7206}
7207
6d820c5c
DJ
7208/* Send the command in *BUF to the remote machine, and read the reply
7209 into *BUF. Report an error if we get an error reply. Resize
7210 *BUF using xrealloc if necessary to hold the result, and update
7211 *SIZEOF_BUF. */
c906108c
SS
7212
7213static void
6d820c5c
DJ
7214remote_send (char **buf,
7215 long *sizeof_buf)
c906108c 7216{
6d820c5c 7217 putpkt (*buf);
c2d11a7d 7218 getpkt (buf, sizeof_buf, 0);
c906108c 7219
6d820c5c
DJ
7220 if ((*buf)[0] == 'E')
7221 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
7222}
7223
6e5abd65
PA
7224/* Return a pointer to an xmalloc'ed string representing an escaped
7225 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7226 etc. The caller is responsible for releasing the returned
7227 memory. */
7228
7229static char *
7230escape_buffer (const char *buf, int n)
7231{
7232 struct cleanup *old_chain;
7233 struct ui_file *stb;
7234 char *str;
6e5abd65
PA
7235
7236 stb = mem_fileopen ();
7237 old_chain = make_cleanup_ui_file_delete (stb);
7238
7239 fputstrn_unfiltered (buf, n, 0, stb);
759ef836 7240 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
7241 do_cleanups (old_chain);
7242 return str;
7243}
7244
c906108c
SS
7245/* Display a null-terminated packet on stdout, for debugging, using C
7246 string notation. */
7247
7248static void
fba45db2 7249print_packet (char *buf)
c906108c
SS
7250{
7251 puts_filtered ("\"");
43e526b9 7252 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
7253 puts_filtered ("\"");
7254}
7255
7256int
fba45db2 7257putpkt (char *buf)
c906108c
SS
7258{
7259 return putpkt_binary (buf, strlen (buf));
7260}
7261
7262/* Send a packet to the remote machine, with error checking. The data
23860348 7263 of the packet is in BUF. The string in BUF can be at most
ea9c271d 7264 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
7265 and for a possible /0 if we are debugging (remote_debug) and want
7266 to print the sent packet as a string. */
c906108c
SS
7267
7268static int
fba45db2 7269putpkt_binary (char *buf, int cnt)
c906108c 7270{
2d717e4f 7271 struct remote_state *rs = get_remote_state ();
c906108c
SS
7272 int i;
7273 unsigned char csum = 0;
11cf8741 7274 char *buf2 = alloca (cnt + 6);
085dd6e6 7275
c906108c
SS
7276 int ch;
7277 int tcount = 0;
7278 char *p;
dd61ec5c 7279 char *message;
c906108c 7280
e24a49d8
PA
7281 /* Catch cases like trying to read memory or listing threads while
7282 we're waiting for a stop reply. The remote server wouldn't be
7283 ready to handle this request, so we'd hang and timeout. We don't
7284 have to worry about this in synchronous mode, because in that
7285 case it's not possible to issue a command while the target is
74531fed
PA
7286 running. This is not a problem in non-stop mode, because in that
7287 case, the stub is always ready to process serial input. */
7288 if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
e24a49d8
PA
7289 error (_("Cannot execute this command while the target is running."));
7290
2d717e4f
DJ
7291 /* We're sending out a new packet. Make sure we don't look at a
7292 stale cached response. */
7293 rs->cached_wait_status = 0;
7294
c906108c
SS
7295 /* Copy the packet into buffer BUF2, encapsulating it
7296 and giving it a checksum. */
7297
c906108c
SS
7298 p = buf2;
7299 *p++ = '$';
7300
7301 for (i = 0; i < cnt; i++)
7302 {
7303 csum += buf[i];
7304 *p++ = buf[i];
7305 }
7306 *p++ = '#';
7307 *p++ = tohex ((csum >> 4) & 0xf);
7308 *p++ = tohex (csum & 0xf);
7309
7310 /* Send it over and over until we get a positive ack. */
7311
7312 while (1)
7313 {
7314 int started_error_output = 0;
7315
7316 if (remote_debug)
7317 {
6e5abd65
PA
7318 struct cleanup *old_chain;
7319 char *str;
7320
c906108c 7321 *p = '\0';
6e5abd65
PA
7322 str = escape_buffer (buf2, p - buf2);
7323 old_chain = make_cleanup (xfree, str);
7324 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 7325 gdb_flush (gdb_stdlog);
6e5abd65 7326 do_cleanups (old_chain);
c906108c 7327 }
c33e31fd 7328 remote_serial_write (buf2, p - buf2);
c906108c 7329
a6f3e723
SL
7330 /* If this is a no acks version of the remote protocol, send the
7331 packet and move on. */
7332 if (rs->noack_mode)
7333 break;
7334
74531fed
PA
7335 /* Read until either a timeout occurs (-2) or '+' is read.
7336 Handle any notification that arrives in the mean time. */
c906108c
SS
7337 while (1)
7338 {
7339 ch = readchar (remote_timeout);
7340
c5aa993b 7341 if (remote_debug)
c906108c
SS
7342 {
7343 switch (ch)
7344 {
7345 case '+':
1216fa2c 7346 case '-':
c906108c
SS
7347 case SERIAL_TIMEOUT:
7348 case '$':
74531fed 7349 case '%':
c906108c
SS
7350 if (started_error_output)
7351 {
7352 putchar_unfiltered ('\n');
7353 started_error_output = 0;
7354 }
7355 }
7356 }
7357
7358 switch (ch)
7359 {
7360 case '+':
7361 if (remote_debug)
0f71a2f6 7362 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 7363 return 1;
1216fa2c
AC
7364 case '-':
7365 if (remote_debug)
7366 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 7367 /* FALLTHROUGH */
c906108c 7368 case SERIAL_TIMEOUT:
c5aa993b 7369 tcount++;
c906108c
SS
7370 if (tcount > 3)
7371 return 0;
23860348 7372 break; /* Retransmit buffer. */
c906108c
SS
7373 case '$':
7374 {
40e3f985 7375 if (remote_debug)
2bc416ba 7376 fprintf_unfiltered (gdb_stdlog,
23860348 7377 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
7378 /* It's probably an old response sent because an ACK
7379 was lost. Gobble up the packet and ack it so it
7380 doesn't get retransmitted when we resend this
7381 packet. */
6d820c5c 7382 skip_frame ();
c33e31fd 7383 remote_serial_write ("+", 1);
23860348 7384 continue; /* Now, go look for +. */
c906108c 7385 }
74531fed
PA
7386
7387 case '%':
7388 {
7389 int val;
7390
7391 /* If we got a notification, handle it, and go back to looking
7392 for an ack. */
7393 /* We've found the start of a notification. Now
7394 collect the data. */
7395 val = read_frame (&rs->buf, &rs->buf_size);
7396 if (val >= 0)
7397 {
7398 if (remote_debug)
7399 {
6e5abd65
PA
7400 struct cleanup *old_chain;
7401 char *str;
7402
7403 str = escape_buffer (rs->buf, val);
7404 old_chain = make_cleanup (xfree, str);
7405 fprintf_unfiltered (gdb_stdlog,
7406 " Notification received: %s\n",
7407 str);
7408 do_cleanups (old_chain);
74531fed 7409 }
5965e028 7410 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
7411 /* We're in sync now, rewait for the ack. */
7412 tcount = 0;
7413 }
7414 else
7415 {
7416 if (remote_debug)
7417 {
7418 if (!started_error_output)
7419 {
7420 started_error_output = 1;
7421 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7422 }
7423 fputc_unfiltered (ch & 0177, gdb_stdlog);
7424 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7425 }
7426 }
7427 continue;
7428 }
7429 /* fall-through */
c906108c
SS
7430 default:
7431 if (remote_debug)
7432 {
7433 if (!started_error_output)
7434 {
7435 started_error_output = 1;
0f71a2f6 7436 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 7437 }
0f71a2f6 7438 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
7439 }
7440 continue;
7441 }
23860348 7442 break; /* Here to retransmit. */
c906108c
SS
7443 }
7444
7445#if 0
7446 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
7447 able to get out next time we call QUIT, without anything as
7448 violent as interrupt_query. If we want to provide a way out of
7449 here without getting to the next QUIT, it should be based on
7450 hitting ^C twice as in remote_wait. */
c906108c
SS
7451 if (quit_flag)
7452 {
7453 quit_flag = 0;
7454 interrupt_query ();
7455 }
7456#endif
7457 }
a6f3e723 7458 return 0;
c906108c
SS
7459}
7460
6d820c5c
DJ
7461/* Come here after finding the start of a frame when we expected an
7462 ack. Do our best to discard the rest of this packet. */
7463
7464static void
7465skip_frame (void)
7466{
7467 int c;
7468
7469 while (1)
7470 {
7471 c = readchar (remote_timeout);
7472 switch (c)
7473 {
7474 case SERIAL_TIMEOUT:
7475 /* Nothing we can do. */
7476 return;
7477 case '#':
7478 /* Discard the two bytes of checksum and stop. */
7479 c = readchar (remote_timeout);
7480 if (c >= 0)
7481 c = readchar (remote_timeout);
7482
7483 return;
7484 case '*': /* Run length encoding. */
7485 /* Discard the repeat count. */
7486 c = readchar (remote_timeout);
7487 if (c < 0)
7488 return;
7489 break;
7490 default:
7491 /* A regular character. */
7492 break;
7493 }
7494 }
7495}
7496
c906108c 7497/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
7498 into *BUF, verifying the checksum, length, and handling run-length
7499 compression. NUL terminate the buffer. If there is not enough room,
7500 expand *BUF using xrealloc.
c906108c 7501
c2d11a7d
JM
7502 Returns -1 on error, number of characters in buffer (ignoring the
7503 trailing NULL) on success. (could be extended to return one of the
23860348 7504 SERIAL status indications). */
c2d11a7d
JM
7505
7506static long
6d820c5c
DJ
7507read_frame (char **buf_p,
7508 long *sizeof_buf)
c906108c
SS
7509{
7510 unsigned char csum;
c2d11a7d 7511 long bc;
c906108c 7512 int c;
6d820c5c 7513 char *buf = *buf_p;
a6f3e723 7514 struct remote_state *rs = get_remote_state ();
c906108c
SS
7515
7516 csum = 0;
c2d11a7d 7517 bc = 0;
c906108c
SS
7518
7519 while (1)
7520 {
7521 c = readchar (remote_timeout);
c906108c
SS
7522 switch (c)
7523 {
7524 case SERIAL_TIMEOUT:
7525 if (remote_debug)
0f71a2f6 7526 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 7527 return -1;
c906108c
SS
7528 case '$':
7529 if (remote_debug)
0f71a2f6
JM
7530 fputs_filtered ("Saw new packet start in middle of old one\n",
7531 gdb_stdlog);
23860348 7532 return -1; /* Start a new packet, count retries. */
c906108c
SS
7533 case '#':
7534 {
7535 unsigned char pktcsum;
e1b09194
AC
7536 int check_0 = 0;
7537 int check_1 = 0;
c906108c 7538
c2d11a7d 7539 buf[bc] = '\0';
c906108c 7540
e1b09194
AC
7541 check_0 = readchar (remote_timeout);
7542 if (check_0 >= 0)
7543 check_1 = readchar (remote_timeout);
802188a7 7544
e1b09194
AC
7545 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7546 {
7547 if (remote_debug)
2bc416ba 7548 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 7549 gdb_stdlog);
e1b09194
AC
7550 return -1;
7551 }
7552 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
7553 {
7554 if (remote_debug)
2bc416ba 7555 fputs_filtered ("Communication error in checksum\n",
23860348 7556 gdb_stdlog);
40e3f985
FN
7557 return -1;
7558 }
c906108c 7559
a6f3e723
SL
7560 /* Don't recompute the checksum; with no ack packets we
7561 don't have any way to indicate a packet retransmission
7562 is necessary. */
7563 if (rs->noack_mode)
7564 return bc;
7565
e1b09194 7566 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 7567 if (csum == pktcsum)
c2d11a7d 7568 return bc;
c906108c 7569
c5aa993b 7570 if (remote_debug)
c906108c 7571 {
6e5abd65
PA
7572 struct cleanup *old_chain;
7573 char *str;
7574
7575 str = escape_buffer (buf, bc);
7576 old_chain = make_cleanup (xfree, str);
7577 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7578 "Bad checksum, sentsum=0x%x, "
7579 "csum=0x%x, buf=%s\n",
6e5abd65
PA
7580 pktcsum, csum, str);
7581 do_cleanups (old_chain);
c906108c 7582 }
c2d11a7d 7583 /* Number of characters in buffer ignoring trailing
23860348 7584 NULL. */
c2d11a7d 7585 return -1;
c906108c 7586 }
23860348 7587 case '*': /* Run length encoding. */
c2c6d25f
JM
7588 {
7589 int repeat;
c906108c 7590
a744cf53 7591 csum += c;
b4501125
AC
7592 c = readchar (remote_timeout);
7593 csum += c;
23860348 7594 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 7595
23860348 7596 /* The character before ``*'' is repeated. */
c2d11a7d 7597
6d820c5c 7598 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 7599 {
6d820c5c
DJ
7600 if (bc + repeat - 1 >= *sizeof_buf - 1)
7601 {
7602 /* Make some more room in the buffer. */
7603 *sizeof_buf += repeat;
7604 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7605 buf = *buf_p;
7606 }
7607
c2d11a7d
JM
7608 memset (&buf[bc], buf[bc - 1], repeat);
7609 bc += repeat;
c2c6d25f
JM
7610 continue;
7611 }
7612
c2d11a7d 7613 buf[bc] = '\0';
6d820c5c 7614 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 7615 return -1;
c2c6d25f 7616 }
c906108c 7617 default:
6d820c5c 7618 if (bc >= *sizeof_buf - 1)
c906108c 7619 {
6d820c5c
DJ
7620 /* Make some more room in the buffer. */
7621 *sizeof_buf *= 2;
7622 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7623 buf = *buf_p;
c906108c
SS
7624 }
7625
6d820c5c
DJ
7626 buf[bc++] = c;
7627 csum += c;
7628 continue;
c906108c
SS
7629 }
7630 }
7631}
7632
7633/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
7634 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7635 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7636 rather than timing out; this is used (in synchronous mode) to wait
7637 for a target that is is executing user code to stop. */
d9fcf2fb
JM
7638/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7639 don't have to change all the calls to getpkt to deal with the
7640 return value, because at the moment I don't know what the right
23860348 7641 thing to do it for those. */
c906108c 7642void
6d820c5c
DJ
7643getpkt (char **buf,
7644 long *sizeof_buf,
c2d11a7d 7645 int forever)
d9fcf2fb
JM
7646{
7647 int timed_out;
7648
7649 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7650}
7651
7652
7653/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
7654 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7655 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7656 rather than timing out; this is used (in synchronous mode) to wait
7657 for a target that is is executing user code to stop. If FOREVER ==
7658 0, this function is allowed to time out gracefully and return an
74531fed
PA
7659 indication of this to the caller. Otherwise return the number of
7660 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
7661 enough reason to return to the caller. *IS_NOTIF is an output
7662 boolean that indicates whether *BUF holds a notification or not
7663 (a regular packet). */
74531fed 7664
3172dc30 7665static int
74531fed 7666getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 7667 int expecting_notif, int *is_notif)
c906108c 7668{
2d717e4f 7669 struct remote_state *rs = get_remote_state ();
c906108c
SS
7670 int c;
7671 int tries;
7672 int timeout;
df4b58fe 7673 int val = -1;
c906108c 7674
2d717e4f
DJ
7675 /* We're reading a new response. Make sure we don't look at a
7676 previously cached response. */
7677 rs->cached_wait_status = 0;
7678
6d820c5c 7679 strcpy (*buf, "timeout");
c906108c
SS
7680
7681 if (forever)
74531fed
PA
7682 timeout = watchdog > 0 ? watchdog : -1;
7683 else if (expecting_notif)
7684 timeout = 0; /* There should already be a char in the buffer. If
7685 not, bail out. */
c906108c
SS
7686 else
7687 timeout = remote_timeout;
7688
7689#define MAX_TRIES 3
7690
74531fed
PA
7691 /* Process any number of notifications, and then return when
7692 we get a packet. */
7693 for (;;)
c906108c 7694 {
d9c43928 7695 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
7696 times. */
7697 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 7698 {
74531fed
PA
7699 /* This can loop forever if the remote side sends us
7700 characters continuously, but if it pauses, we'll get
7701 SERIAL_TIMEOUT from readchar because of timeout. Then
7702 we'll count that as a retry.
7703
7704 Note that even when forever is set, we will only wait
7705 forever prior to the start of a packet. After that, we
7706 expect characters to arrive at a brisk pace. They should
7707 show up within remote_timeout intervals. */
7708 do
7709 c = readchar (timeout);
7710 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
7711
7712 if (c == SERIAL_TIMEOUT)
7713 {
74531fed
PA
7714 if (expecting_notif)
7715 return -1; /* Don't complain, it's normal to not get
7716 anything in this case. */
7717
23860348 7718 if (forever) /* Watchdog went off? Kill the target. */
c906108c 7719 {
2acceee2 7720 QUIT;
78a095c3 7721 remote_unpush_target ();
598d3636
JK
7722 throw_error (TARGET_CLOSE_ERROR,
7723 _("Watchdog timeout has expired. "
7724 "Target detached."));
c906108c 7725 }
c906108c 7726 if (remote_debug)
0f71a2f6 7727 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 7728 }
74531fed
PA
7729 else
7730 {
7731 /* We've found the start of a packet or notification.
7732 Now collect the data. */
7733 val = read_frame (buf, sizeof_buf);
7734 if (val >= 0)
7735 break;
7736 }
7737
c33e31fd 7738 remote_serial_write ("-", 1);
c906108c 7739 }
c906108c 7740
74531fed
PA
7741 if (tries > MAX_TRIES)
7742 {
7743 /* We have tried hard enough, and just can't receive the
7744 packet/notification. Give up. */
7745 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 7746
74531fed
PA
7747 /* Skip the ack char if we're in no-ack mode. */
7748 if (!rs->noack_mode)
c33e31fd 7749 remote_serial_write ("+", 1);
74531fed
PA
7750 return -1;
7751 }
c906108c 7752
74531fed
PA
7753 /* If we got an ordinary packet, return that to our caller. */
7754 if (c == '$')
c906108c
SS
7755 {
7756 if (remote_debug)
43e526b9 7757 {
6e5abd65
PA
7758 struct cleanup *old_chain;
7759 char *str;
7760
7761 str = escape_buffer (*buf, val);
7762 old_chain = make_cleanup (xfree, str);
7763 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7764 do_cleanups (old_chain);
43e526b9 7765 }
a6f3e723
SL
7766
7767 /* Skip the ack char if we're in no-ack mode. */
7768 if (!rs->noack_mode)
c33e31fd 7769 remote_serial_write ("+", 1);
fee9eda9
YQ
7770 if (is_notif != NULL)
7771 *is_notif = 0;
0876f84a 7772 return val;
c906108c
SS
7773 }
7774
74531fed
PA
7775 /* If we got a notification, handle it, and go back to looking
7776 for a packet. */
7777 else
7778 {
7779 gdb_assert (c == '%');
7780
7781 if (remote_debug)
7782 {
6e5abd65
PA
7783 struct cleanup *old_chain;
7784 char *str;
7785
7786 str = escape_buffer (*buf, val);
7787 old_chain = make_cleanup (xfree, str);
7788 fprintf_unfiltered (gdb_stdlog,
7789 " Notification received: %s\n",
7790 str);
7791 do_cleanups (old_chain);
74531fed 7792 }
fee9eda9
YQ
7793 if (is_notif != NULL)
7794 *is_notif = 1;
c906108c 7795
5965e028 7796 handle_notification (rs->notif_state, *buf);
c906108c 7797
74531fed 7798 /* Notifications require no acknowledgement. */
a6f3e723 7799
74531fed 7800 if (expecting_notif)
fee9eda9 7801 return val;
74531fed
PA
7802 }
7803 }
7804}
7805
7806static int
7807getpkt_sane (char **buf, long *sizeof_buf, int forever)
7808{
fee9eda9 7809 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
7810}
7811
7812static int
fee9eda9
YQ
7813getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
7814 int *is_notif)
74531fed 7815{
fee9eda9
YQ
7816 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
7817 is_notif);
c906108c 7818}
74531fed 7819
c906108c
SS
7820\f
7821static void
7d85a9c0 7822remote_kill (struct target_ops *ops)
43ff13b4 7823{
c90a6fb7 7824 volatile struct gdb_exception ex;
0fdf84ca
PA
7825
7826 /* Catch errors so the user can quit from gdb even when we
23860348 7827 aren't on speaking terms with the remote system. */
0fdf84ca
PA
7828 TRY_CATCH (ex, RETURN_MASK_ERROR)
7829 {
7830 putpkt ("k");
7831 }
7832 if (ex.reason < 0)
7833 {
7834 if (ex.error == TARGET_CLOSE_ERROR)
7835 {
7836 /* If we got an (EOF) error that caused the target
7837 to go away, then we're done, that's what we wanted.
7838 "k" is susceptible to cause a premature EOF, given
7839 that the remote server isn't actually required to
7840 reply to "k", and it can happen that it doesn't
7841 even get to reply ACK to the "k". */
7842 return;
7843 }
7844
7845 /* Otherwise, something went wrong. We didn't actually kill
7846 the target. Just propagate the exception, and let the
7847 user or higher layers decide what to do. */
7848 throw_exception (ex);
7849 }
43ff13b4 7850
0fdf84ca
PA
7851 /* We've killed the remote end, we get to mourn it. Since this is
7852 target remote, single-process, mourning the inferior also
7853 unpushes remote_ops. */
43ff13b4
JM
7854 target_mourn_inferior ();
7855}
7856
82f73884
PA
7857static int
7858remote_vkill (int pid, struct remote_state *rs)
7859{
7860 if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7861 return -1;
7862
7863 /* Tell the remote target to detach. */
bba74b36 7864 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
7865 putpkt (rs->buf);
7866 getpkt (&rs->buf, &rs->buf_size, 0);
7867
7868 if (packet_ok (rs->buf,
7869 &remote_protocol_packets[PACKET_vKill]) == PACKET_OK)
7870 return 0;
7871 else if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7872 return -1;
7873 else
7874 return 1;
7875}
7876
7877static void
7d85a9c0 7878extended_remote_kill (struct target_ops *ops)
82f73884
PA
7879{
7880 int res;
7881 int pid = ptid_get_pid (inferior_ptid);
7882 struct remote_state *rs = get_remote_state ();
7883
7884 res = remote_vkill (pid, rs);
901f9912 7885 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
82f73884
PA
7886 {
7887 /* Don't try 'k' on a multi-process aware stub -- it has no way
7888 to specify the pid. */
7889
7890 putpkt ("k");
7891#if 0
7892 getpkt (&rs->buf, &rs->buf_size, 0);
7893 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7894 res = 1;
7895#else
7896 /* Don't wait for it to die. I'm not really sure it matters whether
7897 we do or not. For the existing stubs, kill is a noop. */
7898 res = 0;
7899#endif
7900 }
7901
7902 if (res != 0)
7903 error (_("Can't kill process"));
7904
82f73884
PA
7905 target_mourn_inferior ();
7906}
7907
c906108c 7908static void
136d6dae 7909remote_mourn (struct target_ops *ops)
c906108c 7910{
136d6dae 7911 remote_mourn_1 (ops);
c906108c
SS
7912}
7913
c906108c
SS
7914/* Worker function for remote_mourn. */
7915static void
fba45db2 7916remote_mourn_1 (struct target_ops *target)
c906108c
SS
7917{
7918 unpush_target (target);
ce5ce7ed 7919
8a2492ee
PA
7920 /* remote_close takes care of doing most of the clean up. */
7921 generic_mourn_inferior ();
c906108c
SS
7922}
7923
2d717e4f
DJ
7924static void
7925extended_remote_mourn_1 (struct target_ops *target)
7926{
7927 struct remote_state *rs = get_remote_state ();
c906108c 7928
e24a49d8
PA
7929 /* In case we got here due to an error, but we're going to stay
7930 connected. */
7931 rs->waiting_for_stop_reply = 0;
7932
dc1981d7
PA
7933 /* If the current general thread belonged to the process we just
7934 detached from or has exited, the remote side current general
7935 thread becomes undefined. Considering a case like this:
7936
7937 - We just got here due to a detach.
7938 - The process that we're detaching from happens to immediately
7939 report a global breakpoint being hit in non-stop mode, in the
7940 same thread we had selected before.
7941 - GDB attaches to this process again.
7942 - This event happens to be the next event we handle.
7943
7944 GDB would consider that the current general thread didn't need to
7945 be set on the stub side (with Hg), since for all it knew,
7946 GENERAL_THREAD hadn't changed.
7947
7948 Notice that although in all-stop mode, the remote server always
7949 sets the current thread to the thread reporting the stop event,
7950 that doesn't happen in non-stop mode; in non-stop, the stub *must
7951 not* change the current thread when reporting a breakpoint hit,
7952 due to the decoupling of event reporting and event handling.
7953
7954 To keep things simple, we always invalidate our notion of the
7955 current thread. */
47f8a51d 7956 record_currthread (rs, minus_one_ptid);
dc1981d7 7957
2d717e4f
DJ
7958 /* Unlike "target remote", we do not want to unpush the target; then
7959 the next time the user says "run", we won't be connected. */
7960
48aa3c27
PA
7961 /* Call common code to mark the inferior as not running. */
7962 generic_mourn_inferior ();
7963
d729566a 7964 if (!have_inferiors ())
2d717e4f 7965 {
82f73884
PA
7966 if (!remote_multi_process_p (rs))
7967 {
7968 /* Check whether the target is running now - some remote stubs
7969 automatically restart after kill. */
7970 putpkt ("?");
7971 getpkt (&rs->buf, &rs->buf_size, 0);
7972
7973 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7974 {
3e43a32a
MS
7975 /* Assume that the target has been restarted. Set
7976 inferior_ptid so that bits of core GDB realizes
7977 there's something here, e.g., so that the user can
7978 say "kill" again. */
82f73884
PA
7979 inferior_ptid = magic_null_ptid;
7980 }
82f73884 7981 }
2d717e4f
DJ
7982 }
7983}
c906108c
SS
7984
7985static void
136d6dae 7986extended_remote_mourn (struct target_ops *ops)
c906108c 7987{
136d6dae 7988 extended_remote_mourn_1 (ops);
2d717e4f 7989}
c906108c 7990
03583c20 7991static int
2bfc0540 7992extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
7993{
7994 return (remote_protocol_packets[PACKET_QDisableRandomization].support
7995 == PACKET_ENABLE);
7996}
7997
7998static void
7999extended_remote_disable_randomization (int val)
8000{
8001 struct remote_state *rs = get_remote_state ();
8002 char *reply;
8003
bba74b36
YQ
8004 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8005 val);
03583c20
UW
8006 putpkt (rs->buf);
8007 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8008 if (*reply == '\0')
8009 error (_("Target does not support QDisableRandomization."));
8010 if (strcmp (reply, "OK") != 0)
8011 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8012}
8013
2d717e4f
DJ
8014static int
8015extended_remote_run (char *args)
8016{
8017 struct remote_state *rs = get_remote_state ();
2d717e4f 8018 int len;
c906108c 8019
2d717e4f
DJ
8020 /* If the user has disabled vRun support, or we have detected that
8021 support is not available, do not try it. */
8022 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
8023 return -1;
424163ea 8024
2d717e4f
DJ
8025 strcpy (rs->buf, "vRun;");
8026 len = strlen (rs->buf);
c906108c 8027
2d717e4f
DJ
8028 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8029 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
8030 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8031 strlen (remote_exec_file));
2d717e4f 8032
d1a41061 8033 gdb_assert (args != NULL);
2d717e4f
DJ
8034 if (*args)
8035 {
8036 struct cleanup *back_to;
8037 int i;
8038 char **argv;
8039
d1a41061 8040 argv = gdb_buildargv (args);
2d717e4f
DJ
8041 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
8042 for (i = 0; argv[i] != NULL; i++)
8043 {
8044 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8045 error (_("Argument list too long for run packet"));
8046 rs->buf[len++] = ';';
9f1b45b0
TT
8047 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8048 strlen (argv[i]));
2d717e4f
DJ
8049 }
8050 do_cleanups (back_to);
8051 }
8052
8053 rs->buf[len++] = '\0';
8054
8055 putpkt (rs->buf);
8056 getpkt (&rs->buf, &rs->buf_size, 0);
8057
8058 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
8059 {
3405876a 8060 /* We have a wait response. All is well. */
2d717e4f
DJ
8061 return 0;
8062 }
8063 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
8064 /* It wasn't disabled before, but it is now. */
8065 return -1;
8066 else
8067 {
8068 if (remote_exec_file[0] == '\0')
8069 error (_("Running the default executable on the remote target failed; "
8070 "try \"set remote exec-file\"?"));
8071 else
8072 error (_("Running \"%s\" on the remote target failed"),
8073 remote_exec_file);
8074 }
c906108c
SS
8075}
8076
2d717e4f
DJ
8077/* In the extended protocol we want to be able to do things like
8078 "run" and have them basically work as expected. So we need
8079 a special create_inferior function. We support changing the
8080 executable file and the command line arguments, but not the
8081 environment. */
8082
43ff13b4 8083static void
77a19445
TT
8084extended_remote_create_inferior (struct target_ops *ops,
8085 char *exec_file, char *args,
8086 char **env, int from_tty)
43ff13b4 8087{
3405876a
PA
8088 int run_worked;
8089 char *stop_reply;
8090 struct remote_state *rs = get_remote_state ();
8091
43ff13b4 8092 /* If running asynchronously, register the target file descriptor
23860348 8093 with the event loop. */
75c99385 8094 if (target_can_async_p ())
2acceee2 8095 target_async (inferior_event_handler, 0);
43ff13b4 8096
03583c20 8097 /* Disable address space randomization if requested (and supported). */
2bfc0540 8098 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
8099 extended_remote_disable_randomization (disable_randomization);
8100
43ff13b4 8101 /* Now restart the remote server. */
3405876a
PA
8102 run_worked = extended_remote_run (args) != -1;
8103 if (!run_worked)
2d717e4f
DJ
8104 {
8105 /* vRun was not supported. Fail if we need it to do what the
8106 user requested. */
8107 if (remote_exec_file[0])
8108 error (_("Remote target does not support \"set remote exec-file\""));
8109 if (args[0])
8110 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 8111
2d717e4f
DJ
8112 /* Fall back to "R". */
8113 extended_remote_restart ();
8114 }
424163ea 8115
6c95b8df
PA
8116 if (!have_inferiors ())
8117 {
8118 /* Clean up from the last time we ran, before we mark the target
8119 running again. This will mark breakpoints uninserted, and
8120 get_offsets may insert breakpoints. */
8121 init_thread_list ();
8122 init_wait_for_inferior ();
8123 }
45280a52 8124
3405876a
PA
8125 /* vRun's success return is a stop reply. */
8126 stop_reply = run_worked ? rs->buf : NULL;
8127 add_current_inferior_and_thread (stop_reply);
c0a2216e 8128
2d717e4f
DJ
8129 /* Get updated offsets, if the stub uses qOffsets. */
8130 get_offsets ();
2d717e4f 8131}
c906108c 8132\f
c5aa993b 8133
b775012e
LM
8134/* Given a location's target info BP_TGT and the packet buffer BUF, output
8135 the list of conditions (in agent expression bytecode format), if any, the
8136 target needs to evaluate. The output is placed into the packet buffer
bba74b36 8137 started from BUF and ended at BUF_END. */
b775012e
LM
8138
8139static int
8140remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
8141 struct bp_target_info *bp_tgt, char *buf,
8142 char *buf_end)
b775012e
LM
8143{
8144 struct agent_expr *aexpr = NULL;
8145 int i, ix;
8146 char *pkt;
8147 char *buf_start = buf;
8148
8149 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8150 return 0;
8151
8152 buf += strlen (buf);
bba74b36 8153 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
8154 buf++;
8155
8156 /* Send conditions to the target and free the vector. */
8157 for (ix = 0;
8158 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8159 ix++)
8160 {
bba74b36 8161 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
8162 buf += strlen (buf);
8163 for (i = 0; i < aexpr->len; ++i)
8164 buf = pack_hex_byte (buf, aexpr->buf[i]);
8165 *buf = '\0';
8166 }
b775012e
LM
8167 return 0;
8168}
8169
d3ce09f5
SS
8170static void
8171remote_add_target_side_commands (struct gdbarch *gdbarch,
8172 struct bp_target_info *bp_tgt, char *buf)
8173{
8174 struct agent_expr *aexpr = NULL;
8175 int i, ix;
8176
8177 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8178 return;
8179
8180 buf += strlen (buf);
8181
8182 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8183 buf += strlen (buf);
8184
8185 /* Concatenate all the agent expressions that are commands into the
8186 cmds parameter. */
8187 for (ix = 0;
8188 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8189 ix++)
8190 {
8191 sprintf (buf, "X%x,", aexpr->len);
8192 buf += strlen (buf);
8193 for (i = 0; i < aexpr->len; ++i)
8194 buf = pack_hex_byte (buf, aexpr->buf[i]);
8195 *buf = '\0';
8196 }
d3ce09f5
SS
8197}
8198
8181d85f
DJ
8199/* Insert a breakpoint. On targets that have software breakpoint
8200 support, we ask the remote target to do the work; on targets
8201 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
8202
8203static int
3db08215
MM
8204remote_insert_breakpoint (struct target_ops *ops,
8205 struct gdbarch *gdbarch,
a6d9a66e 8206 struct bp_target_info *bp_tgt)
c906108c 8207{
d471ea57
AC
8208 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8209 If it succeeds, then set the support to PACKET_ENABLE. If it
8210 fails, and the user has explicitly requested the Z support then
23860348 8211 report an error, otherwise, mark it disabled and go on. */
802188a7 8212
444abaca 8213 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
96baa820 8214 {
7c0f6dcc 8215 CORE_ADDR addr = bp_tgt->placed_address;
4fff2411 8216 struct remote_state *rs;
bba74b36 8217 char *p, *endbuf;
7c0f6dcc 8218 int bpsize;
b775012e 8219 struct condition_list *cond = NULL;
4fff2411 8220
28439a30
PA
8221 /* Make sure the remote is pointing at the right process, if
8222 necessary. */
8223 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8224 set_general_process ();
8225
a1dcb23a 8226 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
8227
8228 rs = get_remote_state ();
8229 p = rs->buf;
bba74b36 8230 endbuf = rs->buf + get_remote_packet_size ();
802188a7 8231
96baa820
JM
8232 *(p++) = 'Z';
8233 *(p++) = '0';
8234 *(p++) = ',';
7c0f6dcc 8235 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 8236 p += hexnumstr (p, addr);
bba74b36 8237 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 8238
efcc2da7 8239 if (remote_supports_cond_breakpoints (ops))
bba74b36 8240 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8241
78eff0ec 8242 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
8243 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8244
6d820c5c
DJ
8245 putpkt (rs->buf);
8246 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8247
6d820c5c 8248 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 8249 {
d471ea57
AC
8250 case PACKET_ERROR:
8251 return -1;
8252 case PACKET_OK:
7c0f6dcc
JL
8253 bp_tgt->placed_address = addr;
8254 bp_tgt->placed_size = bpsize;
d471ea57
AC
8255 return 0;
8256 case PACKET_UNKNOWN:
8257 break;
96baa820
JM
8258 }
8259 }
c906108c 8260
0000e5cc
PA
8261 /* If this breakpoint has target-side commands but this stub doesn't
8262 support Z0 packets, throw error. */
8263 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8264 throw_error (NOT_SUPPORTED_ERROR, _("\
8265Target doesn't support breakpoints that have target side commands."));
8266
3db08215 8267 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8268}
8269
8270static int
3db08215
MM
8271remote_remove_breakpoint (struct target_ops *ops,
8272 struct gdbarch *gdbarch,
a6d9a66e 8273 struct bp_target_info *bp_tgt)
c906108c 8274{
8181d85f 8275 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 8276 struct remote_state *rs = get_remote_state ();
96baa820 8277
444abaca 8278 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
96baa820 8279 {
6d820c5c 8280 char *p = rs->buf;
bba74b36 8281 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 8282
28439a30
PA
8283 /* Make sure the remote is pointing at the right process, if
8284 necessary. */
8285 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8286 set_general_process ();
8287
96baa820
JM
8288 *(p++) = 'z';
8289 *(p++) = '0';
8290 *(p++) = ',';
8291
8181d85f
DJ
8292 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8293 p += hexnumstr (p, addr);
bba74b36 8294 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 8295
6d820c5c
DJ
8296 putpkt (rs->buf);
8297 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8298
6d820c5c 8299 return (rs->buf[0] == 'E');
96baa820
JM
8300 }
8301
3db08215 8302 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8303}
8304
d471ea57
AC
8305static int
8306watchpoint_to_Z_packet (int type)
8307{
8308 switch (type)
8309 {
8310 case hw_write:
bb858e6a 8311 return Z_PACKET_WRITE_WP;
d471ea57
AC
8312 break;
8313 case hw_read:
bb858e6a 8314 return Z_PACKET_READ_WP;
d471ea57
AC
8315 break;
8316 case hw_access:
bb858e6a 8317 return Z_PACKET_ACCESS_WP;
d471ea57
AC
8318 break;
8319 default:
8e65ff28 8320 internal_error (__FILE__, __LINE__,
e2e0b3e5 8321 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
8322 }
8323}
8324
3c3bea1c 8325static int
7bb99c53
TT
8326remote_insert_watchpoint (struct target_ops *self,
8327 CORE_ADDR addr, int len, int type,
0cf6dd15 8328 struct expression *cond)
96baa820 8329{
d01949b6 8330 struct remote_state *rs = get_remote_state ();
bba74b36 8331 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8332 char *p;
d471ea57 8333 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 8334
444abaca 8335 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
85d721b8 8336 return 1;
802188a7 8337
28439a30
PA
8338 /* Make sure the remote is pointing at the right process, if
8339 necessary. */
8340 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8341 set_general_process ();
8342
bba74b36 8343 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 8344 p = strchr (rs->buf, '\0');
96baa820
JM
8345 addr = remote_address_masked (addr);
8346 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8347 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 8348
6d820c5c
DJ
8349 putpkt (rs->buf);
8350 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8351
6d820c5c 8352 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8353 {
8354 case PACKET_ERROR:
d471ea57 8355 return -1;
85d721b8
PA
8356 case PACKET_UNKNOWN:
8357 return 1;
d471ea57
AC
8358 case PACKET_OK:
8359 return 0;
8360 }
8e65ff28 8361 internal_error (__FILE__, __LINE__,
e2e0b3e5 8362 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
8363}
8364
283002cf
MR
8365static int
8366remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8367 CORE_ADDR start, int length)
8368{
8369 CORE_ADDR diff = remote_address_masked (addr - start);
8370
8371 return diff < length;
8372}
8373
d471ea57 8374
3c3bea1c 8375static int
11b5219a
TT
8376remote_remove_watchpoint (struct target_ops *self,
8377 CORE_ADDR addr, int len, int type,
0cf6dd15 8378 struct expression *cond)
96baa820 8379{
d01949b6 8380 struct remote_state *rs = get_remote_state ();
bba74b36 8381 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8382 char *p;
d471ea57
AC
8383 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8384
444abaca 8385 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
5cffb350 8386 return -1;
802188a7 8387
28439a30
PA
8388 /* Make sure the remote is pointing at the right process, if
8389 necessary. */
8390 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8391 set_general_process ();
8392
bba74b36 8393 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 8394 p = strchr (rs->buf, '\0');
96baa820
JM
8395 addr = remote_address_masked (addr);
8396 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8397 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
8398 putpkt (rs->buf);
8399 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8400
6d820c5c 8401 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8402 {
8403 case PACKET_ERROR:
8404 case PACKET_UNKNOWN:
8405 return -1;
8406 case PACKET_OK:
8407 return 0;
8408 }
8e65ff28 8409 internal_error (__FILE__, __LINE__,
e2e0b3e5 8410 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
8411}
8412
3c3bea1c 8413
501eef12 8414int remote_hw_watchpoint_limit = -1;
480a3f21 8415int remote_hw_watchpoint_length_limit = -1;
501eef12 8416int remote_hw_breakpoint_limit = -1;
d471ea57 8417
480a3f21 8418static int
31568a15
TT
8419remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8420 CORE_ADDR addr, int len)
480a3f21
PW
8421{
8422 if (remote_hw_watchpoint_length_limit == 0)
8423 return 0;
8424 else if (remote_hw_watchpoint_length_limit < 0)
8425 return 1;
8426 else if (len <= remote_hw_watchpoint_length_limit)
8427 return 1;
8428 else
8429 return 0;
8430}
8431
b9362cc7 8432static int
5461485a
TT
8433remote_check_watch_resources (struct target_ops *self,
8434 int type, int cnt, int ot)
96baa820 8435{
3c3bea1c
GS
8436 if (type == bp_hardware_breakpoint)
8437 {
8438 if (remote_hw_breakpoint_limit == 0)
8439 return 0;
501eef12
AC
8440 else if (remote_hw_breakpoint_limit < 0)
8441 return 1;
3c3bea1c
GS
8442 else if (cnt <= remote_hw_breakpoint_limit)
8443 return 1;
8444 }
8445 else
8446 {
8447 if (remote_hw_watchpoint_limit == 0)
8448 return 0;
501eef12
AC
8449 else if (remote_hw_watchpoint_limit < 0)
8450 return 1;
3c3bea1c
GS
8451 else if (ot)
8452 return -1;
8453 else if (cnt <= remote_hw_watchpoint_limit)
8454 return 1;
8455 }
8456 return -1;
8457}
8458
b9362cc7 8459static int
6a109b6b 8460remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 8461{
ee154bee
TT
8462 struct remote_state *rs = get_remote_state ();
8463
8464 return rs->remote_stopped_by_watchpoint_p;
3c3bea1c
GS
8465}
8466
4aa7a7f5
JJ
8467static int
8468remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 8469{
ee154bee 8470 struct remote_state *rs = get_remote_state ();
4aa7a7f5 8471 int rc = 0;
a744cf53 8472
6a109b6b 8473 if (remote_stopped_by_watchpoint (target))
4aa7a7f5 8474 {
ee154bee 8475 *addr_p = rs->remote_watch_data_address;
4aa7a7f5
JJ
8476 rc = 1;
8477 }
8478
8479 return rc;
3c3bea1c
GS
8480}
8481
8482
8483static int
23a26771 8484remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 8485 struct bp_target_info *bp_tgt)
3c3bea1c 8486{
8181d85f 8487 CORE_ADDR addr;
4fff2411 8488 struct remote_state *rs;
bba74b36 8489 char *p, *endbuf;
dd61ec5c 8490 char *message;
802188a7 8491
c8189ed1 8492 /* The length field should be set to the size of a breakpoint
8181d85f 8493 instruction, even though we aren't inserting one ourselves. */
c8189ed1 8494
a1dcb23a 8495 gdbarch_remote_breakpoint_from_pc
a6d9a66e 8496 (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
3c3bea1c 8497
444abaca 8498 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5cffb350 8499 return -1;
2bc416ba 8500
28439a30
PA
8501 /* Make sure the remote is pointing at the right process, if
8502 necessary. */
8503 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8504 set_general_process ();
8505
4fff2411
JZ
8506 rs = get_remote_state ();
8507 p = rs->buf;
bba74b36 8508 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 8509
96baa820
JM
8510 *(p++) = 'Z';
8511 *(p++) = '1';
8512 *(p++) = ',';
802188a7 8513
8181d85f 8514 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 8515 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8516 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 8517
efcc2da7 8518 if (remote_supports_cond_breakpoints (self))
bba74b36 8519 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8520
78eff0ec 8521 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
8522 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8523
6d820c5c
DJ
8524 putpkt (rs->buf);
8525 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8526
6d820c5c 8527 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
8528 {
8529 case PACKET_ERROR:
dd61ec5c
MW
8530 if (rs->buf[1] == '.')
8531 {
8532 message = strchr (rs->buf + 2, '.');
8533 if (message)
0316657e 8534 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
8535 }
8536 return -1;
d471ea57
AC
8537 case PACKET_UNKNOWN:
8538 return -1;
8539 case PACKET_OK:
8540 return 0;
8541 }
8e65ff28 8542 internal_error (__FILE__, __LINE__,
e2e0b3e5 8543 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
8544}
8545
d471ea57 8546
802188a7 8547static int
a64dc96c 8548remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 8549 struct bp_target_info *bp_tgt)
96baa820 8550{
8181d85f 8551 CORE_ADDR addr;
d01949b6 8552 struct remote_state *rs = get_remote_state ();
6d820c5c 8553 char *p = rs->buf;
bba74b36 8554 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 8555
444abaca 8556 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5cffb350 8557 return -1;
802188a7 8558
28439a30
PA
8559 /* Make sure the remote is pointing at the right process, if
8560 necessary. */
8561 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8562 set_general_process ();
8563
96baa820
JM
8564 *(p++) = 'z';
8565 *(p++) = '1';
8566 *(p++) = ',';
802188a7 8567
8181d85f 8568 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 8569 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8570 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 8571
6d820c5c
DJ
8572 putpkt (rs->buf);
8573 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 8574
6d820c5c 8575 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
8576 {
8577 case PACKET_ERROR:
8578 case PACKET_UNKNOWN:
8579 return -1;
8580 case PACKET_OK:
8581 return 0;
8582 }
8e65ff28 8583 internal_error (__FILE__, __LINE__,
e2e0b3e5 8584 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 8585}
96baa820 8586
4a5e7a5b
PA
8587/* Verify memory using the "qCRC:" request. */
8588
8589static int
8590remote_verify_memory (struct target_ops *ops,
8591 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8592{
8593 struct remote_state *rs = get_remote_state ();
8594 unsigned long host_crc, target_crc;
8595 char *tmp;
8596
28439a30
PA
8597 /* Make sure the remote is pointing at the right process. */
8598 set_general_process ();
8599
4a5e7a5b
PA
8600 /* FIXME: assumes lma can fit into long. */
8601 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8602 (long) lma, (long) size);
8603 putpkt (rs->buf);
8604
8605 /* Be clever; compute the host_crc before waiting for target
8606 reply. */
85ec6ce7 8607 host_crc = xcrc32 (data, size, 0xffffffff);
4a5e7a5b
PA
8608
8609 getpkt (&rs->buf, &rs->buf_size, 0);
8610 if (rs->buf[0] == 'E')
8611 return -1;
8612
8613 if (rs->buf[0] != 'C')
8614 error (_("remote target does not support this operation"));
8615
8616 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8617 target_crc = target_crc * 16 + fromhex (*tmp);
8618
8619 return (host_crc == target_crc);
8620}
8621
c906108c
SS
8622/* compare-sections command
8623
8624 With no arguments, compares each loadable section in the exec bfd
8625 with the same memory range on the target, and reports mismatches.
4a5e7a5b 8626 Useful for verifying the image on the target against the exec file. */
e514a9d6 8627
c906108c 8628static void
fba45db2 8629compare_sections_command (char *args, int from_tty)
c906108c
SS
8630{
8631 asection *s;
c906108c 8632 struct cleanup *old_chain;
948f8e3d 8633 gdb_byte *sectdata;
ce359b09 8634 const char *sectname;
c906108c
SS
8635 bfd_size_type size;
8636 bfd_vma lma;
8637 int matched = 0;
8638 int mismatched = 0;
4a5e7a5b 8639 int res;
c906108c
SS
8640
8641 if (!exec_bfd)
8a3fe4f8 8642 error (_("command cannot be used without an exec file"));
c906108c 8643
28439a30
PA
8644 /* Make sure the remote is pointing at the right process. */
8645 set_general_process ();
8646
c5aa993b 8647 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
8648 {
8649 if (!(s->flags & SEC_LOAD))
0df8b418 8650 continue; /* Skip non-loadable section. */
c906108c 8651
2c500098 8652 size = bfd_get_section_size (s);
c906108c 8653 if (size == 0)
0df8b418 8654 continue; /* Skip zero-length section. */
c906108c 8655
ce359b09 8656 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 8657 if (args && strcmp (args, sectname) != 0)
0df8b418 8658 continue; /* Not the section selected by user. */
c906108c 8659
0df8b418 8660 matched = 1; /* Do this section. */
c906108c 8661 lma = s->lma;
c906108c 8662
c906108c 8663 sectdata = xmalloc (size);
b8c9b27d 8664 old_chain = make_cleanup (xfree, sectdata);
c906108c 8665 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 8666
4a5e7a5b
PA
8667 res = target_verify_memory (sectdata, lma, size);
8668
8669 if (res == -1)
5af949e3 8670 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
8671 paddress (target_gdbarch (), lma),
8672 paddress (target_gdbarch (), lma + size));
c906108c 8673
5af949e3 8674 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
8675 paddress (target_gdbarch (), lma),
8676 paddress (target_gdbarch (), lma + size));
4a5e7a5b 8677 if (res)
c906108c
SS
8678 printf_filtered ("matched.\n");
8679 else
c5aa993b
JM
8680 {
8681 printf_filtered ("MIS-MATCHED!\n");
8682 mismatched++;
8683 }
c906108c
SS
8684
8685 do_cleanups (old_chain);
8686 }
8687 if (mismatched > 0)
8a3fe4f8
AC
8688 warning (_("One or more sections of the remote executable does not match\n\
8689the loaded file\n"));
c906108c 8690 if (args && !matched)
a3f17187 8691 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
8692}
8693
0e7f50da
UW
8694/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8695 into remote target. The number of bytes written to the remote
8696 target is returned, or -1 for error. */
8697
9b409511 8698static enum target_xfer_status
0e7f50da
UW
8699remote_write_qxfer (struct target_ops *ops, const char *object_name,
8700 const char *annex, const gdb_byte *writebuf,
9b409511 8701 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
8702 struct packet_config *packet)
8703{
8704 int i, buf_len;
8705 ULONGEST n;
0e7f50da
UW
8706 struct remote_state *rs = get_remote_state ();
8707 int max_size = get_memory_write_packet_size ();
8708
8709 if (packet->support == PACKET_DISABLE)
2ed4b548 8710 return TARGET_XFER_E_IO;
0e7f50da
UW
8711
8712 /* Insert header. */
8713 i = snprintf (rs->buf, max_size,
8714 "qXfer:%s:write:%s:%s:",
8715 object_name, annex ? annex : "",
8716 phex_nz (offset, sizeof offset));
8717 max_size -= (i + 1);
8718
8719 /* Escape as much data as fits into rs->buf. */
8720 buf_len = remote_escape_output
bc20a4af 8721 (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
8722
8723 if (putpkt_binary (rs->buf, i + buf_len) < 0
8724 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8725 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 8726 return TARGET_XFER_E_IO;
0e7f50da
UW
8727
8728 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
8729
8730 *xfered_len = n;
8731 return TARGET_XFER_OK;
0e7f50da
UW
8732}
8733
0876f84a
DJ
8734/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8735 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8736 number of bytes read is returned, or 0 for EOF, or -1 for error.
8737 The number of bytes read may be less than LEN without indicating an
8738 EOF. PACKET is checked and updated to indicate whether the remote
8739 target supports this object. */
8740
9b409511 8741static enum target_xfer_status
0876f84a
DJ
8742remote_read_qxfer (struct target_ops *ops, const char *object_name,
8743 const char *annex,
8744 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 8745 ULONGEST *xfered_len,
0876f84a
DJ
8746 struct packet_config *packet)
8747{
0876f84a 8748 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
8749 LONGEST i, n, packet_len;
8750
8751 if (packet->support == PACKET_DISABLE)
2ed4b548 8752 return TARGET_XFER_E_IO;
0876f84a
DJ
8753
8754 /* Check whether we've cached an end-of-object packet that matches
8755 this request. */
8e88304f 8756 if (rs->finished_object)
0876f84a 8757 {
8e88304f
TT
8758 if (strcmp (object_name, rs->finished_object) == 0
8759 && strcmp (annex ? annex : "", rs->finished_annex) == 0
8760 && offset == rs->finished_offset)
9b409511
YQ
8761 return TARGET_XFER_EOF;
8762
0876f84a
DJ
8763
8764 /* Otherwise, we're now reading something different. Discard
8765 the cache. */
8e88304f
TT
8766 xfree (rs->finished_object);
8767 xfree (rs->finished_annex);
8768 rs->finished_object = NULL;
8769 rs->finished_annex = NULL;
0876f84a
DJ
8770 }
8771
8772 /* Request only enough to fit in a single packet. The actual data
8773 may not, since we don't know how much of it will need to be escaped;
8774 the target is free to respond with slightly less data. We subtract
8775 five to account for the response type and the protocol frame. */
8776 n = min (get_remote_packet_size () - 5, len);
8777 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8778 object_name, annex ? annex : "",
8779 phex_nz (offset, sizeof offset),
8780 phex_nz (n, sizeof n));
8781 i = putpkt (rs->buf);
8782 if (i < 0)
2ed4b548 8783 return TARGET_XFER_E_IO;
0876f84a
DJ
8784
8785 rs->buf[0] = '\0';
8786 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8787 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 8788 return TARGET_XFER_E_IO;
0876f84a
DJ
8789
8790 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8791 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8792
8793 /* 'm' means there is (or at least might be) more data after this
8794 batch. That does not make sense unless there's at least one byte
8795 of data in this reply. */
8796 if (rs->buf[0] == 'm' && packet_len == 1)
8797 error (_("Remote qXfer reply contained no data."));
8798
8799 /* Got some data. */
bc20a4af
PA
8800 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
8801 packet_len - 1, readbuf, n);
0876f84a
DJ
8802
8803 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
8804 or possibly empty. If we have the final block of a non-empty
8805 object, record this fact to bypass a subsequent partial read. */
8806 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 8807 {
8e88304f
TT
8808 rs->finished_object = xstrdup (object_name);
8809 rs->finished_annex = xstrdup (annex ? annex : "");
8810 rs->finished_offset = offset + i;
0876f84a
DJ
8811 }
8812
9b409511
YQ
8813 if (i == 0)
8814 return TARGET_XFER_EOF;
8815 else
8816 {
8817 *xfered_len = i;
8818 return TARGET_XFER_OK;
8819 }
0876f84a
DJ
8820}
8821
9b409511 8822static enum target_xfer_status
4b8a223f 8823remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 8824 const char *annex, gdb_byte *readbuf,
9b409511
YQ
8825 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
8826 ULONGEST *xfered_len)
c906108c 8827{
82f73884 8828 struct remote_state *rs;
c906108c 8829 int i;
6d820c5c 8830 char *p2;
1e3ff5ad 8831 char query_type;
c906108c 8832
e6e4e701 8833 set_remote_traceframe ();
82f73884
PA
8834 set_general_thread (inferior_ptid);
8835
8836 rs = get_remote_state ();
8837
b2182ed2 8838 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
8839 if (object == TARGET_OBJECT_MEMORY)
8840 {
2d717e4f
DJ
8841 /* If the remote target is connected but not running, we should
8842 pass this request down to a lower stratum (e.g. the executable
8843 file). */
8844 if (!target_has_execution)
9b409511 8845 return TARGET_XFER_EOF;
2d717e4f 8846
21e3b9b9 8847 if (writebuf != NULL)
9b409511 8848 return remote_write_bytes (offset, writebuf, len, xfered_len);
21e3b9b9 8849 else
8acf9577 8850 return remote_read_bytes (ops, offset, readbuf, len, xfered_len);
21e3b9b9
DJ
8851 }
8852
0df8b418 8853 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
8854 if (object == TARGET_OBJECT_SPU)
8855 {
8856 if (readbuf)
8857 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
8858 xfered_len, &remote_protocol_packets
8859 [PACKET_qXfer_spu_read]);
0e7f50da
UW
8860 else
8861 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
8862 xfered_len, &remote_protocol_packets
8863 [PACKET_qXfer_spu_write]);
0e7f50da
UW
8864 }
8865
4aa995e1
PA
8866 /* Handle extra signal info using qxfer packets. */
8867 if (object == TARGET_OBJECT_SIGNAL_INFO)
8868 {
8869 if (readbuf)
8870 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 8871 xfered_len, &remote_protocol_packets
4aa995e1
PA
8872 [PACKET_qXfer_siginfo_read]);
8873 else
3e43a32a 8874 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 8875 writebuf, offset, len, xfered_len,
4aa995e1
PA
8876 &remote_protocol_packets
8877 [PACKET_qXfer_siginfo_write]);
8878 }
8879
0fb4aa4b
PA
8880 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8881 {
8882 if (readbuf)
3e43a32a 8883 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 8884 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
8885 &remote_protocol_packets
8886 [PACKET_qXfer_statictrace_read]);
8887 else
2ed4b548 8888 return TARGET_XFER_E_IO;
0fb4aa4b
PA
8889 }
8890
a76d924d
DJ
8891 /* Only handle flash writes. */
8892 if (writebuf != NULL)
8893 {
8894 LONGEST xfered;
8895
8896 switch (object)
8897 {
8898 case TARGET_OBJECT_FLASH:
9b409511
YQ
8899 return remote_flash_write (ops, offset, len, xfered_len,
8900 writebuf);
a76d924d
DJ
8901
8902 default:
2ed4b548 8903 return TARGET_XFER_E_IO;
a76d924d
DJ
8904 }
8905 }
4b8a223f 8906
1e3ff5ad
AC
8907 /* Map pre-existing objects onto letters. DO NOT do this for new
8908 objects!!! Instead specify new query packets. */
8909 switch (object)
c906108c 8910 {
1e3ff5ad
AC
8911 case TARGET_OBJECT_AVR:
8912 query_type = 'R';
8913 break;
802188a7
RM
8914
8915 case TARGET_OBJECT_AUXV:
0876f84a
DJ
8916 gdb_assert (annex == NULL);
8917 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 8918 xfered_len,
0876f84a 8919 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 8920
23181151
DJ
8921 case TARGET_OBJECT_AVAILABLE_FEATURES:
8922 return remote_read_qxfer
9b409511 8923 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
8924 &remote_protocol_packets[PACKET_qXfer_features]);
8925
cfa9d6d9
DJ
8926 case TARGET_OBJECT_LIBRARIES:
8927 return remote_read_qxfer
9b409511 8928 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
8929 &remote_protocol_packets[PACKET_qXfer_libraries]);
8930
2268b414
JK
8931 case TARGET_OBJECT_LIBRARIES_SVR4:
8932 return remote_read_qxfer
9b409511 8933 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
8934 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
8935
fd79ecee
DJ
8936 case TARGET_OBJECT_MEMORY_MAP:
8937 gdb_assert (annex == NULL);
8938 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 8939 xfered_len,
fd79ecee
DJ
8940 &remote_protocol_packets[PACKET_qXfer_memory_map]);
8941
07e059b5
VP
8942 case TARGET_OBJECT_OSDATA:
8943 /* Should only get here if we're connected. */
5d93a237 8944 gdb_assert (rs->remote_desc);
07e059b5 8945 return remote_read_qxfer
9b409511 8946 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
8947 &remote_protocol_packets[PACKET_qXfer_osdata]);
8948
dc146f7c
VP
8949 case TARGET_OBJECT_THREADS:
8950 gdb_assert (annex == NULL);
8951 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 8952 xfered_len,
dc146f7c
VP
8953 &remote_protocol_packets[PACKET_qXfer_threads]);
8954
b3b9301e
PA
8955 case TARGET_OBJECT_TRACEFRAME_INFO:
8956 gdb_assert (annex == NULL);
8957 return remote_read_qxfer
9b409511 8958 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 8959 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
8960
8961 case TARGET_OBJECT_FDPIC:
8962 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 8963 xfered_len,
78d85199 8964 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
8965
8966 case TARGET_OBJECT_OPENVMS_UIB:
8967 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 8968 xfered_len,
169081d0
TG
8969 &remote_protocol_packets[PACKET_qXfer_uib]);
8970
9accd112
MM
8971 case TARGET_OBJECT_BTRACE:
8972 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 8973 xfered_len,
9accd112
MM
8974 &remote_protocol_packets[PACKET_qXfer_btrace]);
8975
1e3ff5ad 8976 default:
2ed4b548 8977 return TARGET_XFER_E_IO;
c906108c
SS
8978 }
8979
4b8a223f 8980 /* Note: a zero OFFSET and LEN can be used to query the minimum
1e3ff5ad 8981 buffer size. */
4b8a223f 8982 if (offset == 0 && len == 0)
ea9c271d 8983 return (get_remote_packet_size ());
0df8b418 8984 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 8985 large enough let the caller deal with it. */
ea9c271d 8986 if (len < get_remote_packet_size ())
2ed4b548 8987 return TARGET_XFER_E_IO;
ea9c271d 8988 len = get_remote_packet_size ();
1e3ff5ad 8989
23860348 8990 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 8991 if (!rs->remote_desc)
8a3fe4f8 8992 error (_("remote query is only available after target open"));
c906108c 8993
1e3ff5ad 8994 gdb_assert (annex != NULL);
4b8a223f 8995 gdb_assert (readbuf != NULL);
c906108c 8996
6d820c5c 8997 p2 = rs->buf;
c906108c
SS
8998 *p2++ = 'q';
8999 *p2++ = query_type;
9000
23860348
MS
9001 /* We used one buffer char for the remote protocol q command and
9002 another for the query type. As the remote protocol encapsulation
9003 uses 4 chars plus one extra in case we are debugging
9004 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9005 string. */
c906108c 9006 i = 0;
ea9c271d 9007 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 9008 {
1e3ff5ad
AC
9009 /* Bad caller may have sent forbidden characters. */
9010 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9011 *p2++ = annex[i];
c906108c
SS
9012 i++;
9013 }
1e3ff5ad
AC
9014 *p2 = '\0';
9015 gdb_assert (annex[i] == '\0');
c906108c 9016
6d820c5c 9017 i = putpkt (rs->buf);
c5aa993b 9018 if (i < 0)
2ed4b548 9019 return TARGET_XFER_E_IO;
c906108c 9020
6d820c5c
DJ
9021 getpkt (&rs->buf, &rs->buf_size, 0);
9022 strcpy ((char *) readbuf, rs->buf);
c906108c 9023
9b409511
YQ
9024 *xfered_len = strlen ((char *) readbuf);
9025 return TARGET_XFER_OK;
c906108c
SS
9026}
9027
08388c79
DE
9028static int
9029remote_search_memory (struct target_ops* ops,
9030 CORE_ADDR start_addr, ULONGEST search_space_len,
9031 const gdb_byte *pattern, ULONGEST pattern_len,
9032 CORE_ADDR *found_addrp)
9033{
f5656ead 9034 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
9035 struct remote_state *rs = get_remote_state ();
9036 int max_size = get_memory_write_packet_size ();
9037 struct packet_config *packet =
9038 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
9039 /* Number of packet bytes used to encode the pattern;
9040 this could be more than PATTERN_LEN due to escape characters. */
08388c79 9041 int escaped_pattern_len;
0df8b418 9042 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
9043 int used_pattern_len;
9044 int i;
9045 int found;
9046 ULONGEST found_addr;
9047
9048 /* Don't go to the target if we don't have to.
9049 This is done before checking packet->support to avoid the possibility that
9050 a success for this edge case means the facility works in general. */
9051 if (pattern_len > search_space_len)
9052 return 0;
9053 if (pattern_len == 0)
9054 {
9055 *found_addrp = start_addr;
9056 return 1;
9057 }
9058
9059 /* If we already know the packet isn't supported, fall back to the simple
9060 way of searching memory. */
9061
9062 if (packet->support == PACKET_DISABLE)
9063 {
9064 /* Target doesn't provided special support, fall back and use the
9065 standard support (copy memory and do the search here). */
9066 return simple_search_memory (ops, start_addr, search_space_len,
9067 pattern, pattern_len, found_addrp);
9068 }
9069
28439a30
PA
9070 /* Make sure the remote is pointing at the right process. */
9071 set_general_process ();
9072
08388c79
DE
9073 /* Insert header. */
9074 i = snprintf (rs->buf, max_size,
9075 "qSearch:memory:%s;%s;",
5af949e3 9076 phex_nz (start_addr, addr_size),
08388c79
DE
9077 phex_nz (search_space_len, sizeof (search_space_len)));
9078 max_size -= (i + 1);
9079
9080 /* Escape as much data as fits into rs->buf. */
9081 escaped_pattern_len =
bc20a4af 9082 remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
08388c79
DE
9083 &used_pattern_len, max_size);
9084
9085 /* Bail if the pattern is too large. */
9086 if (used_pattern_len != pattern_len)
9b20d036 9087 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
9088
9089 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9090 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9091 || packet_ok (rs->buf, packet) != PACKET_OK)
9092 {
9093 /* The request may not have worked because the command is not
9094 supported. If so, fall back to the simple way. */
9095 if (packet->support == PACKET_DISABLE)
9096 {
9097 return simple_search_memory (ops, start_addr, search_space_len,
9098 pattern, pattern_len, found_addrp);
9099 }
9100 return -1;
9101 }
9102
9103 if (rs->buf[0] == '0')
9104 found = 0;
9105 else if (rs->buf[0] == '1')
9106 {
9107 found = 1;
9108 if (rs->buf[1] != ',')
10e0fa18 9109 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9110 unpack_varlen_hex (rs->buf + 2, &found_addr);
9111 *found_addrp = found_addr;
9112 }
9113 else
10e0fa18 9114 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9115
9116 return found;
9117}
9118
96baa820 9119static void
1aac633b 9120remote_rcmd (struct target_ops *self, char *command,
d9fcf2fb 9121 struct ui_file *outbuf)
96baa820 9122{
d01949b6 9123 struct remote_state *rs = get_remote_state ();
2e9f7625 9124 char *p = rs->buf;
96baa820 9125
5d93a237 9126 if (!rs->remote_desc)
8a3fe4f8 9127 error (_("remote rcmd is only available after target open"));
96baa820 9128
23860348 9129 /* Send a NULL command across as an empty command. */
7be570e7
JM
9130 if (command == NULL)
9131 command = "";
9132
23860348 9133 /* The query prefix. */
2e9f7625
DJ
9134 strcpy (rs->buf, "qRcmd,");
9135 p = strchr (rs->buf, '\0');
96baa820 9136
3e43a32a
MS
9137 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9138 > get_remote_packet_size ())
8a3fe4f8 9139 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 9140
23860348 9141 /* Encode the actual command. */
9f1b45b0 9142 bin2hex ((gdb_byte *) command, p, strlen (command));
96baa820 9143
6d820c5c 9144 if (putpkt (rs->buf) < 0)
8a3fe4f8 9145 error (_("Communication problem with target."));
96baa820
JM
9146
9147 /* get/display the response */
9148 while (1)
9149 {
2e9f7625
DJ
9150 char *buf;
9151
00bf0b85 9152 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 9153 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 9154 rs->buf[0] = '\0';
5b37825d
PW
9155 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9156 {
9157 /* Timeout. Continue to (try to) read responses.
9158 This is better than stopping with an error, assuming the stub
9159 is still executing the (long) monitor command.
9160 If needed, the user can interrupt gdb using C-c, obtaining
9161 an effect similar to stop on timeout. */
9162 continue;
9163 }
2e9f7625 9164 buf = rs->buf;
96baa820 9165 if (buf[0] == '\0')
8a3fe4f8 9166 error (_("Target does not support this command."));
96baa820
JM
9167 if (buf[0] == 'O' && buf[1] != 'K')
9168 {
23860348 9169 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
9170 continue;
9171 }
9172 if (strcmp (buf, "OK") == 0)
9173 break;
7be570e7
JM
9174 if (strlen (buf) == 3 && buf[0] == 'E'
9175 && isdigit (buf[1]) && isdigit (buf[2]))
9176 {
8a3fe4f8 9177 error (_("Protocol error with Rcmd"));
7be570e7 9178 }
96baa820
JM
9179 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9180 {
9181 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 9182
96baa820
JM
9183 fputc_unfiltered (c, outbuf);
9184 }
9185 break;
9186 }
9187}
9188
fd79ecee
DJ
9189static VEC(mem_region_s) *
9190remote_memory_map (struct target_ops *ops)
9191{
9192 VEC(mem_region_s) *result = NULL;
9193 char *text = target_read_stralloc (&current_target,
9194 TARGET_OBJECT_MEMORY_MAP, NULL);
9195
9196 if (text)
9197 {
9198 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 9199
fd79ecee
DJ
9200 result = parse_memory_map (text);
9201 do_cleanups (back_to);
9202 }
9203
9204 return result;
9205}
9206
c906108c 9207static void
fba45db2 9208packet_command (char *args, int from_tty)
c906108c 9209{
d01949b6 9210 struct remote_state *rs = get_remote_state ();
c906108c 9211
5d93a237 9212 if (!rs->remote_desc)
8a3fe4f8 9213 error (_("command can only be used with remote target"));
c906108c 9214
c5aa993b 9215 if (!args)
8a3fe4f8 9216 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
9217
9218 puts_filtered ("sending: ");
9219 print_packet (args);
9220 puts_filtered ("\n");
9221 putpkt (args);
9222
6d820c5c 9223 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 9224 puts_filtered ("received: ");
6d820c5c 9225 print_packet (rs->buf);
c906108c
SS
9226 puts_filtered ("\n");
9227}
9228
9229#if 0
23860348 9230/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 9231
a14ed312 9232static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 9233
a14ed312 9234static void threadset_test_cmd (char *cmd, int tty);
c906108c 9235
a14ed312 9236static void threadalive_test (char *cmd, int tty);
c906108c 9237
a14ed312 9238static void threadlist_test_cmd (char *cmd, int tty);
c906108c 9239
23860348 9240int get_and_display_threadinfo (threadref *ref);
c906108c 9241
a14ed312 9242static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 9243
23860348 9244static int thread_display_step (threadref *ref, void *context);
c906108c 9245
a14ed312 9246static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 9247
a14ed312 9248static void init_remote_threadtests (void);
c906108c 9249
23860348 9250#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
9251
9252static void
fba45db2 9253threadset_test_cmd (char *cmd, int tty)
c906108c
SS
9254{
9255 int sample_thread = SAMPLE_THREAD;
9256
a3f17187 9257 printf_filtered (_("Remote threadset test\n"));
79d7f229 9258 set_general_thread (sample_thread);
c906108c
SS
9259}
9260
9261
9262static void
fba45db2 9263threadalive_test (char *cmd, int tty)
c906108c
SS
9264{
9265 int sample_thread = SAMPLE_THREAD;
79d7f229 9266 int pid = ptid_get_pid (inferior_ptid);
ba348170 9267 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 9268
79d7f229 9269 if (remote_thread_alive (ptid))
c906108c
SS
9270 printf_filtered ("PASS: Thread alive test\n");
9271 else
9272 printf_filtered ("FAIL: Thread alive test\n");
9273}
9274
23860348 9275void output_threadid (char *title, threadref *ref);
c906108c
SS
9276
9277void
fba45db2 9278output_threadid (char *title, threadref *ref)
c906108c
SS
9279{
9280 char hexid[20];
9281
23860348 9282 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
9283 hexid[16] = 0;
9284 printf_filtered ("%s %s\n", title, (&hexid[0]));
9285}
9286
9287static void
fba45db2 9288threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
9289{
9290 int startflag = 1;
9291 threadref nextthread;
9292 int done, result_count;
9293 threadref threadlist[3];
9294
9295 printf_filtered ("Remote Threadlist test\n");
9296 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9297 &result_count, &threadlist[0]))
9298 printf_filtered ("FAIL: threadlist test\n");
9299 else
9300 {
9301 threadref *scan = threadlist;
9302 threadref *limit = scan + result_count;
9303
9304 while (scan < limit)
9305 output_threadid (" thread ", scan++);
9306 }
9307}
9308
9309void
fba45db2 9310display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
9311{
9312 output_threadid ("Threadid: ", &info->threadid);
9313 printf_filtered ("Name: %s\n ", info->shortname);
9314 printf_filtered ("State: %s\n", info->display);
9315 printf_filtered ("other: %s\n\n", info->more_display);
9316}
9317
9318int
fba45db2 9319get_and_display_threadinfo (threadref *ref)
c906108c
SS
9320{
9321 int result;
9322 int set;
9323 struct gdb_ext_thread_info threadinfo;
9324
9325 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9326 | TAG_MOREDISPLAY | TAG_DISPLAY;
9327 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9328 display_thread_info (&threadinfo);
9329 return result;
9330}
9331
9332static void
fba45db2 9333threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
9334{
9335 int athread = SAMPLE_THREAD;
9336 threadref thread;
9337 int set;
9338
9339 int_to_threadref (&thread, athread);
9340 printf_filtered ("Remote Threadinfo test\n");
9341 if (!get_and_display_threadinfo (&thread))
9342 printf_filtered ("FAIL cannot get thread info\n");
9343}
9344
9345static int
fba45db2 9346thread_display_step (threadref *ref, void *context)
c906108c
SS
9347{
9348 /* output_threadid(" threadstep ",ref); *//* simple test */
9349 return get_and_display_threadinfo (ref);
9350}
9351
9352static void
fba45db2 9353threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
9354{
9355 printf_filtered ("Remote Threadlist update test\n");
9356 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9357}
9358
9359static void
9360init_remote_threadtests (void)
9361{
3e43a32a
MS
9362 add_com ("tlist", class_obscure, threadlist_test_cmd,
9363 _("Fetch and print the remote list of "
9364 "thread identifiers, one pkt only"));
c906108c 9365 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 9366 _("Fetch and display info about one thread"));
c906108c 9367 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 9368 _("Test setting to a different thread"));
c906108c 9369 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 9370 _("Iterate through updating all remote thread info"));
c906108c 9371 add_com ("talive", class_obscure, threadalive_test,
1bedd215 9372 _(" Remote thread alive test "));
c906108c
SS
9373}
9374
9375#endif /* 0 */
9376
f3fb8c85
MS
9377/* Convert a thread ID to a string. Returns the string in a static
9378 buffer. */
9379
9380static char *
117de6a9 9381remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 9382{
79d7f229 9383 static char buf[64];
82f73884 9384 struct remote_state *rs = get_remote_state ();
f3fb8c85 9385
7cee1e54
PA
9386 if (ptid_equal (ptid, null_ptid))
9387 return normal_pid_to_str (ptid);
9388 else if (ptid_is_pid (ptid))
ecd0ada5
PA
9389 {
9390 /* Printing an inferior target id. */
9391
9392 /* When multi-process extensions are off, there's no way in the
9393 remote protocol to know the remote process id, if there's any
9394 at all. There's one exception --- when we're connected with
9395 target extended-remote, and we manually attached to a process
9396 with "attach PID". We don't record anywhere a flag that
9397 allows us to distinguish that case from the case of
9398 connecting with extended-remote and the stub already being
9399 attached to a process, and reporting yes to qAttached, hence
9400 no smart special casing here. */
9401 if (!remote_multi_process_p (rs))
9402 {
9403 xsnprintf (buf, sizeof buf, "Remote target");
9404 return buf;
9405 }
9406
9407 return normal_pid_to_str (ptid);
82f73884 9408 }
ecd0ada5 9409 else
79d7f229 9410 {
ecd0ada5
PA
9411 if (ptid_equal (magic_null_ptid, ptid))
9412 xsnprintf (buf, sizeof buf, "Thread <main>");
901f9912 9413 else if (rs->extended && remote_multi_process_p (rs))
ecd0ada5 9414 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
ba348170 9415 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
9416 else
9417 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 9418 ptid_get_lwp (ptid));
79d7f229
PA
9419 return buf;
9420 }
f3fb8c85
MS
9421}
9422
38691318
KB
9423/* Get the address of the thread local variable in OBJFILE which is
9424 stored at OFFSET within the thread local storage for thread PTID. */
9425
9426static CORE_ADDR
117de6a9
PA
9427remote_get_thread_local_address (struct target_ops *ops,
9428 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 9429{
444abaca 9430 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
38691318
KB
9431 {
9432 struct remote_state *rs = get_remote_state ();
6d820c5c 9433 char *p = rs->buf;
82f73884 9434 char *endp = rs->buf + get_remote_packet_size ();
571dd617 9435 enum packet_result result;
38691318
KB
9436
9437 strcpy (p, "qGetTLSAddr:");
9438 p += strlen (p);
82f73884 9439 p = write_ptid (p, endp, ptid);
38691318
KB
9440 *p++ = ',';
9441 p += hexnumstr (p, offset);
9442 *p++ = ',';
9443 p += hexnumstr (p, lm);
9444 *p++ = '\0';
9445
6d820c5c
DJ
9446 putpkt (rs->buf);
9447 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
9448 result = packet_ok (rs->buf,
9449 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 9450 if (result == PACKET_OK)
38691318
KB
9451 {
9452 ULONGEST result;
9453
6d820c5c 9454 unpack_varlen_hex (rs->buf, &result);
38691318
KB
9455 return result;
9456 }
571dd617 9457 else if (result == PACKET_UNKNOWN)
109c3e39
AC
9458 throw_error (TLS_GENERIC_ERROR,
9459 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 9460 else
109c3e39
AC
9461 throw_error (TLS_GENERIC_ERROR,
9462 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
9463 }
9464 else
109c3e39
AC
9465 throw_error (TLS_GENERIC_ERROR,
9466 _("TLS not supported or disabled on this target"));
38691318
KB
9467 /* Not reached. */
9468 return 0;
9469}
9470
711e434b
PM
9471/* Provide thread local base, i.e. Thread Information Block address.
9472 Returns 1 if ptid is found and thread_local_base is non zero. */
9473
70221824 9474static int
bd7ae0f5 9475remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b
PM
9476{
9477 if (remote_protocol_packets[PACKET_qGetTIBAddr].support != PACKET_DISABLE)
9478 {
9479 struct remote_state *rs = get_remote_state ();
9480 char *p = rs->buf;
9481 char *endp = rs->buf + get_remote_packet_size ();
9482 enum packet_result result;
9483
9484 strcpy (p, "qGetTIBAddr:");
9485 p += strlen (p);
9486 p = write_ptid (p, endp, ptid);
9487 *p++ = '\0';
9488
9489 putpkt (rs->buf);
9490 getpkt (&rs->buf, &rs->buf_size, 0);
9491 result = packet_ok (rs->buf,
9492 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9493 if (result == PACKET_OK)
9494 {
9495 ULONGEST result;
9496
9497 unpack_varlen_hex (rs->buf, &result);
9498 if (addr)
9499 *addr = (CORE_ADDR) result;
9500 return 1;
9501 }
9502 else if (result == PACKET_UNKNOWN)
9503 error (_("Remote target doesn't support qGetTIBAddr packet"));
9504 else
9505 error (_("Remote target failed to process qGetTIBAddr request"));
9506 }
9507 else
9508 error (_("qGetTIBAddr not supported or disabled on this target"));
9509 /* Not reached. */
9510 return 0;
9511}
9512
29709017
DJ
9513/* Support for inferring a target description based on the current
9514 architecture and the size of a 'g' packet. While the 'g' packet
9515 can have any size (since optional registers can be left off the
9516 end), some sizes are easily recognizable given knowledge of the
9517 approximate architecture. */
9518
9519struct remote_g_packet_guess
9520{
9521 int bytes;
9522 const struct target_desc *tdesc;
9523};
9524typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9525DEF_VEC_O(remote_g_packet_guess_s);
9526
9527struct remote_g_packet_data
9528{
9529 VEC(remote_g_packet_guess_s) *guesses;
9530};
9531
9532static struct gdbarch_data *remote_g_packet_data_handle;
9533
9534static void *
9535remote_g_packet_data_init (struct obstack *obstack)
9536{
9537 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9538}
9539
9540void
9541register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9542 const struct target_desc *tdesc)
9543{
9544 struct remote_g_packet_data *data
9545 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9546 struct remote_g_packet_guess new_guess, *guess;
9547 int ix;
9548
9549 gdb_assert (tdesc != NULL);
9550
9551 for (ix = 0;
9552 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9553 ix++)
9554 if (guess->bytes == bytes)
9555 internal_error (__FILE__, __LINE__,
9b20d036 9556 _("Duplicate g packet description added for size %d"),
29709017
DJ
9557 bytes);
9558
9559 new_guess.bytes = bytes;
9560 new_guess.tdesc = tdesc;
9561 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9562}
9563
d962ef82
DJ
9564/* Return 1 if remote_read_description would do anything on this target
9565 and architecture, 0 otherwise. */
9566
9567static int
9568remote_read_description_p (struct target_ops *target)
9569{
9570 struct remote_g_packet_data *data
f5656ead 9571 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
d962ef82
DJ
9572
9573 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9574 return 1;
9575
9576 return 0;
9577}
9578
29709017
DJ
9579static const struct target_desc *
9580remote_read_description (struct target_ops *target)
9581{
9582 struct remote_g_packet_data *data
f5656ead 9583 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
29709017 9584
d962ef82
DJ
9585 /* Do not try this during initial connection, when we do not know
9586 whether there is a running but stopped thread. */
9587 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 9588 return target->beneath->to_read_description (target->beneath);
d962ef82 9589
29709017
DJ
9590 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9591 {
9592 struct remote_g_packet_guess *guess;
9593 int ix;
9594 int bytes = send_g_packet ();
9595
9596 for (ix = 0;
9597 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9598 ix++)
9599 if (guess->bytes == bytes)
9600 return guess->tdesc;
9601
9602 /* We discard the g packet. A minor optimization would be to
9603 hold on to it, and fill the register cache once we have selected
9604 an architecture, but it's too tricky to do safely. */
9605 }
9606
2117c711 9607 return target->beneath->to_read_description (target->beneath);
29709017
DJ
9608}
9609
a6b151f1
DJ
9610/* Remote file transfer support. This is host-initiated I/O, not
9611 target-initiated; for target-initiated, see remote-fileio.c. */
9612
9613/* If *LEFT is at least the length of STRING, copy STRING to
9614 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9615 decrease *LEFT. Otherwise raise an error. */
9616
9617static void
9618remote_buffer_add_string (char **buffer, int *left, char *string)
9619{
9620 int len = strlen (string);
9621
9622 if (len > *left)
9623 error (_("Packet too long for target."));
9624
9625 memcpy (*buffer, string, len);
9626 *buffer += len;
9627 *left -= len;
9628
9629 /* NUL-terminate the buffer as a convenience, if there is
9630 room. */
9631 if (*left)
9632 **buffer = '\0';
9633}
9634
9635/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9636 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9637 decrease *LEFT. Otherwise raise an error. */
9638
9639static void
9640remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9641 int len)
9642{
9643 if (2 * len > *left)
9644 error (_("Packet too long for target."));
9645
9646 bin2hex (bytes, *buffer, len);
9647 *buffer += 2 * len;
9648 *left -= 2 * len;
9649
9650 /* NUL-terminate the buffer as a convenience, if there is
9651 room. */
9652 if (*left)
9653 **buffer = '\0';
9654}
9655
9656/* If *LEFT is large enough, convert VALUE to hex and add it to
9657 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9658 decrease *LEFT. Otherwise raise an error. */
9659
9660static void
9661remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9662{
9663 int len = hexnumlen (value);
9664
9665 if (len > *left)
9666 error (_("Packet too long for target."));
9667
9668 hexnumstr (*buffer, value);
9669 *buffer += len;
9670 *left -= len;
9671
9672 /* NUL-terminate the buffer as a convenience, if there is
9673 room. */
9674 if (*left)
9675 **buffer = '\0';
9676}
9677
9678/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9679 value, *REMOTE_ERRNO to the remote error number or zero if none
9680 was included, and *ATTACHMENT to point to the start of the annex
9681 if any. The length of the packet isn't needed here; there may
9682 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9683
9684 Return 0 if the packet could be parsed, -1 if it could not. If
9685 -1 is returned, the other variables may not be initialized. */
9686
9687static int
9688remote_hostio_parse_result (char *buffer, int *retcode,
9689 int *remote_errno, char **attachment)
9690{
9691 char *p, *p2;
9692
9693 *remote_errno = 0;
9694 *attachment = NULL;
9695
9696 if (buffer[0] != 'F')
9697 return -1;
9698
9699 errno = 0;
9700 *retcode = strtol (&buffer[1], &p, 16);
9701 if (errno != 0 || p == &buffer[1])
9702 return -1;
9703
9704 /* Check for ",errno". */
9705 if (*p == ',')
9706 {
9707 errno = 0;
9708 *remote_errno = strtol (p + 1, &p2, 16);
9709 if (errno != 0 || p + 1 == p2)
9710 return -1;
9711 p = p2;
9712 }
9713
9714 /* Check for ";attachment". If there is no attachment, the
9715 packet should end here. */
9716 if (*p == ';')
9717 {
9718 *attachment = p + 1;
9719 return 0;
9720 }
9721 else if (*p == '\0')
9722 return 0;
9723 else
9724 return -1;
9725}
9726
9727/* Send a prepared I/O packet to the target and read its response.
9728 The prepared packet is in the global RS->BUF before this function
9729 is called, and the answer is there when we return.
9730
9731 COMMAND_BYTES is the length of the request to send, which may include
9732 binary data. WHICH_PACKET is the packet configuration to check
9733 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9734 is set to the error number and -1 is returned. Otherwise the value
9735 returned by the function is returned.
9736
9737 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9738 attachment is expected; an error will be reported if there's a
9739 mismatch. If one is found, *ATTACHMENT will be set to point into
9740 the packet buffer and *ATTACHMENT_LEN will be set to the
9741 attachment's length. */
9742
9743static int
9744remote_hostio_send_command (int command_bytes, int which_packet,
9745 int *remote_errno, char **attachment,
9746 int *attachment_len)
9747{
9748 struct remote_state *rs = get_remote_state ();
9749 int ret, bytes_read;
9750 char *attachment_tmp;
9751
5d93a237 9752 if (!rs->remote_desc
f1838a98 9753 || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
a6b151f1
DJ
9754 {
9755 *remote_errno = FILEIO_ENOSYS;
9756 return -1;
9757 }
9758
9759 putpkt_binary (rs->buf, command_bytes);
9760 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9761
9762 /* If it timed out, something is wrong. Don't try to parse the
9763 buffer. */
9764 if (bytes_read < 0)
9765 {
9766 *remote_errno = FILEIO_EINVAL;
9767 return -1;
9768 }
9769
9770 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9771 {
9772 case PACKET_ERROR:
9773 *remote_errno = FILEIO_EINVAL;
9774 return -1;
9775 case PACKET_UNKNOWN:
9776 *remote_errno = FILEIO_ENOSYS;
9777 return -1;
9778 case PACKET_OK:
9779 break;
9780 }
9781
9782 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9783 &attachment_tmp))
9784 {
9785 *remote_errno = FILEIO_EINVAL;
9786 return -1;
9787 }
9788
9789 /* Make sure we saw an attachment if and only if we expected one. */
9790 if ((attachment_tmp == NULL && attachment != NULL)
9791 || (attachment_tmp != NULL && attachment == NULL))
9792 {
9793 *remote_errno = FILEIO_EINVAL;
9794 return -1;
9795 }
9796
9797 /* If an attachment was found, it must point into the packet buffer;
9798 work out how many bytes there were. */
9799 if (attachment_tmp != NULL)
9800 {
9801 *attachment = attachment_tmp;
9802 *attachment_len = bytes_read - (*attachment - rs->buf);
9803 }
9804
9805 return ret;
9806}
9807
9808/* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9809 remote file descriptor, or -1 if an error occurs (and set
9810 *REMOTE_ERRNO). */
9811
9812static int
cd897586
TT
9813remote_hostio_open (struct target_ops *self,
9814 const char *filename, int flags, int mode,
a6b151f1
DJ
9815 int *remote_errno)
9816{
9817 struct remote_state *rs = get_remote_state ();
9818 char *p = rs->buf;
9819 int left = get_remote_packet_size () - 1;
9820
9821 remote_buffer_add_string (&p, &left, "vFile:open:");
9822
9823 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9824 strlen (filename));
9825 remote_buffer_add_string (&p, &left, ",");
9826
9827 remote_buffer_add_int (&p, &left, flags);
9828 remote_buffer_add_string (&p, &left, ",");
9829
9830 remote_buffer_add_int (&p, &left, mode);
9831
9832 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9833 remote_errno, NULL, NULL);
9834}
9835
9836/* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9837 Return the number of bytes written, or -1 if an error occurs (and
9838 set *REMOTE_ERRNO). */
9839
9840static int
0d866f62
TT
9841remote_hostio_pwrite (struct target_ops *self,
9842 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
9843 ULONGEST offset, int *remote_errno)
9844{
9845 struct remote_state *rs = get_remote_state ();
9846 char *p = rs->buf;
9847 int left = get_remote_packet_size ();
9848 int out_len;
9849
9850 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9851
9852 remote_buffer_add_int (&p, &left, fd);
9853 remote_buffer_add_string (&p, &left, ",");
9854
9855 remote_buffer_add_int (&p, &left, offset);
9856 remote_buffer_add_string (&p, &left, ",");
9857
bc20a4af 9858 p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
a6b151f1
DJ
9859 get_remote_packet_size () - (p - rs->buf));
9860
9861 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9862 remote_errno, NULL, NULL);
9863}
9864
9865/* Read up to LEN bytes FD on the remote target into READ_BUF
9866 Return the number of bytes read, or -1 if an error occurs (and
9867 set *REMOTE_ERRNO). */
9868
9869static int
a3be983c
TT
9870remote_hostio_pread (struct target_ops *self,
9871 int fd, gdb_byte *read_buf, int len,
a6b151f1
DJ
9872 ULONGEST offset, int *remote_errno)
9873{
9874 struct remote_state *rs = get_remote_state ();
9875 char *p = rs->buf;
9876 char *attachment;
9877 int left = get_remote_packet_size ();
9878 int ret, attachment_len;
9879 int read_len;
9880
9881 remote_buffer_add_string (&p, &left, "vFile:pread:");
9882
9883 remote_buffer_add_int (&p, &left, fd);
9884 remote_buffer_add_string (&p, &left, ",");
9885
9886 remote_buffer_add_int (&p, &left, len);
9887 remote_buffer_add_string (&p, &left, ",");
9888
9889 remote_buffer_add_int (&p, &left, offset);
9890
9891 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9892 remote_errno, &attachment,
9893 &attachment_len);
9894
9895 if (ret < 0)
9896 return ret;
9897
bc20a4af 9898 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
9899 read_buf, len);
9900 if (read_len != ret)
9901 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9902
9903 return ret;
9904}
9905
9906/* Close FD on the remote target. Return 0, or -1 if an error occurs
9907 (and set *REMOTE_ERRNO). */
9908
9909static int
df39ea25 9910remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
9911{
9912 struct remote_state *rs = get_remote_state ();
9913 char *p = rs->buf;
9914 int left = get_remote_packet_size () - 1;
9915
9916 remote_buffer_add_string (&p, &left, "vFile:close:");
9917
9918 remote_buffer_add_int (&p, &left, fd);
9919
9920 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
9921 remote_errno, NULL, NULL);
9922}
9923
9924/* Unlink FILENAME on the remote target. Return 0, or -1 if an error
9925 occurs (and set *REMOTE_ERRNO). */
9926
9927static int
dbbca37d
TT
9928remote_hostio_unlink (struct target_ops *self,
9929 const char *filename, int *remote_errno)
a6b151f1
DJ
9930{
9931 struct remote_state *rs = get_remote_state ();
9932 char *p = rs->buf;
9933 int left = get_remote_packet_size () - 1;
9934
9935 remote_buffer_add_string (&p, &left, "vFile:unlink:");
9936
9937 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9938 strlen (filename));
9939
9940 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
9941 remote_errno, NULL, NULL);
9942}
9943
b9e7b9c3
UW
9944/* Read value of symbolic link FILENAME on the remote target. Return
9945 a null-terminated string allocated via xmalloc, or NULL if an error
9946 occurs (and set *REMOTE_ERRNO). */
9947
9948static char *
fab5aa7c
TT
9949remote_hostio_readlink (struct target_ops *self,
9950 const char *filename, int *remote_errno)
b9e7b9c3
UW
9951{
9952 struct remote_state *rs = get_remote_state ();
9953 char *p = rs->buf;
9954 char *attachment;
9955 int left = get_remote_packet_size ();
9956 int len, attachment_len;
9957 int read_len;
9958 char *ret;
9959
9960 remote_buffer_add_string (&p, &left, "vFile:readlink:");
9961
9962 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9963 strlen (filename));
9964
9965 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
9966 remote_errno, &attachment,
9967 &attachment_len);
9968
9969 if (len < 0)
9970 return NULL;
9971
9972 ret = xmalloc (len + 1);
9973
bc20a4af
PA
9974 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9975 (gdb_byte *) ret, len);
b9e7b9c3
UW
9976 if (read_len != len)
9977 error (_("Readlink returned %d, but %d bytes."), len, read_len);
9978
9979 ret[len] = '\0';
9980 return ret;
9981}
9982
a6b151f1
DJ
9983static int
9984remote_fileio_errno_to_host (int errnum)
9985{
9986 switch (errnum)
9987 {
9988 case FILEIO_EPERM:
9989 return EPERM;
9990 case FILEIO_ENOENT:
9991 return ENOENT;
9992 case FILEIO_EINTR:
9993 return EINTR;
9994 case FILEIO_EIO:
9995 return EIO;
9996 case FILEIO_EBADF:
9997 return EBADF;
9998 case FILEIO_EACCES:
9999 return EACCES;
10000 case FILEIO_EFAULT:
10001 return EFAULT;
10002 case FILEIO_EBUSY:
10003 return EBUSY;
10004 case FILEIO_EEXIST:
10005 return EEXIST;
10006 case FILEIO_ENODEV:
10007 return ENODEV;
10008 case FILEIO_ENOTDIR:
10009 return ENOTDIR;
10010 case FILEIO_EISDIR:
10011 return EISDIR;
10012 case FILEIO_EINVAL:
10013 return EINVAL;
10014 case FILEIO_ENFILE:
10015 return ENFILE;
10016 case FILEIO_EMFILE:
10017 return EMFILE;
10018 case FILEIO_EFBIG:
10019 return EFBIG;
10020 case FILEIO_ENOSPC:
10021 return ENOSPC;
10022 case FILEIO_ESPIPE:
10023 return ESPIPE;
10024 case FILEIO_EROFS:
10025 return EROFS;
10026 case FILEIO_ENOSYS:
10027 return ENOSYS;
10028 case FILEIO_ENAMETOOLONG:
10029 return ENAMETOOLONG;
10030 }
10031 return -1;
10032}
10033
10034static char *
10035remote_hostio_error (int errnum)
10036{
10037 int host_error = remote_fileio_errno_to_host (errnum);
10038
10039 if (host_error == -1)
10040 error (_("Unknown remote I/O error %d"), errnum);
10041 else
10042 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10043}
10044
a6b151f1
DJ
10045static void
10046remote_hostio_close_cleanup (void *opaque)
10047{
10048 int fd = *(int *) opaque;
10049 int remote_errno;
10050
df39ea25 10051 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
10052}
10053
f1838a98
UW
10054
10055static void *
10056remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
10057{
10058 const char *filename = bfd_get_filename (abfd);
10059 int fd, remote_errno;
10060 int *stream;
10061
10062 gdb_assert (remote_filename_p (filename));
10063
cd897586
TT
10064 fd = remote_hostio_open (find_target_at (process_stratum),
10065 filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
f1838a98
UW
10066 if (fd == -1)
10067 {
10068 errno = remote_fileio_errno_to_host (remote_errno);
10069 bfd_set_error (bfd_error_system_call);
10070 return NULL;
10071 }
10072
10073 stream = xmalloc (sizeof (int));
10074 *stream = fd;
10075 return stream;
10076}
10077
10078static int
10079remote_bfd_iovec_close (struct bfd *abfd, void *stream)
10080{
10081 int fd = *(int *)stream;
10082 int remote_errno;
10083
10084 xfree (stream);
10085
10086 /* Ignore errors on close; these may happen if the remote
10087 connection was already torn down. */
df39ea25 10088 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
f1838a98 10089
39ed5604
JK
10090 /* Zero means success. */
10091 return 0;
f1838a98
UW
10092}
10093
10094static file_ptr
10095remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
10096 file_ptr nbytes, file_ptr offset)
10097{
10098 int fd = *(int *)stream;
10099 int remote_errno;
10100 file_ptr pos, bytes;
10101
10102 pos = 0;
10103 while (nbytes > pos)
10104 {
a3be983c
TT
10105 bytes = remote_hostio_pread (find_target_at (process_stratum),
10106 fd, (gdb_byte *) buf + pos, nbytes - pos,
f1838a98
UW
10107 offset + pos, &remote_errno);
10108 if (bytes == 0)
10109 /* Success, but no bytes, means end-of-file. */
10110 break;
10111 if (bytes == -1)
10112 {
10113 errno = remote_fileio_errno_to_host (remote_errno);
10114 bfd_set_error (bfd_error_system_call);
10115 return -1;
10116 }
10117
10118 pos += bytes;
10119 }
10120
10121 return pos;
10122}
10123
10124static int
10125remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
10126{
10127 /* FIXME: We should probably implement remote_hostio_stat. */
10128 sb->st_size = INT_MAX;
10129 return 0;
10130}
10131
10132int
10133remote_filename_p (const char *filename)
10134{
3736004f
PA
10135 return strncmp (filename,
10136 REMOTE_SYSROOT_PREFIX,
10137 sizeof (REMOTE_SYSROOT_PREFIX) - 1) == 0;
f1838a98
UW
10138}
10139
10140bfd *
10141remote_bfd_open (const char *remote_file, const char *target)
10142{
64c31149
TT
10143 bfd *abfd = gdb_bfd_openr_iovec (remote_file, target,
10144 remote_bfd_iovec_open, NULL,
10145 remote_bfd_iovec_pread,
10146 remote_bfd_iovec_close,
10147 remote_bfd_iovec_stat);
10148
a4453b7e 10149 return abfd;
f1838a98
UW
10150}
10151
a6b151f1
DJ
10152void
10153remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10154{
10155 struct cleanup *back_to, *close_cleanup;
10156 int retcode, fd, remote_errno, bytes, io_size;
10157 FILE *file;
10158 gdb_byte *buffer;
10159 int bytes_in_buffer;
10160 int saw_eof;
10161 ULONGEST offset;
5d93a237 10162 struct remote_state *rs = get_remote_state ();
a6b151f1 10163
5d93a237 10164 if (!rs->remote_desc)
a6b151f1
DJ
10165 error (_("command can only be used with remote target"));
10166
614c279d 10167 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
10168 if (file == NULL)
10169 perror_with_name (local_file);
7c8a8b04 10170 back_to = make_cleanup_fclose (file);
a6b151f1 10171
cd897586
TT
10172 fd = remote_hostio_open (find_target_at (process_stratum),
10173 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1
DJ
10174 | FILEIO_O_TRUNC),
10175 0700, &remote_errno);
10176 if (fd == -1)
10177 remote_hostio_error (remote_errno);
10178
10179 /* Send up to this many bytes at once. They won't all fit in the
10180 remote packet limit, so we'll transfer slightly fewer. */
10181 io_size = get_remote_packet_size ();
10182 buffer = xmalloc (io_size);
10183 make_cleanup (xfree, buffer);
10184
10185 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10186
10187 bytes_in_buffer = 0;
10188 saw_eof = 0;
10189 offset = 0;
10190 while (bytes_in_buffer || !saw_eof)
10191 {
10192 if (!saw_eof)
10193 {
3e43a32a
MS
10194 bytes = fread (buffer + bytes_in_buffer, 1,
10195 io_size - bytes_in_buffer,
a6b151f1
DJ
10196 file);
10197 if (bytes == 0)
10198 {
10199 if (ferror (file))
10200 error (_("Error reading %s."), local_file);
10201 else
10202 {
10203 /* EOF. Unless there is something still in the
10204 buffer from the last iteration, we are done. */
10205 saw_eof = 1;
10206 if (bytes_in_buffer == 0)
10207 break;
10208 }
10209 }
10210 }
10211 else
10212 bytes = 0;
10213
10214 bytes += bytes_in_buffer;
10215 bytes_in_buffer = 0;
10216
0d866f62
TT
10217 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
10218 fd, buffer, bytes,
3e43a32a 10219 offset, &remote_errno);
a6b151f1
DJ
10220
10221 if (retcode < 0)
10222 remote_hostio_error (remote_errno);
10223 else if (retcode == 0)
10224 error (_("Remote write of %d bytes returned 0!"), bytes);
10225 else if (retcode < bytes)
10226 {
10227 /* Short write. Save the rest of the read data for the next
10228 write. */
10229 bytes_in_buffer = bytes - retcode;
10230 memmove (buffer, buffer + retcode, bytes_in_buffer);
10231 }
10232
10233 offset += retcode;
10234 }
10235
10236 discard_cleanups (close_cleanup);
df39ea25 10237 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
10238 remote_hostio_error (remote_errno);
10239
10240 if (from_tty)
10241 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10242 do_cleanups (back_to);
10243}
10244
10245void
10246remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10247{
10248 struct cleanup *back_to, *close_cleanup;
cea39f65 10249 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
10250 FILE *file;
10251 gdb_byte *buffer;
10252 ULONGEST offset;
5d93a237 10253 struct remote_state *rs = get_remote_state ();
a6b151f1 10254
5d93a237 10255 if (!rs->remote_desc)
a6b151f1
DJ
10256 error (_("command can only be used with remote target"));
10257
cd897586
TT
10258 fd = remote_hostio_open (find_target_at (process_stratum),
10259 remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
a6b151f1
DJ
10260 if (fd == -1)
10261 remote_hostio_error (remote_errno);
10262
614c279d 10263 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
10264 if (file == NULL)
10265 perror_with_name (local_file);
7c8a8b04 10266 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
10267
10268 /* Send up to this many bytes at once. They won't all fit in the
10269 remote packet limit, so we'll transfer slightly fewer. */
10270 io_size = get_remote_packet_size ();
10271 buffer = xmalloc (io_size);
10272 make_cleanup (xfree, buffer);
10273
10274 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10275
10276 offset = 0;
10277 while (1)
10278 {
a3be983c
TT
10279 bytes = remote_hostio_pread (find_target_at (process_stratum),
10280 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
10281 if (bytes == 0)
10282 /* Success, but no bytes, means end-of-file. */
10283 break;
10284 if (bytes == -1)
10285 remote_hostio_error (remote_errno);
10286
10287 offset += bytes;
10288
10289 bytes = fwrite (buffer, 1, bytes, file);
10290 if (bytes == 0)
10291 perror_with_name (local_file);
10292 }
10293
10294 discard_cleanups (close_cleanup);
df39ea25 10295 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
10296 remote_hostio_error (remote_errno);
10297
10298 if (from_tty)
10299 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10300 do_cleanups (back_to);
10301}
10302
10303void
10304remote_file_delete (const char *remote_file, int from_tty)
10305{
10306 int retcode, remote_errno;
5d93a237 10307 struct remote_state *rs = get_remote_state ();
a6b151f1 10308
5d93a237 10309 if (!rs->remote_desc)
a6b151f1
DJ
10310 error (_("command can only be used with remote target"));
10311
dbbca37d
TT
10312 retcode = remote_hostio_unlink (find_target_at (process_stratum),
10313 remote_file, &remote_errno);
a6b151f1
DJ
10314 if (retcode == -1)
10315 remote_hostio_error (remote_errno);
10316
10317 if (from_tty)
10318 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10319}
10320
10321static void
10322remote_put_command (char *args, int from_tty)
10323{
10324 struct cleanup *back_to;
10325 char **argv;
10326
d1a41061
PP
10327 if (args == NULL)
10328 error_no_arg (_("file to put"));
10329
10330 argv = gdb_buildargv (args);
a6b151f1
DJ
10331 back_to = make_cleanup_freeargv (argv);
10332 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10333 error (_("Invalid parameters to remote put"));
10334
10335 remote_file_put (argv[0], argv[1], from_tty);
10336
10337 do_cleanups (back_to);
10338}
10339
10340static void
10341remote_get_command (char *args, int from_tty)
10342{
10343 struct cleanup *back_to;
10344 char **argv;
10345
d1a41061
PP
10346 if (args == NULL)
10347 error_no_arg (_("file to get"));
10348
10349 argv = gdb_buildargv (args);
a6b151f1
DJ
10350 back_to = make_cleanup_freeargv (argv);
10351 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10352 error (_("Invalid parameters to remote get"));
10353
10354 remote_file_get (argv[0], argv[1], from_tty);
10355
10356 do_cleanups (back_to);
10357}
10358
10359static void
10360remote_delete_command (char *args, int from_tty)
10361{
10362 struct cleanup *back_to;
10363 char **argv;
10364
d1a41061
PP
10365 if (args == NULL)
10366 error_no_arg (_("file to delete"));
10367
10368 argv = gdb_buildargv (args);
a6b151f1
DJ
10369 back_to = make_cleanup_freeargv (argv);
10370 if (argv[0] == NULL || argv[1] != NULL)
10371 error (_("Invalid parameters to remote delete"));
10372
10373 remote_file_delete (argv[0], from_tty);
10374
10375 do_cleanups (back_to);
10376}
10377
10378static void
10379remote_command (char *args, int from_tty)
10380{
10381 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
10382}
10383
b2175913 10384static int
19db3e69 10385remote_can_execute_reverse (struct target_ops *self)
b2175913 10386{
40ab02ce
MS
10387 if (remote_protocol_packets[PACKET_bs].support == PACKET_ENABLE
10388 || remote_protocol_packets[PACKET_bc].support == PACKET_ENABLE)
10389 return 1;
10390 else
10391 return 0;
b2175913
MS
10392}
10393
74531fed 10394static int
2a9a2795 10395remote_supports_non_stop (struct target_ops *self)
74531fed
PA
10396{
10397 return 1;
10398}
10399
03583c20 10400static int
2bfc0540 10401remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
10402{
10403 /* Only supported in extended mode. */
10404 return 0;
10405}
10406
8a305172 10407static int
86ce2668 10408remote_supports_multi_process (struct target_ops *self)
8a305172
PA
10409{
10410 struct remote_state *rs = get_remote_state ();
a744cf53 10411
901f9912
UW
10412 /* Only extended-remote handles being attached to multiple
10413 processes, even though plain remote can use the multi-process
10414 thread id extensions, so that GDB knows the target process's
10415 PID. */
10416 return rs->extended && remote_multi_process_p (rs);
8a305172
PA
10417}
10418
70221824 10419static int
782b2b07
SS
10420remote_supports_cond_tracepoints (void)
10421{
10422 struct remote_state *rs = get_remote_state ();
a744cf53 10423
782b2b07
SS
10424 return rs->cond_tracepoints;
10425}
10426
3788aec7 10427static int
efcc2da7 10428remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7
LM
10429{
10430 struct remote_state *rs = get_remote_state ();
10431
10432 return rs->cond_breakpoints;
10433}
10434
70221824 10435static int
7a697b8d
SS
10436remote_supports_fast_tracepoints (void)
10437{
10438 struct remote_state *rs = get_remote_state ();
a744cf53 10439
7a697b8d
SS
10440 return rs->fast_tracepoints;
10441}
10442
0fb4aa4b
PA
10443static int
10444remote_supports_static_tracepoints (void)
10445{
10446 struct remote_state *rs = get_remote_state ();
10447
10448 return rs->static_tracepoints;
10449}
10450
1e4d1764
YQ
10451static int
10452remote_supports_install_in_trace (void)
10453{
10454 struct remote_state *rs = get_remote_state ();
10455
10456 return rs->install_in_trace;
10457}
10458
d248b706 10459static int
7d178d6a 10460remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706
KY
10461{
10462 struct remote_state *rs = get_remote_state ();
10463
10464 return rs->enable_disable_tracepoints;
10465}
10466
3065dfb6 10467static int
6de37a3a 10468remote_supports_string_tracing (struct target_ops *self)
3065dfb6
SS
10469{
10470 struct remote_state *rs = get_remote_state ();
10471
10472 return rs->string_tracing;
10473}
10474
d3ce09f5 10475static int
78eff0ec 10476remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5
SS
10477{
10478 struct remote_state *rs = get_remote_state ();
10479
10480 return rs->breakpoint_commands;
10481}
10482
35b1e5cc 10483static void
ecae04e1 10484remote_trace_init (struct target_ops *self)
35b1e5cc
SS
10485{
10486 putpkt ("QTinit");
10487 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 10488 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
10489 error (_("Target does not support this command."));
10490}
10491
10492static void free_actions_list (char **actions_list);
10493static void free_actions_list_cleanup_wrapper (void *);
10494static void
10495free_actions_list_cleanup_wrapper (void *al)
10496{
10497 free_actions_list (al);
10498}
10499
10500static void
10501free_actions_list (char **actions_list)
10502{
10503 int ndx;
10504
10505 if (actions_list == 0)
10506 return;
10507
10508 for (ndx = 0; actions_list[ndx]; ndx++)
10509 xfree (actions_list[ndx]);
10510
10511 xfree (actions_list);
10512}
10513
409873ef
SS
10514/* Recursive routine to walk through command list including loops, and
10515 download packets for each command. */
10516
10517static void
10518remote_download_command_source (int num, ULONGEST addr,
10519 struct command_line *cmds)
10520{
10521 struct remote_state *rs = get_remote_state ();
10522 struct command_line *cmd;
10523
10524 for (cmd = cmds; cmd; cmd = cmd->next)
10525 {
0df8b418 10526 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
10527 strcpy (rs->buf, "QTDPsrc:");
10528 encode_source_string (num, addr, "cmd", cmd->line,
10529 rs->buf + strlen (rs->buf),
10530 rs->buf_size - strlen (rs->buf));
10531 putpkt (rs->buf);
10532 remote_get_noisy_reply (&target_buf, &target_buf_size);
10533 if (strcmp (target_buf, "OK"))
10534 warning (_("Target does not support source download."));
10535
10536 if (cmd->control_type == while_control
10537 || cmd->control_type == while_stepping_control)
10538 {
10539 remote_download_command_source (num, addr, *cmd->body_list);
10540
0df8b418 10541 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
10542 strcpy (rs->buf, "QTDPsrc:");
10543 encode_source_string (num, addr, "cmd", "end",
10544 rs->buf + strlen (rs->buf),
10545 rs->buf_size - strlen (rs->buf));
10546 putpkt (rs->buf);
10547 remote_get_noisy_reply (&target_buf, &target_buf_size);
10548 if (strcmp (target_buf, "OK"))
10549 warning (_("Target does not support source download."));
10550 }
10551 }
10552}
10553
35b1e5cc 10554static void
548f7808 10555remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 10556{
bba74b36 10557#define BUF_SIZE 2048
e8ba3115 10558
35b1e5cc 10559 CORE_ADDR tpaddr;
409873ef 10560 char addrbuf[40];
bba74b36 10561 char buf[BUF_SIZE];
35b1e5cc
SS
10562 char **tdp_actions;
10563 char **stepping_actions;
10564 int ndx;
10565 struct cleanup *old_chain = NULL;
10566 struct agent_expr *aexpr;
10567 struct cleanup *aexpr_chain = NULL;
10568 char *pkt;
e8ba3115 10569 struct breakpoint *b = loc->owner;
d9b3f62e 10570 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 10571
dc673c81 10572 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
10573 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10574 tdp_actions);
10575 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10576 stepping_actions);
10577
10578 tpaddr = loc->address;
10579 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
10580 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10581 addrbuf, /* address */
10582 (b->enable_state == bp_enabled ? 'E' : 'D'),
10583 t->step_count, t->pass_count);
e8ba3115
YQ
10584 /* Fast tracepoints are mostly handled by the target, but we can
10585 tell the target how big of an instruction block should be moved
10586 around. */
10587 if (b->type == bp_fast_tracepoint)
10588 {
10589 /* Only test for support at download time; we may not know
10590 target capabilities at definition time. */
10591 if (remote_supports_fast_tracepoints ())
35b1e5cc 10592 {
e8ba3115 10593 int isize;
35b1e5cc 10594
f5656ead 10595 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
e8ba3115 10596 tpaddr, &isize, NULL))
bba74b36
YQ
10597 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10598 isize);
35b1e5cc 10599 else
e8ba3115
YQ
10600 /* If it passed validation at definition but fails now,
10601 something is very wrong. */
10602 internal_error (__FILE__, __LINE__,
10603 _("Fast tracepoint not "
10604 "valid during download"));
35b1e5cc 10605 }
e8ba3115
YQ
10606 else
10607 /* Fast tracepoints are functionally identical to regular
10608 tracepoints, so don't take lack of support as a reason to
10609 give up on the trace run. */
10610 warning (_("Target does not support fast tracepoints, "
10611 "downloading %d as regular tracepoint"), b->number);
10612 }
10613 else if (b->type == bp_static_tracepoint)
10614 {
10615 /* Only test for support at download time; we may not know
10616 target capabilities at definition time. */
10617 if (remote_supports_static_tracepoints ())
0fb4aa4b 10618 {
e8ba3115 10619 struct static_tracepoint_marker marker;
0fb4aa4b 10620
e8ba3115
YQ
10621 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10622 strcat (buf, ":S");
0fb4aa4b 10623 else
e8ba3115 10624 error (_("Static tracepoint not valid during download"));
0fb4aa4b 10625 }
e8ba3115
YQ
10626 else
10627 /* Fast tracepoints are functionally identical to regular
10628 tracepoints, so don't take lack of support as a reason
10629 to give up on the trace run. */
10630 error (_("Target does not support static tracepoints"));
10631 }
10632 /* If the tracepoint has a conditional, make it into an agent
10633 expression and append to the definition. */
10634 if (loc->cond)
10635 {
10636 /* Only test support at download time, we may not know target
10637 capabilities at definition time. */
10638 if (remote_supports_cond_tracepoints ())
35b1e5cc 10639 {
e8ba3115
YQ
10640 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10641 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
10642 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10643 aexpr->len);
e8ba3115
YQ
10644 pkt = buf + strlen (buf);
10645 for (ndx = 0; ndx < aexpr->len; ++ndx)
10646 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10647 *pkt = '\0';
10648 do_cleanups (aexpr_chain);
35b1e5cc 10649 }
e8ba3115
YQ
10650 else
10651 warning (_("Target does not support conditional tracepoints, "
10652 "ignoring tp %d cond"), b->number);
10653 }
35b1e5cc 10654
d9b3f62e 10655 if (b->commands || *default_collect)
e8ba3115
YQ
10656 strcat (buf, "-");
10657 putpkt (buf);
10658 remote_get_noisy_reply (&target_buf, &target_buf_size);
10659 if (strcmp (target_buf, "OK"))
10660 error (_("Target does not support tracepoints."));
35b1e5cc 10661
e8ba3115
YQ
10662 /* do_single_steps (t); */
10663 if (tdp_actions)
10664 {
10665 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 10666 {
e8ba3115 10667 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
10668 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10669 b->number, addrbuf, /* address */
10670 tdp_actions[ndx],
10671 ((tdp_actions[ndx + 1] || stepping_actions)
10672 ? '-' : 0));
e8ba3115
YQ
10673 putpkt (buf);
10674 remote_get_noisy_reply (&target_buf,
10675 &target_buf_size);
10676 if (strcmp (target_buf, "OK"))
10677 error (_("Error on target while setting tracepoints."));
35b1e5cc 10678 }
e8ba3115
YQ
10679 }
10680 if (stepping_actions)
10681 {
10682 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 10683 {
e8ba3115 10684 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
10685 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10686 b->number, addrbuf, /* address */
10687 ((ndx == 0) ? "S" : ""),
10688 stepping_actions[ndx],
10689 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
10690 putpkt (buf);
10691 remote_get_noisy_reply (&target_buf,
10692 &target_buf_size);
10693 if (strcmp (target_buf, "OK"))
10694 error (_("Error on target while setting tracepoints."));
35b1e5cc 10695 }
e8ba3115 10696 }
409873ef 10697
e8ba3115
YQ
10698 if (remote_protocol_packets[PACKET_TracepointSource].support
10699 == PACKET_ENABLE)
10700 {
10701 if (b->addr_string)
409873ef 10702 {
e8ba3115
YQ
10703 strcpy (buf, "QTDPsrc:");
10704 encode_source_string (b->number, loc->address,
10705 "at", b->addr_string, buf + strlen (buf),
10706 2048 - strlen (buf));
409873ef 10707
e8ba3115
YQ
10708 putpkt (buf);
10709 remote_get_noisy_reply (&target_buf, &target_buf_size);
10710 if (strcmp (target_buf, "OK"))
10711 warning (_("Target does not support source download."));
409873ef 10712 }
e8ba3115
YQ
10713 if (b->cond_string)
10714 {
10715 strcpy (buf, "QTDPsrc:");
10716 encode_source_string (b->number, loc->address,
10717 "cond", b->cond_string, buf + strlen (buf),
10718 2048 - strlen (buf));
10719 putpkt (buf);
10720 remote_get_noisy_reply (&target_buf, &target_buf_size);
10721 if (strcmp (target_buf, "OK"))
10722 warning (_("Target does not support source download."));
10723 }
10724 remote_download_command_source (b->number, loc->address,
10725 breakpoint_commands (b));
35b1e5cc 10726 }
e8ba3115
YQ
10727
10728 do_cleanups (old_chain);
35b1e5cc
SS
10729}
10730
1e4d1764 10731static int
a52a8357 10732remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 10733{
1e51243a
PA
10734 struct remote_state *rs = get_remote_state ();
10735 struct trace_status *ts;
10736 int status;
10737
10738 /* Don't try to install tracepoints until we've relocated our
10739 symbols, and fetched and merged the target's tracepoint list with
10740 ours. */
10741 if (rs->starting_up)
10742 return 0;
10743
10744 ts = current_trace_status ();
8bd200f1 10745 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
10746
10747 if (status == -1 || !ts->running_known || !ts->running)
10748 return 0;
10749
10750 /* If we are in a tracing experiment, but remote stub doesn't support
10751 installing tracepoint in trace, we have to return. */
10752 if (!remote_supports_install_in_trace ())
10753 return 0;
10754
10755 return 1;
10756}
10757
10758
35b1e5cc 10759static void
559d2b81
TT
10760remote_download_trace_state_variable (struct target_ops *self,
10761 struct trace_state_variable *tsv)
35b1e5cc
SS
10762{
10763 struct remote_state *rs = get_remote_state ();
00bf0b85 10764 char *p;
35b1e5cc 10765
bba74b36
YQ
10766 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10767 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10768 tsv->builtin);
00bf0b85
SS
10769 p = rs->buf + strlen (rs->buf);
10770 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10771 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 10772 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 10773 *p++ = '\0';
35b1e5cc
SS
10774 putpkt (rs->buf);
10775 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
10776 if (*target_buf == '\0')
10777 error (_("Target does not support this command."));
10778 if (strcmp (target_buf, "OK") != 0)
10779 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
10780}
10781
d248b706 10782static void
46670d57
TT
10783remote_enable_tracepoint (struct target_ops *self,
10784 struct bp_location *location)
d248b706
KY
10785{
10786 struct remote_state *rs = get_remote_state ();
10787 char addr_buf[40];
10788
10789 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
10790 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10791 location->owner->number, addr_buf);
d248b706
KY
10792 putpkt (rs->buf);
10793 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10794 if (*rs->buf == '\0')
10795 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10796 if (strcmp (rs->buf, "OK") != 0)
10797 error (_("Error on target while enabling tracepoint."));
10798}
10799
10800static void
780b049c
TT
10801remote_disable_tracepoint (struct target_ops *self,
10802 struct bp_location *location)
d248b706
KY
10803{
10804 struct remote_state *rs = get_remote_state ();
10805 char addr_buf[40];
10806
10807 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
10808 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10809 location->owner->number, addr_buf);
d248b706
KY
10810 putpkt (rs->buf);
10811 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10812 if (*rs->buf == '\0')
10813 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10814 if (strcmp (rs->buf, "OK") != 0)
10815 error (_("Error on target while disabling tracepoint."));
10816}
10817
35b1e5cc 10818static void
583f9a86 10819remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
10820{
10821 asection *s;
81b9b86e 10822 bfd *abfd = NULL;
35b1e5cc 10823 bfd_size_type size;
608bcef2 10824 bfd_vma vma;
35b1e5cc 10825 int anysecs = 0;
c2fa21f1 10826 int offset = 0;
35b1e5cc
SS
10827
10828 if (!exec_bfd)
10829 return; /* No information to give. */
10830
10831 strcpy (target_buf, "QTro");
9779ab84 10832 offset = strlen (target_buf);
35b1e5cc
SS
10833 for (s = exec_bfd->sections; s; s = s->next)
10834 {
10835 char tmp1[40], tmp2[40];
c2fa21f1 10836 int sec_length;
35b1e5cc
SS
10837
10838 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 10839 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
10840 (s->flags & SEC_READONLY) == 0)
10841 continue;
10842
10843 anysecs = 1;
81b9b86e 10844 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 10845 size = bfd_get_section_size (s);
608bcef2
HZ
10846 sprintf_vma (tmp1, vma);
10847 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
10848 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10849 if (offset + sec_length + 1 > target_buf_size)
10850 {
864ac8a7
HZ
10851 if (remote_protocol_packets[PACKET_qXfer_traceframe_info].support
10852 != PACKET_ENABLE)
10853 warning (_("\
c2fa21f1
HZ
10854Too many sections for read-only sections definition packet."));
10855 break;
10856 }
bba74b36
YQ
10857 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10858 tmp1, tmp2);
c2fa21f1 10859 offset += sec_length;
35b1e5cc
SS
10860 }
10861 if (anysecs)
10862 {
10863 putpkt (target_buf);
10864 getpkt (&target_buf, &target_buf_size, 0);
10865 }
10866}
10867
10868static void
e2d1aae3 10869remote_trace_start (struct target_ops *self)
35b1e5cc
SS
10870{
10871 putpkt ("QTStart");
10872 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
10873 if (*target_buf == '\0')
10874 error (_("Target does not support this command."));
10875 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
10876 error (_("Bogus reply from target: %s"), target_buf);
10877}
10878
10879static int
8bd200f1 10880remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 10881{
953b98d1 10882 /* Initialize it just to avoid a GCC false warning. */
f652de6f 10883 char *p = NULL;
0df8b418 10884 /* FIXME we need to get register block size some other way. */
00bf0b85 10885 extern int trace_regblock_size;
67f41397 10886 volatile struct gdb_exception ex;
bd3eecc3
PA
10887 enum packet_result result;
10888
10889 if (remote_protocol_packets[PACKET_qTStatus].support == PACKET_DISABLE)
10890 return -1;
a744cf53 10891
00bf0b85
SS
10892 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10893
049dc89b
JK
10894 putpkt ("qTStatus");
10895
67f41397
JK
10896 TRY_CATCH (ex, RETURN_MASK_ERROR)
10897 {
10898 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10899 }
10900 if (ex.reason < 0)
10901 {
598d3636
JK
10902 if (ex.error != TARGET_CLOSE_ERROR)
10903 {
10904 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10905 return -1;
10906 }
10907 throw_exception (ex);
67f41397 10908 }
00bf0b85 10909
bd3eecc3
PA
10910 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
10911
00bf0b85 10912 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 10913 if (result == PACKET_UNKNOWN)
00bf0b85 10914 return -1;
35b1e5cc 10915
00bf0b85 10916 /* We're working with a live target. */
f5911ea1 10917 ts->filename = NULL;
00bf0b85 10918
00bf0b85 10919 if (*p++ != 'T')
35b1e5cc
SS
10920 error (_("Bogus trace status reply from target: %s"), target_buf);
10921
84cebc4a
YQ
10922 /* Function 'parse_trace_status' sets default value of each field of
10923 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
10924 parse_trace_status (p, ts);
10925
10926 return ts->running;
35b1e5cc
SS
10927}
10928
70221824 10929static void
db90e85c 10930remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
10931 struct uploaded_tp *utp)
10932{
10933 struct remote_state *rs = get_remote_state ();
f196051f
SS
10934 char *reply;
10935 struct bp_location *loc;
10936 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 10937 size_t size = get_remote_packet_size ();
f196051f
SS
10938
10939 if (tp)
10940 {
10941 tp->base.hit_count = 0;
10942 tp->traceframe_usage = 0;
10943 for (loc = tp->base.loc; loc; loc = loc->next)
10944 {
10945 /* If the tracepoint was never downloaded, don't go asking for
10946 any status. */
10947 if (tp->number_on_target == 0)
10948 continue;
bba74b36
YQ
10949 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
10950 phex_nz (loc->address, 0));
f196051f
SS
10951 putpkt (rs->buf);
10952 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10953 if (reply && *reply)
10954 {
10955 if (*reply == 'V')
10956 parse_tracepoint_status (reply + 1, bp, utp);
10957 }
10958 }
10959 }
10960 else if (utp)
10961 {
10962 utp->hit_count = 0;
10963 utp->traceframe_usage = 0;
bba74b36
YQ
10964 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
10965 phex_nz (utp->addr, 0));
f196051f
SS
10966 putpkt (rs->buf);
10967 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10968 if (reply && *reply)
10969 {
10970 if (*reply == 'V')
10971 parse_tracepoint_status (reply + 1, bp, utp);
10972 }
10973 }
10974}
10975
35b1e5cc 10976static void
74499f1b 10977remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
10978{
10979 putpkt ("QTStop");
10980 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
10981 if (*target_buf == '\0')
10982 error (_("Target does not support this command."));
10983 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
10984 error (_("Bogus reply from target: %s"), target_buf);
10985}
10986
10987static int
bd4c6793
TT
10988remote_trace_find (struct target_ops *self,
10989 enum trace_find_type type, int num,
cc5925ad 10990 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
10991 int *tpp)
10992{
10993 struct remote_state *rs = get_remote_state ();
bba74b36 10994 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
10995 char *p, *reply;
10996 int target_frameno = -1, target_tracept = -1;
10997
e6e4e701
PA
10998 /* Lookups other than by absolute frame number depend on the current
10999 trace selected, so make sure it is correct on the remote end
11000 first. */
11001 if (type != tfind_number)
11002 set_remote_traceframe ();
11003
35b1e5cc
SS
11004 p = rs->buf;
11005 strcpy (p, "QTFrame:");
11006 p = strchr (p, '\0');
11007 switch (type)
11008 {
11009 case tfind_number:
bba74b36 11010 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
11011 break;
11012 case tfind_pc:
bba74b36 11013 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
11014 break;
11015 case tfind_tp:
bba74b36 11016 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
11017 break;
11018 case tfind_range:
bba74b36
YQ
11019 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11020 phex_nz (addr2, 0));
35b1e5cc
SS
11021 break;
11022 case tfind_outside:
bba74b36
YQ
11023 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11024 phex_nz (addr2, 0));
35b1e5cc
SS
11025 break;
11026 default:
9b20d036 11027 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
11028 }
11029
11030 putpkt (rs->buf);
2f65bcb7 11031 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
11032 if (*reply == '\0')
11033 error (_("Target does not support this command."));
35b1e5cc
SS
11034
11035 while (reply && *reply)
11036 switch (*reply)
11037 {
11038 case 'F':
f197e0f1
VP
11039 p = ++reply;
11040 target_frameno = (int) strtol (p, &reply, 16);
11041 if (reply == p)
11042 error (_("Unable to parse trace frame number"));
e6e4e701
PA
11043 /* Don't update our remote traceframe number cache on failure
11044 to select a remote traceframe. */
f197e0f1
VP
11045 if (target_frameno == -1)
11046 return -1;
35b1e5cc
SS
11047 break;
11048 case 'T':
f197e0f1
VP
11049 p = ++reply;
11050 target_tracept = (int) strtol (p, &reply, 16);
11051 if (reply == p)
11052 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
11053 break;
11054 case 'O': /* "OK"? */
11055 if (reply[1] == 'K' && reply[2] == '\0')
11056 reply += 2;
11057 else
11058 error (_("Bogus reply from target: %s"), reply);
11059 break;
11060 default:
11061 error (_("Bogus reply from target: %s"), reply);
11062 }
11063 if (tpp)
11064 *tpp = target_tracept;
e6e4e701 11065
262e1174 11066 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
11067 return target_frameno;
11068}
11069
11070static int
4011015b
TT
11071remote_get_trace_state_variable_value (struct target_ops *self,
11072 int tsvnum, LONGEST *val)
35b1e5cc
SS
11073{
11074 struct remote_state *rs = get_remote_state ();
11075 char *reply;
11076 ULONGEST uval;
11077
e6e4e701
PA
11078 set_remote_traceframe ();
11079
bba74b36 11080 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
11081 putpkt (rs->buf);
11082 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11083 if (reply && *reply)
11084 {
11085 if (*reply == 'V')
11086 {
11087 unpack_varlen_hex (reply + 1, &uval);
11088 *val = (LONGEST) uval;
11089 return 1;
11090 }
11091 }
11092 return 0;
11093}
11094
00bf0b85 11095static int
dc3decaf 11096remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
11097{
11098 struct remote_state *rs = get_remote_state ();
11099 char *p, *reply;
11100
11101 p = rs->buf;
11102 strcpy (p, "QTSave:");
11103 p += strlen (p);
11104 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11105 error (_("Remote file name too long for trace save packet"));
9f1b45b0 11106 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
11107 *p++ = '\0';
11108 putpkt (rs->buf);
ad91cd99 11109 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 11110 if (*reply == '\0')
ad91cd99
PA
11111 error (_("Target does not support this command."));
11112 if (strcmp (reply, "OK") != 0)
11113 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
11114 return 0;
11115}
11116
11117/* This is basically a memory transfer, but needs to be its own packet
11118 because we don't know how the target actually organizes its trace
11119 memory, plus we want to be able to ask for as much as possible, but
11120 not be unhappy if we don't get as much as we ask for. */
11121
11122static LONGEST
88ee6f45
TT
11123remote_get_raw_trace_data (struct target_ops *self,
11124 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
11125{
11126 struct remote_state *rs = get_remote_state ();
11127 char *reply;
11128 char *p;
11129 int rslt;
11130
11131 p = rs->buf;
11132 strcpy (p, "qTBuffer:");
11133 p += strlen (p);
11134 p += hexnumstr (p, offset);
11135 *p++ = ',';
11136 p += hexnumstr (p, len);
11137 *p++ = '\0';
11138
11139 putpkt (rs->buf);
11140 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11141 if (reply && *reply)
11142 {
11143 /* 'l' by itself means we're at the end of the buffer and
11144 there is nothing more to get. */
11145 if (*reply == 'l')
11146 return 0;
11147
11148 /* Convert the reply into binary. Limit the number of bytes to
11149 convert according to our passed-in buffer size, rather than
11150 what was returned in the packet; if the target is
11151 unexpectedly generous and gives us a bigger reply than we
11152 asked for, we don't want to crash. */
11153 rslt = hex2bin (target_buf, buf, len);
11154 return rslt;
11155 }
11156
11157 /* Something went wrong, flag as an error. */
11158 return -1;
11159}
11160
35b1e5cc 11161static void
37b25738 11162remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
11163{
11164 struct remote_state *rs = get_remote_state ();
11165
33da3f1c
SS
11166 if (rs->disconnected_tracing)
11167 {
ad91cd99
PA
11168 char *reply;
11169
bba74b36 11170 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 11171 putpkt (rs->buf);
ad91cd99
PA
11172 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11173 if (*reply == '\0')
33da3f1c 11174 error (_("Target does not support this command."));
ad91cd99
PA
11175 if (strcmp (reply, "OK") != 0)
11176 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
11177 }
11178 else if (val)
11179 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
11180}
11181
dc146f7c
VP
11182static int
11183remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11184{
11185 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 11186
dc146f7c
VP
11187 if (info && info->private)
11188 return info->private->core;
11189 return -1;
11190}
11191
4daf5ac0 11192static void
736d5b1f 11193remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
11194{
11195 struct remote_state *rs = get_remote_state ();
ad91cd99 11196 char *reply;
4daf5ac0 11197
bba74b36 11198 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 11199 putpkt (rs->buf);
ad91cd99
PA
11200 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11201 if (*reply == '\0')
4daf5ac0 11202 error (_("Target does not support this command."));
ad91cd99
PA
11203 if (strcmp (reply, "OK") != 0)
11204 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
11205}
11206
b3b9301e 11207static struct traceframe_info *
a893e81f 11208remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
11209{
11210 char *text;
11211
11212 text = target_read_stralloc (&current_target,
11213 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11214 if (text != NULL)
11215 {
11216 struct traceframe_info *info;
11217 struct cleanup *back_to = make_cleanup (xfree, text);
11218
11219 info = parse_traceframe_info (text);
11220 do_cleanups (back_to);
11221 return info;
11222 }
11223
11224 return NULL;
11225}
11226
405f8e94
SS
11227/* Handle the qTMinFTPILen packet. Returns the minimum length of
11228 instruction on which a fast tracepoint may be placed. Returns -1
11229 if the packet is not supported, and 0 if the minimum instruction
11230 length is unknown. */
11231
11232static int
0e67620a 11233remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
11234{
11235 struct remote_state *rs = get_remote_state ();
11236 char *reply;
11237
e886a173
PA
11238 /* If we're not debugging a process yet, the IPA can't be
11239 loaded. */
11240 if (!target_has_execution)
11241 return 0;
11242
11243 /* Make sure the remote is pointing at the right process. */
11244 set_general_process ();
11245
bba74b36 11246 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
11247 putpkt (rs->buf);
11248 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11249 if (*reply == '\0')
11250 return -1;
11251 else
11252 {
11253 ULONGEST min_insn_len;
11254
11255 unpack_varlen_hex (reply, &min_insn_len);
11256
11257 return (int) min_insn_len;
11258 }
11259}
11260
f6f899bf 11261static void
4da384be 11262remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 11263{
90585175
HAQ
11264 if (remote_protocol_packets[PACKET_QTBuffer_size].support
11265 != PACKET_DISABLE)
f6f899bf
HAQ
11266 {
11267 struct remote_state *rs = get_remote_state ();
11268 char *buf = rs->buf;
11269 char *endbuf = rs->buf + get_remote_packet_size ();
11270 enum packet_result result;
11271
11272 gdb_assert (val >= 0 || val == -1);
11273 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11274 /* Send -1 as literal "-1" to avoid host size dependency. */
11275 if (val < 0)
11276 {
11277 *buf++ = '-';
11278 buf += hexnumstr (buf, (ULONGEST) -val);
11279 }
11280 else
11281 buf += hexnumstr (buf, (ULONGEST) val);
11282
11283 putpkt (rs->buf);
11284 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11285 result = packet_ok (rs->buf,
11286 &remote_protocol_packets[PACKET_QTBuffer_size]);
11287
11288 if (result != PACKET_OK)
11289 warning (_("Bogus reply from target: %s"), rs->buf);
11290 }
11291}
11292
f196051f 11293static int
d9e68a2c
TT
11294remote_set_trace_notes (struct target_ops *self,
11295 const char *user, const char *notes,
ca623f82 11296 const char *stop_notes)
f196051f
SS
11297{
11298 struct remote_state *rs = get_remote_state ();
11299 char *reply;
11300 char *buf = rs->buf;
11301 char *endbuf = rs->buf + get_remote_packet_size ();
11302 int nbytes;
11303
11304 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11305 if (user)
11306 {
11307 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 11308 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
11309 buf += 2 * nbytes;
11310 *buf++ = ';';
11311 }
11312 if (notes)
11313 {
11314 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 11315 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
11316 buf += 2 * nbytes;
11317 *buf++ = ';';
11318 }
11319 if (stop_notes)
11320 {
11321 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 11322 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
11323 buf += 2 * nbytes;
11324 *buf++ = ';';
11325 }
11326 /* Ensure the buffer is terminated. */
11327 *buf = '\0';
11328
11329 putpkt (rs->buf);
11330 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11331 if (*reply == '\0')
11332 return 0;
11333
11334 if (strcmp (reply, "OK") != 0)
11335 error (_("Bogus reply from target: %s"), reply);
11336
11337 return 1;
11338}
11339
d1feda86 11340static int
2c152180 11341remote_use_agent (struct target_ops *self, int use)
d1feda86
YQ
11342{
11343 if (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE)
11344 {
11345 struct remote_state *rs = get_remote_state ();
11346
11347 /* If the stub supports QAgent. */
bba74b36 11348 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
11349 putpkt (rs->buf);
11350 getpkt (&rs->buf, &rs->buf_size, 0);
11351
11352 if (strcmp (rs->buf, "OK") == 0)
11353 {
11354 use_agent = use;
11355 return 1;
11356 }
11357 }
11358
11359 return 0;
11360}
11361
11362static int
fe38f897 11363remote_can_use_agent (struct target_ops *self)
d1feda86
YQ
11364{
11365 return (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE);
11366}
11367
9accd112
MM
11368struct btrace_target_info
11369{
11370 /* The ptid of the traced thread. */
11371 ptid_t ptid;
11372};
11373
11374/* Check whether the target supports branch tracing. */
11375
11376static int
46917d26 11377remote_supports_btrace (struct target_ops *self)
9accd112
MM
11378{
11379 if (remote_protocol_packets[PACKET_Qbtrace_off].support != PACKET_ENABLE)
11380 return 0;
11381 if (remote_protocol_packets[PACKET_Qbtrace_bts].support != PACKET_ENABLE)
11382 return 0;
11383 if (remote_protocol_packets[PACKET_qXfer_btrace].support != PACKET_ENABLE)
11384 return 0;
11385
11386 return 1;
11387}
11388
11389/* Enable branch tracing. */
11390
11391static struct btrace_target_info *
e3c49f88 11392remote_enable_btrace (struct target_ops *self, ptid_t ptid)
9accd112
MM
11393{
11394 struct btrace_target_info *tinfo = NULL;
11395 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11396 struct remote_state *rs = get_remote_state ();
11397 char *buf = rs->buf;
11398 char *endbuf = rs->buf + get_remote_packet_size ();
11399
11400 if (packet->support != PACKET_ENABLE)
11401 error (_("Target does not support branch tracing."));
11402
11403 set_general_thread (ptid);
11404
11405 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11406 putpkt (rs->buf);
11407 getpkt (&rs->buf, &rs->buf_size, 0);
11408
11409 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11410 {
11411 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11412 error (_("Could not enable branch tracing for %s: %s"),
11413 target_pid_to_str (ptid), rs->buf + 2);
11414 else
11415 error (_("Could not enable branch tracing for %s."),
11416 target_pid_to_str (ptid));
11417 }
11418
11419 tinfo = xzalloc (sizeof (*tinfo));
11420 tinfo->ptid = ptid;
11421
11422 return tinfo;
11423}
11424
11425/* Disable branch tracing. */
11426
11427static void
25e95349
TT
11428remote_disable_btrace (struct target_ops *self,
11429 struct btrace_target_info *tinfo)
9accd112
MM
11430{
11431 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11432 struct remote_state *rs = get_remote_state ();
11433 char *buf = rs->buf;
11434 char *endbuf = rs->buf + get_remote_packet_size ();
11435
11436 if (packet->support != PACKET_ENABLE)
11437 error (_("Target does not support branch tracing."));
11438
11439 set_general_thread (tinfo->ptid);
11440
11441 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11442 putpkt (rs->buf);
11443 getpkt (&rs->buf, &rs->buf_size, 0);
11444
11445 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11446 {
11447 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11448 error (_("Could not disable branch tracing for %s: %s"),
11449 target_pid_to_str (tinfo->ptid), rs->buf + 2);
11450 else
11451 error (_("Could not disable branch tracing for %s."),
11452 target_pid_to_str (tinfo->ptid));
11453 }
11454
11455 xfree (tinfo);
11456}
11457
11458/* Teardown branch tracing. */
11459
11460static void
1777056d
TT
11461remote_teardown_btrace (struct target_ops *self,
11462 struct btrace_target_info *tinfo)
9accd112
MM
11463{
11464 /* We must not talk to the target during teardown. */
11465 xfree (tinfo);
11466}
11467
11468/* Read the branch trace. */
11469
969c39fb 11470static enum btrace_error
39c49f83
TT
11471remote_read_btrace (struct target_ops *self,
11472 VEC (btrace_block_s) **btrace,
969c39fb 11473 struct btrace_target_info *tinfo,
9accd112
MM
11474 enum btrace_read_type type)
11475{
11476 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11477 struct remote_state *rs = get_remote_state ();
969c39fb 11478 struct cleanup *cleanup;
9accd112
MM
11479 const char *annex;
11480 char *xml;
11481
11482 if (packet->support != PACKET_ENABLE)
11483 error (_("Target does not support branch tracing."));
11484
11485#if !defined(HAVE_LIBEXPAT)
11486 error (_("Cannot process branch tracing result. XML parsing not supported."));
11487#endif
11488
11489 switch (type)
11490 {
864089d2 11491 case BTRACE_READ_ALL:
9accd112
MM
11492 annex = "all";
11493 break;
864089d2 11494 case BTRACE_READ_NEW:
9accd112
MM
11495 annex = "new";
11496 break;
969c39fb
MM
11497 case BTRACE_READ_DELTA:
11498 annex = "delta";
11499 break;
9accd112
MM
11500 default:
11501 internal_error (__FILE__, __LINE__,
11502 _("Bad branch tracing read type: %u."),
11503 (unsigned int) type);
11504 }
11505
11506 xml = target_read_stralloc (&current_target,
11507 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
11508 if (xml == NULL)
11509 return BTRACE_ERR_UNKNOWN;
9accd112 11510
969c39fb
MM
11511 cleanup = make_cleanup (xfree, xml);
11512 *btrace = parse_xml_btrace (xml);
11513 do_cleanups (cleanup);
9accd112 11514
969c39fb 11515 return BTRACE_ERR_NONE;
9accd112
MM
11516}
11517
ced63ec0 11518static int
5436ff03 11519remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0
GB
11520{
11521 struct remote_state *rs = get_remote_state ();
11522
11523 return rs->augmented_libraries_svr4_read;
11524}
11525
9dd130a0
TT
11526/* Implementation of to_load. */
11527
11528static void
71a9f134 11529remote_load (struct target_ops *self, char *name, int from_tty)
9dd130a0
TT
11530{
11531 generic_load (name, from_tty);
11532}
11533
c906108c 11534static void
fba45db2 11535init_remote_ops (void)
c906108c 11536{
c5aa993b 11537 remote_ops.to_shortname = "remote";
c906108c 11538 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 11539 remote_ops.to_doc =
c906108c 11540 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
11541Specify the serial device it is connected to\n\
11542(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
11543 remote_ops.to_open = remote_open;
11544 remote_ops.to_close = remote_close;
c906108c 11545 remote_ops.to_detach = remote_detach;
6ad8ae5c 11546 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 11547 remote_ops.to_resume = remote_resume;
c906108c
SS
11548 remote_ops.to_wait = remote_wait;
11549 remote_ops.to_fetch_registers = remote_fetch_registers;
11550 remote_ops.to_store_registers = remote_store_registers;
11551 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 11552 remote_ops.to_files_info = remote_files_info;
c906108c
SS
11553 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11554 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
3c3bea1c
GS
11555 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11556 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
11557 remote_ops.to_watchpoint_addr_within_range =
11558 remote_watchpoint_addr_within_range;
3c3bea1c
GS
11559 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11560 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11561 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
11562 remote_ops.to_region_ok_for_hw_watchpoint
11563 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
11564 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11565 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 11566 remote_ops.to_kill = remote_kill;
9dd130a0 11567 remote_ops.to_load = remote_load;
c906108c 11568 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 11569 remote_ops.to_pass_signals = remote_pass_signals;
9b224c5e 11570 remote_ops.to_program_signals = remote_program_signals;
c906108c 11571 remote_ops.to_thread_alive = remote_thread_alive;
0f71a2f6 11572 remote_ops.to_find_new_threads = remote_threads_info;
0caabb7e 11573 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 11574 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 11575 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 11576 remote_ops.to_stop = remote_stop;
4b8a223f 11577 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 11578 remote_ops.to_rcmd = remote_rcmd;
49d03eab 11579 remote_ops.to_log_command = serial_log_command;
38691318 11580 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 11581 remote_ops.to_stratum = process_stratum;
c35b1492
PA
11582 remote_ops.to_has_all_memory = default_child_has_all_memory;
11583 remote_ops.to_has_memory = default_child_has_memory;
11584 remote_ops.to_has_stack = default_child_has_stack;
11585 remote_ops.to_has_registers = default_child_has_registers;
11586 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 11587 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 11588 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 11589 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 11590 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
11591 remote_ops.to_flash_erase = remote_flash_erase;
11592 remote_ops.to_flash_done = remote_flash_done;
29709017 11593 remote_ops.to_read_description = remote_read_description;
08388c79 11594 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
11595 remote_ops.to_can_async_p = remote_can_async_p;
11596 remote_ops.to_is_async_p = remote_is_async_p;
11597 remote_ops.to_async = remote_async;
75c99385
PA
11598 remote_ops.to_terminal_inferior = remote_terminal_inferior;
11599 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 11600 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 11601 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
11602 remote_ops.to_supports_disable_randomization
11603 = remote_supports_disable_randomization;
7313baad
UW
11604 remote_ops.to_fileio_open = remote_hostio_open;
11605 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11606 remote_ops.to_fileio_pread = remote_hostio_pread;
11607 remote_ops.to_fileio_close = remote_hostio_close;
11608 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 11609 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 11610 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 11611 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 11612 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 11613 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
11614 remote_ops.to_trace_init = remote_trace_init;
11615 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 11616 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
11617 remote_ops.to_download_trace_state_variable
11618 = remote_download_trace_state_variable;
d248b706
KY
11619 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11620 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
11621 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11622 remote_ops.to_trace_start = remote_trace_start;
11623 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 11624 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
11625 remote_ops.to_trace_stop = remote_trace_stop;
11626 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
11627 remote_ops.to_get_trace_state_variable_value
11628 = remote_get_trace_state_variable_value;
00bf0b85
SS
11629 remote_ops.to_save_trace_data = remote_save_trace_data;
11630 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
11631 remote_ops.to_upload_trace_state_variables
11632 = remote_upload_trace_state_variables;
00bf0b85 11633 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 11634 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 11635 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 11636 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 11637 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 11638 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 11639 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 11640 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 11641 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 11642 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
11643 remote_ops.to_static_tracepoint_marker_at
11644 = remote_static_tracepoint_marker_at;
11645 remote_ops.to_static_tracepoint_markers_by_strid
11646 = remote_static_tracepoint_markers_by_strid;
b3b9301e 11647 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
11648 remote_ops.to_use_agent = remote_use_agent;
11649 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
11650 remote_ops.to_supports_btrace = remote_supports_btrace;
11651 remote_ops.to_enable_btrace = remote_enable_btrace;
11652 remote_ops.to_disable_btrace = remote_disable_btrace;
11653 remote_ops.to_teardown_btrace = remote_teardown_btrace;
11654 remote_ops.to_read_btrace = remote_read_btrace;
ced63ec0
GB
11655 remote_ops.to_augmented_libraries_svr4_read =
11656 remote_augmented_libraries_svr4_read;
c906108c
SS
11657}
11658
11659/* Set up the extended remote vector by making a copy of the standard
11660 remote vector and adding to it. */
11661
11662static void
fba45db2 11663init_extended_remote_ops (void)
c906108c
SS
11664{
11665 extended_remote_ops = remote_ops;
11666
0f71a2f6 11667 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 11668 extended_remote_ops.to_longname =
c906108c 11669 "Extended remote serial target in gdb-specific protocol";
c5aa993b 11670 extended_remote_ops.to_doc =
c906108c 11671 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
11672Specify the serial device it is connected to (e.g. /dev/ttya).";
11673 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
11674 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11675 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
11676 extended_remote_ops.to_detach = extended_remote_detach;
11677 extended_remote_ops.to_attach = extended_remote_attach;
82f73884 11678 extended_remote_ops.to_kill = extended_remote_kill;
03583c20
UW
11679 extended_remote_ops.to_supports_disable_randomization
11680 = extended_remote_supports_disable_randomization;
0f71a2f6
JM
11681}
11682
6426a772 11683static int
6a109b6b 11684remote_can_async_p (struct target_ops *ops)
6426a772 11685{
5d93a237
TT
11686 struct remote_state *rs = get_remote_state ();
11687
c6ebd6cf 11688 if (!target_async_permitted)
75c99385
PA
11689 /* We only enable async when the user specifically asks for it. */
11690 return 0;
11691
23860348 11692 /* We're async whenever the serial device is. */
5d93a237 11693 return serial_can_async_p (rs->remote_desc);
6426a772
JM
11694}
11695
11696static int
6a109b6b 11697remote_is_async_p (struct target_ops *ops)
6426a772 11698{
5d93a237
TT
11699 struct remote_state *rs = get_remote_state ();
11700
c6ebd6cf 11701 if (!target_async_permitted)
75c99385
PA
11702 /* We only enable async when the user specifically asks for it. */
11703 return 0;
11704
23860348 11705 /* We're async whenever the serial device is. */
5d93a237 11706 return serial_is_async_p (rs->remote_desc);
6426a772
JM
11707}
11708
2acceee2
JM
11709/* Pass the SERIAL event on and up to the client. One day this code
11710 will be able to delay notifying the client of an event until the
23860348 11711 point where an entire packet has been received. */
2acceee2 11712
2acceee2
JM
11713static serial_event_ftype remote_async_serial_handler;
11714
6426a772 11715static void
819cc324 11716remote_async_serial_handler (struct serial *scb, void *context)
6426a772 11717{
88b496c3
TT
11718 struct remote_state *rs = context;
11719
2acceee2
JM
11720 /* Don't propogate error information up to the client. Instead let
11721 the client find out about the error by querying the target. */
88b496c3 11722 rs->async_client_callback (INF_REG_EVENT, rs->async_client_context);
2acceee2
JM
11723}
11724
74531fed
PA
11725static void
11726remote_async_inferior_event_handler (gdb_client_data data)
11727{
11728 inferior_event_handler (INF_REG_EVENT, NULL);
11729}
11730
2acceee2 11731static void
6a109b6b
TT
11732remote_async (struct target_ops *ops,
11733 void (*callback) (enum inferior_event_type event_type,
11734 void *context),
11735 void *context)
2acceee2 11736{
5d93a237
TT
11737 struct remote_state *rs = get_remote_state ();
11738
2acceee2
JM
11739 if (callback != NULL)
11740 {
88b496c3
TT
11741 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
11742 rs->async_client_callback = callback;
11743 rs->async_client_context = context;
2acceee2
JM
11744 }
11745 else
5d93a237 11746 serial_async (rs->remote_desc, NULL, NULL);
6426a772
JM
11747}
11748
5a2468f5 11749static void
c2d11a7d 11750set_remote_cmd (char *args, int from_tty)
5a2468f5 11751{
427c3a89 11752 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
5a2468f5
JM
11753}
11754
d471ea57
AC
11755static void
11756show_remote_cmd (char *args, int from_tty)
11757{
37a105a1 11758 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 11759 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
11760 struct cleanup *showlist_chain;
11761 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 11762 struct ui_out *uiout = current_uiout;
37a105a1
DJ
11763
11764 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
11765 for (; list != NULL; list = list->next)
11766 if (strcmp (list->name, "Z-packet") == 0)
11767 continue;
427c3a89
DJ
11768 else if (list->type == not_set_cmd)
11769 /* Alias commands are exactly like the original, except they
11770 don't have the normal type. */
11771 continue;
11772 else
37a105a1
DJ
11773 {
11774 struct cleanup *option_chain
11775 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 11776
37a105a1
DJ
11777 ui_out_field_string (uiout, "name", list->name);
11778 ui_out_text (uiout, ": ");
427c3a89 11779 if (list->type == show_cmd)
5b9afe8a 11780 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
11781 else
11782 cmd_func (list, NULL, from_tty);
37a105a1
DJ
11783 /* Close the tuple. */
11784 do_cleanups (option_chain);
11785 }
427c3a89
DJ
11786
11787 /* Close the tuple. */
11788 do_cleanups (showlist_chain);
d471ea57 11789}
5a2468f5 11790
0f71a2f6 11791
23860348 11792/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
11793static void
11794remote_new_objfile (struct objfile *objfile)
11795{
5d93a237
TT
11796 struct remote_state *rs = get_remote_state ();
11797
11798 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 11799 remote_check_symbols ();
dc8acb97
MS
11800}
11801
00bf0b85
SS
11802/* Pull all the tracepoints defined on the target and create local
11803 data structures representing them. We don't want to create real
11804 tracepoints yet, we don't want to mess up the user's existing
11805 collection. */
11806
11807static int
ab6617cc 11808remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 11809{
00bf0b85
SS
11810 struct remote_state *rs = get_remote_state ();
11811 char *p;
d5551862 11812
00bf0b85
SS
11813 /* Ask for a first packet of tracepoint definition. */
11814 putpkt ("qTfP");
11815 getpkt (&rs->buf, &rs->buf_size, 0);
11816 p = rs->buf;
11817 while (*p && *p != 'l')
d5551862 11818 {
00bf0b85
SS
11819 parse_tracepoint_definition (p, utpp);
11820 /* Ask for another packet of tracepoint definition. */
11821 putpkt ("qTsP");
11822 getpkt (&rs->buf, &rs->buf_size, 0);
11823 p = rs->buf;
d5551862 11824 }
00bf0b85 11825 return 0;
d5551862
SS
11826}
11827
00bf0b85 11828static int
181e3713
TT
11829remote_upload_trace_state_variables (struct target_ops *self,
11830 struct uploaded_tsv **utsvp)
d5551862 11831{
00bf0b85 11832 struct remote_state *rs = get_remote_state ();
d5551862 11833 char *p;
d5551862 11834
00bf0b85
SS
11835 /* Ask for a first packet of variable definition. */
11836 putpkt ("qTfV");
d5551862
SS
11837 getpkt (&rs->buf, &rs->buf_size, 0);
11838 p = rs->buf;
00bf0b85 11839 while (*p && *p != 'l')
d5551862 11840 {
00bf0b85
SS
11841 parse_tsv_definition (p, utsvp);
11842 /* Ask for another packet of variable definition. */
11843 putpkt ("qTsV");
d5551862
SS
11844 getpkt (&rs->buf, &rs->buf_size, 0);
11845 p = rs->buf;
11846 }
00bf0b85 11847 return 0;
d5551862
SS
11848}
11849
c1e36e3e
PA
11850/* The "set/show range-stepping" show hook. */
11851
11852static void
11853show_range_stepping (struct ui_file *file, int from_tty,
11854 struct cmd_list_element *c,
11855 const char *value)
11856{
11857 fprintf_filtered (file,
11858 _("Debugger's willingness to use range stepping "
11859 "is %s.\n"), value);
11860}
11861
11862/* The "set/show range-stepping" set hook. */
11863
11864static void
11865set_range_stepping (char *ignore_args, int from_tty,
11866 struct cmd_list_element *c)
11867{
5d93a237
TT
11868 struct remote_state *rs = get_remote_state ();
11869
c1e36e3e
PA
11870 /* Whene enabling, check whether range stepping is actually
11871 supported by the target, and warn if not. */
11872 if (use_range_stepping)
11873 {
5d93a237 11874 if (rs->remote_desc != NULL)
c1e36e3e 11875 {
c1e36e3e
PA
11876 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
11877 remote_vcont_probe (rs);
11878
11879 if (remote_protocol_packets[PACKET_vCont].support == PACKET_ENABLE
11880 && rs->supports_vCont.r)
11881 return;
11882 }
11883
11884 warning (_("Range stepping is not supported by the current target"));
11885 }
11886}
11887
c906108c 11888void
fba45db2 11889_initialize_remote (void)
c906108c 11890{
ea9c271d 11891 struct remote_state *rs;
9a7071a8 11892 struct cmd_list_element *cmd;
6f937416 11893 const char *cmd_name;
ea9c271d 11894
0f71a2f6 11895 /* architecture specific data */
2bc416ba 11896 remote_gdbarch_data_handle =
23860348 11897 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
11898 remote_g_packet_data_handle =
11899 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 11900
ea9c271d
DJ
11901 /* Initialize the per-target state. At the moment there is only one
11902 of these, not one per target. Only one target is active at a
cf792862
TT
11903 time. */
11904 remote_state = new_remote_state ();
ea9c271d 11905
c906108c
SS
11906 init_remote_ops ();
11907 add_target (&remote_ops);
11908
11909 init_extended_remote_ops ();
11910 add_target (&extended_remote_ops);
cce74817 11911
dc8acb97 11912 /* Hook into new objfile notification. */
06d3b283 11913 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
11914 /* We're no longer interested in notification events of an inferior
11915 when it exits. */
11916 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 11917
b803fb0f 11918 /* Set up signal handlers. */
934b9bac 11919 async_sigint_remote_token =
b803fb0f 11920 create_async_signal_handler (async_remote_interrupt, NULL);
934b9bac 11921 async_sigint_remote_twice_token =
6d549500 11922 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 11923
c906108c
SS
11924#if 0
11925 init_remote_threadtests ();
11926#endif
11927
722247f1 11928 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 11929 /* set/show remote ... */
d471ea57 11930
1bedd215 11931 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
11932Remote protocol specific variables\n\
11933Configure various remote-protocol specific variables such as\n\
1bedd215 11934the packets being used"),
cff3e48b 11935 &remote_set_cmdlist, "set remote ",
23860348 11936 0 /* allow-unknown */, &setlist);
1bedd215 11937 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
11938Remote protocol specific variables\n\
11939Configure various remote-protocol specific variables such as\n\
1bedd215 11940the packets being used"),
cff3e48b 11941 &remote_show_cmdlist, "show remote ",
23860348 11942 0 /* allow-unknown */, &showlist);
5a2468f5 11943
1a966eab
AC
11944 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
11945Compare section data on target to the exec file.\n\
11946Argument is a single section name (default: all loaded sections)."),
c906108c
SS
11947 &cmdlist);
11948
1a966eab
AC
11949 add_cmd ("packet", class_maintenance, packet_command, _("\
11950Send an arbitrary packet to a remote target.\n\
c906108c
SS
11951 maintenance packet TEXT\n\
11952If GDB is talking to an inferior via the GDB serial protocol, then\n\
11953this command sends the string TEXT to the inferior, and displays the\n\
11954response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 11955terminating `#' character and checksum."),
c906108c
SS
11956 &maintenancelist);
11957
7915a72c
AC
11958 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
11959Set whether to send break if interrupted."), _("\
11960Show whether to send break if interrupted."), _("\
11961If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 11962 set_remotebreak, show_remotebreak,
e707bbc2 11963 &setlist, &showlist);
9a7071a8
JB
11964 cmd_name = "remotebreak";
11965 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
11966 deprecate_cmd (cmd, "set remote interrupt-sequence");
11967 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
11968 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
11969 deprecate_cmd (cmd, "show remote interrupt-sequence");
11970
11971 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
11972 interrupt_sequence_modes, &interrupt_sequence_mode,
11973 _("\
9a7071a8
JB
11974Set interrupt sequence to remote target."), _("\
11975Show interrupt sequence to remote target."), _("\
11976Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
11977 NULL, show_interrupt_sequence,
11978 &remote_set_cmdlist,
11979 &remote_show_cmdlist);
11980
11981 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
11982 &interrupt_on_connect, _("\
11983Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11984Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11985If set, interrupt sequence is sent to remote target."),
11986 NULL, NULL,
11987 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 11988
23860348 11989 /* Install commands for configuring memory read/write packets. */
11cf8741 11990
1a966eab
AC
11991 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
11992Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 11993 &setlist);
1a966eab
AC
11994 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
11995Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
11996 &showlist);
11997 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
11998 set_memory_write_packet_size, _("\
11999Set the maximum number of bytes per memory-write packet.\n\
12000Specify the number of bytes in a packet or 0 (zero) for the\n\
12001default packet size. The actual limit is further reduced\n\
12002dependent on the target. Specify ``fixed'' to disable the\n\
12003further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
12004 &remote_set_cmdlist);
12005 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
12006 set_memory_read_packet_size, _("\
12007Set the maximum number of bytes per memory-read packet.\n\
12008Specify the number of bytes in a packet or 0 (zero) for the\n\
12009default packet size. The actual limit is further reduced\n\
12010dependent on the target. Specify ``fixed'' to disable the\n\
12011further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
12012 &remote_set_cmdlist);
12013 add_cmd ("memory-write-packet-size", no_class,
12014 show_memory_write_packet_size,
1a966eab 12015 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
12016 &remote_show_cmdlist);
12017 add_cmd ("memory-read-packet-size", no_class,
12018 show_memory_read_packet_size,
1a966eab 12019 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 12020 &remote_show_cmdlist);
c906108c 12021
b3f42336 12022 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
12023 &remote_hw_watchpoint_limit, _("\
12024Set the maximum number of target hardware watchpoints."), _("\
12025Show the maximum number of target hardware watchpoints."), _("\
12026Specify a negative limit for unlimited."),
3e43a32a
MS
12027 NULL, NULL, /* FIXME: i18n: The maximum
12028 number of target hardware
12029 watchpoints is %s. */
b3f42336 12030 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
12031 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
12032 &remote_hw_watchpoint_length_limit, _("\
12033Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
12034Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
12035Specify a negative limit for unlimited."),
12036 NULL, NULL, /* FIXME: i18n: The maximum
12037 length (in bytes) of a target
12038 hardware watchpoint is %s. */
12039 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 12040 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
12041 &remote_hw_breakpoint_limit, _("\
12042Set the maximum number of target hardware breakpoints."), _("\
12043Show the maximum number of target hardware breakpoints."), _("\
12044Specify a negative limit for unlimited."),
3e43a32a
MS
12045 NULL, NULL, /* FIXME: i18n: The maximum
12046 number of target hardware
12047 breakpoints is %s. */
b3f42336 12048 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 12049
1b493192
PA
12050 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
12051 &remote_address_size, _("\
4d28ad1e
AC
12052Set the maximum size of the address (in bits) in a memory packet."), _("\
12053Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
12054 NULL,
12055 NULL, /* FIXME: i18n: */
12056 &setlist, &showlist);
c906108c 12057
444abaca 12058 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 12059 "X", "binary-download", 1);
0f71a2f6 12060
444abaca 12061 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 12062 "vCont", "verbose-resume", 0);
506fb367 12063
89be2091
DJ
12064 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
12065 "QPassSignals", "pass-signals", 0);
12066
9b224c5e
PA
12067 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
12068 "QProgramSignals", "program-signals", 0);
12069
444abaca 12070 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 12071 "qSymbol", "symbol-lookup", 0);
dc8acb97 12072
444abaca 12073 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 12074 "P", "set-register", 1);
d471ea57 12075
444abaca 12076 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 12077 "p", "fetch-register", 1);
b96ec7ac 12078
444abaca 12079 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 12080 "Z0", "software-breakpoint", 0);
d471ea57 12081
444abaca 12082 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 12083 "Z1", "hardware-breakpoint", 0);
d471ea57 12084
444abaca 12085 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 12086 "Z2", "write-watchpoint", 0);
d471ea57 12087
444abaca 12088 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 12089 "Z3", "read-watchpoint", 0);
d471ea57 12090
444abaca 12091 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 12092 "Z4", "access-watchpoint", 0);
d471ea57 12093
0876f84a
DJ
12094 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
12095 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 12096
23181151
DJ
12097 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
12098 "qXfer:features:read", "target-features", 0);
12099
cfa9d6d9
DJ
12100 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
12101 "qXfer:libraries:read", "library-info", 0);
12102
2268b414
JK
12103 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12104 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12105
fd79ecee
DJ
12106 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12107 "qXfer:memory-map:read", "memory-map", 0);
12108
0e7f50da
UW
12109 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12110 "qXfer:spu:read", "read-spu-object", 0);
12111
12112 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12113 "qXfer:spu:write", "write-spu-object", 0);
12114
07e059b5
VP
12115 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12116 "qXfer:osdata:read", "osdata", 0);
12117
dc146f7c
VP
12118 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12119 "qXfer:threads:read", "threads", 0);
12120
4aa995e1
PA
12121 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12122 "qXfer:siginfo:read", "read-siginfo-object", 0);
12123
12124 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12125 "qXfer:siginfo:write", "write-siginfo-object", 0);
12126
b3b9301e
PA
12127 add_packet_config_cmd
12128 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 12129 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 12130
169081d0
TG
12131 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12132 "qXfer:uib:read", "unwind-info-block", 0);
12133
444abaca 12134 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 12135 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
12136 0);
12137
711e434b
PM
12138 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12139 "qGetTIBAddr", "get-thread-information-block-address",
12140 0);
12141
40ab02ce
MS
12142 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12143 "bc", "reverse-continue", 0);
12144
12145 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12146 "bs", "reverse-step", 0);
12147
be2a5f71
DJ
12148 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12149 "qSupported", "supported-packets", 0);
12150
08388c79
DE
12151 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12152 "qSearch:memory", "search-memory", 0);
12153
bd3eecc3
PA
12154 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12155 "qTStatus", "trace-status", 0);
12156
a6b151f1
DJ
12157 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12158 "vFile:open", "hostio-open", 0);
12159
12160 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12161 "vFile:pread", "hostio-pread", 0);
12162
12163 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12164 "vFile:pwrite", "hostio-pwrite", 0);
12165
12166 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12167 "vFile:close", "hostio-close", 0);
12168
12169 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12170 "vFile:unlink", "hostio-unlink", 0);
12171
b9e7b9c3
UW
12172 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12173 "vFile:readlink", "hostio-readlink", 0);
12174
2d717e4f
DJ
12175 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12176 "vAttach", "attach", 0);
12177
12178 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12179 "vRun", "run", 0);
12180
a6f3e723
SL
12181 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12182 "QStartNoAckMode", "noack", 0);
12183
82f73884
PA
12184 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12185 "vKill", "kill", 0);
12186
0b16c5cf
PA
12187 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12188 "qAttached", "query-attached", 0);
12189
782b2b07 12190 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
12191 "ConditionalTracepoints",
12192 "conditional-tracepoints", 0);
3788aec7
LM
12193
12194 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12195 "ConditionalBreakpoints",
12196 "conditional-breakpoints", 0);
12197
d3ce09f5
SS
12198 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12199 "BreakpointCommands",
12200 "breakpoint-commands", 0);
12201
7a697b8d
SS
12202 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12203 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 12204
409873ef
SS
12205 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12206 "TracepointSource", "TracepointSource", 0);
12207
d914c394
SS
12208 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12209 "QAllow", "allow", 0);
12210
0fb4aa4b
PA
12211 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12212 "StaticTracepoints", "static-tracepoints", 0);
12213
1e4d1764
YQ
12214 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12215 "InstallInTrace", "install-in-trace", 0);
12216
0fb4aa4b
PA
12217 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12218 "qXfer:statictrace:read", "read-sdata-object", 0);
12219
78d85199
YQ
12220 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12221 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12222
03583c20
UW
12223 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12224 "QDisableRandomization", "disable-randomization", 0);
12225
d1feda86
YQ
12226 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12227 "QAgent", "agent", 0);
12228
f6f899bf
HAQ
12229 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12230 "QTBuffer:size", "trace-buffer-size", 0);
12231
9accd112
MM
12232 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12233 "Qbtrace:off", "disable-btrace", 0);
12234
12235 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12236 "Qbtrace:bts", "enable-btrace", 0);
12237
12238 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12239 "qXfer:btrace", "read-btrace", 0);
12240
37a105a1
DJ
12241 /* Keep the old ``set remote Z-packet ...'' working. Each individual
12242 Z sub-packet has its own set and show commands, but users may
12243 have sets to this variable in their .gdbinit files (or in their
12244 documentation). */
e9e68a56 12245 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
12246 &remote_Z_packet_detect, _("\
12247Set use of remote protocol `Z' packets"), _("\
12248Show use of remote protocol `Z' packets "), _("\
3b64bf98 12249When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 12250packets."),
e9e68a56 12251 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
12252 show_remote_protocol_Z_packet_cmd,
12253 /* FIXME: i18n: Use of remote protocol
12254 `Z' packets is %s. */
e9e68a56 12255 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 12256
a6b151f1
DJ
12257 add_prefix_cmd ("remote", class_files, remote_command, _("\
12258Manipulate files on the remote system\n\
12259Transfer files to and from the remote target system."),
12260 &remote_cmdlist, "remote ",
12261 0 /* allow-unknown */, &cmdlist);
12262
12263 add_cmd ("put", class_files, remote_put_command,
12264 _("Copy a local file to the remote system."),
12265 &remote_cmdlist);
12266
12267 add_cmd ("get", class_files, remote_get_command,
12268 _("Copy a remote file to the local system."),
12269 &remote_cmdlist);
12270
12271 add_cmd ("delete", class_files, remote_delete_command,
12272 _("Delete a remote file."),
12273 &remote_cmdlist);
12274
2d717e4f
DJ
12275 remote_exec_file = xstrdup ("");
12276 add_setshow_string_noescape_cmd ("exec-file", class_files,
12277 &remote_exec_file, _("\
12278Set the remote pathname for \"run\""), _("\
12279Show the remote pathname for \"run\""), NULL, NULL, NULL,
12280 &remote_set_cmdlist, &remote_show_cmdlist);
12281
c1e36e3e
PA
12282 add_setshow_boolean_cmd ("range-stepping", class_run,
12283 &use_range_stepping, _("\
12284Enable or disable range stepping."), _("\
12285Show whether target-assisted range stepping is enabled."), _("\
12286If on, and the target supports it, when stepping a source line, GDB\n\
12287tells the target to step the corresponding range of addresses itself instead\n\
12288of issuing multiple single-steps. This speeds up source level\n\
12289stepping. If off, GDB always issues single-steps, even if range\n\
12290stepping is supported by the target. The default is on."),
12291 set_range_stepping,
12292 show_range_stepping,
12293 &setlist,
12294 &showlist);
12295
449092f6
CV
12296 /* Eventually initialize fileio. See fileio.c */
12297 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 12298
ba348170 12299 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 12300 special ptids with it set to != 0. */
ba348170
PA
12301 magic_null_ptid = ptid_build (42000, -1, 1);
12302 not_sent_ptid = ptid_build (42000, -2, 1);
12303 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
12304
12305 target_buf_size = 2048;
12306 target_buf = xmalloc (target_buf_size);
c906108c 12307}
10760264 12308
This page took 3.166319 seconds and 4 git commands to generate.