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