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