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