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