]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
Add target_ops argument to to_traceframe_info
[thirdparty/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
1882 if (ptid_get_pid (ptid) != 0 && ptid_get_tid (ptid) == 0)
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 }
2020 tid = ptid_get_tid (ptid);
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;
2050 return ptid_build (pid, 0, tid);
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;
2067 return ptid_build (pid, 0, tid);
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
PA
2559 int pid = ptid_get_pid (inferior_ptid);
2560 ptid_t ptid = ptid_build (pid, 0, threadref_to_int (ref));
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
PA
2828 if (ptid_equal (tp->ptid, magic_null_ptid)
2829 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_tid (tp->ptid) == 0))
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;
79d7f229 2868 int_to_threadref (&id, ptid_get_tid (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
JB
2977{
2978 return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
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
MS
3672 char *msg, *reply, *tmp;
3673 struct minimal_symbol *sym;
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 {
3704 tmp = &reply[8];
cfd77fa1 3705 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
3706 msg[end] = '\0';
3707 sym = lookup_minimal_symbol (msg, NULL, NULL);
3708 if (sym == NULL)
ea9c271d 3709 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 3710 else
2bbe3cc1 3711 {
f5656ead 3712 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
2bbe3cc1
DJ
3713 CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
3714
3715 /* If this is a function address, return the start of code
3716 instead of any data function descriptor. */
f5656ead 3717 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
3718 sym_addr,
3719 &current_target);
3720
3721 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 3722 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
3723 }
3724
dc8acb97 3725 putpkt (msg);
6d820c5c 3726 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3727 reply = rs->buf;
dc8acb97
MS
3728 }
3729}
3730
9db8d71f
DJ
3731static struct serial *
3732remote_serial_open (char *name)
3733{
3734 static int udp_warning = 0;
3735
3736 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3737 of in ser-tcp.c, because it is the remote protocol assuming that the
3738 serial connection is reliable and not the serial connection promising
3739 to be. */
3740 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
3741 {
3e43a32a
MS
3742 warning (_("The remote protocol may be unreliable over UDP.\n"
3743 "Some events may be lost, rendering further debugging "
3744 "impossible."));
9db8d71f
DJ
3745 udp_warning = 1;
3746 }
3747
3748 return serial_open (name);
3749}
3750
d914c394
SS
3751/* Inform the target of our permission settings. The permission flags
3752 work without this, but if the target knows the settings, it can do
3753 a couple things. First, it can add its own check, to catch cases
3754 that somehow manage to get by the permissions checks in target
3755 methods. Second, if the target is wired to disallow particular
3756 settings (for instance, a system in the field that is not set up to
3757 be able to stop at a breakpoint), it can object to any unavailable
3758 permissions. */
3759
3760void
c378d69d 3761remote_set_permissions (struct target_ops *self)
d914c394
SS
3762{
3763 struct remote_state *rs = get_remote_state ();
3764
bba74b36
YQ
3765 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3766 "WriteReg:%x;WriteMem:%x;"
3767 "InsertBreak:%x;InsertTrace:%x;"
3768 "InsertFastTrace:%x;Stop:%x",
3769 may_write_registers, may_write_memory,
3770 may_insert_breakpoints, may_insert_tracepoints,
3771 may_insert_fast_tracepoints, may_stop);
d914c394
SS
3772 putpkt (rs->buf);
3773 getpkt (&rs->buf, &rs->buf_size, 0);
3774
3775 /* If the target didn't like the packet, warn the user. Do not try
3776 to undo the user's settings, that would just be maddening. */
3777 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 3778 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
3779}
3780
be2a5f71
DJ
3781/* This type describes each known response to the qSupported
3782 packet. */
3783struct protocol_feature
3784{
3785 /* The name of this protocol feature. */
3786 const char *name;
3787
3788 /* The default for this protocol feature. */
3789 enum packet_support default_support;
3790
3791 /* The function to call when this feature is reported, or after
3792 qSupported processing if the feature is not supported.
3793 The first argument points to this structure. The second
3794 argument indicates whether the packet requested support be
3795 enabled, disabled, or probed (or the default, if this function
3796 is being called at the end of processing and this feature was
3797 not reported). The third argument may be NULL; if not NULL, it
3798 is a NUL-terminated string taken from the packet following
3799 this feature's name and an equals sign. */
3800 void (*func) (const struct protocol_feature *, enum packet_support,
3801 const char *);
3802
3803 /* The corresponding packet for this feature. Only used if
3804 FUNC is remote_supported_packet. */
3805 int packet;
3806};
3807
be2a5f71
DJ
3808static void
3809remote_supported_packet (const struct protocol_feature *feature,
3810 enum packet_support support,
3811 const char *argument)
3812{
3813 if (argument)
3814 {
3815 warning (_("Remote qSupported response supplied an unexpected value for"
3816 " \"%s\"."), feature->name);
3817 return;
3818 }
3819
3820 if (remote_protocol_packets[feature->packet].support
3821 == PACKET_SUPPORT_UNKNOWN)
3822 remote_protocol_packets[feature->packet].support = support;
3823}
be2a5f71
DJ
3824
3825static void
3826remote_packet_size (const struct protocol_feature *feature,
3827 enum packet_support support, const char *value)
3828{
3829 struct remote_state *rs = get_remote_state ();
3830
3831 int packet_size;
3832 char *value_end;
3833
3834 if (support != PACKET_ENABLE)
3835 return;
3836
3837 if (value == NULL || *value == '\0')
3838 {
3839 warning (_("Remote target reported \"%s\" without a size."),
3840 feature->name);
3841 return;
3842 }
3843
3844 errno = 0;
3845 packet_size = strtol (value, &value_end, 16);
3846 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3847 {
3848 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3849 feature->name, value);
3850 return;
3851 }
3852
3853 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3854 {
3855 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3856 packet_size, MAX_REMOTE_PACKET_SIZE);
3857 packet_size = MAX_REMOTE_PACKET_SIZE;
3858 }
3859
3860 /* Record the new maximum packet size. */
3861 rs->explicit_packet_size = packet_size;
3862}
3863
82f73884
PA
3864static void
3865remote_multi_process_feature (const struct protocol_feature *feature,
3866 enum packet_support support, const char *value)
3867{
3868 struct remote_state *rs = get_remote_state ();
a744cf53 3869
82f73884
PA
3870 rs->multi_process_aware = (support == PACKET_ENABLE);
3871}
3872
74531fed
PA
3873static void
3874remote_non_stop_feature (const struct protocol_feature *feature,
3875 enum packet_support support, const char *value)
3876{
3877 struct remote_state *rs = get_remote_state ();
a744cf53 3878
74531fed
PA
3879 rs->non_stop_aware = (support == PACKET_ENABLE);
3880}
3881
782b2b07
SS
3882static void
3883remote_cond_tracepoint_feature (const struct protocol_feature *feature,
3884 enum packet_support support,
3885 const char *value)
3886{
3887 struct remote_state *rs = get_remote_state ();
a744cf53 3888
782b2b07
SS
3889 rs->cond_tracepoints = (support == PACKET_ENABLE);
3890}
3891
3788aec7
LM
3892static void
3893remote_cond_breakpoint_feature (const struct protocol_feature *feature,
3894 enum packet_support support,
3895 const char *value)
3896{
3897 struct remote_state *rs = get_remote_state ();
3898
3899 rs->cond_breakpoints = (support == PACKET_ENABLE);
3900}
3901
d3ce09f5
SS
3902static void
3903remote_breakpoint_commands_feature (const struct protocol_feature *feature,
3904 enum packet_support support,
3905 const char *value)
3906{
3907 struct remote_state *rs = get_remote_state ();
3908
3909 rs->breakpoint_commands = (support == PACKET_ENABLE);
3910}
3911
7a697b8d
SS
3912static void
3913remote_fast_tracepoint_feature (const struct protocol_feature *feature,
3914 enum packet_support support,
3915 const char *value)
3916{
3917 struct remote_state *rs = get_remote_state ();
a744cf53 3918
7a697b8d
SS
3919 rs->fast_tracepoints = (support == PACKET_ENABLE);
3920}
3921
0fb4aa4b
PA
3922static void
3923remote_static_tracepoint_feature (const struct protocol_feature *feature,
3924 enum packet_support support,
3925 const char *value)
3926{
3927 struct remote_state *rs = get_remote_state ();
3928
3929 rs->static_tracepoints = (support == PACKET_ENABLE);
3930}
3931
1e4d1764
YQ
3932static void
3933remote_install_in_trace_feature (const struct protocol_feature *feature,
3934 enum packet_support support,
3935 const char *value)
3936{
3937 struct remote_state *rs = get_remote_state ();
3938
3939 rs->install_in_trace = (support == PACKET_ENABLE);
3940}
3941
d5551862
SS
3942static void
3943remote_disconnected_tracing_feature (const struct protocol_feature *feature,
3944 enum packet_support support,
3945 const char *value)
3946{
3947 struct remote_state *rs = get_remote_state ();
a744cf53 3948
d5551862
SS
3949 rs->disconnected_tracing = (support == PACKET_ENABLE);
3950}
3951
d248b706
KY
3952static void
3953remote_enable_disable_tracepoint_feature (const struct protocol_feature *feature,
3954 enum packet_support support,
3955 const char *value)
3956{
3957 struct remote_state *rs = get_remote_state ();
3958
3959 rs->enable_disable_tracepoints = (support == PACKET_ENABLE);
3960}
3961
3065dfb6
SS
3962static void
3963remote_string_tracing_feature (const struct protocol_feature *feature,
3964 enum packet_support support,
3965 const char *value)
3966{
3967 struct remote_state *rs = get_remote_state ();
3968
3969 rs->string_tracing = (support == PACKET_ENABLE);
3970}
3971
ced63ec0
GB
3972static void
3973remote_augmented_libraries_svr4_read_feature
3974 (const struct protocol_feature *feature,
3975 enum packet_support support, const char *value)
3976{
3977 struct remote_state *rs = get_remote_state ();
3978
3979 rs->augmented_libraries_svr4_read = (support == PACKET_ENABLE);
3980}
3981
dc473cfb 3982static const struct protocol_feature remote_protocol_features[] = {
0876f84a 3983 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 3984 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 3985 PACKET_qXfer_auxv },
23181151
DJ
3986 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3987 PACKET_qXfer_features },
cfa9d6d9
DJ
3988 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3989 PACKET_qXfer_libraries },
2268b414
JK
3990 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
3991 PACKET_qXfer_libraries_svr4 },
ced63ec0
GB
3992 { "augmented-libraries-svr4-read", PACKET_DISABLE,
3993 remote_augmented_libraries_svr4_read_feature, -1 },
fd79ecee 3994 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 3995 PACKET_qXfer_memory_map },
4de6483e
UW
3996 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3997 PACKET_qXfer_spu_read },
3998 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3999 PACKET_qXfer_spu_write },
07e059b5
VP
4000 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4001 PACKET_qXfer_osdata },
dc146f7c
VP
4002 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4003 PACKET_qXfer_threads },
b3b9301e
PA
4004 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4005 PACKET_qXfer_traceframe_info },
89be2091
DJ
4006 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4007 PACKET_QPassSignals },
9b224c5e
PA
4008 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4009 PACKET_QProgramSignals },
a6f3e723
SL
4010 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4011 PACKET_QStartNoAckMode },
82f73884 4012 { "multiprocess", PACKET_DISABLE, remote_multi_process_feature, -1 },
74531fed 4013 { "QNonStop", PACKET_DISABLE, remote_non_stop_feature, -1 },
4aa995e1
PA
4014 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4015 PACKET_qXfer_siginfo_read },
4016 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4017 PACKET_qXfer_siginfo_write },
782b2b07
SS
4018 { "ConditionalTracepoints", PACKET_DISABLE, remote_cond_tracepoint_feature,
4019 PACKET_ConditionalTracepoints },
3788aec7
LM
4020 { "ConditionalBreakpoints", PACKET_DISABLE, remote_cond_breakpoint_feature,
4021 PACKET_ConditionalBreakpoints },
d3ce09f5
SS
4022 { "BreakpointCommands", PACKET_DISABLE, remote_breakpoint_commands_feature,
4023 PACKET_BreakpointCommands },
7a697b8d
SS
4024 { "FastTracepoints", PACKET_DISABLE, remote_fast_tracepoint_feature,
4025 PACKET_FastTracepoints },
0fb4aa4b
PA
4026 { "StaticTracepoints", PACKET_DISABLE, remote_static_tracepoint_feature,
4027 PACKET_StaticTracepoints },
1e4d1764
YQ
4028 {"InstallInTrace", PACKET_DISABLE, remote_install_in_trace_feature,
4029 PACKET_InstallInTrace},
d5551862
SS
4030 { "DisconnectedTracing", PACKET_DISABLE, remote_disconnected_tracing_feature,
4031 -1 },
40ab02ce
MS
4032 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4033 PACKET_bc },
4034 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4035 PACKET_bs },
409873ef
SS
4036 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4037 PACKET_TracepointSource },
d914c394
SS
4038 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4039 PACKET_QAllow },
d248b706
KY
4040 { "EnableDisableTracepoints", PACKET_DISABLE,
4041 remote_enable_disable_tracepoint_feature, -1 },
78d85199
YQ
4042 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4043 PACKET_qXfer_fdpic },
169081d0
TG
4044 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4045 PACKET_qXfer_uib },
03583c20
UW
4046 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4047 PACKET_QDisableRandomization },
d1feda86 4048 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4049 { "QTBuffer:size", PACKET_DISABLE,
4050 remote_supported_packet, PACKET_QTBuffer_size},
3065dfb6
SS
4051 { "tracenz", PACKET_DISABLE,
4052 remote_string_tracing_feature, -1 },
9accd112
MM
4053 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4054 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4055 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4056 PACKET_qXfer_btrace }
be2a5f71
DJ
4057};
4058
c8d5aac9
L
4059static char *remote_support_xml;
4060
4061/* Register string appended to "xmlRegisters=" in qSupported query. */
4062
4063void
6e39997a 4064register_remote_support_xml (const char *xml)
c8d5aac9
L
4065{
4066#if defined(HAVE_LIBEXPAT)
4067 if (remote_support_xml == NULL)
c4f7c687 4068 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4069 else
4070 {
4071 char *copy = xstrdup (remote_support_xml + 13);
4072 char *p = strtok (copy, ",");
4073
4074 do
4075 {
4076 if (strcmp (p, xml) == 0)
4077 {
4078 /* already there */
4079 xfree (copy);
4080 return;
4081 }
4082 }
4083 while ((p = strtok (NULL, ",")) != NULL);
4084 xfree (copy);
4085
94b0dee1
PA
4086 remote_support_xml = reconcat (remote_support_xml,
4087 remote_support_xml, ",", xml,
4088 (char *) NULL);
c8d5aac9
L
4089 }
4090#endif
4091}
4092
4093static char *
4094remote_query_supported_append (char *msg, const char *append)
4095{
4096 if (msg)
94b0dee1 4097 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4098 else
4099 return xstrdup (append);
4100}
4101
be2a5f71
DJ
4102static void
4103remote_query_supported (void)
4104{
4105 struct remote_state *rs = get_remote_state ();
4106 char *next;
4107 int i;
4108 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4109
4110 /* The packet support flags are handled differently for this packet
4111 than for most others. We treat an error, a disabled packet, and
4112 an empty response identically: any features which must be reported
4113 to be used will be automatically disabled. An empty buffer
4114 accomplishes this, since that is also the representation for a list
4115 containing no features. */
4116
4117 rs->buf[0] = 0;
4118 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
4119 {
c8d5aac9 4120 char *q = NULL;
94b0dee1 4121 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4122
901f9912 4123 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9
L
4124
4125 if (remote_support_xml)
4126 q = remote_query_supported_append (q, remote_support_xml);
4127
dde08ee1
PA
4128 q = remote_query_supported_append (q, "qRelocInsn+");
4129
4130 q = reconcat (q, "qSupported:", q, (char *) NULL);
4131 putpkt (q);
82f73884 4132
94b0dee1
PA
4133 do_cleanups (old_chain);
4134
be2a5f71
DJ
4135 getpkt (&rs->buf, &rs->buf_size, 0);
4136
4137 /* If an error occured, warn, but do not return - just reset the
4138 buffer to empty and go on to disable features. */
4139 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4140 == PACKET_ERROR)
4141 {
4142 warning (_("Remote failure reply: %s"), rs->buf);
4143 rs->buf[0] = 0;
4144 }
4145 }
4146
4147 memset (seen, 0, sizeof (seen));
4148
4149 next = rs->buf;
4150 while (*next)
4151 {
4152 enum packet_support is_supported;
4153 char *p, *end, *name_end, *value;
4154
4155 /* First separate out this item from the rest of the packet. If
4156 there's another item after this, we overwrite the separator
4157 (terminated strings are much easier to work with). */
4158 p = next;
4159 end = strchr (p, ';');
4160 if (end == NULL)
4161 {
4162 end = p + strlen (p);
4163 next = end;
4164 }
4165 else
4166 {
89be2091
DJ
4167 *end = '\0';
4168 next = end + 1;
4169
be2a5f71
DJ
4170 if (end == p)
4171 {
4172 warning (_("empty item in \"qSupported\" response"));
4173 continue;
4174 }
be2a5f71
DJ
4175 }
4176
4177 name_end = strchr (p, '=');
4178 if (name_end)
4179 {
4180 /* This is a name=value entry. */
4181 is_supported = PACKET_ENABLE;
4182 value = name_end + 1;
4183 *name_end = '\0';
4184 }
4185 else
4186 {
4187 value = NULL;
4188 switch (end[-1])
4189 {
4190 case '+':
4191 is_supported = PACKET_ENABLE;
4192 break;
4193
4194 case '-':
4195 is_supported = PACKET_DISABLE;
4196 break;
4197
4198 case '?':
4199 is_supported = PACKET_SUPPORT_UNKNOWN;
4200 break;
4201
4202 default:
3e43a32a
MS
4203 warning (_("unrecognized item \"%s\" "
4204 "in \"qSupported\" response"), p);
be2a5f71
DJ
4205 continue;
4206 }
4207 end[-1] = '\0';
4208 }
4209
4210 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4211 if (strcmp (remote_protocol_features[i].name, p) == 0)
4212 {
4213 const struct protocol_feature *feature;
4214
4215 seen[i] = 1;
4216 feature = &remote_protocol_features[i];
4217 feature->func (feature, is_supported, value);
4218 break;
4219 }
4220 }
4221
4222 /* If we increased the packet size, make sure to increase the global
4223 buffer size also. We delay this until after parsing the entire
4224 qSupported packet, because this is the same buffer we were
4225 parsing. */
4226 if (rs->buf_size < rs->explicit_packet_size)
4227 {
4228 rs->buf_size = rs->explicit_packet_size;
4229 rs->buf = xrealloc (rs->buf, rs->buf_size);
4230 }
4231
4232 /* Handle the defaults for unmentioned features. */
4233 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4234 if (!seen[i])
4235 {
4236 const struct protocol_feature *feature;
4237
4238 feature = &remote_protocol_features[i];
4239 feature->func (feature, feature->default_support, NULL);
4240 }
4241}
4242
78a095c3
JK
4243/* Remove any of the remote.c targets from target stack. Upper targets depend
4244 on it so remove them first. */
4245
4246static void
4247remote_unpush_target (void)
4248{
4249 pop_all_targets_above (process_stratum - 1);
4250}
be2a5f71 4251
c906108c 4252static void
3e43a32a
MS
4253remote_open_1 (char *name, int from_tty,
4254 struct target_ops *target, int extended_p)
c906108c 4255{
d01949b6 4256 struct remote_state *rs = get_remote_state ();
a6f3e723 4257
c906108c 4258 if (name == 0)
8a3fe4f8 4259 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4260 "serial device is attached to the remote system\n"
8a3fe4f8 4261 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4262
23860348 4263 /* See FIXME above. */
c6ebd6cf 4264 if (!target_async_permitted)
92d1e331 4265 wait_forever_enabled_p = 1;
6426a772 4266
2d717e4f 4267 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4268 Ask this question first, before target_preopen has a chance to kill
4269 anything. */
5d93a237 4270 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4271 {
78a095c3
JK
4272 if (from_tty
4273 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4274 error (_("Still connected."));
4275 }
4276
78a095c3 4277 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4278 target_preopen (from_tty);
4279
89be2091 4280 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4281 xfree (rs->last_pass_packet);
4282 rs->last_pass_packet = NULL;
89be2091 4283
9b224c5e
PA
4284 /* Make sure we send the program signals list the next time we
4285 resume. */
5e4a05c4
TT
4286 xfree (rs->last_program_signals_packet);
4287 rs->last_program_signals_packet = NULL;
9b224c5e 4288
ad9a8f3f 4289 remote_fileio_reset ();
1dd41f16
NS
4290 reopen_exec_file ();
4291 reread_symbols ();
4292
5d93a237
TT
4293 rs->remote_desc = remote_serial_open (name);
4294 if (!rs->remote_desc)
c906108c
SS
4295 perror_with_name (name);
4296
4297 if (baud_rate != -1)
4298 {
5d93a237 4299 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4300 {
9b74d5d3
KB
4301 /* The requested speed could not be set. Error out to
4302 top level after closing remote_desc. Take care to
4303 set remote_desc to NULL to avoid closing remote_desc
4304 more than once. */
5d93a237
TT
4305 serial_close (rs->remote_desc);
4306 rs->remote_desc = NULL;
c906108c
SS
4307 perror_with_name (name);
4308 }
4309 }
4310
5d93a237 4311 serial_raw (rs->remote_desc);
c906108c
SS
4312
4313 /* If there is something sitting in the buffer we might take it as a
4314 response to a command, which would be bad. */
5d93a237 4315 serial_flush_input (rs->remote_desc);
c906108c
SS
4316
4317 if (from_tty)
4318 {
4319 puts_filtered ("Remote debugging using ");
4320 puts_filtered (name);
4321 puts_filtered ("\n");
4322 }
23860348 4323 push_target (target); /* Switch to using remote target now. */
c906108c 4324
74531fed
PA
4325 /* Register extra event sources in the event loop. */
4326 remote_async_inferior_event_token
4327 = create_async_event_handler (remote_async_inferior_event_handler,
4328 NULL);
5965e028 4329 rs->notif_state = remote_notif_state_allocate ();
74531fed 4330
be2a5f71
DJ
4331 /* Reset the target state; these things will be queried either by
4332 remote_query_supported or as they are needed. */
d471ea57 4333 init_all_packet_configs ();
74531fed 4334 rs->cached_wait_status = 0;
be2a5f71 4335 rs->explicit_packet_size = 0;
a6f3e723 4336 rs->noack_mode = 0;
82f73884
PA
4337 rs->multi_process_aware = 0;
4338 rs->extended = extended_p;
74531fed 4339 rs->non_stop_aware = 0;
e24a49d8 4340 rs->waiting_for_stop_reply = 0;
3a29589a 4341 rs->ctrlc_pending_p = 0;
802188a7 4342
47f8a51d
TT
4343 rs->general_thread = not_sent_ptid;
4344 rs->continue_thread = not_sent_ptid;
262e1174 4345 rs->remote_traceframe_number = -1;
c906108c 4346
9d1f7ab2 4347 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
4348 rs->use_threadinfo_query = 1;
4349 rs->use_threadextra_query = 1;
9d1f7ab2 4350
c6ebd6cf 4351 if (target_async_permitted)
92d1e331 4352 {
23860348 4353 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4354 remote_async_terminal_ours_p = 1;
4355
4356 /* FIXME: cagney/1999-09-23: During the initial connection it is
4357 assumed that the target is already ready and able to respond to
0df8b418 4358 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4359 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4360 around this. Eventually a mechanism that allows
92d1e331 4361 wait_for_inferior() to expect/get timeouts will be
23860348 4362 implemented. */
92d1e331
DJ
4363 wait_forever_enabled_p = 0;
4364 }
4365
23860348 4366 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4367 no_shared_libraries (NULL, 0);
f78f6cf1 4368
74531fed
PA
4369 /* Start afresh. */
4370 init_thread_list ();
4371
36918e70 4372 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4373 target (we'd otherwise be in an inconsistent state) and then
4374 propogate the error on up the exception chain. This ensures that
4375 the caller doesn't stumble along blindly assuming that the
4376 function succeeded. The CLI doesn't have this problem but other
4377 UI's, such as MI do.
36918e70
AC
4378
4379 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4380 this function should return an error indication letting the
ce2826aa 4381 caller restore the previous state. Unfortunately the command
36918e70
AC
4382 ``target remote'' is directly wired to this function making that
4383 impossible. On a positive note, the CLI side of this problem has
4384 been fixed - the function set_cmd_context() makes it possible for
4385 all the ``target ....'' commands to share a common callback
4386 function. See cli-dump.c. */
109c3e39 4387 {
04bd08de 4388 volatile struct gdb_exception ex;
2d717e4f 4389
04bd08de
TT
4390 TRY_CATCH (ex, RETURN_MASK_ALL)
4391 {
4392 remote_start_remote (from_tty, target, extended_p);
4393 }
109c3e39
AC
4394 if (ex.reason < 0)
4395 {
c8d104ad
PA
4396 /* Pop the partially set up target - unless something else did
4397 already before throwing the exception. */
5d93a237 4398 if (rs->remote_desc != NULL)
78a095c3 4399 remote_unpush_target ();
c6ebd6cf 4400 if (target_async_permitted)
109c3e39
AC
4401 wait_forever_enabled_p = 1;
4402 throw_exception (ex);
4403 }
4404 }
c906108c 4405
c6ebd6cf 4406 if (target_async_permitted)
92d1e331 4407 wait_forever_enabled_p = 1;
43ff13b4
JM
4408}
4409
c906108c
SS
4410/* This takes a program previously attached to and detaches it. After
4411 this is done, GDB can be used to debug some other program. We
4412 better not have left any breakpoints in the target program or it'll
4413 die when it hits one. */
4414
4415static void
52554a0e 4416remote_detach_1 (const char *args, int from_tty, int extended)
c906108c 4417{
82f73884 4418 int pid = ptid_get_pid (inferior_ptid);
d01949b6 4419 struct remote_state *rs = get_remote_state ();
c906108c
SS
4420
4421 if (args)
8a3fe4f8 4422 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 4423
2d717e4f
DJ
4424 if (!target_has_execution)
4425 error (_("No process to detach from."));
4426
7cee1e54
PA
4427 if (from_tty)
4428 {
4429 char *exec_file = get_exec_file (0);
4430 if (exec_file == NULL)
4431 exec_file = "";
4432 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4433 target_pid_to_str (pid_to_ptid (pid)));
4434 gdb_flush (gdb_stdout);
4435 }
4436
c906108c 4437 /* Tell the remote target to detach. */
82f73884 4438 if (remote_multi_process_p (rs))
bba74b36 4439 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
82f73884
PA
4440 else
4441 strcpy (rs->buf, "D");
4442
4ddda9b5
PA
4443 putpkt (rs->buf);
4444 getpkt (&rs->buf, &rs->buf_size, 0);
4445
82f73884
PA
4446 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4447 ;
4448 else if (rs->buf[0] == '\0')
4449 error (_("Remote doesn't know how to detach"));
4450 else
4ddda9b5 4451 error (_("Can't detach process."));
c906108c 4452
7cee1e54
PA
4453 if (from_tty && !extended)
4454 puts_filtered (_("Ending remote debugging.\n"));
82f73884 4455
82f73884 4456 target_mourn_inferior ();
2d717e4f
DJ
4457}
4458
4459static void
52554a0e 4460remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f
DJ
4461{
4462 remote_detach_1 (args, from_tty, 0);
4463}
4464
4465static void
52554a0e 4466extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f
DJ
4467{
4468 remote_detach_1 (args, from_tty, 1);
c906108c
SS
4469}
4470
6ad8ae5c
DJ
4471/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4472
43ff13b4 4473static void
597320e7 4474remote_disconnect (struct target_ops *target, char *args, int from_tty)
43ff13b4 4475{
43ff13b4 4476 if (args)
2d717e4f 4477 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 4478
2d717e4f
DJ
4479 /* Make sure we unpush even the extended remote targets; mourn
4480 won't do it. So call remote_mourn_1 directly instead of
4481 target_mourn_inferior. */
4482 remote_mourn_1 (target);
4483
43ff13b4
JM
4484 if (from_tty)
4485 puts_filtered ("Ending remote debugging.\n");
4486}
4487
2d717e4f
DJ
4488/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4489 be chatty about it. */
4490
4491static void
4492extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
4493{
4494 struct remote_state *rs = get_remote_state ();
be86555c 4495 int pid;
96ef3384 4496 char *wait_status = NULL;
2d717e4f 4497
74164c56 4498 pid = parse_pid_to_attach (args);
2d717e4f 4499
74164c56
JK
4500 /* Remote PID can be freely equal to getpid, do not check it here the same
4501 way as in other targets. */
2d717e4f
DJ
4502
4503 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4504 error (_("This target does not support attaching to a process"));
4505
7cee1e54
PA
4506 if (from_tty)
4507 {
4508 char *exec_file = get_exec_file (0);
4509
4510 if (exec_file)
4511 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4512 target_pid_to_str (pid_to_ptid (pid)));
4513 else
4514 printf_unfiltered (_("Attaching to %s\n"),
4515 target_pid_to_str (pid_to_ptid (pid)));
4516
4517 gdb_flush (gdb_stdout);
4518 }
4519
bba74b36 4520 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
4521 putpkt (rs->buf);
4522 getpkt (&rs->buf, &rs->buf_size, 0);
4523
3e43a32a
MS
4524 if (packet_ok (rs->buf,
4525 &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
2d717e4f 4526 {
74531fed
PA
4527 if (!non_stop)
4528 {
4529 /* Save the reply for later. */
4530 wait_status = alloca (strlen (rs->buf) + 1);
4531 strcpy (wait_status, rs->buf);
4532 }
4533 else if (strcmp (rs->buf, "OK") != 0)
4534 error (_("Attaching to %s failed with: %s"),
4535 target_pid_to_str (pid_to_ptid (pid)),
4536 rs->buf);
2d717e4f
DJ
4537 }
4538 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4539 error (_("This target does not support attaching to a process"));
4540 else
4541 error (_("Attaching to %s failed"),
4542 target_pid_to_str (pid_to_ptid (pid)));
4543
49c62f2e 4544 set_current_inferior (remote_add_inferior (0, pid, 1));
bad34192 4545
2d717e4f 4546 inferior_ptid = pid_to_ptid (pid);
79d7f229 4547
bad34192
PA
4548 if (non_stop)
4549 {
4550 struct thread_info *thread;
79d7f229 4551
bad34192
PA
4552 /* Get list of threads. */
4553 remote_threads_info (target);
82f73884 4554
bad34192
PA
4555 thread = first_thread_of_process (pid);
4556 if (thread)
4557 inferior_ptid = thread->ptid;
4558 else
4559 inferior_ptid = pid_to_ptid (pid);
4560
4561 /* Invalidate our notion of the remote current thread. */
47f8a51d 4562 record_currthread (rs, minus_one_ptid);
bad34192 4563 }
74531fed 4564 else
bad34192
PA
4565 {
4566 /* Now, if we have thread information, update inferior_ptid. */
4567 inferior_ptid = remote_current_thread (inferior_ptid);
4568
4569 /* Add the main thread to the thread list. */
4570 add_thread_silent (inferior_ptid);
4571 }
c0a2216e 4572
96ef3384
UW
4573 /* Next, if the target can specify a description, read it. We do
4574 this before anything involving memory or registers. */
4575 target_find_description ();
4576
74531fed
PA
4577 if (!non_stop)
4578 {
4579 /* Use the previously fetched status. */
4580 gdb_assert (wait_status != NULL);
4581
4582 if (target_can_async_p ())
4583 {
722247f1
YQ
4584 struct notif_event *reply
4585 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 4586
722247f1 4587 push_stop_reply ((struct stop_reply *) reply);
74531fed
PA
4588
4589 target_async (inferior_event_handler, 0);
4590 }
4591 else
4592 {
4593 gdb_assert (wait_status != NULL);
4594 strcpy (rs->buf, wait_status);
4595 rs->cached_wait_status = 1;
4596 }
4597 }
4598 else
4599 gdb_assert (wait_status == NULL);
2d717e4f
DJ
4600}
4601
4602static void
136d6dae 4603extended_remote_attach (struct target_ops *ops, char *args, int from_tty)
2d717e4f 4604{
136d6dae 4605 extended_remote_attach_1 (ops, args, from_tty);
2d717e4f
DJ
4606}
4607
c906108c 4608\f
506fb367
DJ
4609/* Check for the availability of vCont. This function should also check
4610 the response. */
c906108c
SS
4611
4612static void
6d820c5c 4613remote_vcont_probe (struct remote_state *rs)
c906108c 4614{
2e9f7625 4615 char *buf;
6d820c5c 4616
2e9f7625
DJ
4617 strcpy (rs->buf, "vCont?");
4618 putpkt (rs->buf);
6d820c5c 4619 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4620 buf = rs->buf;
c906108c 4621
506fb367
DJ
4622 /* Make sure that the features we assume are supported. */
4623 if (strncmp (buf, "vCont", 5) == 0)
4624 {
4625 char *p = &buf[5];
4626 int support_s, support_S, support_c, support_C;
4627
4628 support_s = 0;
4629 support_S = 0;
4630 support_c = 0;
4631 support_C = 0;
d458bd84 4632 rs->supports_vCont.t = 0;
c1e36e3e 4633 rs->supports_vCont.r = 0;
506fb367
DJ
4634 while (p && *p == ';')
4635 {
4636 p++;
4637 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4638 support_s = 1;
4639 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4640 support_S = 1;
4641 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4642 support_c = 1;
4643 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4644 support_C = 1;
74531fed 4645 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 4646 rs->supports_vCont.t = 1;
c1e36e3e
PA
4647 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4648 rs->supports_vCont.r = 1;
506fb367
DJ
4649
4650 p = strchr (p, ';');
4651 }
c906108c 4652
506fb367
DJ
4653 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4654 BUF will make packet_ok disable the packet. */
4655 if (!support_s || !support_S || !support_c || !support_C)
4656 buf[0] = 0;
4657 }
c906108c 4658
444abaca 4659 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 4660}
c906108c 4661
0d8f58ca
PA
4662/* Helper function for building "vCont" resumptions. Write a
4663 resumption to P. ENDP points to one-passed-the-end of the buffer
4664 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4665 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4666 resumed thread should be single-stepped and/or signalled. If PTID
4667 equals minus_one_ptid, then all threads are resumed; if PTID
4668 represents a process, then all threads of the process are resumed;
4669 the thread to be stepped and/or signalled is given in the global
4670 INFERIOR_PTID. */
4671
4672static char *
4673append_resumption (char *p, char *endp,
2ea28649 4674 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
4675{
4676 struct remote_state *rs = get_remote_state ();
4677
a493e3e2 4678 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 4679 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
4680 else if (step
4681 /* GDB is willing to range step. */
4682 && use_range_stepping
4683 /* Target supports range stepping. */
4684 && rs->supports_vCont.r
4685 /* We don't currently support range stepping multiple
4686 threads with a wildcard (though the protocol allows it,
4687 so stubs shouldn't make an active effort to forbid
4688 it). */
4689 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4690 {
4691 struct thread_info *tp;
4692
4693 if (ptid_equal (ptid, minus_one_ptid))
4694 {
4695 /* If we don't know about the target thread's tid, then
4696 we're resuming magic_null_ptid (see caller). */
4697 tp = find_thread_ptid (magic_null_ptid);
4698 }
4699 else
4700 tp = find_thread_ptid (ptid);
4701 gdb_assert (tp != NULL);
4702
4703 if (tp->control.may_range_step)
4704 {
4705 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4706
4707 p += xsnprintf (p, endp - p, ";r%s,%s",
4708 phex_nz (tp->control.step_range_start,
4709 addr_size),
4710 phex_nz (tp->control.step_range_end,
4711 addr_size));
4712 }
4713 else
4714 p += xsnprintf (p, endp - p, ";s");
4715 }
0d8f58ca
PA
4716 else if (step)
4717 p += xsnprintf (p, endp - p, ";s");
a493e3e2 4718 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
4719 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4720 else
4721 p += xsnprintf (p, endp - p, ";c");
4722
4723 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4724 {
4725 ptid_t nptid;
4726
4727 /* All (-1) threads of process. */
4728 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
4729
4730 p += xsnprintf (p, endp - p, ":");
4731 p = write_ptid (p, endp, nptid);
4732 }
4733 else if (!ptid_equal (ptid, minus_one_ptid))
4734 {
4735 p += xsnprintf (p, endp - p, ":");
4736 p = write_ptid (p, endp, ptid);
4737 }
4738
4739 return p;
4740}
4741
e5ef252a
PA
4742/* Append a vCont continue-with-signal action for threads that have a
4743 non-zero stop signal. */
4744
4745static char *
4746append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4747{
4748 struct thread_info *thread;
4749
4750 ALL_THREADS (thread)
4751 if (ptid_match (thread->ptid, ptid)
4752 && !ptid_equal (inferior_ptid, thread->ptid)
4753 && thread->suspend.stop_signal != GDB_SIGNAL_0
4754 && signal_pass_state (thread->suspend.stop_signal))
4755 {
4756 p = append_resumption (p, endp, thread->ptid,
4757 0, thread->suspend.stop_signal);
4758 thread->suspend.stop_signal = GDB_SIGNAL_0;
4759 }
4760
4761 return p;
4762}
4763
506fb367
DJ
4764/* Resume the remote inferior by using a "vCont" packet. The thread
4765 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
4766 resumed thread should be single-stepped and/or signalled. If PTID
4767 equals minus_one_ptid, then all threads are resumed; the thread to
4768 be stepped and/or signalled is given in the global INFERIOR_PTID.
4769 This function returns non-zero iff it resumes the inferior.
44eaed12 4770
506fb367
DJ
4771 This function issues a strict subset of all possible vCont commands at the
4772 moment. */
44eaed12 4773
506fb367 4774static int
2ea28649 4775remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
4776{
4777 struct remote_state *rs = get_remote_state ();
82f73884
PA
4778 char *p;
4779 char *endp;
44eaed12 4780
444abaca 4781 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
6d820c5c 4782 remote_vcont_probe (rs);
44eaed12 4783
444abaca 4784 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
6d820c5c 4785 return 0;
44eaed12 4786
82f73884
PA
4787 p = rs->buf;
4788 endp = rs->buf + get_remote_packet_size ();
4789
506fb367
DJ
4790 /* If we could generate a wider range of packets, we'd have to worry
4791 about overflowing BUF. Should there be a generic
4792 "multi-part-packet" packet? */
4793
0d8f58ca
PA
4794 p += xsnprintf (p, endp - p, "vCont");
4795
79d7f229 4796 if (ptid_equal (ptid, magic_null_ptid))
c906108c 4797 {
79d7f229
PA
4798 /* MAGIC_NULL_PTID means that we don't have any active threads,
4799 so we don't have any TID numbers the inferior will
4800 understand. Make sure to only send forms that do not specify
4801 a TID. */
a9cbf802 4802 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 4803 }
0d8f58ca 4804 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 4805 {
0d8f58ca
PA
4806 /* Resume all threads (of all processes, or of a single
4807 process), with preference for INFERIOR_PTID. This assumes
4808 inferior_ptid belongs to the set of all threads we are about
4809 to resume. */
a493e3e2 4810 if (step || siggnal != GDB_SIGNAL_0)
82f73884 4811 {
0d8f58ca
PA
4812 /* Step inferior_ptid, with or without signal. */
4813 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 4814 }
0d8f58ca 4815
e5ef252a
PA
4816 /* Also pass down any pending signaled resumption for other
4817 threads not the current. */
4818 p = append_pending_thread_resumptions (p, endp, ptid);
4819
0d8f58ca 4820 /* And continue others without a signal. */
a493e3e2 4821 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
4822 }
4823 else
506fb367
DJ
4824 {
4825 /* Scheduler locking; resume only PTID. */
a9cbf802 4826 append_resumption (p, endp, ptid, step, siggnal);
506fb367 4827 }
c906108c 4828
82f73884
PA
4829 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4830 putpkt (rs->buf);
506fb367 4831
74531fed
PA
4832 if (non_stop)
4833 {
4834 /* In non-stop, the stub replies to vCont with "OK". The stop
4835 reply will be reported asynchronously by means of a `%Stop'
4836 notification. */
4837 getpkt (&rs->buf, &rs->buf_size, 0);
4838 if (strcmp (rs->buf, "OK") != 0)
4839 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4840 }
4841
506fb367 4842 return 1;
c906108c 4843}
43ff13b4 4844
506fb367
DJ
4845/* Tell the remote machine to resume. */
4846
43ff13b4 4847static void
28439f5e 4848remote_resume (struct target_ops *ops,
2ea28649 4849 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 4850{
d01949b6 4851 struct remote_state *rs = get_remote_state ();
2e9f7625 4852 char *buf;
43ff13b4 4853
722247f1
YQ
4854 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
4855 (explained in remote-notif.c:handle_notification) so
4856 remote_notif_process is not called. We need find a place where
4857 it is safe to start a 'vNotif' sequence. It is good to do it
4858 before resuming inferior, because inferior was stopped and no RSP
4859 traffic at that moment. */
4860 if (!non_stop)
5965e028 4861 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 4862
b73be471 4863 rs->last_sent_signal = siggnal;
280ceea3 4864 rs->last_sent_step = step;
43ff13b4 4865
506fb367 4866 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
4867 /* No reverse support (yet) for vCont. */
4868 if (execution_direction != EXEC_REVERSE)
4869 if (remote_vcont_resume (ptid, step, siggnal))
4870 goto done;
506fb367 4871
79d7f229
PA
4872 /* All other supported resume packets do use Hc, so set the continue
4873 thread. */
4874 if (ptid_equal (ptid, minus_one_ptid))
4875 set_continue_thread (any_thread_ptid);
506fb367 4876 else
79d7f229 4877 set_continue_thread (ptid);
506fb367 4878
2e9f7625 4879 buf = rs->buf;
b2175913
MS
4880 if (execution_direction == EXEC_REVERSE)
4881 {
4882 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 4883 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 4884 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 4885 siggnal);
40ab02ce
MS
4886
4887 if (step
4888 && remote_protocol_packets[PACKET_bs].support == PACKET_DISABLE)
4889 error (_("Remote reverse-step not supported."));
4890 if (!step
4891 && remote_protocol_packets[PACKET_bc].support == PACKET_DISABLE)
08c93ed9 4892 error (_("Remote reverse-continue not supported."));
40ab02ce 4893
b2175913
MS
4894 strcpy (buf, step ? "bs" : "bc");
4895 }
a493e3e2 4896 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
4897 {
4898 buf[0] = step ? 'S' : 'C';
c5aa993b 4899 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 4900 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
4901 buf[3] = '\0';
4902 }
4903 else
c5aa993b 4904 strcpy (buf, step ? "s" : "c");
506fb367 4905
44eaed12 4906 putpkt (buf);
43ff13b4 4907
75c99385 4908 done:
2acceee2 4909 /* We are about to start executing the inferior, let's register it
0df8b418
MS
4910 with the event loop. NOTE: this is the one place where all the
4911 execution commands end up. We could alternatively do this in each
23860348 4912 of the execution commands in infcmd.c. */
2acceee2
JM
4913 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4914 into infcmd.c in order to allow inferior function calls to work
23860348 4915 NOT asynchronously. */
362646f5 4916 if (target_can_async_p ())
2acceee2 4917 target_async (inferior_event_handler, 0);
e24a49d8
PA
4918
4919 /* We've just told the target to resume. The remote server will
4920 wait for the inferior to stop, and then send a stop reply. In
4921 the mean time, we can't start another command/query ourselves
74531fed
PA
4922 because the stub wouldn't be ready to process it. This applies
4923 only to the base all-stop protocol, however. In non-stop (which
4924 only supports vCont), the stub replies with an "OK", and is
4925 immediate able to process further serial input. */
4926 if (!non_stop)
4927 rs->waiting_for_stop_reply = 1;
43ff13b4 4928}
c906108c 4929\f
43ff13b4
JM
4930
4931/* Set up the signal handler for SIGINT, while the target is
23860348 4932 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 4933static void
934b9bac 4934async_initialize_sigint_signal_handler (void)
43ff13b4 4935{
934b9bac 4936 signal (SIGINT, async_handle_remote_sigint);
43ff13b4
JM
4937}
4938
23860348 4939/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 4940static void
934b9bac 4941async_handle_remote_sigint (int sig)
43ff13b4 4942{
934b9bac
JK
4943 signal (sig, async_handle_remote_sigint_twice);
4944 mark_async_signal_handler (async_sigint_remote_token);
43ff13b4
JM
4945}
4946
4947/* Signal handler for SIGINT, installed after SIGINT has already been
4948 sent once. It will take effect the second time that the user sends
23860348 4949 a ^C. */
43ff13b4 4950static void
934b9bac 4951async_handle_remote_sigint_twice (int sig)
43ff13b4 4952{
934b9bac
JK
4953 signal (sig, async_handle_remote_sigint);
4954 mark_async_signal_handler (async_sigint_remote_twice_token);
43ff13b4
JM
4955}
4956
6426a772 4957/* Perform the real interruption of the target execution, in response
23860348 4958 to a ^C. */
c5aa993b 4959static void
fba45db2 4960async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
4961{
4962 if (remote_debug)
248fd3bf 4963 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
43ff13b4 4964
94cc34af 4965 target_stop (inferior_ptid);
43ff13b4
JM
4966}
4967
0df8b418 4968/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 4969 up on the target alltogether. */
47e1ce27 4970static void
fba45db2 4971async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 4972{
2df3850c 4973 if (remote_debug)
248fd3bf 4974 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
b803fb0f
DJ
4975
4976 interrupt_query ();
43ff13b4
JM
4977}
4978
4979/* Reinstall the usual SIGINT handlers, after the target has
23860348 4980 stopped. */
6426a772 4981static void
934b9bac 4982async_cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
4983{
4984 signal (SIGINT, handle_sigint);
43ff13b4
JM
4985}
4986
c906108c
SS
4987/* Send ^C to target to halt it. Target will respond, and send us a
4988 packet. */
507f3c78 4989static void (*ofunc) (int);
c906108c 4990
0df8b418
MS
4991/* The command line interface's stop routine. This function is installed
4992 as a signal handler for SIGINT. The first time a user requests a
4993 stop, we call remote_stop to send a break or ^C. If there is no
7a292a7a 4994 response from the target (it didn't stop when the user requested it),
23860348 4995 we ask the user if he'd like to detach from the target. */
c906108c 4996static void
934b9bac 4997sync_remote_interrupt (int signo)
c906108c 4998{
23860348 4999 /* If this doesn't work, try more severe steps. */
934b9bac 5000 signal (signo, sync_remote_interrupt_twice);
7a292a7a 5001
934b9bac 5002 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
7a292a7a
SS
5003}
5004
5005/* The user typed ^C twice. */
5006
5007static void
934b9bac 5008sync_remote_interrupt_twice (int signo)
7a292a7a
SS
5009{
5010 signal (signo, ofunc);
934b9bac
JK
5011 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5012 signal (signo, sync_remote_interrupt);
c906108c 5013}
7a292a7a 5014
74531fed
PA
5015/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5016 thread, all threads of a remote process, or all threads of all
5017 processes. */
5018
5019static void
5020remote_stop_ns (ptid_t ptid)
5021{
5022 struct remote_state *rs = get_remote_state ();
5023 char *p = rs->buf;
5024 char *endp = rs->buf + get_remote_packet_size ();
74531fed
PA
5025
5026 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
5027 remote_vcont_probe (rs);
5028
d458bd84 5029 if (!rs->supports_vCont.t)
74531fed
PA
5030 error (_("Remote server does not support stopping threads"));
5031
f91d3df5
PA
5032 if (ptid_equal (ptid, minus_one_ptid)
5033 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5034 p += xsnprintf (p, endp - p, "vCont;t");
5035 else
5036 {
5037 ptid_t nptid;
5038
74531fed
PA
5039 p += xsnprintf (p, endp - p, "vCont;t:");
5040
5041 if (ptid_is_pid (ptid))
5042 /* All (-1) threads of process. */
5043 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
5044 else
5045 {
5046 /* Small optimization: if we already have a stop reply for
5047 this thread, no use in telling the stub we want this
5048 stopped. */
5049 if (peek_stop_reply (ptid))
5050 return;
5051
5052 nptid = ptid;
5053 }
5054
a9cbf802 5055 write_ptid (p, endp, nptid);
74531fed
PA
5056 }
5057
5058 /* In non-stop, we get an immediate OK reply. The stop reply will
5059 come in asynchronously by notification. */
5060 putpkt (rs->buf);
5061 getpkt (&rs->buf, &rs->buf_size, 0);
5062 if (strcmp (rs->buf, "OK") != 0)
5063 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5064}
5065
5066/* All-stop version of target_stop. Sends a break or a ^C to stop the
5067 remote target. It is undefined which thread of which process
5068 reports the stop. */
5069
5070static void
5071remote_stop_as (ptid_t ptid)
5072{
5073 struct remote_state *rs = get_remote_state ();
5074
3a29589a
DJ
5075 rs->ctrlc_pending_p = 1;
5076
74531fed
PA
5077 /* If the inferior is stopped already, but the core didn't know
5078 about it yet, just ignore the request. The cached wait status
5079 will be collected in remote_wait. */
5080 if (rs->cached_wait_status)
5081 return;
5082
9a7071a8
JB
5083 /* Send interrupt_sequence to remote target. */
5084 send_interrupt_sequence ();
74531fed
PA
5085}
5086
0df8b418 5087/* This is the generic stop called via the target vector. When a target
7a292a7a 5088 interrupt is requested, either by the command line or the GUI, we
23860348 5089 will eventually end up here. */
74531fed 5090
c906108c 5091static void
1eab8a48 5092remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5093{
7a292a7a 5094 if (remote_debug)
0f71a2f6 5095 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5096
74531fed
PA
5097 if (non_stop)
5098 remote_stop_ns (ptid);
c906108c 5099 else
74531fed 5100 remote_stop_as (ptid);
c906108c
SS
5101}
5102
5103/* Ask the user what to do when an interrupt is received. */
5104
5105static void
fba45db2 5106interrupt_query (void)
c906108c
SS
5107{
5108 target_terminal_ours ();
5109
74531fed 5110 if (target_can_async_p ())
c906108c 5111 {
74531fed 5112 signal (SIGINT, handle_sigint);
039e3c22 5113 quit ();
c906108c 5114 }
74531fed
PA
5115 else
5116 {
9e2f0ad4
HZ
5117 if (query (_("Interrupted while waiting for the program.\n\
5118Give up (and stop debugging it)? ")))
74531fed 5119 {
78a095c3 5120 remote_unpush_target ();
039e3c22 5121 quit ();
74531fed
PA
5122 }
5123 }
c906108c
SS
5124
5125 target_terminal_inferior ();
5126}
5127
6426a772
JM
5128/* Enable/disable target terminal ownership. Most targets can use
5129 terminal groups to control terminal ownership. Remote targets are
5130 different in that explicit transfer of ownership to/from GDB/target
23860348 5131 is required. */
6426a772
JM
5132
5133static void
d2f640d4 5134remote_terminal_inferior (struct target_ops *self)
6426a772 5135{
c6ebd6cf 5136 if (!target_async_permitted)
75c99385
PA
5137 /* Nothing to do. */
5138 return;
5139
d9d2d8b6
PA
5140 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5141 idempotent. The event-loop GDB talking to an asynchronous target
5142 with a synchronous command calls this function from both
5143 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5144 transfer the terminal to the target when it shouldn't this guard
5145 can go away. */
6426a772
JM
5146 if (!remote_async_terminal_ours_p)
5147 return;
5148 delete_file_handler (input_fd);
5149 remote_async_terminal_ours_p = 0;
934b9bac 5150 async_initialize_sigint_signal_handler ();
6426a772
JM
5151 /* NOTE: At this point we could also register our selves as the
5152 recipient of all input. Any characters typed could then be
23860348 5153 passed on down to the target. */
6426a772
JM
5154}
5155
5156static void
e3594fd1 5157remote_terminal_ours (struct target_ops *self)
6426a772 5158{
c6ebd6cf 5159 if (!target_async_permitted)
75c99385
PA
5160 /* Nothing to do. */
5161 return;
5162
5163 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5164 if (remote_async_terminal_ours_p)
5165 return;
934b9bac 5166 async_cleanup_sigint_signal_handler (NULL);
6426a772
JM
5167 add_file_handler (input_fd, stdin_event_handler, 0);
5168 remote_async_terminal_ours_p = 1;
5169}
5170
176a6961 5171static void
917317f4 5172remote_console_output (char *msg)
c906108c
SS
5173{
5174 char *p;
5175
c5aa993b 5176 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5177 {
5178 char tb[2];
5179 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5180
c906108c
SS
5181 tb[0] = c;
5182 tb[1] = 0;
43ff13b4 5183 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5184 }
00db5b94
PA
5185 gdb_flush (gdb_stdtarg);
5186}
74531fed
PA
5187
5188typedef struct cached_reg
5189{
5190 int num;
5191 gdb_byte data[MAX_REGISTER_SIZE];
5192} cached_reg_t;
5193
5194DEF_VEC_O(cached_reg_t);
5195
722247f1 5196typedef struct stop_reply
74531fed 5197{
722247f1 5198 struct notif_event base;
74531fed 5199
722247f1 5200 /* The identifier of the thread about this event */
74531fed
PA
5201 ptid_t ptid;
5202
340e3c99 5203 /* The remote state this event is associated with. When the remote
bcc75809
YQ
5204 connection, represented by a remote_state object, is closed,
5205 all the associated stop_reply events should be released. */
5206 struct remote_state *rs;
5207
74531fed
PA
5208 struct target_waitstatus ws;
5209
15148d6a
PA
5210 /* Expedited registers. This makes remote debugging a bit more
5211 efficient for those targets that provide critical registers as
5212 part of their normal status mechanism (as another roundtrip to
5213 fetch them is avoided). */
74531fed
PA
5214 VEC(cached_reg_t) *regcache;
5215
5216 int stopped_by_watchpoint_p;
5217 CORE_ADDR watch_data_address;
5218
dc146f7c 5219 int core;
722247f1 5220} *stop_reply_p;
a744cf53 5221
722247f1
YQ
5222DECLARE_QUEUE_P (stop_reply_p);
5223DEFINE_QUEUE_P (stop_reply_p);
5224/* The list of already fetched and acknowledged stop events. This
5225 queue is used for notification Stop, and other notifications
5226 don't need queue for their events, because the notification events
5227 of Stop can't be consumed immediately, so that events should be
5228 queued first, and be consumed by remote_wait_{ns,as} one per
5229 time. Other notifications can consume their events immediately,
5230 so queue is not needed for them. */
5231static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
5232
5233static void
5234stop_reply_xfree (struct stop_reply *r)
5235{
f48ff2a7 5236 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
5237}
5238
722247f1
YQ
5239static void
5240remote_notif_stop_parse (struct notif_client *self, char *buf,
5241 struct notif_event *event)
5242{
5243 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5244}
5245
5246static void
5247remote_notif_stop_ack (struct notif_client *self, char *buf,
5248 struct notif_event *event)
5249{
5250 struct stop_reply *stop_reply = (struct stop_reply *) event;
5251
5252 /* acknowledge */
5253 putpkt ((char *) self->ack_command);
5254
5255 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5256 /* We got an unknown stop reply. */
5257 error (_("Unknown stop reply"));
5258
5259 push_stop_reply (stop_reply);
5260}
5261
5262static int
5263remote_notif_stop_can_get_pending_events (struct notif_client *self)
5264{
5265 /* We can't get pending events in remote_notif_process for
5266 notification stop, and we have to do this in remote_wait_ns
5267 instead. If we fetch all queued events from stub, remote stub
5268 may exit and we have no chance to process them back in
5269 remote_wait_ns. */
5270 mark_async_event_handler (remote_async_inferior_event_token);
5271 return 0;
5272}
5273
5274static void
5275stop_reply_dtr (struct notif_event *event)
5276{
5277 struct stop_reply *r = (struct stop_reply *) event;
5278
5279 VEC_free (cached_reg_t, r->regcache);
5280}
5281
5282static struct notif_event *
5283remote_notif_stop_alloc_reply (void)
5284{
5285 struct notif_event *r
70ba0933 5286 = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
5287
5288 r->dtr = stop_reply_dtr;
5289
5290 return r;
5291}
5292
5293/* A client of notification Stop. */
5294
5295struct notif_client notif_client_stop =
5296{
5297 "Stop",
5298 "vStopped",
5299 remote_notif_stop_parse,
5300 remote_notif_stop_ack,
5301 remote_notif_stop_can_get_pending_events,
5302 remote_notif_stop_alloc_reply,
f48ff2a7 5303 REMOTE_NOTIF_STOP,
722247f1
YQ
5304};
5305
5306/* A parameter to pass data in and out. */
5307
5308struct queue_iter_param
5309{
5310 void *input;
5311 struct stop_reply *output;
5312};
5313
f48ff2a7
YQ
5314/* Remove stop replies in the queue if its pid is equal to the given
5315 inferior's pid. */
722247f1
YQ
5316
5317static int
f48ff2a7
YQ
5318remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5319 QUEUE_ITER (stop_reply_p) *iter,
5320 stop_reply_p event,
5321 void *data)
722247f1
YQ
5322{
5323 struct queue_iter_param *param = data;
5324 struct inferior *inf = param->input;
5325
f48ff2a7 5326 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
5327 {
5328 stop_reply_xfree (event);
5329 QUEUE_remove_elem (stop_reply_p, q, iter);
5330 }
5331
5332 return 1;
5333}
5334
f48ff2a7 5335/* Discard all pending stop replies of inferior INF. */
c906108c 5336
74531fed 5337static void
5f4cf0bb 5338discard_pending_stop_replies (struct inferior *inf)
c906108c 5339{
722247f1
YQ
5340 int i;
5341 struct queue_iter_param param;
f48ff2a7
YQ
5342 struct stop_reply *reply;
5343 struct remote_state *rs = get_remote_state ();
5344 struct remote_notif_state *rns = rs->notif_state;
5345
5346 /* This function can be notified when an inferior exists. When the
5347 target is not remote, the notification state is NULL. */
5348 if (rs->remote_desc == NULL)
5349 return;
5350
5351 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 5352
74531fed 5353 /* Discard the in-flight notification. */
f48ff2a7 5354 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 5355 {
722247f1 5356 stop_reply_xfree (reply);
f48ff2a7 5357 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 5358 }
c906108c 5359
722247f1
YQ
5360 param.input = inf;
5361 param.output = NULL;
74531fed
PA
5362 /* Discard the stop replies we have already pulled with
5363 vStopped. */
722247f1 5364 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
5365 remove_stop_reply_for_inferior, &param);
5366}
5367
bcc75809
YQ
5368/* If its remote state is equal to the given remote state,
5369 remove EVENT from the stop reply queue. */
5370
5371static int
5372remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5373 QUEUE_ITER (stop_reply_p) *iter,
5374 stop_reply_p event,
5375 void *data)
5376{
5377 struct queue_iter_param *param = data;
5378 struct remote_state *rs = param->input;
5379
5380 if (event->rs == rs)
5381 {
5382 stop_reply_xfree (event);
5383 QUEUE_remove_elem (stop_reply_p, q, iter);
5384 }
5385
5386 return 1;
5387}
5388
5389/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
5390
5391static void
bcc75809 5392discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
5393{
5394 struct queue_iter_param param;
5395
bcc75809 5396 param.input = rs;
f48ff2a7
YQ
5397 param.output = NULL;
5398 /* Discard the stop replies we have already pulled with
5399 vStopped. */
5400 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 5401 remove_stop_reply_of_remote_state, &param);
722247f1 5402}
74531fed 5403
722247f1
YQ
5404/* A parameter to pass data in and out. */
5405
5406static int
5407remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5408 QUEUE_ITER (stop_reply_p) *iter,
5409 stop_reply_p event,
5410 void *data)
5411{
5412 struct queue_iter_param *param = data;
5413 ptid_t *ptid = param->input;
5414
5415 if (ptid_match (event->ptid, *ptid))
5416 {
5417 param->output = event;
5418 QUEUE_remove_elem (stop_reply_p, q, iter);
5419 return 0;
c8e38a49 5420 }
722247f1
YQ
5421
5422 return 1;
74531fed 5423}
43ff13b4 5424
722247f1
YQ
5425/* Remove the first reply in 'stop_reply_queue' which matches
5426 PTID. */
2e9f7625 5427
722247f1
YQ
5428static struct stop_reply *
5429remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 5430{
722247f1
YQ
5431 struct queue_iter_param param;
5432
5433 param.input = &ptid;
5434 param.output = NULL;
5435
5436 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5437 remote_notif_remove_once_on_match, &param);
5438 if (notif_debug)
5439 fprintf_unfiltered (gdb_stdlog,
5440 "notif: discard queued event: 'Stop' in %s\n",
5441 target_pid_to_str (ptid));
a744cf53 5442
722247f1 5443 return param.output;
74531fed 5444}
75c99385 5445
74531fed
PA
5446/* Look for a queued stop reply belonging to PTID. If one is found,
5447 remove it from the queue, and return it. Returns NULL if none is
5448 found. If there are still queued events left to process, tell the
5449 event loop to get back to target_wait soon. */
e24a49d8 5450
74531fed
PA
5451static struct stop_reply *
5452queued_stop_reply (ptid_t ptid)
5453{
722247f1 5454 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 5455
722247f1 5456 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
5457 /* There's still at least an event left. */
5458 mark_async_event_handler (remote_async_inferior_event_token);
5459
722247f1 5460 return r;
74531fed
PA
5461}
5462
5463/* Push a fully parsed stop reply in the stop reply queue. Since we
5464 know that we now have at least one queued event left to pass to the
5465 core side, tell the event loop to get back to target_wait soon. */
5466
5467static void
5468push_stop_reply (struct stop_reply *new_event)
5469{
722247f1 5470 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 5471
722247f1
YQ
5472 if (notif_debug)
5473 fprintf_unfiltered (gdb_stdlog,
5474 "notif: push 'Stop' %s to queue %d\n",
5475 target_pid_to_str (new_event->ptid),
5476 QUEUE_length (stop_reply_p,
5477 stop_reply_queue));
74531fed
PA
5478
5479 mark_async_event_handler (remote_async_inferior_event_token);
5480}
5481
722247f1
YQ
5482static int
5483stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5484 QUEUE_ITER (stop_reply_p) *iter,
5485 struct stop_reply *event,
5486 void *data)
5487{
5488 ptid_t *ptid = data;
5489
5490 return !(ptid_equal (*ptid, event->ptid)
5491 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5492}
5493
74531fed
PA
5494/* Returns true if we have a stop reply for PTID. */
5495
5496static int
5497peek_stop_reply (ptid_t ptid)
5498{
722247f1
YQ
5499 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5500 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
5501}
5502
5503/* Parse the stop reply in BUF. Either the function succeeds, and the
5504 result is stored in EVENT, or throws an error. */
5505
5506static void
5507remote_parse_stop_reply (char *buf, struct stop_reply *event)
5508{
5509 struct remote_arch_state *rsa = get_remote_arch_state ();
5510 ULONGEST addr;
5511 char *p;
5512
5513 event->ptid = null_ptid;
bcc75809 5514 event->rs = get_remote_state ();
74531fed
PA
5515 event->ws.kind = TARGET_WAITKIND_IGNORE;
5516 event->ws.value.integer = 0;
74531fed
PA
5517 event->stopped_by_watchpoint_p = 0;
5518 event->regcache = NULL;
dc146f7c 5519 event->core = -1;
74531fed
PA
5520
5521 switch (buf[0])
5522 {
5523 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
5524 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5525 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5526 ss = signal number
5527 n... = register number
5528 r... = register contents
5529 */
5530
5531 p = &buf[3]; /* after Txx */
5532 while (*p)
5533 {
5534 char *p1;
5535 char *p_temp;
5536 int fieldsize;
5537 LONGEST pnum = 0;
43ff13b4 5538
cea39f65
MS
5539 /* If the packet contains a register number, save it in
5540 pnum and set p1 to point to the character following it.
5541 Otherwise p1 points to p. */
3c3bea1c 5542
cea39f65
MS
5543 /* If this packet is an awatch packet, don't parse the 'a'
5544 as a register number. */
c8e38a49 5545
dc146f7c
VP
5546 if (strncmp (p, "awatch", strlen("awatch")) != 0
5547 && strncmp (p, "core", strlen ("core") != 0))
cea39f65
MS
5548 {
5549 /* Read the ``P'' register number. */
5550 pnum = strtol (p, &p_temp, 16);
5551 p1 = p_temp;
5552 }
5553 else
5554 p1 = p;
802188a7 5555
cea39f65
MS
5556 if (p1 == p) /* No register number present here. */
5557 {
5558 p1 = strchr (p, ':');
5559 if (p1 == NULL)
5560 error (_("Malformed packet(a) (missing colon): %s\n\
c8e38a49 5561Packet: '%s'\n"),
cea39f65
MS
5562 p, buf);
5563 if (strncmp (p, "thread", p1 - p) == 0)
5564 event->ptid = read_ptid (++p1, &p);
5565 else if ((strncmp (p, "watch", p1 - p) == 0)
5566 || (strncmp (p, "rwatch", p1 - p) == 0)
5567 || (strncmp (p, "awatch", p1 - p) == 0))
5568 {
5569 event->stopped_by_watchpoint_p = 1;
5570 p = unpack_varlen_hex (++p1, &addr);
5571 event->watch_data_address = (CORE_ADDR) addr;
5572 }
5573 else if (strncmp (p, "library", p1 - p) == 0)
5574 {
5575 p1++;
5576 p_temp = p1;
5577 while (*p_temp && *p_temp != ';')
5578 p_temp++;
c8e38a49 5579
5b5596ff 5580 event->ws.kind = TARGET_WAITKIND_LOADED;
cea39f65
MS
5581 p = p_temp;
5582 }
5583 else if (strncmp (p, "replaylog", p1 - p) == 0)
5584 {
5b5596ff
PA
5585 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5586 /* p1 will indicate "begin" or "end", but it makes
5587 no difference for now, so ignore it. */
cea39f65
MS
5588 p_temp = strchr (p1 + 1, ';');
5589 if (p_temp)
c8e38a49 5590 p = p_temp;
cea39f65 5591 }
dc146f7c
VP
5592 else if (strncmp (p, "core", p1 - p) == 0)
5593 {
5594 ULONGEST c;
a744cf53 5595
dc146f7c
VP
5596 p = unpack_varlen_hex (++p1, &c);
5597 event->core = c;
5598 }
cea39f65
MS
5599 else
5600 {
5601 /* Silently skip unknown optional info. */
5602 p_temp = strchr (p1 + 1, ';');
5603 if (p_temp)
5604 p = p_temp;
5605 }
5606 }
5607 else
5608 {
5609 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5610 cached_reg_t cached_reg;
74531fed 5611
cea39f65 5612 p = p1;
75c99385 5613
cea39f65
MS
5614 if (*p != ':')
5615 error (_("Malformed packet(b) (missing colon): %s\n\
8a3fe4f8 5616Packet: '%s'\n"),
cea39f65
MS
5617 p, buf);
5618 ++p;
43ff13b4 5619
cea39f65
MS
5620 if (reg == NULL)
5621 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 5622Packet: '%s'\n"),
7c47795c 5623 hex_string (pnum), p, buf);
c8e38a49 5624
cea39f65 5625 cached_reg.num = reg->regnum;
4100683b 5626
cea39f65 5627 fieldsize = hex2bin (p, cached_reg.data,
f5656ead 5628 register_size (target_gdbarch (),
cea39f65
MS
5629 reg->regnum));
5630 p += 2 * fieldsize;
f5656ead 5631 if (fieldsize < register_size (target_gdbarch (),
cea39f65
MS
5632 reg->regnum))
5633 warning (_("Remote reply is too short: %s"), buf);
74531fed 5634
cea39f65
MS
5635 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5636 }
c8e38a49 5637
cea39f65
MS
5638 if (*p != ';')
5639 error (_("Remote register badly formatted: %s\nhere: %s"),
5640 buf, p);
5641 ++p;
5642 }
5b5596ff
PA
5643
5644 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
5645 break;
5646
c8e38a49
PA
5647 /* fall through */
5648 case 'S': /* Old style status, just signal only. */
3a09da41
PA
5649 {
5650 int sig;
5651
5652 event->ws.kind = TARGET_WAITKIND_STOPPED;
5653 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
5654 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
5655 event->ws.value.sig = (enum gdb_signal) sig;
5656 else
5657 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5658 }
c8e38a49
PA
5659 break;
5660 case 'W': /* Target exited. */
5661 case 'X':
5662 {
5663 char *p;
5664 int pid;
5665 ULONGEST value;
82f73884 5666
c8e38a49
PA
5667 /* GDB used to accept only 2 hex chars here. Stubs should
5668 only send more if they detect GDB supports multi-process
5669 support. */
5670 p = unpack_varlen_hex (&buf[1], &value);
82f73884 5671
c8e38a49
PA
5672 if (buf[0] == 'W')
5673 {
5674 /* The remote process exited. */
74531fed
PA
5675 event->ws.kind = TARGET_WAITKIND_EXITED;
5676 event->ws.value.integer = value;
c8e38a49
PA
5677 }
5678 else
5679 {
5680 /* The remote process exited with a signal. */
74531fed 5681 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
5682 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
5683 event->ws.value.sig = (enum gdb_signal) value;
5684 else
5685 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 5686 }
82f73884 5687
c8e38a49
PA
5688 /* If no process is specified, assume inferior_ptid. */
5689 pid = ptid_get_pid (inferior_ptid);
5690 if (*p == '\0')
5691 ;
5692 else if (*p == ';')
5693 {
5694 p++;
5695
5696 if (p == '\0')
82f73884 5697 ;
c8e38a49
PA
5698 else if (strncmp (p,
5699 "process:", sizeof ("process:") - 1) == 0)
82f73884 5700 {
c8e38a49 5701 ULONGEST upid;
a744cf53 5702
c8e38a49
PA
5703 p += sizeof ("process:") - 1;
5704 unpack_varlen_hex (p, &upid);
5705 pid = upid;
82f73884
PA
5706 }
5707 else
5708 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 5709 }
c8e38a49
PA
5710 else
5711 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
5712 event->ptid = pid_to_ptid (pid);
5713 }
5714 break;
5715 }
5716
5717 if (non_stop && ptid_equal (event->ptid, null_ptid))
5718 error (_("No process or thread specified in stop reply: %s"), buf);
5719}
5720
722247f1
YQ
5721/* When the stub wants to tell GDB about a new notification reply, it
5722 sends a notification (%Stop, for example). Those can come it at
5723 any time, hence, we have to make sure that any pending
5724 putpkt/getpkt sequence we're making is finished, before querying
5725 the stub for more events with the corresponding ack command
5726 (vStopped, for example). E.g., if we started a vStopped sequence
5727 immediately upon receiving the notification, something like this
5728 could happen:
74531fed
PA
5729
5730 1.1) --> Hg 1
5731 1.2) <-- OK
5732 1.3) --> g
5733 1.4) <-- %Stop
5734 1.5) --> vStopped
5735 1.6) <-- (registers reply to step #1.3)
5736
5737 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5738 query.
5739
796cb314 5740 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
5741 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5742 doing whatever we were doing:
5743
5744 2.1) --> Hg 1
5745 2.2) <-- OK
5746 2.3) --> g
5747 2.4) <-- %Stop
5748 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5749 2.5) <-- (registers reply to step #2.3)
5750
5751 Eventualy after step #2.5, we return to the event loop, which
5752 notices there's an event on the
5753 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5754 associated callback --- the function below. At this point, we're
5755 always safe to start a vStopped sequence. :
5756
5757 2.6) --> vStopped
5758 2.7) <-- T05 thread:2
5759 2.8) --> vStopped
5760 2.9) --> OK
5761*/
5762
722247f1
YQ
5763void
5764remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
5765{
5766 struct remote_state *rs = get_remote_state ();
74531fed 5767
f48ff2a7 5768 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 5769 {
722247f1
YQ
5770 if (notif_debug)
5771 fprintf_unfiltered (gdb_stdlog,
5772 "notif: process: '%s' ack pending event\n",
5773 nc->name);
74531fed 5774
722247f1 5775 /* acknowledge */
f48ff2a7
YQ
5776 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
5777 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
5778
5779 while (1)
5780 {
5781 getpkt (&rs->buf, &rs->buf_size, 0);
5782 if (strcmp (rs->buf, "OK") == 0)
5783 break;
5784 else
722247f1 5785 remote_notif_ack (nc, rs->buf);
74531fed
PA
5786 }
5787 }
722247f1
YQ
5788 else
5789 {
5790 if (notif_debug)
5791 fprintf_unfiltered (gdb_stdlog,
5792 "notif: process: '%s' no pending reply\n",
5793 nc->name);
5794 }
74531fed
PA
5795}
5796
74531fed
PA
5797/* Called when it is decided that STOP_REPLY holds the info of the
5798 event that is to be returned to the core. This function always
5799 destroys STOP_REPLY. */
5800
5801static ptid_t
5802process_stop_reply (struct stop_reply *stop_reply,
5803 struct target_waitstatus *status)
5804{
5805 ptid_t ptid;
5806
5807 *status = stop_reply->ws;
5808 ptid = stop_reply->ptid;
5809
5810 /* If no thread/process was reported by the stub, assume the current
5811 inferior. */
5812 if (ptid_equal (ptid, null_ptid))
5813 ptid = inferior_ptid;
5814
5f3563ea
PA
5815 if (status->kind != TARGET_WAITKIND_EXITED
5816 && status->kind != TARGET_WAITKIND_SIGNALLED)
74531fed 5817 {
ee154bee
TT
5818 struct remote_state *rs = get_remote_state ();
5819
5f3563ea
PA
5820 /* Expedited registers. */
5821 if (stop_reply->regcache)
5822 {
217f1f79 5823 struct regcache *regcache
f5656ead 5824 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
5825 cached_reg_t *reg;
5826 int ix;
5827
5828 for (ix = 0;
5829 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5830 ix++)
217f1f79 5831 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
5832 VEC_free (cached_reg_t, stop_reply->regcache);
5833 }
74531fed 5834
ee154bee
TT
5835 rs->remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
5836 rs->remote_watch_data_address = stop_reply->watch_data_address;
1941c569
PA
5837
5838 remote_notice_new_inferior (ptid, 0);
dc146f7c 5839 demand_private_info (ptid)->core = stop_reply->core;
74531fed
PA
5840 }
5841
74531fed
PA
5842 stop_reply_xfree (stop_reply);
5843 return ptid;
5844}
5845
5846/* The non-stop mode version of target_wait. */
5847
5848static ptid_t
47608cb1 5849remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
5850{
5851 struct remote_state *rs = get_remote_state ();
74531fed
PA
5852 struct stop_reply *stop_reply;
5853 int ret;
fee9eda9 5854 int is_notif = 0;
74531fed
PA
5855
5856 /* If in non-stop mode, get out of getpkt even if a
5857 notification is received. */
5858
5859 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 5860 0 /* forever */, &is_notif);
74531fed
PA
5861 while (1)
5862 {
fee9eda9 5863 if (ret != -1 && !is_notif)
74531fed
PA
5864 switch (rs->buf[0])
5865 {
5866 case 'E': /* Error of some sort. */
5867 /* We're out of sync with the target now. Did it continue
5868 or not? We can't tell which thread it was in non-stop,
5869 so just ignore this. */
5870 warning (_("Remote failure reply: %s"), rs->buf);
5871 break;
5872 case 'O': /* Console output. */
5873 remote_console_output (rs->buf + 1);
5874 break;
5875 default:
5876 warning (_("Invalid remote reply: %s"), rs->buf);
5877 break;
5878 }
5879
5880 /* Acknowledge a pending stop reply that may have arrived in the
5881 mean time. */
f48ff2a7 5882 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 5883 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
5884
5885 /* If indeed we noticed a stop reply, we're done. */
5886 stop_reply = queued_stop_reply (ptid);
5887 if (stop_reply != NULL)
5888 return process_stop_reply (stop_reply, status);
5889
47608cb1 5890 /* Still no event. If we're just polling for an event, then
74531fed 5891 return to the event loop. */
47608cb1 5892 if (options & TARGET_WNOHANG)
74531fed
PA
5893 {
5894 status->kind = TARGET_WAITKIND_IGNORE;
5895 return minus_one_ptid;
5896 }
5897
47608cb1 5898 /* Otherwise do a blocking wait. */
74531fed 5899 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 5900 1 /* forever */, &is_notif);
74531fed
PA
5901 }
5902}
5903
5904/* Wait until the remote machine stops, then return, storing status in
5905 STATUS just as `wait' would. */
5906
5907static ptid_t
47608cb1 5908remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
5909{
5910 struct remote_state *rs = get_remote_state ();
74531fed 5911 ptid_t event_ptid = null_ptid;
cea39f65 5912 char *buf;
74531fed
PA
5913 struct stop_reply *stop_reply;
5914
47608cb1
PA
5915 again:
5916
74531fed
PA
5917 status->kind = TARGET_WAITKIND_IGNORE;
5918 status->value.integer = 0;
5919
5920 stop_reply = queued_stop_reply (ptid);
5921 if (stop_reply != NULL)
5922 return process_stop_reply (stop_reply, status);
5923
5924 if (rs->cached_wait_status)
5925 /* Use the cached wait status, but only once. */
5926 rs->cached_wait_status = 0;
5927 else
5928 {
5929 int ret;
722247f1 5930 int is_notif;
74531fed
PA
5931
5932 if (!target_is_async_p ())
5933 {
934b9bac 5934 ofunc = signal (SIGINT, sync_remote_interrupt);
74531fed
PA
5935 /* If the user hit C-c before this packet, or between packets,
5936 pretend that it was hit right here. */
522002f9 5937 if (check_quit_flag ())
74531fed 5938 {
522002f9 5939 clear_quit_flag ();
934b9bac 5940 sync_remote_interrupt (SIGINT);
74531fed
PA
5941 }
5942 }
5943
5944 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5945 _never_ wait for ever -> test on target_is_async_p().
5946 However, before we do that we need to ensure that the caller
5947 knows how to take the target into/out of async mode. */
722247f1
YQ
5948 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5949 wait_forever_enabled_p, &is_notif);
5950
5e1b953b
SDJ
5951 if (!target_is_async_p ())
5952 signal (SIGINT, ofunc);
5953
722247f1
YQ
5954 /* GDB gets a notification. Return to core as this event is
5955 not interesting. */
5956 if (ret != -1 && is_notif)
5957 return minus_one_ptid;
74531fed
PA
5958 }
5959
5960 buf = rs->buf;
5961
ee154bee 5962 rs->remote_stopped_by_watchpoint_p = 0;
74531fed
PA
5963
5964 /* We got something. */
5965 rs->waiting_for_stop_reply = 0;
5966
3a29589a
DJ
5967 /* Assume that the target has acknowledged Ctrl-C unless we receive
5968 an 'F' or 'O' packet. */
5969 if (buf[0] != 'F' && buf[0] != 'O')
5970 rs->ctrlc_pending_p = 0;
5971
74531fed
PA
5972 switch (buf[0])
5973 {
5974 case 'E': /* Error of some sort. */
5975 /* We're out of sync with the target now. Did it continue or
5976 not? Not is more likely, so report a stop. */
5977 warning (_("Remote failure reply: %s"), buf);
5978 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 5979 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
5980 break;
5981 case 'F': /* File-I/O request. */
3a29589a
DJ
5982 remote_fileio_request (buf, rs->ctrlc_pending_p);
5983 rs->ctrlc_pending_p = 0;
74531fed
PA
5984 break;
5985 case 'T': case 'S': case 'X': case 'W':
5986 {
722247f1
YQ
5987 struct stop_reply *stop_reply
5988 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
5989 rs->buf);
74531fed 5990
74531fed 5991 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
5992 break;
5993 }
5994 case 'O': /* Console output. */
5995 remote_console_output (buf + 1);
e24a49d8 5996
c8e38a49
PA
5997 /* The target didn't really stop; keep waiting. */
5998 rs->waiting_for_stop_reply = 1;
e24a49d8 5999
c8e38a49
PA
6000 break;
6001 case '\0':
b73be471 6002 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
6003 {
6004 /* Zero length reply means that we tried 'S' or 'C' and the
6005 remote system doesn't support it. */
6006 target_terminal_ours_for_output ();
6007 printf_filtered
6008 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
6009 gdb_signal_to_name (rs->last_sent_signal));
6010 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
6011 target_terminal_inferior ();
6012
280ceea3 6013 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49
PA
6014 putpkt ((char *) buf);
6015
6016 /* We just told the target to resume, so a stop reply is in
6017 order. */
e24a49d8 6018 rs->waiting_for_stop_reply = 1;
c8e38a49 6019 break;
43ff13b4 6020 }
c8e38a49
PA
6021 /* else fallthrough */
6022 default:
6023 warning (_("Invalid remote reply: %s"), buf);
6024 /* Keep waiting. */
6025 rs->waiting_for_stop_reply = 1;
6026 break;
43ff13b4 6027 }
c8e38a49 6028
c8e38a49 6029 if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
6030 {
6031 /* Nothing interesting happened. If we're doing a non-blocking
6032 poll, we're done. Otherwise, go back to waiting. */
6033 if (options & TARGET_WNOHANG)
6034 return minus_one_ptid;
6035 else
6036 goto again;
6037 }
74531fed
PA
6038 else if (status->kind != TARGET_WAITKIND_EXITED
6039 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
6040 {
6041 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 6042 record_currthread (rs, event_ptid);
82f73884
PA
6043 else
6044 event_ptid = inferior_ptid;
43ff13b4 6045 }
74531fed
PA
6046 else
6047 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 6048 record_currthread (rs, minus_one_ptid);
79d7f229 6049
82f73884 6050 return event_ptid;
43ff13b4
JM
6051}
6052
74531fed
PA
6053/* Wait until the remote machine stops, then return, storing status in
6054 STATUS just as `wait' would. */
6055
c8e38a49 6056static ptid_t
117de6a9 6057remote_wait (struct target_ops *ops,
47608cb1 6058 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
6059{
6060 ptid_t event_ptid;
6061
74531fed 6062 if (non_stop)
47608cb1 6063 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 6064 else
47608cb1 6065 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 6066
74531fed 6067 if (target_can_async_p ())
c8e38a49 6068 {
74531fed
PA
6069 /* If there are are events left in the queue tell the event loop
6070 to return here. */
722247f1 6071 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 6072 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 6073 }
c8e38a49
PA
6074
6075 return event_ptid;
6076}
6077
74ca34ce 6078/* Fetch a single register using a 'p' packet. */
c906108c 6079
b96ec7ac 6080static int
56be3814 6081fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
6082{
6083 struct remote_state *rs = get_remote_state ();
2e9f7625 6084 char *buf, *p;
b96ec7ac
AC
6085 char regp[MAX_REGISTER_SIZE];
6086 int i;
6087
74ca34ce
DJ
6088 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
6089 return 0;
6090
6091 if (reg->pnum == -1)
6092 return 0;
6093
2e9f7625 6094 p = rs->buf;
fcad0fa4 6095 *p++ = 'p';
74ca34ce 6096 p += hexnumstr (p, reg->pnum);
fcad0fa4 6097 *p++ = '\0';
1f4437a4
MS
6098 putpkt (rs->buf);
6099 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 6100
2e9f7625
DJ
6101 buf = rs->buf;
6102
74ca34ce
DJ
6103 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6104 {
6105 case PACKET_OK:
6106 break;
6107 case PACKET_UNKNOWN:
6108 return 0;
6109 case PACKET_ERROR:
27a9c0bf
MS
6110 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6111 gdbarch_register_name (get_regcache_arch (regcache),
6112 reg->regnum),
6113 buf);
74ca34ce 6114 }
3f9a994c
JB
6115
6116 /* If this register is unfetchable, tell the regcache. */
6117 if (buf[0] == 'x')
8480adf2 6118 {
56be3814 6119 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 6120 return 1;
b96ec7ac 6121 }
b96ec7ac 6122
3f9a994c
JB
6123 /* Otherwise, parse and supply the value. */
6124 p = buf;
6125 i = 0;
6126 while (p[0] != 0)
6127 {
6128 if (p[1] == 0)
74ca34ce 6129 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
6130
6131 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6132 p += 2;
6133 }
56be3814 6134 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 6135 return 1;
b96ec7ac
AC
6136}
6137
74ca34ce
DJ
6138/* Fetch the registers included in the target's 'g' packet. */
6139
29709017
DJ
6140static int
6141send_g_packet (void)
c906108c 6142{
d01949b6 6143 struct remote_state *rs = get_remote_state ();
cea39f65 6144 int buf_len;
c906108c 6145
bba74b36 6146 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 6147 remote_send (&rs->buf, &rs->buf_size);
c906108c 6148
29709017
DJ
6149 /* We can get out of synch in various cases. If the first character
6150 in the buffer is not a hex character, assume that has happened
6151 and try to fetch another packet to read. */
6152 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6153 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6154 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6155 && rs->buf[0] != 'x') /* New: unavailable register value. */
6156 {
6157 if (remote_debug)
6158 fprintf_unfiltered (gdb_stdlog,
6159 "Bad register packet; fetching a new packet\n");
6160 getpkt (&rs->buf, &rs->buf_size, 0);
6161 }
6162
74ca34ce
DJ
6163 buf_len = strlen (rs->buf);
6164
6165 /* Sanity check the received packet. */
6166 if (buf_len % 2 != 0)
6167 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
6168
6169 return buf_len / 2;
6170}
6171
6172static void
56be3814 6173process_g_packet (struct regcache *regcache)
29709017 6174{
4a22f64d 6175 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
6176 struct remote_state *rs = get_remote_state ();
6177 struct remote_arch_state *rsa = get_remote_arch_state ();
6178 int i, buf_len;
6179 char *p;
6180 char *regs;
6181
6182 buf_len = strlen (rs->buf);
6183
6184 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
6185 if (buf_len > 2 * rsa->sizeof_g_packet)
6186 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6187
6188 /* Save the size of the packet sent to us by the target. It is used
6189 as a heuristic when determining the max size of packets that the
6190 target can safely receive. */
6191 if (rsa->actual_register_packet_size == 0)
6192 rsa->actual_register_packet_size = buf_len;
6193
6194 /* If this is smaller than we guessed the 'g' packet would be,
6195 update our records. A 'g' reply that doesn't include a register's
6196 value implies either that the register is not available, or that
6197 the 'p' packet must be used. */
6198 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 6199 {
74ca34ce
DJ
6200 rsa->sizeof_g_packet = buf_len / 2;
6201
4a22f64d 6202 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 6203 {
74ca34ce
DJ
6204 if (rsa->regs[i].pnum == -1)
6205 continue;
6206
6207 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6208 rsa->regs[i].in_g_packet = 0;
b96ec7ac 6209 else
74ca34ce 6210 rsa->regs[i].in_g_packet = 1;
b96ec7ac 6211 }
74ca34ce 6212 }
b323314b 6213
74ca34ce 6214 regs = alloca (rsa->sizeof_g_packet);
c906108c
SS
6215
6216 /* Unimplemented registers read as all bits zero. */
ea9c271d 6217 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 6218
c906108c
SS
6219 /* Reply describes registers byte by byte, each byte encoded as two
6220 hex characters. Suck them all up, then supply them to the
6221 register cacheing/storage mechanism. */
6222
74ca34ce 6223 p = rs->buf;
ea9c271d 6224 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 6225 {
74ca34ce
DJ
6226 if (p[0] == 0 || p[1] == 0)
6227 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6228 internal_error (__FILE__, __LINE__,
9b20d036 6229 _("unexpected end of 'g' packet reply"));
74ca34ce 6230
c906108c 6231 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 6232 regs[i] = 0; /* 'x' */
c906108c
SS
6233 else
6234 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6235 p += 2;
6236 }
6237
a744cf53
MS
6238 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6239 {
6240 struct packet_reg *r = &rsa->regs[i];
6241
6242 if (r->in_g_packet)
6243 {
6244 if (r->offset * 2 >= strlen (rs->buf))
6245 /* This shouldn't happen - we adjusted in_g_packet above. */
6246 internal_error (__FILE__, __LINE__,
9b20d036 6247 _("unexpected end of 'g' packet reply"));
a744cf53
MS
6248 else if (rs->buf[r->offset * 2] == 'x')
6249 {
6250 gdb_assert (r->offset * 2 < strlen (rs->buf));
6251 /* The register isn't available, mark it as such (at
6252 the same time setting the value to zero). */
6253 regcache_raw_supply (regcache, r->regnum, NULL);
6254 }
6255 else
6256 regcache_raw_supply (regcache, r->regnum,
6257 regs + r->offset);
6258 }
6259 }
c906108c
SS
6260}
6261
29709017 6262static void
56be3814 6263fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
6264{
6265 send_g_packet ();
56be3814 6266 process_g_packet (regcache);
29709017
DJ
6267}
6268
e6e4e701
PA
6269/* Make the remote selected traceframe match GDB's selected
6270 traceframe. */
6271
6272static void
6273set_remote_traceframe (void)
6274{
6275 int newnum;
262e1174 6276 struct remote_state *rs = get_remote_state ();
e6e4e701 6277
262e1174 6278 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
6279 return;
6280
6281 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 6282 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
6283
6284 newnum = target_trace_find (tfind_number,
6285 get_traceframe_number (), 0, 0, NULL);
6286
6287 /* Should not happen. If it does, all bets are off. */
6288 if (newnum != get_traceframe_number ())
6289 warning (_("could not set remote traceframe"));
6290}
6291
74ca34ce 6292static void
28439f5e
PA
6293remote_fetch_registers (struct target_ops *ops,
6294 struct regcache *regcache, int regnum)
74ca34ce 6295{
74ca34ce
DJ
6296 struct remote_arch_state *rsa = get_remote_arch_state ();
6297 int i;
6298
e6e4e701 6299 set_remote_traceframe ();
79d7f229 6300 set_general_thread (inferior_ptid);
74ca34ce
DJ
6301
6302 if (regnum >= 0)
6303 {
6304 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6305
74ca34ce
DJ
6306 gdb_assert (reg != NULL);
6307
6308 /* If this register might be in the 'g' packet, try that first -
6309 we are likely to read more than one register. If this is the
6310 first 'g' packet, we might be overly optimistic about its
6311 contents, so fall back to 'p'. */
6312 if (reg->in_g_packet)
6313 {
56be3814 6314 fetch_registers_using_g (regcache);
74ca34ce
DJ
6315 if (reg->in_g_packet)
6316 return;
6317 }
6318
56be3814 6319 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
6320 return;
6321
6322 /* This register is not available. */
56be3814 6323 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
6324
6325 return;
6326 }
6327
56be3814 6328 fetch_registers_using_g (regcache);
74ca34ce 6329
4a22f64d 6330 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6331 if (!rsa->regs[i].in_g_packet)
56be3814 6332 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
6333 {
6334 /* This register is not available. */
56be3814 6335 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
6336 }
6337}
6338
c906108c
SS
6339/* Prepare to store registers. Since we may send them all (using a
6340 'G' request), we have to read out the ones we don't want to change
6341 first. */
6342
c5aa993b 6343static void
f32dbf8c 6344remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 6345{
ea9c271d 6346 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 6347 int i;
cfd77fa1 6348 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 6349
c906108c 6350 /* Make sure the entire registers array is valid. */
444abaca 6351 switch (remote_protocol_packets[PACKET_P].support)
5a2468f5
JM
6352 {
6353 case PACKET_DISABLE:
6354 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 6355 /* Make sure all the necessary registers are cached. */
4a22f64d 6356 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 6357 if (rsa->regs[i].in_g_packet)
316f2060 6358 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
6359 break;
6360 case PACKET_ENABLE:
6361 break;
6362 }
6363}
6364
ad10f812 6365/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 6366 packet was not recognized. */
5a2468f5
JM
6367
6368static int
1f4437a4
MS
6369store_register_using_P (const struct regcache *regcache,
6370 struct packet_reg *reg)
5a2468f5 6371{
4a22f64d 6372 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 6373 struct remote_state *rs = get_remote_state ();
5a2468f5 6374 /* Try storing a single register. */
6d820c5c 6375 char *buf = rs->buf;
cfd77fa1 6376 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 6377 char *p;
5a2468f5 6378
74ca34ce
DJ
6379 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
6380 return 0;
6381
6382 if (reg->pnum == -1)
6383 return 0;
6384
ea9c271d 6385 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 6386 p = buf + strlen (buf);
56be3814 6387 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 6388 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
6389 putpkt (rs->buf);
6390 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 6391
74ca34ce
DJ
6392 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6393 {
6394 case PACKET_OK:
6395 return 1;
6396 case PACKET_ERROR:
27a9c0bf
MS
6397 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6398 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
6399 case PACKET_UNKNOWN:
6400 return 0;
6401 default:
6402 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6403 }
c906108c
SS
6404}
6405
23860348
MS
6406/* Store register REGNUM, or all registers if REGNUM == -1, from the
6407 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
6408
6409static void
56be3814 6410store_registers_using_G (const struct regcache *regcache)
c906108c 6411{
d01949b6 6412 struct remote_state *rs = get_remote_state ();
ea9c271d 6413 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 6414 gdb_byte *regs;
c906108c
SS
6415 char *p;
6416
193cb69f
AC
6417 /* Extract all the registers in the regcache copying them into a
6418 local buffer. */
6419 {
b323314b 6420 int i;
a744cf53 6421
ea9c271d
DJ
6422 regs = alloca (rsa->sizeof_g_packet);
6423 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 6424 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 6425 {
ea9c271d 6426 struct packet_reg *r = &rsa->regs[i];
a744cf53 6427
b323314b 6428 if (r->in_g_packet)
56be3814 6429 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
6430 }
6431 }
c906108c
SS
6432
6433 /* Command describes registers byte by byte,
6434 each byte encoded as two hex characters. */
6d820c5c 6435 p = rs->buf;
193cb69f 6436 *p++ = 'G';
74ca34ce
DJ
6437 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6438 updated. */
6439 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
6440 putpkt (rs->buf);
6441 getpkt (&rs->buf, &rs->buf_size, 0);
6442 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
6443 error (_("Could not write registers; remote failure reply '%s'"),
6444 rs->buf);
c906108c 6445}
74ca34ce
DJ
6446
6447/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6448 of the register cache buffer. FIXME: ignores errors. */
6449
6450static void
28439f5e
PA
6451remote_store_registers (struct target_ops *ops,
6452 struct regcache *regcache, int regnum)
74ca34ce 6453{
74ca34ce
DJ
6454 struct remote_arch_state *rsa = get_remote_arch_state ();
6455 int i;
6456
e6e4e701 6457 set_remote_traceframe ();
79d7f229 6458 set_general_thread (inferior_ptid);
74ca34ce
DJ
6459
6460 if (regnum >= 0)
6461 {
6462 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6463
74ca34ce
DJ
6464 gdb_assert (reg != NULL);
6465
6466 /* Always prefer to store registers using the 'P' packet if
6467 possible; we often change only a small number of registers.
6468 Sometimes we change a larger number; we'd need help from a
6469 higher layer to know to use 'G'. */
56be3814 6470 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
6471 return;
6472
6473 /* For now, don't complain if we have no way to write the
6474 register. GDB loses track of unavailable registers too
6475 easily. Some day, this may be an error. We don't have
0df8b418 6476 any way to read the register, either... */
74ca34ce
DJ
6477 if (!reg->in_g_packet)
6478 return;
6479
56be3814 6480 store_registers_using_G (regcache);
74ca34ce
DJ
6481 return;
6482 }
6483
56be3814 6484 store_registers_using_G (regcache);
74ca34ce 6485
4a22f64d 6486 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6487 if (!rsa->regs[i].in_g_packet)
56be3814 6488 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
6489 /* See above for why we do not issue an error here. */
6490 continue;
6491}
c906108c
SS
6492\f
6493
6494/* Return the number of hex digits in num. */
6495
6496static int
fba45db2 6497hexnumlen (ULONGEST num)
c906108c
SS
6498{
6499 int i;
6500
6501 for (i = 0; num != 0; i++)
6502 num >>= 4;
6503
6504 return max (i, 1);
6505}
6506
2df3850c 6507/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
6508
6509static int
fba45db2 6510hexnumstr (char *buf, ULONGEST num)
c906108c 6511{
c906108c 6512 int len = hexnumlen (num);
a744cf53 6513
2df3850c
JM
6514 return hexnumnstr (buf, num, len);
6515}
6516
c906108c 6517
2df3850c 6518/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 6519
2df3850c 6520static int
fba45db2 6521hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
6522{
6523 int i;
6524
6525 buf[width] = '\0';
6526
6527 for (i = width - 1; i >= 0; i--)
c906108c 6528 {
c5aa993b 6529 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
6530 num >>= 4;
6531 }
6532
2df3850c 6533 return width;
c906108c
SS
6534}
6535
23860348 6536/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
6537
6538static CORE_ADDR
fba45db2 6539remote_address_masked (CORE_ADDR addr)
c906108c 6540{
883b9c6c 6541 unsigned int address_size = remote_address_size;
a744cf53 6542
911c95a5
UW
6543 /* If "remoteaddresssize" was not set, default to target address size. */
6544 if (!address_size)
f5656ead 6545 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
6546
6547 if (address_size > 0
6548 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
6549 {
6550 /* Only create a mask when that mask can safely be constructed
23860348 6551 in a ULONGEST variable. */
c906108c 6552 ULONGEST mask = 1;
a744cf53 6553
911c95a5 6554 mask = (mask << address_size) - 1;
c906108c
SS
6555 addr &= mask;
6556 }
6557 return addr;
6558}
6559
6560/* Determine whether the remote target supports binary downloading.
6561 This is accomplished by sending a no-op memory write of zero length
6562 to the target at the specified address. It does not suffice to send
23860348
MS
6563 the whole packet, since many stubs strip the eighth bit and
6564 subsequently compute a wrong checksum, which causes real havoc with
6565 remote_write_bytes.
7a292a7a 6566
96baa820 6567 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 6568 clean. In cases like this, the user should clear "remote
23860348 6569 X-packet". */
96baa820 6570
c906108c 6571static void
fba45db2 6572check_binary_download (CORE_ADDR addr)
c906108c 6573{
d01949b6 6574 struct remote_state *rs = get_remote_state ();
24b06219 6575
444abaca 6576 switch (remote_protocol_packets[PACKET_X].support)
c906108c 6577 {
96baa820
JM
6578 case PACKET_DISABLE:
6579 break;
6580 case PACKET_ENABLE:
6581 break;
6582 case PACKET_SUPPORT_UNKNOWN:
6583 {
96baa820 6584 char *p;
802188a7 6585
2e9f7625 6586 p = rs->buf;
96baa820
JM
6587 *p++ = 'X';
6588 p += hexnumstr (p, (ULONGEST) addr);
6589 *p++ = ',';
6590 p += hexnumstr (p, (ULONGEST) 0);
6591 *p++ = ':';
6592 *p = '\0';
802188a7 6593
2e9f7625 6594 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 6595 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 6596
2e9f7625 6597 if (rs->buf[0] == '\0')
96baa820
JM
6598 {
6599 if (remote_debug)
6600 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
6601 "binary downloading NOT "
6602 "supported by target\n");
444abaca 6603 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
6604 }
6605 else
6606 {
6607 if (remote_debug)
6608 fprintf_unfiltered (gdb_stdlog,
64b9b334 6609 "binary downloading supported by target\n");
444abaca 6610 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
6611 }
6612 break;
6613 }
c906108c
SS
6614 }
6615}
6616
6617/* Write memory data directly to the remote machine.
6618 This does not inform the data cache; the data cache uses this.
a76d924d 6619 HEADER is the starting part of the packet.
c906108c
SS
6620 MEMADDR is the address in the remote memory space.
6621 MYADDR is the address of the buffer in our space.
6622 LEN is the number of bytes.
a76d924d
DJ
6623 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6624 should send data as binary ('X'), or hex-encoded ('M').
6625
6626 The function creates packet of the form
6627 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6628
6629 where encoding of <DATA> is termined by PACKET_FORMAT.
6630
6631 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6632 are omitted.
6633
9b409511
YQ
6634 Return the transferred status, error or OK (an
6635 'enum target_xfer_status' value). Save the number of bytes
6636 transferred in *XFERED_LEN. Only transfer a single packet. */
c906108c 6637
9b409511 6638static enum target_xfer_status
a76d924d 6639remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
5d6df423 6640 const gdb_byte *myaddr, ULONGEST len,
9b409511
YQ
6641 ULONGEST *xfered_len, char packet_format,
6642 int use_length)
c906108c 6643{
6d820c5c 6644 struct remote_state *rs = get_remote_state ();
cfd77fa1 6645 char *p;
a76d924d
DJ
6646 char *plen = NULL;
6647 int plenlen = 0;
917317f4
JM
6648 int todo;
6649 int nr_bytes;
a257b5bb 6650 int payload_size;
6765f3e5 6651 int payload_length;
a76d924d
DJ
6652 int header_length;
6653
6654 if (packet_format != 'X' && packet_format != 'M')
6655 internal_error (__FILE__, __LINE__,
9b20d036 6656 _("remote_write_bytes_aux: bad packet format"));
c906108c 6657
5d6df423 6658 if (len == 0)
9b409511 6659 return TARGET_XFER_EOF;
b2182ed2 6660
3de11b2e 6661 payload_size = get_memory_write_packet_size ();
2bc416ba 6662
6d820c5c
DJ
6663 /* The packet buffer will be large enough for the payload;
6664 get_memory_packet_size ensures this. */
a76d924d 6665 rs->buf[0] = '\0';
c906108c 6666
a257b5bb 6667 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
6668 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6669
a76d924d
DJ
6670 payload_size -= strlen ("$,:#NN");
6671 if (!use_length)
0df8b418 6672 /* The comma won't be used. */
a76d924d
DJ
6673 payload_size += 1;
6674 header_length = strlen (header);
6675 payload_size -= header_length;
3de11b2e 6676 payload_size -= hexnumlen (memaddr);
c906108c 6677
a76d924d 6678 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 6679
a76d924d
DJ
6680 strcat (rs->buf, header);
6681 p = rs->buf + strlen (header);
6682
6683 /* Compute a best guess of the number of bytes actually transfered. */
6684 if (packet_format == 'X')
c906108c 6685 {
23860348 6686 /* Best guess at number of bytes that will fit. */
a257b5bb 6687 todo = min (len, payload_size);
a76d924d
DJ
6688 if (use_length)
6689 payload_size -= hexnumlen (todo);
3de11b2e 6690 todo = min (todo, payload_size);
a76d924d
DJ
6691 }
6692 else
6693 {
23860348 6694 /* Num bytes that will fit. */
a257b5bb 6695 todo = min (len, payload_size / 2);
a76d924d
DJ
6696 if (use_length)
6697 payload_size -= hexnumlen (todo);
3de11b2e 6698 todo = min (todo, payload_size / 2);
917317f4 6699 }
a76d924d 6700
3de11b2e
NS
6701 if (todo <= 0)
6702 internal_error (__FILE__, __LINE__,
405f8e94 6703 _("minimum packet size too small to write data"));
802188a7 6704
6765f3e5
DJ
6705 /* If we already need another packet, then try to align the end
6706 of this packet to a useful boundary. */
6707 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6708 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6709
a257b5bb 6710 /* Append "<memaddr>". */
917317f4
JM
6711 memaddr = remote_address_masked (memaddr);
6712 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 6713
a76d924d
DJ
6714 if (use_length)
6715 {
6716 /* Append ",". */
6717 *p++ = ',';
802188a7 6718
a76d924d
DJ
6719 /* Append <len>. Retain the location/size of <len>. It may need to
6720 be adjusted once the packet body has been created. */
6721 plen = p;
6722 plenlen = hexnumstr (p, (ULONGEST) todo);
6723 p += plenlen;
6724 }
a257b5bb
AC
6725
6726 /* Append ":". */
917317f4
JM
6727 *p++ = ':';
6728 *p = '\0';
802188a7 6729
a257b5bb 6730 /* Append the packet body. */
a76d924d 6731 if (packet_format == 'X')
917317f4 6732 {
917317f4
JM
6733 /* Binary mode. Send target system values byte by byte, in
6734 increasing byte addresses. Only escape certain critical
6735 characters. */
bc20a4af
PA
6736 payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
6737 &nr_bytes, payload_size);
6765f3e5
DJ
6738
6739 /* If not all TODO bytes fit, then we'll need another packet. Make
9b7194bc
DJ
6740 a second try to keep the end of the packet aligned. Don't do
6741 this if the packet is tiny. */
6742 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6765f3e5
DJ
6743 {
6744 int new_nr_bytes;
6745
6746 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6747 - memaddr);
6748 if (new_nr_bytes != nr_bytes)
6749 payload_length = remote_escape_output (myaddr, new_nr_bytes,
bc20a4af 6750 (gdb_byte *) p, &nr_bytes,
6765f3e5
DJ
6751 payload_size);
6752 }
6753
6754 p += payload_length;
a76d924d 6755 if (use_length && nr_bytes < todo)
c906108c 6756 {
802188a7 6757 /* Escape chars have filled up the buffer prematurely,
917317f4
JM
6758 and we have actually sent fewer bytes than planned.
6759 Fix-up the length field of the packet. Use the same
6760 number of characters as before. */
917317f4
JM
6761 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6762 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 6763 }
a76d924d
DJ
6764 }
6765 else
6766 {
917317f4
JM
6767 /* Normal mode: Send target system values byte by byte, in
6768 increasing byte addresses. Each byte is encoded as a two hex
6769 value. */
2644f393 6770 nr_bytes = bin2hex (myaddr, p, todo);
aa6c0017 6771 p += 2 * nr_bytes;
c906108c 6772 }
802188a7 6773
2e9f7625 6774 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 6775 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 6776
2e9f7625 6777 if (rs->buf[0] == 'E')
00d84524 6778 return TARGET_XFER_E_IO;
802188a7 6779
23860348
MS
6780 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6781 fewer bytes than we'd planned. */
9b409511
YQ
6782 *xfered_len = (ULONGEST) nr_bytes;
6783 return TARGET_XFER_OK;
c906108c
SS
6784}
6785
a76d924d
DJ
6786/* Write memory data directly to the remote machine.
6787 This does not inform the data cache; the data cache uses this.
6788 MEMADDR is the address in the remote memory space.
6789 MYADDR is the address of the buffer in our space.
6790 LEN is the number of bytes.
6791
9b409511
YQ
6792 Return the transferred status, error or OK (an
6793 'enum target_xfer_status' value). Save the number of bytes
6794 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 6795
9b409511
YQ
6796static enum target_xfer_status
6797remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
6798 ULONGEST *xfered_len)
a76d924d
DJ
6799{
6800 char *packet_format = 0;
6801
6802 /* Check whether the target supports binary download. */
6803 check_binary_download (memaddr);
6804
6805 switch (remote_protocol_packets[PACKET_X].support)
6806 {
6807 case PACKET_ENABLE:
6808 packet_format = "X";
6809 break;
6810 case PACKET_DISABLE:
6811 packet_format = "M";
6812 break;
6813 case PACKET_SUPPORT_UNKNOWN:
6814 internal_error (__FILE__, __LINE__,
6815 _("remote_write_bytes: bad internal state"));
6816 default:
6817 internal_error (__FILE__, __LINE__, _("bad switch"));
6818 }
6819
6820 return remote_write_bytes_aux (packet_format,
9b409511
YQ
6821 memaddr, myaddr, len, xfered_len,
6822 packet_format[0], 1);
a76d924d
DJ
6823}
6824
c906108c
SS
6825/* Read memory data directly from the remote machine.
6826 This does not use the data cache; the data cache uses this.
6827 MEMADDR is the address in the remote memory space.
6828 MYADDR is the address of the buffer in our space.
6829 LEN is the number of bytes.
6830
9b409511
YQ
6831 Return the transferred status, error or OK (an
6832 'enum target_xfer_status' value). Save the number of bytes
6833 transferred in *XFERED_LEN. */
c906108c 6834
9b409511
YQ
6835static enum target_xfer_status
6836remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len,
6837 ULONGEST *xfered_len)
c906108c 6838{
6d820c5c 6839 struct remote_state *rs = get_remote_state ();
23860348 6840 int max_buf_size; /* Max size of packet output buffer. */
f7605bc2
PA
6841 char *p;
6842 int todo;
6843 int i;
c906108c 6844
6b6aa828 6845 if (len == 0)
b2182ed2
DJ
6846 return 0;
6847
11cf8741 6848 max_buf_size = get_memory_read_packet_size ();
6d820c5c
DJ
6849 /* The packet buffer will be large enough for the payload;
6850 get_memory_packet_size ensures this. */
c906108c 6851
f7605bc2
PA
6852 /* Number if bytes that will fit. */
6853 todo = min (len, max_buf_size / 2);
c906108c 6854
f7605bc2
PA
6855 /* Construct "m"<memaddr>","<len>". */
6856 memaddr = remote_address_masked (memaddr);
6857 p = rs->buf;
6858 *p++ = 'm';
6859 p += hexnumstr (p, (ULONGEST) memaddr);
6860 *p++ = ',';
6861 p += hexnumstr (p, (ULONGEST) todo);
6862 *p = '\0';
6863 putpkt (rs->buf);
6864 getpkt (&rs->buf, &rs->buf_size, 0);
6865 if (rs->buf[0] == 'E'
6866 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6867 && rs->buf[3] == '\0')
00d84524 6868 return TARGET_XFER_E_IO;
f7605bc2
PA
6869 /* Reply describes memory byte by byte, each byte encoded as two hex
6870 characters. */
6871 p = rs->buf;
6872 i = hex2bin (p, myaddr, todo);
6873 /* Return what we have. Let higher layers handle partial reads. */
9b409511
YQ
6874 *xfered_len = (ULONGEST) i;
6875 return TARGET_XFER_OK;
c906108c 6876}
74531fed 6877
c906108c 6878\f
c906108c 6879
a76d924d
DJ
6880/* Sends a packet with content determined by the printf format string
6881 FORMAT and the remaining arguments, then gets the reply. Returns
6882 whether the packet was a success, a failure, or unknown. */
6883
2c0b251b 6884static enum packet_result
a76d924d
DJ
6885remote_send_printf (const char *format, ...)
6886{
6887 struct remote_state *rs = get_remote_state ();
6888 int max_size = get_remote_packet_size ();
a76d924d 6889 va_list ap;
a744cf53 6890
a76d924d
DJ
6891 va_start (ap, format);
6892
6893 rs->buf[0] = '\0';
6894 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 6895 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
6896
6897 if (putpkt (rs->buf) < 0)
6898 error (_("Communication problem with target."));
6899
6900 rs->buf[0] = '\0';
6901 getpkt (&rs->buf, &rs->buf_size, 0);
6902
6903 return packet_check_result (rs->buf);
6904}
6905
6906static void
6907restore_remote_timeout (void *p)
6908{
6909 int value = *(int *)p;
a744cf53 6910
a76d924d
DJ
6911 remote_timeout = value;
6912}
6913
6914/* Flash writing can take quite some time. We'll set
6915 effectively infinite timeout for flash operations.
6916 In future, we'll need to decide on a better approach. */
6917static const int remote_flash_timeout = 1000;
6918
6919static void
6920remote_flash_erase (struct target_ops *ops,
6921 ULONGEST address, LONGEST length)
6922{
f5656ead 6923 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
6924 int saved_remote_timeout = remote_timeout;
6925 enum packet_result ret;
a76d924d
DJ
6926 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6927 &saved_remote_timeout);
a744cf53 6928
a76d924d
DJ
6929 remote_timeout = remote_flash_timeout;
6930
6931 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 6932 phex (address, addr_size),
a76d924d
DJ
6933 phex (length, 4));
6934 switch (ret)
6935 {
6936 case PACKET_UNKNOWN:
6937 error (_("Remote target does not support flash erase"));
6938 case PACKET_ERROR:
6939 error (_("Error erasing flash with vFlashErase packet"));
6940 default:
6941 break;
6942 }
6943
6944 do_cleanups (back_to);
6945}
6946
9b409511
YQ
6947static enum target_xfer_status
6948remote_flash_write (struct target_ops *ops, ULONGEST address,
6949 ULONGEST length, ULONGEST *xfered_len,
6950 const gdb_byte *data)
a76d924d
DJ
6951{
6952 int saved_remote_timeout = remote_timeout;
9b409511 6953 enum target_xfer_status ret;
a76d924d 6954 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 6955 &saved_remote_timeout);
a76d924d
DJ
6956
6957 remote_timeout = remote_flash_timeout;
9b409511
YQ
6958 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length,
6959 xfered_len,'X', 0);
a76d924d
DJ
6960 do_cleanups (back_to);
6961
6962 return ret;
6963}
6964
6965static void
6966remote_flash_done (struct target_ops *ops)
6967{
6968 int saved_remote_timeout = remote_timeout;
6969 int ret;
6970 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6971 &saved_remote_timeout);
6972
6973 remote_timeout = remote_flash_timeout;
6974 ret = remote_send_printf ("vFlashDone");
6975 do_cleanups (back_to);
6976
6977 switch (ret)
6978 {
6979 case PACKET_UNKNOWN:
6980 error (_("Remote target does not support vFlashDone"));
6981 case PACKET_ERROR:
6982 error (_("Error finishing flash operation"));
6983 default:
6984 break;
6985 }
6986}
6987
c906108c 6988static void
fba45db2 6989remote_files_info (struct target_ops *ignore)
c906108c
SS
6990{
6991 puts_filtered ("Debugging a target over a serial line.\n");
6992}
6993\f
6994/* Stuff for dealing with the packets which are part of this protocol.
6995 See comment at top of file for details. */
6996
1927e618
PA
6997/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
6998 error to higher layers. Called when a serial error is detected.
6999 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
7000 the system error message for errno at function entry and final dot
7001 for output compatibility with throw_perror_with_name. */
1927e618
PA
7002
7003static void
7004unpush_and_perror (const char *string)
7005{
d6cb50a2 7006 int saved_errno = errno;
1927e618
PA
7007
7008 remote_unpush_target ();
d6cb50a2
JK
7009 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7010 safe_strerror (saved_errno));
1927e618
PA
7011}
7012
0876f84a 7013/* Read a single character from the remote end. */
c906108c
SS
7014
7015static int
fba45db2 7016readchar (int timeout)
c906108c
SS
7017{
7018 int ch;
5d93a237 7019 struct remote_state *rs = get_remote_state ();
c906108c 7020
5d93a237 7021 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 7022
2acceee2 7023 if (ch >= 0)
0876f84a 7024 return ch;
2acceee2
JM
7025
7026 switch ((enum serial_rc) ch)
c906108c
SS
7027 {
7028 case SERIAL_EOF:
78a095c3 7029 remote_unpush_target ();
598d3636 7030 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 7031 /* no return */
c906108c 7032 case SERIAL_ERROR:
1927e618
PA
7033 unpush_and_perror (_("Remote communication error. "
7034 "Target disconnected."));
2acceee2 7035 /* no return */
c906108c 7036 case SERIAL_TIMEOUT:
2acceee2 7037 break;
c906108c 7038 }
2acceee2 7039 return ch;
c906108c
SS
7040}
7041
c33e31fd
PA
7042/* Wrapper for serial_write that closes the target and throws if
7043 writing fails. */
7044
7045static void
7046remote_serial_write (const char *str, int len)
7047{
5d93a237
TT
7048 struct remote_state *rs = get_remote_state ();
7049
7050 if (serial_write (rs->remote_desc, str, len))
c33e31fd 7051 {
1927e618
PA
7052 unpush_and_perror (_("Remote communication error. "
7053 "Target disconnected."));
c33e31fd
PA
7054 }
7055}
7056
6d820c5c
DJ
7057/* Send the command in *BUF to the remote machine, and read the reply
7058 into *BUF. Report an error if we get an error reply. Resize
7059 *BUF using xrealloc if necessary to hold the result, and update
7060 *SIZEOF_BUF. */
c906108c
SS
7061
7062static void
6d820c5c
DJ
7063remote_send (char **buf,
7064 long *sizeof_buf)
c906108c 7065{
6d820c5c 7066 putpkt (*buf);
c2d11a7d 7067 getpkt (buf, sizeof_buf, 0);
c906108c 7068
6d820c5c
DJ
7069 if ((*buf)[0] == 'E')
7070 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
7071}
7072
6e5abd65
PA
7073/* Return a pointer to an xmalloc'ed string representing an escaped
7074 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7075 etc. The caller is responsible for releasing the returned
7076 memory. */
7077
7078static char *
7079escape_buffer (const char *buf, int n)
7080{
7081 struct cleanup *old_chain;
7082 struct ui_file *stb;
7083 char *str;
6e5abd65
PA
7084
7085 stb = mem_fileopen ();
7086 old_chain = make_cleanup_ui_file_delete (stb);
7087
7088 fputstrn_unfiltered (buf, n, 0, stb);
759ef836 7089 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
7090 do_cleanups (old_chain);
7091 return str;
7092}
7093
c906108c
SS
7094/* Display a null-terminated packet on stdout, for debugging, using C
7095 string notation. */
7096
7097static void
fba45db2 7098print_packet (char *buf)
c906108c
SS
7099{
7100 puts_filtered ("\"");
43e526b9 7101 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
7102 puts_filtered ("\"");
7103}
7104
7105int
fba45db2 7106putpkt (char *buf)
c906108c
SS
7107{
7108 return putpkt_binary (buf, strlen (buf));
7109}
7110
7111/* Send a packet to the remote machine, with error checking. The data
23860348 7112 of the packet is in BUF. The string in BUF can be at most
ea9c271d 7113 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
7114 and for a possible /0 if we are debugging (remote_debug) and want
7115 to print the sent packet as a string. */
c906108c
SS
7116
7117static int
fba45db2 7118putpkt_binary (char *buf, int cnt)
c906108c 7119{
2d717e4f 7120 struct remote_state *rs = get_remote_state ();
c906108c
SS
7121 int i;
7122 unsigned char csum = 0;
11cf8741 7123 char *buf2 = alloca (cnt + 6);
085dd6e6 7124
c906108c
SS
7125 int ch;
7126 int tcount = 0;
7127 char *p;
dd61ec5c 7128 char *message;
c906108c 7129
e24a49d8
PA
7130 /* Catch cases like trying to read memory or listing threads while
7131 we're waiting for a stop reply. The remote server wouldn't be
7132 ready to handle this request, so we'd hang and timeout. We don't
7133 have to worry about this in synchronous mode, because in that
7134 case it's not possible to issue a command while the target is
74531fed
PA
7135 running. This is not a problem in non-stop mode, because in that
7136 case, the stub is always ready to process serial input. */
7137 if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
e24a49d8
PA
7138 error (_("Cannot execute this command while the target is running."));
7139
2d717e4f
DJ
7140 /* We're sending out a new packet. Make sure we don't look at a
7141 stale cached response. */
7142 rs->cached_wait_status = 0;
7143
c906108c
SS
7144 /* Copy the packet into buffer BUF2, encapsulating it
7145 and giving it a checksum. */
7146
c906108c
SS
7147 p = buf2;
7148 *p++ = '$';
7149
7150 for (i = 0; i < cnt; i++)
7151 {
7152 csum += buf[i];
7153 *p++ = buf[i];
7154 }
7155 *p++ = '#';
7156 *p++ = tohex ((csum >> 4) & 0xf);
7157 *p++ = tohex (csum & 0xf);
7158
7159 /* Send it over and over until we get a positive ack. */
7160
7161 while (1)
7162 {
7163 int started_error_output = 0;
7164
7165 if (remote_debug)
7166 {
6e5abd65
PA
7167 struct cleanup *old_chain;
7168 char *str;
7169
c906108c 7170 *p = '\0';
6e5abd65
PA
7171 str = escape_buffer (buf2, p - buf2);
7172 old_chain = make_cleanup (xfree, str);
7173 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 7174 gdb_flush (gdb_stdlog);
6e5abd65 7175 do_cleanups (old_chain);
c906108c 7176 }
c33e31fd 7177 remote_serial_write (buf2, p - buf2);
c906108c 7178
a6f3e723
SL
7179 /* If this is a no acks version of the remote protocol, send the
7180 packet and move on. */
7181 if (rs->noack_mode)
7182 break;
7183
74531fed
PA
7184 /* Read until either a timeout occurs (-2) or '+' is read.
7185 Handle any notification that arrives in the mean time. */
c906108c
SS
7186 while (1)
7187 {
7188 ch = readchar (remote_timeout);
7189
c5aa993b 7190 if (remote_debug)
c906108c
SS
7191 {
7192 switch (ch)
7193 {
7194 case '+':
1216fa2c 7195 case '-':
c906108c
SS
7196 case SERIAL_TIMEOUT:
7197 case '$':
74531fed 7198 case '%':
c906108c
SS
7199 if (started_error_output)
7200 {
7201 putchar_unfiltered ('\n');
7202 started_error_output = 0;
7203 }
7204 }
7205 }
7206
7207 switch (ch)
7208 {
7209 case '+':
7210 if (remote_debug)
0f71a2f6 7211 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 7212 return 1;
1216fa2c
AC
7213 case '-':
7214 if (remote_debug)
7215 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 7216 /* FALLTHROUGH */
c906108c 7217 case SERIAL_TIMEOUT:
c5aa993b 7218 tcount++;
c906108c
SS
7219 if (tcount > 3)
7220 return 0;
23860348 7221 break; /* Retransmit buffer. */
c906108c
SS
7222 case '$':
7223 {
40e3f985 7224 if (remote_debug)
2bc416ba 7225 fprintf_unfiltered (gdb_stdlog,
23860348 7226 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
7227 /* It's probably an old response sent because an ACK
7228 was lost. Gobble up the packet and ack it so it
7229 doesn't get retransmitted when we resend this
7230 packet. */
6d820c5c 7231 skip_frame ();
c33e31fd 7232 remote_serial_write ("+", 1);
23860348 7233 continue; /* Now, go look for +. */
c906108c 7234 }
74531fed
PA
7235
7236 case '%':
7237 {
7238 int val;
7239
7240 /* If we got a notification, handle it, and go back to looking
7241 for an ack. */
7242 /* We've found the start of a notification. Now
7243 collect the data. */
7244 val = read_frame (&rs->buf, &rs->buf_size);
7245 if (val >= 0)
7246 {
7247 if (remote_debug)
7248 {
6e5abd65
PA
7249 struct cleanup *old_chain;
7250 char *str;
7251
7252 str = escape_buffer (rs->buf, val);
7253 old_chain = make_cleanup (xfree, str);
7254 fprintf_unfiltered (gdb_stdlog,
7255 " Notification received: %s\n",
7256 str);
7257 do_cleanups (old_chain);
74531fed 7258 }
5965e028 7259 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
7260 /* We're in sync now, rewait for the ack. */
7261 tcount = 0;
7262 }
7263 else
7264 {
7265 if (remote_debug)
7266 {
7267 if (!started_error_output)
7268 {
7269 started_error_output = 1;
7270 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7271 }
7272 fputc_unfiltered (ch & 0177, gdb_stdlog);
7273 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7274 }
7275 }
7276 continue;
7277 }
7278 /* fall-through */
c906108c
SS
7279 default:
7280 if (remote_debug)
7281 {
7282 if (!started_error_output)
7283 {
7284 started_error_output = 1;
0f71a2f6 7285 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 7286 }
0f71a2f6 7287 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
7288 }
7289 continue;
7290 }
23860348 7291 break; /* Here to retransmit. */
c906108c
SS
7292 }
7293
7294#if 0
7295 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
7296 able to get out next time we call QUIT, without anything as
7297 violent as interrupt_query. If we want to provide a way out of
7298 here without getting to the next QUIT, it should be based on
7299 hitting ^C twice as in remote_wait. */
c906108c
SS
7300 if (quit_flag)
7301 {
7302 quit_flag = 0;
7303 interrupt_query ();
7304 }
7305#endif
7306 }
a6f3e723 7307 return 0;
c906108c
SS
7308}
7309
6d820c5c
DJ
7310/* Come here after finding the start of a frame when we expected an
7311 ack. Do our best to discard the rest of this packet. */
7312
7313static void
7314skip_frame (void)
7315{
7316 int c;
7317
7318 while (1)
7319 {
7320 c = readchar (remote_timeout);
7321 switch (c)
7322 {
7323 case SERIAL_TIMEOUT:
7324 /* Nothing we can do. */
7325 return;
7326 case '#':
7327 /* Discard the two bytes of checksum and stop. */
7328 c = readchar (remote_timeout);
7329 if (c >= 0)
7330 c = readchar (remote_timeout);
7331
7332 return;
7333 case '*': /* Run length encoding. */
7334 /* Discard the repeat count. */
7335 c = readchar (remote_timeout);
7336 if (c < 0)
7337 return;
7338 break;
7339 default:
7340 /* A regular character. */
7341 break;
7342 }
7343 }
7344}
7345
c906108c 7346/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
7347 into *BUF, verifying the checksum, length, and handling run-length
7348 compression. NUL terminate the buffer. If there is not enough room,
7349 expand *BUF using xrealloc.
c906108c 7350
c2d11a7d
JM
7351 Returns -1 on error, number of characters in buffer (ignoring the
7352 trailing NULL) on success. (could be extended to return one of the
23860348 7353 SERIAL status indications). */
c2d11a7d
JM
7354
7355static long
6d820c5c
DJ
7356read_frame (char **buf_p,
7357 long *sizeof_buf)
c906108c
SS
7358{
7359 unsigned char csum;
c2d11a7d 7360 long bc;
c906108c 7361 int c;
6d820c5c 7362 char *buf = *buf_p;
a6f3e723 7363 struct remote_state *rs = get_remote_state ();
c906108c
SS
7364
7365 csum = 0;
c2d11a7d 7366 bc = 0;
c906108c
SS
7367
7368 while (1)
7369 {
7370 c = readchar (remote_timeout);
c906108c
SS
7371 switch (c)
7372 {
7373 case SERIAL_TIMEOUT:
7374 if (remote_debug)
0f71a2f6 7375 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 7376 return -1;
c906108c
SS
7377 case '$':
7378 if (remote_debug)
0f71a2f6
JM
7379 fputs_filtered ("Saw new packet start in middle of old one\n",
7380 gdb_stdlog);
23860348 7381 return -1; /* Start a new packet, count retries. */
c906108c
SS
7382 case '#':
7383 {
7384 unsigned char pktcsum;
e1b09194
AC
7385 int check_0 = 0;
7386 int check_1 = 0;
c906108c 7387
c2d11a7d 7388 buf[bc] = '\0';
c906108c 7389
e1b09194
AC
7390 check_0 = readchar (remote_timeout);
7391 if (check_0 >= 0)
7392 check_1 = readchar (remote_timeout);
802188a7 7393
e1b09194
AC
7394 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7395 {
7396 if (remote_debug)
2bc416ba 7397 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 7398 gdb_stdlog);
e1b09194
AC
7399 return -1;
7400 }
7401 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
7402 {
7403 if (remote_debug)
2bc416ba 7404 fputs_filtered ("Communication error in checksum\n",
23860348 7405 gdb_stdlog);
40e3f985
FN
7406 return -1;
7407 }
c906108c 7408
a6f3e723
SL
7409 /* Don't recompute the checksum; with no ack packets we
7410 don't have any way to indicate a packet retransmission
7411 is necessary. */
7412 if (rs->noack_mode)
7413 return bc;
7414
e1b09194 7415 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 7416 if (csum == pktcsum)
c2d11a7d 7417 return bc;
c906108c 7418
c5aa993b 7419 if (remote_debug)
c906108c 7420 {
6e5abd65
PA
7421 struct cleanup *old_chain;
7422 char *str;
7423
7424 str = escape_buffer (buf, bc);
7425 old_chain = make_cleanup (xfree, str);
7426 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7427 "Bad checksum, sentsum=0x%x, "
7428 "csum=0x%x, buf=%s\n",
6e5abd65
PA
7429 pktcsum, csum, str);
7430 do_cleanups (old_chain);
c906108c 7431 }
c2d11a7d 7432 /* Number of characters in buffer ignoring trailing
23860348 7433 NULL. */
c2d11a7d 7434 return -1;
c906108c 7435 }
23860348 7436 case '*': /* Run length encoding. */
c2c6d25f
JM
7437 {
7438 int repeat;
c906108c 7439
a744cf53 7440 csum += c;
b4501125
AC
7441 c = readchar (remote_timeout);
7442 csum += c;
23860348 7443 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 7444
23860348 7445 /* The character before ``*'' is repeated. */
c2d11a7d 7446
6d820c5c 7447 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 7448 {
6d820c5c
DJ
7449 if (bc + repeat - 1 >= *sizeof_buf - 1)
7450 {
7451 /* Make some more room in the buffer. */
7452 *sizeof_buf += repeat;
7453 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7454 buf = *buf_p;
7455 }
7456
c2d11a7d
JM
7457 memset (&buf[bc], buf[bc - 1], repeat);
7458 bc += repeat;
c2c6d25f
JM
7459 continue;
7460 }
7461
c2d11a7d 7462 buf[bc] = '\0';
6d820c5c 7463 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 7464 return -1;
c2c6d25f 7465 }
c906108c 7466 default:
6d820c5c 7467 if (bc >= *sizeof_buf - 1)
c906108c 7468 {
6d820c5c
DJ
7469 /* Make some more room in the buffer. */
7470 *sizeof_buf *= 2;
7471 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7472 buf = *buf_p;
c906108c
SS
7473 }
7474
6d820c5c
DJ
7475 buf[bc++] = c;
7476 csum += c;
7477 continue;
c906108c
SS
7478 }
7479 }
7480}
7481
7482/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
7483 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7484 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7485 rather than timing out; this is used (in synchronous mode) to wait
7486 for a target that is is executing user code to stop. */
d9fcf2fb
JM
7487/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7488 don't have to change all the calls to getpkt to deal with the
7489 return value, because at the moment I don't know what the right
23860348 7490 thing to do it for those. */
c906108c 7491void
6d820c5c
DJ
7492getpkt (char **buf,
7493 long *sizeof_buf,
c2d11a7d 7494 int forever)
d9fcf2fb
JM
7495{
7496 int timed_out;
7497
7498 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7499}
7500
7501
7502/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
7503 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7504 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7505 rather than timing out; this is used (in synchronous mode) to wait
7506 for a target that is is executing user code to stop. If FOREVER ==
7507 0, this function is allowed to time out gracefully and return an
74531fed
PA
7508 indication of this to the caller. Otherwise return the number of
7509 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
7510 enough reason to return to the caller. *IS_NOTIF is an output
7511 boolean that indicates whether *BUF holds a notification or not
7512 (a regular packet). */
74531fed 7513
3172dc30 7514static int
74531fed 7515getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 7516 int expecting_notif, int *is_notif)
c906108c 7517{
2d717e4f 7518 struct remote_state *rs = get_remote_state ();
c906108c
SS
7519 int c;
7520 int tries;
7521 int timeout;
df4b58fe 7522 int val = -1;
c906108c 7523
2d717e4f
DJ
7524 /* We're reading a new response. Make sure we don't look at a
7525 previously cached response. */
7526 rs->cached_wait_status = 0;
7527
6d820c5c 7528 strcpy (*buf, "timeout");
c906108c
SS
7529
7530 if (forever)
74531fed
PA
7531 timeout = watchdog > 0 ? watchdog : -1;
7532 else if (expecting_notif)
7533 timeout = 0; /* There should already be a char in the buffer. If
7534 not, bail out. */
c906108c
SS
7535 else
7536 timeout = remote_timeout;
7537
7538#define MAX_TRIES 3
7539
74531fed
PA
7540 /* Process any number of notifications, and then return when
7541 we get a packet. */
7542 for (;;)
c906108c 7543 {
d9c43928 7544 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
7545 times. */
7546 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 7547 {
74531fed
PA
7548 /* This can loop forever if the remote side sends us
7549 characters continuously, but if it pauses, we'll get
7550 SERIAL_TIMEOUT from readchar because of timeout. Then
7551 we'll count that as a retry.
7552
7553 Note that even when forever is set, we will only wait
7554 forever prior to the start of a packet. After that, we
7555 expect characters to arrive at a brisk pace. They should
7556 show up within remote_timeout intervals. */
7557 do
7558 c = readchar (timeout);
7559 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
7560
7561 if (c == SERIAL_TIMEOUT)
7562 {
74531fed
PA
7563 if (expecting_notif)
7564 return -1; /* Don't complain, it's normal to not get
7565 anything in this case. */
7566
23860348 7567 if (forever) /* Watchdog went off? Kill the target. */
c906108c 7568 {
2acceee2 7569 QUIT;
78a095c3 7570 remote_unpush_target ();
598d3636
JK
7571 throw_error (TARGET_CLOSE_ERROR,
7572 _("Watchdog timeout has expired. "
7573 "Target detached."));
c906108c 7574 }
c906108c 7575 if (remote_debug)
0f71a2f6 7576 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 7577 }
74531fed
PA
7578 else
7579 {
7580 /* We've found the start of a packet or notification.
7581 Now collect the data. */
7582 val = read_frame (buf, sizeof_buf);
7583 if (val >= 0)
7584 break;
7585 }
7586
c33e31fd 7587 remote_serial_write ("-", 1);
c906108c 7588 }
c906108c 7589
74531fed
PA
7590 if (tries > MAX_TRIES)
7591 {
7592 /* We have tried hard enough, and just can't receive the
7593 packet/notification. Give up. */
7594 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 7595
74531fed
PA
7596 /* Skip the ack char if we're in no-ack mode. */
7597 if (!rs->noack_mode)
c33e31fd 7598 remote_serial_write ("+", 1);
74531fed
PA
7599 return -1;
7600 }
c906108c 7601
74531fed
PA
7602 /* If we got an ordinary packet, return that to our caller. */
7603 if (c == '$')
c906108c
SS
7604 {
7605 if (remote_debug)
43e526b9 7606 {
6e5abd65
PA
7607 struct cleanup *old_chain;
7608 char *str;
7609
7610 str = escape_buffer (*buf, val);
7611 old_chain = make_cleanup (xfree, str);
7612 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7613 do_cleanups (old_chain);
43e526b9 7614 }
a6f3e723
SL
7615
7616 /* Skip the ack char if we're in no-ack mode. */
7617 if (!rs->noack_mode)
c33e31fd 7618 remote_serial_write ("+", 1);
fee9eda9
YQ
7619 if (is_notif != NULL)
7620 *is_notif = 0;
0876f84a 7621 return val;
c906108c
SS
7622 }
7623
74531fed
PA
7624 /* If we got a notification, handle it, and go back to looking
7625 for a packet. */
7626 else
7627 {
7628 gdb_assert (c == '%');
7629
7630 if (remote_debug)
7631 {
6e5abd65
PA
7632 struct cleanup *old_chain;
7633 char *str;
7634
7635 str = escape_buffer (*buf, val);
7636 old_chain = make_cleanup (xfree, str);
7637 fprintf_unfiltered (gdb_stdlog,
7638 " Notification received: %s\n",
7639 str);
7640 do_cleanups (old_chain);
74531fed 7641 }
fee9eda9
YQ
7642 if (is_notif != NULL)
7643 *is_notif = 1;
c906108c 7644
5965e028 7645 handle_notification (rs->notif_state, *buf);
c906108c 7646
74531fed 7647 /* Notifications require no acknowledgement. */
a6f3e723 7648
74531fed 7649 if (expecting_notif)
fee9eda9 7650 return val;
74531fed
PA
7651 }
7652 }
7653}
7654
7655static int
7656getpkt_sane (char **buf, long *sizeof_buf, int forever)
7657{
fee9eda9 7658 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
7659}
7660
7661static int
fee9eda9
YQ
7662getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
7663 int *is_notif)
74531fed 7664{
fee9eda9
YQ
7665 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
7666 is_notif);
c906108c 7667}
74531fed 7668
c906108c
SS
7669\f
7670static void
7d85a9c0 7671remote_kill (struct target_ops *ops)
43ff13b4 7672{
c90a6fb7 7673 volatile struct gdb_exception ex;
0fdf84ca
PA
7674
7675 /* Catch errors so the user can quit from gdb even when we
23860348 7676 aren't on speaking terms with the remote system. */
0fdf84ca
PA
7677 TRY_CATCH (ex, RETURN_MASK_ERROR)
7678 {
7679 putpkt ("k");
7680 }
7681 if (ex.reason < 0)
7682 {
7683 if (ex.error == TARGET_CLOSE_ERROR)
7684 {
7685 /* If we got an (EOF) error that caused the target
7686 to go away, then we're done, that's what we wanted.
7687 "k" is susceptible to cause a premature EOF, given
7688 that the remote server isn't actually required to
7689 reply to "k", and it can happen that it doesn't
7690 even get to reply ACK to the "k". */
7691 return;
7692 }
7693
7694 /* Otherwise, something went wrong. We didn't actually kill
7695 the target. Just propagate the exception, and let the
7696 user or higher layers decide what to do. */
7697 throw_exception (ex);
7698 }
43ff13b4 7699
0fdf84ca
PA
7700 /* We've killed the remote end, we get to mourn it. Since this is
7701 target remote, single-process, mourning the inferior also
7702 unpushes remote_ops. */
43ff13b4
JM
7703 target_mourn_inferior ();
7704}
7705
82f73884
PA
7706static int
7707remote_vkill (int pid, struct remote_state *rs)
7708{
7709 if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7710 return -1;
7711
7712 /* Tell the remote target to detach. */
bba74b36 7713 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
7714 putpkt (rs->buf);
7715 getpkt (&rs->buf, &rs->buf_size, 0);
7716
7717 if (packet_ok (rs->buf,
7718 &remote_protocol_packets[PACKET_vKill]) == PACKET_OK)
7719 return 0;
7720 else if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7721 return -1;
7722 else
7723 return 1;
7724}
7725
7726static void
7d85a9c0 7727extended_remote_kill (struct target_ops *ops)
82f73884
PA
7728{
7729 int res;
7730 int pid = ptid_get_pid (inferior_ptid);
7731 struct remote_state *rs = get_remote_state ();
7732
7733 res = remote_vkill (pid, rs);
901f9912 7734 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
82f73884
PA
7735 {
7736 /* Don't try 'k' on a multi-process aware stub -- it has no way
7737 to specify the pid. */
7738
7739 putpkt ("k");
7740#if 0
7741 getpkt (&rs->buf, &rs->buf_size, 0);
7742 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7743 res = 1;
7744#else
7745 /* Don't wait for it to die. I'm not really sure it matters whether
7746 we do or not. For the existing stubs, kill is a noop. */
7747 res = 0;
7748#endif
7749 }
7750
7751 if (res != 0)
7752 error (_("Can't kill process"));
7753
82f73884
PA
7754 target_mourn_inferior ();
7755}
7756
c906108c 7757static void
136d6dae 7758remote_mourn (struct target_ops *ops)
c906108c 7759{
136d6dae 7760 remote_mourn_1 (ops);
c906108c
SS
7761}
7762
c906108c
SS
7763/* Worker function for remote_mourn. */
7764static void
fba45db2 7765remote_mourn_1 (struct target_ops *target)
c906108c
SS
7766{
7767 unpush_target (target);
ce5ce7ed 7768
8a2492ee
PA
7769 /* remote_close takes care of doing most of the clean up. */
7770 generic_mourn_inferior ();
c906108c
SS
7771}
7772
2d717e4f
DJ
7773static void
7774extended_remote_mourn_1 (struct target_ops *target)
7775{
7776 struct remote_state *rs = get_remote_state ();
c906108c 7777
e24a49d8
PA
7778 /* In case we got here due to an error, but we're going to stay
7779 connected. */
7780 rs->waiting_for_stop_reply = 0;
7781
dc1981d7
PA
7782 /* If the current general thread belonged to the process we just
7783 detached from or has exited, the remote side current general
7784 thread becomes undefined. Considering a case like this:
7785
7786 - We just got here due to a detach.
7787 - The process that we're detaching from happens to immediately
7788 report a global breakpoint being hit in non-stop mode, in the
7789 same thread we had selected before.
7790 - GDB attaches to this process again.
7791 - This event happens to be the next event we handle.
7792
7793 GDB would consider that the current general thread didn't need to
7794 be set on the stub side (with Hg), since for all it knew,
7795 GENERAL_THREAD hadn't changed.
7796
7797 Notice that although in all-stop mode, the remote server always
7798 sets the current thread to the thread reporting the stop event,
7799 that doesn't happen in non-stop mode; in non-stop, the stub *must
7800 not* change the current thread when reporting a breakpoint hit,
7801 due to the decoupling of event reporting and event handling.
7802
7803 To keep things simple, we always invalidate our notion of the
7804 current thread. */
47f8a51d 7805 record_currthread (rs, minus_one_ptid);
dc1981d7 7806
2d717e4f
DJ
7807 /* Unlike "target remote", we do not want to unpush the target; then
7808 the next time the user says "run", we won't be connected. */
7809
48aa3c27
PA
7810 /* Call common code to mark the inferior as not running. */
7811 generic_mourn_inferior ();
7812
d729566a 7813 if (!have_inferiors ())
2d717e4f 7814 {
82f73884
PA
7815 if (!remote_multi_process_p (rs))
7816 {
7817 /* Check whether the target is running now - some remote stubs
7818 automatically restart after kill. */
7819 putpkt ("?");
7820 getpkt (&rs->buf, &rs->buf_size, 0);
7821
7822 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7823 {
3e43a32a
MS
7824 /* Assume that the target has been restarted. Set
7825 inferior_ptid so that bits of core GDB realizes
7826 there's something here, e.g., so that the user can
7827 say "kill" again. */
82f73884
PA
7828 inferior_ptid = magic_null_ptid;
7829 }
82f73884 7830 }
2d717e4f
DJ
7831 }
7832}
c906108c
SS
7833
7834static void
136d6dae 7835extended_remote_mourn (struct target_ops *ops)
c906108c 7836{
136d6dae 7837 extended_remote_mourn_1 (ops);
2d717e4f 7838}
c906108c 7839
03583c20 7840static int
2bfc0540 7841extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
7842{
7843 return (remote_protocol_packets[PACKET_QDisableRandomization].support
7844 == PACKET_ENABLE);
7845}
7846
7847static void
7848extended_remote_disable_randomization (int val)
7849{
7850 struct remote_state *rs = get_remote_state ();
7851 char *reply;
7852
bba74b36
YQ
7853 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
7854 val);
03583c20
UW
7855 putpkt (rs->buf);
7856 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
7857 if (*reply == '\0')
7858 error (_("Target does not support QDisableRandomization."));
7859 if (strcmp (reply, "OK") != 0)
7860 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
7861}
7862
2d717e4f
DJ
7863static int
7864extended_remote_run (char *args)
7865{
7866 struct remote_state *rs = get_remote_state ();
2d717e4f 7867 int len;
c906108c 7868
2d717e4f
DJ
7869 /* If the user has disabled vRun support, or we have detected that
7870 support is not available, do not try it. */
7871 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7872 return -1;
424163ea 7873
2d717e4f
DJ
7874 strcpy (rs->buf, "vRun;");
7875 len = strlen (rs->buf);
c906108c 7876
2d717e4f
DJ
7877 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
7878 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
7879 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
7880 strlen (remote_exec_file));
2d717e4f 7881
d1a41061 7882 gdb_assert (args != NULL);
2d717e4f
DJ
7883 if (*args)
7884 {
7885 struct cleanup *back_to;
7886 int i;
7887 char **argv;
7888
d1a41061 7889 argv = gdb_buildargv (args);
2d717e4f
DJ
7890 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
7891 for (i = 0; argv[i] != NULL; i++)
7892 {
7893 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
7894 error (_("Argument list too long for run packet"));
7895 rs->buf[len++] = ';';
9f1b45b0
TT
7896 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
7897 strlen (argv[i]));
2d717e4f
DJ
7898 }
7899 do_cleanups (back_to);
7900 }
7901
7902 rs->buf[len++] = '\0';
7903
7904 putpkt (rs->buf);
7905 getpkt (&rs->buf, &rs->buf_size, 0);
7906
7907 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
7908 {
3405876a 7909 /* We have a wait response. All is well. */
2d717e4f
DJ
7910 return 0;
7911 }
7912 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7913 /* It wasn't disabled before, but it is now. */
7914 return -1;
7915 else
7916 {
7917 if (remote_exec_file[0] == '\0')
7918 error (_("Running the default executable on the remote target failed; "
7919 "try \"set remote exec-file\"?"));
7920 else
7921 error (_("Running \"%s\" on the remote target failed"),
7922 remote_exec_file);
7923 }
c906108c
SS
7924}
7925
2d717e4f
DJ
7926/* In the extended protocol we want to be able to do things like
7927 "run" and have them basically work as expected. So we need
7928 a special create_inferior function. We support changing the
7929 executable file and the command line arguments, but not the
7930 environment. */
7931
43ff13b4 7932static void
77a19445
TT
7933extended_remote_create_inferior (struct target_ops *ops,
7934 char *exec_file, char *args,
7935 char **env, int from_tty)
43ff13b4 7936{
3405876a
PA
7937 int run_worked;
7938 char *stop_reply;
7939 struct remote_state *rs = get_remote_state ();
7940
43ff13b4 7941 /* If running asynchronously, register the target file descriptor
23860348 7942 with the event loop. */
75c99385 7943 if (target_can_async_p ())
2acceee2 7944 target_async (inferior_event_handler, 0);
43ff13b4 7945
03583c20 7946 /* Disable address space randomization if requested (and supported). */
2bfc0540 7947 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
7948 extended_remote_disable_randomization (disable_randomization);
7949
43ff13b4 7950 /* Now restart the remote server. */
3405876a
PA
7951 run_worked = extended_remote_run (args) != -1;
7952 if (!run_worked)
2d717e4f
DJ
7953 {
7954 /* vRun was not supported. Fail if we need it to do what the
7955 user requested. */
7956 if (remote_exec_file[0])
7957 error (_("Remote target does not support \"set remote exec-file\""));
7958 if (args[0])
7959 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 7960
2d717e4f
DJ
7961 /* Fall back to "R". */
7962 extended_remote_restart ();
7963 }
424163ea 7964
6c95b8df
PA
7965 if (!have_inferiors ())
7966 {
7967 /* Clean up from the last time we ran, before we mark the target
7968 running again. This will mark breakpoints uninserted, and
7969 get_offsets may insert breakpoints. */
7970 init_thread_list ();
7971 init_wait_for_inferior ();
7972 }
45280a52 7973
3405876a
PA
7974 /* vRun's success return is a stop reply. */
7975 stop_reply = run_worked ? rs->buf : NULL;
7976 add_current_inferior_and_thread (stop_reply);
c0a2216e 7977
2d717e4f
DJ
7978 /* Get updated offsets, if the stub uses qOffsets. */
7979 get_offsets ();
2d717e4f 7980}
c906108c 7981\f
c5aa993b 7982
b775012e
LM
7983/* Given a location's target info BP_TGT and the packet buffer BUF, output
7984 the list of conditions (in agent expression bytecode format), if any, the
7985 target needs to evaluate. The output is placed into the packet buffer
bba74b36 7986 started from BUF and ended at BUF_END. */
b775012e
LM
7987
7988static int
7989remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
7990 struct bp_target_info *bp_tgt, char *buf,
7991 char *buf_end)
b775012e
LM
7992{
7993 struct agent_expr *aexpr = NULL;
7994 int i, ix;
7995 char *pkt;
7996 char *buf_start = buf;
7997
7998 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
7999 return 0;
8000
8001 buf += strlen (buf);
bba74b36 8002 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
8003 buf++;
8004
8005 /* Send conditions to the target and free the vector. */
8006 for (ix = 0;
8007 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8008 ix++)
8009 {
bba74b36 8010 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
8011 buf += strlen (buf);
8012 for (i = 0; i < aexpr->len; ++i)
8013 buf = pack_hex_byte (buf, aexpr->buf[i]);
8014 *buf = '\0';
8015 }
b775012e
LM
8016 return 0;
8017}
8018
d3ce09f5
SS
8019static void
8020remote_add_target_side_commands (struct gdbarch *gdbarch,
8021 struct bp_target_info *bp_tgt, char *buf)
8022{
8023 struct agent_expr *aexpr = NULL;
8024 int i, ix;
8025
8026 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8027 return;
8028
8029 buf += strlen (buf);
8030
8031 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8032 buf += strlen (buf);
8033
8034 /* Concatenate all the agent expressions that are commands into the
8035 cmds parameter. */
8036 for (ix = 0;
8037 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8038 ix++)
8039 {
8040 sprintf (buf, "X%x,", aexpr->len);
8041 buf += strlen (buf);
8042 for (i = 0; i < aexpr->len; ++i)
8043 buf = pack_hex_byte (buf, aexpr->buf[i]);
8044 *buf = '\0';
8045 }
d3ce09f5
SS
8046}
8047
8181d85f
DJ
8048/* Insert a breakpoint. On targets that have software breakpoint
8049 support, we ask the remote target to do the work; on targets
8050 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
8051
8052static int
3db08215
MM
8053remote_insert_breakpoint (struct target_ops *ops,
8054 struct gdbarch *gdbarch,
a6d9a66e 8055 struct bp_target_info *bp_tgt)
c906108c 8056{
d471ea57
AC
8057 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8058 If it succeeds, then set the support to PACKET_ENABLE. If it
8059 fails, and the user has explicitly requested the Z support then
23860348 8060 report an error, otherwise, mark it disabled and go on. */
802188a7 8061
444abaca 8062 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
96baa820 8063 {
7c0f6dcc 8064 CORE_ADDR addr = bp_tgt->placed_address;
4fff2411 8065 struct remote_state *rs;
bba74b36 8066 char *p, *endbuf;
7c0f6dcc 8067 int bpsize;
b775012e 8068 struct condition_list *cond = NULL;
4fff2411 8069
28439a30
PA
8070 /* Make sure the remote is pointing at the right process, if
8071 necessary. */
8072 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8073 set_general_process ();
8074
a1dcb23a 8075 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
8076
8077 rs = get_remote_state ();
8078 p = rs->buf;
bba74b36 8079 endbuf = rs->buf + get_remote_packet_size ();
802188a7 8080
96baa820
JM
8081 *(p++) = 'Z';
8082 *(p++) = '0';
8083 *(p++) = ',';
7c0f6dcc 8084 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 8085 p += hexnumstr (p, addr);
bba74b36 8086 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 8087
efcc2da7 8088 if (remote_supports_cond_breakpoints (ops))
bba74b36 8089 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8090
78eff0ec 8091 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
8092 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8093
6d820c5c
DJ
8094 putpkt (rs->buf);
8095 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8096
6d820c5c 8097 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 8098 {
d471ea57
AC
8099 case PACKET_ERROR:
8100 return -1;
8101 case PACKET_OK:
7c0f6dcc
JL
8102 bp_tgt->placed_address = addr;
8103 bp_tgt->placed_size = bpsize;
d471ea57
AC
8104 return 0;
8105 case PACKET_UNKNOWN:
8106 break;
96baa820
JM
8107 }
8108 }
c906108c 8109
0000e5cc
PA
8110 /* If this breakpoint has target-side commands but this stub doesn't
8111 support Z0 packets, throw error. */
8112 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8113 throw_error (NOT_SUPPORTED_ERROR, _("\
8114Target doesn't support breakpoints that have target side commands."));
8115
3db08215 8116 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8117}
8118
8119static int
3db08215
MM
8120remote_remove_breakpoint (struct target_ops *ops,
8121 struct gdbarch *gdbarch,
a6d9a66e 8122 struct bp_target_info *bp_tgt)
c906108c 8123{
8181d85f 8124 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 8125 struct remote_state *rs = get_remote_state ();
96baa820 8126
444abaca 8127 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
96baa820 8128 {
6d820c5c 8129 char *p = rs->buf;
bba74b36 8130 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 8131
28439a30
PA
8132 /* Make sure the remote is pointing at the right process, if
8133 necessary. */
8134 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8135 set_general_process ();
8136
96baa820
JM
8137 *(p++) = 'z';
8138 *(p++) = '0';
8139 *(p++) = ',';
8140
8181d85f
DJ
8141 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8142 p += hexnumstr (p, addr);
bba74b36 8143 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 8144
6d820c5c
DJ
8145 putpkt (rs->buf);
8146 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8147
6d820c5c 8148 return (rs->buf[0] == 'E');
96baa820
JM
8149 }
8150
3db08215 8151 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8152}
8153
d471ea57
AC
8154static int
8155watchpoint_to_Z_packet (int type)
8156{
8157 switch (type)
8158 {
8159 case hw_write:
bb858e6a 8160 return Z_PACKET_WRITE_WP;
d471ea57
AC
8161 break;
8162 case hw_read:
bb858e6a 8163 return Z_PACKET_READ_WP;
d471ea57
AC
8164 break;
8165 case hw_access:
bb858e6a 8166 return Z_PACKET_ACCESS_WP;
d471ea57
AC
8167 break;
8168 default:
8e65ff28 8169 internal_error (__FILE__, __LINE__,
e2e0b3e5 8170 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
8171 }
8172}
8173
3c3bea1c 8174static int
7bb99c53
TT
8175remote_insert_watchpoint (struct target_ops *self,
8176 CORE_ADDR addr, int len, int type,
0cf6dd15 8177 struct expression *cond)
96baa820 8178{
d01949b6 8179 struct remote_state *rs = get_remote_state ();
bba74b36 8180 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8181 char *p;
d471ea57 8182 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 8183
444abaca 8184 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
85d721b8 8185 return 1;
802188a7 8186
28439a30
PA
8187 /* Make sure the remote is pointing at the right process, if
8188 necessary. */
8189 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8190 set_general_process ();
8191
bba74b36 8192 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 8193 p = strchr (rs->buf, '\0');
96baa820
JM
8194 addr = remote_address_masked (addr);
8195 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8196 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 8197
6d820c5c
DJ
8198 putpkt (rs->buf);
8199 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8200
6d820c5c 8201 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8202 {
8203 case PACKET_ERROR:
d471ea57 8204 return -1;
85d721b8
PA
8205 case PACKET_UNKNOWN:
8206 return 1;
d471ea57
AC
8207 case PACKET_OK:
8208 return 0;
8209 }
8e65ff28 8210 internal_error (__FILE__, __LINE__,
e2e0b3e5 8211 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
8212}
8213
283002cf
MR
8214static int
8215remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8216 CORE_ADDR start, int length)
8217{
8218 CORE_ADDR diff = remote_address_masked (addr - start);
8219
8220 return diff < length;
8221}
8222
d471ea57 8223
3c3bea1c 8224static int
11b5219a
TT
8225remote_remove_watchpoint (struct target_ops *self,
8226 CORE_ADDR addr, int len, int type,
0cf6dd15 8227 struct expression *cond)
96baa820 8228{
d01949b6 8229 struct remote_state *rs = get_remote_state ();
bba74b36 8230 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8231 char *p;
d471ea57
AC
8232 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8233
444abaca 8234 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
5cffb350 8235 return -1;
802188a7 8236
28439a30
PA
8237 /* Make sure the remote is pointing at the right process, if
8238 necessary. */
8239 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8240 set_general_process ();
8241
bba74b36 8242 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 8243 p = strchr (rs->buf, '\0');
96baa820
JM
8244 addr = remote_address_masked (addr);
8245 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8246 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
8247 putpkt (rs->buf);
8248 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8249
6d820c5c 8250 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8251 {
8252 case PACKET_ERROR:
8253 case PACKET_UNKNOWN:
8254 return -1;
8255 case PACKET_OK:
8256 return 0;
8257 }
8e65ff28 8258 internal_error (__FILE__, __LINE__,
e2e0b3e5 8259 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
8260}
8261
3c3bea1c 8262
501eef12 8263int remote_hw_watchpoint_limit = -1;
480a3f21 8264int remote_hw_watchpoint_length_limit = -1;
501eef12 8265int remote_hw_breakpoint_limit = -1;
d471ea57 8266
480a3f21 8267static int
31568a15
TT
8268remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8269 CORE_ADDR addr, int len)
480a3f21
PW
8270{
8271 if (remote_hw_watchpoint_length_limit == 0)
8272 return 0;
8273 else if (remote_hw_watchpoint_length_limit < 0)
8274 return 1;
8275 else if (len <= remote_hw_watchpoint_length_limit)
8276 return 1;
8277 else
8278 return 0;
8279}
8280
b9362cc7 8281static int
5461485a
TT
8282remote_check_watch_resources (struct target_ops *self,
8283 int type, int cnt, int ot)
96baa820 8284{
3c3bea1c
GS
8285 if (type == bp_hardware_breakpoint)
8286 {
8287 if (remote_hw_breakpoint_limit == 0)
8288 return 0;
501eef12
AC
8289 else if (remote_hw_breakpoint_limit < 0)
8290 return 1;
3c3bea1c
GS
8291 else if (cnt <= remote_hw_breakpoint_limit)
8292 return 1;
8293 }
8294 else
8295 {
8296 if (remote_hw_watchpoint_limit == 0)
8297 return 0;
501eef12
AC
8298 else if (remote_hw_watchpoint_limit < 0)
8299 return 1;
3c3bea1c
GS
8300 else if (ot)
8301 return -1;
8302 else if (cnt <= remote_hw_watchpoint_limit)
8303 return 1;
8304 }
8305 return -1;
8306}
8307
b9362cc7 8308static int
6a109b6b 8309remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 8310{
ee154bee
TT
8311 struct remote_state *rs = get_remote_state ();
8312
8313 return rs->remote_stopped_by_watchpoint_p;
3c3bea1c
GS
8314}
8315
4aa7a7f5
JJ
8316static int
8317remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 8318{
ee154bee 8319 struct remote_state *rs = get_remote_state ();
4aa7a7f5 8320 int rc = 0;
a744cf53 8321
6a109b6b 8322 if (remote_stopped_by_watchpoint (target))
4aa7a7f5 8323 {
ee154bee 8324 *addr_p = rs->remote_watch_data_address;
4aa7a7f5
JJ
8325 rc = 1;
8326 }
8327
8328 return rc;
3c3bea1c
GS
8329}
8330
8331
8332static int
23a26771 8333remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 8334 struct bp_target_info *bp_tgt)
3c3bea1c 8335{
8181d85f 8336 CORE_ADDR addr;
4fff2411 8337 struct remote_state *rs;
bba74b36 8338 char *p, *endbuf;
dd61ec5c 8339 char *message;
802188a7 8340
c8189ed1 8341 /* The length field should be set to the size of a breakpoint
8181d85f 8342 instruction, even though we aren't inserting one ourselves. */
c8189ed1 8343
a1dcb23a 8344 gdbarch_remote_breakpoint_from_pc
a6d9a66e 8345 (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
3c3bea1c 8346
444abaca 8347 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5cffb350 8348 return -1;
2bc416ba 8349
28439a30
PA
8350 /* Make sure the remote is pointing at the right process, if
8351 necessary. */
8352 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8353 set_general_process ();
8354
4fff2411
JZ
8355 rs = get_remote_state ();
8356 p = rs->buf;
bba74b36 8357 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 8358
96baa820
JM
8359 *(p++) = 'Z';
8360 *(p++) = '1';
8361 *(p++) = ',';
802188a7 8362
8181d85f 8363 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 8364 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8365 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 8366
efcc2da7 8367 if (remote_supports_cond_breakpoints (self))
bba74b36 8368 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8369
78eff0ec 8370 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
8371 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8372
6d820c5c
DJ
8373 putpkt (rs->buf);
8374 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8375
6d820c5c 8376 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
8377 {
8378 case PACKET_ERROR:
dd61ec5c
MW
8379 if (rs->buf[1] == '.')
8380 {
8381 message = strchr (rs->buf + 2, '.');
8382 if (message)
0316657e 8383 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
8384 }
8385 return -1;
d471ea57
AC
8386 case PACKET_UNKNOWN:
8387 return -1;
8388 case PACKET_OK:
8389 return 0;
8390 }
8e65ff28 8391 internal_error (__FILE__, __LINE__,
e2e0b3e5 8392 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
8393}
8394
d471ea57 8395
802188a7 8396static int
a64dc96c 8397remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 8398 struct bp_target_info *bp_tgt)
96baa820 8399{
8181d85f 8400 CORE_ADDR addr;
d01949b6 8401 struct remote_state *rs = get_remote_state ();
6d820c5c 8402 char *p = rs->buf;
bba74b36 8403 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 8404
444abaca 8405 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5cffb350 8406 return -1;
802188a7 8407
28439a30
PA
8408 /* Make sure the remote is pointing at the right process, if
8409 necessary. */
8410 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8411 set_general_process ();
8412
96baa820
JM
8413 *(p++) = 'z';
8414 *(p++) = '1';
8415 *(p++) = ',';
802188a7 8416
8181d85f 8417 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 8418 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8419 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 8420
6d820c5c
DJ
8421 putpkt (rs->buf);
8422 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 8423
6d820c5c 8424 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
8425 {
8426 case PACKET_ERROR:
8427 case PACKET_UNKNOWN:
8428 return -1;
8429 case PACKET_OK:
8430 return 0;
8431 }
8e65ff28 8432 internal_error (__FILE__, __LINE__,
e2e0b3e5 8433 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 8434}
96baa820 8435
4a5e7a5b
PA
8436/* Verify memory using the "qCRC:" request. */
8437
8438static int
8439remote_verify_memory (struct target_ops *ops,
8440 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8441{
8442 struct remote_state *rs = get_remote_state ();
8443 unsigned long host_crc, target_crc;
8444 char *tmp;
8445
28439a30
PA
8446 /* Make sure the remote is pointing at the right process. */
8447 set_general_process ();
8448
4a5e7a5b
PA
8449 /* FIXME: assumes lma can fit into long. */
8450 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8451 (long) lma, (long) size);
8452 putpkt (rs->buf);
8453
8454 /* Be clever; compute the host_crc before waiting for target
8455 reply. */
85ec6ce7 8456 host_crc = xcrc32 (data, size, 0xffffffff);
4a5e7a5b
PA
8457
8458 getpkt (&rs->buf, &rs->buf_size, 0);
8459 if (rs->buf[0] == 'E')
8460 return -1;
8461
8462 if (rs->buf[0] != 'C')
8463 error (_("remote target does not support this operation"));
8464
8465 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8466 target_crc = target_crc * 16 + fromhex (*tmp);
8467
8468 return (host_crc == target_crc);
8469}
8470
c906108c
SS
8471/* compare-sections command
8472
8473 With no arguments, compares each loadable section in the exec bfd
8474 with the same memory range on the target, and reports mismatches.
4a5e7a5b 8475 Useful for verifying the image on the target against the exec file. */
e514a9d6 8476
c906108c 8477static void
fba45db2 8478compare_sections_command (char *args, int from_tty)
c906108c
SS
8479{
8480 asection *s;
c906108c 8481 struct cleanup *old_chain;
948f8e3d 8482 gdb_byte *sectdata;
ce359b09 8483 const char *sectname;
c906108c
SS
8484 bfd_size_type size;
8485 bfd_vma lma;
8486 int matched = 0;
8487 int mismatched = 0;
4a5e7a5b 8488 int res;
c906108c
SS
8489
8490 if (!exec_bfd)
8a3fe4f8 8491 error (_("command cannot be used without an exec file"));
c906108c 8492
28439a30
PA
8493 /* Make sure the remote is pointing at the right process. */
8494 set_general_process ();
8495
c5aa993b 8496 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
8497 {
8498 if (!(s->flags & SEC_LOAD))
0df8b418 8499 continue; /* Skip non-loadable section. */
c906108c 8500
2c500098 8501 size = bfd_get_section_size (s);
c906108c 8502 if (size == 0)
0df8b418 8503 continue; /* Skip zero-length section. */
c906108c 8504
ce359b09 8505 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 8506 if (args && strcmp (args, sectname) != 0)
0df8b418 8507 continue; /* Not the section selected by user. */
c906108c 8508
0df8b418 8509 matched = 1; /* Do this section. */
c906108c 8510 lma = s->lma;
c906108c 8511
c906108c 8512 sectdata = xmalloc (size);
b8c9b27d 8513 old_chain = make_cleanup (xfree, sectdata);
c906108c 8514 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 8515
4a5e7a5b
PA
8516 res = target_verify_memory (sectdata, lma, size);
8517
8518 if (res == -1)
5af949e3 8519 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
8520 paddress (target_gdbarch (), lma),
8521 paddress (target_gdbarch (), lma + size));
c906108c 8522
5af949e3 8523 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
8524 paddress (target_gdbarch (), lma),
8525 paddress (target_gdbarch (), lma + size));
4a5e7a5b 8526 if (res)
c906108c
SS
8527 printf_filtered ("matched.\n");
8528 else
c5aa993b
JM
8529 {
8530 printf_filtered ("MIS-MATCHED!\n");
8531 mismatched++;
8532 }
c906108c
SS
8533
8534 do_cleanups (old_chain);
8535 }
8536 if (mismatched > 0)
8a3fe4f8
AC
8537 warning (_("One or more sections of the remote executable does not match\n\
8538the loaded file\n"));
c906108c 8539 if (args && !matched)
a3f17187 8540 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
8541}
8542
0e7f50da
UW
8543/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8544 into remote target. The number of bytes written to the remote
8545 target is returned, or -1 for error. */
8546
9b409511 8547static enum target_xfer_status
0e7f50da
UW
8548remote_write_qxfer (struct target_ops *ops, const char *object_name,
8549 const char *annex, const gdb_byte *writebuf,
9b409511 8550 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
8551 struct packet_config *packet)
8552{
8553 int i, buf_len;
8554 ULONGEST n;
0e7f50da
UW
8555 struct remote_state *rs = get_remote_state ();
8556 int max_size = get_memory_write_packet_size ();
8557
8558 if (packet->support == PACKET_DISABLE)
2ed4b548 8559 return TARGET_XFER_E_IO;
0e7f50da
UW
8560
8561 /* Insert header. */
8562 i = snprintf (rs->buf, max_size,
8563 "qXfer:%s:write:%s:%s:",
8564 object_name, annex ? annex : "",
8565 phex_nz (offset, sizeof offset));
8566 max_size -= (i + 1);
8567
8568 /* Escape as much data as fits into rs->buf. */
8569 buf_len = remote_escape_output
bc20a4af 8570 (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
8571
8572 if (putpkt_binary (rs->buf, i + buf_len) < 0
8573 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8574 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 8575 return TARGET_XFER_E_IO;
0e7f50da
UW
8576
8577 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
8578
8579 *xfered_len = n;
8580 return TARGET_XFER_OK;
0e7f50da
UW
8581}
8582
0876f84a
DJ
8583/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8584 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8585 number of bytes read is returned, or 0 for EOF, or -1 for error.
8586 The number of bytes read may be less than LEN without indicating an
8587 EOF. PACKET is checked and updated to indicate whether the remote
8588 target supports this object. */
8589
9b409511 8590static enum target_xfer_status
0876f84a
DJ
8591remote_read_qxfer (struct target_ops *ops, const char *object_name,
8592 const char *annex,
8593 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 8594 ULONGEST *xfered_len,
0876f84a
DJ
8595 struct packet_config *packet)
8596{
0876f84a 8597 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
8598 LONGEST i, n, packet_len;
8599
8600 if (packet->support == PACKET_DISABLE)
2ed4b548 8601 return TARGET_XFER_E_IO;
0876f84a
DJ
8602
8603 /* Check whether we've cached an end-of-object packet that matches
8604 this request. */
8e88304f 8605 if (rs->finished_object)
0876f84a 8606 {
8e88304f
TT
8607 if (strcmp (object_name, rs->finished_object) == 0
8608 && strcmp (annex ? annex : "", rs->finished_annex) == 0
8609 && offset == rs->finished_offset)
9b409511
YQ
8610 return TARGET_XFER_EOF;
8611
0876f84a
DJ
8612
8613 /* Otherwise, we're now reading something different. Discard
8614 the cache. */
8e88304f
TT
8615 xfree (rs->finished_object);
8616 xfree (rs->finished_annex);
8617 rs->finished_object = NULL;
8618 rs->finished_annex = NULL;
0876f84a
DJ
8619 }
8620
8621 /* Request only enough to fit in a single packet. The actual data
8622 may not, since we don't know how much of it will need to be escaped;
8623 the target is free to respond with slightly less data. We subtract
8624 five to account for the response type and the protocol frame. */
8625 n = min (get_remote_packet_size () - 5, len);
8626 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8627 object_name, annex ? annex : "",
8628 phex_nz (offset, sizeof offset),
8629 phex_nz (n, sizeof n));
8630 i = putpkt (rs->buf);
8631 if (i < 0)
2ed4b548 8632 return TARGET_XFER_E_IO;
0876f84a
DJ
8633
8634 rs->buf[0] = '\0';
8635 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8636 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 8637 return TARGET_XFER_E_IO;
0876f84a
DJ
8638
8639 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8640 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8641
8642 /* 'm' means there is (or at least might be) more data after this
8643 batch. That does not make sense unless there's at least one byte
8644 of data in this reply. */
8645 if (rs->buf[0] == 'm' && packet_len == 1)
8646 error (_("Remote qXfer reply contained no data."));
8647
8648 /* Got some data. */
bc20a4af
PA
8649 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
8650 packet_len - 1, readbuf, n);
0876f84a
DJ
8651
8652 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
8653 or possibly empty. If we have the final block of a non-empty
8654 object, record this fact to bypass a subsequent partial read. */
8655 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 8656 {
8e88304f
TT
8657 rs->finished_object = xstrdup (object_name);
8658 rs->finished_annex = xstrdup (annex ? annex : "");
8659 rs->finished_offset = offset + i;
0876f84a
DJ
8660 }
8661
9b409511
YQ
8662 if (i == 0)
8663 return TARGET_XFER_EOF;
8664 else
8665 {
8666 *xfered_len = i;
8667 return TARGET_XFER_OK;
8668 }
0876f84a
DJ
8669}
8670
9b409511 8671static enum target_xfer_status
4b8a223f 8672remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 8673 const char *annex, gdb_byte *readbuf,
9b409511
YQ
8674 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
8675 ULONGEST *xfered_len)
c906108c 8676{
82f73884 8677 struct remote_state *rs;
c906108c 8678 int i;
6d820c5c 8679 char *p2;
1e3ff5ad 8680 char query_type;
c906108c 8681
e6e4e701 8682 set_remote_traceframe ();
82f73884
PA
8683 set_general_thread (inferior_ptid);
8684
8685 rs = get_remote_state ();
8686
b2182ed2 8687 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
8688 if (object == TARGET_OBJECT_MEMORY)
8689 {
2d717e4f
DJ
8690 /* If the remote target is connected but not running, we should
8691 pass this request down to a lower stratum (e.g. the executable
8692 file). */
8693 if (!target_has_execution)
9b409511 8694 return TARGET_XFER_EOF;
2d717e4f 8695
21e3b9b9 8696 if (writebuf != NULL)
9b409511 8697 return remote_write_bytes (offset, writebuf, len, xfered_len);
21e3b9b9 8698 else
9b409511 8699 return remote_read_bytes (offset, readbuf, len, xfered_len);
21e3b9b9
DJ
8700 }
8701
0df8b418 8702 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
8703 if (object == TARGET_OBJECT_SPU)
8704 {
8705 if (readbuf)
8706 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
8707 xfered_len, &remote_protocol_packets
8708 [PACKET_qXfer_spu_read]);
0e7f50da
UW
8709 else
8710 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
8711 xfered_len, &remote_protocol_packets
8712 [PACKET_qXfer_spu_write]);
0e7f50da
UW
8713 }
8714
4aa995e1
PA
8715 /* Handle extra signal info using qxfer packets. */
8716 if (object == TARGET_OBJECT_SIGNAL_INFO)
8717 {
8718 if (readbuf)
8719 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 8720 xfered_len, &remote_protocol_packets
4aa995e1
PA
8721 [PACKET_qXfer_siginfo_read]);
8722 else
3e43a32a 8723 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 8724 writebuf, offset, len, xfered_len,
4aa995e1
PA
8725 &remote_protocol_packets
8726 [PACKET_qXfer_siginfo_write]);
8727 }
8728
0fb4aa4b
PA
8729 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8730 {
8731 if (readbuf)
3e43a32a 8732 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 8733 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
8734 &remote_protocol_packets
8735 [PACKET_qXfer_statictrace_read]);
8736 else
2ed4b548 8737 return TARGET_XFER_E_IO;
0fb4aa4b
PA
8738 }
8739
a76d924d
DJ
8740 /* Only handle flash writes. */
8741 if (writebuf != NULL)
8742 {
8743 LONGEST xfered;
8744
8745 switch (object)
8746 {
8747 case TARGET_OBJECT_FLASH:
9b409511
YQ
8748 return remote_flash_write (ops, offset, len, xfered_len,
8749 writebuf);
a76d924d
DJ
8750
8751 default:
2ed4b548 8752 return TARGET_XFER_E_IO;
a76d924d
DJ
8753 }
8754 }
4b8a223f 8755
1e3ff5ad
AC
8756 /* Map pre-existing objects onto letters. DO NOT do this for new
8757 objects!!! Instead specify new query packets. */
8758 switch (object)
c906108c 8759 {
1e3ff5ad
AC
8760 case TARGET_OBJECT_AVR:
8761 query_type = 'R';
8762 break;
802188a7
RM
8763
8764 case TARGET_OBJECT_AUXV:
0876f84a
DJ
8765 gdb_assert (annex == NULL);
8766 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 8767 xfered_len,
0876f84a 8768 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 8769
23181151
DJ
8770 case TARGET_OBJECT_AVAILABLE_FEATURES:
8771 return remote_read_qxfer
9b409511 8772 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
8773 &remote_protocol_packets[PACKET_qXfer_features]);
8774
cfa9d6d9
DJ
8775 case TARGET_OBJECT_LIBRARIES:
8776 return remote_read_qxfer
9b409511 8777 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
8778 &remote_protocol_packets[PACKET_qXfer_libraries]);
8779
2268b414
JK
8780 case TARGET_OBJECT_LIBRARIES_SVR4:
8781 return remote_read_qxfer
9b409511 8782 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
8783 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
8784
fd79ecee
DJ
8785 case TARGET_OBJECT_MEMORY_MAP:
8786 gdb_assert (annex == NULL);
8787 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 8788 xfered_len,
fd79ecee
DJ
8789 &remote_protocol_packets[PACKET_qXfer_memory_map]);
8790
07e059b5
VP
8791 case TARGET_OBJECT_OSDATA:
8792 /* Should only get here if we're connected. */
5d93a237 8793 gdb_assert (rs->remote_desc);
07e059b5 8794 return remote_read_qxfer
9b409511 8795 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
8796 &remote_protocol_packets[PACKET_qXfer_osdata]);
8797
dc146f7c
VP
8798 case TARGET_OBJECT_THREADS:
8799 gdb_assert (annex == NULL);
8800 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 8801 xfered_len,
dc146f7c
VP
8802 &remote_protocol_packets[PACKET_qXfer_threads]);
8803
b3b9301e
PA
8804 case TARGET_OBJECT_TRACEFRAME_INFO:
8805 gdb_assert (annex == NULL);
8806 return remote_read_qxfer
9b409511 8807 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 8808 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
8809
8810 case TARGET_OBJECT_FDPIC:
8811 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 8812 xfered_len,
78d85199 8813 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
8814
8815 case TARGET_OBJECT_OPENVMS_UIB:
8816 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 8817 xfered_len,
169081d0
TG
8818 &remote_protocol_packets[PACKET_qXfer_uib]);
8819
9accd112
MM
8820 case TARGET_OBJECT_BTRACE:
8821 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 8822 xfered_len,
9accd112
MM
8823 &remote_protocol_packets[PACKET_qXfer_btrace]);
8824
1e3ff5ad 8825 default:
2ed4b548 8826 return TARGET_XFER_E_IO;
c906108c
SS
8827 }
8828
4b8a223f 8829 /* Note: a zero OFFSET and LEN can be used to query the minimum
1e3ff5ad 8830 buffer size. */
4b8a223f 8831 if (offset == 0 && len == 0)
ea9c271d 8832 return (get_remote_packet_size ());
0df8b418 8833 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 8834 large enough let the caller deal with it. */
ea9c271d 8835 if (len < get_remote_packet_size ())
2ed4b548 8836 return TARGET_XFER_E_IO;
ea9c271d 8837 len = get_remote_packet_size ();
1e3ff5ad 8838
23860348 8839 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 8840 if (!rs->remote_desc)
8a3fe4f8 8841 error (_("remote query is only available after target open"));
c906108c 8842
1e3ff5ad 8843 gdb_assert (annex != NULL);
4b8a223f 8844 gdb_assert (readbuf != NULL);
c906108c 8845
6d820c5c 8846 p2 = rs->buf;
c906108c
SS
8847 *p2++ = 'q';
8848 *p2++ = query_type;
8849
23860348
MS
8850 /* We used one buffer char for the remote protocol q command and
8851 another for the query type. As the remote protocol encapsulation
8852 uses 4 chars plus one extra in case we are debugging
8853 (remote_debug), we have PBUFZIZ - 7 left to pack the query
8854 string. */
c906108c 8855 i = 0;
ea9c271d 8856 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 8857 {
1e3ff5ad
AC
8858 /* Bad caller may have sent forbidden characters. */
8859 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
8860 *p2++ = annex[i];
c906108c
SS
8861 i++;
8862 }
1e3ff5ad
AC
8863 *p2 = '\0';
8864 gdb_assert (annex[i] == '\0');
c906108c 8865
6d820c5c 8866 i = putpkt (rs->buf);
c5aa993b 8867 if (i < 0)
2ed4b548 8868 return TARGET_XFER_E_IO;
c906108c 8869
6d820c5c
DJ
8870 getpkt (&rs->buf, &rs->buf_size, 0);
8871 strcpy ((char *) readbuf, rs->buf);
c906108c 8872
9b409511
YQ
8873 *xfered_len = strlen ((char *) readbuf);
8874 return TARGET_XFER_OK;
c906108c
SS
8875}
8876
08388c79
DE
8877static int
8878remote_search_memory (struct target_ops* ops,
8879 CORE_ADDR start_addr, ULONGEST search_space_len,
8880 const gdb_byte *pattern, ULONGEST pattern_len,
8881 CORE_ADDR *found_addrp)
8882{
f5656ead 8883 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
8884 struct remote_state *rs = get_remote_state ();
8885 int max_size = get_memory_write_packet_size ();
8886 struct packet_config *packet =
8887 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
8888 /* Number of packet bytes used to encode the pattern;
8889 this could be more than PATTERN_LEN due to escape characters. */
08388c79 8890 int escaped_pattern_len;
0df8b418 8891 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
8892 int used_pattern_len;
8893 int i;
8894 int found;
8895 ULONGEST found_addr;
8896
8897 /* Don't go to the target if we don't have to.
8898 This is done before checking packet->support to avoid the possibility that
8899 a success for this edge case means the facility works in general. */
8900 if (pattern_len > search_space_len)
8901 return 0;
8902 if (pattern_len == 0)
8903 {
8904 *found_addrp = start_addr;
8905 return 1;
8906 }
8907
8908 /* If we already know the packet isn't supported, fall back to the simple
8909 way of searching memory. */
8910
8911 if (packet->support == PACKET_DISABLE)
8912 {
8913 /* Target doesn't provided special support, fall back and use the
8914 standard support (copy memory and do the search here). */
8915 return simple_search_memory (ops, start_addr, search_space_len,
8916 pattern, pattern_len, found_addrp);
8917 }
8918
28439a30
PA
8919 /* Make sure the remote is pointing at the right process. */
8920 set_general_process ();
8921
08388c79
DE
8922 /* Insert header. */
8923 i = snprintf (rs->buf, max_size,
8924 "qSearch:memory:%s;%s;",
5af949e3 8925 phex_nz (start_addr, addr_size),
08388c79
DE
8926 phex_nz (search_space_len, sizeof (search_space_len)));
8927 max_size -= (i + 1);
8928
8929 /* Escape as much data as fits into rs->buf. */
8930 escaped_pattern_len =
bc20a4af 8931 remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
08388c79
DE
8932 &used_pattern_len, max_size);
8933
8934 /* Bail if the pattern is too large. */
8935 if (used_pattern_len != pattern_len)
9b20d036 8936 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
8937
8938 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
8939 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8940 || packet_ok (rs->buf, packet) != PACKET_OK)
8941 {
8942 /* The request may not have worked because the command is not
8943 supported. If so, fall back to the simple way. */
8944 if (packet->support == PACKET_DISABLE)
8945 {
8946 return simple_search_memory (ops, start_addr, search_space_len,
8947 pattern, pattern_len, found_addrp);
8948 }
8949 return -1;
8950 }
8951
8952 if (rs->buf[0] == '0')
8953 found = 0;
8954 else if (rs->buf[0] == '1')
8955 {
8956 found = 1;
8957 if (rs->buf[1] != ',')
10e0fa18 8958 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
8959 unpack_varlen_hex (rs->buf + 2, &found_addr);
8960 *found_addrp = found_addr;
8961 }
8962 else
10e0fa18 8963 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
8964
8965 return found;
8966}
8967
96baa820 8968static void
1aac633b 8969remote_rcmd (struct target_ops *self, char *command,
d9fcf2fb 8970 struct ui_file *outbuf)
96baa820 8971{
d01949b6 8972 struct remote_state *rs = get_remote_state ();
2e9f7625 8973 char *p = rs->buf;
96baa820 8974
5d93a237 8975 if (!rs->remote_desc)
8a3fe4f8 8976 error (_("remote rcmd is only available after target open"));
96baa820 8977
23860348 8978 /* Send a NULL command across as an empty command. */
7be570e7
JM
8979 if (command == NULL)
8980 command = "";
8981
23860348 8982 /* The query prefix. */
2e9f7625
DJ
8983 strcpy (rs->buf, "qRcmd,");
8984 p = strchr (rs->buf, '\0');
96baa820 8985
3e43a32a
MS
8986 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
8987 > get_remote_packet_size ())
8a3fe4f8 8988 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 8989
23860348 8990 /* Encode the actual command. */
9f1b45b0 8991 bin2hex ((gdb_byte *) command, p, strlen (command));
96baa820 8992
6d820c5c 8993 if (putpkt (rs->buf) < 0)
8a3fe4f8 8994 error (_("Communication problem with target."));
96baa820
JM
8995
8996 /* get/display the response */
8997 while (1)
8998 {
2e9f7625
DJ
8999 char *buf;
9000
00bf0b85 9001 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 9002 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 9003 rs->buf[0] = '\0';
5b37825d
PW
9004 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9005 {
9006 /* Timeout. Continue to (try to) read responses.
9007 This is better than stopping with an error, assuming the stub
9008 is still executing the (long) monitor command.
9009 If needed, the user can interrupt gdb using C-c, obtaining
9010 an effect similar to stop on timeout. */
9011 continue;
9012 }
2e9f7625 9013 buf = rs->buf;
96baa820 9014 if (buf[0] == '\0')
8a3fe4f8 9015 error (_("Target does not support this command."));
96baa820
JM
9016 if (buf[0] == 'O' && buf[1] != 'K')
9017 {
23860348 9018 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
9019 continue;
9020 }
9021 if (strcmp (buf, "OK") == 0)
9022 break;
7be570e7
JM
9023 if (strlen (buf) == 3 && buf[0] == 'E'
9024 && isdigit (buf[1]) && isdigit (buf[2]))
9025 {
8a3fe4f8 9026 error (_("Protocol error with Rcmd"));
7be570e7 9027 }
96baa820
JM
9028 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9029 {
9030 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 9031
96baa820
JM
9032 fputc_unfiltered (c, outbuf);
9033 }
9034 break;
9035 }
9036}
9037
fd79ecee
DJ
9038static VEC(mem_region_s) *
9039remote_memory_map (struct target_ops *ops)
9040{
9041 VEC(mem_region_s) *result = NULL;
9042 char *text = target_read_stralloc (&current_target,
9043 TARGET_OBJECT_MEMORY_MAP, NULL);
9044
9045 if (text)
9046 {
9047 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 9048
fd79ecee
DJ
9049 result = parse_memory_map (text);
9050 do_cleanups (back_to);
9051 }
9052
9053 return result;
9054}
9055
c906108c 9056static void
fba45db2 9057packet_command (char *args, int from_tty)
c906108c 9058{
d01949b6 9059 struct remote_state *rs = get_remote_state ();
c906108c 9060
5d93a237 9061 if (!rs->remote_desc)
8a3fe4f8 9062 error (_("command can only be used with remote target"));
c906108c 9063
c5aa993b 9064 if (!args)
8a3fe4f8 9065 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
9066
9067 puts_filtered ("sending: ");
9068 print_packet (args);
9069 puts_filtered ("\n");
9070 putpkt (args);
9071
6d820c5c 9072 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 9073 puts_filtered ("received: ");
6d820c5c 9074 print_packet (rs->buf);
c906108c
SS
9075 puts_filtered ("\n");
9076}
9077
9078#if 0
23860348 9079/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 9080
a14ed312 9081static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 9082
a14ed312 9083static void threadset_test_cmd (char *cmd, int tty);
c906108c 9084
a14ed312 9085static void threadalive_test (char *cmd, int tty);
c906108c 9086
a14ed312 9087static void threadlist_test_cmd (char *cmd, int tty);
c906108c 9088
23860348 9089int get_and_display_threadinfo (threadref *ref);
c906108c 9090
a14ed312 9091static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 9092
23860348 9093static int thread_display_step (threadref *ref, void *context);
c906108c 9094
a14ed312 9095static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 9096
a14ed312 9097static void init_remote_threadtests (void);
c906108c 9098
23860348 9099#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
9100
9101static void
fba45db2 9102threadset_test_cmd (char *cmd, int tty)
c906108c
SS
9103{
9104 int sample_thread = SAMPLE_THREAD;
9105
a3f17187 9106 printf_filtered (_("Remote threadset test\n"));
79d7f229 9107 set_general_thread (sample_thread);
c906108c
SS
9108}
9109
9110
9111static void
fba45db2 9112threadalive_test (char *cmd, int tty)
c906108c
SS
9113{
9114 int sample_thread = SAMPLE_THREAD;
79d7f229
PA
9115 int pid = ptid_get_pid (inferior_ptid);
9116 ptid_t ptid = ptid_build (pid, 0, sample_thread);
c906108c 9117
79d7f229 9118 if (remote_thread_alive (ptid))
c906108c
SS
9119 printf_filtered ("PASS: Thread alive test\n");
9120 else
9121 printf_filtered ("FAIL: Thread alive test\n");
9122}
9123
23860348 9124void output_threadid (char *title, threadref *ref);
c906108c
SS
9125
9126void
fba45db2 9127output_threadid (char *title, threadref *ref)
c906108c
SS
9128{
9129 char hexid[20];
9130
23860348 9131 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
9132 hexid[16] = 0;
9133 printf_filtered ("%s %s\n", title, (&hexid[0]));
9134}
9135
9136static void
fba45db2 9137threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
9138{
9139 int startflag = 1;
9140 threadref nextthread;
9141 int done, result_count;
9142 threadref threadlist[3];
9143
9144 printf_filtered ("Remote Threadlist test\n");
9145 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9146 &result_count, &threadlist[0]))
9147 printf_filtered ("FAIL: threadlist test\n");
9148 else
9149 {
9150 threadref *scan = threadlist;
9151 threadref *limit = scan + result_count;
9152
9153 while (scan < limit)
9154 output_threadid (" thread ", scan++);
9155 }
9156}
9157
9158void
fba45db2 9159display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
9160{
9161 output_threadid ("Threadid: ", &info->threadid);
9162 printf_filtered ("Name: %s\n ", info->shortname);
9163 printf_filtered ("State: %s\n", info->display);
9164 printf_filtered ("other: %s\n\n", info->more_display);
9165}
9166
9167int
fba45db2 9168get_and_display_threadinfo (threadref *ref)
c906108c
SS
9169{
9170 int result;
9171 int set;
9172 struct gdb_ext_thread_info threadinfo;
9173
9174 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9175 | TAG_MOREDISPLAY | TAG_DISPLAY;
9176 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9177 display_thread_info (&threadinfo);
9178 return result;
9179}
9180
9181static void
fba45db2 9182threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
9183{
9184 int athread = SAMPLE_THREAD;
9185 threadref thread;
9186 int set;
9187
9188 int_to_threadref (&thread, athread);
9189 printf_filtered ("Remote Threadinfo test\n");
9190 if (!get_and_display_threadinfo (&thread))
9191 printf_filtered ("FAIL cannot get thread info\n");
9192}
9193
9194static int
fba45db2 9195thread_display_step (threadref *ref, void *context)
c906108c
SS
9196{
9197 /* output_threadid(" threadstep ",ref); *//* simple test */
9198 return get_and_display_threadinfo (ref);
9199}
9200
9201static void
fba45db2 9202threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
9203{
9204 printf_filtered ("Remote Threadlist update test\n");
9205 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9206}
9207
9208static void
9209init_remote_threadtests (void)
9210{
3e43a32a
MS
9211 add_com ("tlist", class_obscure, threadlist_test_cmd,
9212 _("Fetch and print the remote list of "
9213 "thread identifiers, one pkt only"));
c906108c 9214 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 9215 _("Fetch and display info about one thread"));
c906108c 9216 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 9217 _("Test setting to a different thread"));
c906108c 9218 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 9219 _("Iterate through updating all remote thread info"));
c906108c 9220 add_com ("talive", class_obscure, threadalive_test,
1bedd215 9221 _(" Remote thread alive test "));
c906108c
SS
9222}
9223
9224#endif /* 0 */
9225
f3fb8c85
MS
9226/* Convert a thread ID to a string. Returns the string in a static
9227 buffer. */
9228
9229static char *
117de6a9 9230remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 9231{
79d7f229 9232 static char buf[64];
82f73884 9233 struct remote_state *rs = get_remote_state ();
f3fb8c85 9234
7cee1e54
PA
9235 if (ptid_equal (ptid, null_ptid))
9236 return normal_pid_to_str (ptid);
9237 else if (ptid_is_pid (ptid))
ecd0ada5
PA
9238 {
9239 /* Printing an inferior target id. */
9240
9241 /* When multi-process extensions are off, there's no way in the
9242 remote protocol to know the remote process id, if there's any
9243 at all. There's one exception --- when we're connected with
9244 target extended-remote, and we manually attached to a process
9245 with "attach PID". We don't record anywhere a flag that
9246 allows us to distinguish that case from the case of
9247 connecting with extended-remote and the stub already being
9248 attached to a process, and reporting yes to qAttached, hence
9249 no smart special casing here. */
9250 if (!remote_multi_process_p (rs))
9251 {
9252 xsnprintf (buf, sizeof buf, "Remote target");
9253 return buf;
9254 }
9255
9256 return normal_pid_to_str (ptid);
82f73884 9257 }
ecd0ada5 9258 else
79d7f229 9259 {
ecd0ada5
PA
9260 if (ptid_equal (magic_null_ptid, ptid))
9261 xsnprintf (buf, sizeof buf, "Thread <main>");
901f9912 9262 else if (rs->extended && remote_multi_process_p (rs))
ecd0ada5
PA
9263 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
9264 ptid_get_pid (ptid), ptid_get_tid (ptid));
9265 else
9266 xsnprintf (buf, sizeof buf, "Thread %ld",
9267 ptid_get_tid (ptid));
79d7f229
PA
9268 return buf;
9269 }
f3fb8c85
MS
9270}
9271
38691318
KB
9272/* Get the address of the thread local variable in OBJFILE which is
9273 stored at OFFSET within the thread local storage for thread PTID. */
9274
9275static CORE_ADDR
117de6a9
PA
9276remote_get_thread_local_address (struct target_ops *ops,
9277 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 9278{
444abaca 9279 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
38691318
KB
9280 {
9281 struct remote_state *rs = get_remote_state ();
6d820c5c 9282 char *p = rs->buf;
82f73884 9283 char *endp = rs->buf + get_remote_packet_size ();
571dd617 9284 enum packet_result result;
38691318
KB
9285
9286 strcpy (p, "qGetTLSAddr:");
9287 p += strlen (p);
82f73884 9288 p = write_ptid (p, endp, ptid);
38691318
KB
9289 *p++ = ',';
9290 p += hexnumstr (p, offset);
9291 *p++ = ',';
9292 p += hexnumstr (p, lm);
9293 *p++ = '\0';
9294
6d820c5c
DJ
9295 putpkt (rs->buf);
9296 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
9297 result = packet_ok (rs->buf,
9298 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 9299 if (result == PACKET_OK)
38691318
KB
9300 {
9301 ULONGEST result;
9302
6d820c5c 9303 unpack_varlen_hex (rs->buf, &result);
38691318
KB
9304 return result;
9305 }
571dd617 9306 else if (result == PACKET_UNKNOWN)
109c3e39
AC
9307 throw_error (TLS_GENERIC_ERROR,
9308 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 9309 else
109c3e39
AC
9310 throw_error (TLS_GENERIC_ERROR,
9311 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
9312 }
9313 else
109c3e39
AC
9314 throw_error (TLS_GENERIC_ERROR,
9315 _("TLS not supported or disabled on this target"));
38691318
KB
9316 /* Not reached. */
9317 return 0;
9318}
9319
711e434b
PM
9320/* Provide thread local base, i.e. Thread Information Block address.
9321 Returns 1 if ptid is found and thread_local_base is non zero. */
9322
70221824 9323static int
bd7ae0f5 9324remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b
PM
9325{
9326 if (remote_protocol_packets[PACKET_qGetTIBAddr].support != PACKET_DISABLE)
9327 {
9328 struct remote_state *rs = get_remote_state ();
9329 char *p = rs->buf;
9330 char *endp = rs->buf + get_remote_packet_size ();
9331 enum packet_result result;
9332
9333 strcpy (p, "qGetTIBAddr:");
9334 p += strlen (p);
9335 p = write_ptid (p, endp, ptid);
9336 *p++ = '\0';
9337
9338 putpkt (rs->buf);
9339 getpkt (&rs->buf, &rs->buf_size, 0);
9340 result = packet_ok (rs->buf,
9341 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9342 if (result == PACKET_OK)
9343 {
9344 ULONGEST result;
9345
9346 unpack_varlen_hex (rs->buf, &result);
9347 if (addr)
9348 *addr = (CORE_ADDR) result;
9349 return 1;
9350 }
9351 else if (result == PACKET_UNKNOWN)
9352 error (_("Remote target doesn't support qGetTIBAddr packet"));
9353 else
9354 error (_("Remote target failed to process qGetTIBAddr request"));
9355 }
9356 else
9357 error (_("qGetTIBAddr not supported or disabled on this target"));
9358 /* Not reached. */
9359 return 0;
9360}
9361
29709017
DJ
9362/* Support for inferring a target description based on the current
9363 architecture and the size of a 'g' packet. While the 'g' packet
9364 can have any size (since optional registers can be left off the
9365 end), some sizes are easily recognizable given knowledge of the
9366 approximate architecture. */
9367
9368struct remote_g_packet_guess
9369{
9370 int bytes;
9371 const struct target_desc *tdesc;
9372};
9373typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9374DEF_VEC_O(remote_g_packet_guess_s);
9375
9376struct remote_g_packet_data
9377{
9378 VEC(remote_g_packet_guess_s) *guesses;
9379};
9380
9381static struct gdbarch_data *remote_g_packet_data_handle;
9382
9383static void *
9384remote_g_packet_data_init (struct obstack *obstack)
9385{
9386 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9387}
9388
9389void
9390register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9391 const struct target_desc *tdesc)
9392{
9393 struct remote_g_packet_data *data
9394 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9395 struct remote_g_packet_guess new_guess, *guess;
9396 int ix;
9397
9398 gdb_assert (tdesc != NULL);
9399
9400 for (ix = 0;
9401 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9402 ix++)
9403 if (guess->bytes == bytes)
9404 internal_error (__FILE__, __LINE__,
9b20d036 9405 _("Duplicate g packet description added for size %d"),
29709017
DJ
9406 bytes);
9407
9408 new_guess.bytes = bytes;
9409 new_guess.tdesc = tdesc;
9410 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9411}
9412
d962ef82
DJ
9413/* Return 1 if remote_read_description would do anything on this target
9414 and architecture, 0 otherwise. */
9415
9416static int
9417remote_read_description_p (struct target_ops *target)
9418{
9419 struct remote_g_packet_data *data
f5656ead 9420 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
d962ef82
DJ
9421
9422 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9423 return 1;
9424
9425 return 0;
9426}
9427
29709017
DJ
9428static const struct target_desc *
9429remote_read_description (struct target_ops *target)
9430{
9431 struct remote_g_packet_data *data
f5656ead 9432 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
29709017 9433
d962ef82
DJ
9434 /* Do not try this during initial connection, when we do not know
9435 whether there is a running but stopped thread. */
9436 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
9437 return NULL;
9438
29709017
DJ
9439 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9440 {
9441 struct remote_g_packet_guess *guess;
9442 int ix;
9443 int bytes = send_g_packet ();
9444
9445 for (ix = 0;
9446 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9447 ix++)
9448 if (guess->bytes == bytes)
9449 return guess->tdesc;
9450
9451 /* We discard the g packet. A minor optimization would be to
9452 hold on to it, and fill the register cache once we have selected
9453 an architecture, but it's too tricky to do safely. */
9454 }
9455
9456 return NULL;
9457}
9458
a6b151f1
DJ
9459/* Remote file transfer support. This is host-initiated I/O, not
9460 target-initiated; for target-initiated, see remote-fileio.c. */
9461
9462/* If *LEFT is at least the length of STRING, copy STRING to
9463 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9464 decrease *LEFT. Otherwise raise an error. */
9465
9466static void
9467remote_buffer_add_string (char **buffer, int *left, char *string)
9468{
9469 int len = strlen (string);
9470
9471 if (len > *left)
9472 error (_("Packet too long for target."));
9473
9474 memcpy (*buffer, string, len);
9475 *buffer += len;
9476 *left -= len;
9477
9478 /* NUL-terminate the buffer as a convenience, if there is
9479 room. */
9480 if (*left)
9481 **buffer = '\0';
9482}
9483
9484/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9485 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9486 decrease *LEFT. Otherwise raise an error. */
9487
9488static void
9489remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9490 int len)
9491{
9492 if (2 * len > *left)
9493 error (_("Packet too long for target."));
9494
9495 bin2hex (bytes, *buffer, len);
9496 *buffer += 2 * len;
9497 *left -= 2 * len;
9498
9499 /* NUL-terminate the buffer as a convenience, if there is
9500 room. */
9501 if (*left)
9502 **buffer = '\0';
9503}
9504
9505/* If *LEFT is large enough, convert VALUE to hex and add it to
9506 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9507 decrease *LEFT. Otherwise raise an error. */
9508
9509static void
9510remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9511{
9512 int len = hexnumlen (value);
9513
9514 if (len > *left)
9515 error (_("Packet too long for target."));
9516
9517 hexnumstr (*buffer, value);
9518 *buffer += len;
9519 *left -= len;
9520
9521 /* NUL-terminate the buffer as a convenience, if there is
9522 room. */
9523 if (*left)
9524 **buffer = '\0';
9525}
9526
9527/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9528 value, *REMOTE_ERRNO to the remote error number or zero if none
9529 was included, and *ATTACHMENT to point to the start of the annex
9530 if any. The length of the packet isn't needed here; there may
9531 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9532
9533 Return 0 if the packet could be parsed, -1 if it could not. If
9534 -1 is returned, the other variables may not be initialized. */
9535
9536static int
9537remote_hostio_parse_result (char *buffer, int *retcode,
9538 int *remote_errno, char **attachment)
9539{
9540 char *p, *p2;
9541
9542 *remote_errno = 0;
9543 *attachment = NULL;
9544
9545 if (buffer[0] != 'F')
9546 return -1;
9547
9548 errno = 0;
9549 *retcode = strtol (&buffer[1], &p, 16);
9550 if (errno != 0 || p == &buffer[1])
9551 return -1;
9552
9553 /* Check for ",errno". */
9554 if (*p == ',')
9555 {
9556 errno = 0;
9557 *remote_errno = strtol (p + 1, &p2, 16);
9558 if (errno != 0 || p + 1 == p2)
9559 return -1;
9560 p = p2;
9561 }
9562
9563 /* Check for ";attachment". If there is no attachment, the
9564 packet should end here. */
9565 if (*p == ';')
9566 {
9567 *attachment = p + 1;
9568 return 0;
9569 }
9570 else if (*p == '\0')
9571 return 0;
9572 else
9573 return -1;
9574}
9575
9576/* Send a prepared I/O packet to the target and read its response.
9577 The prepared packet is in the global RS->BUF before this function
9578 is called, and the answer is there when we return.
9579
9580 COMMAND_BYTES is the length of the request to send, which may include
9581 binary data. WHICH_PACKET is the packet configuration to check
9582 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9583 is set to the error number and -1 is returned. Otherwise the value
9584 returned by the function is returned.
9585
9586 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9587 attachment is expected; an error will be reported if there's a
9588 mismatch. If one is found, *ATTACHMENT will be set to point into
9589 the packet buffer and *ATTACHMENT_LEN will be set to the
9590 attachment's length. */
9591
9592static int
9593remote_hostio_send_command (int command_bytes, int which_packet,
9594 int *remote_errno, char **attachment,
9595 int *attachment_len)
9596{
9597 struct remote_state *rs = get_remote_state ();
9598 int ret, bytes_read;
9599 char *attachment_tmp;
9600
5d93a237 9601 if (!rs->remote_desc
f1838a98 9602 || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
a6b151f1
DJ
9603 {
9604 *remote_errno = FILEIO_ENOSYS;
9605 return -1;
9606 }
9607
9608 putpkt_binary (rs->buf, command_bytes);
9609 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9610
9611 /* If it timed out, something is wrong. Don't try to parse the
9612 buffer. */
9613 if (bytes_read < 0)
9614 {
9615 *remote_errno = FILEIO_EINVAL;
9616 return -1;
9617 }
9618
9619 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9620 {
9621 case PACKET_ERROR:
9622 *remote_errno = FILEIO_EINVAL;
9623 return -1;
9624 case PACKET_UNKNOWN:
9625 *remote_errno = FILEIO_ENOSYS;
9626 return -1;
9627 case PACKET_OK:
9628 break;
9629 }
9630
9631 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9632 &attachment_tmp))
9633 {
9634 *remote_errno = FILEIO_EINVAL;
9635 return -1;
9636 }
9637
9638 /* Make sure we saw an attachment if and only if we expected one. */
9639 if ((attachment_tmp == NULL && attachment != NULL)
9640 || (attachment_tmp != NULL && attachment == NULL))
9641 {
9642 *remote_errno = FILEIO_EINVAL;
9643 return -1;
9644 }
9645
9646 /* If an attachment was found, it must point into the packet buffer;
9647 work out how many bytes there were. */
9648 if (attachment_tmp != NULL)
9649 {
9650 *attachment = attachment_tmp;
9651 *attachment_len = bytes_read - (*attachment - rs->buf);
9652 }
9653
9654 return ret;
9655}
9656
9657/* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9658 remote file descriptor, or -1 if an error occurs (and set
9659 *REMOTE_ERRNO). */
9660
9661static int
cd897586
TT
9662remote_hostio_open (struct target_ops *self,
9663 const char *filename, int flags, int mode,
a6b151f1
DJ
9664 int *remote_errno)
9665{
9666 struct remote_state *rs = get_remote_state ();
9667 char *p = rs->buf;
9668 int left = get_remote_packet_size () - 1;
9669
9670 remote_buffer_add_string (&p, &left, "vFile:open:");
9671
9672 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9673 strlen (filename));
9674 remote_buffer_add_string (&p, &left, ",");
9675
9676 remote_buffer_add_int (&p, &left, flags);
9677 remote_buffer_add_string (&p, &left, ",");
9678
9679 remote_buffer_add_int (&p, &left, mode);
9680
9681 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9682 remote_errno, NULL, NULL);
9683}
9684
9685/* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9686 Return the number of bytes written, or -1 if an error occurs (and
9687 set *REMOTE_ERRNO). */
9688
9689static int
0d866f62
TT
9690remote_hostio_pwrite (struct target_ops *self,
9691 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
9692 ULONGEST offset, int *remote_errno)
9693{
9694 struct remote_state *rs = get_remote_state ();
9695 char *p = rs->buf;
9696 int left = get_remote_packet_size ();
9697 int out_len;
9698
9699 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9700
9701 remote_buffer_add_int (&p, &left, fd);
9702 remote_buffer_add_string (&p, &left, ",");
9703
9704 remote_buffer_add_int (&p, &left, offset);
9705 remote_buffer_add_string (&p, &left, ",");
9706
bc20a4af 9707 p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
a6b151f1
DJ
9708 get_remote_packet_size () - (p - rs->buf));
9709
9710 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9711 remote_errno, NULL, NULL);
9712}
9713
9714/* Read up to LEN bytes FD on the remote target into READ_BUF
9715 Return the number of bytes read, or -1 if an error occurs (and
9716 set *REMOTE_ERRNO). */
9717
9718static int
a3be983c
TT
9719remote_hostio_pread (struct target_ops *self,
9720 int fd, gdb_byte *read_buf, int len,
a6b151f1
DJ
9721 ULONGEST offset, int *remote_errno)
9722{
9723 struct remote_state *rs = get_remote_state ();
9724 char *p = rs->buf;
9725 char *attachment;
9726 int left = get_remote_packet_size ();
9727 int ret, attachment_len;
9728 int read_len;
9729
9730 remote_buffer_add_string (&p, &left, "vFile:pread:");
9731
9732 remote_buffer_add_int (&p, &left, fd);
9733 remote_buffer_add_string (&p, &left, ",");
9734
9735 remote_buffer_add_int (&p, &left, len);
9736 remote_buffer_add_string (&p, &left, ",");
9737
9738 remote_buffer_add_int (&p, &left, offset);
9739
9740 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9741 remote_errno, &attachment,
9742 &attachment_len);
9743
9744 if (ret < 0)
9745 return ret;
9746
bc20a4af 9747 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
9748 read_buf, len);
9749 if (read_len != ret)
9750 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9751
9752 return ret;
9753}
9754
9755/* Close FD on the remote target. Return 0, or -1 if an error occurs
9756 (and set *REMOTE_ERRNO). */
9757
9758static int
df39ea25 9759remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
9760{
9761 struct remote_state *rs = get_remote_state ();
9762 char *p = rs->buf;
9763 int left = get_remote_packet_size () - 1;
9764
9765 remote_buffer_add_string (&p, &left, "vFile:close:");
9766
9767 remote_buffer_add_int (&p, &left, fd);
9768
9769 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
9770 remote_errno, NULL, NULL);
9771}
9772
9773/* Unlink FILENAME on the remote target. Return 0, or -1 if an error
9774 occurs (and set *REMOTE_ERRNO). */
9775
9776static int
dbbca37d
TT
9777remote_hostio_unlink (struct target_ops *self,
9778 const char *filename, int *remote_errno)
a6b151f1
DJ
9779{
9780 struct remote_state *rs = get_remote_state ();
9781 char *p = rs->buf;
9782 int left = get_remote_packet_size () - 1;
9783
9784 remote_buffer_add_string (&p, &left, "vFile:unlink:");
9785
9786 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9787 strlen (filename));
9788
9789 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
9790 remote_errno, NULL, NULL);
9791}
9792
b9e7b9c3
UW
9793/* Read value of symbolic link FILENAME on the remote target. Return
9794 a null-terminated string allocated via xmalloc, or NULL if an error
9795 occurs (and set *REMOTE_ERRNO). */
9796
9797static char *
fab5aa7c
TT
9798remote_hostio_readlink (struct target_ops *self,
9799 const char *filename, int *remote_errno)
b9e7b9c3
UW
9800{
9801 struct remote_state *rs = get_remote_state ();
9802 char *p = rs->buf;
9803 char *attachment;
9804 int left = get_remote_packet_size ();
9805 int len, attachment_len;
9806 int read_len;
9807 char *ret;
9808
9809 remote_buffer_add_string (&p, &left, "vFile:readlink:");
9810
9811 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9812 strlen (filename));
9813
9814 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
9815 remote_errno, &attachment,
9816 &attachment_len);
9817
9818 if (len < 0)
9819 return NULL;
9820
9821 ret = xmalloc (len + 1);
9822
bc20a4af
PA
9823 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9824 (gdb_byte *) ret, len);
b9e7b9c3
UW
9825 if (read_len != len)
9826 error (_("Readlink returned %d, but %d bytes."), len, read_len);
9827
9828 ret[len] = '\0';
9829 return ret;
9830}
9831
a6b151f1
DJ
9832static int
9833remote_fileio_errno_to_host (int errnum)
9834{
9835 switch (errnum)
9836 {
9837 case FILEIO_EPERM:
9838 return EPERM;
9839 case FILEIO_ENOENT:
9840 return ENOENT;
9841 case FILEIO_EINTR:
9842 return EINTR;
9843 case FILEIO_EIO:
9844 return EIO;
9845 case FILEIO_EBADF:
9846 return EBADF;
9847 case FILEIO_EACCES:
9848 return EACCES;
9849 case FILEIO_EFAULT:
9850 return EFAULT;
9851 case FILEIO_EBUSY:
9852 return EBUSY;
9853 case FILEIO_EEXIST:
9854 return EEXIST;
9855 case FILEIO_ENODEV:
9856 return ENODEV;
9857 case FILEIO_ENOTDIR:
9858 return ENOTDIR;
9859 case FILEIO_EISDIR:
9860 return EISDIR;
9861 case FILEIO_EINVAL:
9862 return EINVAL;
9863 case FILEIO_ENFILE:
9864 return ENFILE;
9865 case FILEIO_EMFILE:
9866 return EMFILE;
9867 case FILEIO_EFBIG:
9868 return EFBIG;
9869 case FILEIO_ENOSPC:
9870 return ENOSPC;
9871 case FILEIO_ESPIPE:
9872 return ESPIPE;
9873 case FILEIO_EROFS:
9874 return EROFS;
9875 case FILEIO_ENOSYS:
9876 return ENOSYS;
9877 case FILEIO_ENAMETOOLONG:
9878 return ENAMETOOLONG;
9879 }
9880 return -1;
9881}
9882
9883static char *
9884remote_hostio_error (int errnum)
9885{
9886 int host_error = remote_fileio_errno_to_host (errnum);
9887
9888 if (host_error == -1)
9889 error (_("Unknown remote I/O error %d"), errnum);
9890 else
9891 error (_("Remote I/O error: %s"), safe_strerror (host_error));
9892}
9893
a6b151f1
DJ
9894static void
9895remote_hostio_close_cleanup (void *opaque)
9896{
9897 int fd = *(int *) opaque;
9898 int remote_errno;
9899
df39ea25 9900 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
9901}
9902
f1838a98
UW
9903
9904static void *
9905remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
9906{
9907 const char *filename = bfd_get_filename (abfd);
9908 int fd, remote_errno;
9909 int *stream;
9910
9911 gdb_assert (remote_filename_p (filename));
9912
cd897586
TT
9913 fd = remote_hostio_open (find_target_at (process_stratum),
9914 filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
f1838a98
UW
9915 if (fd == -1)
9916 {
9917 errno = remote_fileio_errno_to_host (remote_errno);
9918 bfd_set_error (bfd_error_system_call);
9919 return NULL;
9920 }
9921
9922 stream = xmalloc (sizeof (int));
9923 *stream = fd;
9924 return stream;
9925}
9926
9927static int
9928remote_bfd_iovec_close (struct bfd *abfd, void *stream)
9929{
9930 int fd = *(int *)stream;
9931 int remote_errno;
9932
9933 xfree (stream);
9934
9935 /* Ignore errors on close; these may happen if the remote
9936 connection was already torn down. */
df39ea25 9937 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
f1838a98 9938
39ed5604
JK
9939 /* Zero means success. */
9940 return 0;
f1838a98
UW
9941}
9942
9943static file_ptr
9944remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
9945 file_ptr nbytes, file_ptr offset)
9946{
9947 int fd = *(int *)stream;
9948 int remote_errno;
9949 file_ptr pos, bytes;
9950
9951 pos = 0;
9952 while (nbytes > pos)
9953 {
a3be983c
TT
9954 bytes = remote_hostio_pread (find_target_at (process_stratum),
9955 fd, (gdb_byte *) buf + pos, nbytes - pos,
f1838a98
UW
9956 offset + pos, &remote_errno);
9957 if (bytes == 0)
9958 /* Success, but no bytes, means end-of-file. */
9959 break;
9960 if (bytes == -1)
9961 {
9962 errno = remote_fileio_errno_to_host (remote_errno);
9963 bfd_set_error (bfd_error_system_call);
9964 return -1;
9965 }
9966
9967 pos += bytes;
9968 }
9969
9970 return pos;
9971}
9972
9973static int
9974remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
9975{
9976 /* FIXME: We should probably implement remote_hostio_stat. */
9977 sb->st_size = INT_MAX;
9978 return 0;
9979}
9980
9981int
9982remote_filename_p (const char *filename)
9983{
3736004f
PA
9984 return strncmp (filename,
9985 REMOTE_SYSROOT_PREFIX,
9986 sizeof (REMOTE_SYSROOT_PREFIX) - 1) == 0;
f1838a98
UW
9987}
9988
9989bfd *
9990remote_bfd_open (const char *remote_file, const char *target)
9991{
64c31149
TT
9992 bfd *abfd = gdb_bfd_openr_iovec (remote_file, target,
9993 remote_bfd_iovec_open, NULL,
9994 remote_bfd_iovec_pread,
9995 remote_bfd_iovec_close,
9996 remote_bfd_iovec_stat);
9997
a4453b7e 9998 return abfd;
f1838a98
UW
9999}
10000
a6b151f1
DJ
10001void
10002remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10003{
10004 struct cleanup *back_to, *close_cleanup;
10005 int retcode, fd, remote_errno, bytes, io_size;
10006 FILE *file;
10007 gdb_byte *buffer;
10008 int bytes_in_buffer;
10009 int saw_eof;
10010 ULONGEST offset;
5d93a237 10011 struct remote_state *rs = get_remote_state ();
a6b151f1 10012
5d93a237 10013 if (!rs->remote_desc)
a6b151f1
DJ
10014 error (_("command can only be used with remote target"));
10015
614c279d 10016 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
10017 if (file == NULL)
10018 perror_with_name (local_file);
7c8a8b04 10019 back_to = make_cleanup_fclose (file);
a6b151f1 10020
cd897586
TT
10021 fd = remote_hostio_open (find_target_at (process_stratum),
10022 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1
DJ
10023 | FILEIO_O_TRUNC),
10024 0700, &remote_errno);
10025 if (fd == -1)
10026 remote_hostio_error (remote_errno);
10027
10028 /* Send up to this many bytes at once. They won't all fit in the
10029 remote packet limit, so we'll transfer slightly fewer. */
10030 io_size = get_remote_packet_size ();
10031 buffer = xmalloc (io_size);
10032 make_cleanup (xfree, buffer);
10033
10034 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10035
10036 bytes_in_buffer = 0;
10037 saw_eof = 0;
10038 offset = 0;
10039 while (bytes_in_buffer || !saw_eof)
10040 {
10041 if (!saw_eof)
10042 {
3e43a32a
MS
10043 bytes = fread (buffer + bytes_in_buffer, 1,
10044 io_size - bytes_in_buffer,
a6b151f1
DJ
10045 file);
10046 if (bytes == 0)
10047 {
10048 if (ferror (file))
10049 error (_("Error reading %s."), local_file);
10050 else
10051 {
10052 /* EOF. Unless there is something still in the
10053 buffer from the last iteration, we are done. */
10054 saw_eof = 1;
10055 if (bytes_in_buffer == 0)
10056 break;
10057 }
10058 }
10059 }
10060 else
10061 bytes = 0;
10062
10063 bytes += bytes_in_buffer;
10064 bytes_in_buffer = 0;
10065
0d866f62
TT
10066 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
10067 fd, buffer, bytes,
3e43a32a 10068 offset, &remote_errno);
a6b151f1
DJ
10069
10070 if (retcode < 0)
10071 remote_hostio_error (remote_errno);
10072 else if (retcode == 0)
10073 error (_("Remote write of %d bytes returned 0!"), bytes);
10074 else if (retcode < bytes)
10075 {
10076 /* Short write. Save the rest of the read data for the next
10077 write. */
10078 bytes_in_buffer = bytes - retcode;
10079 memmove (buffer, buffer + retcode, bytes_in_buffer);
10080 }
10081
10082 offset += retcode;
10083 }
10084
10085 discard_cleanups (close_cleanup);
df39ea25 10086 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
10087 remote_hostio_error (remote_errno);
10088
10089 if (from_tty)
10090 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10091 do_cleanups (back_to);
10092}
10093
10094void
10095remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10096{
10097 struct cleanup *back_to, *close_cleanup;
cea39f65 10098 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
10099 FILE *file;
10100 gdb_byte *buffer;
10101 ULONGEST offset;
5d93a237 10102 struct remote_state *rs = get_remote_state ();
a6b151f1 10103
5d93a237 10104 if (!rs->remote_desc)
a6b151f1
DJ
10105 error (_("command can only be used with remote target"));
10106
cd897586
TT
10107 fd = remote_hostio_open (find_target_at (process_stratum),
10108 remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
a6b151f1
DJ
10109 if (fd == -1)
10110 remote_hostio_error (remote_errno);
10111
614c279d 10112 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
10113 if (file == NULL)
10114 perror_with_name (local_file);
7c8a8b04 10115 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
10116
10117 /* Send up to this many bytes at once. They won't all fit in the
10118 remote packet limit, so we'll transfer slightly fewer. */
10119 io_size = get_remote_packet_size ();
10120 buffer = xmalloc (io_size);
10121 make_cleanup (xfree, buffer);
10122
10123 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10124
10125 offset = 0;
10126 while (1)
10127 {
a3be983c
TT
10128 bytes = remote_hostio_pread (find_target_at (process_stratum),
10129 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
10130 if (bytes == 0)
10131 /* Success, but no bytes, means end-of-file. */
10132 break;
10133 if (bytes == -1)
10134 remote_hostio_error (remote_errno);
10135
10136 offset += bytes;
10137
10138 bytes = fwrite (buffer, 1, bytes, file);
10139 if (bytes == 0)
10140 perror_with_name (local_file);
10141 }
10142
10143 discard_cleanups (close_cleanup);
df39ea25 10144 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
10145 remote_hostio_error (remote_errno);
10146
10147 if (from_tty)
10148 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10149 do_cleanups (back_to);
10150}
10151
10152void
10153remote_file_delete (const char *remote_file, int from_tty)
10154{
10155 int retcode, remote_errno;
5d93a237 10156 struct remote_state *rs = get_remote_state ();
a6b151f1 10157
5d93a237 10158 if (!rs->remote_desc)
a6b151f1
DJ
10159 error (_("command can only be used with remote target"));
10160
dbbca37d
TT
10161 retcode = remote_hostio_unlink (find_target_at (process_stratum),
10162 remote_file, &remote_errno);
a6b151f1
DJ
10163 if (retcode == -1)
10164 remote_hostio_error (remote_errno);
10165
10166 if (from_tty)
10167 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10168}
10169
10170static void
10171remote_put_command (char *args, int from_tty)
10172{
10173 struct cleanup *back_to;
10174 char **argv;
10175
d1a41061
PP
10176 if (args == NULL)
10177 error_no_arg (_("file to put"));
10178
10179 argv = gdb_buildargv (args);
a6b151f1
DJ
10180 back_to = make_cleanup_freeargv (argv);
10181 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10182 error (_("Invalid parameters to remote put"));
10183
10184 remote_file_put (argv[0], argv[1], from_tty);
10185
10186 do_cleanups (back_to);
10187}
10188
10189static void
10190remote_get_command (char *args, int from_tty)
10191{
10192 struct cleanup *back_to;
10193 char **argv;
10194
d1a41061
PP
10195 if (args == NULL)
10196 error_no_arg (_("file to get"));
10197
10198 argv = gdb_buildargv (args);
a6b151f1
DJ
10199 back_to = make_cleanup_freeargv (argv);
10200 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10201 error (_("Invalid parameters to remote get"));
10202
10203 remote_file_get (argv[0], argv[1], from_tty);
10204
10205 do_cleanups (back_to);
10206}
10207
10208static void
10209remote_delete_command (char *args, int from_tty)
10210{
10211 struct cleanup *back_to;
10212 char **argv;
10213
d1a41061
PP
10214 if (args == NULL)
10215 error_no_arg (_("file to delete"));
10216
10217 argv = gdb_buildargv (args);
a6b151f1
DJ
10218 back_to = make_cleanup_freeargv (argv);
10219 if (argv[0] == NULL || argv[1] != NULL)
10220 error (_("Invalid parameters to remote delete"));
10221
10222 remote_file_delete (argv[0], from_tty);
10223
10224 do_cleanups (back_to);
10225}
10226
10227static void
10228remote_command (char *args, int from_tty)
10229{
10230 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
10231}
10232
b2175913 10233static int
19db3e69 10234remote_can_execute_reverse (struct target_ops *self)
b2175913 10235{
40ab02ce
MS
10236 if (remote_protocol_packets[PACKET_bs].support == PACKET_ENABLE
10237 || remote_protocol_packets[PACKET_bc].support == PACKET_ENABLE)
10238 return 1;
10239 else
10240 return 0;
b2175913
MS
10241}
10242
74531fed 10243static int
2a9a2795 10244remote_supports_non_stop (struct target_ops *self)
74531fed
PA
10245{
10246 return 1;
10247}
10248
03583c20 10249static int
2bfc0540 10250remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
10251{
10252 /* Only supported in extended mode. */
10253 return 0;
10254}
10255
8a305172 10256static int
86ce2668 10257remote_supports_multi_process (struct target_ops *self)
8a305172
PA
10258{
10259 struct remote_state *rs = get_remote_state ();
a744cf53 10260
901f9912
UW
10261 /* Only extended-remote handles being attached to multiple
10262 processes, even though plain remote can use the multi-process
10263 thread id extensions, so that GDB knows the target process's
10264 PID. */
10265 return rs->extended && remote_multi_process_p (rs);
8a305172
PA
10266}
10267
70221824 10268static int
782b2b07
SS
10269remote_supports_cond_tracepoints (void)
10270{
10271 struct remote_state *rs = get_remote_state ();
a744cf53 10272
782b2b07
SS
10273 return rs->cond_tracepoints;
10274}
10275
3788aec7 10276static int
efcc2da7 10277remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7
LM
10278{
10279 struct remote_state *rs = get_remote_state ();
10280
10281 return rs->cond_breakpoints;
10282}
10283
70221824 10284static int
7a697b8d
SS
10285remote_supports_fast_tracepoints (void)
10286{
10287 struct remote_state *rs = get_remote_state ();
a744cf53 10288
7a697b8d
SS
10289 return rs->fast_tracepoints;
10290}
10291
0fb4aa4b
PA
10292static int
10293remote_supports_static_tracepoints (void)
10294{
10295 struct remote_state *rs = get_remote_state ();
10296
10297 return rs->static_tracepoints;
10298}
10299
1e4d1764
YQ
10300static int
10301remote_supports_install_in_trace (void)
10302{
10303 struct remote_state *rs = get_remote_state ();
10304
10305 return rs->install_in_trace;
10306}
10307
d248b706 10308static int
7d178d6a 10309remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706
KY
10310{
10311 struct remote_state *rs = get_remote_state ();
10312
10313 return rs->enable_disable_tracepoints;
10314}
10315
3065dfb6 10316static int
6de37a3a 10317remote_supports_string_tracing (struct target_ops *self)
3065dfb6
SS
10318{
10319 struct remote_state *rs = get_remote_state ();
10320
10321 return rs->string_tracing;
10322}
10323
d3ce09f5 10324static int
78eff0ec 10325remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5
SS
10326{
10327 struct remote_state *rs = get_remote_state ();
10328
10329 return rs->breakpoint_commands;
10330}
10331
35b1e5cc 10332static void
ecae04e1 10333remote_trace_init (struct target_ops *self)
35b1e5cc
SS
10334{
10335 putpkt ("QTinit");
10336 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 10337 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
10338 error (_("Target does not support this command."));
10339}
10340
10341static void free_actions_list (char **actions_list);
10342static void free_actions_list_cleanup_wrapper (void *);
10343static void
10344free_actions_list_cleanup_wrapper (void *al)
10345{
10346 free_actions_list (al);
10347}
10348
10349static void
10350free_actions_list (char **actions_list)
10351{
10352 int ndx;
10353
10354 if (actions_list == 0)
10355 return;
10356
10357 for (ndx = 0; actions_list[ndx]; ndx++)
10358 xfree (actions_list[ndx]);
10359
10360 xfree (actions_list);
10361}
10362
409873ef
SS
10363/* Recursive routine to walk through command list including loops, and
10364 download packets for each command. */
10365
10366static void
10367remote_download_command_source (int num, ULONGEST addr,
10368 struct command_line *cmds)
10369{
10370 struct remote_state *rs = get_remote_state ();
10371 struct command_line *cmd;
10372
10373 for (cmd = cmds; cmd; cmd = cmd->next)
10374 {
0df8b418 10375 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
10376 strcpy (rs->buf, "QTDPsrc:");
10377 encode_source_string (num, addr, "cmd", cmd->line,
10378 rs->buf + strlen (rs->buf),
10379 rs->buf_size - strlen (rs->buf));
10380 putpkt (rs->buf);
10381 remote_get_noisy_reply (&target_buf, &target_buf_size);
10382 if (strcmp (target_buf, "OK"))
10383 warning (_("Target does not support source download."));
10384
10385 if (cmd->control_type == while_control
10386 || cmd->control_type == while_stepping_control)
10387 {
10388 remote_download_command_source (num, addr, *cmd->body_list);
10389
0df8b418 10390 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
10391 strcpy (rs->buf, "QTDPsrc:");
10392 encode_source_string (num, addr, "cmd", "end",
10393 rs->buf + strlen (rs->buf),
10394 rs->buf_size - strlen (rs->buf));
10395 putpkt (rs->buf);
10396 remote_get_noisy_reply (&target_buf, &target_buf_size);
10397 if (strcmp (target_buf, "OK"))
10398 warning (_("Target does not support source download."));
10399 }
10400 }
10401}
10402
35b1e5cc 10403static void
548f7808 10404remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 10405{
bba74b36 10406#define BUF_SIZE 2048
e8ba3115 10407
35b1e5cc 10408 CORE_ADDR tpaddr;
409873ef 10409 char addrbuf[40];
bba74b36 10410 char buf[BUF_SIZE];
35b1e5cc
SS
10411 char **tdp_actions;
10412 char **stepping_actions;
10413 int ndx;
10414 struct cleanup *old_chain = NULL;
10415 struct agent_expr *aexpr;
10416 struct cleanup *aexpr_chain = NULL;
10417 char *pkt;
e8ba3115 10418 struct breakpoint *b = loc->owner;
d9b3f62e 10419 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 10420
dc673c81 10421 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
10422 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10423 tdp_actions);
10424 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10425 stepping_actions);
10426
10427 tpaddr = loc->address;
10428 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
10429 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10430 addrbuf, /* address */
10431 (b->enable_state == bp_enabled ? 'E' : 'D'),
10432 t->step_count, t->pass_count);
e8ba3115
YQ
10433 /* Fast tracepoints are mostly handled by the target, but we can
10434 tell the target how big of an instruction block should be moved
10435 around. */
10436 if (b->type == bp_fast_tracepoint)
10437 {
10438 /* Only test for support at download time; we may not know
10439 target capabilities at definition time. */
10440 if (remote_supports_fast_tracepoints ())
35b1e5cc 10441 {
e8ba3115 10442 int isize;
35b1e5cc 10443
f5656ead 10444 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
e8ba3115 10445 tpaddr, &isize, NULL))
bba74b36
YQ
10446 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10447 isize);
35b1e5cc 10448 else
e8ba3115
YQ
10449 /* If it passed validation at definition but fails now,
10450 something is very wrong. */
10451 internal_error (__FILE__, __LINE__,
10452 _("Fast tracepoint not "
10453 "valid during download"));
35b1e5cc 10454 }
e8ba3115
YQ
10455 else
10456 /* Fast tracepoints are functionally identical to regular
10457 tracepoints, so don't take lack of support as a reason to
10458 give up on the trace run. */
10459 warning (_("Target does not support fast tracepoints, "
10460 "downloading %d as regular tracepoint"), b->number);
10461 }
10462 else if (b->type == bp_static_tracepoint)
10463 {
10464 /* Only test for support at download time; we may not know
10465 target capabilities at definition time. */
10466 if (remote_supports_static_tracepoints ())
0fb4aa4b 10467 {
e8ba3115 10468 struct static_tracepoint_marker marker;
0fb4aa4b 10469
e8ba3115
YQ
10470 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10471 strcat (buf, ":S");
0fb4aa4b 10472 else
e8ba3115 10473 error (_("Static tracepoint not valid during download"));
0fb4aa4b 10474 }
e8ba3115
YQ
10475 else
10476 /* Fast tracepoints are functionally identical to regular
10477 tracepoints, so don't take lack of support as a reason
10478 to give up on the trace run. */
10479 error (_("Target does not support static tracepoints"));
10480 }
10481 /* If the tracepoint has a conditional, make it into an agent
10482 expression and append to the definition. */
10483 if (loc->cond)
10484 {
10485 /* Only test support at download time, we may not know target
10486 capabilities at definition time. */
10487 if (remote_supports_cond_tracepoints ())
35b1e5cc 10488 {
e8ba3115
YQ
10489 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10490 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
10491 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10492 aexpr->len);
e8ba3115
YQ
10493 pkt = buf + strlen (buf);
10494 for (ndx = 0; ndx < aexpr->len; ++ndx)
10495 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10496 *pkt = '\0';
10497 do_cleanups (aexpr_chain);
35b1e5cc 10498 }
e8ba3115
YQ
10499 else
10500 warning (_("Target does not support conditional tracepoints, "
10501 "ignoring tp %d cond"), b->number);
10502 }
35b1e5cc 10503
d9b3f62e 10504 if (b->commands || *default_collect)
e8ba3115
YQ
10505 strcat (buf, "-");
10506 putpkt (buf);
10507 remote_get_noisy_reply (&target_buf, &target_buf_size);
10508 if (strcmp (target_buf, "OK"))
10509 error (_("Target does not support tracepoints."));
35b1e5cc 10510
e8ba3115
YQ
10511 /* do_single_steps (t); */
10512 if (tdp_actions)
10513 {
10514 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 10515 {
e8ba3115 10516 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
10517 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10518 b->number, addrbuf, /* address */
10519 tdp_actions[ndx],
10520 ((tdp_actions[ndx + 1] || stepping_actions)
10521 ? '-' : 0));
e8ba3115
YQ
10522 putpkt (buf);
10523 remote_get_noisy_reply (&target_buf,
10524 &target_buf_size);
10525 if (strcmp (target_buf, "OK"))
10526 error (_("Error on target while setting tracepoints."));
35b1e5cc 10527 }
e8ba3115
YQ
10528 }
10529 if (stepping_actions)
10530 {
10531 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 10532 {
e8ba3115 10533 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
10534 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10535 b->number, addrbuf, /* address */
10536 ((ndx == 0) ? "S" : ""),
10537 stepping_actions[ndx],
10538 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
10539 putpkt (buf);
10540 remote_get_noisy_reply (&target_buf,
10541 &target_buf_size);
10542 if (strcmp (target_buf, "OK"))
10543 error (_("Error on target while setting tracepoints."));
35b1e5cc 10544 }
e8ba3115 10545 }
409873ef 10546
e8ba3115
YQ
10547 if (remote_protocol_packets[PACKET_TracepointSource].support
10548 == PACKET_ENABLE)
10549 {
10550 if (b->addr_string)
409873ef 10551 {
e8ba3115
YQ
10552 strcpy (buf, "QTDPsrc:");
10553 encode_source_string (b->number, loc->address,
10554 "at", b->addr_string, buf + strlen (buf),
10555 2048 - strlen (buf));
409873ef 10556
e8ba3115
YQ
10557 putpkt (buf);
10558 remote_get_noisy_reply (&target_buf, &target_buf_size);
10559 if (strcmp (target_buf, "OK"))
10560 warning (_("Target does not support source download."));
409873ef 10561 }
e8ba3115
YQ
10562 if (b->cond_string)
10563 {
10564 strcpy (buf, "QTDPsrc:");
10565 encode_source_string (b->number, loc->address,
10566 "cond", b->cond_string, buf + strlen (buf),
10567 2048 - strlen (buf));
10568 putpkt (buf);
10569 remote_get_noisy_reply (&target_buf, &target_buf_size);
10570 if (strcmp (target_buf, "OK"))
10571 warning (_("Target does not support source download."));
10572 }
10573 remote_download_command_source (b->number, loc->address,
10574 breakpoint_commands (b));
35b1e5cc 10575 }
e8ba3115
YQ
10576
10577 do_cleanups (old_chain);
35b1e5cc
SS
10578}
10579
1e4d1764 10580static int
a52a8357 10581remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 10582{
1e51243a
PA
10583 struct remote_state *rs = get_remote_state ();
10584 struct trace_status *ts;
10585 int status;
10586
10587 /* Don't try to install tracepoints until we've relocated our
10588 symbols, and fetched and merged the target's tracepoint list with
10589 ours. */
10590 if (rs->starting_up)
10591 return 0;
10592
10593 ts = current_trace_status ();
8bd200f1 10594 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
10595
10596 if (status == -1 || !ts->running_known || !ts->running)
10597 return 0;
10598
10599 /* If we are in a tracing experiment, but remote stub doesn't support
10600 installing tracepoint in trace, we have to return. */
10601 if (!remote_supports_install_in_trace ())
10602 return 0;
10603
10604 return 1;
10605}
10606
10607
35b1e5cc 10608static void
559d2b81
TT
10609remote_download_trace_state_variable (struct target_ops *self,
10610 struct trace_state_variable *tsv)
35b1e5cc
SS
10611{
10612 struct remote_state *rs = get_remote_state ();
00bf0b85 10613 char *p;
35b1e5cc 10614
bba74b36
YQ
10615 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10616 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10617 tsv->builtin);
00bf0b85
SS
10618 p = rs->buf + strlen (rs->buf);
10619 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10620 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 10621 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 10622 *p++ = '\0';
35b1e5cc
SS
10623 putpkt (rs->buf);
10624 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
10625 if (*target_buf == '\0')
10626 error (_("Target does not support this command."));
10627 if (strcmp (target_buf, "OK") != 0)
10628 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
10629}
10630
d248b706 10631static void
46670d57
TT
10632remote_enable_tracepoint (struct target_ops *self,
10633 struct bp_location *location)
d248b706
KY
10634{
10635 struct remote_state *rs = get_remote_state ();
10636 char addr_buf[40];
10637
10638 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
10639 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10640 location->owner->number, addr_buf);
d248b706
KY
10641 putpkt (rs->buf);
10642 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10643 if (*rs->buf == '\0')
10644 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10645 if (strcmp (rs->buf, "OK") != 0)
10646 error (_("Error on target while enabling tracepoint."));
10647}
10648
10649static void
780b049c
TT
10650remote_disable_tracepoint (struct target_ops *self,
10651 struct bp_location *location)
d248b706
KY
10652{
10653 struct remote_state *rs = get_remote_state ();
10654 char addr_buf[40];
10655
10656 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
10657 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10658 location->owner->number, addr_buf);
d248b706
KY
10659 putpkt (rs->buf);
10660 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10661 if (*rs->buf == '\0')
10662 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10663 if (strcmp (rs->buf, "OK") != 0)
10664 error (_("Error on target while disabling tracepoint."));
10665}
10666
35b1e5cc 10667static void
583f9a86 10668remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
10669{
10670 asection *s;
81b9b86e 10671 bfd *abfd = NULL;
35b1e5cc 10672 bfd_size_type size;
608bcef2 10673 bfd_vma vma;
35b1e5cc 10674 int anysecs = 0;
c2fa21f1 10675 int offset = 0;
35b1e5cc
SS
10676
10677 if (!exec_bfd)
10678 return; /* No information to give. */
10679
10680 strcpy (target_buf, "QTro");
9779ab84 10681 offset = strlen (target_buf);
35b1e5cc
SS
10682 for (s = exec_bfd->sections; s; s = s->next)
10683 {
10684 char tmp1[40], tmp2[40];
c2fa21f1 10685 int sec_length;
35b1e5cc
SS
10686
10687 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 10688 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
10689 (s->flags & SEC_READONLY) == 0)
10690 continue;
10691
10692 anysecs = 1;
81b9b86e 10693 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 10694 size = bfd_get_section_size (s);
608bcef2
HZ
10695 sprintf_vma (tmp1, vma);
10696 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
10697 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10698 if (offset + sec_length + 1 > target_buf_size)
10699 {
864ac8a7
HZ
10700 if (remote_protocol_packets[PACKET_qXfer_traceframe_info].support
10701 != PACKET_ENABLE)
10702 warning (_("\
c2fa21f1
HZ
10703Too many sections for read-only sections definition packet."));
10704 break;
10705 }
bba74b36
YQ
10706 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10707 tmp1, tmp2);
c2fa21f1 10708 offset += sec_length;
35b1e5cc
SS
10709 }
10710 if (anysecs)
10711 {
10712 putpkt (target_buf);
10713 getpkt (&target_buf, &target_buf_size, 0);
10714 }
10715}
10716
10717static void
e2d1aae3 10718remote_trace_start (struct target_ops *self)
35b1e5cc
SS
10719{
10720 putpkt ("QTStart");
10721 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
10722 if (*target_buf == '\0')
10723 error (_("Target does not support this command."));
10724 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
10725 error (_("Bogus reply from target: %s"), target_buf);
10726}
10727
10728static int
8bd200f1 10729remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 10730{
953b98d1 10731 /* Initialize it just to avoid a GCC false warning. */
f652de6f 10732 char *p = NULL;
0df8b418 10733 /* FIXME we need to get register block size some other way. */
00bf0b85 10734 extern int trace_regblock_size;
67f41397 10735 volatile struct gdb_exception ex;
bd3eecc3
PA
10736 enum packet_result result;
10737
10738 if (remote_protocol_packets[PACKET_qTStatus].support == PACKET_DISABLE)
10739 return -1;
a744cf53 10740
00bf0b85
SS
10741 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10742
049dc89b
JK
10743 putpkt ("qTStatus");
10744
67f41397
JK
10745 TRY_CATCH (ex, RETURN_MASK_ERROR)
10746 {
10747 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10748 }
10749 if (ex.reason < 0)
10750 {
598d3636
JK
10751 if (ex.error != TARGET_CLOSE_ERROR)
10752 {
10753 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10754 return -1;
10755 }
10756 throw_exception (ex);
67f41397 10757 }
00bf0b85 10758
bd3eecc3
PA
10759 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
10760
00bf0b85 10761 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 10762 if (result == PACKET_UNKNOWN)
00bf0b85 10763 return -1;
35b1e5cc 10764
00bf0b85 10765 /* We're working with a live target. */
f5911ea1 10766 ts->filename = NULL;
00bf0b85 10767
00bf0b85 10768 if (*p++ != 'T')
35b1e5cc
SS
10769 error (_("Bogus trace status reply from target: %s"), target_buf);
10770
84cebc4a
YQ
10771 /* Function 'parse_trace_status' sets default value of each field of
10772 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
10773 parse_trace_status (p, ts);
10774
10775 return ts->running;
35b1e5cc
SS
10776}
10777
70221824 10778static void
db90e85c 10779remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
10780 struct uploaded_tp *utp)
10781{
10782 struct remote_state *rs = get_remote_state ();
f196051f
SS
10783 char *reply;
10784 struct bp_location *loc;
10785 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 10786 size_t size = get_remote_packet_size ();
f196051f
SS
10787
10788 if (tp)
10789 {
10790 tp->base.hit_count = 0;
10791 tp->traceframe_usage = 0;
10792 for (loc = tp->base.loc; loc; loc = loc->next)
10793 {
10794 /* If the tracepoint was never downloaded, don't go asking for
10795 any status. */
10796 if (tp->number_on_target == 0)
10797 continue;
bba74b36
YQ
10798 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
10799 phex_nz (loc->address, 0));
f196051f
SS
10800 putpkt (rs->buf);
10801 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10802 if (reply && *reply)
10803 {
10804 if (*reply == 'V')
10805 parse_tracepoint_status (reply + 1, bp, utp);
10806 }
10807 }
10808 }
10809 else if (utp)
10810 {
10811 utp->hit_count = 0;
10812 utp->traceframe_usage = 0;
bba74b36
YQ
10813 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
10814 phex_nz (utp->addr, 0));
f196051f
SS
10815 putpkt (rs->buf);
10816 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10817 if (reply && *reply)
10818 {
10819 if (*reply == 'V')
10820 parse_tracepoint_status (reply + 1, bp, utp);
10821 }
10822 }
10823}
10824
35b1e5cc 10825static void
74499f1b 10826remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
10827{
10828 putpkt ("QTStop");
10829 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
10830 if (*target_buf == '\0')
10831 error (_("Target does not support this command."));
10832 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
10833 error (_("Bogus reply from target: %s"), target_buf);
10834}
10835
10836static int
bd4c6793
TT
10837remote_trace_find (struct target_ops *self,
10838 enum trace_find_type type, int num,
cc5925ad 10839 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
10840 int *tpp)
10841{
10842 struct remote_state *rs = get_remote_state ();
bba74b36 10843 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
10844 char *p, *reply;
10845 int target_frameno = -1, target_tracept = -1;
10846
e6e4e701
PA
10847 /* Lookups other than by absolute frame number depend on the current
10848 trace selected, so make sure it is correct on the remote end
10849 first. */
10850 if (type != tfind_number)
10851 set_remote_traceframe ();
10852
35b1e5cc
SS
10853 p = rs->buf;
10854 strcpy (p, "QTFrame:");
10855 p = strchr (p, '\0');
10856 switch (type)
10857 {
10858 case tfind_number:
bba74b36 10859 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
10860 break;
10861 case tfind_pc:
bba74b36 10862 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
10863 break;
10864 case tfind_tp:
bba74b36 10865 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
10866 break;
10867 case tfind_range:
bba74b36
YQ
10868 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
10869 phex_nz (addr2, 0));
35b1e5cc
SS
10870 break;
10871 case tfind_outside:
bba74b36
YQ
10872 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
10873 phex_nz (addr2, 0));
35b1e5cc
SS
10874 break;
10875 default:
9b20d036 10876 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
10877 }
10878
10879 putpkt (rs->buf);
2f65bcb7 10880 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
10881 if (*reply == '\0')
10882 error (_("Target does not support this command."));
35b1e5cc
SS
10883
10884 while (reply && *reply)
10885 switch (*reply)
10886 {
10887 case 'F':
f197e0f1
VP
10888 p = ++reply;
10889 target_frameno = (int) strtol (p, &reply, 16);
10890 if (reply == p)
10891 error (_("Unable to parse trace frame number"));
e6e4e701
PA
10892 /* Don't update our remote traceframe number cache on failure
10893 to select a remote traceframe. */
f197e0f1
VP
10894 if (target_frameno == -1)
10895 return -1;
35b1e5cc
SS
10896 break;
10897 case 'T':
f197e0f1
VP
10898 p = ++reply;
10899 target_tracept = (int) strtol (p, &reply, 16);
10900 if (reply == p)
10901 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
10902 break;
10903 case 'O': /* "OK"? */
10904 if (reply[1] == 'K' && reply[2] == '\0')
10905 reply += 2;
10906 else
10907 error (_("Bogus reply from target: %s"), reply);
10908 break;
10909 default:
10910 error (_("Bogus reply from target: %s"), reply);
10911 }
10912 if (tpp)
10913 *tpp = target_tracept;
e6e4e701 10914
262e1174 10915 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
10916 return target_frameno;
10917}
10918
10919static int
4011015b
TT
10920remote_get_trace_state_variable_value (struct target_ops *self,
10921 int tsvnum, LONGEST *val)
35b1e5cc
SS
10922{
10923 struct remote_state *rs = get_remote_state ();
10924 char *reply;
10925 ULONGEST uval;
10926
e6e4e701
PA
10927 set_remote_traceframe ();
10928
bba74b36 10929 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
10930 putpkt (rs->buf);
10931 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10932 if (reply && *reply)
10933 {
10934 if (*reply == 'V')
10935 {
10936 unpack_varlen_hex (reply + 1, &uval);
10937 *val = (LONGEST) uval;
10938 return 1;
10939 }
10940 }
10941 return 0;
10942}
10943
00bf0b85 10944static int
dc3decaf 10945remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
10946{
10947 struct remote_state *rs = get_remote_state ();
10948 char *p, *reply;
10949
10950 p = rs->buf;
10951 strcpy (p, "QTSave:");
10952 p += strlen (p);
10953 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
10954 error (_("Remote file name too long for trace save packet"));
9f1b45b0 10955 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
10956 *p++ = '\0';
10957 putpkt (rs->buf);
ad91cd99 10958 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 10959 if (*reply == '\0')
ad91cd99
PA
10960 error (_("Target does not support this command."));
10961 if (strcmp (reply, "OK") != 0)
10962 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
10963 return 0;
10964}
10965
10966/* This is basically a memory transfer, but needs to be its own packet
10967 because we don't know how the target actually organizes its trace
10968 memory, plus we want to be able to ask for as much as possible, but
10969 not be unhappy if we don't get as much as we ask for. */
10970
10971static LONGEST
88ee6f45
TT
10972remote_get_raw_trace_data (struct target_ops *self,
10973 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
10974{
10975 struct remote_state *rs = get_remote_state ();
10976 char *reply;
10977 char *p;
10978 int rslt;
10979
10980 p = rs->buf;
10981 strcpy (p, "qTBuffer:");
10982 p += strlen (p);
10983 p += hexnumstr (p, offset);
10984 *p++ = ',';
10985 p += hexnumstr (p, len);
10986 *p++ = '\0';
10987
10988 putpkt (rs->buf);
10989 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10990 if (reply && *reply)
10991 {
10992 /* 'l' by itself means we're at the end of the buffer and
10993 there is nothing more to get. */
10994 if (*reply == 'l')
10995 return 0;
10996
10997 /* Convert the reply into binary. Limit the number of bytes to
10998 convert according to our passed-in buffer size, rather than
10999 what was returned in the packet; if the target is
11000 unexpectedly generous and gives us a bigger reply than we
11001 asked for, we don't want to crash. */
11002 rslt = hex2bin (target_buf, buf, len);
11003 return rslt;
11004 }
11005
11006 /* Something went wrong, flag as an error. */
11007 return -1;
11008}
11009
35b1e5cc 11010static void
37b25738 11011remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
11012{
11013 struct remote_state *rs = get_remote_state ();
11014
33da3f1c
SS
11015 if (rs->disconnected_tracing)
11016 {
ad91cd99
PA
11017 char *reply;
11018
bba74b36 11019 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 11020 putpkt (rs->buf);
ad91cd99
PA
11021 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11022 if (*reply == '\0')
33da3f1c 11023 error (_("Target does not support this command."));
ad91cd99
PA
11024 if (strcmp (reply, "OK") != 0)
11025 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
11026 }
11027 else if (val)
11028 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
11029}
11030
dc146f7c
VP
11031static int
11032remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11033{
11034 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 11035
dc146f7c
VP
11036 if (info && info->private)
11037 return info->private->core;
11038 return -1;
11039}
11040
4daf5ac0 11041static void
736d5b1f 11042remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
11043{
11044 struct remote_state *rs = get_remote_state ();
ad91cd99 11045 char *reply;
4daf5ac0 11046
bba74b36 11047 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 11048 putpkt (rs->buf);
ad91cd99
PA
11049 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11050 if (*reply == '\0')
4daf5ac0 11051 error (_("Target does not support this command."));
ad91cd99
PA
11052 if (strcmp (reply, "OK") != 0)
11053 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
11054}
11055
b3b9301e 11056static struct traceframe_info *
a893e81f 11057remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
11058{
11059 char *text;
11060
6c177e28
YQ
11061 /* If current traceframe is not selected, don't bother the remote
11062 stub. */
11063 if (get_traceframe_number () < 0)
11064 return NULL;
11065
b3b9301e
PA
11066 text = target_read_stralloc (&current_target,
11067 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11068 if (text != NULL)
11069 {
11070 struct traceframe_info *info;
11071 struct cleanup *back_to = make_cleanup (xfree, text);
11072
11073 info = parse_traceframe_info (text);
11074 do_cleanups (back_to);
11075 return info;
11076 }
11077
11078 return NULL;
11079}
11080
405f8e94
SS
11081/* Handle the qTMinFTPILen packet. Returns the minimum length of
11082 instruction on which a fast tracepoint may be placed. Returns -1
11083 if the packet is not supported, and 0 if the minimum instruction
11084 length is unknown. */
11085
11086static int
0e67620a 11087remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
11088{
11089 struct remote_state *rs = get_remote_state ();
11090 char *reply;
11091
e886a173
PA
11092 /* If we're not debugging a process yet, the IPA can't be
11093 loaded. */
11094 if (!target_has_execution)
11095 return 0;
11096
11097 /* Make sure the remote is pointing at the right process. */
11098 set_general_process ();
11099
bba74b36 11100 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
11101 putpkt (rs->buf);
11102 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11103 if (*reply == '\0')
11104 return -1;
11105 else
11106 {
11107 ULONGEST min_insn_len;
11108
11109 unpack_varlen_hex (reply, &min_insn_len);
11110
11111 return (int) min_insn_len;
11112 }
11113}
11114
f6f899bf 11115static void
4da384be 11116remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 11117{
90585175
HAQ
11118 if (remote_protocol_packets[PACKET_QTBuffer_size].support
11119 != PACKET_DISABLE)
f6f899bf
HAQ
11120 {
11121 struct remote_state *rs = get_remote_state ();
11122 char *buf = rs->buf;
11123 char *endbuf = rs->buf + get_remote_packet_size ();
11124 enum packet_result result;
11125
11126 gdb_assert (val >= 0 || val == -1);
11127 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11128 /* Send -1 as literal "-1" to avoid host size dependency. */
11129 if (val < 0)
11130 {
11131 *buf++ = '-';
11132 buf += hexnumstr (buf, (ULONGEST) -val);
11133 }
11134 else
11135 buf += hexnumstr (buf, (ULONGEST) val);
11136
11137 putpkt (rs->buf);
11138 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11139 result = packet_ok (rs->buf,
11140 &remote_protocol_packets[PACKET_QTBuffer_size]);
11141
11142 if (result != PACKET_OK)
11143 warning (_("Bogus reply from target: %s"), rs->buf);
11144 }
11145}
11146
f196051f 11147static int
d9e68a2c
TT
11148remote_set_trace_notes (struct target_ops *self,
11149 const char *user, const char *notes,
ca623f82 11150 const char *stop_notes)
f196051f
SS
11151{
11152 struct remote_state *rs = get_remote_state ();
11153 char *reply;
11154 char *buf = rs->buf;
11155 char *endbuf = rs->buf + get_remote_packet_size ();
11156 int nbytes;
11157
11158 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11159 if (user)
11160 {
11161 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 11162 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
11163 buf += 2 * nbytes;
11164 *buf++ = ';';
11165 }
11166 if (notes)
11167 {
11168 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 11169 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
11170 buf += 2 * nbytes;
11171 *buf++ = ';';
11172 }
11173 if (stop_notes)
11174 {
11175 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 11176 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
11177 buf += 2 * nbytes;
11178 *buf++ = ';';
11179 }
11180 /* Ensure the buffer is terminated. */
11181 *buf = '\0';
11182
11183 putpkt (rs->buf);
11184 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11185 if (*reply == '\0')
11186 return 0;
11187
11188 if (strcmp (reply, "OK") != 0)
11189 error (_("Bogus reply from target: %s"), reply);
11190
11191 return 1;
11192}
11193
d1feda86
YQ
11194static int
11195remote_use_agent (int use)
11196{
11197 if (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE)
11198 {
11199 struct remote_state *rs = get_remote_state ();
11200
11201 /* If the stub supports QAgent. */
bba74b36 11202 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
11203 putpkt (rs->buf);
11204 getpkt (&rs->buf, &rs->buf_size, 0);
11205
11206 if (strcmp (rs->buf, "OK") == 0)
11207 {
11208 use_agent = use;
11209 return 1;
11210 }
11211 }
11212
11213 return 0;
11214}
11215
11216static int
11217remote_can_use_agent (void)
11218{
11219 return (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE);
11220}
11221
9accd112
MM
11222struct btrace_target_info
11223{
11224 /* The ptid of the traced thread. */
11225 ptid_t ptid;
11226};
11227
11228/* Check whether the target supports branch tracing. */
11229
11230static int
46917d26 11231remote_supports_btrace (struct target_ops *self)
9accd112
MM
11232{
11233 if (remote_protocol_packets[PACKET_Qbtrace_off].support != PACKET_ENABLE)
11234 return 0;
11235 if (remote_protocol_packets[PACKET_Qbtrace_bts].support != PACKET_ENABLE)
11236 return 0;
11237 if (remote_protocol_packets[PACKET_qXfer_btrace].support != PACKET_ENABLE)
11238 return 0;
11239
11240 return 1;
11241}
11242
11243/* Enable branch tracing. */
11244
11245static struct btrace_target_info *
11246remote_enable_btrace (ptid_t ptid)
11247{
11248 struct btrace_target_info *tinfo = NULL;
11249 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11250 struct remote_state *rs = get_remote_state ();
11251 char *buf = rs->buf;
11252 char *endbuf = rs->buf + get_remote_packet_size ();
11253
11254 if (packet->support != PACKET_ENABLE)
11255 error (_("Target does not support branch tracing."));
11256
11257 set_general_thread (ptid);
11258
11259 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11260 putpkt (rs->buf);
11261 getpkt (&rs->buf, &rs->buf_size, 0);
11262
11263 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11264 {
11265 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11266 error (_("Could not enable branch tracing for %s: %s"),
11267 target_pid_to_str (ptid), rs->buf + 2);
11268 else
11269 error (_("Could not enable branch tracing for %s."),
11270 target_pid_to_str (ptid));
11271 }
11272
11273 tinfo = xzalloc (sizeof (*tinfo));
11274 tinfo->ptid = ptid;
11275
11276 return tinfo;
11277}
11278
11279/* Disable branch tracing. */
11280
11281static void
11282remote_disable_btrace (struct btrace_target_info *tinfo)
11283{
11284 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11285 struct remote_state *rs = get_remote_state ();
11286 char *buf = rs->buf;
11287 char *endbuf = rs->buf + get_remote_packet_size ();
11288
11289 if (packet->support != PACKET_ENABLE)
11290 error (_("Target does not support branch tracing."));
11291
11292 set_general_thread (tinfo->ptid);
11293
11294 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11295 putpkt (rs->buf);
11296 getpkt (&rs->buf, &rs->buf_size, 0);
11297
11298 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11299 {
11300 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11301 error (_("Could not disable branch tracing for %s: %s"),
11302 target_pid_to_str (tinfo->ptid), rs->buf + 2);
11303 else
11304 error (_("Could not disable branch tracing for %s."),
11305 target_pid_to_str (tinfo->ptid));
11306 }
11307
11308 xfree (tinfo);
11309}
11310
11311/* Teardown branch tracing. */
11312
11313static void
11314remote_teardown_btrace (struct btrace_target_info *tinfo)
11315{
11316 /* We must not talk to the target during teardown. */
11317 xfree (tinfo);
11318}
11319
11320/* Read the branch trace. */
11321
969c39fb
MM
11322static enum btrace_error
11323remote_read_btrace (VEC (btrace_block_s) **btrace,
11324 struct btrace_target_info *tinfo,
9accd112
MM
11325 enum btrace_read_type type)
11326{
11327 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11328 struct remote_state *rs = get_remote_state ();
969c39fb 11329 struct cleanup *cleanup;
9accd112
MM
11330 const char *annex;
11331 char *xml;
11332
11333 if (packet->support != PACKET_ENABLE)
11334 error (_("Target does not support branch tracing."));
11335
11336#if !defined(HAVE_LIBEXPAT)
11337 error (_("Cannot process branch tracing result. XML parsing not supported."));
11338#endif
11339
11340 switch (type)
11341 {
864089d2 11342 case BTRACE_READ_ALL:
9accd112
MM
11343 annex = "all";
11344 break;
864089d2 11345 case BTRACE_READ_NEW:
9accd112
MM
11346 annex = "new";
11347 break;
969c39fb
MM
11348 case BTRACE_READ_DELTA:
11349 annex = "delta";
11350 break;
9accd112
MM
11351 default:
11352 internal_error (__FILE__, __LINE__,
11353 _("Bad branch tracing read type: %u."),
11354 (unsigned int) type);
11355 }
11356
11357 xml = target_read_stralloc (&current_target,
11358 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
11359 if (xml == NULL)
11360 return BTRACE_ERR_UNKNOWN;
9accd112 11361
969c39fb
MM
11362 cleanup = make_cleanup (xfree, xml);
11363 *btrace = parse_xml_btrace (xml);
11364 do_cleanups (cleanup);
9accd112 11365
969c39fb 11366 return BTRACE_ERR_NONE;
9accd112
MM
11367}
11368
ced63ec0
GB
11369static int
11370remote_augmented_libraries_svr4_read (void)
11371{
11372 struct remote_state *rs = get_remote_state ();
11373
11374 return rs->augmented_libraries_svr4_read;
11375}
11376
9dd130a0
TT
11377/* Implementation of to_load. */
11378
11379static void
71a9f134 11380remote_load (struct target_ops *self, char *name, int from_tty)
9dd130a0
TT
11381{
11382 generic_load (name, from_tty);
11383}
11384
c906108c 11385static void
fba45db2 11386init_remote_ops (void)
c906108c 11387{
c5aa993b 11388 remote_ops.to_shortname = "remote";
c906108c 11389 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 11390 remote_ops.to_doc =
c906108c 11391 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
11392Specify the serial device it is connected to\n\
11393(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
11394 remote_ops.to_open = remote_open;
11395 remote_ops.to_close = remote_close;
c906108c 11396 remote_ops.to_detach = remote_detach;
6ad8ae5c 11397 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 11398 remote_ops.to_resume = remote_resume;
c906108c
SS
11399 remote_ops.to_wait = remote_wait;
11400 remote_ops.to_fetch_registers = remote_fetch_registers;
11401 remote_ops.to_store_registers = remote_store_registers;
11402 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 11403 remote_ops.to_files_info = remote_files_info;
c906108c
SS
11404 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11405 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
3c3bea1c
GS
11406 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11407 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
11408 remote_ops.to_watchpoint_addr_within_range =
11409 remote_watchpoint_addr_within_range;
3c3bea1c
GS
11410 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11411 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11412 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
11413 remote_ops.to_region_ok_for_hw_watchpoint
11414 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
11415 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11416 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 11417 remote_ops.to_kill = remote_kill;
9dd130a0 11418 remote_ops.to_load = remote_load;
c906108c 11419 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 11420 remote_ops.to_pass_signals = remote_pass_signals;
9b224c5e 11421 remote_ops.to_program_signals = remote_program_signals;
c906108c 11422 remote_ops.to_thread_alive = remote_thread_alive;
0f71a2f6 11423 remote_ops.to_find_new_threads = remote_threads_info;
0caabb7e 11424 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 11425 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 11426 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 11427 remote_ops.to_stop = remote_stop;
4b8a223f 11428 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 11429 remote_ops.to_rcmd = remote_rcmd;
49d03eab 11430 remote_ops.to_log_command = serial_log_command;
38691318 11431 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 11432 remote_ops.to_stratum = process_stratum;
c35b1492
PA
11433 remote_ops.to_has_all_memory = default_child_has_all_memory;
11434 remote_ops.to_has_memory = default_child_has_memory;
11435 remote_ops.to_has_stack = default_child_has_stack;
11436 remote_ops.to_has_registers = default_child_has_registers;
11437 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 11438 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 11439 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 11440 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 11441 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
11442 remote_ops.to_flash_erase = remote_flash_erase;
11443 remote_ops.to_flash_done = remote_flash_done;
29709017 11444 remote_ops.to_read_description = remote_read_description;
08388c79 11445 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
11446 remote_ops.to_can_async_p = remote_can_async_p;
11447 remote_ops.to_is_async_p = remote_is_async_p;
11448 remote_ops.to_async = remote_async;
75c99385
PA
11449 remote_ops.to_terminal_inferior = remote_terminal_inferior;
11450 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 11451 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 11452 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
11453 remote_ops.to_supports_disable_randomization
11454 = remote_supports_disable_randomization;
7313baad
UW
11455 remote_ops.to_fileio_open = remote_hostio_open;
11456 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11457 remote_ops.to_fileio_pread = remote_hostio_pread;
11458 remote_ops.to_fileio_close = remote_hostio_close;
11459 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 11460 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 11461 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 11462 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 11463 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 11464 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
11465 remote_ops.to_trace_init = remote_trace_init;
11466 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 11467 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
11468 remote_ops.to_download_trace_state_variable
11469 = remote_download_trace_state_variable;
d248b706
KY
11470 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11471 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
11472 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11473 remote_ops.to_trace_start = remote_trace_start;
11474 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 11475 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
11476 remote_ops.to_trace_stop = remote_trace_stop;
11477 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
11478 remote_ops.to_get_trace_state_variable_value
11479 = remote_get_trace_state_variable_value;
00bf0b85
SS
11480 remote_ops.to_save_trace_data = remote_save_trace_data;
11481 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
11482 remote_ops.to_upload_trace_state_variables
11483 = remote_upload_trace_state_variables;
00bf0b85 11484 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 11485 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 11486 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 11487 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 11488 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 11489 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 11490 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 11491 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 11492 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 11493 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
11494 remote_ops.to_static_tracepoint_marker_at
11495 = remote_static_tracepoint_marker_at;
11496 remote_ops.to_static_tracepoint_markers_by_strid
11497 = remote_static_tracepoint_markers_by_strid;
b3b9301e 11498 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
11499 remote_ops.to_use_agent = remote_use_agent;
11500 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
11501 remote_ops.to_supports_btrace = remote_supports_btrace;
11502 remote_ops.to_enable_btrace = remote_enable_btrace;
11503 remote_ops.to_disable_btrace = remote_disable_btrace;
11504 remote_ops.to_teardown_btrace = remote_teardown_btrace;
11505 remote_ops.to_read_btrace = remote_read_btrace;
ced63ec0
GB
11506 remote_ops.to_augmented_libraries_svr4_read =
11507 remote_augmented_libraries_svr4_read;
c906108c
SS
11508}
11509
11510/* Set up the extended remote vector by making a copy of the standard
11511 remote vector and adding to it. */
11512
11513static void
fba45db2 11514init_extended_remote_ops (void)
c906108c
SS
11515{
11516 extended_remote_ops = remote_ops;
11517
0f71a2f6 11518 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 11519 extended_remote_ops.to_longname =
c906108c 11520 "Extended remote serial target in gdb-specific protocol";
c5aa993b 11521 extended_remote_ops.to_doc =
c906108c 11522 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
11523Specify the serial device it is connected to (e.g. /dev/ttya).";
11524 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
11525 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11526 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
11527 extended_remote_ops.to_detach = extended_remote_detach;
11528 extended_remote_ops.to_attach = extended_remote_attach;
82f73884 11529 extended_remote_ops.to_kill = extended_remote_kill;
03583c20
UW
11530 extended_remote_ops.to_supports_disable_randomization
11531 = extended_remote_supports_disable_randomization;
0f71a2f6
JM
11532}
11533
6426a772 11534static int
6a109b6b 11535remote_can_async_p (struct target_ops *ops)
6426a772 11536{
5d93a237
TT
11537 struct remote_state *rs = get_remote_state ();
11538
c6ebd6cf 11539 if (!target_async_permitted)
75c99385
PA
11540 /* We only enable async when the user specifically asks for it. */
11541 return 0;
11542
23860348 11543 /* We're async whenever the serial device is. */
5d93a237 11544 return serial_can_async_p (rs->remote_desc);
6426a772
JM
11545}
11546
11547static int
6a109b6b 11548remote_is_async_p (struct target_ops *ops)
6426a772 11549{
5d93a237
TT
11550 struct remote_state *rs = get_remote_state ();
11551
c6ebd6cf 11552 if (!target_async_permitted)
75c99385
PA
11553 /* We only enable async when the user specifically asks for it. */
11554 return 0;
11555
23860348 11556 /* We're async whenever the serial device is. */
5d93a237 11557 return serial_is_async_p (rs->remote_desc);
6426a772
JM
11558}
11559
2acceee2
JM
11560/* Pass the SERIAL event on and up to the client. One day this code
11561 will be able to delay notifying the client of an event until the
23860348 11562 point where an entire packet has been received. */
2acceee2 11563
2acceee2
JM
11564static serial_event_ftype remote_async_serial_handler;
11565
6426a772 11566static void
819cc324 11567remote_async_serial_handler (struct serial *scb, void *context)
6426a772 11568{
88b496c3
TT
11569 struct remote_state *rs = context;
11570
2acceee2
JM
11571 /* Don't propogate error information up to the client. Instead let
11572 the client find out about the error by querying the target. */
88b496c3 11573 rs->async_client_callback (INF_REG_EVENT, rs->async_client_context);
2acceee2
JM
11574}
11575
74531fed
PA
11576static void
11577remote_async_inferior_event_handler (gdb_client_data data)
11578{
11579 inferior_event_handler (INF_REG_EVENT, NULL);
11580}
11581
2acceee2 11582static void
6a109b6b
TT
11583remote_async (struct target_ops *ops,
11584 void (*callback) (enum inferior_event_type event_type,
11585 void *context),
11586 void *context)
2acceee2 11587{
5d93a237
TT
11588 struct remote_state *rs = get_remote_state ();
11589
2acceee2
JM
11590 if (callback != NULL)
11591 {
88b496c3
TT
11592 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
11593 rs->async_client_callback = callback;
11594 rs->async_client_context = context;
2acceee2
JM
11595 }
11596 else
5d93a237 11597 serial_async (rs->remote_desc, NULL, NULL);
6426a772
JM
11598}
11599
5a2468f5 11600static void
c2d11a7d 11601set_remote_cmd (char *args, int from_tty)
5a2468f5 11602{
427c3a89 11603 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
5a2468f5
JM
11604}
11605
d471ea57
AC
11606static void
11607show_remote_cmd (char *args, int from_tty)
11608{
37a105a1 11609 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 11610 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
11611 struct cleanup *showlist_chain;
11612 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 11613 struct ui_out *uiout = current_uiout;
37a105a1
DJ
11614
11615 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
11616 for (; list != NULL; list = list->next)
11617 if (strcmp (list->name, "Z-packet") == 0)
11618 continue;
427c3a89
DJ
11619 else if (list->type == not_set_cmd)
11620 /* Alias commands are exactly like the original, except they
11621 don't have the normal type. */
11622 continue;
11623 else
37a105a1
DJ
11624 {
11625 struct cleanup *option_chain
11626 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 11627
37a105a1
DJ
11628 ui_out_field_string (uiout, "name", list->name);
11629 ui_out_text (uiout, ": ");
427c3a89 11630 if (list->type == show_cmd)
5b9afe8a 11631 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
11632 else
11633 cmd_func (list, NULL, from_tty);
37a105a1
DJ
11634 /* Close the tuple. */
11635 do_cleanups (option_chain);
11636 }
427c3a89
DJ
11637
11638 /* Close the tuple. */
11639 do_cleanups (showlist_chain);
d471ea57 11640}
5a2468f5 11641
0f71a2f6 11642
23860348 11643/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
11644static void
11645remote_new_objfile (struct objfile *objfile)
11646{
5d93a237
TT
11647 struct remote_state *rs = get_remote_state ();
11648
11649 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 11650 remote_check_symbols ();
dc8acb97
MS
11651}
11652
00bf0b85
SS
11653/* Pull all the tracepoints defined on the target and create local
11654 data structures representing them. We don't want to create real
11655 tracepoints yet, we don't want to mess up the user's existing
11656 collection. */
11657
11658static int
ab6617cc 11659remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 11660{
00bf0b85
SS
11661 struct remote_state *rs = get_remote_state ();
11662 char *p;
d5551862 11663
00bf0b85
SS
11664 /* Ask for a first packet of tracepoint definition. */
11665 putpkt ("qTfP");
11666 getpkt (&rs->buf, &rs->buf_size, 0);
11667 p = rs->buf;
11668 while (*p && *p != 'l')
d5551862 11669 {
00bf0b85
SS
11670 parse_tracepoint_definition (p, utpp);
11671 /* Ask for another packet of tracepoint definition. */
11672 putpkt ("qTsP");
11673 getpkt (&rs->buf, &rs->buf_size, 0);
11674 p = rs->buf;
d5551862 11675 }
00bf0b85 11676 return 0;
d5551862
SS
11677}
11678
00bf0b85 11679static int
181e3713
TT
11680remote_upload_trace_state_variables (struct target_ops *self,
11681 struct uploaded_tsv **utsvp)
d5551862 11682{
00bf0b85 11683 struct remote_state *rs = get_remote_state ();
d5551862 11684 char *p;
d5551862 11685
00bf0b85
SS
11686 /* Ask for a first packet of variable definition. */
11687 putpkt ("qTfV");
d5551862
SS
11688 getpkt (&rs->buf, &rs->buf_size, 0);
11689 p = rs->buf;
00bf0b85 11690 while (*p && *p != 'l')
d5551862 11691 {
00bf0b85
SS
11692 parse_tsv_definition (p, utsvp);
11693 /* Ask for another packet of variable definition. */
11694 putpkt ("qTsV");
d5551862
SS
11695 getpkt (&rs->buf, &rs->buf_size, 0);
11696 p = rs->buf;
11697 }
00bf0b85 11698 return 0;
d5551862
SS
11699}
11700
c1e36e3e
PA
11701/* The "set/show range-stepping" show hook. */
11702
11703static void
11704show_range_stepping (struct ui_file *file, int from_tty,
11705 struct cmd_list_element *c,
11706 const char *value)
11707{
11708 fprintf_filtered (file,
11709 _("Debugger's willingness to use range stepping "
11710 "is %s.\n"), value);
11711}
11712
11713/* The "set/show range-stepping" set hook. */
11714
11715static void
11716set_range_stepping (char *ignore_args, int from_tty,
11717 struct cmd_list_element *c)
11718{
5d93a237
TT
11719 struct remote_state *rs = get_remote_state ();
11720
c1e36e3e
PA
11721 /* Whene enabling, check whether range stepping is actually
11722 supported by the target, and warn if not. */
11723 if (use_range_stepping)
11724 {
5d93a237 11725 if (rs->remote_desc != NULL)
c1e36e3e 11726 {
c1e36e3e
PA
11727 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
11728 remote_vcont_probe (rs);
11729
11730 if (remote_protocol_packets[PACKET_vCont].support == PACKET_ENABLE
11731 && rs->supports_vCont.r)
11732 return;
11733 }
11734
11735 warning (_("Range stepping is not supported by the current target"));
11736 }
11737}
11738
c906108c 11739void
fba45db2 11740_initialize_remote (void)
c906108c 11741{
ea9c271d 11742 struct remote_state *rs;
9a7071a8 11743 struct cmd_list_element *cmd;
6f937416 11744 const char *cmd_name;
ea9c271d 11745
0f71a2f6 11746 /* architecture specific data */
2bc416ba 11747 remote_gdbarch_data_handle =
23860348 11748 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
11749 remote_g_packet_data_handle =
11750 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 11751
ea9c271d
DJ
11752 /* Initialize the per-target state. At the moment there is only one
11753 of these, not one per target. Only one target is active at a
cf792862
TT
11754 time. */
11755 remote_state = new_remote_state ();
ea9c271d 11756
c906108c
SS
11757 init_remote_ops ();
11758 add_target (&remote_ops);
11759
11760 init_extended_remote_ops ();
11761 add_target (&extended_remote_ops);
cce74817 11762
dc8acb97 11763 /* Hook into new objfile notification. */
06d3b283 11764 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
11765 /* We're no longer interested in notification events of an inferior
11766 when it exits. */
11767 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 11768
b803fb0f 11769 /* Set up signal handlers. */
934b9bac 11770 async_sigint_remote_token =
b803fb0f 11771 create_async_signal_handler (async_remote_interrupt, NULL);
934b9bac 11772 async_sigint_remote_twice_token =
6d549500 11773 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 11774
c906108c
SS
11775#if 0
11776 init_remote_threadtests ();
11777#endif
11778
722247f1 11779 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 11780 /* set/show remote ... */
d471ea57 11781
1bedd215 11782 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
11783Remote protocol specific variables\n\
11784Configure various remote-protocol specific variables such as\n\
1bedd215 11785the packets being used"),
cff3e48b 11786 &remote_set_cmdlist, "set remote ",
23860348 11787 0 /* allow-unknown */, &setlist);
1bedd215 11788 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
11789Remote protocol specific variables\n\
11790Configure various remote-protocol specific variables such as\n\
1bedd215 11791the packets being used"),
cff3e48b 11792 &remote_show_cmdlist, "show remote ",
23860348 11793 0 /* allow-unknown */, &showlist);
5a2468f5 11794
1a966eab
AC
11795 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
11796Compare section data on target to the exec file.\n\
11797Argument is a single section name (default: all loaded sections)."),
c906108c
SS
11798 &cmdlist);
11799
1a966eab
AC
11800 add_cmd ("packet", class_maintenance, packet_command, _("\
11801Send an arbitrary packet to a remote target.\n\
c906108c
SS
11802 maintenance packet TEXT\n\
11803If GDB is talking to an inferior via the GDB serial protocol, then\n\
11804this command sends the string TEXT to the inferior, and displays the\n\
11805response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 11806terminating `#' character and checksum."),
c906108c
SS
11807 &maintenancelist);
11808
7915a72c
AC
11809 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
11810Set whether to send break if interrupted."), _("\
11811Show whether to send break if interrupted."), _("\
11812If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 11813 set_remotebreak, show_remotebreak,
e707bbc2 11814 &setlist, &showlist);
9a7071a8
JB
11815 cmd_name = "remotebreak";
11816 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
11817 deprecate_cmd (cmd, "set remote interrupt-sequence");
11818 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
11819 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
11820 deprecate_cmd (cmd, "show remote interrupt-sequence");
11821
11822 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
11823 interrupt_sequence_modes, &interrupt_sequence_mode,
11824 _("\
9a7071a8
JB
11825Set interrupt sequence to remote target."), _("\
11826Show interrupt sequence to remote target."), _("\
11827Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
11828 NULL, show_interrupt_sequence,
11829 &remote_set_cmdlist,
11830 &remote_show_cmdlist);
11831
11832 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
11833 &interrupt_on_connect, _("\
11834Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11835Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11836If set, interrupt sequence is sent to remote target."),
11837 NULL, NULL,
11838 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 11839
23860348 11840 /* Install commands for configuring memory read/write packets. */
11cf8741 11841
1a966eab
AC
11842 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
11843Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 11844 &setlist);
1a966eab
AC
11845 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
11846Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
11847 &showlist);
11848 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
11849 set_memory_write_packet_size, _("\
11850Set the maximum number of bytes per memory-write packet.\n\
11851Specify the number of bytes in a packet or 0 (zero) for the\n\
11852default packet size. The actual limit is further reduced\n\
11853dependent on the target. Specify ``fixed'' to disable the\n\
11854further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
11855 &remote_set_cmdlist);
11856 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
11857 set_memory_read_packet_size, _("\
11858Set the maximum number of bytes per memory-read packet.\n\
11859Specify the number of bytes in a packet or 0 (zero) for the\n\
11860default packet size. The actual limit is further reduced\n\
11861dependent on the target. Specify ``fixed'' to disable the\n\
11862further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
11863 &remote_set_cmdlist);
11864 add_cmd ("memory-write-packet-size", no_class,
11865 show_memory_write_packet_size,
1a966eab 11866 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
11867 &remote_show_cmdlist);
11868 add_cmd ("memory-read-packet-size", no_class,
11869 show_memory_read_packet_size,
1a966eab 11870 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 11871 &remote_show_cmdlist);
c906108c 11872
b3f42336 11873 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
11874 &remote_hw_watchpoint_limit, _("\
11875Set the maximum number of target hardware watchpoints."), _("\
11876Show the maximum number of target hardware watchpoints."), _("\
11877Specify a negative limit for unlimited."),
3e43a32a
MS
11878 NULL, NULL, /* FIXME: i18n: The maximum
11879 number of target hardware
11880 watchpoints is %s. */
b3f42336 11881 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
11882 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
11883 &remote_hw_watchpoint_length_limit, _("\
11884Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
11885Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
11886Specify a negative limit for unlimited."),
11887 NULL, NULL, /* FIXME: i18n: The maximum
11888 length (in bytes) of a target
11889 hardware watchpoint is %s. */
11890 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 11891 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
11892 &remote_hw_breakpoint_limit, _("\
11893Set the maximum number of target hardware breakpoints."), _("\
11894Show the maximum number of target hardware breakpoints."), _("\
11895Specify a negative limit for unlimited."),
3e43a32a
MS
11896 NULL, NULL, /* FIXME: i18n: The maximum
11897 number of target hardware
11898 breakpoints is %s. */
b3f42336 11899 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 11900
1b493192
PA
11901 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
11902 &remote_address_size, _("\
4d28ad1e
AC
11903Set the maximum size of the address (in bits) in a memory packet."), _("\
11904Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
11905 NULL,
11906 NULL, /* FIXME: i18n: */
11907 &setlist, &showlist);
c906108c 11908
444abaca 11909 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 11910 "X", "binary-download", 1);
0f71a2f6 11911
444abaca 11912 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 11913 "vCont", "verbose-resume", 0);
506fb367 11914
89be2091
DJ
11915 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
11916 "QPassSignals", "pass-signals", 0);
11917
9b224c5e
PA
11918 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
11919 "QProgramSignals", "program-signals", 0);
11920
444abaca 11921 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 11922 "qSymbol", "symbol-lookup", 0);
dc8acb97 11923
444abaca 11924 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 11925 "P", "set-register", 1);
d471ea57 11926
444abaca 11927 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 11928 "p", "fetch-register", 1);
b96ec7ac 11929
444abaca 11930 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 11931 "Z0", "software-breakpoint", 0);
d471ea57 11932
444abaca 11933 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 11934 "Z1", "hardware-breakpoint", 0);
d471ea57 11935
444abaca 11936 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 11937 "Z2", "write-watchpoint", 0);
d471ea57 11938
444abaca 11939 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 11940 "Z3", "read-watchpoint", 0);
d471ea57 11941
444abaca 11942 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 11943 "Z4", "access-watchpoint", 0);
d471ea57 11944
0876f84a
DJ
11945 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
11946 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 11947
23181151
DJ
11948 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
11949 "qXfer:features:read", "target-features", 0);
11950
cfa9d6d9
DJ
11951 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
11952 "qXfer:libraries:read", "library-info", 0);
11953
2268b414
JK
11954 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
11955 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
11956
fd79ecee
DJ
11957 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
11958 "qXfer:memory-map:read", "memory-map", 0);
11959
0e7f50da
UW
11960 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
11961 "qXfer:spu:read", "read-spu-object", 0);
11962
11963 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
11964 "qXfer:spu:write", "write-spu-object", 0);
11965
07e059b5
VP
11966 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
11967 "qXfer:osdata:read", "osdata", 0);
11968
dc146f7c
VP
11969 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
11970 "qXfer:threads:read", "threads", 0);
11971
4aa995e1
PA
11972 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
11973 "qXfer:siginfo:read", "read-siginfo-object", 0);
11974
11975 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
11976 "qXfer:siginfo:write", "write-siginfo-object", 0);
11977
b3b9301e
PA
11978 add_packet_config_cmd
11979 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 11980 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 11981
169081d0
TG
11982 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
11983 "qXfer:uib:read", "unwind-info-block", 0);
11984
444abaca 11985 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 11986 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
11987 0);
11988
711e434b
PM
11989 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
11990 "qGetTIBAddr", "get-thread-information-block-address",
11991 0);
11992
40ab02ce
MS
11993 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
11994 "bc", "reverse-continue", 0);
11995
11996 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
11997 "bs", "reverse-step", 0);
11998
be2a5f71
DJ
11999 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12000 "qSupported", "supported-packets", 0);
12001
08388c79
DE
12002 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12003 "qSearch:memory", "search-memory", 0);
12004
bd3eecc3
PA
12005 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12006 "qTStatus", "trace-status", 0);
12007
a6b151f1
DJ
12008 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12009 "vFile:open", "hostio-open", 0);
12010
12011 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12012 "vFile:pread", "hostio-pread", 0);
12013
12014 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12015 "vFile:pwrite", "hostio-pwrite", 0);
12016
12017 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12018 "vFile:close", "hostio-close", 0);
12019
12020 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12021 "vFile:unlink", "hostio-unlink", 0);
12022
b9e7b9c3
UW
12023 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12024 "vFile:readlink", "hostio-readlink", 0);
12025
2d717e4f
DJ
12026 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12027 "vAttach", "attach", 0);
12028
12029 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12030 "vRun", "run", 0);
12031
a6f3e723
SL
12032 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12033 "QStartNoAckMode", "noack", 0);
12034
82f73884
PA
12035 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12036 "vKill", "kill", 0);
12037
0b16c5cf
PA
12038 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12039 "qAttached", "query-attached", 0);
12040
782b2b07 12041 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
12042 "ConditionalTracepoints",
12043 "conditional-tracepoints", 0);
3788aec7
LM
12044
12045 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12046 "ConditionalBreakpoints",
12047 "conditional-breakpoints", 0);
12048
d3ce09f5
SS
12049 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12050 "BreakpointCommands",
12051 "breakpoint-commands", 0);
12052
7a697b8d
SS
12053 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12054 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 12055
409873ef
SS
12056 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12057 "TracepointSource", "TracepointSource", 0);
12058
d914c394
SS
12059 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12060 "QAllow", "allow", 0);
12061
0fb4aa4b
PA
12062 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12063 "StaticTracepoints", "static-tracepoints", 0);
12064
1e4d1764
YQ
12065 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12066 "InstallInTrace", "install-in-trace", 0);
12067
0fb4aa4b
PA
12068 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12069 "qXfer:statictrace:read", "read-sdata-object", 0);
12070
78d85199
YQ
12071 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12072 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12073
03583c20
UW
12074 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12075 "QDisableRandomization", "disable-randomization", 0);
12076
d1feda86
YQ
12077 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12078 "QAgent", "agent", 0);
12079
f6f899bf
HAQ
12080 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12081 "QTBuffer:size", "trace-buffer-size", 0);
12082
9accd112
MM
12083 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12084 "Qbtrace:off", "disable-btrace", 0);
12085
12086 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12087 "Qbtrace:bts", "enable-btrace", 0);
12088
12089 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12090 "qXfer:btrace", "read-btrace", 0);
12091
37a105a1
DJ
12092 /* Keep the old ``set remote Z-packet ...'' working. Each individual
12093 Z sub-packet has its own set and show commands, but users may
12094 have sets to this variable in their .gdbinit files (or in their
12095 documentation). */
e9e68a56 12096 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
12097 &remote_Z_packet_detect, _("\
12098Set use of remote protocol `Z' packets"), _("\
12099Show use of remote protocol `Z' packets "), _("\
3b64bf98 12100When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 12101packets."),
e9e68a56 12102 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
12103 show_remote_protocol_Z_packet_cmd,
12104 /* FIXME: i18n: Use of remote protocol
12105 `Z' packets is %s. */
e9e68a56 12106 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 12107
a6b151f1
DJ
12108 add_prefix_cmd ("remote", class_files, remote_command, _("\
12109Manipulate files on the remote system\n\
12110Transfer files to and from the remote target system."),
12111 &remote_cmdlist, "remote ",
12112 0 /* allow-unknown */, &cmdlist);
12113
12114 add_cmd ("put", class_files, remote_put_command,
12115 _("Copy a local file to the remote system."),
12116 &remote_cmdlist);
12117
12118 add_cmd ("get", class_files, remote_get_command,
12119 _("Copy a remote file to the local system."),
12120 &remote_cmdlist);
12121
12122 add_cmd ("delete", class_files, remote_delete_command,
12123 _("Delete a remote file."),
12124 &remote_cmdlist);
12125
2d717e4f
DJ
12126 remote_exec_file = xstrdup ("");
12127 add_setshow_string_noescape_cmd ("exec-file", class_files,
12128 &remote_exec_file, _("\
12129Set the remote pathname for \"run\""), _("\
12130Show the remote pathname for \"run\""), NULL, NULL, NULL,
12131 &remote_set_cmdlist, &remote_show_cmdlist);
12132
c1e36e3e
PA
12133 add_setshow_boolean_cmd ("range-stepping", class_run,
12134 &use_range_stepping, _("\
12135Enable or disable range stepping."), _("\
12136Show whether target-assisted range stepping is enabled."), _("\
12137If on, and the target supports it, when stepping a source line, GDB\n\
12138tells the target to step the corresponding range of addresses itself instead\n\
12139of issuing multiple single-steps. This speeds up source level\n\
12140stepping. If off, GDB always issues single-steps, even if range\n\
12141stepping is supported by the target. The default is on."),
12142 set_range_stepping,
12143 show_range_stepping,
12144 &setlist,
12145 &showlist);
12146
449092f6
CV
12147 /* Eventually initialize fileio. See fileio.c */
12148 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229
PA
12149
12150 /* Take advantage of the fact that the LWP field is not used, to tag
12151 special ptids with it set to != 0. */
82f73884
PA
12152 magic_null_ptid = ptid_build (42000, 1, -1);
12153 not_sent_ptid = ptid_build (42000, 1, -2);
12154 any_thread_ptid = ptid_build (42000, 1, 0);
35b1e5cc
SS
12155
12156 target_buf_size = 2048;
12157 target_buf = xmalloc (target_buf_size);
c906108c 12158}
10760264 12159