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