OpenCores
URL https://opencores.org/ocsvn/openrisc_2011-10-31/openrisc_2011-10-31/trunk

Subversion Repositories openrisc_2011-10-31

[/] [openrisc/] [trunk/] [gnu-src/] [gdb-7.1/] [gdb/] [remote.c] - Blame information for rev 634

Go to most recent revision | Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.