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