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