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