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