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