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