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