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