btrace: uppercase btrace_read_type
[deliverable/binutils-gdb.git] / gdb / remote.c
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. */
74 static char *target_buf;
75 static 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. */
87 enum { REMOTE_ALIGN_WRITES = 16 };
88
89 /* Prototypes for local functions. */
90 static void async_cleanup_sigint_signal_handler (void *dummy);
91 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
92 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
93 int forever, int *is_notif);
94
95 static void async_handle_remote_sigint (int);
96 static void async_handle_remote_sigint_twice (int);
97
98 static void remote_files_info (struct target_ops *ignore);
99
100 static void remote_prepare_to_store (struct regcache *regcache);
101
102 static void remote_open (char *name, int from_tty);
103
104 static void extended_remote_open (char *name, int from_tty);
105
106 static void remote_open_1 (char *, int, struct target_ops *, int extended_p);
107
108 static void remote_close (void);
109
110 static void remote_mourn (struct target_ops *ops);
111
112 static void extended_remote_restart (void);
113
114 static void extended_remote_mourn (struct target_ops *);
115
116 static void remote_mourn_1 (struct target_ops *);
117
118 static void remote_send (char **buf, long *sizeof_buf_p);
119
120 static int readchar (int timeout);
121
122 static void remote_serial_write (const char *str, int len);
123
124 static void remote_kill (struct target_ops *ops);
125
126 static int tohex (int nib);
127
128 static int remote_can_async_p (void);
129
130 static int remote_is_async_p (void);
131
132 static void remote_async (void (*callback) (enum inferior_event_type event_type,
133 void *context), void *context);
134
135 static void sync_remote_interrupt_twice (int signo);
136
137 static void interrupt_query (void);
138
139 static void set_general_thread (struct ptid ptid);
140 static void set_continue_thread (struct ptid ptid);
141
142 static void get_offsets (void);
143
144 static void skip_frame (void);
145
146 static long read_frame (char **buf_p, long *sizeof_buf);
147
148 static int hexnumlen (ULONGEST num);
149
150 static void init_remote_ops (void);
151
152 static void init_extended_remote_ops (void);
153
154 static void remote_stop (ptid_t);
155
156 static int ishex (int ch, int *val);
157
158 static int stubhex (int ch);
159
160 static int hexnumstr (char *, ULONGEST);
161
162 static int hexnumnstr (char *, ULONGEST, int);
163
164 static CORE_ADDR remote_address_masked (CORE_ADDR);
165
166 static void print_packet (char *);
167
168 static void compare_sections_command (char *, int);
169
170 static void packet_command (char *, int);
171
172 static int stub_unpack_int (char *buff, int fieldlength);
173
174 static ptid_t remote_current_thread (ptid_t oldptid);
175
176 static void remote_find_new_threads (void);
177
178 static int fromhex (int a);
179
180 static int putpkt_binary (char *buf, int cnt);
181
182 static void check_binary_download (CORE_ADDR addr);
183
184 struct packet_config;
185
186 static void show_packet_config_cmd (struct packet_config *config);
187
188 static void update_packet_config (struct packet_config *config);
189
190 static void set_remote_protocol_packet_cmd (char *args, int from_tty,
191 struct cmd_list_element *c);
192
193 static 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
198 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
199 static ptid_t read_ptid (char *buf, char **obuf);
200
201 static void remote_set_permissions (void);
202
203 struct remote_state;
204 static int remote_get_trace_status (struct trace_status *ts);
205
206 static int remote_upload_tracepoints (struct uploaded_tp **utpp);
207
208 static int remote_upload_trace_state_variables (struct uploaded_tsv **utsvp);
209
210 static void remote_query_supported (void);
211
212 static void remote_check_symbols (void);
213
214 void _initialize_remote (void);
215
216 struct stop_reply;
217 static void stop_reply_xfree (struct stop_reply *);
218 static void remote_parse_stop_reply (char *, struct stop_reply *);
219 static void push_stop_reply (struct stop_reply *);
220 static void discard_pending_stop_replies_in_queue (struct remote_state *);
221 static int peek_stop_reply (ptid_t ptid);
222
223 static void remote_async_inferior_event_handler (gdb_client_data);
224
225 static void remote_terminal_ours (void);
226
227 static int remote_read_description_p (struct target_ops *target);
228
229 static void remote_console_output (char *msg);
230
231 static int remote_supports_cond_breakpoints (void);
232
233 static int remote_can_run_breakpoint_commands (void);
234
235 /* For "remote". */
236
237 static struct cmd_list_element *remote_cmdlist;
238
239 /* For "set remote" and "show remote". */
240
241 static struct cmd_list_element *remote_set_cmdlist;
242 static 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
249 struct 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
260 static int use_range_stepping = 1;
261
262 #define OPAQUETHREADBYTES 8
263
264 /* a 64 bit opaque identifier */
265 typedef 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
275 struct 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. */
431 struct private_thread_info
432 {
433 char *extra;
434 int core;
435 };
436
437 static void
438 free_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. */
445 static int
446 remote_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. */
455 static struct remote_state *remote_state;
456
457 static struct remote_state *
458 get_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
466 static struct remote_state *
467 new_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
483 struct 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
495 struct 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. */
518 static void
519 trace_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. */
537 static char *
538 remote_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. */
608 static struct gdbarch_data *remote_gdbarch_data_handle;
609
610 static struct remote_arch_state *
611 get_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
618 static struct remote_state *
619 get_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
631 static int
632 compare_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
645 static int
646 map_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
695 int
696 remote_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
718 static void *
719 init_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. */
771 static long
772 get_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
783 static struct packet_reg *
784 packet_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
797 static struct packet_reg *
798 packet_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
812 static struct target_ops remote_ops;
813
814 static 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. */
823 static 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. */
831 const char interrupt_sequence_control_c[] = "Ctrl-C";
832 const char interrupt_sequence_break[] = "BREAK";
833 const char interrupt_sequence_break_g[] = "BREAK-g";
834 static const char *const interrupt_sequence_modes[] =
835 {
836 interrupt_sequence_control_c,
837 interrupt_sequence_break,
838 interrupt_sequence_break_g,
839 NULL
840 };
841 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
842
843 static void
844 show_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. */
872 static 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. */
877 static int remote_break;
878
879 static void
880 set_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
888 static void
889 show_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
906 static unsigned int remote_address_size;
907
908 /* Temporary to track who currently owns the terminal. See
909 remote_terminal_* for more details. */
910
911 static int remote_async_terminal_ours_p;
912
913 /* The executable file to use for "run" on the remote side. */
914
915 static 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
926 struct 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
936 static long
937 get_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
996 static void
997 set_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
1039 static void
1040 show_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
1051 static struct memory_packet_config memory_write_packet_config =
1052 {
1053 "memory-write-packet-size",
1054 };
1055
1056 static void
1057 set_memory_write_packet_size (char *args, int from_tty)
1058 {
1059 set_memory_packet_size (args, &memory_write_packet_config);
1060 }
1061
1062 static void
1063 show_memory_write_packet_size (char *args, int from_tty)
1064 {
1065 show_memory_packet_size (&memory_write_packet_config);
1066 }
1067
1068 static long
1069 get_memory_write_packet_size (void)
1070 {
1071 return get_memory_packet_size (&memory_write_packet_config);
1072 }
1073
1074 static struct memory_packet_config memory_read_packet_config =
1075 {
1076 "memory-read-packet-size",
1077 };
1078
1079 static void
1080 set_memory_read_packet_size (char *args, int from_tty)
1081 {
1082 set_memory_packet_size (args, &memory_read_packet_config);
1083 }
1084
1085 static void
1086 show_memory_read_packet_size (char *args, int from_tty)
1087 {
1088 show_memory_packet_size (&memory_read_packet_config);
1089 }
1090
1091 static long
1092 get_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
1109 enum packet_support
1110 {
1111 PACKET_SUPPORT_UNKNOWN = 0,
1112 PACKET_ENABLE,
1113 PACKET_DISABLE
1114 };
1115
1116 struct 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
1127 enum packet_result
1128 {
1129 PACKET_ERROR,
1130 PACKET_OK,
1131 PACKET_UNKNOWN
1132 };
1133
1134 static void
1135 update_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
1151 static void
1152 show_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
1183 static void
1184 add_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
1224 static enum packet_result
1225 packet_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
1250 static enum packet_result
1251 packet_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
1309 enum {
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
1372 static struct packet_config remote_protocol_packets[PACKET_MAX];
1373
1374 static void
1375 set_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
1394 static void
1395 show_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
1417 enum 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
1430 static enum auto_boolean remote_Z_packet_detect;
1431
1432 static void
1433 set_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
1445 static void
1446 show_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. */
1459 static struct async_signal_handler *async_sigint_remote_twice_token;
1460 static 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
1466 static struct async_event_handler *remote_async_inferior_event_token;
1467
1468 \f
1469
1470 static ptid_t magic_null_ptid;
1471 static ptid_t not_sent_ptid;
1472 static 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
1477 static int
1478 remote_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
1520 static struct inferior *
1521 remote_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
1561 static void
1562 remote_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
1587 static void
1588 remote_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
1667 static struct private_thread_info *
1668 demand_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
1690 static void
1691 record_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
1699 static void
1700 remote_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
1751 static void
1752 remote_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. */
1804 static void
1805 set_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
1833 static void
1834 set_general_thread (struct ptid ptid)
1835 {
1836 set_thread (ptid, 1);
1837 }
1838
1839 static void
1840 set_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
1854 static void
1855 set_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
1873 static int
1874 remote_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
1913 typedef 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
1918 struct 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
1943 char *unpack_varlen_hex (char *buff, ULONGEST *result);
1944
1945 static char *unpack_nibble (char *buf, int *val);
1946
1947 static char *pack_nibble (char *buf, int nibble);
1948
1949 static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
1950
1951 static char *unpack_byte (char *buf, int *value);
1952
1953 static char *pack_int (char *buf, int value);
1954
1955 static char *unpack_int (char *buf, int *value);
1956
1957 static char *unpack_string (char *src, char *dest, int length);
1958
1959 static char *pack_threadid (char *pkt, threadref *id);
1960
1961 static char *unpack_threadid (char *inbuf, threadref *id);
1962
1963 void int_to_threadref (threadref *id, int value);
1964
1965 static int threadref_to_int (threadref *ref);
1966
1967 static void copy_threadref (threadref *dest, threadref *src);
1968
1969 static int threadmatch (threadref *dest, threadref *src);
1970
1971 static char *pack_threadinfo_request (char *pkt, int mode,
1972 threadref *id);
1973
1974 static int remote_unpack_thread_info_response (char *pkt,
1975 threadref *expectedref,
1976 struct gdb_ext_thread_info
1977 *info);
1978
1979
1980 static int remote_get_threadinfo (threadref *threadid,
1981 int fieldset, /*TAG mask */
1982 struct gdb_ext_thread_info *info);
1983
1984 static char *pack_threadlist_request (char *pkt, int startflag,
1985 int threadcount,
1986 threadref *nextthread);
1987
1988 static int parse_threadlist_response (char *pkt,
1989 int result_limit,
1990 threadref *original_echo,
1991 threadref *resultlist,
1992 int *doneflag);
1993
1994 static int remote_get_threadlist (int startflag,
1995 threadref *nextthread,
1996 int result_limit,
1997 int *done,
1998 int *result_count,
1999 threadref *threadlist);
2000
2001 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2002
2003 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2004 void *context, int looplimit);
2005
2006 static 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
2013 static char *
2014 write_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
2039 static ptid_t
2040 read_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
2079 static const char hexchars[] = "0123456789abcdef";
2080
2081 static int
2082 ishex (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
2102 static int
2103 stubhex (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
2114 static int
2115 stub_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
2131 char *
2132 unpack_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
2148 static char *
2149 unpack_nibble (char *buf, int *val)
2150 {
2151 *val = fromhex (*buf++);
2152 return buf;
2153 }
2154
2155 static char *
2156 pack_nibble (char *buf, int nibble)
2157 {
2158 *buf++ = hexchars[(nibble & 0x0f)];
2159 return buf;
2160 }
2161
2162 static char *
2163 pack_hex_byte (char *pkt, int byte)
2164 {
2165 *pkt++ = hexchars[(byte >> 4) & 0xf];
2166 *pkt++ = hexchars[(byte & 0xf)];
2167 return pkt;
2168 }
2169
2170 static char *
2171 unpack_byte (char *buf, int *value)
2172 {
2173 *value = stub_unpack_int (buf, 2);
2174 return buf + 2;
2175 }
2176
2177 static char *
2178 pack_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
2187 static char *
2188 unpack_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. */
2195 static char *pack_string (char *pkt, char *string);
2196
2197 static char *
2198 pack_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
2218 static char *
2219 unpack_string (char *src, char *dest, int length)
2220 {
2221 while (length--)
2222 *dest++ = *src++;
2223 *dest = '\0';
2224 return src;
2225 }
2226
2227 static char *
2228 pack_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
2241 static char *
2242 unpack_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
2264 void
2265 int_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
2281 static int
2282 threadref_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
2295 static void
2296 copy_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
2308 static int
2309 threadmatch (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
2336 static char *
2337 pack_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
2359 static int
2360 remote_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
2452 static int
2453 remote_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
2473 static char *
2474 pack_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
2488 static int
2489 parse_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
2516 static int
2517 remote_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
2580 static int
2581 remote_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
2620 static int
2621 remote_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
2633 static ptid_t
2634 remote_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
2650 static void
2651 remote_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
2659 typedef struct thread_item
2660 {
2661 ptid_t ptid;
2662 char *extra;
2663 int core;
2664 } thread_item_t;
2665 DEF_VEC_O(thread_item_t);
2666
2667 struct threads_parsing_context
2668 {
2669 VEC (thread_item_t) *items;
2670 };
2671
2672 static void
2673 start_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
2697 static void
2698 end_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
2708 const 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
2714 const struct gdb_xml_element thread_children[] = {
2715 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2716 };
2717
2718 const 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
2725 const 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
2733 static void
2734 clear_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
2755 static void
2756 remote_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
2877 static char *
2878 remote_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
2958 static int
2959 remote_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
2984 static VEC(static_tracepoint_marker_p) *
2985 remote_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
3038 static ptid_t
3039 remote_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
3047 static void
3048 extended_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
3062 static void
3063 remote_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
3098 static void
3099 get_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
3260 static int
3261 set_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. */
3271 static void
3272 send_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
3295 static ptid_t
3296 stop_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
3335 static ptid_t
3336 get_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
3362 static void
3363 add_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
3397 static void
3398 remote_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
3703 static void
3704 remote_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
3712 static void
3713 extended_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
3720 static void
3721 init_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
3731 static void
3732 remote_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
3794 static struct serial *
3795 remote_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
3823 void
3824 remote_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. */
3846 struct 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
3871 static void
3872 remote_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
3888 static void
3889 remote_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
3927 static void
3928 remote_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
3936 static void
3937 remote_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
3945 static void
3946 remote_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
3955 static void
3956 remote_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
3965 static void
3966 remote_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
3975 static void
3976 remote_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
3985 static void
3986 remote_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
3995 static void
3996 remote_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
4005 static void
4006 remote_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
4015 static void
4016 remote_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
4025 static void
4026 remote_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
4035 static void
4036 remote_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
4045 static 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
4122 static char *remote_support_xml;
4123
4124 /* Register string appended to "xmlRegisters=" in qSupported query. */
4125
4126 void
4127 register_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
4156 static char *
4157 remote_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
4165 static void
4166 remote_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
4309 static void
4310 remote_unpush_target (void)
4311 {
4312 pop_all_targets_above (process_stratum - 1);
4313 }
4314
4315 static void
4316 remote_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
4478 static void
4479 remote_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
4522 static void
4523 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4524 {
4525 remote_detach_1 (args, from_tty, 0);
4526 }
4527
4528 static void
4529 extended_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
4536 static void
4537 remote_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
4554 static void
4555 extended_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
4665 static void
4666 extended_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
4673 static int
4674 fromhex (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
4686 int
4687 hex2bin (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
4707 static int
4708 tohex (int nib)
4709 {
4710 if (nib < 10)
4711 return '0' + nib;
4712 else
4713 return 'a' + nib - 10;
4714 }
4715
4716 int
4717 bin2hex (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
4737 static void
4738 remote_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
4797 static char *
4798 append_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
4870 static char *
4871 append_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
4899 static int
4900 remote_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
4972 static void
4973 remote_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. */
5058 static void
5059 async_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. */
5065 static void
5066 async_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. */
5075 static void
5076 async_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. */
5084 static void
5085 async_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. */
5095 static void
5096 async_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. */
5106 static void
5107 async_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. */
5114 static 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. */
5121 static void
5122 sync_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
5132 static void
5133 sync_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
5144 static void
5145 remote_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
5195 static void
5196 remote_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
5216 static void
5217 remote_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
5230 static void
5231 interrupt_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\
5243 Give 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
5258 static void
5259 remote_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
5281 static void
5282 remote_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
5296 static void
5297 remote_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
5313 typedef struct cached_reg
5314 {
5315 int num;
5316 gdb_byte data[MAX_REGISTER_SIZE];
5317 } cached_reg_t;
5318
5319 DEF_VEC_O(cached_reg_t);
5320
5321 typedef 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
5347 DECLARE_QUEUE_P (stop_reply_p);
5348 DEFINE_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. */
5356 static QUEUE (stop_reply_p) *stop_reply_queue;
5357
5358 static void
5359 stop_reply_xfree (struct stop_reply *r)
5360 {
5361 notif_event_xfree ((struct notif_event *) r);
5362 }
5363
5364 static void
5365 remote_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
5371 static void
5372 remote_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
5387 static int
5388 remote_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
5399 static void
5400 stop_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
5407 static struct notif_event *
5408 remote_notif_stop_alloc_reply (void)
5409 {
5410 struct notif_event *r
5411 = (struct notif_event *) XNEW (struct stop_reply);
5412
5413 r->dtr = stop_reply_dtr;
5414
5415 return r;
5416 }
5417
5418 /* A client of notification Stop. */
5419
5420 struct 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
5433 struct 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
5442 static int
5443 remove_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
5462 static void
5463 discard_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
5496 static int
5497 remove_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
5516 static void
5517 discard_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
5531 static int
5532 remote_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
5553 static struct stop_reply *
5554 remote_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
5576 static struct stop_reply *
5577 queued_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
5592 static void
5593 push_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
5607 static int
5608 stop_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
5621 static int
5622 peek_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
5631 static void
5632 remote_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\
5686 Packet: '%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\
5741 Packet: '%s'\n"),
5742 p, buf);
5743 ++p;
5744
5745 if (reg == NULL)
5746 error (_("Remote sent bad register number %s: %s\n\
5747 Packet: '%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
5888 void
5889 remote_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
5926 static ptid_t
5927 process_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
5973 static ptid_t
5974 remote_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
6032 static ptid_t
6033 remote_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
6181 static ptid_t
6182 remote_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
6205 static int
6206 fetch_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
6265 static int
6266 send_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
6297 static void
6298 process_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
6387 static void
6388 fetch_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
6397 static void
6398 set_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
6417 static void
6418 remote_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
6468 static void
6469 remote_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
6493 static int
6494 store_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
6534 static void
6535 store_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
6575 static void
6576 remote_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
6621 static int
6622 hexnumlen (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
6634 static int
6635 hexnumstr (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
6645 static int
6646 hexnumnstr (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
6663 static CORE_ADDR
6664 remote_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
6692 static int
6693 remote_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
6733 static int
6734 remote_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
6781 static void
6782 check_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
6848 static LONGEST
6849 remote_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
7004 static LONGEST
7005 remote_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
7040 static LONGEST
7041 remote_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
7087 static enum packet_result
7088 remote_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
7109 static void
7110 restore_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. */
7120 static const int remote_flash_timeout = 1000;
7121
7122 static void
7123 remote_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
7150 static LONGEST
7151 remote_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
7167 static void
7168 remote_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
7190 static void
7191 remote_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
7205 static void
7206 unpush_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
7217 static int
7218 readchar (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
7247 static void
7248 remote_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
7264 static void
7265 remote_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
7280 static char *
7281 escape_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
7299 static void
7300 print_packet (char *buf)
7301 {
7302 puts_filtered ("\"");
7303 fputstr_filtered (buf, '"', gdb_stdout);
7304 puts_filtered ("\"");
7305 }
7306
7307 int
7308 putpkt (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
7319 static int
7320 putpkt_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
7515 static void
7516 skip_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
7557 static long
7558 read_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. */
7693 void
7694 getpkt (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
7716 static int
7717 getpkt_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
7857 static int
7858 getpkt_sane (char **buf, long *sizeof_buf, int forever)
7859 {
7860 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
7861 }
7862
7863 static int
7864 getpkt_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
7872 static void
7873 remote_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
7908 static int
7909 remote_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
7928 static void
7929 extended_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
7959 static void
7960 remote_mourn (struct target_ops *ops)
7961 {
7962 remote_mourn_1 (ops);
7963 }
7964
7965 /* Worker function for remote_mourn. */
7966 static void
7967 remote_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
7975 static void
7976 extended_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
8036 static void
8037 extended_remote_mourn (struct target_ops *ops)
8038 {
8039 extended_remote_mourn_1 (ops);
8040 }
8041
8042 static int
8043 extended_remote_supports_disable_randomization (void)
8044 {
8045 return (remote_protocol_packets[PACKET_QDisableRandomization].support
8046 == PACKET_ENABLE);
8047 }
8048
8049 static void
8050 extended_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
8065 static int
8066 extended_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
8132 static void
8133 extended_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
8181 static void
8182 extended_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
8195 static int
8196 remote_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
8226 static void
8227 remote_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
8259 static int
8260 remote_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 /* If this breakpoint has target-side commands but this stub doesn't
8317 support Z0 packets, throw error. */
8318 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8319 throw_error (NOT_SUPPORTED_ERROR, _("\
8320 Target doesn't support breakpoints that have target side commands."));
8321
8322 return memory_insert_breakpoint (gdbarch, bp_tgt);
8323 }
8324
8325 static int
8326 remote_remove_breakpoint (struct gdbarch *gdbarch,
8327 struct bp_target_info *bp_tgt)
8328 {
8329 CORE_ADDR addr = bp_tgt->placed_address;
8330 struct remote_state *rs = get_remote_state ();
8331
8332 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
8333 {
8334 char *p = rs->buf;
8335 char *endbuf = rs->buf + get_remote_packet_size ();
8336
8337 /* Make sure the remote is pointing at the right process, if
8338 necessary. */
8339 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8340 set_general_process ();
8341
8342 *(p++) = 'z';
8343 *(p++) = '0';
8344 *(p++) = ',';
8345
8346 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8347 p += hexnumstr (p, addr);
8348 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
8349
8350 putpkt (rs->buf);
8351 getpkt (&rs->buf, &rs->buf_size, 0);
8352
8353 return (rs->buf[0] == 'E');
8354 }
8355
8356 return memory_remove_breakpoint (gdbarch, bp_tgt);
8357 }
8358
8359 static int
8360 watchpoint_to_Z_packet (int type)
8361 {
8362 switch (type)
8363 {
8364 case hw_write:
8365 return Z_PACKET_WRITE_WP;
8366 break;
8367 case hw_read:
8368 return Z_PACKET_READ_WP;
8369 break;
8370 case hw_access:
8371 return Z_PACKET_ACCESS_WP;
8372 break;
8373 default:
8374 internal_error (__FILE__, __LINE__,
8375 _("hw_bp_to_z: bad watchpoint type %d"), type);
8376 }
8377 }
8378
8379 static int
8380 remote_insert_watchpoint (CORE_ADDR addr, int len, int type,
8381 struct expression *cond)
8382 {
8383 struct remote_state *rs = get_remote_state ();
8384 char *endbuf = rs->buf + get_remote_packet_size ();
8385 char *p;
8386 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8387
8388 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
8389 return 1;
8390
8391 /* Make sure the remote is pointing at the right process, if
8392 necessary. */
8393 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8394 set_general_process ();
8395
8396 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
8397 p = strchr (rs->buf, '\0');
8398 addr = remote_address_masked (addr);
8399 p += hexnumstr (p, (ULONGEST) addr);
8400 xsnprintf (p, endbuf - p, ",%x", len);
8401
8402 putpkt (rs->buf);
8403 getpkt (&rs->buf, &rs->buf_size, 0);
8404
8405 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8406 {
8407 case PACKET_ERROR:
8408 return -1;
8409 case PACKET_UNKNOWN:
8410 return 1;
8411 case PACKET_OK:
8412 return 0;
8413 }
8414 internal_error (__FILE__, __LINE__,
8415 _("remote_insert_watchpoint: reached end of function"));
8416 }
8417
8418 static int
8419 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8420 CORE_ADDR start, int length)
8421 {
8422 CORE_ADDR diff = remote_address_masked (addr - start);
8423
8424 return diff < length;
8425 }
8426
8427
8428 static int
8429 remote_remove_watchpoint (CORE_ADDR addr, int len, int type,
8430 struct expression *cond)
8431 {
8432 struct remote_state *rs = get_remote_state ();
8433 char *endbuf = rs->buf + get_remote_packet_size ();
8434 char *p;
8435 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8436
8437 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
8438 return -1;
8439
8440 /* Make sure the remote is pointing at the right process, if
8441 necessary. */
8442 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8443 set_general_process ();
8444
8445 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
8446 p = strchr (rs->buf, '\0');
8447 addr = remote_address_masked (addr);
8448 p += hexnumstr (p, (ULONGEST) addr);
8449 xsnprintf (p, endbuf - p, ",%x", len);
8450 putpkt (rs->buf);
8451 getpkt (&rs->buf, &rs->buf_size, 0);
8452
8453 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8454 {
8455 case PACKET_ERROR:
8456 case PACKET_UNKNOWN:
8457 return -1;
8458 case PACKET_OK:
8459 return 0;
8460 }
8461 internal_error (__FILE__, __LINE__,
8462 _("remote_remove_watchpoint: reached end of function"));
8463 }
8464
8465
8466 int remote_hw_watchpoint_limit = -1;
8467 int remote_hw_watchpoint_length_limit = -1;
8468 int remote_hw_breakpoint_limit = -1;
8469
8470 static int
8471 remote_region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
8472 {
8473 if (remote_hw_watchpoint_length_limit == 0)
8474 return 0;
8475 else if (remote_hw_watchpoint_length_limit < 0)
8476 return 1;
8477 else if (len <= remote_hw_watchpoint_length_limit)
8478 return 1;
8479 else
8480 return 0;
8481 }
8482
8483 static int
8484 remote_check_watch_resources (int type, int cnt, int ot)
8485 {
8486 if (type == bp_hardware_breakpoint)
8487 {
8488 if (remote_hw_breakpoint_limit == 0)
8489 return 0;
8490 else if (remote_hw_breakpoint_limit < 0)
8491 return 1;
8492 else if (cnt <= remote_hw_breakpoint_limit)
8493 return 1;
8494 }
8495 else
8496 {
8497 if (remote_hw_watchpoint_limit == 0)
8498 return 0;
8499 else if (remote_hw_watchpoint_limit < 0)
8500 return 1;
8501 else if (ot)
8502 return -1;
8503 else if (cnt <= remote_hw_watchpoint_limit)
8504 return 1;
8505 }
8506 return -1;
8507 }
8508
8509 static int
8510 remote_stopped_by_watchpoint (void)
8511 {
8512 struct remote_state *rs = get_remote_state ();
8513
8514 return rs->remote_stopped_by_watchpoint_p;
8515 }
8516
8517 static int
8518 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
8519 {
8520 struct remote_state *rs = get_remote_state ();
8521 int rc = 0;
8522
8523 if (remote_stopped_by_watchpoint ())
8524 {
8525 *addr_p = rs->remote_watch_data_address;
8526 rc = 1;
8527 }
8528
8529 return rc;
8530 }
8531
8532
8533 static int
8534 remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
8535 struct bp_target_info *bp_tgt)
8536 {
8537 CORE_ADDR addr;
8538 struct remote_state *rs;
8539 char *p, *endbuf;
8540 char *message;
8541
8542 /* The length field should be set to the size of a breakpoint
8543 instruction, even though we aren't inserting one ourselves. */
8544
8545 gdbarch_remote_breakpoint_from_pc
8546 (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
8547
8548 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
8549 return -1;
8550
8551 /* Make sure the remote is pointing at the right process, if
8552 necessary. */
8553 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8554 set_general_process ();
8555
8556 rs = get_remote_state ();
8557 p = rs->buf;
8558 endbuf = rs->buf + get_remote_packet_size ();
8559
8560 *(p++) = 'Z';
8561 *(p++) = '1';
8562 *(p++) = ',';
8563
8564 addr = remote_address_masked (bp_tgt->placed_address);
8565 p += hexnumstr (p, (ULONGEST) addr);
8566 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
8567
8568 if (remote_supports_cond_breakpoints ())
8569 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8570
8571 if (remote_can_run_breakpoint_commands ())
8572 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8573
8574 putpkt (rs->buf);
8575 getpkt (&rs->buf, &rs->buf_size, 0);
8576
8577 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8578 {
8579 case PACKET_ERROR:
8580 if (rs->buf[1] == '.')
8581 {
8582 message = strchr (rs->buf + 2, '.');
8583 if (message)
8584 error (_("Remote failure reply: %s"), message + 1);
8585 }
8586 return -1;
8587 case PACKET_UNKNOWN:
8588 return -1;
8589 case PACKET_OK:
8590 return 0;
8591 }
8592 internal_error (__FILE__, __LINE__,
8593 _("remote_insert_hw_breakpoint: reached end of function"));
8594 }
8595
8596
8597 static int
8598 remote_remove_hw_breakpoint (struct gdbarch *gdbarch,
8599 struct bp_target_info *bp_tgt)
8600 {
8601 CORE_ADDR addr;
8602 struct remote_state *rs = get_remote_state ();
8603 char *p = rs->buf;
8604 char *endbuf = rs->buf + get_remote_packet_size ();
8605
8606 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
8607 return -1;
8608
8609 /* Make sure the remote is pointing at the right process, if
8610 necessary. */
8611 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8612 set_general_process ();
8613
8614 *(p++) = 'z';
8615 *(p++) = '1';
8616 *(p++) = ',';
8617
8618 addr = remote_address_masked (bp_tgt->placed_address);
8619 p += hexnumstr (p, (ULONGEST) addr);
8620 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
8621
8622 putpkt (rs->buf);
8623 getpkt (&rs->buf, &rs->buf_size, 0);
8624
8625 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8626 {
8627 case PACKET_ERROR:
8628 case PACKET_UNKNOWN:
8629 return -1;
8630 case PACKET_OK:
8631 return 0;
8632 }
8633 internal_error (__FILE__, __LINE__,
8634 _("remote_remove_hw_breakpoint: reached end of function"));
8635 }
8636
8637 /* Verify memory using the "qCRC:" request. */
8638
8639 static int
8640 remote_verify_memory (struct target_ops *ops,
8641 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8642 {
8643 struct remote_state *rs = get_remote_state ();
8644 unsigned long host_crc, target_crc;
8645 char *tmp;
8646
8647 /* Make sure the remote is pointing at the right process. */
8648 set_general_process ();
8649
8650 /* FIXME: assumes lma can fit into long. */
8651 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8652 (long) lma, (long) size);
8653 putpkt (rs->buf);
8654
8655 /* Be clever; compute the host_crc before waiting for target
8656 reply. */
8657 host_crc = xcrc32 (data, size, 0xffffffff);
8658
8659 getpkt (&rs->buf, &rs->buf_size, 0);
8660 if (rs->buf[0] == 'E')
8661 return -1;
8662
8663 if (rs->buf[0] != 'C')
8664 error (_("remote target does not support this operation"));
8665
8666 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8667 target_crc = target_crc * 16 + fromhex (*tmp);
8668
8669 return (host_crc == target_crc);
8670 }
8671
8672 /* compare-sections command
8673
8674 With no arguments, compares each loadable section in the exec bfd
8675 with the same memory range on the target, and reports mismatches.
8676 Useful for verifying the image on the target against the exec file. */
8677
8678 static void
8679 compare_sections_command (char *args, int from_tty)
8680 {
8681 asection *s;
8682 struct cleanup *old_chain;
8683 gdb_byte *sectdata;
8684 const char *sectname;
8685 bfd_size_type size;
8686 bfd_vma lma;
8687 int matched = 0;
8688 int mismatched = 0;
8689 int res;
8690
8691 if (!exec_bfd)
8692 error (_("command cannot be used without an exec file"));
8693
8694 /* Make sure the remote is pointing at the right process. */
8695 set_general_process ();
8696
8697 for (s = exec_bfd->sections; s; s = s->next)
8698 {
8699 if (!(s->flags & SEC_LOAD))
8700 continue; /* Skip non-loadable section. */
8701
8702 size = bfd_get_section_size (s);
8703 if (size == 0)
8704 continue; /* Skip zero-length section. */
8705
8706 sectname = bfd_get_section_name (exec_bfd, s);
8707 if (args && strcmp (args, sectname) != 0)
8708 continue; /* Not the section selected by user. */
8709
8710 matched = 1; /* Do this section. */
8711 lma = s->lma;
8712
8713 sectdata = xmalloc (size);
8714 old_chain = make_cleanup (xfree, sectdata);
8715 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
8716
8717 res = target_verify_memory (sectdata, lma, size);
8718
8719 if (res == -1)
8720 error (_("target memory fault, section %s, range %s -- %s"), sectname,
8721 paddress (target_gdbarch (), lma),
8722 paddress (target_gdbarch (), lma + size));
8723
8724 printf_filtered ("Section %s, range %s -- %s: ", sectname,
8725 paddress (target_gdbarch (), lma),
8726 paddress (target_gdbarch (), lma + size));
8727 if (res)
8728 printf_filtered ("matched.\n");
8729 else
8730 {
8731 printf_filtered ("MIS-MATCHED!\n");
8732 mismatched++;
8733 }
8734
8735 do_cleanups (old_chain);
8736 }
8737 if (mismatched > 0)
8738 warning (_("One or more sections of the remote executable does not match\n\
8739 the loaded file\n"));
8740 if (args && !matched)
8741 printf_filtered (_("No loaded section named '%s'.\n"), args);
8742 }
8743
8744 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8745 into remote target. The number of bytes written to the remote
8746 target is returned, or -1 for error. */
8747
8748 static LONGEST
8749 remote_write_qxfer (struct target_ops *ops, const char *object_name,
8750 const char *annex, const gdb_byte *writebuf,
8751 ULONGEST offset, LONGEST len,
8752 struct packet_config *packet)
8753 {
8754 int i, buf_len;
8755 ULONGEST n;
8756 struct remote_state *rs = get_remote_state ();
8757 int max_size = get_memory_write_packet_size ();
8758
8759 if (packet->support == PACKET_DISABLE)
8760 return -1;
8761
8762 /* Insert header. */
8763 i = snprintf (rs->buf, max_size,
8764 "qXfer:%s:write:%s:%s:",
8765 object_name, annex ? annex : "",
8766 phex_nz (offset, sizeof offset));
8767 max_size -= (i + 1);
8768
8769 /* Escape as much data as fits into rs->buf. */
8770 buf_len = remote_escape_output
8771 (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
8772
8773 if (putpkt_binary (rs->buf, i + buf_len) < 0
8774 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8775 || packet_ok (rs->buf, packet) != PACKET_OK)
8776 return -1;
8777
8778 unpack_varlen_hex (rs->buf, &n);
8779 return n;
8780 }
8781
8782 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8783 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8784 number of bytes read is returned, or 0 for EOF, or -1 for error.
8785 The number of bytes read may be less than LEN without indicating an
8786 EOF. PACKET is checked and updated to indicate whether the remote
8787 target supports this object. */
8788
8789 static LONGEST
8790 remote_read_qxfer (struct target_ops *ops, const char *object_name,
8791 const char *annex,
8792 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
8793 struct packet_config *packet)
8794 {
8795 struct remote_state *rs = get_remote_state ();
8796 LONGEST i, n, packet_len;
8797
8798 if (packet->support == PACKET_DISABLE)
8799 return -1;
8800
8801 /* Check whether we've cached an end-of-object packet that matches
8802 this request. */
8803 if (rs->finished_object)
8804 {
8805 if (strcmp (object_name, rs->finished_object) == 0
8806 && strcmp (annex ? annex : "", rs->finished_annex) == 0
8807 && offset == rs->finished_offset)
8808 return 0;
8809
8810 /* Otherwise, we're now reading something different. Discard
8811 the cache. */
8812 xfree (rs->finished_object);
8813 xfree (rs->finished_annex);
8814 rs->finished_object = NULL;
8815 rs->finished_annex = NULL;
8816 }
8817
8818 /* Request only enough to fit in a single packet. The actual data
8819 may not, since we don't know how much of it will need to be escaped;
8820 the target is free to respond with slightly less data. We subtract
8821 five to account for the response type and the protocol frame. */
8822 n = min (get_remote_packet_size () - 5, len);
8823 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8824 object_name, annex ? annex : "",
8825 phex_nz (offset, sizeof offset),
8826 phex_nz (n, sizeof n));
8827 i = putpkt (rs->buf);
8828 if (i < 0)
8829 return -1;
8830
8831 rs->buf[0] = '\0';
8832 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8833 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
8834 return -1;
8835
8836 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8837 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8838
8839 /* 'm' means there is (or at least might be) more data after this
8840 batch. That does not make sense unless there's at least one byte
8841 of data in this reply. */
8842 if (rs->buf[0] == 'm' && packet_len == 1)
8843 error (_("Remote qXfer reply contained no data."));
8844
8845 /* Got some data. */
8846 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
8847 packet_len - 1, readbuf, n);
8848
8849 /* 'l' is an EOF marker, possibly including a final block of data,
8850 or possibly empty. If we have the final block of a non-empty
8851 object, record this fact to bypass a subsequent partial read. */
8852 if (rs->buf[0] == 'l' && offset + i > 0)
8853 {
8854 rs->finished_object = xstrdup (object_name);
8855 rs->finished_annex = xstrdup (annex ? annex : "");
8856 rs->finished_offset = offset + i;
8857 }
8858
8859 return i;
8860 }
8861
8862 static LONGEST
8863 remote_xfer_partial (struct target_ops *ops, enum target_object object,
8864 const char *annex, gdb_byte *readbuf,
8865 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len)
8866 {
8867 struct remote_state *rs;
8868 int i;
8869 char *p2;
8870 char query_type;
8871
8872 set_remote_traceframe ();
8873 set_general_thread (inferior_ptid);
8874
8875 rs = get_remote_state ();
8876
8877 /* Handle memory using the standard memory routines. */
8878 if (object == TARGET_OBJECT_MEMORY)
8879 {
8880 LONGEST xfered;
8881
8882 /* If the remote target is connected but not running, we should
8883 pass this request down to a lower stratum (e.g. the executable
8884 file). */
8885 if (!target_has_execution)
8886 return 0;
8887
8888 if (writebuf != NULL)
8889 xfered = remote_write_bytes (offset, writebuf, len);
8890 else
8891 xfered = remote_read_bytes (offset, readbuf, len);
8892
8893 return xfered;
8894 }
8895
8896 /* Handle SPU memory using qxfer packets. */
8897 if (object == TARGET_OBJECT_SPU)
8898 {
8899 if (readbuf)
8900 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
8901 &remote_protocol_packets
8902 [PACKET_qXfer_spu_read]);
8903 else
8904 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
8905 &remote_protocol_packets
8906 [PACKET_qXfer_spu_write]);
8907 }
8908
8909 /* Handle extra signal info using qxfer packets. */
8910 if (object == TARGET_OBJECT_SIGNAL_INFO)
8911 {
8912 if (readbuf)
8913 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
8914 &remote_protocol_packets
8915 [PACKET_qXfer_siginfo_read]);
8916 else
8917 return remote_write_qxfer (ops, "siginfo", annex,
8918 writebuf, offset, len,
8919 &remote_protocol_packets
8920 [PACKET_qXfer_siginfo_write]);
8921 }
8922
8923 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8924 {
8925 if (readbuf)
8926 return remote_read_qxfer (ops, "statictrace", annex,
8927 readbuf, offset, len,
8928 &remote_protocol_packets
8929 [PACKET_qXfer_statictrace_read]);
8930 else
8931 return -1;
8932 }
8933
8934 /* Only handle flash writes. */
8935 if (writebuf != NULL)
8936 {
8937 LONGEST xfered;
8938
8939 switch (object)
8940 {
8941 case TARGET_OBJECT_FLASH:
8942 return remote_flash_write (ops, offset, len, writebuf);
8943
8944 default:
8945 return -1;
8946 }
8947 }
8948
8949 /* Map pre-existing objects onto letters. DO NOT do this for new
8950 objects!!! Instead specify new query packets. */
8951 switch (object)
8952 {
8953 case TARGET_OBJECT_AVR:
8954 query_type = 'R';
8955 break;
8956
8957 case TARGET_OBJECT_AUXV:
8958 gdb_assert (annex == NULL);
8959 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
8960 &remote_protocol_packets[PACKET_qXfer_auxv]);
8961
8962 case TARGET_OBJECT_AVAILABLE_FEATURES:
8963 return remote_read_qxfer
8964 (ops, "features", annex, readbuf, offset, len,
8965 &remote_protocol_packets[PACKET_qXfer_features]);
8966
8967 case TARGET_OBJECT_LIBRARIES:
8968 return remote_read_qxfer
8969 (ops, "libraries", annex, readbuf, offset, len,
8970 &remote_protocol_packets[PACKET_qXfer_libraries]);
8971
8972 case TARGET_OBJECT_LIBRARIES_SVR4:
8973 return remote_read_qxfer
8974 (ops, "libraries-svr4", annex, readbuf, offset, len,
8975 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
8976
8977 case TARGET_OBJECT_MEMORY_MAP:
8978 gdb_assert (annex == NULL);
8979 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
8980 &remote_protocol_packets[PACKET_qXfer_memory_map]);
8981
8982 case TARGET_OBJECT_OSDATA:
8983 /* Should only get here if we're connected. */
8984 gdb_assert (rs->remote_desc);
8985 return remote_read_qxfer
8986 (ops, "osdata", annex, readbuf, offset, len,
8987 &remote_protocol_packets[PACKET_qXfer_osdata]);
8988
8989 case TARGET_OBJECT_THREADS:
8990 gdb_assert (annex == NULL);
8991 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
8992 &remote_protocol_packets[PACKET_qXfer_threads]);
8993
8994 case TARGET_OBJECT_TRACEFRAME_INFO:
8995 gdb_assert (annex == NULL);
8996 return remote_read_qxfer
8997 (ops, "traceframe-info", annex, readbuf, offset, len,
8998 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
8999
9000 case TARGET_OBJECT_FDPIC:
9001 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9002 &remote_protocol_packets[PACKET_qXfer_fdpic]);
9003
9004 case TARGET_OBJECT_OPENVMS_UIB:
9005 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9006 &remote_protocol_packets[PACKET_qXfer_uib]);
9007
9008 case TARGET_OBJECT_BTRACE:
9009 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9010 &remote_protocol_packets[PACKET_qXfer_btrace]);
9011
9012 default:
9013 return -1;
9014 }
9015
9016 /* Note: a zero OFFSET and LEN can be used to query the minimum
9017 buffer size. */
9018 if (offset == 0 && len == 0)
9019 return (get_remote_packet_size ());
9020 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
9021 large enough let the caller deal with it. */
9022 if (len < get_remote_packet_size ())
9023 return -1;
9024 len = get_remote_packet_size ();
9025
9026 /* Except for querying the minimum buffer size, target must be open. */
9027 if (!rs->remote_desc)
9028 error (_("remote query is only available after target open"));
9029
9030 gdb_assert (annex != NULL);
9031 gdb_assert (readbuf != NULL);
9032
9033 p2 = rs->buf;
9034 *p2++ = 'q';
9035 *p2++ = query_type;
9036
9037 /* We used one buffer char for the remote protocol q command and
9038 another for the query type. As the remote protocol encapsulation
9039 uses 4 chars plus one extra in case we are debugging
9040 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9041 string. */
9042 i = 0;
9043 while (annex[i] && (i < (get_remote_packet_size () - 8)))
9044 {
9045 /* Bad caller may have sent forbidden characters. */
9046 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9047 *p2++ = annex[i];
9048 i++;
9049 }
9050 *p2 = '\0';
9051 gdb_assert (annex[i] == '\0');
9052
9053 i = putpkt (rs->buf);
9054 if (i < 0)
9055 return i;
9056
9057 getpkt (&rs->buf, &rs->buf_size, 0);
9058 strcpy ((char *) readbuf, rs->buf);
9059
9060 return strlen ((char *) readbuf);
9061 }
9062
9063 static int
9064 remote_search_memory (struct target_ops* ops,
9065 CORE_ADDR start_addr, ULONGEST search_space_len,
9066 const gdb_byte *pattern, ULONGEST pattern_len,
9067 CORE_ADDR *found_addrp)
9068 {
9069 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9070 struct remote_state *rs = get_remote_state ();
9071 int max_size = get_memory_write_packet_size ();
9072 struct packet_config *packet =
9073 &remote_protocol_packets[PACKET_qSearch_memory];
9074 /* Number of packet bytes used to encode the pattern;
9075 this could be more than PATTERN_LEN due to escape characters. */
9076 int escaped_pattern_len;
9077 /* Amount of pattern that was encodable in the packet. */
9078 int used_pattern_len;
9079 int i;
9080 int found;
9081 ULONGEST found_addr;
9082
9083 /* Don't go to the target if we don't have to.
9084 This is done before checking packet->support to avoid the possibility that
9085 a success for this edge case means the facility works in general. */
9086 if (pattern_len > search_space_len)
9087 return 0;
9088 if (pattern_len == 0)
9089 {
9090 *found_addrp = start_addr;
9091 return 1;
9092 }
9093
9094 /* If we already know the packet isn't supported, fall back to the simple
9095 way of searching memory. */
9096
9097 if (packet->support == PACKET_DISABLE)
9098 {
9099 /* Target doesn't provided special support, fall back and use the
9100 standard support (copy memory and do the search here). */
9101 return simple_search_memory (ops, start_addr, search_space_len,
9102 pattern, pattern_len, found_addrp);
9103 }
9104
9105 /* Make sure the remote is pointing at the right process. */
9106 set_general_process ();
9107
9108 /* Insert header. */
9109 i = snprintf (rs->buf, max_size,
9110 "qSearch:memory:%s;%s;",
9111 phex_nz (start_addr, addr_size),
9112 phex_nz (search_space_len, sizeof (search_space_len)));
9113 max_size -= (i + 1);
9114
9115 /* Escape as much data as fits into rs->buf. */
9116 escaped_pattern_len =
9117 remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
9118 &used_pattern_len, max_size);
9119
9120 /* Bail if the pattern is too large. */
9121 if (used_pattern_len != pattern_len)
9122 error (_("Pattern is too large to transmit to remote target."));
9123
9124 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9125 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9126 || packet_ok (rs->buf, packet) != PACKET_OK)
9127 {
9128 /* The request may not have worked because the command is not
9129 supported. If so, fall back to the simple way. */
9130 if (packet->support == PACKET_DISABLE)
9131 {
9132 return simple_search_memory (ops, start_addr, search_space_len,
9133 pattern, pattern_len, found_addrp);
9134 }
9135 return -1;
9136 }
9137
9138 if (rs->buf[0] == '0')
9139 found = 0;
9140 else if (rs->buf[0] == '1')
9141 {
9142 found = 1;
9143 if (rs->buf[1] != ',')
9144 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9145 unpack_varlen_hex (rs->buf + 2, &found_addr);
9146 *found_addrp = found_addr;
9147 }
9148 else
9149 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9150
9151 return found;
9152 }
9153
9154 static void
9155 remote_rcmd (char *command,
9156 struct ui_file *outbuf)
9157 {
9158 struct remote_state *rs = get_remote_state ();
9159 char *p = rs->buf;
9160
9161 if (!rs->remote_desc)
9162 error (_("remote rcmd is only available after target open"));
9163
9164 /* Send a NULL command across as an empty command. */
9165 if (command == NULL)
9166 command = "";
9167
9168 /* The query prefix. */
9169 strcpy (rs->buf, "qRcmd,");
9170 p = strchr (rs->buf, '\0');
9171
9172 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9173 > get_remote_packet_size ())
9174 error (_("\"monitor\" command ``%s'' is too long."), command);
9175
9176 /* Encode the actual command. */
9177 bin2hex ((gdb_byte *) command, p, 0);
9178
9179 if (putpkt (rs->buf) < 0)
9180 error (_("Communication problem with target."));
9181
9182 /* get/display the response */
9183 while (1)
9184 {
9185 char *buf;
9186
9187 /* XXX - see also remote_get_noisy_reply(). */
9188 QUIT; /* Allow user to bail out with ^C. */
9189 rs->buf[0] = '\0';
9190 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9191 {
9192 /* Timeout. Continue to (try to) read responses.
9193 This is better than stopping with an error, assuming the stub
9194 is still executing the (long) monitor command.
9195 If needed, the user can interrupt gdb using C-c, obtaining
9196 an effect similar to stop on timeout. */
9197 continue;
9198 }
9199 buf = rs->buf;
9200 if (buf[0] == '\0')
9201 error (_("Target does not support this command."));
9202 if (buf[0] == 'O' && buf[1] != 'K')
9203 {
9204 remote_console_output (buf + 1); /* 'O' message from stub. */
9205 continue;
9206 }
9207 if (strcmp (buf, "OK") == 0)
9208 break;
9209 if (strlen (buf) == 3 && buf[0] == 'E'
9210 && isdigit (buf[1]) && isdigit (buf[2]))
9211 {
9212 error (_("Protocol error with Rcmd"));
9213 }
9214 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9215 {
9216 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
9217
9218 fputc_unfiltered (c, outbuf);
9219 }
9220 break;
9221 }
9222 }
9223
9224 static VEC(mem_region_s) *
9225 remote_memory_map (struct target_ops *ops)
9226 {
9227 VEC(mem_region_s) *result = NULL;
9228 char *text = target_read_stralloc (&current_target,
9229 TARGET_OBJECT_MEMORY_MAP, NULL);
9230
9231 if (text)
9232 {
9233 struct cleanup *back_to = make_cleanup (xfree, text);
9234
9235 result = parse_memory_map (text);
9236 do_cleanups (back_to);
9237 }
9238
9239 return result;
9240 }
9241
9242 static void
9243 packet_command (char *args, int from_tty)
9244 {
9245 struct remote_state *rs = get_remote_state ();
9246
9247 if (!rs->remote_desc)
9248 error (_("command can only be used with remote target"));
9249
9250 if (!args)
9251 error (_("remote-packet command requires packet text as argument"));
9252
9253 puts_filtered ("sending: ");
9254 print_packet (args);
9255 puts_filtered ("\n");
9256 putpkt (args);
9257
9258 getpkt (&rs->buf, &rs->buf_size, 0);
9259 puts_filtered ("received: ");
9260 print_packet (rs->buf);
9261 puts_filtered ("\n");
9262 }
9263
9264 #if 0
9265 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
9266
9267 static void display_thread_info (struct gdb_ext_thread_info *info);
9268
9269 static void threadset_test_cmd (char *cmd, int tty);
9270
9271 static void threadalive_test (char *cmd, int tty);
9272
9273 static void threadlist_test_cmd (char *cmd, int tty);
9274
9275 int get_and_display_threadinfo (threadref *ref);
9276
9277 static void threadinfo_test_cmd (char *cmd, int tty);
9278
9279 static int thread_display_step (threadref *ref, void *context);
9280
9281 static void threadlist_update_test_cmd (char *cmd, int tty);
9282
9283 static void init_remote_threadtests (void);
9284
9285 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
9286
9287 static void
9288 threadset_test_cmd (char *cmd, int tty)
9289 {
9290 int sample_thread = SAMPLE_THREAD;
9291
9292 printf_filtered (_("Remote threadset test\n"));
9293 set_general_thread (sample_thread);
9294 }
9295
9296
9297 static void
9298 threadalive_test (char *cmd, int tty)
9299 {
9300 int sample_thread = SAMPLE_THREAD;
9301 int pid = ptid_get_pid (inferior_ptid);
9302 ptid_t ptid = ptid_build (pid, 0, sample_thread);
9303
9304 if (remote_thread_alive (ptid))
9305 printf_filtered ("PASS: Thread alive test\n");
9306 else
9307 printf_filtered ("FAIL: Thread alive test\n");
9308 }
9309
9310 void output_threadid (char *title, threadref *ref);
9311
9312 void
9313 output_threadid (char *title, threadref *ref)
9314 {
9315 char hexid[20];
9316
9317 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
9318 hexid[16] = 0;
9319 printf_filtered ("%s %s\n", title, (&hexid[0]));
9320 }
9321
9322 static void
9323 threadlist_test_cmd (char *cmd, int tty)
9324 {
9325 int startflag = 1;
9326 threadref nextthread;
9327 int done, result_count;
9328 threadref threadlist[3];
9329
9330 printf_filtered ("Remote Threadlist test\n");
9331 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9332 &result_count, &threadlist[0]))
9333 printf_filtered ("FAIL: threadlist test\n");
9334 else
9335 {
9336 threadref *scan = threadlist;
9337 threadref *limit = scan + result_count;
9338
9339 while (scan < limit)
9340 output_threadid (" thread ", scan++);
9341 }
9342 }
9343
9344 void
9345 display_thread_info (struct gdb_ext_thread_info *info)
9346 {
9347 output_threadid ("Threadid: ", &info->threadid);
9348 printf_filtered ("Name: %s\n ", info->shortname);
9349 printf_filtered ("State: %s\n", info->display);
9350 printf_filtered ("other: %s\n\n", info->more_display);
9351 }
9352
9353 int
9354 get_and_display_threadinfo (threadref *ref)
9355 {
9356 int result;
9357 int set;
9358 struct gdb_ext_thread_info threadinfo;
9359
9360 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9361 | TAG_MOREDISPLAY | TAG_DISPLAY;
9362 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9363 display_thread_info (&threadinfo);
9364 return result;
9365 }
9366
9367 static void
9368 threadinfo_test_cmd (char *cmd, int tty)
9369 {
9370 int athread = SAMPLE_THREAD;
9371 threadref thread;
9372 int set;
9373
9374 int_to_threadref (&thread, athread);
9375 printf_filtered ("Remote Threadinfo test\n");
9376 if (!get_and_display_threadinfo (&thread))
9377 printf_filtered ("FAIL cannot get thread info\n");
9378 }
9379
9380 static int
9381 thread_display_step (threadref *ref, void *context)
9382 {
9383 /* output_threadid(" threadstep ",ref); *//* simple test */
9384 return get_and_display_threadinfo (ref);
9385 }
9386
9387 static void
9388 threadlist_update_test_cmd (char *cmd, int tty)
9389 {
9390 printf_filtered ("Remote Threadlist update test\n");
9391 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9392 }
9393
9394 static void
9395 init_remote_threadtests (void)
9396 {
9397 add_com ("tlist", class_obscure, threadlist_test_cmd,
9398 _("Fetch and print the remote list of "
9399 "thread identifiers, one pkt only"));
9400 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
9401 _("Fetch and display info about one thread"));
9402 add_com ("tset", class_obscure, threadset_test_cmd,
9403 _("Test setting to a different thread"));
9404 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
9405 _("Iterate through updating all remote thread info"));
9406 add_com ("talive", class_obscure, threadalive_test,
9407 _(" Remote thread alive test "));
9408 }
9409
9410 #endif /* 0 */
9411
9412 /* Convert a thread ID to a string. Returns the string in a static
9413 buffer. */
9414
9415 static char *
9416 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
9417 {
9418 static char buf[64];
9419 struct remote_state *rs = get_remote_state ();
9420
9421 if (ptid_equal (ptid, null_ptid))
9422 return normal_pid_to_str (ptid);
9423 else if (ptid_is_pid (ptid))
9424 {
9425 /* Printing an inferior target id. */
9426
9427 /* When multi-process extensions are off, there's no way in the
9428 remote protocol to know the remote process id, if there's any
9429 at all. There's one exception --- when we're connected with
9430 target extended-remote, and we manually attached to a process
9431 with "attach PID". We don't record anywhere a flag that
9432 allows us to distinguish that case from the case of
9433 connecting with extended-remote and the stub already being
9434 attached to a process, and reporting yes to qAttached, hence
9435 no smart special casing here. */
9436 if (!remote_multi_process_p (rs))
9437 {
9438 xsnprintf (buf, sizeof buf, "Remote target");
9439 return buf;
9440 }
9441
9442 return normal_pid_to_str (ptid);
9443 }
9444 else
9445 {
9446 if (ptid_equal (magic_null_ptid, ptid))
9447 xsnprintf (buf, sizeof buf, "Thread <main>");
9448 else if (rs->extended && remote_multi_process_p (rs))
9449 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
9450 ptid_get_pid (ptid), ptid_get_tid (ptid));
9451 else
9452 xsnprintf (buf, sizeof buf, "Thread %ld",
9453 ptid_get_tid (ptid));
9454 return buf;
9455 }
9456 }
9457
9458 /* Get the address of the thread local variable in OBJFILE which is
9459 stored at OFFSET within the thread local storage for thread PTID. */
9460
9461 static CORE_ADDR
9462 remote_get_thread_local_address (struct target_ops *ops,
9463 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
9464 {
9465 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
9466 {
9467 struct remote_state *rs = get_remote_state ();
9468 char *p = rs->buf;
9469 char *endp = rs->buf + get_remote_packet_size ();
9470 enum packet_result result;
9471
9472 strcpy (p, "qGetTLSAddr:");
9473 p += strlen (p);
9474 p = write_ptid (p, endp, ptid);
9475 *p++ = ',';
9476 p += hexnumstr (p, offset);
9477 *p++ = ',';
9478 p += hexnumstr (p, lm);
9479 *p++ = '\0';
9480
9481 putpkt (rs->buf);
9482 getpkt (&rs->buf, &rs->buf_size, 0);
9483 result = packet_ok (rs->buf,
9484 &remote_protocol_packets[PACKET_qGetTLSAddr]);
9485 if (result == PACKET_OK)
9486 {
9487 ULONGEST result;
9488
9489 unpack_varlen_hex (rs->buf, &result);
9490 return result;
9491 }
9492 else if (result == PACKET_UNKNOWN)
9493 throw_error (TLS_GENERIC_ERROR,
9494 _("Remote target doesn't support qGetTLSAddr packet"));
9495 else
9496 throw_error (TLS_GENERIC_ERROR,
9497 _("Remote target failed to process qGetTLSAddr request"));
9498 }
9499 else
9500 throw_error (TLS_GENERIC_ERROR,
9501 _("TLS not supported or disabled on this target"));
9502 /* Not reached. */
9503 return 0;
9504 }
9505
9506 /* Provide thread local base, i.e. Thread Information Block address.
9507 Returns 1 if ptid is found and thread_local_base is non zero. */
9508
9509 static int
9510 remote_get_tib_address (ptid_t ptid, CORE_ADDR *addr)
9511 {
9512 if (remote_protocol_packets[PACKET_qGetTIBAddr].support != PACKET_DISABLE)
9513 {
9514 struct remote_state *rs = get_remote_state ();
9515 char *p = rs->buf;
9516 char *endp = rs->buf + get_remote_packet_size ();
9517 enum packet_result result;
9518
9519 strcpy (p, "qGetTIBAddr:");
9520 p += strlen (p);
9521 p = write_ptid (p, endp, ptid);
9522 *p++ = '\0';
9523
9524 putpkt (rs->buf);
9525 getpkt (&rs->buf, &rs->buf_size, 0);
9526 result = packet_ok (rs->buf,
9527 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9528 if (result == PACKET_OK)
9529 {
9530 ULONGEST result;
9531
9532 unpack_varlen_hex (rs->buf, &result);
9533 if (addr)
9534 *addr = (CORE_ADDR) result;
9535 return 1;
9536 }
9537 else if (result == PACKET_UNKNOWN)
9538 error (_("Remote target doesn't support qGetTIBAddr packet"));
9539 else
9540 error (_("Remote target failed to process qGetTIBAddr request"));
9541 }
9542 else
9543 error (_("qGetTIBAddr not supported or disabled on this target"));
9544 /* Not reached. */
9545 return 0;
9546 }
9547
9548 /* Support for inferring a target description based on the current
9549 architecture and the size of a 'g' packet. While the 'g' packet
9550 can have any size (since optional registers can be left off the
9551 end), some sizes are easily recognizable given knowledge of the
9552 approximate architecture. */
9553
9554 struct remote_g_packet_guess
9555 {
9556 int bytes;
9557 const struct target_desc *tdesc;
9558 };
9559 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9560 DEF_VEC_O(remote_g_packet_guess_s);
9561
9562 struct remote_g_packet_data
9563 {
9564 VEC(remote_g_packet_guess_s) *guesses;
9565 };
9566
9567 static struct gdbarch_data *remote_g_packet_data_handle;
9568
9569 static void *
9570 remote_g_packet_data_init (struct obstack *obstack)
9571 {
9572 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9573 }
9574
9575 void
9576 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9577 const struct target_desc *tdesc)
9578 {
9579 struct remote_g_packet_data *data
9580 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9581 struct remote_g_packet_guess new_guess, *guess;
9582 int ix;
9583
9584 gdb_assert (tdesc != NULL);
9585
9586 for (ix = 0;
9587 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9588 ix++)
9589 if (guess->bytes == bytes)
9590 internal_error (__FILE__, __LINE__,
9591 _("Duplicate g packet description added for size %d"),
9592 bytes);
9593
9594 new_guess.bytes = bytes;
9595 new_guess.tdesc = tdesc;
9596 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9597 }
9598
9599 /* Return 1 if remote_read_description would do anything on this target
9600 and architecture, 0 otherwise. */
9601
9602 static int
9603 remote_read_description_p (struct target_ops *target)
9604 {
9605 struct remote_g_packet_data *data
9606 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9607
9608 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9609 return 1;
9610
9611 return 0;
9612 }
9613
9614 static const struct target_desc *
9615 remote_read_description (struct target_ops *target)
9616 {
9617 struct remote_g_packet_data *data
9618 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9619
9620 /* Do not try this during initial connection, when we do not know
9621 whether there is a running but stopped thread. */
9622 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
9623 return NULL;
9624
9625 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9626 {
9627 struct remote_g_packet_guess *guess;
9628 int ix;
9629 int bytes = send_g_packet ();
9630
9631 for (ix = 0;
9632 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9633 ix++)
9634 if (guess->bytes == bytes)
9635 return guess->tdesc;
9636
9637 /* We discard the g packet. A minor optimization would be to
9638 hold on to it, and fill the register cache once we have selected
9639 an architecture, but it's too tricky to do safely. */
9640 }
9641
9642 return NULL;
9643 }
9644
9645 /* Remote file transfer support. This is host-initiated I/O, not
9646 target-initiated; for target-initiated, see remote-fileio.c. */
9647
9648 /* If *LEFT is at least the length of STRING, copy STRING to
9649 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9650 decrease *LEFT. Otherwise raise an error. */
9651
9652 static void
9653 remote_buffer_add_string (char **buffer, int *left, char *string)
9654 {
9655 int len = strlen (string);
9656
9657 if (len > *left)
9658 error (_("Packet too long for target."));
9659
9660 memcpy (*buffer, string, len);
9661 *buffer += len;
9662 *left -= len;
9663
9664 /* NUL-terminate the buffer as a convenience, if there is
9665 room. */
9666 if (*left)
9667 **buffer = '\0';
9668 }
9669
9670 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9671 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9672 decrease *LEFT. Otherwise raise an error. */
9673
9674 static void
9675 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9676 int len)
9677 {
9678 if (2 * len > *left)
9679 error (_("Packet too long for target."));
9680
9681 bin2hex (bytes, *buffer, len);
9682 *buffer += 2 * len;
9683 *left -= 2 * len;
9684
9685 /* NUL-terminate the buffer as a convenience, if there is
9686 room. */
9687 if (*left)
9688 **buffer = '\0';
9689 }
9690
9691 /* If *LEFT is large enough, convert VALUE to hex and add it to
9692 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9693 decrease *LEFT. Otherwise raise an error. */
9694
9695 static void
9696 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9697 {
9698 int len = hexnumlen (value);
9699
9700 if (len > *left)
9701 error (_("Packet too long for target."));
9702
9703 hexnumstr (*buffer, value);
9704 *buffer += len;
9705 *left -= len;
9706
9707 /* NUL-terminate the buffer as a convenience, if there is
9708 room. */
9709 if (*left)
9710 **buffer = '\0';
9711 }
9712
9713 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9714 value, *REMOTE_ERRNO to the remote error number or zero if none
9715 was included, and *ATTACHMENT to point to the start of the annex
9716 if any. The length of the packet isn't needed here; there may
9717 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9718
9719 Return 0 if the packet could be parsed, -1 if it could not. If
9720 -1 is returned, the other variables may not be initialized. */
9721
9722 static int
9723 remote_hostio_parse_result (char *buffer, int *retcode,
9724 int *remote_errno, char **attachment)
9725 {
9726 char *p, *p2;
9727
9728 *remote_errno = 0;
9729 *attachment = NULL;
9730
9731 if (buffer[0] != 'F')
9732 return -1;
9733
9734 errno = 0;
9735 *retcode = strtol (&buffer[1], &p, 16);
9736 if (errno != 0 || p == &buffer[1])
9737 return -1;
9738
9739 /* Check for ",errno". */
9740 if (*p == ',')
9741 {
9742 errno = 0;
9743 *remote_errno = strtol (p + 1, &p2, 16);
9744 if (errno != 0 || p + 1 == p2)
9745 return -1;
9746 p = p2;
9747 }
9748
9749 /* Check for ";attachment". If there is no attachment, the
9750 packet should end here. */
9751 if (*p == ';')
9752 {
9753 *attachment = p + 1;
9754 return 0;
9755 }
9756 else if (*p == '\0')
9757 return 0;
9758 else
9759 return -1;
9760 }
9761
9762 /* Send a prepared I/O packet to the target and read its response.
9763 The prepared packet is in the global RS->BUF before this function
9764 is called, and the answer is there when we return.
9765
9766 COMMAND_BYTES is the length of the request to send, which may include
9767 binary data. WHICH_PACKET is the packet configuration to check
9768 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9769 is set to the error number and -1 is returned. Otherwise the value
9770 returned by the function is returned.
9771
9772 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9773 attachment is expected; an error will be reported if there's a
9774 mismatch. If one is found, *ATTACHMENT will be set to point into
9775 the packet buffer and *ATTACHMENT_LEN will be set to the
9776 attachment's length. */
9777
9778 static int
9779 remote_hostio_send_command (int command_bytes, int which_packet,
9780 int *remote_errno, char **attachment,
9781 int *attachment_len)
9782 {
9783 struct remote_state *rs = get_remote_state ();
9784 int ret, bytes_read;
9785 char *attachment_tmp;
9786
9787 if (!rs->remote_desc
9788 || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
9789 {
9790 *remote_errno = FILEIO_ENOSYS;
9791 return -1;
9792 }
9793
9794 putpkt_binary (rs->buf, command_bytes);
9795 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9796
9797 /* If it timed out, something is wrong. Don't try to parse the
9798 buffer. */
9799 if (bytes_read < 0)
9800 {
9801 *remote_errno = FILEIO_EINVAL;
9802 return -1;
9803 }
9804
9805 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9806 {
9807 case PACKET_ERROR:
9808 *remote_errno = FILEIO_EINVAL;
9809 return -1;
9810 case PACKET_UNKNOWN:
9811 *remote_errno = FILEIO_ENOSYS;
9812 return -1;
9813 case PACKET_OK:
9814 break;
9815 }
9816
9817 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9818 &attachment_tmp))
9819 {
9820 *remote_errno = FILEIO_EINVAL;
9821 return -1;
9822 }
9823
9824 /* Make sure we saw an attachment if and only if we expected one. */
9825 if ((attachment_tmp == NULL && attachment != NULL)
9826 || (attachment_tmp != NULL && attachment == NULL))
9827 {
9828 *remote_errno = FILEIO_EINVAL;
9829 return -1;
9830 }
9831
9832 /* If an attachment was found, it must point into the packet buffer;
9833 work out how many bytes there were. */
9834 if (attachment_tmp != NULL)
9835 {
9836 *attachment = attachment_tmp;
9837 *attachment_len = bytes_read - (*attachment - rs->buf);
9838 }
9839
9840 return ret;
9841 }
9842
9843 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9844 remote file descriptor, or -1 if an error occurs (and set
9845 *REMOTE_ERRNO). */
9846
9847 static int
9848 remote_hostio_open (const char *filename, int flags, int mode,
9849 int *remote_errno)
9850 {
9851 struct remote_state *rs = get_remote_state ();
9852 char *p = rs->buf;
9853 int left = get_remote_packet_size () - 1;
9854
9855 remote_buffer_add_string (&p, &left, "vFile:open:");
9856
9857 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9858 strlen (filename));
9859 remote_buffer_add_string (&p, &left, ",");
9860
9861 remote_buffer_add_int (&p, &left, flags);
9862 remote_buffer_add_string (&p, &left, ",");
9863
9864 remote_buffer_add_int (&p, &left, mode);
9865
9866 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9867 remote_errno, NULL, NULL);
9868 }
9869
9870 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9871 Return the number of bytes written, or -1 if an error occurs (and
9872 set *REMOTE_ERRNO). */
9873
9874 static int
9875 remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
9876 ULONGEST offset, int *remote_errno)
9877 {
9878 struct remote_state *rs = get_remote_state ();
9879 char *p = rs->buf;
9880 int left = get_remote_packet_size ();
9881 int out_len;
9882
9883 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9884
9885 remote_buffer_add_int (&p, &left, fd);
9886 remote_buffer_add_string (&p, &left, ",");
9887
9888 remote_buffer_add_int (&p, &left, offset);
9889 remote_buffer_add_string (&p, &left, ",");
9890
9891 p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
9892 get_remote_packet_size () - (p - rs->buf));
9893
9894 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9895 remote_errno, NULL, NULL);
9896 }
9897
9898 /* Read up to LEN bytes FD on the remote target into READ_BUF
9899 Return the number of bytes read, or -1 if an error occurs (and
9900 set *REMOTE_ERRNO). */
9901
9902 static int
9903 remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
9904 ULONGEST offset, int *remote_errno)
9905 {
9906 struct remote_state *rs = get_remote_state ();
9907 char *p = rs->buf;
9908 char *attachment;
9909 int left = get_remote_packet_size ();
9910 int ret, attachment_len;
9911 int read_len;
9912
9913 remote_buffer_add_string (&p, &left, "vFile:pread:");
9914
9915 remote_buffer_add_int (&p, &left, fd);
9916 remote_buffer_add_string (&p, &left, ",");
9917
9918 remote_buffer_add_int (&p, &left, len);
9919 remote_buffer_add_string (&p, &left, ",");
9920
9921 remote_buffer_add_int (&p, &left, offset);
9922
9923 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9924 remote_errno, &attachment,
9925 &attachment_len);
9926
9927 if (ret < 0)
9928 return ret;
9929
9930 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
9931 read_buf, len);
9932 if (read_len != ret)
9933 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9934
9935 return ret;
9936 }
9937
9938 /* Close FD on the remote target. Return 0, or -1 if an error occurs
9939 (and set *REMOTE_ERRNO). */
9940
9941 static int
9942 remote_hostio_close (int fd, int *remote_errno)
9943 {
9944 struct remote_state *rs = get_remote_state ();
9945 char *p = rs->buf;
9946 int left = get_remote_packet_size () - 1;
9947
9948 remote_buffer_add_string (&p, &left, "vFile:close:");
9949
9950 remote_buffer_add_int (&p, &left, fd);
9951
9952 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
9953 remote_errno, NULL, NULL);
9954 }
9955
9956 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
9957 occurs (and set *REMOTE_ERRNO). */
9958
9959 static int
9960 remote_hostio_unlink (const char *filename, int *remote_errno)
9961 {
9962 struct remote_state *rs = get_remote_state ();
9963 char *p = rs->buf;
9964 int left = get_remote_packet_size () - 1;
9965
9966 remote_buffer_add_string (&p, &left, "vFile:unlink:");
9967
9968 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9969 strlen (filename));
9970
9971 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
9972 remote_errno, NULL, NULL);
9973 }
9974
9975 /* Read value of symbolic link FILENAME on the remote target. Return
9976 a null-terminated string allocated via xmalloc, or NULL if an error
9977 occurs (and set *REMOTE_ERRNO). */
9978
9979 static char *
9980 remote_hostio_readlink (const char *filename, int *remote_errno)
9981 {
9982 struct remote_state *rs = get_remote_state ();
9983 char *p = rs->buf;
9984 char *attachment;
9985 int left = get_remote_packet_size ();
9986 int len, attachment_len;
9987 int read_len;
9988 char *ret;
9989
9990 remote_buffer_add_string (&p, &left, "vFile:readlink:");
9991
9992 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9993 strlen (filename));
9994
9995 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
9996 remote_errno, &attachment,
9997 &attachment_len);
9998
9999 if (len < 0)
10000 return NULL;
10001
10002 ret = xmalloc (len + 1);
10003
10004 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10005 (gdb_byte *) ret, len);
10006 if (read_len != len)
10007 error (_("Readlink returned %d, but %d bytes."), len, read_len);
10008
10009 ret[len] = '\0';
10010 return ret;
10011 }
10012
10013 static int
10014 remote_fileio_errno_to_host (int errnum)
10015 {
10016 switch (errnum)
10017 {
10018 case FILEIO_EPERM:
10019 return EPERM;
10020 case FILEIO_ENOENT:
10021 return ENOENT;
10022 case FILEIO_EINTR:
10023 return EINTR;
10024 case FILEIO_EIO:
10025 return EIO;
10026 case FILEIO_EBADF:
10027 return EBADF;
10028 case FILEIO_EACCES:
10029 return EACCES;
10030 case FILEIO_EFAULT:
10031 return EFAULT;
10032 case FILEIO_EBUSY:
10033 return EBUSY;
10034 case FILEIO_EEXIST:
10035 return EEXIST;
10036 case FILEIO_ENODEV:
10037 return ENODEV;
10038 case FILEIO_ENOTDIR:
10039 return ENOTDIR;
10040 case FILEIO_EISDIR:
10041 return EISDIR;
10042 case FILEIO_EINVAL:
10043 return EINVAL;
10044 case FILEIO_ENFILE:
10045 return ENFILE;
10046 case FILEIO_EMFILE:
10047 return EMFILE;
10048 case FILEIO_EFBIG:
10049 return EFBIG;
10050 case FILEIO_ENOSPC:
10051 return ENOSPC;
10052 case FILEIO_ESPIPE:
10053 return ESPIPE;
10054 case FILEIO_EROFS:
10055 return EROFS;
10056 case FILEIO_ENOSYS:
10057 return ENOSYS;
10058 case FILEIO_ENAMETOOLONG:
10059 return ENAMETOOLONG;
10060 }
10061 return -1;
10062 }
10063
10064 static char *
10065 remote_hostio_error (int errnum)
10066 {
10067 int host_error = remote_fileio_errno_to_host (errnum);
10068
10069 if (host_error == -1)
10070 error (_("Unknown remote I/O error %d"), errnum);
10071 else
10072 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10073 }
10074
10075 static void
10076 remote_hostio_close_cleanup (void *opaque)
10077 {
10078 int fd = *(int *) opaque;
10079 int remote_errno;
10080
10081 remote_hostio_close (fd, &remote_errno);
10082 }
10083
10084
10085 static void *
10086 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
10087 {
10088 const char *filename = bfd_get_filename (abfd);
10089 int fd, remote_errno;
10090 int *stream;
10091
10092 gdb_assert (remote_filename_p (filename));
10093
10094 fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
10095 if (fd == -1)
10096 {
10097 errno = remote_fileio_errno_to_host (remote_errno);
10098 bfd_set_error (bfd_error_system_call);
10099 return NULL;
10100 }
10101
10102 stream = xmalloc (sizeof (int));
10103 *stream = fd;
10104 return stream;
10105 }
10106
10107 static int
10108 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
10109 {
10110 int fd = *(int *)stream;
10111 int remote_errno;
10112
10113 xfree (stream);
10114
10115 /* Ignore errors on close; these may happen if the remote
10116 connection was already torn down. */
10117 remote_hostio_close (fd, &remote_errno);
10118
10119 /* Zero means success. */
10120 return 0;
10121 }
10122
10123 static file_ptr
10124 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
10125 file_ptr nbytes, file_ptr offset)
10126 {
10127 int fd = *(int *)stream;
10128 int remote_errno;
10129 file_ptr pos, bytes;
10130
10131 pos = 0;
10132 while (nbytes > pos)
10133 {
10134 bytes = remote_hostio_pread (fd, (gdb_byte *) buf + pos, nbytes - pos,
10135 offset + pos, &remote_errno);
10136 if (bytes == 0)
10137 /* Success, but no bytes, means end-of-file. */
10138 break;
10139 if (bytes == -1)
10140 {
10141 errno = remote_fileio_errno_to_host (remote_errno);
10142 bfd_set_error (bfd_error_system_call);
10143 return -1;
10144 }
10145
10146 pos += bytes;
10147 }
10148
10149 return pos;
10150 }
10151
10152 static int
10153 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
10154 {
10155 /* FIXME: We should probably implement remote_hostio_stat. */
10156 sb->st_size = INT_MAX;
10157 return 0;
10158 }
10159
10160 int
10161 remote_filename_p (const char *filename)
10162 {
10163 return strncmp (filename,
10164 REMOTE_SYSROOT_PREFIX,
10165 sizeof (REMOTE_SYSROOT_PREFIX) - 1) == 0;
10166 }
10167
10168 bfd *
10169 remote_bfd_open (const char *remote_file, const char *target)
10170 {
10171 bfd *abfd = gdb_bfd_openr_iovec (remote_file, target,
10172 remote_bfd_iovec_open, NULL,
10173 remote_bfd_iovec_pread,
10174 remote_bfd_iovec_close,
10175 remote_bfd_iovec_stat);
10176
10177 return abfd;
10178 }
10179
10180 void
10181 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10182 {
10183 struct cleanup *back_to, *close_cleanup;
10184 int retcode, fd, remote_errno, bytes, io_size;
10185 FILE *file;
10186 gdb_byte *buffer;
10187 int bytes_in_buffer;
10188 int saw_eof;
10189 ULONGEST offset;
10190 struct remote_state *rs = get_remote_state ();
10191
10192 if (!rs->remote_desc)
10193 error (_("command can only be used with remote target"));
10194
10195 file = gdb_fopen_cloexec (local_file, "rb");
10196 if (file == NULL)
10197 perror_with_name (local_file);
10198 back_to = make_cleanup_fclose (file);
10199
10200 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
10201 | FILEIO_O_TRUNC),
10202 0700, &remote_errno);
10203 if (fd == -1)
10204 remote_hostio_error (remote_errno);
10205
10206 /* Send up to this many bytes at once. They won't all fit in the
10207 remote packet limit, so we'll transfer slightly fewer. */
10208 io_size = get_remote_packet_size ();
10209 buffer = xmalloc (io_size);
10210 make_cleanup (xfree, buffer);
10211
10212 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10213
10214 bytes_in_buffer = 0;
10215 saw_eof = 0;
10216 offset = 0;
10217 while (bytes_in_buffer || !saw_eof)
10218 {
10219 if (!saw_eof)
10220 {
10221 bytes = fread (buffer + bytes_in_buffer, 1,
10222 io_size - bytes_in_buffer,
10223 file);
10224 if (bytes == 0)
10225 {
10226 if (ferror (file))
10227 error (_("Error reading %s."), local_file);
10228 else
10229 {
10230 /* EOF. Unless there is something still in the
10231 buffer from the last iteration, we are done. */
10232 saw_eof = 1;
10233 if (bytes_in_buffer == 0)
10234 break;
10235 }
10236 }
10237 }
10238 else
10239 bytes = 0;
10240
10241 bytes += bytes_in_buffer;
10242 bytes_in_buffer = 0;
10243
10244 retcode = remote_hostio_pwrite (fd, buffer, bytes,
10245 offset, &remote_errno);
10246
10247 if (retcode < 0)
10248 remote_hostio_error (remote_errno);
10249 else if (retcode == 0)
10250 error (_("Remote write of %d bytes returned 0!"), bytes);
10251 else if (retcode < bytes)
10252 {
10253 /* Short write. Save the rest of the read data for the next
10254 write. */
10255 bytes_in_buffer = bytes - retcode;
10256 memmove (buffer, buffer + retcode, bytes_in_buffer);
10257 }
10258
10259 offset += retcode;
10260 }
10261
10262 discard_cleanups (close_cleanup);
10263 if (remote_hostio_close (fd, &remote_errno))
10264 remote_hostio_error (remote_errno);
10265
10266 if (from_tty)
10267 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10268 do_cleanups (back_to);
10269 }
10270
10271 void
10272 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10273 {
10274 struct cleanup *back_to, *close_cleanup;
10275 int fd, remote_errno, bytes, io_size;
10276 FILE *file;
10277 gdb_byte *buffer;
10278 ULONGEST offset;
10279 struct remote_state *rs = get_remote_state ();
10280
10281 if (!rs->remote_desc)
10282 error (_("command can only be used with remote target"));
10283
10284 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
10285 if (fd == -1)
10286 remote_hostio_error (remote_errno);
10287
10288 file = gdb_fopen_cloexec (local_file, "wb");
10289 if (file == NULL)
10290 perror_with_name (local_file);
10291 back_to = make_cleanup_fclose (file);
10292
10293 /* Send up to this many bytes at once. They won't all fit in the
10294 remote packet limit, so we'll transfer slightly fewer. */
10295 io_size = get_remote_packet_size ();
10296 buffer = xmalloc (io_size);
10297 make_cleanup (xfree, buffer);
10298
10299 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10300
10301 offset = 0;
10302 while (1)
10303 {
10304 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
10305 if (bytes == 0)
10306 /* Success, but no bytes, means end-of-file. */
10307 break;
10308 if (bytes == -1)
10309 remote_hostio_error (remote_errno);
10310
10311 offset += bytes;
10312
10313 bytes = fwrite (buffer, 1, bytes, file);
10314 if (bytes == 0)
10315 perror_with_name (local_file);
10316 }
10317
10318 discard_cleanups (close_cleanup);
10319 if (remote_hostio_close (fd, &remote_errno))
10320 remote_hostio_error (remote_errno);
10321
10322 if (from_tty)
10323 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10324 do_cleanups (back_to);
10325 }
10326
10327 void
10328 remote_file_delete (const char *remote_file, int from_tty)
10329 {
10330 int retcode, remote_errno;
10331 struct remote_state *rs = get_remote_state ();
10332
10333 if (!rs->remote_desc)
10334 error (_("command can only be used with remote target"));
10335
10336 retcode = remote_hostio_unlink (remote_file, &remote_errno);
10337 if (retcode == -1)
10338 remote_hostio_error (remote_errno);
10339
10340 if (from_tty)
10341 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10342 }
10343
10344 static void
10345 remote_put_command (char *args, int from_tty)
10346 {
10347 struct cleanup *back_to;
10348 char **argv;
10349
10350 if (args == NULL)
10351 error_no_arg (_("file to put"));
10352
10353 argv = gdb_buildargv (args);
10354 back_to = make_cleanup_freeargv (argv);
10355 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10356 error (_("Invalid parameters to remote put"));
10357
10358 remote_file_put (argv[0], argv[1], from_tty);
10359
10360 do_cleanups (back_to);
10361 }
10362
10363 static void
10364 remote_get_command (char *args, int from_tty)
10365 {
10366 struct cleanup *back_to;
10367 char **argv;
10368
10369 if (args == NULL)
10370 error_no_arg (_("file to get"));
10371
10372 argv = gdb_buildargv (args);
10373 back_to = make_cleanup_freeargv (argv);
10374 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10375 error (_("Invalid parameters to remote get"));
10376
10377 remote_file_get (argv[0], argv[1], from_tty);
10378
10379 do_cleanups (back_to);
10380 }
10381
10382 static void
10383 remote_delete_command (char *args, int from_tty)
10384 {
10385 struct cleanup *back_to;
10386 char **argv;
10387
10388 if (args == NULL)
10389 error_no_arg (_("file to delete"));
10390
10391 argv = gdb_buildargv (args);
10392 back_to = make_cleanup_freeargv (argv);
10393 if (argv[0] == NULL || argv[1] != NULL)
10394 error (_("Invalid parameters to remote delete"));
10395
10396 remote_file_delete (argv[0], from_tty);
10397
10398 do_cleanups (back_to);
10399 }
10400
10401 static void
10402 remote_command (char *args, int from_tty)
10403 {
10404 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
10405 }
10406
10407 static int
10408 remote_can_execute_reverse (void)
10409 {
10410 if (remote_protocol_packets[PACKET_bs].support == PACKET_ENABLE
10411 || remote_protocol_packets[PACKET_bc].support == PACKET_ENABLE)
10412 return 1;
10413 else
10414 return 0;
10415 }
10416
10417 static int
10418 remote_supports_non_stop (void)
10419 {
10420 return 1;
10421 }
10422
10423 static int
10424 remote_supports_disable_randomization (void)
10425 {
10426 /* Only supported in extended mode. */
10427 return 0;
10428 }
10429
10430 static int
10431 remote_supports_multi_process (void)
10432 {
10433 struct remote_state *rs = get_remote_state ();
10434
10435 /* Only extended-remote handles being attached to multiple
10436 processes, even though plain remote can use the multi-process
10437 thread id extensions, so that GDB knows the target process's
10438 PID. */
10439 return rs->extended && remote_multi_process_p (rs);
10440 }
10441
10442 static int
10443 remote_supports_cond_tracepoints (void)
10444 {
10445 struct remote_state *rs = get_remote_state ();
10446
10447 return rs->cond_tracepoints;
10448 }
10449
10450 static int
10451 remote_supports_cond_breakpoints (void)
10452 {
10453 struct remote_state *rs = get_remote_state ();
10454
10455 return rs->cond_breakpoints;
10456 }
10457
10458 static int
10459 remote_supports_fast_tracepoints (void)
10460 {
10461 struct remote_state *rs = get_remote_state ();
10462
10463 return rs->fast_tracepoints;
10464 }
10465
10466 static int
10467 remote_supports_static_tracepoints (void)
10468 {
10469 struct remote_state *rs = get_remote_state ();
10470
10471 return rs->static_tracepoints;
10472 }
10473
10474 static int
10475 remote_supports_install_in_trace (void)
10476 {
10477 struct remote_state *rs = get_remote_state ();
10478
10479 return rs->install_in_trace;
10480 }
10481
10482 static int
10483 remote_supports_enable_disable_tracepoint (void)
10484 {
10485 struct remote_state *rs = get_remote_state ();
10486
10487 return rs->enable_disable_tracepoints;
10488 }
10489
10490 static int
10491 remote_supports_string_tracing (void)
10492 {
10493 struct remote_state *rs = get_remote_state ();
10494
10495 return rs->string_tracing;
10496 }
10497
10498 static int
10499 remote_can_run_breakpoint_commands (void)
10500 {
10501 struct remote_state *rs = get_remote_state ();
10502
10503 return rs->breakpoint_commands;
10504 }
10505
10506 static void
10507 remote_trace_init (void)
10508 {
10509 putpkt ("QTinit");
10510 remote_get_noisy_reply (&target_buf, &target_buf_size);
10511 if (strcmp (target_buf, "OK") != 0)
10512 error (_("Target does not support this command."));
10513 }
10514
10515 static void free_actions_list (char **actions_list);
10516 static void free_actions_list_cleanup_wrapper (void *);
10517 static void
10518 free_actions_list_cleanup_wrapper (void *al)
10519 {
10520 free_actions_list (al);
10521 }
10522
10523 static void
10524 free_actions_list (char **actions_list)
10525 {
10526 int ndx;
10527
10528 if (actions_list == 0)
10529 return;
10530
10531 for (ndx = 0; actions_list[ndx]; ndx++)
10532 xfree (actions_list[ndx]);
10533
10534 xfree (actions_list);
10535 }
10536
10537 /* Recursive routine to walk through command list including loops, and
10538 download packets for each command. */
10539
10540 static void
10541 remote_download_command_source (int num, ULONGEST addr,
10542 struct command_line *cmds)
10543 {
10544 struct remote_state *rs = get_remote_state ();
10545 struct command_line *cmd;
10546
10547 for (cmd = cmds; cmd; cmd = cmd->next)
10548 {
10549 QUIT; /* Allow user to bail out with ^C. */
10550 strcpy (rs->buf, "QTDPsrc:");
10551 encode_source_string (num, addr, "cmd", cmd->line,
10552 rs->buf + strlen (rs->buf),
10553 rs->buf_size - strlen (rs->buf));
10554 putpkt (rs->buf);
10555 remote_get_noisy_reply (&target_buf, &target_buf_size);
10556 if (strcmp (target_buf, "OK"))
10557 warning (_("Target does not support source download."));
10558
10559 if (cmd->control_type == while_control
10560 || cmd->control_type == while_stepping_control)
10561 {
10562 remote_download_command_source (num, addr, *cmd->body_list);
10563
10564 QUIT; /* Allow user to bail out with ^C. */
10565 strcpy (rs->buf, "QTDPsrc:");
10566 encode_source_string (num, addr, "cmd", "end",
10567 rs->buf + strlen (rs->buf),
10568 rs->buf_size - strlen (rs->buf));
10569 putpkt (rs->buf);
10570 remote_get_noisy_reply (&target_buf, &target_buf_size);
10571 if (strcmp (target_buf, "OK"))
10572 warning (_("Target does not support source download."));
10573 }
10574 }
10575 }
10576
10577 static void
10578 remote_download_tracepoint (struct bp_location *loc)
10579 {
10580 #define BUF_SIZE 2048
10581
10582 CORE_ADDR tpaddr;
10583 char addrbuf[40];
10584 char buf[BUF_SIZE];
10585 char **tdp_actions;
10586 char **stepping_actions;
10587 int ndx;
10588 struct cleanup *old_chain = NULL;
10589 struct agent_expr *aexpr;
10590 struct cleanup *aexpr_chain = NULL;
10591 char *pkt;
10592 struct breakpoint *b = loc->owner;
10593 struct tracepoint *t = (struct tracepoint *) b;
10594
10595 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
10596 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10597 tdp_actions);
10598 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10599 stepping_actions);
10600
10601 tpaddr = loc->address;
10602 sprintf_vma (addrbuf, tpaddr);
10603 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10604 addrbuf, /* address */
10605 (b->enable_state == bp_enabled ? 'E' : 'D'),
10606 t->step_count, t->pass_count);
10607 /* Fast tracepoints are mostly handled by the target, but we can
10608 tell the target how big of an instruction block should be moved
10609 around. */
10610 if (b->type == bp_fast_tracepoint)
10611 {
10612 /* Only test for support at download time; we may not know
10613 target capabilities at definition time. */
10614 if (remote_supports_fast_tracepoints ())
10615 {
10616 int isize;
10617
10618 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
10619 tpaddr, &isize, NULL))
10620 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10621 isize);
10622 else
10623 /* If it passed validation at definition but fails now,
10624 something is very wrong. */
10625 internal_error (__FILE__, __LINE__,
10626 _("Fast tracepoint not "
10627 "valid during download"));
10628 }
10629 else
10630 /* Fast tracepoints are functionally identical to regular
10631 tracepoints, so don't take lack of support as a reason to
10632 give up on the trace run. */
10633 warning (_("Target does not support fast tracepoints, "
10634 "downloading %d as regular tracepoint"), b->number);
10635 }
10636 else if (b->type == bp_static_tracepoint)
10637 {
10638 /* Only test for support at download time; we may not know
10639 target capabilities at definition time. */
10640 if (remote_supports_static_tracepoints ())
10641 {
10642 struct static_tracepoint_marker marker;
10643
10644 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10645 strcat (buf, ":S");
10646 else
10647 error (_("Static tracepoint not valid during download"));
10648 }
10649 else
10650 /* Fast tracepoints are functionally identical to regular
10651 tracepoints, so don't take lack of support as a reason
10652 to give up on the trace run. */
10653 error (_("Target does not support static tracepoints"));
10654 }
10655 /* If the tracepoint has a conditional, make it into an agent
10656 expression and append to the definition. */
10657 if (loc->cond)
10658 {
10659 /* Only test support at download time, we may not know target
10660 capabilities at definition time. */
10661 if (remote_supports_cond_tracepoints ())
10662 {
10663 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10664 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
10665 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10666 aexpr->len);
10667 pkt = buf + strlen (buf);
10668 for (ndx = 0; ndx < aexpr->len; ++ndx)
10669 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10670 *pkt = '\0';
10671 do_cleanups (aexpr_chain);
10672 }
10673 else
10674 warning (_("Target does not support conditional tracepoints, "
10675 "ignoring tp %d cond"), b->number);
10676 }
10677
10678 if (b->commands || *default_collect)
10679 strcat (buf, "-");
10680 putpkt (buf);
10681 remote_get_noisy_reply (&target_buf, &target_buf_size);
10682 if (strcmp (target_buf, "OK"))
10683 error (_("Target does not support tracepoints."));
10684
10685 /* do_single_steps (t); */
10686 if (tdp_actions)
10687 {
10688 for (ndx = 0; tdp_actions[ndx]; ndx++)
10689 {
10690 QUIT; /* Allow user to bail out with ^C. */
10691 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10692 b->number, addrbuf, /* address */
10693 tdp_actions[ndx],
10694 ((tdp_actions[ndx + 1] || stepping_actions)
10695 ? '-' : 0));
10696 putpkt (buf);
10697 remote_get_noisy_reply (&target_buf,
10698 &target_buf_size);
10699 if (strcmp (target_buf, "OK"))
10700 error (_("Error on target while setting tracepoints."));
10701 }
10702 }
10703 if (stepping_actions)
10704 {
10705 for (ndx = 0; stepping_actions[ndx]; ndx++)
10706 {
10707 QUIT; /* Allow user to bail out with ^C. */
10708 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10709 b->number, addrbuf, /* address */
10710 ((ndx == 0) ? "S" : ""),
10711 stepping_actions[ndx],
10712 (stepping_actions[ndx + 1] ? "-" : ""));
10713 putpkt (buf);
10714 remote_get_noisy_reply (&target_buf,
10715 &target_buf_size);
10716 if (strcmp (target_buf, "OK"))
10717 error (_("Error on target while setting tracepoints."));
10718 }
10719 }
10720
10721 if (remote_protocol_packets[PACKET_TracepointSource].support
10722 == PACKET_ENABLE)
10723 {
10724 if (b->addr_string)
10725 {
10726 strcpy (buf, "QTDPsrc:");
10727 encode_source_string (b->number, loc->address,
10728 "at", b->addr_string, buf + strlen (buf),
10729 2048 - strlen (buf));
10730
10731 putpkt (buf);
10732 remote_get_noisy_reply (&target_buf, &target_buf_size);
10733 if (strcmp (target_buf, "OK"))
10734 warning (_("Target does not support source download."));
10735 }
10736 if (b->cond_string)
10737 {
10738 strcpy (buf, "QTDPsrc:");
10739 encode_source_string (b->number, loc->address,
10740 "cond", b->cond_string, buf + strlen (buf),
10741 2048 - strlen (buf));
10742 putpkt (buf);
10743 remote_get_noisy_reply (&target_buf, &target_buf_size);
10744 if (strcmp (target_buf, "OK"))
10745 warning (_("Target does not support source download."));
10746 }
10747 remote_download_command_source (b->number, loc->address,
10748 breakpoint_commands (b));
10749 }
10750
10751 do_cleanups (old_chain);
10752 }
10753
10754 static int
10755 remote_can_download_tracepoint (void)
10756 {
10757 struct remote_state *rs = get_remote_state ();
10758 struct trace_status *ts;
10759 int status;
10760
10761 /* Don't try to install tracepoints until we've relocated our
10762 symbols, and fetched and merged the target's tracepoint list with
10763 ours. */
10764 if (rs->starting_up)
10765 return 0;
10766
10767 ts = current_trace_status ();
10768 status = remote_get_trace_status (ts);
10769
10770 if (status == -1 || !ts->running_known || !ts->running)
10771 return 0;
10772
10773 /* If we are in a tracing experiment, but remote stub doesn't support
10774 installing tracepoint in trace, we have to return. */
10775 if (!remote_supports_install_in_trace ())
10776 return 0;
10777
10778 return 1;
10779 }
10780
10781
10782 static void
10783 remote_download_trace_state_variable (struct trace_state_variable *tsv)
10784 {
10785 struct remote_state *rs = get_remote_state ();
10786 char *p;
10787
10788 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10789 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10790 tsv->builtin);
10791 p = rs->buf + strlen (rs->buf);
10792 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10793 error (_("Trace state variable name too long for tsv definition packet"));
10794 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, 0);
10795 *p++ = '\0';
10796 putpkt (rs->buf);
10797 remote_get_noisy_reply (&target_buf, &target_buf_size);
10798 if (*target_buf == '\0')
10799 error (_("Target does not support this command."));
10800 if (strcmp (target_buf, "OK") != 0)
10801 error (_("Error on target while downloading trace state variable."));
10802 }
10803
10804 static void
10805 remote_enable_tracepoint (struct bp_location *location)
10806 {
10807 struct remote_state *rs = get_remote_state ();
10808 char addr_buf[40];
10809
10810 sprintf_vma (addr_buf, location->address);
10811 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10812 location->owner->number, addr_buf);
10813 putpkt (rs->buf);
10814 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10815 if (*rs->buf == '\0')
10816 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10817 if (strcmp (rs->buf, "OK") != 0)
10818 error (_("Error on target while enabling tracepoint."));
10819 }
10820
10821 static void
10822 remote_disable_tracepoint (struct bp_location *location)
10823 {
10824 struct remote_state *rs = get_remote_state ();
10825 char addr_buf[40];
10826
10827 sprintf_vma (addr_buf, location->address);
10828 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10829 location->owner->number, addr_buf);
10830 putpkt (rs->buf);
10831 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10832 if (*rs->buf == '\0')
10833 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10834 if (strcmp (rs->buf, "OK") != 0)
10835 error (_("Error on target while disabling tracepoint."));
10836 }
10837
10838 static void
10839 remote_trace_set_readonly_regions (void)
10840 {
10841 asection *s;
10842 bfd *abfd = NULL;
10843 bfd_size_type size;
10844 bfd_vma vma;
10845 int anysecs = 0;
10846 int offset = 0;
10847
10848 if (!exec_bfd)
10849 return; /* No information to give. */
10850
10851 strcpy (target_buf, "QTro");
10852 offset = strlen (target_buf);
10853 for (s = exec_bfd->sections; s; s = s->next)
10854 {
10855 char tmp1[40], tmp2[40];
10856 int sec_length;
10857
10858 if ((s->flags & SEC_LOAD) == 0 ||
10859 /* (s->flags & SEC_CODE) == 0 || */
10860 (s->flags & SEC_READONLY) == 0)
10861 continue;
10862
10863 anysecs = 1;
10864 vma = bfd_get_section_vma (abfd, s);
10865 size = bfd_get_section_size (s);
10866 sprintf_vma (tmp1, vma);
10867 sprintf_vma (tmp2, vma + size);
10868 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10869 if (offset + sec_length + 1 > target_buf_size)
10870 {
10871 if (remote_protocol_packets[PACKET_qXfer_traceframe_info].support
10872 != PACKET_ENABLE)
10873 warning (_("\
10874 Too many sections for read-only sections definition packet."));
10875 break;
10876 }
10877 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10878 tmp1, tmp2);
10879 offset += sec_length;
10880 }
10881 if (anysecs)
10882 {
10883 putpkt (target_buf);
10884 getpkt (&target_buf, &target_buf_size, 0);
10885 }
10886 }
10887
10888 static void
10889 remote_trace_start (void)
10890 {
10891 putpkt ("QTStart");
10892 remote_get_noisy_reply (&target_buf, &target_buf_size);
10893 if (*target_buf == '\0')
10894 error (_("Target does not support this command."));
10895 if (strcmp (target_buf, "OK") != 0)
10896 error (_("Bogus reply from target: %s"), target_buf);
10897 }
10898
10899 static int
10900 remote_get_trace_status (struct trace_status *ts)
10901 {
10902 /* Initialize it just to avoid a GCC false warning. */
10903 char *p = NULL;
10904 /* FIXME we need to get register block size some other way. */
10905 extern int trace_regblock_size;
10906 volatile struct gdb_exception ex;
10907 enum packet_result result;
10908
10909 if (remote_protocol_packets[PACKET_qTStatus].support == PACKET_DISABLE)
10910 return -1;
10911
10912 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10913
10914 putpkt ("qTStatus");
10915
10916 TRY_CATCH (ex, RETURN_MASK_ERROR)
10917 {
10918 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10919 }
10920 if (ex.reason < 0)
10921 {
10922 if (ex.error != TARGET_CLOSE_ERROR)
10923 {
10924 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10925 return -1;
10926 }
10927 throw_exception (ex);
10928 }
10929
10930 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
10931
10932 /* If the remote target doesn't do tracing, flag it. */
10933 if (result == PACKET_UNKNOWN)
10934 return -1;
10935
10936 /* We're working with a live target. */
10937 ts->filename = NULL;
10938
10939 if (*p++ != 'T')
10940 error (_("Bogus trace status reply from target: %s"), target_buf);
10941
10942 /* Function 'parse_trace_status' sets default value of each field of
10943 'ts' at first, so we don't have to do it here. */
10944 parse_trace_status (p, ts);
10945
10946 return ts->running;
10947 }
10948
10949 static void
10950 remote_get_tracepoint_status (struct breakpoint *bp,
10951 struct uploaded_tp *utp)
10952 {
10953 struct remote_state *rs = get_remote_state ();
10954 char *reply;
10955 struct bp_location *loc;
10956 struct tracepoint *tp = (struct tracepoint *) bp;
10957 size_t size = get_remote_packet_size ();
10958
10959 if (tp)
10960 {
10961 tp->base.hit_count = 0;
10962 tp->traceframe_usage = 0;
10963 for (loc = tp->base.loc; loc; loc = loc->next)
10964 {
10965 /* If the tracepoint was never downloaded, don't go asking for
10966 any status. */
10967 if (tp->number_on_target == 0)
10968 continue;
10969 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
10970 phex_nz (loc->address, 0));
10971 putpkt (rs->buf);
10972 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10973 if (reply && *reply)
10974 {
10975 if (*reply == 'V')
10976 parse_tracepoint_status (reply + 1, bp, utp);
10977 }
10978 }
10979 }
10980 else if (utp)
10981 {
10982 utp->hit_count = 0;
10983 utp->traceframe_usage = 0;
10984 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
10985 phex_nz (utp->addr, 0));
10986 putpkt (rs->buf);
10987 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10988 if (reply && *reply)
10989 {
10990 if (*reply == 'V')
10991 parse_tracepoint_status (reply + 1, bp, utp);
10992 }
10993 }
10994 }
10995
10996 static void
10997 remote_trace_stop (void)
10998 {
10999 putpkt ("QTStop");
11000 remote_get_noisy_reply (&target_buf, &target_buf_size);
11001 if (*target_buf == '\0')
11002 error (_("Target does not support this command."));
11003 if (strcmp (target_buf, "OK") != 0)
11004 error (_("Bogus reply from target: %s"), target_buf);
11005 }
11006
11007 static int
11008 remote_trace_find (enum trace_find_type type, int num,
11009 CORE_ADDR addr1, CORE_ADDR addr2,
11010 int *tpp)
11011 {
11012 struct remote_state *rs = get_remote_state ();
11013 char *endbuf = rs->buf + get_remote_packet_size ();
11014 char *p, *reply;
11015 int target_frameno = -1, target_tracept = -1;
11016
11017 /* Lookups other than by absolute frame number depend on the current
11018 trace selected, so make sure it is correct on the remote end
11019 first. */
11020 if (type != tfind_number)
11021 set_remote_traceframe ();
11022
11023 p = rs->buf;
11024 strcpy (p, "QTFrame:");
11025 p = strchr (p, '\0');
11026 switch (type)
11027 {
11028 case tfind_number:
11029 xsnprintf (p, endbuf - p, "%x", num);
11030 break;
11031 case tfind_pc:
11032 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
11033 break;
11034 case tfind_tp:
11035 xsnprintf (p, endbuf - p, "tdp:%x", num);
11036 break;
11037 case tfind_range:
11038 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11039 phex_nz (addr2, 0));
11040 break;
11041 case tfind_outside:
11042 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11043 phex_nz (addr2, 0));
11044 break;
11045 default:
11046 error (_("Unknown trace find type %d"), type);
11047 }
11048
11049 putpkt (rs->buf);
11050 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
11051 if (*reply == '\0')
11052 error (_("Target does not support this command."));
11053
11054 while (reply && *reply)
11055 switch (*reply)
11056 {
11057 case 'F':
11058 p = ++reply;
11059 target_frameno = (int) strtol (p, &reply, 16);
11060 if (reply == p)
11061 error (_("Unable to parse trace frame number"));
11062 /* Don't update our remote traceframe number cache on failure
11063 to select a remote traceframe. */
11064 if (target_frameno == -1)
11065 return -1;
11066 break;
11067 case 'T':
11068 p = ++reply;
11069 target_tracept = (int) strtol (p, &reply, 16);
11070 if (reply == p)
11071 error (_("Unable to parse tracepoint number"));
11072 break;
11073 case 'O': /* "OK"? */
11074 if (reply[1] == 'K' && reply[2] == '\0')
11075 reply += 2;
11076 else
11077 error (_("Bogus reply from target: %s"), reply);
11078 break;
11079 default:
11080 error (_("Bogus reply from target: %s"), reply);
11081 }
11082 if (tpp)
11083 *tpp = target_tracept;
11084
11085 rs->remote_traceframe_number = target_frameno;
11086 return target_frameno;
11087 }
11088
11089 static int
11090 remote_get_trace_state_variable_value (int tsvnum, LONGEST *val)
11091 {
11092 struct remote_state *rs = get_remote_state ();
11093 char *reply;
11094 ULONGEST uval;
11095
11096 set_remote_traceframe ();
11097
11098 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
11099 putpkt (rs->buf);
11100 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11101 if (reply && *reply)
11102 {
11103 if (*reply == 'V')
11104 {
11105 unpack_varlen_hex (reply + 1, &uval);
11106 *val = (LONGEST) uval;
11107 return 1;
11108 }
11109 }
11110 return 0;
11111 }
11112
11113 static int
11114 remote_save_trace_data (const char *filename)
11115 {
11116 struct remote_state *rs = get_remote_state ();
11117 char *p, *reply;
11118
11119 p = rs->buf;
11120 strcpy (p, "QTSave:");
11121 p += strlen (p);
11122 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11123 error (_("Remote file name too long for trace save packet"));
11124 p += 2 * bin2hex ((gdb_byte *) filename, p, 0);
11125 *p++ = '\0';
11126 putpkt (rs->buf);
11127 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11128 if (*reply == '\0')
11129 error (_("Target does not support this command."));
11130 if (strcmp (reply, "OK") != 0)
11131 error (_("Bogus reply from target: %s"), reply);
11132 return 0;
11133 }
11134
11135 /* This is basically a memory transfer, but needs to be its own packet
11136 because we don't know how the target actually organizes its trace
11137 memory, plus we want to be able to ask for as much as possible, but
11138 not be unhappy if we don't get as much as we ask for. */
11139
11140 static LONGEST
11141 remote_get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
11142 {
11143 struct remote_state *rs = get_remote_state ();
11144 char *reply;
11145 char *p;
11146 int rslt;
11147
11148 p = rs->buf;
11149 strcpy (p, "qTBuffer:");
11150 p += strlen (p);
11151 p += hexnumstr (p, offset);
11152 *p++ = ',';
11153 p += hexnumstr (p, len);
11154 *p++ = '\0';
11155
11156 putpkt (rs->buf);
11157 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11158 if (reply && *reply)
11159 {
11160 /* 'l' by itself means we're at the end of the buffer and
11161 there is nothing more to get. */
11162 if (*reply == 'l')
11163 return 0;
11164
11165 /* Convert the reply into binary. Limit the number of bytes to
11166 convert according to our passed-in buffer size, rather than
11167 what was returned in the packet; if the target is
11168 unexpectedly generous and gives us a bigger reply than we
11169 asked for, we don't want to crash. */
11170 rslt = hex2bin (target_buf, buf, len);
11171 return rslt;
11172 }
11173
11174 /* Something went wrong, flag as an error. */
11175 return -1;
11176 }
11177
11178 static void
11179 remote_set_disconnected_tracing (int val)
11180 {
11181 struct remote_state *rs = get_remote_state ();
11182
11183 if (rs->disconnected_tracing)
11184 {
11185 char *reply;
11186
11187 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
11188 putpkt (rs->buf);
11189 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11190 if (*reply == '\0')
11191 error (_("Target does not support this command."));
11192 if (strcmp (reply, "OK") != 0)
11193 error (_("Bogus reply from target: %s"), reply);
11194 }
11195 else if (val)
11196 warning (_("Target does not support disconnected tracing."));
11197 }
11198
11199 static int
11200 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11201 {
11202 struct thread_info *info = find_thread_ptid (ptid);
11203
11204 if (info && info->private)
11205 return info->private->core;
11206 return -1;
11207 }
11208
11209 static void
11210 remote_set_circular_trace_buffer (int val)
11211 {
11212 struct remote_state *rs = get_remote_state ();
11213 char *reply;
11214
11215 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
11216 putpkt (rs->buf);
11217 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11218 if (*reply == '\0')
11219 error (_("Target does not support this command."));
11220 if (strcmp (reply, "OK") != 0)
11221 error (_("Bogus reply from target: %s"), reply);
11222 }
11223
11224 static struct traceframe_info *
11225 remote_traceframe_info (void)
11226 {
11227 char *text;
11228
11229 /* If current traceframe is not selected, don't bother the remote
11230 stub. */
11231 if (get_traceframe_number () < 0)
11232 return NULL;
11233
11234 text = target_read_stralloc (&current_target,
11235 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11236 if (text != NULL)
11237 {
11238 struct traceframe_info *info;
11239 struct cleanup *back_to = make_cleanup (xfree, text);
11240
11241 info = parse_traceframe_info (text);
11242 do_cleanups (back_to);
11243 return info;
11244 }
11245
11246 return NULL;
11247 }
11248
11249 /* Handle the qTMinFTPILen packet. Returns the minimum length of
11250 instruction on which a fast tracepoint may be placed. Returns -1
11251 if the packet is not supported, and 0 if the minimum instruction
11252 length is unknown. */
11253
11254 static int
11255 remote_get_min_fast_tracepoint_insn_len (void)
11256 {
11257 struct remote_state *rs = get_remote_state ();
11258 char *reply;
11259
11260 /* If we're not debugging a process yet, the IPA can't be
11261 loaded. */
11262 if (!target_has_execution)
11263 return 0;
11264
11265 /* Make sure the remote is pointing at the right process. */
11266 set_general_process ();
11267
11268 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
11269 putpkt (rs->buf);
11270 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11271 if (*reply == '\0')
11272 return -1;
11273 else
11274 {
11275 ULONGEST min_insn_len;
11276
11277 unpack_varlen_hex (reply, &min_insn_len);
11278
11279 return (int) min_insn_len;
11280 }
11281 }
11282
11283 static void
11284 remote_set_trace_buffer_size (LONGEST val)
11285 {
11286 if (remote_protocol_packets[PACKET_QTBuffer_size].support
11287 != PACKET_DISABLE)
11288 {
11289 struct remote_state *rs = get_remote_state ();
11290 char *buf = rs->buf;
11291 char *endbuf = rs->buf + get_remote_packet_size ();
11292 enum packet_result result;
11293
11294 gdb_assert (val >= 0 || val == -1);
11295 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11296 /* Send -1 as literal "-1" to avoid host size dependency. */
11297 if (val < 0)
11298 {
11299 *buf++ = '-';
11300 buf += hexnumstr (buf, (ULONGEST) -val);
11301 }
11302 else
11303 buf += hexnumstr (buf, (ULONGEST) val);
11304
11305 putpkt (rs->buf);
11306 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11307 result = packet_ok (rs->buf,
11308 &remote_protocol_packets[PACKET_QTBuffer_size]);
11309
11310 if (result != PACKET_OK)
11311 warning (_("Bogus reply from target: %s"), rs->buf);
11312 }
11313 }
11314
11315 static int
11316 remote_set_trace_notes (const char *user, const char *notes,
11317 const char *stop_notes)
11318 {
11319 struct remote_state *rs = get_remote_state ();
11320 char *reply;
11321 char *buf = rs->buf;
11322 char *endbuf = rs->buf + get_remote_packet_size ();
11323 int nbytes;
11324
11325 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11326 if (user)
11327 {
11328 buf += xsnprintf (buf, endbuf - buf, "user:");
11329 nbytes = bin2hex ((gdb_byte *) user, buf, 0);
11330 buf += 2 * nbytes;
11331 *buf++ = ';';
11332 }
11333 if (notes)
11334 {
11335 buf += xsnprintf (buf, endbuf - buf, "notes:");
11336 nbytes = bin2hex ((gdb_byte *) notes, buf, 0);
11337 buf += 2 * nbytes;
11338 *buf++ = ';';
11339 }
11340 if (stop_notes)
11341 {
11342 buf += xsnprintf (buf, endbuf - buf, "tstop:");
11343 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, 0);
11344 buf += 2 * nbytes;
11345 *buf++ = ';';
11346 }
11347 /* Ensure the buffer is terminated. */
11348 *buf = '\0';
11349
11350 putpkt (rs->buf);
11351 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11352 if (*reply == '\0')
11353 return 0;
11354
11355 if (strcmp (reply, "OK") != 0)
11356 error (_("Bogus reply from target: %s"), reply);
11357
11358 return 1;
11359 }
11360
11361 static int
11362 remote_use_agent (int use)
11363 {
11364 if (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE)
11365 {
11366 struct remote_state *rs = get_remote_state ();
11367
11368 /* If the stub supports QAgent. */
11369 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
11370 putpkt (rs->buf);
11371 getpkt (&rs->buf, &rs->buf_size, 0);
11372
11373 if (strcmp (rs->buf, "OK") == 0)
11374 {
11375 use_agent = use;
11376 return 1;
11377 }
11378 }
11379
11380 return 0;
11381 }
11382
11383 static int
11384 remote_can_use_agent (void)
11385 {
11386 return (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE);
11387 }
11388
11389 struct btrace_target_info
11390 {
11391 /* The ptid of the traced thread. */
11392 ptid_t ptid;
11393 };
11394
11395 /* Check whether the target supports branch tracing. */
11396
11397 static int
11398 remote_supports_btrace (void)
11399 {
11400 if (remote_protocol_packets[PACKET_Qbtrace_off].support != PACKET_ENABLE)
11401 return 0;
11402 if (remote_protocol_packets[PACKET_Qbtrace_bts].support != PACKET_ENABLE)
11403 return 0;
11404 if (remote_protocol_packets[PACKET_qXfer_btrace].support != PACKET_ENABLE)
11405 return 0;
11406
11407 return 1;
11408 }
11409
11410 /* Enable branch tracing. */
11411
11412 static struct btrace_target_info *
11413 remote_enable_btrace (ptid_t ptid)
11414 {
11415 struct btrace_target_info *tinfo = NULL;
11416 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11417 struct remote_state *rs = get_remote_state ();
11418 char *buf = rs->buf;
11419 char *endbuf = rs->buf + get_remote_packet_size ();
11420
11421 if (packet->support != PACKET_ENABLE)
11422 error (_("Target does not support branch tracing."));
11423
11424 set_general_thread (ptid);
11425
11426 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11427 putpkt (rs->buf);
11428 getpkt (&rs->buf, &rs->buf_size, 0);
11429
11430 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11431 {
11432 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11433 error (_("Could not enable branch tracing for %s: %s"),
11434 target_pid_to_str (ptid), rs->buf + 2);
11435 else
11436 error (_("Could not enable branch tracing for %s."),
11437 target_pid_to_str (ptid));
11438 }
11439
11440 tinfo = xzalloc (sizeof (*tinfo));
11441 tinfo->ptid = ptid;
11442
11443 return tinfo;
11444 }
11445
11446 /* Disable branch tracing. */
11447
11448 static void
11449 remote_disable_btrace (struct btrace_target_info *tinfo)
11450 {
11451 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11452 struct remote_state *rs = get_remote_state ();
11453 char *buf = rs->buf;
11454 char *endbuf = rs->buf + get_remote_packet_size ();
11455
11456 if (packet->support != PACKET_ENABLE)
11457 error (_("Target does not support branch tracing."));
11458
11459 set_general_thread (tinfo->ptid);
11460
11461 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11462 putpkt (rs->buf);
11463 getpkt (&rs->buf, &rs->buf_size, 0);
11464
11465 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11466 {
11467 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11468 error (_("Could not disable branch tracing for %s: %s"),
11469 target_pid_to_str (tinfo->ptid), rs->buf + 2);
11470 else
11471 error (_("Could not disable branch tracing for %s."),
11472 target_pid_to_str (tinfo->ptid));
11473 }
11474
11475 xfree (tinfo);
11476 }
11477
11478 /* Teardown branch tracing. */
11479
11480 static void
11481 remote_teardown_btrace (struct btrace_target_info *tinfo)
11482 {
11483 /* We must not talk to the target during teardown. */
11484 xfree (tinfo);
11485 }
11486
11487 /* Read the branch trace. */
11488
11489 static VEC (btrace_block_s) *
11490 remote_read_btrace (struct btrace_target_info *tinfo,
11491 enum btrace_read_type type)
11492 {
11493 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11494 struct remote_state *rs = get_remote_state ();
11495 VEC (btrace_block_s) *btrace = NULL;
11496 const char *annex;
11497 char *xml;
11498
11499 if (packet->support != PACKET_ENABLE)
11500 error (_("Target does not support branch tracing."));
11501
11502 #if !defined(HAVE_LIBEXPAT)
11503 error (_("Cannot process branch tracing result. XML parsing not supported."));
11504 #endif
11505
11506 switch (type)
11507 {
11508 case BTRACE_READ_ALL:
11509 annex = "all";
11510 break;
11511 case BTRACE_READ_NEW:
11512 annex = "new";
11513 break;
11514 default:
11515 internal_error (__FILE__, __LINE__,
11516 _("Bad branch tracing read type: %u."),
11517 (unsigned int) type);
11518 }
11519
11520 xml = target_read_stralloc (&current_target,
11521 TARGET_OBJECT_BTRACE, annex);
11522 if (xml != NULL)
11523 {
11524 struct cleanup *cleanup = make_cleanup (xfree, xml);
11525
11526 btrace = parse_xml_btrace (xml);
11527 do_cleanups (cleanup);
11528 }
11529
11530 return btrace;
11531 }
11532
11533 static int
11534 remote_augmented_libraries_svr4_read (void)
11535 {
11536 struct remote_state *rs = get_remote_state ();
11537
11538 return rs->augmented_libraries_svr4_read;
11539 }
11540
11541 static void
11542 init_remote_ops (void)
11543 {
11544 remote_ops.to_shortname = "remote";
11545 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
11546 remote_ops.to_doc =
11547 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11548 Specify the serial device it is connected to\n\
11549 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
11550 remote_ops.to_open = remote_open;
11551 remote_ops.to_close = remote_close;
11552 remote_ops.to_detach = remote_detach;
11553 remote_ops.to_disconnect = remote_disconnect;
11554 remote_ops.to_resume = remote_resume;
11555 remote_ops.to_wait = remote_wait;
11556 remote_ops.to_fetch_registers = remote_fetch_registers;
11557 remote_ops.to_store_registers = remote_store_registers;
11558 remote_ops.to_prepare_to_store = remote_prepare_to_store;
11559 remote_ops.to_files_info = remote_files_info;
11560 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11561 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
11562 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11563 remote_ops.to_stopped_data_address = remote_stopped_data_address;
11564 remote_ops.to_watchpoint_addr_within_range =
11565 remote_watchpoint_addr_within_range;
11566 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11567 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11568 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
11569 remote_ops.to_region_ok_for_hw_watchpoint
11570 = remote_region_ok_for_hw_watchpoint;
11571 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11572 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
11573 remote_ops.to_kill = remote_kill;
11574 remote_ops.to_load = generic_load;
11575 remote_ops.to_mourn_inferior = remote_mourn;
11576 remote_ops.to_pass_signals = remote_pass_signals;
11577 remote_ops.to_program_signals = remote_program_signals;
11578 remote_ops.to_thread_alive = remote_thread_alive;
11579 remote_ops.to_find_new_threads = remote_threads_info;
11580 remote_ops.to_pid_to_str = remote_pid_to_str;
11581 remote_ops.to_extra_thread_info = remote_threads_extra_info;
11582 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
11583 remote_ops.to_stop = remote_stop;
11584 remote_ops.to_xfer_partial = remote_xfer_partial;
11585 remote_ops.to_rcmd = remote_rcmd;
11586 remote_ops.to_log_command = serial_log_command;
11587 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
11588 remote_ops.to_stratum = process_stratum;
11589 remote_ops.to_has_all_memory = default_child_has_all_memory;
11590 remote_ops.to_has_memory = default_child_has_memory;
11591 remote_ops.to_has_stack = default_child_has_stack;
11592 remote_ops.to_has_registers = default_child_has_registers;
11593 remote_ops.to_has_execution = default_child_has_execution;
11594 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
11595 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
11596 remote_ops.to_magic = OPS_MAGIC;
11597 remote_ops.to_memory_map = remote_memory_map;
11598 remote_ops.to_flash_erase = remote_flash_erase;
11599 remote_ops.to_flash_done = remote_flash_done;
11600 remote_ops.to_read_description = remote_read_description;
11601 remote_ops.to_search_memory = remote_search_memory;
11602 remote_ops.to_can_async_p = remote_can_async_p;
11603 remote_ops.to_is_async_p = remote_is_async_p;
11604 remote_ops.to_async = remote_async;
11605 remote_ops.to_terminal_inferior = remote_terminal_inferior;
11606 remote_ops.to_terminal_ours = remote_terminal_ours;
11607 remote_ops.to_supports_non_stop = remote_supports_non_stop;
11608 remote_ops.to_supports_multi_process = remote_supports_multi_process;
11609 remote_ops.to_supports_disable_randomization
11610 = remote_supports_disable_randomization;
11611 remote_ops.to_fileio_open = remote_hostio_open;
11612 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11613 remote_ops.to_fileio_pread = remote_hostio_pread;
11614 remote_ops.to_fileio_close = remote_hostio_close;
11615 remote_ops.to_fileio_unlink = remote_hostio_unlink;
11616 remote_ops.to_fileio_readlink = remote_hostio_readlink;
11617 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
11618 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
11619 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
11620 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
11621 remote_ops.to_trace_init = remote_trace_init;
11622 remote_ops.to_download_tracepoint = remote_download_tracepoint;
11623 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
11624 remote_ops.to_download_trace_state_variable
11625 = remote_download_trace_state_variable;
11626 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11627 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
11628 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11629 remote_ops.to_trace_start = remote_trace_start;
11630 remote_ops.to_get_trace_status = remote_get_trace_status;
11631 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
11632 remote_ops.to_trace_stop = remote_trace_stop;
11633 remote_ops.to_trace_find = remote_trace_find;
11634 remote_ops.to_get_trace_state_variable_value
11635 = remote_get_trace_state_variable_value;
11636 remote_ops.to_save_trace_data = remote_save_trace_data;
11637 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
11638 remote_ops.to_upload_trace_state_variables
11639 = remote_upload_trace_state_variables;
11640 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
11641 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
11642 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
11643 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
11644 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
11645 remote_ops.to_set_trace_notes = remote_set_trace_notes;
11646 remote_ops.to_core_of_thread = remote_core_of_thread;
11647 remote_ops.to_verify_memory = remote_verify_memory;
11648 remote_ops.to_get_tib_address = remote_get_tib_address;
11649 remote_ops.to_set_permissions = remote_set_permissions;
11650 remote_ops.to_static_tracepoint_marker_at
11651 = remote_static_tracepoint_marker_at;
11652 remote_ops.to_static_tracepoint_markers_by_strid
11653 = remote_static_tracepoint_markers_by_strid;
11654 remote_ops.to_traceframe_info = remote_traceframe_info;
11655 remote_ops.to_use_agent = remote_use_agent;
11656 remote_ops.to_can_use_agent = remote_can_use_agent;
11657 remote_ops.to_supports_btrace = remote_supports_btrace;
11658 remote_ops.to_enable_btrace = remote_enable_btrace;
11659 remote_ops.to_disable_btrace = remote_disable_btrace;
11660 remote_ops.to_teardown_btrace = remote_teardown_btrace;
11661 remote_ops.to_read_btrace = remote_read_btrace;
11662 remote_ops.to_augmented_libraries_svr4_read =
11663 remote_augmented_libraries_svr4_read;
11664 }
11665
11666 /* Set up the extended remote vector by making a copy of the standard
11667 remote vector and adding to it. */
11668
11669 static void
11670 init_extended_remote_ops (void)
11671 {
11672 extended_remote_ops = remote_ops;
11673
11674 extended_remote_ops.to_shortname = "extended-remote";
11675 extended_remote_ops.to_longname =
11676 "Extended remote serial target in gdb-specific protocol";
11677 extended_remote_ops.to_doc =
11678 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
11679 Specify the serial device it is connected to (e.g. /dev/ttya).";
11680 extended_remote_ops.to_open = extended_remote_open;
11681 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11682 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
11683 extended_remote_ops.to_detach = extended_remote_detach;
11684 extended_remote_ops.to_attach = extended_remote_attach;
11685 extended_remote_ops.to_kill = extended_remote_kill;
11686 extended_remote_ops.to_supports_disable_randomization
11687 = extended_remote_supports_disable_randomization;
11688 }
11689
11690 static int
11691 remote_can_async_p (void)
11692 {
11693 struct remote_state *rs = get_remote_state ();
11694
11695 if (!target_async_permitted)
11696 /* We only enable async when the user specifically asks for it. */
11697 return 0;
11698
11699 /* We're async whenever the serial device is. */
11700 return serial_can_async_p (rs->remote_desc);
11701 }
11702
11703 static int
11704 remote_is_async_p (void)
11705 {
11706 struct remote_state *rs = get_remote_state ();
11707
11708 if (!target_async_permitted)
11709 /* We only enable async when the user specifically asks for it. */
11710 return 0;
11711
11712 /* We're async whenever the serial device is. */
11713 return serial_is_async_p (rs->remote_desc);
11714 }
11715
11716 /* Pass the SERIAL event on and up to the client. One day this code
11717 will be able to delay notifying the client of an event until the
11718 point where an entire packet has been received. */
11719
11720 static serial_event_ftype remote_async_serial_handler;
11721
11722 static void
11723 remote_async_serial_handler (struct serial *scb, void *context)
11724 {
11725 struct remote_state *rs = context;
11726
11727 /* Don't propogate error information up to the client. Instead let
11728 the client find out about the error by querying the target. */
11729 rs->async_client_callback (INF_REG_EVENT, rs->async_client_context);
11730 }
11731
11732 static void
11733 remote_async_inferior_event_handler (gdb_client_data data)
11734 {
11735 inferior_event_handler (INF_REG_EVENT, NULL);
11736 }
11737
11738 static void
11739 remote_async (void (*callback) (enum inferior_event_type event_type,
11740 void *context), void *context)
11741 {
11742 struct remote_state *rs = get_remote_state ();
11743
11744 if (callback != NULL)
11745 {
11746 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
11747 rs->async_client_callback = callback;
11748 rs->async_client_context = context;
11749 }
11750 else
11751 serial_async (rs->remote_desc, NULL, NULL);
11752 }
11753
11754 static void
11755 set_remote_cmd (char *args, int from_tty)
11756 {
11757 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
11758 }
11759
11760 static void
11761 show_remote_cmd (char *args, int from_tty)
11762 {
11763 /* We can't just use cmd_show_list here, because we want to skip
11764 the redundant "show remote Z-packet" and the legacy aliases. */
11765 struct cleanup *showlist_chain;
11766 struct cmd_list_element *list = remote_show_cmdlist;
11767 struct ui_out *uiout = current_uiout;
11768
11769 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
11770 for (; list != NULL; list = list->next)
11771 if (strcmp (list->name, "Z-packet") == 0)
11772 continue;
11773 else if (list->type == not_set_cmd)
11774 /* Alias commands are exactly like the original, except they
11775 don't have the normal type. */
11776 continue;
11777 else
11778 {
11779 struct cleanup *option_chain
11780 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
11781
11782 ui_out_field_string (uiout, "name", list->name);
11783 ui_out_text (uiout, ": ");
11784 if (list->type == show_cmd)
11785 do_show_command ((char *) NULL, from_tty, list);
11786 else
11787 cmd_func (list, NULL, from_tty);
11788 /* Close the tuple. */
11789 do_cleanups (option_chain);
11790 }
11791
11792 /* Close the tuple. */
11793 do_cleanups (showlist_chain);
11794 }
11795
11796
11797 /* Function to be called whenever a new objfile (shlib) is detected. */
11798 static void
11799 remote_new_objfile (struct objfile *objfile)
11800 {
11801 struct remote_state *rs = get_remote_state ();
11802
11803 if (rs->remote_desc != 0) /* Have a remote connection. */
11804 remote_check_symbols ();
11805 }
11806
11807 /* Pull all the tracepoints defined on the target and create local
11808 data structures representing them. We don't want to create real
11809 tracepoints yet, we don't want to mess up the user's existing
11810 collection. */
11811
11812 static int
11813 remote_upload_tracepoints (struct uploaded_tp **utpp)
11814 {
11815 struct remote_state *rs = get_remote_state ();
11816 char *p;
11817
11818 /* Ask for a first packet of tracepoint definition. */
11819 putpkt ("qTfP");
11820 getpkt (&rs->buf, &rs->buf_size, 0);
11821 p = rs->buf;
11822 while (*p && *p != 'l')
11823 {
11824 parse_tracepoint_definition (p, utpp);
11825 /* Ask for another packet of tracepoint definition. */
11826 putpkt ("qTsP");
11827 getpkt (&rs->buf, &rs->buf_size, 0);
11828 p = rs->buf;
11829 }
11830 return 0;
11831 }
11832
11833 static int
11834 remote_upload_trace_state_variables (struct uploaded_tsv **utsvp)
11835 {
11836 struct remote_state *rs = get_remote_state ();
11837 char *p;
11838
11839 /* Ask for a first packet of variable definition. */
11840 putpkt ("qTfV");
11841 getpkt (&rs->buf, &rs->buf_size, 0);
11842 p = rs->buf;
11843 while (*p && *p != 'l')
11844 {
11845 parse_tsv_definition (p, utsvp);
11846 /* Ask for another packet of variable definition. */
11847 putpkt ("qTsV");
11848 getpkt (&rs->buf, &rs->buf_size, 0);
11849 p = rs->buf;
11850 }
11851 return 0;
11852 }
11853
11854 /* The "set/show range-stepping" show hook. */
11855
11856 static void
11857 show_range_stepping (struct ui_file *file, int from_tty,
11858 struct cmd_list_element *c,
11859 const char *value)
11860 {
11861 fprintf_filtered (file,
11862 _("Debugger's willingness to use range stepping "
11863 "is %s.\n"), value);
11864 }
11865
11866 /* The "set/show range-stepping" set hook. */
11867
11868 static void
11869 set_range_stepping (char *ignore_args, int from_tty,
11870 struct cmd_list_element *c)
11871 {
11872 struct remote_state *rs = get_remote_state ();
11873
11874 /* Whene enabling, check whether range stepping is actually
11875 supported by the target, and warn if not. */
11876 if (use_range_stepping)
11877 {
11878 if (rs->remote_desc != NULL)
11879 {
11880 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
11881 remote_vcont_probe (rs);
11882
11883 if (remote_protocol_packets[PACKET_vCont].support == PACKET_ENABLE
11884 && rs->supports_vCont.r)
11885 return;
11886 }
11887
11888 warning (_("Range stepping is not supported by the current target"));
11889 }
11890 }
11891
11892 void
11893 _initialize_remote (void)
11894 {
11895 struct remote_state *rs;
11896 struct cmd_list_element *cmd;
11897 const char *cmd_name;
11898
11899 /* architecture specific data */
11900 remote_gdbarch_data_handle =
11901 gdbarch_data_register_post_init (init_remote_state);
11902 remote_g_packet_data_handle =
11903 gdbarch_data_register_pre_init (remote_g_packet_data_init);
11904
11905 /* Initialize the per-target state. At the moment there is only one
11906 of these, not one per target. Only one target is active at a
11907 time. */
11908 remote_state = new_remote_state ();
11909
11910 init_remote_ops ();
11911 add_target (&remote_ops);
11912
11913 init_extended_remote_ops ();
11914 add_target (&extended_remote_ops);
11915
11916 /* Hook into new objfile notification. */
11917 observer_attach_new_objfile (remote_new_objfile);
11918 /* We're no longer interested in notification events of an inferior
11919 when it exits. */
11920 observer_attach_inferior_exit (discard_pending_stop_replies);
11921
11922 /* Set up signal handlers. */
11923 async_sigint_remote_token =
11924 create_async_signal_handler (async_remote_interrupt, NULL);
11925 async_sigint_remote_twice_token =
11926 create_async_signal_handler (async_remote_interrupt_twice, NULL);
11927
11928 #if 0
11929 init_remote_threadtests ();
11930 #endif
11931
11932 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
11933 /* set/show remote ... */
11934
11935 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
11936 Remote protocol specific variables\n\
11937 Configure various remote-protocol specific variables such as\n\
11938 the packets being used"),
11939 &remote_set_cmdlist, "set remote ",
11940 0 /* allow-unknown */, &setlist);
11941 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
11942 Remote protocol specific variables\n\
11943 Configure various remote-protocol specific variables such as\n\
11944 the packets being used"),
11945 &remote_show_cmdlist, "show remote ",
11946 0 /* allow-unknown */, &showlist);
11947
11948 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
11949 Compare section data on target to the exec file.\n\
11950 Argument is a single section name (default: all loaded sections)."),
11951 &cmdlist);
11952
11953 add_cmd ("packet", class_maintenance, packet_command, _("\
11954 Send an arbitrary packet to a remote target.\n\
11955 maintenance packet TEXT\n\
11956 If GDB is talking to an inferior via the GDB serial protocol, then\n\
11957 this command sends the string TEXT to the inferior, and displays the\n\
11958 response packet. GDB supplies the initial `$' character, and the\n\
11959 terminating `#' character and checksum."),
11960 &maintenancelist);
11961
11962 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
11963 Set whether to send break if interrupted."), _("\
11964 Show whether to send break if interrupted."), _("\
11965 If set, a break, instead of a cntrl-c, is sent to the remote target."),
11966 set_remotebreak, show_remotebreak,
11967 &setlist, &showlist);
11968 cmd_name = "remotebreak";
11969 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
11970 deprecate_cmd (cmd, "set remote interrupt-sequence");
11971 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
11972 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
11973 deprecate_cmd (cmd, "show remote interrupt-sequence");
11974
11975 add_setshow_enum_cmd ("interrupt-sequence", class_support,
11976 interrupt_sequence_modes, &interrupt_sequence_mode,
11977 _("\
11978 Set interrupt sequence to remote target."), _("\
11979 Show interrupt sequence to remote target."), _("\
11980 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
11981 NULL, show_interrupt_sequence,
11982 &remote_set_cmdlist,
11983 &remote_show_cmdlist);
11984
11985 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
11986 &interrupt_on_connect, _("\
11987 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11988 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11989 If set, interrupt sequence is sent to remote target."),
11990 NULL, NULL,
11991 &remote_set_cmdlist, &remote_show_cmdlist);
11992
11993 /* Install commands for configuring memory read/write packets. */
11994
11995 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
11996 Set the maximum number of bytes per memory write packet (deprecated)."),
11997 &setlist);
11998 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
11999 Show the maximum number of bytes per memory write packet (deprecated)."),
12000 &showlist);
12001 add_cmd ("memory-write-packet-size", no_class,
12002 set_memory_write_packet_size, _("\
12003 Set the maximum number of bytes per memory-write packet.\n\
12004 Specify the number of bytes in a packet or 0 (zero) for the\n\
12005 default packet size. The actual limit is further reduced\n\
12006 dependent on the target. Specify ``fixed'' to disable the\n\
12007 further restriction and ``limit'' to enable that restriction."),
12008 &remote_set_cmdlist);
12009 add_cmd ("memory-read-packet-size", no_class,
12010 set_memory_read_packet_size, _("\
12011 Set the maximum number of bytes per memory-read packet.\n\
12012 Specify the number of bytes in a packet or 0 (zero) for the\n\
12013 default packet size. The actual limit is further reduced\n\
12014 dependent on the target. Specify ``fixed'' to disable the\n\
12015 further restriction and ``limit'' to enable that restriction."),
12016 &remote_set_cmdlist);
12017 add_cmd ("memory-write-packet-size", no_class,
12018 show_memory_write_packet_size,
12019 _("Show the maximum number of bytes per memory-write packet."),
12020 &remote_show_cmdlist);
12021 add_cmd ("memory-read-packet-size", no_class,
12022 show_memory_read_packet_size,
12023 _("Show the maximum number of bytes per memory-read packet."),
12024 &remote_show_cmdlist);
12025
12026 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
12027 &remote_hw_watchpoint_limit, _("\
12028 Set the maximum number of target hardware watchpoints."), _("\
12029 Show the maximum number of target hardware watchpoints."), _("\
12030 Specify a negative limit for unlimited."),
12031 NULL, NULL, /* FIXME: i18n: The maximum
12032 number of target hardware
12033 watchpoints is %s. */
12034 &remote_set_cmdlist, &remote_show_cmdlist);
12035 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
12036 &remote_hw_watchpoint_length_limit, _("\
12037 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
12038 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
12039 Specify a negative limit for unlimited."),
12040 NULL, NULL, /* FIXME: i18n: The maximum
12041 length (in bytes) of a target
12042 hardware watchpoint is %s. */
12043 &remote_set_cmdlist, &remote_show_cmdlist);
12044 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
12045 &remote_hw_breakpoint_limit, _("\
12046 Set the maximum number of target hardware breakpoints."), _("\
12047 Show the maximum number of target hardware breakpoints."), _("\
12048 Specify a negative limit for unlimited."),
12049 NULL, NULL, /* FIXME: i18n: The maximum
12050 number of target hardware
12051 breakpoints is %s. */
12052 &remote_set_cmdlist, &remote_show_cmdlist);
12053
12054 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
12055 &remote_address_size, _("\
12056 Set the maximum size of the address (in bits) in a memory packet."), _("\
12057 Show the maximum size of the address (in bits) in a memory packet."), NULL,
12058 NULL,
12059 NULL, /* FIXME: i18n: */
12060 &setlist, &showlist);
12061
12062 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
12063 "X", "binary-download", 1);
12064
12065 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
12066 "vCont", "verbose-resume", 0);
12067
12068 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
12069 "QPassSignals", "pass-signals", 0);
12070
12071 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
12072 "QProgramSignals", "program-signals", 0);
12073
12074 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
12075 "qSymbol", "symbol-lookup", 0);
12076
12077 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
12078 "P", "set-register", 1);
12079
12080 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
12081 "p", "fetch-register", 1);
12082
12083 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
12084 "Z0", "software-breakpoint", 0);
12085
12086 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
12087 "Z1", "hardware-breakpoint", 0);
12088
12089 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
12090 "Z2", "write-watchpoint", 0);
12091
12092 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
12093 "Z3", "read-watchpoint", 0);
12094
12095 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
12096 "Z4", "access-watchpoint", 0);
12097
12098 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
12099 "qXfer:auxv:read", "read-aux-vector", 0);
12100
12101 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
12102 "qXfer:features:read", "target-features", 0);
12103
12104 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
12105 "qXfer:libraries:read", "library-info", 0);
12106
12107 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12108 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12109
12110 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12111 "qXfer:memory-map:read", "memory-map", 0);
12112
12113 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12114 "qXfer:spu:read", "read-spu-object", 0);
12115
12116 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12117 "qXfer:spu:write", "write-spu-object", 0);
12118
12119 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12120 "qXfer:osdata:read", "osdata", 0);
12121
12122 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12123 "qXfer:threads:read", "threads", 0);
12124
12125 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12126 "qXfer:siginfo:read", "read-siginfo-object", 0);
12127
12128 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12129 "qXfer:siginfo:write", "write-siginfo-object", 0);
12130
12131 add_packet_config_cmd
12132 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
12133 "qXfer:traceframe-info:read", "traceframe-info", 0);
12134
12135 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12136 "qXfer:uib:read", "unwind-info-block", 0);
12137
12138 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
12139 "qGetTLSAddr", "get-thread-local-storage-address",
12140 0);
12141
12142 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12143 "qGetTIBAddr", "get-thread-information-block-address",
12144 0);
12145
12146 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12147 "bc", "reverse-continue", 0);
12148
12149 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12150 "bs", "reverse-step", 0);
12151
12152 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12153 "qSupported", "supported-packets", 0);
12154
12155 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12156 "qSearch:memory", "search-memory", 0);
12157
12158 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12159 "qTStatus", "trace-status", 0);
12160
12161 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12162 "vFile:open", "hostio-open", 0);
12163
12164 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12165 "vFile:pread", "hostio-pread", 0);
12166
12167 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12168 "vFile:pwrite", "hostio-pwrite", 0);
12169
12170 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12171 "vFile:close", "hostio-close", 0);
12172
12173 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12174 "vFile:unlink", "hostio-unlink", 0);
12175
12176 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12177 "vFile:readlink", "hostio-readlink", 0);
12178
12179 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12180 "vAttach", "attach", 0);
12181
12182 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12183 "vRun", "run", 0);
12184
12185 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12186 "QStartNoAckMode", "noack", 0);
12187
12188 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12189 "vKill", "kill", 0);
12190
12191 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12192 "qAttached", "query-attached", 0);
12193
12194 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
12195 "ConditionalTracepoints",
12196 "conditional-tracepoints", 0);
12197
12198 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12199 "ConditionalBreakpoints",
12200 "conditional-breakpoints", 0);
12201
12202 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12203 "BreakpointCommands",
12204 "breakpoint-commands", 0);
12205
12206 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12207 "FastTracepoints", "fast-tracepoints", 0);
12208
12209 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12210 "TracepointSource", "TracepointSource", 0);
12211
12212 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12213 "QAllow", "allow", 0);
12214
12215 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12216 "StaticTracepoints", "static-tracepoints", 0);
12217
12218 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12219 "InstallInTrace", "install-in-trace", 0);
12220
12221 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12222 "qXfer:statictrace:read", "read-sdata-object", 0);
12223
12224 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12225 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12226
12227 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12228 "QDisableRandomization", "disable-randomization", 0);
12229
12230 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12231 "QAgent", "agent", 0);
12232
12233 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12234 "QTBuffer:size", "trace-buffer-size", 0);
12235
12236 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12237 "Qbtrace:off", "disable-btrace", 0);
12238
12239 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12240 "Qbtrace:bts", "enable-btrace", 0);
12241
12242 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12243 "qXfer:btrace", "read-btrace", 0);
12244
12245 /* Keep the old ``set remote Z-packet ...'' working. Each individual
12246 Z sub-packet has its own set and show commands, but users may
12247 have sets to this variable in their .gdbinit files (or in their
12248 documentation). */
12249 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
12250 &remote_Z_packet_detect, _("\
12251 Set use of remote protocol `Z' packets"), _("\
12252 Show use of remote protocol `Z' packets "), _("\
12253 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
12254 packets."),
12255 set_remote_protocol_Z_packet_cmd,
12256 show_remote_protocol_Z_packet_cmd,
12257 /* FIXME: i18n: Use of remote protocol
12258 `Z' packets is %s. */
12259 &remote_set_cmdlist, &remote_show_cmdlist);
12260
12261 add_prefix_cmd ("remote", class_files, remote_command, _("\
12262 Manipulate files on the remote system\n\
12263 Transfer files to and from the remote target system."),
12264 &remote_cmdlist, "remote ",
12265 0 /* allow-unknown */, &cmdlist);
12266
12267 add_cmd ("put", class_files, remote_put_command,
12268 _("Copy a local file to the remote system."),
12269 &remote_cmdlist);
12270
12271 add_cmd ("get", class_files, remote_get_command,
12272 _("Copy a remote file to the local system."),
12273 &remote_cmdlist);
12274
12275 add_cmd ("delete", class_files, remote_delete_command,
12276 _("Delete a remote file."),
12277 &remote_cmdlist);
12278
12279 remote_exec_file = xstrdup ("");
12280 add_setshow_string_noescape_cmd ("exec-file", class_files,
12281 &remote_exec_file, _("\
12282 Set the remote pathname for \"run\""), _("\
12283 Show the remote pathname for \"run\""), NULL, NULL, NULL,
12284 &remote_set_cmdlist, &remote_show_cmdlist);
12285
12286 add_setshow_boolean_cmd ("range-stepping", class_run,
12287 &use_range_stepping, _("\
12288 Enable or disable range stepping."), _("\
12289 Show whether target-assisted range stepping is enabled."), _("\
12290 If on, and the target supports it, when stepping a source line, GDB\n\
12291 tells the target to step the corresponding range of addresses itself instead\n\
12292 of issuing multiple single-steps. This speeds up source level\n\
12293 stepping. If off, GDB always issues single-steps, even if range\n\
12294 stepping is supported by the target. The default is on."),
12295 set_range_stepping,
12296 show_range_stepping,
12297 &setlist,
12298 &showlist);
12299
12300 /* Eventually initialize fileio. See fileio.c */
12301 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
12302
12303 /* Take advantage of the fact that the LWP field is not used, to tag
12304 special ptids with it set to != 0. */
12305 magic_null_ptid = ptid_build (42000, 1, -1);
12306 not_sent_ptid = ptid_build (42000, 1, -2);
12307 any_thread_ptid = ptid_build (42000, 1, 0);
12308
12309 target_buf_size = 2048;
12310 target_buf = xmalloc (target_buf_size);
12311 }
12312
This page took 0.309355 seconds and 4 git commands to generate.