]> Git Repo - binutils.git/blob - gdb/rdi-share/ardi.c
Applied patches from [email protected] to implement the Angel remote
[binutils.git] / gdb / rdi-share / ardi.c
1 /* 
2  * Copyright (C) 1995 Advanced RISC Machines Limited. All rights reserved.
3  * 
4  * This software may be freely used, copied, modified, and distributed
5  * provided that the above copyright notice is preserved in all copies of the
6  * software.
7  */
8
9 /*
10  * ARDI.c
11  * Angel Remote Debug Interface
12  *
13  *
14  * $Revision$
15  *     $Date$
16  *
17  * This file is based on /plg/pisd/rdi.c, but instead of using RDP it uses
18  * ADP messages.
19  */
20
21 #include <stdarg.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #define uint HIDE_HPs_uint
26 #include <signal.h>
27 #undef uint
28
29
30 #include "endian.h"
31 #include "ardi.h"
32 #include "buffers.h"
33 #include "channels.h"
34 #include "hostchan.h"
35 #include "host.h"
36 #include "bytesex.h"
37 #include "dbg_cp.h"
38 #include "adp.h"
39 #include "hsys.h"
40 #include "logging.h"
41 #include "msgbuild.h"
42 #include "rxtx.h"
43 #include "devsw.h"
44 #include "params.h"
45
46 #ifdef COMPILING_ON_WINDOWS
47 #  define IGNORE(x) (x = x)   /* must go after #includes to work on Windows */
48 #endif
49 #define NOT(x) (!(x))
50
51 #define ADP_INITIAL_TIMEOUT_PERIOD 5
52
53 static volatile int executing;
54 static int rdi_log = 0 ; /* debugging  ? */
55
56 /* we need a starting point for our first buffers, this is a safe one */
57 int Armsd_BufferSize = ADP_BUFFER_MIN_SIZE;
58 int Armsd_LongBufSize = ADP_BUFFER_MIN_SIZE;
59
60 #ifdef WIN32
61   extern int interrupted;
62   extern int swiprocessing;
63 #endif
64
65 static char dummycline = 0;
66 char *ardi_commandline = &dummycline ; /* exported in ardi.h */
67
68 extern unsigned int heartbeat_enabled;
69
70 static unsigned char *cpwords[16];
71
72 typedef struct stoppedProcListElement {
73   struct stoppedProcListElement *next;
74   angel_RDI_TargetStoppedProc *fn;
75   void *arg;
76 } stoppedProcListElement;
77
78 static stoppedProcListElement *stopped_proc_list=NULL;
79
80 const struct Dbg_HostosInterface *angel_hostif;
81 static hsys_state *hstate;
82
83 static void angel_DebugPrint(const char *format, ...)
84 { va_list ap;
85   va_start(ap, format);
86   angel_hostif->dbgprint(angel_hostif->dbgarg, format, ap);
87   va_end(ap);
88 }
89
90 #ifdef RDI_VERBOSE
91 #define TracePrint(s) \
92   if (rdi_log & 2) angel_DebugPrint("\n"); \
93   if (rdi_log & 1) angel_DebugPrint s
94 #else
95 #define TracePrint(s)
96 #endif
97
98 typedef struct receive_dbgmsg_state {
99   volatile int received;
100   Packet *packet;
101 } receive_dbgmsg_state;
102
103 static receive_dbgmsg_state dbgmsg_state;
104
105 static void receive_debug_packet(Packet *packet, void *stateptr)
106 {
107   receive_dbgmsg_state *state = stateptr;
108
109   state->packet = packet;
110   state->received = 1;
111 }
112
113 static int register_debug_message_handler(void)
114 {
115   int err;
116   dbgmsg_state.received = 0;
117
118   err = Adp_ChannelRegisterRead(CI_HADP, receive_debug_packet, &dbgmsg_state);
119 #ifdef DEBUG
120   if (err!=adp_ok) angel_DebugPrint("register_debug_message_handler failed %i\n", err);
121 #endif
122   return err;
123 }
124
125
126 static int wait_for_debug_message(int *rcode, int *debugID,
127                                   int *OSinfo1, int *OSinfo2,
128                                   int *status, Packet **packet)
129 {
130   unsigned int reason;
131
132 #ifdef DEBUG
133   angel_DebugPrint("wait_for_debug_message waiting for %X\n", *rcode);
134 #endif
135
136   for ( ; dbgmsg_state.received == 0 ; )
137     Adp_AsynchronousProcessing(async_block_on_read);
138
139 #ifdef DEBUG
140   angel_DebugPrint("wait_for_debug_message got packet\n");
141 #endif
142
143   *packet = dbgmsg_state.packet;
144
145   Adp_ChannelRegisterRead(CI_HADP, NULL, NULL);
146
147   /*
148    * TODO:
149    * If ADP_Unrecognised return error.
150    * If ADP_Acknowledge - handle appropriately.
151    * If expected message read arguments and return RDIError_NoError.
152    * Note: if RDIError occurs then the data values returned are junk
153    */
154
155   unpack_message(BUFFERDATA((*packet)->pk_buffer), "%w%w%w%w%w", &reason, debugID,
156                  OSinfo1, OSinfo2, status);
157   if (reason&0xffffff == ADP_HADPUnrecognised)
158     return RDIError_UnimplementedMessage;
159   if (reason != (unsigned ) *rcode) {
160     if((reason&0xffffff) == ADP_HADPUnrecognised)
161       return RDIError_UnimplementedMessage;
162     else {
163       angel_DebugPrint("ARDI ERROR: Expected reasoncode %x got reasoncode %x.\n",
164              *rcode, reason);
165       return RDIError_Error;
166     }
167   }
168   else
169     return RDIError_NoError;
170   return RDIError_Error;    /* stop a pesky ANSI compiler warning */
171 }
172
173
174 /*
175  * Handler and registration for logging messages from target
176  */
177 static void TargetLogCallback( Packet *packet, void *state )
178 {
179     p_Buffer     reply = BUFFERDATA(packet->pk_buffer);
180     unsigned int len   = packet->pk_length;
181     IGNORE(state);
182     angel_hostif->write(angel_hostif->hostosarg,
183                         (char *)reply, len - CHAN_HEADER_SIZE);
184     DevSW_FreePacket(packet);
185
186     packet = DevSW_AllocatePacket(4); /* better not ask for 0 */
187     /* the reply is the ACK - any contents are ignored */
188     if (packet != NULL)
189        Adp_ChannelWrite( CI_TLOG, packet );
190 }
191
192 static void TargetLogInit( void )
193 {
194     AdpErrs err = Adp_ChannelRegisterRead( CI_TLOG, TargetLogCallback, NULL );
195
196 #ifdef DEBUG
197     if (err != adp_ok)
198        angel_DebugPrint("CI_TLOG RegisterRead failed %d\n", err);
199 #else
200     IGNORE(err);
201 #endif
202 }
203
204 /*----------------------------------------------------------------------*/
205 /*----angel_RDI_open-----------------------------------------------------*/
206 /*----------------------------------------------------------------------*/
207
208 typedef struct NegotiateState {
209       bool             negotiate_resp;
210       bool             negotiate_ack;
211       bool             link_check_resp;
212       ParameterConfig *accepted_config;
213 } NegotiateState;
214
215 static void receive_negotiate(Packet *packet, void *stateptr)
216 {
217     unsigned reason, debugID, OSinfo1, OSinfo2, status;
218     NegotiateState *n_state = (NegotiateState *)stateptr;
219     p_Buffer reply = BUFFERDATA(packet->pk_buffer);
220
221     unpack_message( reply, "%w%w%w%w",
222                     &reason, &debugID, &OSinfo1, &OSinfo2 );
223     reply += ADP_DEFAULT_HEADER_SIZE;
224
225 #ifdef DEBUG
226     angel_DebugPrint( "receive_negotiate: reason %x\n", reason );
227 #endif
228
229     switch ( reason )
230     {
231         case ADP_ParamNegotiate | TtoH:
232         {
233             n_state->negotiate_resp = TRUE;
234
235             status = GET32LE( reply );
236             reply += sizeof(word);
237 #ifdef DEBUG
238             angel_DebugPrint( "ParamNegotiate status %u\n", status );
239 #endif
240             if ( status == RDIError_NoError )
241             {
242                 if ( Angel_ReadParamConfigMessage(
243                          reply, n_state->accepted_config ) )
244                    n_state->negotiate_ack = TRUE;
245             }
246             break;
247         }
248
249         case ADP_LinkCheck | TtoH:
250         {
251 #ifdef DEBUG
252             angel_DebugPrint( "PONG!\n" );
253 #endif
254             n_state->link_check_resp = TRUE;
255             break;
256         }
257
258         default:
259         {
260 #ifdef DEBUG
261             angel_DebugPrint( "Unexpected!\n" );
262 #endif
263             break;
264         }
265     }
266     DevSW_FreePacket( packet );
267 }
268
269 # include <sys/types.h>
270 #ifdef __unix
271 # include <sys/time.h>
272 #else
273 # include <time.h>
274 #endif
275
276 /*
277  * convert a config into a single-valued options list
278  */
279 static ParameterOptions *config_to_options( const ParameterConfig *config )
280 {
281     unsigned int        num_params;
282     size_t              size;
283     ParameterOptions   *base_p;
284
285     num_params  = config->num_parameters;
286     size        =
287         sizeof(ParameterOptions)
288         + num_params*(sizeof(ParameterList) + sizeof(unsigned int));
289     base_p      = malloc( size );
290
291     if ( base_p != NULL )
292     {
293         unsigned int    u;
294         ParameterList  *list_p          =
295             (ParameterList *)((char *)base_p + sizeof(ParameterOptions));
296         unsigned int   *option_p        =
297             (unsigned int *)(list_p + num_params);
298
299         base_p->num_param_lists = num_params;
300         base_p->param_list = list_p;
301
302         for ( u = 0; u < num_params; ++u )
303         {
304             option_p[u]                 = config->param[u].value;
305             list_p[u].type              = config->param[u].type;
306             list_p[u].num_options       = 1;
307             list_p[u].option            = &option_p[u];
308         }
309     }
310
311     return base_p;
312 }
313
314 static AdpErrs negotiate_params( const ParameterOptions *user_options )
315 {
316     Packet                    *packet;
317     unsigned int               count;
318     static Parameter           params[AP_NUM_PARAMS];
319     static ParameterConfig     accepted_config = { AP_NUM_PARAMS, params };
320
321     time_t t;
322
323     static volatile NegotiateState    n_state = {
324         FALSE, FALSE, FALSE, &accepted_config };
325
326 #ifdef DEBUG
327     angel_DebugPrint( "negotiate_params\n" );
328 #endif
329
330     Adp_ChannelRegisterRead( CI_HBOOT, receive_negotiate, (void *)&n_state );
331
332     packet = (Packet *)DevSW_AllocatePacket(Armsd_BufferSize);
333     count = msgbuild( BUFFERDATA(packet->pk_buffer), "%w%w%w%w",
334                       ADP_ParamNegotiate | HtoT, 0,
335                       ADP_HandleUnknown, ADP_HandleUnknown );
336     count += Angel_BuildParamOptionsMessage(
337         BUFFERDATA(packet->pk_buffer) + count, user_options );
338     packet->pk_length = count;
339     Adp_ChannelWriteAsync( CI_HBOOT, packet );
340
341 #ifdef DEBUG
342     angel_DebugPrint( "sent negotiate packet\n" );
343 #endif
344
345     t=time(NULL);
346
347     do {
348       Adp_AsynchronousProcessing(async_block_on_nothing);
349
350       if ((time(NULL)-t) > ADP_INITIAL_TIMEOUT_PERIOD) {
351         return adp_timeout_on_open;
352       }
353     } while ( ! n_state.negotiate_resp );
354
355     if ( n_state.negotiate_ack )
356     {
357         /* select accepted config */
358         Adp_Ioctl( DC_SET_PARAMS, (void *)n_state.accepted_config );
359
360         /*
361          * 960430 KWelton
362          *
363          * There is a race in the renegotiation protocol: the
364          * target has to have had time to load new config before
365          * we send the link check packet - insert a deliberate
366          * pause (100ms) to give the target some time
367          */
368         Adp_delay(100000);
369
370         /* do link check */
371         msgsend( CI_HBOOT, "%w%w%w%w", ADP_LinkCheck | HtoT, 0,
372                  ADP_HandleUnknown, ADP_HandleUnknown );
373 #ifdef DEBUG
374         angel_DebugPrint("sent link check\n");
375 #endif
376
377         do {
378             Adp_AsynchronousProcessing(async_block_on_read);
379         } while ( ! n_state.link_check_resp );
380         Adp_initSeq();
381     }
382     return adp_ok;
383 }
384
385 static int late_booted = FALSE;
386 static bool ardi_handler_installed = FALSE;
387
388 #ifdef __unix
389 static struct sigaction old_action;
390 #else
391 static void (*old_handler)();
392 #endif
393
394 static bool boot_interrupted = FALSE;
395
396 static void ardi_sigint_handler(int sig) {
397 #ifdef DEBUG
398     if (sig != SIGINT)
399        angel_DebugPrint("Expecting SIGINT got %d.\n", sig);
400 #else
401     IGNORE(sig);
402 #endif
403     boot_interrupted = TRUE;
404 #ifndef __unix
405     signal(SIGINT, ardi_sigint_handler);
406 #endif
407 }
408
409 static void install_ardi_handler( void ) {
410   if (!ardi_handler_installed) {
411     /* install a new Ctrl-C handler so we can abandon waiting */
412 #ifdef __unix
413     struct sigaction new_action;
414     sigemptyset(&new_action.sa_mask);
415     new_action.sa_handler = ardi_sigint_handler;
416     new_action.sa_flags = 0;
417     sigaction(SIGINT, &new_action, &old_action);
418 #else
419     old_handler = signal(SIGINT, ardi_sigint_handler);
420 #endif
421     ardi_handler_installed = TRUE;
422   }
423 }
424
425 static int angel_RDI_errmess(char *buf, int blen, int errnum);
426
427 static void receive_reset_acknowledge(Packet *packet, void *stateptr) {
428   unsigned reason, debugID, OSinfo1, OSinfo2, status;
429   IGNORE(stateptr);
430
431   unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w", &reason, &debugID,
432                  &OSinfo1, &OSinfo2, &status);
433   if (reason==(ADP_Reset | TtoH) && status==AB_NORMAL_ACK) {
434 #ifdef DEBUG
435     angel_DebugPrint("DEBUG: Successfully received normal reset acknowledgement\n");
436     late_booted = FALSE;
437 #endif
438   } else if (reason==(ADP_Reset | TtoH) && status==AB_LATE_ACK) {
439     char late_msg[AdpMessLen_LateStartup];
440     int  late_len;
441 #ifdef DEBUG
442     angel_DebugPrint("DEBUG: Successfully received LATE reset acknowledgement\n");
443 #endif
444     late_booted = TRUE;
445     install_ardi_handler();
446     late_len = angel_RDI_errmess(late_msg,
447                                  AdpMessLen_LateStartup, adp_late_startup);
448     angel_hostif->write(angel_hostif->hostosarg, late_msg, late_len);
449   } else {
450 #ifdef DEBUG
451     angel_DebugPrint("DEBUG: Bad reset ack: reason=%8X, status=%8X\n", reason, status);
452 #endif
453   }
454   DevSW_FreePacket(packet);
455 }
456
457 static int booted_not_received;
458 static unsigned int angel_version;
459 static unsigned int adp_version;
460 static unsigned int arch_info;
461 static unsigned int cpu_info;
462 static unsigned int hw_status;
463
464 static void receive_booted(Packet *packet, void *stateptr) {
465   unsigned reason, debugID, OSinfo1, OSinfo2, banner_length, bufsiz, longsiz;
466   unsigned i, count;
467
468   IGNORE(stateptr);
469
470   count = unpack_message(BUFFERDATA(packet->pk_buffer),
471                          "%w%w%w%w%w%w%w%w%w%w%w%w",
472                  &reason, &debugID, &OSinfo1, &OSinfo2, &bufsiz, &longsiz,
473                  &angel_version, &adp_version,
474                  &arch_info, &cpu_info, &hw_status, &banner_length);
475   if (reason==(ADP_Booted | TtoH)) {
476 #ifdef MONITOR_DOWNLOAD_PACKETS
477     angel_DebugPrint("DEBUG: Successfully received Booted\n");
478     angel_DebugPrint("       cpu_info=%8X, hw_status=%8X, bufsiz=%d, longsiz=%d\n",
479            cpu_info, hw_status, bufsiz, longsiz);
480 #endif
481     /* Get the banner from the booted message */
482     for (i=0; i<banner_length; i++)
483       angel_hostif->writec(angel_hostif->hostosarg,
484                           (BUFFERDATA(packet->pk_buffer)+count)[i]);
485
486     booted_not_received=0;
487 #ifndef NO_HEARTBEAT
488     heartbeat_enabled = TRUE;
489 #endif
490     Armsd_BufferSize = bufsiz + CHAN_HEADER_SIZE;
491     Armsd_LongBufSize = longsiz + CHAN_HEADER_SIZE;
492   } else {
493 #ifdef DEBUG
494     angel_DebugPrint("DEBUG: Bad Booted msg: reason=%8X\n", reason);
495 #endif
496   }
497   DevSW_FreePacket(packet);
498 }
499
500
501 /* forward declaration */
502 static int angel_negotiate_defaults( void );
503
504 /* Open communications. */
505 int angel_RDI_open(
506     unsigned type, Dbg_ConfigBlock const *config,
507     Dbg_HostosInterface const *hostif, struct Dbg_MCState *dbg_state)
508 {
509   Packet *packet;
510   int status, reasoncode, debugID, OSinfo1, OSinfo2, err;
511   ParameterOptions *user_options = NULL;
512
513   time_t t;
514
515   IGNORE( dbg_state );
516
517   if ((type & 1) == 0) {
518     /* cold start */
519     if (hostif != NULL) {
520       angel_hostif = hostif;
521       err = HostSysInit(hostif, &ardi_commandline, &hstate);
522       if (err != RDIError_NoError) {
523 #ifdef DEBUG
524         angel_DebugPrint("DEBUG: HostSysInit error %i\n",err);
525 #endif
526         return err;
527       }
528     }
529     TargetLogInit();
530   }
531
532 #ifdef DEBUG
533   angel_DebugPrint("DEBUG: Buffer allocated in angel_RDI_open(type=%i).\n",type);
534 #endif
535
536   if ((type & 1) == 0) {
537     /* cold start */
538     unsigned endian;
539     Adp_Ioctl( DC_GET_USER_PARAMS, (void *)&user_options );
540     if ( user_options != NULL ) {
541       err = negotiate_params( user_options );
542       if (err != adp_ok) return err;
543     }
544     else {
545       ParameterConfig *default_config = NULL;
546       Adp_Ioctl( DC_GET_DEFAULT_PARAMS, (void *)&default_config );
547       if ( default_config != NULL ) {
548         ParameterOptions *default_options = config_to_options(default_config);
549         err = negotiate_params( default_options );
550         if (err != adp_ok) return err;
551       }
552     }
553
554     /* Register handlers before sending any messages */
555     booted_not_received=1;
556     Adp_ChannelRegisterRead(CI_HBOOT, receive_reset_acknowledge, NULL);
557     Adp_ChannelRegisterRead(CI_TBOOT, receive_booted, NULL);
558     endian = 0;
559     if (config!=NULL) {
560       if (config->bytesex & RDISex_Little) endian |= ADP_BootHostFeature_LittleEnd;
561       if (config->bytesex & RDISex_Big) endian |= ADP_BootHostFeature_BigEnd;
562     }
563     msgsend(CI_HBOOT,"%w%w%w%w%w", ADP_Reset | HtoT, 0,
564             ADP_HandleUnknown, ADP_HandleUnknown, endian);
565 #ifdef DEBUG
566     angel_DebugPrint("DEBUG: Transmitted Reset message in angel_RDI_open.\n");
567 #endif
568
569     /* We will now either get an acknowledgement for the Reset message
570      * or if the target was started after the host, we will get a
571      * rebooted message first.
572      */
573
574 #ifdef DEBUG
575     angel_DebugPrint("DEBUG: waiting for a booted message\n");
576 #endif
577
578     {
579       boot_interrupted = FALSE;
580
581       if (late_booted)
582         install_ardi_handler();
583
584       t=time(NULL);
585
586       do {
587         Adp_AsynchronousProcessing(async_block_on_nothing);
588         if ((time(NULL)-t) > ADP_INITIAL_TIMEOUT_PERIOD && !late_booted) {
589           return adp_timeout_on_open;
590         }
591       } while (booted_not_received && !boot_interrupted);
592
593       if (ardi_handler_installed)
594       {
595         /* uninstall our Ctrl-C handler */
596 #ifdef __unix
597         sigaction(SIGINT, &old_action, NULL);
598 #else
599         signal(SIGINT, old_handler);
600 #endif
601       }
602
603       if (boot_interrupted) {
604         angel_negotiate_defaults();
605         return adp_abandon_boot_wait;
606       }
607     }
608
609     booted_not_received=1;
610     Adp_ChannelRegisterRead(CI_HBOOT, NULL, NULL);
611
612     /* Leave the booted handler installed */
613     msgsend(CI_TBOOT, "%w%w%w%w%w", ADP_Booted | HtoT, 0,
614             ADP_HandleUnknown, ADP_HandleUnknown, 0);
615     Adp_initSeq();
616 #ifdef DEBUG
617     angel_DebugPrint("DEBUG: Transmitted ADP_Booted acknowledgement.\n");
618     angel_DebugPrint("DEBUG: Boot sequence completed, leaving angel_RDI_open.\n");
619 #endif
620
621     return (hw_status & ADP_CPU_BigEndian )? RDIError_BigEndian :
622       RDIError_LittleEndian;
623   }
624   else {
625     /* warm start */
626     register_debug_message_handler();
627
628     msgsend(CI_HADP, "%w%w%w%w",
629             ADP_InitialiseApplication | HtoT, 0,
630             ADP_HandleUnknown, ADP_HandleUnknown);
631 #ifdef DEBUG
632     angel_DebugPrint("DEBUG: Transmitted Initialise Application\n");
633 #endif
634     reasoncode=ADP_InitialiseApplication | TtoH;
635     err = wait_for_debug_message(&reasoncode, &debugID, &OSinfo1, &OSinfo2,
636                                 &status, &packet);
637     if (err != RDIError_NoError) return err;
638     return status;
639   }
640   return -1;
641 }
642
643
644 /*----------------------------------------------------------------------*/
645 /*----angel_RDI_close----------------------------------------------------*/
646 /*----------------------------------------------------------------------*/
647
648 static int angel_negotiate_defaults( void ) {
649     int err = adp_ok;
650     ParameterConfig *default_config = NULL;
651     Adp_Ioctl( DC_GET_DEFAULT_PARAMS, (void *)&default_config );
652     if ( default_config != NULL ) {
653         ParameterOptions *default_options = config_to_options(default_config);
654         err = negotiate_params( default_options );
655         free( default_options );
656     }
657     return err;
658 }
659
660 int angel_RDI_close(void) {
661 /*Angel host exit */
662   int err;
663   int status,debugID, OSinfo1,OSinfo2;
664   int reason;
665   Packet *packet = NULL;;
666 #ifdef DEBUG
667   angel_DebugPrint("DEBUG: Entered angel_RDI_Close.\n");
668 #endif
669
670   register_debug_message_handler();
671
672   heartbeat_enabled = FALSE;
673
674   err = msgsend(CI_HADP,"%w%w%w%w",ADP_End | HtoT,0,
675           ADP_HandleUnknown, ADP_HandleUnknown);
676   if (err != RDIError_NoError) return err;
677   reason = ADP_End | TtoH;
678   err =  wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
679                                   &status, &packet);
680   DevSW_FreePacket(packet);
681   if (err != RDIError_NoError) return err;
682   if (status == RDIError_NoError) {
683     err = angel_negotiate_defaults();
684     if (err != adp_ok) return err;
685     Adp_Ioctl( DC_RESET, NULL ); /* just to be safe */
686     return HostSysExit(hstate);
687   }
688   else
689       return status;
690 }
691
692
693 /*----------------------------------------------------------------------*/
694 /*----angel_RDI_read-----------------------------------------------------*/
695 /*----------------------------------------------------------------------*/
696
697 /* Read memory contents from target to host: use ADP_Read */
698 int angel_RDI_read(ARMword source, void *dest, unsigned *nbytes)
699 {
700   Packet *packet=NULL;
701   int len;                               /* Integer to hold message length. */
702   unsigned int nbtogo = *nbytes, nbinpacket, nbdone=0;
703   int rnbytes = 0, status, reason, debugID, OSinfo1, OSinfo2, err;
704   unsigned int maxlen = Armsd_BufferSize-CHAN_HEADER_SIZE-ADP_ReadHeaderSize;
705
706   /* Print debug trace information, this is just copied straight from rdi.c
707      and I can see no reason why it should have to be changed. */
708   TracePrint(("angel_RDI_read: source=%.8lx dest=%p nbytes=%.8x\n",
709                 (unsigned long)source, dest, *nbytes));
710   if (*nbytes == 0) return RDIError_NoError;       /* Read nothing - easy! */
711   /* check the buffer size */
712   while (nbtogo >0) {
713     register_debug_message_handler();
714
715     nbinpacket = (nbtogo <= maxlen) ? nbtogo : maxlen;
716     len = msgsend(CI_HADP, "%w%w%w%w%w%w", ADP_Read | HtoT, 0,
717                   ADP_HandleUnknown, ADP_HandleUnknown, source+nbdone,
718                   nbinpacket);
719     reason=ADP_Read | TtoH;
720     err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
721                                 &status, &packet);
722     TracePrint(("angel_RDI_read: nbinpacket =%d status=%08x err = %d\n",
723                 nbinpacket,status,err));
724     if (err != RDIError_NoError) return err;       /* Was there an error? */
725     if (status == RDIError_NoError){
726       rnbytes += PREAD(LE,(unsigned int *)(BUFFERDATA(packet->pk_buffer)+20));
727       TracePrint(("angel_RDI_read: rnbytes = %d\n",rnbytes));
728       memcpy(((unsigned char *)dest)+nbdone, BUFFERDATA(packet->pk_buffer)+24,
729              nbinpacket);
730     }
731     nbdone += nbinpacket;
732     nbtogo -= nbinpacket;
733   }
734   *nbytes -= rnbytes;
735   return status;
736 }
737
738
739 /*----------------------------------------------------------------------*/
740 /*----angel_RDI_write----------------------------------------------------*/
741 /*----------------------------------------------------------------------*/
742
743 /* Transfer memory block from host to target.  Use ADP_Write>. */
744 int angel_RDI_write(const void *source, ARMword dest, unsigned *nbytes)
745 {
746   Packet *packet;/* Message buffers. */
747   unsigned int len, nbtogo = *nbytes, nboffset = 0, nbinpacket;
748   int status, reason, debugID, OSinfo1, OSinfo2, err;
749   unsigned int maxlen = Armsd_LongBufSize-CHAN_HEADER_SIZE-ADP_WriteHeaderSize;
750
751   TracePrint(("angel_RDI_write: source=%p dest=%.8lx nbytes=%.8x\n",
752                  source, (unsigned long)dest, *nbytes));
753
754   if (*nbytes == 0) return RDIError_NoError;
755
756   *nbytes = 0;
757   while (nbtogo > 0) {
758     packet = (Packet *) DevSW_AllocatePacket(Armsd_LongBufSize);
759     nbinpacket = (nbtogo <= maxlen) ? nbtogo : maxlen;
760     len = msgbuild(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w",
761                    ADP_Write | HtoT, 0, ADP_HandleUnknown,
762                    ADP_HandleUnknown, dest+nboffset, nbinpacket);
763     /* Copy the data into the packet. */
764
765     memcpy(BUFFERDATA(packet->pk_buffer)+len,
766            ((const unsigned char *) source)+nboffset, nbinpacket);
767     nboffset += nbinpacket;
768     packet->pk_length = nbinpacket+len;
769
770 #ifdef MONITOR_DOWNLOAD_PACKETS
771     angel_DebugPrint("angel_RDI_write packet size=%i, bytes done=%i\n",
772             nbinpacket, nboffset);
773 #endif
774
775     register_debug_message_handler();
776     Adp_ChannelWrite(CI_HADP, packet);
777     reason=ADP_Write | TtoH;
778     err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
779                                 &status, &packet);
780     nbtogo -= nbinpacket;
781     if (err != RDIError_NoError) return err;
782     if (status == RDIError_NoError)
783       *nbytes += nbinpacket;
784
785     DevSW_FreePacket(packet);
786   }
787   return status;
788 }
789
790
791 /*----------------------------------------------------------------------*/
792 /*----angel_RDI_CPUread--------------------------------------------------*/
793 /*----------------------------------------------------------------------*/
794
795 /* Reads the values of registers in the CPU, uses ADP_CPUwrite. */
796 int angel_RDI_CPUread(unsigned mode, unsigned long mask, ARMword *buffer)
797 {
798   unsigned int i, j;
799   Packet *packet = NULL;
800   int err, status, reason, debugID, OSinfo1, OSinfo2;
801 #ifdef DEBUG
802   angel_DebugPrint("DEBUG: Entered angel_RDI_CPUread.\n");
803 #endif
804   for (i=0, j=0 ; i < RDINumCPURegs ; i++)
805     if (mask & (1L << i)) j++;            /* Count the number of registers. */
806
807   register_debug_message_handler();
808   msgsend(CI_HADP, "%w%w%w%w%c%w", ADP_CPUread | HtoT, 0,
809           ADP_HandleUnknown, ADP_HandleUnknown, mode, mask);
810   reason = ADP_CPUread | TtoH;
811   err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
812                               &status, &packet);
813   if (err != RDIError_NoError) {
814     DevSW_FreePacket(packet);
815     return err;
816   }
817   if(status == RDIError_NoError) {
818     for (i=0; i<j; i++)
819       buffer[i] = GET32LE(BUFFERDATA(packet->pk_buffer)+20+(i*4));
820     TracePrint(("angel_RDI_CPUread: mode=%.8x mask=%.8lx", mode, mask));
821     DevSW_FreePacket(packet);
822 #ifdef RDI_VERBOSE
823     if (rdi_log & 1) {
824       unsigned k;
825       for (k = 0, j = 0 ; j <= 20 ; j++)
826         if (mask & (1L << j)) {
827           angel_DebugPrint("%c%.8lx",k%4==0?'\n':' ',
828                            (unsigned long)buffer[k]);
829           k++ ;
830         }
831       angel_DebugPrint("\n") ;
832     }
833 #endif
834
835   }
836   return status;
837 }
838
839 /*----------------------------------------------------------------------*/
840 /*----angel_RDI_CPUwrite-------------------------------------------------*/
841 /*----------------------------------------------------------------------*/
842
843 /* Write CPU registers: use ADP_CPUwrite. */
844 int angel_RDI_CPUwrite(unsigned mode, unsigned long mask,
845                       ARMword const *buffer){
846
847   unsigned i, j, c;
848   Packet *packet;
849   int status, reason, debugID, OSinfo1, OSinfo2, err, len;
850
851   TracePrint(("angel_RDI_CPUwrite: mode=%.8x mask=%.8lx", mode, mask));
852 #ifdef RDI_VERBOSE
853  if (rdi_log & 1) {
854     for (j = 0, i = 0 ; i <= 20 ; i++)
855        if (mask & (1L << i)) {
856           angel_DebugPrint("%c%.8lx",j%4==0?'\n':' ',
857                            (unsigned long)buffer[j]);
858           j++ ;
859           }
860     angel_DebugPrint("\n") ;
861     }
862 #endif
863  packet = (Packet *)DevSW_AllocatePacket(Armsd_BufferSize);
864  for (i=0, j=0; i < RDINumCPURegs ; i++)
865    if (mask & (1L << i)) j++; /* count the number of registers */
866
867  len = msgbuild(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%b%w",
868                 ADP_CPUwrite | HtoT, 0,
869                 ADP_HandleUnknown, ADP_HandleUnknown, mode, mask);
870  for(c=0; c<j; c++)
871    PUT32LE(BUFFERDATA(packet->pk_buffer)+len+(c*4), buffer[c]);
872  packet->pk_length = len+(j*4);
873  register_debug_message_handler();
874
875  Adp_ChannelWrite(CI_HADP, packet);
876  reason = ADP_CPUwrite | TtoH;
877  err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
878                              &status, &packet);
879  unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w", &reason, &debugID,
880                 &OSinfo1, &OSinfo2, &status);
881  DevSW_FreePacket(packet);
882  if (err != RDIError_NoError)
883    return err;      /* Was there an error? */
884  else
885    return status;
886  }
887
888
889 /*----------------------------------------------------------------------*/
890 /*----angel_RDI_CPread---------------------------------------------------*/
891 /*----------------------------------------------------------------------*/
892
893 /* Read coprocessor's internal state.  See dbg_cp.h for help.
894  * Use ADP_CPRead.
895  * It would appear that the correct behaviour at this point is to leave
896  * the unpacking to a the caller and to simply copy the stream of data
897  * words into the buffer
898  */
899
900 int angel_RDI_CPread(unsigned CPnum, unsigned long mask, ARMword *buffer){
901   Packet *packet = NULL;
902   int i, j, status, reasoncode, OSinfo1, OSinfo2, err, debugID;
903   unsigned char *rmap = cpwords[CPnum];
904   int n;
905 #ifdef DEBUG
906   angel_DebugPrint("DEBUG: Entered angel_RDI_CPread.\n");
907 #endif
908   if (rmap == NULL) return RDIError_UnknownCoPro;
909
910   register_debug_message_handler();
911   n = rmap[-1];
912   msgsend(CI_HADP, "%w%w%w%w%b%w", ADP_CPread | HtoT, 0,
913           ADP_HandleUnknown, ADP_HandleUnknown, CPnum, mask);
914   reasoncode=ADP_CPread | TtoH;
915   err = wait_for_debug_message(&reasoncode, &debugID, &OSinfo1, &OSinfo2,
916                               &status, &packet);
917   if (err != RDIError_NoError) {
918     DevSW_FreePacket(packet);
919     return err;          /* Was there an error? */
920   }
921   for (j=i=0; i < n ; i++) /* count the number of registers */
922     if (mask & (1L << i)) {
923       j++;
924     }
925   for (i=0; i<j; i++)
926     buffer[i] = PREAD32(LE, BUFFERDATA(packet->pk_buffer) + 20 + (i*4));
927   DevSW_FreePacket(packet);
928   TracePrint(("angel_RDI_CPread: CPnum=%.8x mask=%.8lx\n", CPnum, mask));
929 #ifdef RDI_VERBOSE
930   if (rdi_log & 1) {
931     for (i = 0, j = 0; j < n ; j++) {
932       if (mask & (1L << j)) {
933         int nw = rmap[j];
934         angel_DebugPrint("%2d ", j);
935         while (--nw > 0)
936           angel_DebugPrint("%.8lx ", (unsigned long)buffer[i++]);
937         angel_DebugPrint("%.8lx\n", (unsigned long)buffer[i++]);
938       }
939     }
940   }
941 #endif
942   return status;
943 }
944
945
946 /*----------------------------------------------------------------------*/
947 /*----angel_RDI_CPwrite--------------------------------------------------*/
948 /*----------------------------------------------------------------------*/
949
950 /* Write coprocessor's internal state.  See dbg_cp.h for help. Use
951  * ADP_CPwrite.
952  */
953
954 int angel_RDI_CPwrite(unsigned CPnum, unsigned long mask,
955                       ARMword const *buffer)
956 {
957   Packet *packet = NULL;
958   int i, j, len, status, reason, OSinfo1, OSinfo2, err, debugID;
959   unsigned char *rmap = cpwords[CPnum];
960   int n;
961
962   if (rmap == NULL) return RDIError_UnknownCoPro;
963   n = rmap[-1];
964
965   TracePrint(("angel_RDI_CPwrite: CPnum=%d mask=%.8lx\n", CPnum, mask));
966
967 #ifdef RDI_VERBOSE
968  if (rdi_log & 1) {
969     for (i = 0, j = 0; j < n ; j++)
970        if (mask & (1L << j)) {
971           int nw = rmap[j];
972           angel_DebugPrint("%2d ", j);
973           while (--nw > 0)
974              angel_DebugPrint("%.8lx ", (unsigned long)buffer[i++]);
975           angel_DebugPrint("%.8lx\n", (unsigned long)buffer[i++]);
976        }
977  }
978 #endif
979
980   for (j=i=0; i < n ; i++) /* Count the number of registers. */
981     if (mask & (1L << i)) j++;
982   packet = DevSW_AllocatePacket(Armsd_BufferSize);
983   len = msgbuild(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%c%w",
984                  ADP_CPwrite | HtoT, 0,
985                  ADP_HandleUnknown, ADP_HandleUnknown, CPnum, mask);
986   for(i=0;  i<j; i++)
987     len+=msgbuild(BUFFERDATA(packet->pk_buffer) + len, "%w", buffer[i]);
988   packet->pk_length = len;
989   register_debug_message_handler();
990   Adp_ChannelWrite(CI_HADP, packet);    /* Transmit message. */
991   reason=ADP_CPwrite | TtoH;
992   err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
993                               &status, &packet);
994   DevSW_FreePacket(packet);
995   if (err != RDIError_NoError)
996     return err;
997   else
998     return status;
999 }
1000
1001
1002 /*----------------------------------------------------------------------*/
1003 /*----angel_RDI_pointinq-------------------------------------------------*/
1004 /*----------------------------------------------------------------------*/
1005
1006 /* Do test calls to ADP_SetBreak/ADP_SetWatch to see if resources exist to
1007    carry out request. */
1008 int angel_RDI_pointinq(ARMword *address, unsigned type, unsigned datatype,
1009                        ARMword *bound)
1010 {
1011   Packet *packet = NULL;
1012   int len, status, reason, OSinfo1, OSinfo2, err=RDIError_NoError;
1013        /* stop a compiler warning */
1014   int debugID, pointhandle;
1015   TracePrint(
1016       ("angel_RDI_pointinq: address=%.8lx type=%d datatype=%d bound=%.8lx ",
1017       (unsigned long)*address, type, datatype, (unsigned long)*bound));
1018        /* for a buffer.  */
1019   packet = DevSW_AllocatePacket(Armsd_BufferSize);
1020   len = msgbuild(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%b",
1021                  ((datatype == 0) ? ADP_SetBreak : ADP_SetWatch) | HtoT, 0,
1022                  ADP_HandleUnknown, ADP_HandleUnknown, address, type);
1023   if (datatype == 0)
1024     len += msgbuild(BUFFERDATA(packet->pk_buffer) + 21, "%w", bound);
1025   else
1026     len += msgbuild(BUFFERDATA(packet->pk_buffer) + 21, "%b%w", datatype, bound);
1027
1028   register_debug_message_handler();
1029   packet->pk_length = len;
1030   Adp_ChannelWrite(CI_HADP, packet);
1031   reason = ((datatype == 0) ? ADP_SetBreak : ADP_SetWatch | TtoH);
1032   err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
1033                               &status, &packet);
1034   if (err != RDIError_NoError) {
1035     DevSW_FreePacket(packet);
1036     return err;        /* Was there an error? */
1037   }
1038   unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w%w%w",
1039                  &reason, &debugID, &OSinfo1, &OSinfo2, &status,
1040                  &pointhandle, &address, &bound);
1041   DevSW_FreePacket(packet);
1042   return err;
1043 }
1044
1045
1046 /*----------------------------------------------------------------------*/
1047 /*----angel_RDI_setbreak-------------------------------------------------*/
1048 /*----------------------------------------------------------------------*/
1049
1050 /* Set a breakpoint: Use ADP_SetBreak */
1051 int angel_RDI_setbreak(ARMword address, unsigned type, ARMword bound,
1052                       PointHandle *handle)
1053 {
1054   int status, reason, OSinfo1, OSinfo2, err, debugID;
1055   int tmpval, tmpaddr, tmpbnd;
1056   Packet *packet;
1057   TracePrint(("angel_RDI_setbreak address=%.8lx type=%d bound=%.8lx \n",
1058               (unsigned long)address, type, (unsigned long)bound));
1059
1060   register_debug_message_handler();
1061   msgsend(CI_HADP, "%w%w%w%w%w%b%w",
1062           ADP_SetBreak| HtoT, 0,  ADP_HandleUnknown,
1063           ADP_HandleUnknown, address, type, bound);
1064   reason = ADP_SetBreak |TtoH;
1065   err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
1066                               &status, &packet);
1067   if (err != RDIError_NoError) {
1068     DevSW_FreePacket(packet);
1069     return err;         /* Was there an error? */
1070   }
1071   /* Work around varargs problem... -sts */
1072   unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w%w%w",
1073                  &reason, &debugID, &OSinfo1, &OSinfo2, &status,
1074                  &tmpval, &tmpaddr, &tmpbnd);
1075   *handle = tmpval;
1076   address = tmpaddr;
1077   bound = tmpbnd;
1078   DevSW_FreePacket(packet);
1079   if (status != RDIError_NoError) return status;
1080   TracePrint(("returns handle %.8lx\n", (unsigned long)*handle));
1081   return RDIError_NoError;
1082 }
1083
1084
1085 /*----------------------------------------------------------------------*/
1086 /*----angel_RDI_clearbreak-----------------------------------------------*/
1087 /*----------------------------------------------------------------------*/
1088
1089 /* Clear a breakpoint: Use ADP_ClearBreak. */
1090 int angel_RDI_clearbreak(PointHandle handle)
1091 {
1092   Packet *packet = NULL;
1093   int status, reason, OSinfo1, OSinfo2, err, debugID;
1094
1095   TracePrint(("angel_RDI_clearbreak: handle=%.8lx\n", (unsigned long)handle));
1096
1097   register_debug_message_handler();
1098   msgsend(CI_HADP, "%w%w%w%w%w",
1099           ADP_ClearBreak| HtoT, 0,  ADP_HandleUnknown,
1100           ADP_HandleUnknown, handle);
1101   reason = ADP_ClearBreak|TtoH;
1102   err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
1103                               &status, &packet);
1104   if (err != RDIError_NoError) {
1105     DevSW_FreePacket(packet);
1106     angel_DebugPrint("***RECEIVE DEBUG MESSAGE RETURNED ERR = %d.\n", err);
1107     return err;          /* Was there an error? */
1108   }
1109   unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w",  &reason,
1110                  &debugID, &OSinfo1, &OSinfo2, &status);
1111   DevSW_FreePacket(packet);
1112 #ifdef DEBUG
1113   angel_DebugPrint("DEBUG: Clear Break completed OK.\n");
1114 #endif
1115   return RDIError_NoError;
1116 }
1117
1118
1119 /*----------------------------------------------------------------------*/
1120 /*----angel_RDI_setwatch-------------------------------------------------*/
1121 /*----------------------------------------------------------------------*/
1122
1123 /* Set a watchpoint: use ADP_SetWatch. */
1124 int angel_RDI_setwatch(ARMword address, unsigned type, unsigned datatype,
1125                        ARMword bound, PointHandle *handle)
1126 {
1127   Packet *packet = NULL;
1128   int status, reason, OSinfo1, OSinfo2, err, debugID;
1129
1130   TracePrint(("angel_RDI_setwatch: address=%.8lx type=%d bound=%.8lx ",
1131               (unsigned long)address, type, (unsigned long)bound));
1132
1133   register_debug_message_handler();
1134   msgsend(CI_HADP, "%w%w%w%w%w%b%b%w",
1135           ADP_SetWatch| HtoT, 0,  ADP_HandleUnknown,
1136           ADP_HandleUnknown, address, type, datatype, bound);
1137
1138   reason = ADP_SetWatch | TtoH;
1139   err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
1140                               &status, &packet);
1141   if (err != RDIError_NoError) {
1142     DevSW_FreePacket(packet);
1143     return err;        /* Was there an error? */
1144   }
1145   unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w%w%w",
1146                  &reason, &debugID, &OSinfo1, &OSinfo2, &status,
1147                  handle, &address, &bound);
1148   DevSW_FreePacket(packet);
1149   TracePrint(("returns handle %.8lx\n", (unsigned long)*handle));
1150   return RDIError_NoError;
1151 }
1152
1153 /*----------------------------------------------------------------------*/
1154 /*----angel_RDI_clearwatch-----------------------------------------------*/
1155 /*----------------------------------------------------------------------*/
1156
1157 /* Clear a watchpoint: use ADP_ClearWatch. */
1158 int angel_RDI_clearwatch(PointHandle handle) {
1159
1160   int status, reason, OSinfo1, OSinfo2, err, debugID;
1161   Packet *packet = NULL;
1162
1163   TracePrint(("angel_RDI_clearwatch: handle=%.8lx\n", (unsigned long)handle));
1164
1165   register_debug_message_handler();
1166   msgsend(CI_HADP, "%w%w%w%w%w",
1167           ADP_ClearWatch| HtoT, 0,  ADP_HandleUnknown,
1168           ADP_HandleUnknown, handle);
1169   reason = ADP_ClearWatch|TtoH;
1170   err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
1171                               &status, &packet);
1172   if (err != RDIError_NoError) {
1173     DevSW_FreePacket(packet);
1174     return err;        /* Was there an error? */
1175   }
1176   unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w",  &reason, &debugID,
1177                  &OSinfo1, &OSinfo2, &status);
1178   DevSW_FreePacket(packet);
1179   return RDIError_NoError;
1180 }
1181
1182 typedef struct {
1183   unsigned stopped_reason;
1184   int stopped_status;
1185   int data;
1186 } adp_stopped_struct;
1187
1188
1189 int angel_RDI_OnTargetStopping(angel_RDI_TargetStoppedProc *fn,
1190                                void *arg)
1191 {
1192   stoppedProcListElement **lptr = &stopped_proc_list;
1193
1194   /* Find the address of the NULL ptr at the end of the list */
1195   for (; *lptr!=NULL ; lptr = &((*lptr)->next))
1196     ; /* Do nothing */
1197
1198   *lptr = (stoppedProcListElement *) malloc(sizeof(stoppedProcListElement));
1199   if (*lptr == NULL) return RDIError_OutOfStore;
1200   (*lptr)->fn = fn;
1201   (*lptr)->arg = arg;
1202
1203   return RDIError_NoError;
1204 }
1205
1206 static int CallStoppedProcs(unsigned reason)
1207 {
1208   stoppedProcListElement *p = stopped_proc_list;
1209   int err=RDIError_NoError;
1210   
1211   for (; p!=NULL ; p=p->next) {
1212     int local_err = p->fn(reason, p->arg);
1213     if (local_err != RDIError_NoError) err=local_err;
1214   }
1215
1216   return err;
1217 }
1218
1219 /*----------------------------------------------------------------------*/
1220 /*----angel_RDI_execute--------------------------------------------------*/
1221 /*----------------------------------------------------------------------*/
1222
1223 static int HandleStoppedMessage(Packet *packet, void *stateptr) {
1224   unsigned int err,  reason, debugID, OSinfo1, OSinfo2, count;
1225   adp_stopped_struct *stopped_info;
1226   stopped_info = (adp_stopped_struct *) stateptr;
1227   IGNORE(stateptr);
1228   count = unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w",
1229                          &reason, &debugID,
1230                          &OSinfo1, &OSinfo2,
1231                          &stopped_info->stopped_reason, &stopped_info->data);
1232   DevSW_FreePacket(packet);
1233
1234   if (reason != (ADP_Stopped | TtoH)) {
1235 #ifdef DEBUG
1236     angel_DebugPrint("Expecting stopped message, got %x", reason);
1237 #endif
1238     return RDIError_Error;
1239   }
1240   else {
1241     executing = FALSE;
1242 #ifdef DEBUG
1243     angel_DebugPrint("Received stopped message.\n");
1244 #endif
1245   }
1246
1247   err = msgsend(CI_TADP,  "%w%w%w%w%w", (ADP_Stopped | HtoT), 0,
1248                 ADP_HandleUnknown, ADP_HandleUnknown, RDIError_NoError);
1249 #ifdef DEBUG
1250   angel_DebugPrint("Transmiting stopped acknowledge.\n");
1251 #endif
1252   if (err != RDIError_NoError) angel_DebugPrint("Transmit failed.\n");
1253 #ifdef DEBUG
1254   angel_DebugPrint("DEBUG: Stopped reason : %x\n", stopped_info->stopped_reason);
1255 #endif
1256   switch (stopped_info->stopped_reason) {
1257   case ADP_Stopped_BranchThroughZero:
1258     stopped_info->stopped_status = RDIError_BranchThrough0;
1259     break;
1260   case ADP_Stopped_UndefinedInstr:
1261     stopped_info->stopped_status = RDIError_UndefinedInstruction;
1262     break;
1263   case ADP_Stopped_SoftwareInterrupt:
1264     stopped_info->stopped_status = RDIError_SoftwareInterrupt;
1265     break;
1266   case ADP_Stopped_PrefetchAbort:
1267     stopped_info->stopped_status = RDIError_PrefetchAbort;
1268     break;
1269   case ADP_Stopped_DataAbort:
1270     stopped_info->stopped_status = RDIError_DataAbort;
1271     break;
1272   case ADP_Stopped_AddressException:
1273     stopped_info->stopped_status = RDIError_AddressException;
1274     break;
1275   case ADP_Stopped_IRQ:
1276     stopped_info->stopped_status = RDIError_IRQ;
1277     break;
1278   case ADP_Stopped_BreakPoint:
1279     stopped_info->stopped_status = RDIError_BreakpointReached;
1280     break;
1281   case ADP_Stopped_WatchPoint:
1282     stopped_info->stopped_status = RDIError_WatchpointAccessed;
1283     break;
1284   case ADP_Stopped_StepComplete:
1285     stopped_info->stopped_status = RDIError_ProgramFinishedInStep;
1286     break;
1287   case ADP_Stopped_RunTimeErrorUnknown:
1288   case ADP_Stopped_StackOverflow:
1289   case ADP_Stopped_DivisionByZero:
1290     stopped_info->stopped_status = RDIError_Error;
1291     break;
1292   case ADP_Stopped_FIQ:
1293     stopped_info->stopped_status = RDIError_FIQ;
1294     break;
1295   case ADP_Stopped_UserInterruption:
1296   case ADP_Stopped_OSSpecific:
1297     stopped_info->stopped_status = RDIError_UserInterrupt;
1298     break;
1299   case ADP_Stopped_ApplicationExit:
1300     stopped_info->stopped_status = RDIError_NoError;
1301     break;
1302   default:
1303     stopped_info->stopped_status = RDIError_NoError;
1304     break;
1305   }
1306   return RDIError_NoError;
1307 }
1308
1309 static volatile bool interrupt_request = FALSE;
1310
1311 static void interrupt_target( void )
1312 {
1313     Packet *packet = NULL;
1314     int err;
1315     int reason, debugID, OSinfo1, OSinfo2, status;
1316
1317 #ifdef DEBUG
1318     angel_DebugPrint("DEBUG: interrupt_target.\n");
1319 #endif
1320
1321     register_debug_message_handler();
1322     msgsend(CI_HADP, "%w%w%w%w", ADP_InterruptRequest | HtoT, 0,
1323                    ADP_HandleUnknown, ADP_HandleUnknown);
1324
1325     reason = ADP_InterruptRequest |TtoH;
1326     err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
1327                               &status, &packet);
1328     DevSW_FreePacket(packet);
1329 #ifdef DEBUG
1330     angel_DebugPrint("DEBUG: got interrupt ack ok err = %d, status=%i\n",
1331                      err, status);
1332 #endif
1333
1334     return;
1335 }
1336
1337 #ifdef TEST_DC_APPL
1338   extern void test_dc_appl_handler( const DeviceDescr *device,
1339                                     Packet *packet );
1340 #endif
1341
1342 /* Core functionality for execute and step */
1343 static int angel_RDI_ExecuteOrStep(PointHandle *handle, word type, 
1344                                    unsigned ninstr)
1345 {
1346   int err;
1347   adp_stopped_struct stopped_info;
1348   void* stateptr = (void *)&stopped_info;
1349   ChannelCallback HandleStoppedMessageFPtr=(ChannelCallback) HandleStoppedMessage;
1350   int status, reasoncode, debugID, OSinfo1, OSinfo2;
1351   Packet *packet = NULL;
1352
1353   TracePrint(("angel_RDI_ExecuteOrStep\n"));
1354
1355   err = Adp_ChannelRegisterRead(CI_TADP,
1356                                 HandleStoppedMessageFPtr, stateptr);
1357   if (err != RDIError_NoError) {
1358 #ifdef DEBUG
1359     angel_DebugPrint("TADP Register failed.\n");
1360 #endif
1361     return err;
1362   }
1363   /* Set executing TRUE here, as it must be set up before the target has
1364    * had any chance at all to execute, or it may send its stopped message
1365    * before we get round to setting executing = TRUE !!!
1366    */
1367   executing = TRUE;
1368
1369   register_debug_message_handler();
1370
1371 #ifdef TEST_DC_APPL
1372   Adp_Install_DC_Appl_Handler( test_dc_appl_handler );
1373 #endif
1374
1375 #ifdef DEBUG
1376   angel_DebugPrint("Transmiting %s message.\n",
1377                    type == ADP_Execute ? "execute": "step");
1378 #endif
1379
1380   register_debug_message_handler();
1381   /* Extra ninstr parameter for execute message will simply be ignored */
1382   err = msgsend(CI_HADP,"%w%w%w%w%w", type | HtoT, 0,
1383                 ADP_HandleUnknown, ADP_HandleUnknown, ninstr);
1384 #if DEBUG
1385   if (err != RDIError_NoError) angel_DebugPrint("Transmit failed.\n");
1386 #endif
1387
1388   reasoncode = type | TtoH;
1389   err = wait_for_debug_message( &reasoncode, &debugID, &OSinfo1, &OSinfo2,
1390                                 &status, &packet );
1391   if (err != RDIError_NoError)
1392      return err;
1393   else if (status != RDIError_NoError)
1394      return status;
1395
1396 #ifdef DEBUG
1397   angel_DebugPrint("Waiting for program to finish...\n");
1398 #endif
1399
1400   while( executing )
1401   {
1402       if (interrupt_request)
1403       {
1404         interrupt_target();
1405         interrupt_request = FALSE;
1406       }
1407       Adp_AsynchronousProcessing( async_block_on_nothing );
1408   }
1409
1410 #ifdef TEST_DC_APPL
1411   Adp_Install_DC_Appl_Handler( NULL );
1412 #endif
1413
1414   (void)Adp_ChannelRegisterRead(CI_TADP, NULL, NULL);
1415
1416   *handle = (PointHandle)stopped_info.data;
1417
1418   CallStoppedProcs(stopped_info.stopped_reason);
1419
1420   return stopped_info.stopped_status;
1421 }
1422
1423 /* Request that the target starts executing from the stored CPU state: use
1424    ADP_Execute. */
1425 int angel_RDI_execute(PointHandle *handle)
1426 {
1427     return angel_RDI_ExecuteOrStep(handle, ADP_Execute, 0);
1428 }
1429
1430 #ifdef __WATCOMC__
1431 typedef void handlertype(int);
1432
1433 static int interrupted=0;
1434
1435 static void myhandler(int sig) {
1436   IGNORE(sig);
1437   interrupted=1;
1438   signal(SIGINT, myhandler);
1439 }
1440 #endif
1441
1442 /*----------------------------------------------------------------------*/
1443 /*----angel_RDI_step-----------------------------------------------------*/
1444 /*----------------------------------------------------------------------*/
1445
1446 /* Step 'ninstr' through the code: use ADP_Step. */
1447 int angel_RDI_step(unsigned ninstr, PointHandle *handle)
1448 {
1449     int err = angel_RDI_ExecuteOrStep(handle, ADP_Step, ninstr);
1450     if (err == RDIError_ProgramFinishedInStep)
1451        return RDIError_NoError;
1452     else
1453        return err;
1454 }
1455
1456
1457 static void SetCPWords(int cpnum, struct Dbg_CoProDesc const *cpd) {
1458   int i, rmax = 0;
1459   for (i = 0; i < cpd->entries; i++)
1460     if (cpd->regdesc[i].rmax > rmax)
1461       rmax = cpd->regdesc[i].rmax;
1462
1463   { unsigned char *rmap = (unsigned char *)malloc(rmax + 2);
1464     *rmap++ = rmax + 1;
1465     for (i = 0; i < cpd->entries; i++) {
1466       int r;
1467       for (r = cpd->regdesc[i].rmin; r <= cpd->regdesc[i].rmax; r++)
1468         rmap[r] = (cpd->regdesc[i].nbytes+3) / 4;
1469       }
1470 /*    if (cpwords[cpnum] != NULL) free(cpwords[cpnum]); */
1471     cpwords[cpnum] = rmap;
1472   }
1473 }
1474
1475 /*----------------------------------------------------------------------*/
1476 /*----angel_RDI_info-----------------------------------------------------*/
1477 /*----------------------------------------------------------------------*/
1478
1479 /* Use ADP_Info, ADP_Ctrl and ADP_Profile calls to implement these,
1480    see adp.h for more details. */
1481
1482 static int angel_cc_exists( void )
1483 {
1484   Packet *packet = NULL;
1485   int err;
1486   int reason, debugID, OSinfo1, OSinfo2, subreason, status;
1487
1488 #ifdef DEBUG
1489   angel_DebugPrint("DEBUG: ADP_ICEB_CC_Exists.\n");
1490 #endif
1491
1492   if ( angel_RDI_info( RDIInfo_Icebreaker, NULL, NULL ) == RDIError_NoError ) {
1493     register_debug_message_handler();
1494     msgsend(CI_HADP, "%w%w%w%w%w", ADP_ICEbreakerHADP | HtoT, 0,
1495             ADP_HandleUnknown, ADP_HandleUnknown,
1496             ADP_ICEB_CC_Exists );
1497     reason = ADP_ICEbreakerHADP |TtoH;
1498     err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
1499                                 &status, &packet);
1500     if (err != RDIError_NoError) {
1501       DevSW_FreePacket(packet);
1502       return err;
1503     }
1504     unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w", &reason,
1505                    &debugID, &OSinfo1, &OSinfo2,  &subreason, &status);
1506     if (subreason !=  ADP_ICEB_CC_Exists) {
1507       DevSW_FreePacket(packet);
1508       return RDIError_Error;
1509     }
1510     else
1511       return status;
1512   }
1513   else
1514     return RDIError_UnimplementedMessage;
1515 }
1516
1517 typedef struct {
1518   RDICCProc_ToHost *tohost; void *tohostarg;
1519   RDICCProc_FromHost *fromhost; void *fromhostarg;
1520   bool registered;
1521 } CCState;
1522 static CCState ccstate = { NULL, NULL, NULL, NULL, FALSE };
1523
1524 static void HandleDCCMessage( Packet *packet, void *stateptr )
1525 {
1526   unsigned int reason, debugID, OSinfo1, OSinfo2;
1527   int count;
1528   CCState *ccstate_p = (CCState *)stateptr;
1529
1530   count = unpack_message( BUFFERDATA(packet->pk_buffer), "%w%w%w%w",
1531                           &reason, &debugID, &OSinfo1, &OSinfo2 );
1532   switch ( reason )
1533   {
1534       case ADP_TDCC_ToHost | TtoH:
1535       {
1536            /* only handles a single word of data, for now */
1537
1538           unsigned int nbytes, data;
1539
1540           unpack_message( BUFFERDATA(packet->pk_buffer)+count, "%w%w",
1541                           &nbytes, &data );
1542 #ifdef DEBUG
1543           angel_DebugPrint( "DEBUG: received CC_ToHost message: nbytes %d data %08x.\n",
1544                   nbytes, data );
1545 #endif
1546           ccstate_p->tohost( ccstate_p->tohostarg, data );
1547           msgsend(CI_TTDCC, "%w%w%w%w%w",
1548                   ADP_TDCC_ToHost | HtoT, debugID, OSinfo1, OSinfo2,
1549                   RDIError_NoError );
1550           break;
1551       }
1552
1553       case ADP_TDCC_FromHost | TtoH:
1554       {
1555            /* only handles a single word of data, for now */
1556
1557           int valid;
1558           ARMword data;
1559
1560           ccstate_p->fromhost( ccstate_p->fromhostarg, &data, &valid );
1561 #ifdef DEBUG
1562           angel_DebugPrint( "DEBUG: received CC_FromHost message, returning: %08x %s.\n",
1563                   data, valid ? "VALID" : "INvalid" );
1564 #endif
1565           msgsend(CI_TTDCC, "%w%w%w%w%w%w%w",
1566                   ADP_TDCC_FromHost | HtoT, debugID, OSinfo1, OSinfo2,
1567                   RDIError_NoError, valid ? 1 : 0, data );
1568           break;
1569       }
1570
1571       default:
1572 #ifdef DEBUG
1573       angel_DebugPrint( "Unexpected TDCC message %08x received\n", reason );
1574 #endif
1575       break;
1576   }
1577   DevSW_FreePacket(packet);
1578   return;
1579 }
1580
1581 static void angel_check_DCC_handler( CCState *ccstate_p )
1582 {
1583     int err;
1584
1585     if ( ccstate_p->tohost != NULL || ccstate_p->fromhost != NULL )
1586     {
1587         /* doing DCC, so need a handler */
1588         if ( ! ccstate_p->registered )
1589         {
1590 #ifdef DEBUG
1591             angel_DebugPrint( "Registering handler for TTDCC channel.\n" );
1592 #endif
1593             err = Adp_ChannelRegisterRead( CI_TTDCC, HandleDCCMessage,
1594                                            ccstate_p );
1595             if ( err == adp_ok )
1596                ccstate_p->registered = TRUE;
1597 #ifdef DEBUG
1598             else
1599                angel_DebugPrint( "angel_check_DCC_handler: register failed!\n" );
1600 #endif
1601         }
1602     }
1603     else
1604     {
1605         /* not doing DCC, so don't need a handler */
1606         if ( ccstate_p->registered )
1607         {
1608 #ifdef DEBUG
1609             angel_DebugPrint( "Unregistering handler for TTDCC channel.\n" );
1610 #endif
1611             err = Adp_ChannelRegisterRead( CI_TTDCC, NULL, NULL );
1612             if ( err == adp_ok )
1613                ccstate_p->registered = FALSE;
1614 #ifdef DEBUG
1615             else
1616                angel_DebugPrint( "angel_check_DCC_handler: unregister failed!\n" );
1617 #endif
1618         }
1619     }
1620 }
1621
1622
1623 static int CheckSubMessageReply(int reason, int subreason) {
1624   Packet *packet = NULL;
1625   int status, debugID, OSinfo1, OSinfo2;
1626   int err = RDIError_NoError;
1627   reason |= TtoH;
1628   err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
1629                                &status, &packet);
1630   if (err != RDIError_NoError) {
1631     status = err;
1632   } else {
1633     int sr;
1634     unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w", &reason, &debugID,
1635                    &OSinfo1, &OSinfo2, &sr, &status);
1636     if (subreason != sr) status = RDIError_Error;
1637   }
1638   DevSW_FreePacket(packet);
1639   return status;
1640 }
1641
1642 static int SendSubMessageAndCheckReply(int reason, int subreason) {
1643   register_debug_message_handler();
1644   msgsend(CI_HADP, "%w%w%w%w%w", reason | HtoT, 0,
1645           ADP_HandleUnknown, ADP_HandleUnknown,
1646           subreason);
1647   return CheckSubMessageReply(reason, subreason);
1648 }
1649
1650 static int SendSubMessageWordAndCheckReply(int reason, int subreason, ARMword word) {
1651   register_debug_message_handler();
1652   msgsend(CI_HADP, "%w%w%w%w%w%w", reason | HtoT, 0,
1653           ADP_HandleUnknown, ADP_HandleUnknown,
1654           subreason, word);
1655   return CheckSubMessageReply(reason, subreason);
1656 }
1657
1658 static int SendSubMessageGetWordAndCheckReply(int reason, int subreason, ARMword *resp) {
1659   Packet *packet = NULL;
1660   int status, debugID, OSinfo1, OSinfo2;
1661   int err = RDIError_NoError;
1662
1663   register_debug_message_handler();
1664   msgsend(CI_HADP, "%w%w%w%w%w", reason | HtoT, 0,
1665           ADP_HandleUnknown, ADP_HandleUnknown,
1666           subreason);
1667   reason |= TtoH;
1668   err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
1669                                &status, &packet);
1670   if (err != RDIError_NoError) {
1671     status = err;
1672   } else {
1673     int sr;
1674     unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w%w", &reason, &debugID,
1675                    &OSinfo1, &OSinfo2,  &sr, &status, resp);
1676     if (subreason != sr) status = RDIError_Error;
1677   }
1678   DevSW_FreePacket(packet);
1679   return status;
1680 }
1681
1682 static int const hostsex = 1;
1683
1684 int angel_RDI_info(unsigned type, ARMword *arg1, ARMword *arg2) {
1685   Packet *packet = NULL;
1686   int len, status, c, reason, subreason, debugID, OSinfo1, OSinfo2;
1687   int err=RDIError_NoError, cpnum=0;
1688   struct Dbg_CoProDesc *cpd;
1689   int count, i;
1690   unsigned char *bp;
1691
1692 #ifdef DEBUG
1693   angel_DebugPrint("DEBUG: Entered angel_RDI_info.\n");
1694 #endif
1695   switch (type) {
1696   case RDIInfo_Target:
1697 #ifdef DEBUG
1698     angel_DebugPrint("DEBUG: RDIInfo_Target.\n");
1699 #endif
1700
1701     register_debug_message_handler();
1702     msgsend(CI_HADP, "%w%w%w%w%w", ADP_Info | HtoT, 0,
1703                  ADP_HandleUnknown, ADP_HandleUnknown, ADP_Info_Target);
1704     reason = ADP_Info |TtoH;
1705     err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
1706                               &status, &packet);
1707     if (err != RDIError_NoError) {
1708       DevSW_FreePacket(packet);
1709       return err;
1710     }
1711     unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w%w%w", &reason,
1712                    &debugID, &OSinfo1, &OSinfo2,  &subreason, &status,
1713                    arg1, arg2);
1714     DevSW_FreePacket(packet);
1715
1716     if (subreason !=  ADP_Info_Target)
1717       return RDIError_Error;
1718     else
1719       return status;
1720
1721   case RDISignal_Stop:
1722 #ifdef DEBUG
1723     angel_DebugPrint("DEBUG: RDISignal_Stop.\n");
1724     if (interrupt_request)
1725        angel_DebugPrint("       STILL WAITING to send previous interrupt request\n");
1726 #endif
1727     interrupt_request = TRUE;
1728     return RDIError_NoError;
1729
1730   case RDIInfo_Points:
1731 #ifdef DEBUG
1732     angel_DebugPrint("DEBUG: RDIInfo_Points.\n");
1733 #endif
1734     return SendSubMessageGetWordAndCheckReply(ADP_Info, ADP_Info_Points, arg1);
1735
1736   case RDIInfo_Step:
1737 #ifdef DEBUG
1738     angel_DebugPrint("DEBUG: RDIInfo_Step.\n");
1739 #endif
1740     return SendSubMessageGetWordAndCheckReply(ADP_Info, ADP_Info_Step, arg1);
1741
1742   case RDISet_Cmdline:
1743 #ifdef DEBUG
1744     angel_DebugPrint("DEBUG: RDISet_Cmdline.\n");
1745 #endif
1746     if (ardi_commandline != &dummycline)
1747       free(ardi_commandline);
1748     ardi_commandline = (char *)malloc(strlen((char*)arg1) + 1) ;
1749     (void)strcpy(ardi_commandline, (char *)arg1) ;
1750     return RDIError_NoError;
1751
1752   case RDIInfo_SetLog:
1753 #ifdef DEBUG
1754     angel_DebugPrint("DEBUG: RDIInfo_SetLog.\n");
1755 #endif
1756     rdi_log = (int) *arg1;
1757     return RDIError_NoError;
1758
1759   case RDIInfo_Log:
1760 #ifdef DEBUG
1761     angel_DebugPrint("DEBUG: RDIInfo_Log.\n");
1762 #endif
1763     *arg1 = rdi_log;
1764     return RDIError_NoError;
1765
1766
1767   case RDIInfo_MMU:
1768 #ifdef DEBUG
1769     angel_DebugPrint("DEBUG: RDIInfo_MMU.\n");
1770 #endif
1771     return SendSubMessageGetWordAndCheckReply(ADP_Info, ADP_Info_MMU, arg1);
1772
1773   case RDIInfo_SemiHosting:
1774 #ifdef DEBUG
1775     angel_DebugPrint("DEBUG: RDIInfo_SemiHosting.\n");
1776 #endif
1777     return SendSubMessageAndCheckReply(ADP_Info, ADP_Info_SemiHosting);
1778
1779   case RDIInfo_CoPro:
1780 #ifdef DEBUG
1781     angel_DebugPrint("DEBUG: RDIInfo_CoPro.\n");
1782 #endif
1783     return SendSubMessageAndCheckReply(ADP_Info, ADP_Info_CoPro);
1784
1785   case RDICycles:
1786 #ifdef DEBUG
1787     angel_DebugPrint("DEBUG: RDICycles.\n");
1788 #endif
1789     register_debug_message_handler();
1790     msgsend(CI_HADP, "%w%w%w%w%w", ADP_Info | HtoT, 0,
1791             ADP_HandleUnknown, ADP_HandleUnknown, ADP_Info_Cycles);
1792     reason = ADP_Info |TtoH;
1793     err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
1794                               &status, &packet);
1795     if (err != RDIError_NoError) {
1796       DevSW_FreePacket(packet);
1797       return err;
1798     }
1799     unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w", &reason, &debugID,
1800                  &OSinfo1, &OSinfo2,  &subreason, &status);
1801     DevSW_FreePacket(packet);
1802     if (subreason !=  ADP_Info_Cycles)
1803       return RDIError_Error;
1804     if (status != RDIError_NoError) return status;
1805     for (c=0; c<12; c++)
1806       arg1[c]=GET32LE(BUFFERDATA(packet->pk_buffer)+24+(c*4));
1807     return status;
1808
1809   case RDIInfo_DescribeCoPro:
1810 #ifdef DEBUG
1811     angel_DebugPrint("DEBUG: RDIInfo_DescribeCoPro.\n");
1812 #endif
1813     cpnum = *(int *)arg1;
1814     cpd = (struct Dbg_CoProDesc *)arg2;
1815     packet = DevSW_AllocatePacket(Armsd_BufferSize);
1816     if (angel_RDI_info(ADP_Info_CoPro, NULL, NULL) != RDIError_NoError)
1817       return RDIError_Error;
1818     len = msgbuild(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w", ADP_Info | HtoT, 0,
1819                    ADP_HandleUnknown, ADP_HandleUnknown,
1820                    ADP_Info_DescribeCoPro);
1821     len +=msgbuild(BUFFERDATA(packet->pk_buffer)+20, "%b%b%b%b%b", cpnum,
1822                    cpd->regdesc[cpnum].rmin, cpd->regdesc[cpnum].rmax,
1823                    cpd->regdesc[cpnum].nbytes, cpd->regdesc[cpnum].access);
1824     if (cpd->regdesc[cpnum].access&0x3 == 0x3){
1825       len += msgbuild(BUFFERDATA(packet->pk_buffer)+25, "%b%b%b%b%b",
1826                       cpd->regdesc[cpnum].accessinst.cprt.read_b0,
1827                       cpd->regdesc[cpnum].accessinst.cprt.read_b1,
1828                       cpd->regdesc[cpnum].accessinst.cprt.write_b0,
1829                       cpd->regdesc[cpnum].accessinst.cprt.write_b1, 0xff);
1830     }
1831     else {
1832       len += msgbuild(BUFFERDATA(packet->pk_buffer)+25, "%b%b%b%b%b%",
1833                       cpd->regdesc[cpnum].accessinst.cpdt.rdbits,
1834                       cpd->regdesc[cpnum].accessinst.cpdt.nbit,0,0, 0xff);
1835     }
1836     register_debug_message_handler();
1837     packet->pk_length = len;
1838     Adp_ChannelWrite(CI_HADP, packet); /* Transmit message. */
1839     reason = ADP_Info |TtoH;
1840     err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
1841                                 &status, &packet);
1842     if (err != RDIError_NoError) {
1843       DevSW_FreePacket(packet);
1844       return err;
1845     }
1846     unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w", &reason, &debugID,
1847                    &OSinfo1, &OSinfo2, &subreason, &status);
1848     DevSW_FreePacket(packet);
1849     if (subreason != ADP_Info_DescribeCoPro)
1850       return RDIError_Error;
1851     else
1852       return status;
1853
1854   case RDIInfo_RequestCoProDesc:
1855 #ifdef DEBUG
1856     angel_DebugPrint("DEBUG: RDIInfo_RequestCoProDesc.\n");
1857 #endif
1858     cpnum = *(int *)arg1;
1859     cpd = (struct Dbg_CoProDesc *)arg2;
1860     packet = DevSW_AllocatePacket(Armsd_BufferSize);
1861     len = msgbuild(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w", ADP_Info | HtoT, 0,
1862                    ADP_HandleUnknown, ADP_HandleUnknown,
1863                    ADP_Info_RequestCoProDesc);
1864     len += msgbuild(BUFFERDATA(packet->pk_buffer)+20, "%b", *(int *)arg1);
1865     packet->pk_length = len;
1866     register_debug_message_handler();
1867     Adp_ChannelWrite(CI_HADP, packet); /* Transmit message. */
1868     reason = ADP_Info |TtoH;
1869     err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
1870                               &status, &packet);
1871     if (err != RDIError_NoError) {
1872       DevSW_FreePacket(packet);
1873       return err;
1874     }
1875     count = unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w", &reason,
1876                            &debugID, &OSinfo1, &OSinfo2,  &subreason, &status);
1877     if (subreason !=  ADP_Info_RequestCoProDesc) {
1878       DevSW_FreePacket(packet);
1879       return RDIError_Error;
1880     } else if ( status != RDIError_NoError ) {
1881       DevSW_FreePacket(packet);
1882       return status;
1883     } else {
1884       bp = BUFFERDATA(packet->pk_buffer)+count;
1885       for ( i = 0; *bp != 0xFF && i < cpd->entries; ++i ) {
1886         cpd->regdesc[i].rmin = *bp++;
1887         cpd->regdesc[i].rmax = *bp++;
1888         cpd->regdesc[i].nbytes = *bp++;
1889         cpd->regdesc[i].access = *bp++;
1890       }
1891       cpd->entries = i;
1892       if ( *bp != 0xFF )
1893         status = RDIError_BufferFull;
1894       else
1895         SetCPWords( cpnum, cpd );
1896       DevSW_FreePacket(packet);
1897       return status;
1898     }
1899
1900   case RDIInfo_GetLoadSize:
1901 #ifdef DEBUG
1902     angel_DebugPrint("DEBUG: ADP_Info_AngelBufferSize.\n");
1903 #endif
1904     register_debug_message_handler();
1905     msgsend(CI_HADP, "%w%w%w%w%w", ADP_Info | HtoT, 0,
1906             ADP_HandleUnknown, ADP_HandleUnknown,
1907             ADP_Info_AngelBufferSize);
1908     reason = ADP_Info |TtoH;
1909     err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
1910                               &status, &packet);
1911     if (err != RDIError_NoError) {
1912       DevSW_FreePacket(packet);
1913       return err;
1914     }
1915     unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w", &reason,
1916                    &debugID, &OSinfo1, &OSinfo2,  &subreason, &status);
1917     if (subreason !=  ADP_Info_AngelBufferSize) {
1918       DevSW_FreePacket(packet);
1919       return RDIError_Error;
1920     }
1921     else {
1922       word defaultsize, longsize;
1923       unpack_message(BUFFERDATA(packet->pk_buffer)+24, "%w%w",
1924                      &defaultsize, &longsize);
1925       *arg1 = longsize - ADP_WriteHeaderSize;   /* space for ADP header */
1926 #ifdef MONITOR_DOWNLOAD_PACKETS
1927       angel_DebugPrint("DEBUG: ADP_Info_AngelBufferSize: got (%d, %d), returning %d.\n",
1928              defaultsize, longsize, *arg1);
1929 #endif
1930       DevSW_FreePacket(packet);
1931       return status;
1932     }
1933
1934   case RDIVector_Catch:
1935 #ifdef DEBUG
1936     angel_DebugPrint("DEBUG: ADP_Ctrl_VectorCatch %lx.\n", *arg1);
1937 #endif
1938     return SendSubMessageWordAndCheckReply(ADP_Control, ADP_Ctrl_VectorCatch, *arg1);
1939
1940   case RDISemiHosting_SetState:
1941 #ifdef DEBUG
1942     angel_DebugPrint("DEBUG: ADP_Ctrl_SemiHosting_SetState %lx.\n", *arg1);
1943 #endif
1944     return SendSubMessageWordAndCheckReply(ADP_Control, ADP_Ctrl_SemiHosting_SetState, *arg1);
1945
1946   case RDISemiHosting_GetState:
1947 #ifdef DEBUG
1948     angel_DebugPrint("DEBUG: ADP_Ctrl_SemiHosting_GetState.\n");
1949 #endif
1950     return SendSubMessageGetWordAndCheckReply(ADP_Control, ADP_Ctrl_SemiHosting_GetState, arg1);
1951
1952   case RDISemiHosting_SetVector:
1953 #ifdef DEBUG
1954     angel_DebugPrint("DEBUG: ADP_Ctrl_SemiHosting_SetVector %lx.\n", *arg1);
1955 #endif
1956     return SendSubMessageWordAndCheckReply(ADP_Control, ADP_Ctrl_SemiHosting_SetVector, *arg1);
1957
1958   case RDISemiHosting_GetVector:
1959 #ifdef DEBUG
1960     angel_DebugPrint("DEBUG: ADP_Ctrl_SemiHosting_GetVector.\n");
1961 #endif
1962     return SendSubMessageGetWordAndCheckReply(ADP_Control, ADP_Ctrl_SemiHosting_GetVector, arg1);
1963
1964   case RDISemiHosting_SetARMSWI:
1965 #ifdef DEBUG
1966     angel_DebugPrint("DEBUG: ADP_Ctrl_SemiHosting_SetARMSWI.\n");
1967 #endif
1968     return SendSubMessageWordAndCheckReply(ADP_Control, ADP_Ctrl_SemiHosting_SetARMSWI, *arg1);
1969
1970   case RDISemiHosting_GetARMSWI:
1971 #ifdef DEBUG
1972     angel_DebugPrint("DEBUG: ADP_Ctrl_SemiHosting_GetARMSWI.\n");
1973 #endif
1974     return SendSubMessageGetWordAndCheckReply(ADP_Control, ADP_Ctrl_SemiHosting_GetARMSWI, arg1);
1975
1976   case RDISemiHosting_SetThumbSWI:
1977 #ifdef DEBUG
1978     angel_DebugPrint("DEBUG: ADP_Ctrl_SemiHosting_SetThumbSWI.\n");
1979 #endif
1980     return SendSubMessageWordAndCheckReply(ADP_Control, ADP_Ctrl_SemiHosting_SetThumbSWI, *arg1);
1981
1982   case RDISemiHosting_GetThumbSWI:
1983 #ifdef DEBUG
1984     angel_DebugPrint("DEBUG: ADP_Ctrl_SemiHosting_GetThumbSWI.\n");
1985 #endif
1986     return SendSubMessageGetWordAndCheckReply(ADP_Control, ADP_Ctrl_SemiHosting_GetThumbSWI, arg1);
1987
1988   case RDIInfo_SetTopMem:
1989 #ifdef DEBUG
1990     angel_DebugPrint("DEBUG: ADP_Ctrl_SetTopMem.\n");
1991 #endif
1992     return SendSubMessageWordAndCheckReply(ADP_Control, ADP_Ctrl_SetTopMem, *arg1);
1993
1994   case RDIPointStatus_Watch:
1995 #ifdef DEBUG
1996     angel_DebugPrint("DEBUG: ADP_Ctrl_PointStatus_Watch.\n");
1997 #endif
1998     register_debug_message_handler();
1999     msgsend(CI_HADP, "%w%w%w%w%w%w", ADP_Control | HtoT, 0,
2000             ADP_HandleUnknown, ADP_HandleUnknown,
2001             ADP_Ctrl_PointStatus_Watch, *arg1 );
2002     reason = ADP_Control |TtoH;
2003     err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
2004                               &status, &packet);
2005     if (err != RDIError_NoError) {
2006       DevSW_FreePacket(packet);
2007       return err;
2008     }
2009     unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w%w%w", &reason,
2010                    &debugID, &OSinfo1, &OSinfo2,  &subreason, &status,
2011                    arg1, arg2);
2012     if (subreason !=  ADP_Ctrl_PointStatus_Watch) {
2013       DevSW_FreePacket(packet);
2014       return RDIError_Error;
2015     }
2016     else
2017       return status;
2018
2019   case RDIPointStatus_Break:
2020 #ifdef DEBUG
2021     angel_DebugPrint("DEBUG: ADP_Ctrl_PointStatus_Break.\n");
2022 #endif
2023     register_debug_message_handler();
2024     msgsend(CI_HADP, "%w%w%w%w%w%w", ADP_Control | HtoT, 0,
2025             ADP_HandleUnknown, ADP_HandleUnknown,
2026             ADP_Ctrl_PointStatus_Break, *arg1 );
2027     reason = ADP_Control |TtoH;
2028     err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
2029                               &status, &packet);
2030     if (err != RDIError_NoError) {
2031       DevSW_FreePacket(packet);
2032       return err;
2033     }
2034     unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w%w%w", &reason,
2035                    &debugID, &OSinfo1, &OSinfo2,  &subreason, &status,
2036                    arg1, arg2);
2037     if (subreason !=  ADP_Ctrl_PointStatus_Break) {
2038       DevSW_FreePacket(packet);
2039       return RDIError_Error;
2040     }
2041     else
2042       return status;
2043
2044   case RDIInfo_DownLoad:
2045 #ifdef DEBUG
2046     angel_DebugPrint("DEBUG: ADP_Ctrl_Download_Supported.\n");
2047 #endif
2048     return SendSubMessageAndCheckReply(ADP_Control, ADP_Ctrl_Download_Supported);
2049
2050   case RDIConfig_Count:
2051 #ifdef DEBUG
2052     angel_DebugPrint("DEBUG: ADP_ICEM_ConfigCount.\n");
2053 #endif
2054     return SendSubMessageGetWordAndCheckReply(ADP_ICEman, ADP_ICEM_ConfigCount, arg1);
2055
2056   case RDIConfig_Nth:
2057 #ifdef DEBUG
2058     angel_DebugPrint("DEBUG: ADP_ICEM_ConfigNth.\n");
2059 #endif
2060     register_debug_message_handler();
2061     msgsend(CI_HADP, "%w%w%w%w%w%w", ADP_ICEman | HtoT, 0,
2062             ADP_HandleUnknown, ADP_HandleUnknown,
2063             ADP_ICEM_ConfigNth, *arg1 );
2064     reason = ADP_ICEman |TtoH;
2065     err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
2066                               &status, &packet);
2067     if (err != RDIError_NoError) {
2068       DevSW_FreePacket(packet);
2069       return err;
2070     } else {
2071       RDI_ConfigDesc *cd = (RDI_ConfigDesc *)arg2;
2072       unsigned char n;
2073       len = unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w%w%b",
2074                            &reason, &debugID,
2075                            &OSinfo1, &OSinfo2,  &subreason, &status,
2076                            &cd->version, &n);
2077       if (subreason !=  ADP_ICEM_ConfigNth) {
2078         DevSW_FreePacket(packet);
2079         return RDIError_Error;
2080       }
2081       else {
2082         memcpy( cd->name, BUFFERDATA(packet->pk_buffer)+len, n+1 );
2083         cd->name[n] = 0;
2084         return status;
2085       }
2086     }
2087
2088   case RDIInfo_Icebreaker:
2089 #ifdef DEBUG
2090     angel_DebugPrint("DEBUG: ADP_ICEB_Exists.\n");
2091 #endif
2092     return SendSubMessageAndCheckReply(ADP_ICEbreakerHADP, ADP_ICEB_Exists);
2093
2094   case RDIIcebreaker_GetLocks:
2095 #ifdef DEBUG
2096     angel_DebugPrint("DEBUG: ADP_ICEB_GetLocks.\n");
2097 #endif
2098     return SendSubMessageGetWordAndCheckReply(ADP_ICEbreakerHADP, ADP_ICEB_GetLocks, arg1);
2099
2100   case RDIIcebreaker_SetLocks:
2101 #ifdef DEBUG
2102     angel_DebugPrint("DEBUG: ADP_ICEB_SetLocks.\n");
2103 #endif
2104     return SendSubMessageWordAndCheckReply(ADP_ICEbreakerHADP, ADP_ICEB_SetLocks, *arg1);
2105
2106   case RDICommsChannel_ToHost:
2107 #ifdef DEBUG
2108     angel_DebugPrint("DEBUG: ADP_ICEB_CC_Connect_ToHost.\n");
2109 #endif
2110     if ( angel_cc_exists() == RDIError_NoError ) {
2111
2112     /*
2113      * The following three lines of code have to be removed in order to get
2114      * the Windows Angel Channel Viewer working with the Thumb comms channel.
2115      * At the moment it allows the ARMSD command line to register a CCIN/CCOUT
2116      * callback which stops the ACV working!
2117      */
2118 #ifdef __unix
2119       ccstate.tohost = (RDICCProc_ToHost *)arg1;
2120       ccstate.tohostarg = arg2;
2121       angel_check_DCC_handler( &ccstate );
2122 #endif
2123 #ifdef _WIN32
2124       
2125 #endif
2126
2127       register_debug_message_handler();
2128       msgsend(CI_HADP, "%w%w%w%w%w%b", ADP_ICEbreakerHADP | HtoT, 0,
2129               ADP_HandleUnknown, ADP_HandleUnknown,
2130               ADP_ICEB_CC_Connect_ToHost, (arg1 != NULL) );
2131       return CheckSubMessageReply(ADP_ICEbreakerHADP, ADP_ICEB_CC_Connect_ToHost);
2132     } else {
2133       return RDIError_UnimplementedMessage;
2134     }
2135
2136   case RDICommsChannel_FromHost:
2137 #ifdef DEBUG
2138     angel_DebugPrint("DEBUG: ADP_ICEB_CC_Connect_FromHost.\n");
2139 #endif
2140     if ( angel_cc_exists() == RDIError_NoError ) {
2141
2142       ccstate.fromhost = (RDICCProc_FromHost *)arg1;
2143       ccstate.fromhostarg = arg2;
2144       angel_check_DCC_handler( &ccstate );
2145
2146       register_debug_message_handler();
2147       msgsend(CI_HADP, "%w%w%w%w%w%b", ADP_ICEbreakerHADP | HtoT, 0,
2148               ADP_HandleUnknown, ADP_HandleUnknown,
2149               ADP_ICEB_CC_Connect_FromHost, (arg1 != NULL) );
2150       return CheckSubMessageReply(ADP_ICEbreakerHADP, ADP_ICEB_CC_Connect_FromHost);
2151     } else {
2152       return RDIError_UnimplementedMessage;
2153     }
2154
2155   case RDIProfile_Stop:
2156     return SendSubMessageAndCheckReply(ADP_Profile, ADP_Profile_Stop);
2157
2158   case RDIProfile_ClearCounts:
2159     return SendSubMessageAndCheckReply(ADP_Profile, ADP_Profile_ClearCounts);
2160
2161   case RDIProfile_Start:
2162 #ifdef DEBUG
2163     angel_DebugPrint("DEBUG: ADP_Profile_Start %ld.\n", (long)*arg1);
2164 #endif
2165     return SendSubMessageWordAndCheckReply(ADP_Profile, ADP_Profile_Start, *arg1);
2166
2167   case RDIProfile_WriteMap:
2168     { RDI_ProfileMap *map = (RDI_ProfileMap *)arg1;
2169       int32 maplen = map->len,
2170             offset,
2171             size;
2172       int32 chunk = (Armsd_LongBufSize-CHAN_HEADER_SIZE-ADP_ProfileWriteHeaderSize) / sizeof(ARMword);
2173                      /* Maximum number of words sendable in one message */
2174       int oldrev = bytesex_reversing();
2175       int host_little = *(uint8 const *)&hostsex;
2176 #ifdef DEBUG
2177       angel_DebugPrint("DEBUG: ADP_Profile_WriteMap %ld.\n", maplen);
2178 #endif
2179       status = RDIError_NoError;
2180       if (!host_little) {
2181         bytesex_reverse(1);
2182         for (offset = 0; offset < maplen; offset++)
2183           map->map[offset] = bytesex_hostval(map->map[offset]);
2184       }
2185       for (offset = 0; offset < maplen; offset += size) {
2186         unsigned hdrlen;
2187         size = maplen - offset;
2188         packet = (Packet *)DevSW_AllocatePacket(Armsd_LongBufSize);
2189         if (size > chunk) size = chunk;
2190         hdrlen = msgbuild(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w%w%w",
2191                           ADP_Profile | HtoT, 0, ADP_HandleUnknown,
2192                           ADP_HandleUnknown, ADP_Profile_WriteMap,
2193                           maplen, size, offset);
2194
2195         /* Copy the data into the packet. */
2196         memcpy(BUFFERDATA(packet->pk_buffer)+hdrlen,
2197                &map->map[offset], (size_t)size * sizeof(ARMword));
2198         packet->pk_length = size * sizeof(ARMword) + hdrlen;
2199         register_debug_message_handler();
2200         Adp_ChannelWrite(CI_HADP, packet);
2201         reason = ADP_Profile | TtoH;
2202         err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
2203                                      &status, &packet);
2204         if (err == RDIError_NoError) {
2205           unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w", &reason,
2206                          &debugID, &OSinfo1, &OSinfo2, &subreason, &status);
2207           if (subreason !=  ADP_Profile_WriteMap) {
2208             err = RDIError_Error;
2209           }
2210           DevSW_FreePacket(packet);
2211         }
2212         if (err != RDIError_NoError) { status = err; break; }
2213       }
2214       if (!host_little) {
2215         for (offset = 0; offset < maplen; offset++)
2216           map->map[offset] = bytesex_hostval(map->map[offset]);
2217         bytesex_reverse(oldrev);
2218       }
2219       return status;
2220     }
2221
2222   case RDIProfile_ReadMap:
2223     { int32 maplen = *(int32 *)arg1,
2224             offset = 0,
2225             size;
2226       int32 chunk = (Armsd_BufferSize-CHAN_HEADER_SIZE-ADP_ProfileReadHeaderSize) / sizeof(ARMword);
2227 #ifdef DEBUG
2228       angel_DebugPrint("DEBUG: ADP_Profile_ReadMap %ld.\n", maplen);
2229 #endif
2230       status = RDIError_NoError;
2231       for (offset = 0; offset < maplen; offset += size) {
2232         size = maplen - offset;
2233         if (size > chunk) size = chunk;
2234         register_debug_message_handler();
2235         msgsend(CI_HADP, "%w%w%w%w%w%w%w", ADP_Profile | HtoT, 0,
2236                 ADP_HandleUnknown, ADP_HandleUnknown,
2237                 ADP_Profile_ReadMap, offset, size);
2238         reason = ADP_Profile | TtoH;
2239         err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
2240                                      &status, &packet);
2241         if (err != RDIError_NoError) return err;
2242         unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w", &reason,
2243                        &debugID, &OSinfo1, &OSinfo2, &subreason, &status);
2244         memcpy(&arg2[offset], BUFFERDATA(packet->pk_buffer)+ADP_ProfileReadHeaderSize,
2245                size * sizeof(ARMword));
2246         DevSW_FreePacket(packet);
2247         if (status != RDIError_NoError) break;
2248       }
2249       { int oldrev = bytesex_reversing();
2250         int host_little = *(uint8 const *)&hostsex;
2251         if (!host_little) {
2252           bytesex_reverse(1);
2253           for (offset = 0; offset < maplen; offset++)
2254             arg2[offset] = bytesex_hostval(arg2[offset]);
2255         }
2256         bytesex_reverse(oldrev);
2257       }
2258       return status;
2259     }
2260
2261   case RDIInfo_CanTargetExecute:
2262 #ifdef DEBUG
2263     printf("DEBUG: RDIInfo_CanTargetExecute.\n");
2264 #endif
2265     return SendSubMessageAndCheckReply(ADP_Info, ADP_Info_CanTargetExecute);
2266
2267   case RDIInfo_AgentEndianess:
2268     return SendSubMessageAndCheckReply(ADP_Info, ADP_Info_AgentEndianess);
2269
2270   default:
2271 #ifdef DEBUG
2272     angel_DebugPrint("DEBUG: Fell through ADP_Info, default case taken.\n");
2273     angel_DebugPrint("DEBUG: type = 0x%x.\n", type);
2274 #endif
2275     if (type & RDIInfo_CapabilityRequest) {
2276       switch (type & ~RDIInfo_CapabilityRequest) {
2277         case RDISemiHosting_SetARMSWI:
2278           return SendSubMessageAndCheckReply(ADP_Info, ADP_Info_ChangeableSHSWI);
2279         default:
2280 #ifdef DEBUG
2281           angel_DebugPrint(
2282           "DEBUG: ADP_Info - Capability Request(%d) - reporting unimplemented \n",
2283                  type & ~RDIInfo_CapabilityRequest);
2284 #endif
2285           break;
2286       }
2287     }
2288     return RDIError_UnimplementedMessage;
2289   }
2290 }
2291
2292
2293 /*----------------------------------------------------------------------*/
2294 /*----angel_RDI_AddConfig------------------------------------------------*/
2295 /*----------------------------------------------------------------------*/
2296
2297 /* Add a configuration: use ADP_ICEM_AddConfig. */
2298 int angel_RDI_AddConfig(unsigned long nbytes) {
2299   Packet *packet = NULL;
2300   int status, reason, subreason, debugID, OSinfo1, OSinfo2, err;
2301
2302 #ifdef DEBUG
2303   angel_DebugPrint("DEBUG: Entered angel_RDI_AddConfig.\n");
2304 #endif
2305   register_debug_message_handler();
2306   msgsend(CI_HADP, "%w%w%w%w%w%w", ADP_ICEman | HtoT,
2307           0, ADP_HandleUnknown, ADP_HandleUnknown,
2308           ADP_ICEM_AddConfig, nbytes);
2309   reason=ADP_ICEman | TtoH;
2310   err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
2311                               &status, &packet);
2312   if (err != RDIError_NoError) {
2313     DevSW_FreePacket(packet);
2314     return -1;
2315   }
2316   unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w", &reason, &debugID,
2317                  &OSinfo1, &OSinfo2, &subreason, &status);
2318   DevSW_FreePacket(packet);
2319   if ( subreason != ADP_ICEM_AddConfig )
2320     return RDIError_Error;
2321   else
2322     return status;
2323 }
2324
2325
2326 /*----------------------------------------------------------------------*/
2327 /*----angel_RDI_LoadConfigData-------------------------------------------*/
2328 /*----------------------------------------------------------------------*/
2329
2330 /* Load configuration data: use ADP_Ctrl_Download_Data. */
2331 int angel_RDI_LoadConfigData(unsigned long nbytes, char const *data) {
2332   Packet *packet = NULL;
2333   int len, status, reason, subreason, debugID, OSinfo1, OSinfo2, err;
2334
2335 #ifdef DEBUG
2336   angel_DebugPrint("DEBUG: Entered angel_RDI_LoadConfigData (%d bytes)\n", nbytes);
2337 #endif
2338 #if 0
2339   if (err = angel_RDI_AddConfig(nbytes) != RDIError_NoError)
2340     return err;
2341 #endif
2342   packet = DevSW_AllocatePacket(Armsd_LongBufSize);
2343   len = msgbuild(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w",
2344                  ADP_Control | HtoT, 0,
2345                  ADP_HandleUnknown, ADP_HandleUnknown,
2346                  ADP_Ctrl_Download_Data, nbytes);
2347   memcpy(BUFFERDATA(packet->pk_buffer)+len, data, nbytes);
2348   len += nbytes;
2349   packet->pk_length = len;
2350 #ifdef DEBUG
2351   angel_DebugPrint("DEBUG: packet len %d.\n", len);
2352 #endif
2353   register_debug_message_handler();
2354   Adp_ChannelWrite(CI_HADP, packet);
2355   reason=ADP_Control | TtoH;
2356   err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
2357                               &status, &packet);
2358   if (err != RDIError_NoError) {
2359     DevSW_FreePacket(packet);
2360     return -1;
2361   }
2362   unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w", &reason, &debugID,
2363                  &OSinfo1, &OSinfo2, &subreason, &status);
2364   DevSW_FreePacket(packet);
2365   if ( subreason != ADP_Ctrl_Download_Data )
2366     return RDIError_Error;
2367   else
2368     return status;
2369 }
2370
2371
2372 /*----------------------------------------------------------------------*/
2373 /*----angel_RDI_SelectConfig---------------------------------------------*/
2374 /*----------------------------------------------------------------------*/
2375
2376 /* Select a configuration: use ADP_ICEM_SelecConfig.*/
2377 int angel_RDI_SelectConfig(RDI_ConfigAspect aspect, char const *name,
2378                            RDI_ConfigMatchType matchtype, unsigned versionreq,
2379                             unsigned *versionp)
2380 {
2381   Packet *packet = NULL;
2382   int len, status, reason, subreason, debugID, OSinfo1, OSinfo2, err;
2383
2384 #ifdef DEBUG
2385   angel_DebugPrint("DEBUG: Entered angel_RDI_SelectConfig.\n");
2386 #endif
2387   packet = DevSW_AllocatePacket(Armsd_BufferSize);
2388   len = msgbuild(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%b%b%b%w",
2389                  ADP_ICEman | HtoT, 0,
2390                  ADP_HandleUnknown, ADP_HandleUnknown,
2391                  ADP_ICEM_SelectConfig, aspect, strlen(name),
2392                  matchtype, versionreq);
2393   /* copy the name into the buffer */
2394   memcpy(BUFFERDATA(packet->pk_buffer)+len, name, strlen(name));
2395   len += strlen(name);
2396   packet->pk_length = len;
2397   register_debug_message_handler();
2398   Adp_ChannelWrite(CI_HADP, packet);
2399   reason=ADP_ICEman | TtoH;
2400   err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
2401                               &status, &packet);
2402   if (err != RDIError_NoError) {
2403     DevSW_FreePacket(packet);
2404     return err;
2405   }
2406   unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w%w",
2407                  &reason, &debugID, &OSinfo1, &OSinfo2,
2408                  &subreason, &status, versionp);
2409   DevSW_FreePacket(packet);
2410   if ( subreason != ADP_ICEM_SelectConfig )
2411     return RDIError_Error;
2412   else
2413     return status;
2414 }
2415
2416
2417 /*----------------------------------------------------------------------*/
2418 /*----angel_RDI_LoadAgent------------------------------------------------*/
2419 /*----------------------------------------------------------------------*/
2420
2421 /* Load a new debug agent: use ADP_Ctrl_Download_Agent. */
2422 int angel_RDI_LoadAgent(ARMword dest, unsigned long size,
2423                        getbufferproc *getb, void *getbarg)
2424 {
2425   Packet *packet = NULL;
2426   int  status, reason, subreason, debugID, OSinfo1, OSinfo2, err;
2427   time_t t;
2428
2429 #if defined(DEBUG) || defined(DEBUG_LOADAGENT)
2430   angel_DebugPrint("DEBUG: Entered angel_RDI_LoadAgent.\n");
2431 #endif
2432   register_debug_message_handler();
2433   msgsend(CI_HADP, "%w%w%w%w%w%w%w", ADP_Control | HtoT,
2434           0, ADP_HandleUnknown, ADP_HandleUnknown,
2435           ADP_Ctrl_Download_Agent, dest, size);
2436   reason=ADP_Control | TtoH;
2437   err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
2438                               &status, &packet);
2439   if (err != RDIError_NoError) {
2440     DevSW_FreePacket(packet);
2441     return -1;
2442   }
2443   unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w", &reason, &debugID,
2444                  &OSinfo1, &OSinfo2, &subreason, &status);
2445     DevSW_FreePacket(packet);
2446   if ( subreason != ADP_Ctrl_Download_Agent )
2447     return RDIError_Error;
2448   if ( status != RDIError_NoError )
2449     return status;
2450
2451 #if defined(DEBUG) || defined(DEBUG_LOADAGENT)
2452   angel_DebugPrint("DEBUG: starting agent data download.\n");
2453 #endif
2454   { unsigned long pos = 0, segsize;
2455     for (; pos < size; pos += segsize) {
2456       char *b = getb(getbarg, &segsize);
2457       if (b == NULL) return RDIError_NoError;
2458       err = angel_RDI_LoadConfigData( segsize, b );
2459       if (err != RDIError_NoError) return err;
2460     }
2461   }
2462 #if defined(DEBUG) || defined(DEBUG_LOADAGENT)
2463   angel_DebugPrint("DEBUG: finished downloading new agent.\n");
2464 #endif
2465
2466   /* renegotiate back down */
2467   err = angel_negotiate_defaults();
2468   if (err != adp_ok)
2469      return err;
2470
2471   /* Output a message to tell the user what is going on.  This is vital
2472    * when switching from ADP EICE to ADP over JTAG, as then the user
2473    * has to reset the target board !
2474    */
2475   { char msg[256];
2476     int len=angel_RDI_errmess(msg, 256, adp_new_agent_starting);
2477     angel_hostif->write(angel_hostif->hostosarg, msg, len);
2478   }
2479
2480   /* get new image started */
2481 #if defined(DEBUG) || defined(DEBUG_LOADAGENT)
2482   angel_DebugPrint("DEBUG: sending start message for new agent.\n");
2483 #endif
2484
2485   register_debug_message_handler();
2486   msgsend(CI_HADP, "%w%w%w%w%w%w", ADP_Control | HtoT,
2487           0, ADP_HandleUnknown, ADP_HandleUnknown,
2488           ADP_Ctrl_Start_Agent, dest);
2489   reason=ADP_Control | TtoH;
2490   err = wait_for_debug_message(&reason, &debugID, &OSinfo1, &OSinfo2,
2491                               &status, &packet);
2492   if (err != RDIError_NoError) {
2493     DevSW_FreePacket(packet);
2494     return -1;
2495   }
2496   unpack_message(BUFFERDATA(packet->pk_buffer), "%w%w%w%w%w%w", &reason,
2497                  &debugID, &OSinfo1, &OSinfo2, &subreason, &status);
2498     DevSW_FreePacket(packet);
2499   if ( subreason != ADP_Ctrl_Start_Agent )
2500     return RDIError_Error;
2501   if ( status != RDIError_NoError )
2502     return status;
2503
2504   /* wait for image to start up */
2505   heartbeat_enabled = FALSE;
2506   t=time(NULL);
2507   do {
2508     Adp_AsynchronousProcessing(async_block_on_nothing);
2509     if ((time(NULL)-t) > 2) {
2510 #ifdef DEBUG
2511       angel_DebugPrint("DEBUG: no booted message from new image yet.\n");
2512 #endif
2513       break;
2514     }
2515   } while (booted_not_received);
2516   booted_not_received=1;
2517
2518   /* Give device driver a chance to do any necessary resyncing with new agent.
2519    * Only used by etherdrv.c at the moment.
2520    */
2521   (void)Adp_Ioctl( DC_RESYNC, NULL );
2522
2523 #if defined(DEBUG) || defined(DEBUG_LOADAGENT)
2524   angel_DebugPrint("DEBUG: reopening to new agent.\n");
2525 #endif
2526   err = angel_RDI_open(0, NULL, NULL, NULL);
2527   switch ( err )
2528   {
2529       case RDIError_NoError:
2530       {
2531 #if defined(DEBUG) || defined(DEBUG_LOADAGENT)
2532           angel_DebugPrint( "LoadAgent: Open returned RDIError_NoError\n" );
2533 #endif
2534           break;
2535       }
2536
2537       case RDIError_LittleEndian:
2538       {
2539 #if defined(DEBUG) || defined(DEBUG_LOADAGENT)
2540           angel_DebugPrint( "LoadAgent: Open returned RDIError_LittleEndian (OK)\n" );
2541 #endif
2542           err = RDIError_NoError;
2543           break;
2544       }
2545
2546       case RDIError_BigEndian:
2547       {
2548 #if defined(DEBUG) || defined(DEBUG_LOADAGENT)
2549           angel_DebugPrint( "LoadAgent: Open returned RDIError_BigEndian (OK)\n" );
2550 #endif
2551           err = RDIError_NoError;
2552           break;
2553       }
2554
2555       default:
2556       {
2557 #if defined(DEBUG) || defined(DEBUG_LOADAGENT)
2558           angel_DebugPrint( "LoadAgent: Open returned %d - unexpected!\n", err );
2559 #endif
2560           break;
2561       }
2562   }
2563 #ifndef NO_HEARTBEAT
2564   heartbeat_enabled = TRUE;
2565 #endif
2566   return err;
2567 }
2568
2569 static int angel_RDI_errmess(char *buf, int blen, int errnum) {
2570   char *s=NULL;
2571   int n;
2572
2573   switch (errnum) {
2574     case adp_malloc_failure:
2575       s=AdpMess_MallocFailed; break;
2576     case adp_illegal_args:
2577       s=AdpMess_IllegalArgs; break;
2578     case adp_device_not_found:
2579       s=AdpMess_DeviceNotFound; break;
2580     case adp_device_open_failed:
2581       s=AdpMess_DeviceOpenFailed; break;
2582     case adp_device_already_open:
2583       s=AdpMess_DeviceAlreadyOpen; break;
2584     case adp_device_not_open:
2585       s=AdpMess_DeviceNotOpen; break;
2586     case adp_bad_channel_id:
2587       s=AdpMess_BadChannelId; break;
2588     case adp_callback_already_registered:
2589       s=AdpMess_CBAlreadyRegd; break;
2590     case adp_write_busy:
2591       s=AdpMess_WriteBusy; break;
2592     case adp_bad_packet:
2593       s=AdpMess_BadPacket; break;
2594     case adp_seq_high:
2595       s=AdpMess_SeqHigh; break;
2596     case adp_seq_low:
2597       s=AdpMess_SeqLow; break;
2598     case adp_timeout_on_open:
2599       s=AdpMess_TimeoutOnOpen; break;
2600     case adp_failed:
2601       s=AdpMess_Failed; break;
2602     case adp_abandon_boot_wait:
2603       s=AdpMess_AbandonBootWait; break;
2604     case adp_late_startup:
2605       s=AdpMess_LateStartup; break;
2606     case adp_new_agent_starting:
2607       s=AdpMess_NewAgentStarting; break;
2608     default: return 0;
2609   }
2610   n=strlen(s);
2611   if (n>blen-1) n=blen-1;
2612   memcpy(buf, s, n);
2613   buf[n++]=0;
2614   return n;
2615 }
2616
2617 extern const struct RDIProcVec angel_rdi;
2618 const struct RDIProcVec angel_rdi = {
2619     "ADP",
2620     angel_RDI_open,
2621     angel_RDI_close,
2622     angel_RDI_read,
2623     angel_RDI_write,
2624     angel_RDI_CPUread,
2625     angel_RDI_CPUwrite,
2626     angel_RDI_CPread,
2627     angel_RDI_CPwrite,
2628     angel_RDI_setbreak,
2629     angel_RDI_clearbreak,
2630     angel_RDI_setwatch,
2631     angel_RDI_clearwatch,
2632     angel_RDI_execute,
2633     angel_RDI_step,
2634     angel_RDI_info,
2635     angel_RDI_pointinq,
2636
2637     angel_RDI_AddConfig,
2638     angel_RDI_LoadConfigData,
2639     angel_RDI_SelectConfig,
2640
2641     0, /*angel_RDI_drivernames,*/
2642     0,   /* cpunames */
2643
2644     angel_RDI_errmess,
2645
2646     angel_RDI_LoadAgent
2647 };
2648
2649 /* EOF ardi.c */
2650
2651 /* Not strictly necessary, but allows linking this code into armsd. */
2652
2653 struct foo {
2654     char *name;
2655     int (*action)();
2656     char *syntax;
2657     char **helpmessage;
2658     int doafterend;
2659     int dobeforestart;
2660     int doinmidline;
2661 } hostappl_CmdTable[1] = {{"", NULL}};
2662
2663 void
2664 hostappl_Init()
2665 {
2666 }
2667
2668 int
2669 hostappl_Backstop()
2670 {
2671   return -30;
2672 }
This page took 0.174707 seconds and 4 git commands to generate.