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