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