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