target_call_timer_callbacks_now() now invokes periodic callbacks immediately
[fw/openocd] / src / target / target.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
19  ***************************************************************************/
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif
23
24 #include "replacements.h"
25 #include "target.h"
26 #include "target_request.h"
27
28 #include "log.h"
29 #include "configuration.h"
30 #include "binarybuffer.h"
31 #include "jtag.h"
32
33 #include <string.h>
34 #include <stdlib.h>
35 #include <inttypes.h>
36
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #include <unistd.h>
40 #include <errno.h>
41
42 #include <sys/time.h>
43 #include <time.h>
44
45 #include <time_support.h>
46
47 #include <fileio.h>
48 #include <image.h>
49
50 int cli_target_callback_event_handler(struct target_s *target, enum target_event event, void *priv);
51
52
53 int handle_target_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
54 int handle_daemon_startup_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
55 int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
56
57 int handle_target_script_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
58 int handle_run_and_halt_time_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
59 int handle_working_area_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
60
61 int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
62 int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
63 int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
64 int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
65 int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
66 int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
67 int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
68 int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
69 int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
70 int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
71 int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
72 int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
73 int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
74 int handle_bp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
75 int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
76 int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
77 int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
78 int handle_virt2phys_command(command_context_t *cmd_ctx, char *cmd, char **args, int argc);
79 int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
80
81 /* targets
82  */
83 extern target_type_t arm7tdmi_target;
84 extern target_type_t arm720t_target;
85 extern target_type_t arm9tdmi_target;
86 extern target_type_t arm920t_target;
87 extern target_type_t arm966e_target;
88 extern target_type_t arm926ejs_target;
89 extern target_type_t feroceon_target;
90 extern target_type_t xscale_target;
91 extern target_type_t cortexm3_target;
92 extern target_type_t arm11_target;
93
94 target_type_t *target_types[] =
95 {
96         &arm7tdmi_target,
97         &arm9tdmi_target,
98         &arm920t_target,
99         &arm720t_target,
100         &arm966e_target,
101         &arm926ejs_target,
102         &feroceon_target,
103         &xscale_target,
104         &cortexm3_target,
105         &arm11_target,
106         NULL,
107 };
108
109 target_t *targets = NULL;
110 target_event_callback_t *target_event_callbacks = NULL;
111 target_timer_callback_t *target_timer_callbacks = NULL;
112
113 char *target_state_strings[] =
114 {
115         "unknown",
116         "running",
117         "halted",
118         "reset",
119         "debug_running",
120 };
121
122 char *target_debug_reason_strings[] =
123 {
124         "debug request", "breakpoint", "watchpoint",
125         "watchpoint and breakpoint", "single step",
126         "target not halted", "undefined"
127 };
128
129 char *target_endianess_strings[] =
130 {
131         "big endian",
132         "little endian",
133 };
134
135 enum daemon_startup_mode startup_mode = DAEMON_ATTACH;
136
137 static int target_continous_poll = 1;
138
139 /* read a u32 from a buffer in target memory endianness */
140 u32 target_buffer_get_u32(target_t *target, u8 *buffer)
141 {
142         if (target->endianness == TARGET_LITTLE_ENDIAN)
143                 return le_to_h_u32(buffer);
144         else
145                 return be_to_h_u32(buffer);
146 }
147
148 /* read a u16 from a buffer in target memory endianness */
149 u16 target_buffer_get_u16(target_t *target, u8 *buffer)
150 {
151         if (target->endianness == TARGET_LITTLE_ENDIAN)
152                 return le_to_h_u16(buffer);
153         else
154                 return be_to_h_u16(buffer);
155 }
156
157 /* write a u32 to a buffer in target memory endianness */
158 void target_buffer_set_u32(target_t *target, u8 *buffer, u32 value)
159 {
160         if (target->endianness == TARGET_LITTLE_ENDIAN)
161                 h_u32_to_le(buffer, value);
162         else
163                 h_u32_to_be(buffer, value);
164 }
165
166 /* write a u16 to a buffer in target memory endianness */
167 void target_buffer_set_u16(target_t *target, u8 *buffer, u16 value)
168 {
169         if (target->endianness == TARGET_LITTLE_ENDIAN)
170                 h_u16_to_le(buffer, value);
171         else
172                 h_u16_to_be(buffer, value);
173 }
174
175 /* returns a pointer to the n-th configured target */
176 target_t* get_target_by_num(int num)
177 {
178         target_t *target = targets;
179         int i = 0;
180
181         while (target)
182         {
183                 if (num == i)
184                         return target;
185                 target = target->next;
186                 i++;
187         }
188
189         return NULL;
190 }
191
192 int get_num_by_target(target_t *query_target)
193 {
194         target_t *target = targets;
195         int i = 0;      
196         
197         while (target)
198         {
199                 if (target == query_target)
200                         return i;
201                 target = target->next;
202                 i++;
203         }
204         
205         return -1;
206 }
207
208 target_t* get_current_target(command_context_t *cmd_ctx)
209 {
210         target_t *target = get_target_by_num(cmd_ctx->current_target);
211         
212         if (target == NULL)
213         {
214                 LOG_ERROR("BUG: current_target out of bounds");
215                 exit(-1);
216         }
217         
218         return target;
219 }
220
221 /* Process target initialization, when target entered debug out of reset
222  * the handler is unregistered at the end of this function, so it's only called once
223  */
224 int target_init_handler(struct target_s *target, enum target_event event, void *priv)
225 {
226         FILE *script;
227         struct command_context_s *cmd_ctx = priv;
228         
229         if ((event == TARGET_EVENT_HALTED) && (target->reset_script))
230         {
231                 target_unregister_event_callback(target_init_handler, priv);
232
233                 script = open_file_from_path(target->reset_script, "r");
234                 if (!script)
235                 {
236                         LOG_ERROR("couldn't open script file %s", target->reset_script);
237                                 return ERROR_OK;
238                 }
239
240                 LOG_INFO("executing reset script '%s'", target->reset_script);
241                 command_run_file(cmd_ctx, script, COMMAND_EXEC);
242                 fclose(script);
243
244                 jtag_execute_queue();
245         }
246         
247         return ERROR_OK;
248 }
249
250 int target_run_and_halt_handler(void *priv)
251 {
252         target_t *target = priv;
253         
254         target->type->halt(target);
255         
256         return ERROR_OK;
257 }
258
259 int target_process_reset(struct command_context_s *cmd_ctx)
260 {
261         int retval = ERROR_OK;
262         target_t *target;
263         struct timeval timeout, now;
264
265         jtag->speed(jtag_speed);
266
267         /* prepare reset_halt where necessary */
268         target = targets;
269         while (target)
270         {
271                 if (jtag_reset_config & RESET_SRST_PULLS_TRST)
272                 {
273                         switch (target->reset_mode)
274                         {
275                                 case RESET_HALT:
276                                         command_print(cmd_ctx, "nSRST pulls nTRST, falling back to \"reset run_and_halt\"");
277                                         target->reset_mode = RESET_RUN_AND_HALT;
278                                         break;
279                                 case RESET_INIT:
280                                         command_print(cmd_ctx, "nSRST pulls nTRST, falling back to \"reset run_and_init\"");
281                                         target->reset_mode = RESET_RUN_AND_INIT;
282                                         break;
283                                 default:
284                                         break;
285                         } 
286                 }
287                 switch (target->reset_mode)
288                 {
289                         case RESET_HALT:
290                         case RESET_INIT:
291                                 target->type->prepare_reset_halt(target);
292                                 break;
293                         default:
294                                 break;
295                 }
296                 target = target->next;
297         }
298         
299         target = targets;
300         while (target)
301         {
302                 target->type->assert_reset(target);
303                 target = target->next;
304         }
305         jtag_execute_queue();
306         
307         /* request target halt if necessary, and schedule further action */
308         target = targets;
309         while (target)
310         {
311                 switch (target->reset_mode)
312                 {
313                         case RESET_RUN:
314                                 /* nothing to do if target just wants to be run */
315                                 break;
316                         case RESET_RUN_AND_HALT:
317                                 /* schedule halt */
318                                 target_register_timer_callback(target_run_and_halt_handler, target->run_and_halt_time, 0, target);
319                                 break;
320                         case RESET_RUN_AND_INIT:
321                                 /* schedule halt */
322                                 target_register_timer_callback(target_run_and_halt_handler, target->run_and_halt_time, 0, target);
323                                 target_register_event_callback(target_init_handler, cmd_ctx);
324                                 break;
325                         case RESET_HALT:
326                                 target->type->halt(target);
327                                 break;
328                         case RESET_INIT:
329                                 target->type->halt(target);
330                                 target_register_event_callback(target_init_handler, cmd_ctx);
331                                 break;
332                         default:
333                                 LOG_ERROR("BUG: unknown target->reset_mode");
334                 }
335                 target = target->next;
336         }
337         
338         target = targets;
339         while (target)
340         {
341                 target->type->deassert_reset(target);
342                 target = target->next;
343         }
344         jtag_execute_queue();
345         
346         /* Wait for reset to complete, maximum 5 seconds. */    
347         gettimeofday(&timeout, NULL);
348         timeval_add_time(&timeout, 5, 0);
349         for(;;)
350         {
351                 gettimeofday(&now, NULL);
352                 
353                 target_call_timer_callbacks_now();
354                 
355                 target = targets;
356                 while (target)
357                 {
358                         target->type->poll(target);
359                         if ((target->reset_mode == RESET_RUN_AND_INIT) || (target->reset_mode == RESET_RUN_AND_HALT))
360                         {
361                                 if (target->state != TARGET_HALTED)
362                                 {
363                                         if ((now.tv_sec > timeout.tv_sec) || ((now.tv_sec == timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
364                                         {
365                                                 LOG_USER("Timed out waiting for reset");
366                                                 goto done;
367                                         }
368                                         /* this will send alive messages on e.g. GDB remote protocol. */
369                                         usleep(500*1000); 
370                                         LOG_USER_N("%s", ""); /* avoid warning about zero length formatting message*/ 
371                                         goto again;
372                                 }
373                         }
374                         target = target->next;
375                 }
376                 /* All targets we're waiting for are halted */
377                 break;
378                 
379                 again:;
380         }
381         done:
382         
383         
384         /* We want any events to be processed before the prompt */
385         target_call_timer_callbacks_now();
386
387         jtag->speed(jtag_speed_post_reset);
388         
389         return retval;
390 }
391
392 static int default_virt2phys(struct target_s *target, u32 virtual, u32 *physical)
393 {
394         *physical = virtual;
395         return ERROR_OK;
396 }
397
398 static int default_mmu(struct target_s *target, int *enabled)
399 {
400         *enabled = 0;
401         return ERROR_OK;
402 }
403
404 int target_init(struct command_context_s *cmd_ctx)
405 {
406         target_t *target = targets;
407         
408         while (target)
409         {
410                 if (target->type->init_target(cmd_ctx, target) != ERROR_OK)
411                 {
412                         LOG_ERROR("target '%s' init failed", target->type->name);
413                         exit(-1);
414                 }
415                 
416                 /* Set up default functions if none are provided by target */
417                 if (target->type->virt2phys == NULL)
418                 {
419                         target->type->virt2phys = default_virt2phys;
420                 }
421                 if (target->type->mmu == NULL)
422                 {
423                         target->type->mmu = default_mmu;
424                 }
425                 target = target->next;
426         }
427         
428         if (targets)
429         {
430                 target_register_user_commands(cmd_ctx);
431                 target_register_timer_callback(handle_target, 100, 1, NULL);
432         }
433                 
434         return ERROR_OK;
435 }
436
437 int target_init_reset(struct command_context_s *cmd_ctx)
438 {
439         if (startup_mode == DAEMON_RESET)
440                 target_process_reset(cmd_ctx);
441         
442         return ERROR_OK;
443 }
444
445 int target_register_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
446 {
447         target_event_callback_t **callbacks_p = &target_event_callbacks;
448         
449         if (callback == NULL)
450         {
451                 return ERROR_INVALID_ARGUMENTS;
452         }
453         
454         if (*callbacks_p)
455         {
456                 while ((*callbacks_p)->next)
457                         callbacks_p = &((*callbacks_p)->next);
458                 callbacks_p = &((*callbacks_p)->next);
459         }
460         
461         (*callbacks_p) = malloc(sizeof(target_event_callback_t));
462         (*callbacks_p)->callback = callback;
463         (*callbacks_p)->priv = priv;
464         (*callbacks_p)->next = NULL;
465         
466         return ERROR_OK;
467 }
468
469 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
470 {
471         target_timer_callback_t **callbacks_p = &target_timer_callbacks;
472         struct timeval now;
473         
474         if (callback == NULL)
475         {
476                 return ERROR_INVALID_ARGUMENTS;
477         }
478         
479         if (*callbacks_p)
480         {
481                 while ((*callbacks_p)->next)
482                         callbacks_p = &((*callbacks_p)->next);
483                 callbacks_p = &((*callbacks_p)->next);
484         }
485         
486         (*callbacks_p) = malloc(sizeof(target_timer_callback_t));
487         (*callbacks_p)->callback = callback;
488         (*callbacks_p)->periodic = periodic;
489         (*callbacks_p)->time_ms = time_ms;
490         
491         gettimeofday(&now, NULL);
492         (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
493         time_ms -= (time_ms % 1000);
494         (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
495         if ((*callbacks_p)->when.tv_usec > 1000000)
496         {
497                 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
498                 (*callbacks_p)->when.tv_sec += 1;
499         }
500         
501         (*callbacks_p)->priv = priv;
502         (*callbacks_p)->next = NULL;
503         
504         return ERROR_OK;
505 }
506
507 int target_unregister_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
508 {
509         target_event_callback_t **p = &target_event_callbacks;
510         target_event_callback_t *c = target_event_callbacks;
511         
512         if (callback == NULL)
513         {
514                 return ERROR_INVALID_ARGUMENTS;
515         }
516                 
517         while (c)
518         {
519                 target_event_callback_t *next = c->next;
520                 if ((c->callback == callback) && (c->priv == priv))
521                 {
522                         *p = next;
523                         free(c);
524                         return ERROR_OK;
525                 }
526                 else
527                         p = &(c->next);
528                 c = next;
529         }
530         
531         return ERROR_OK;
532 }
533
534 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
535 {
536         target_timer_callback_t **p = &target_timer_callbacks;
537         target_timer_callback_t *c = target_timer_callbacks;
538         
539         if (callback == NULL)
540         {
541                 return ERROR_INVALID_ARGUMENTS;
542         }
543                 
544         while (c)
545         {
546                 target_timer_callback_t *next = c->next;
547                 if ((c->callback == callback) && (c->priv == priv))
548                 {
549                         *p = next;
550                         free(c);
551                         return ERROR_OK;
552                 }
553                 else
554                         p = &(c->next);
555                 c = next;
556         }
557         
558         return ERROR_OK;
559 }
560
561 int target_call_event_callbacks(target_t *target, enum target_event event)
562 {
563         target_event_callback_t *callback = target_event_callbacks;
564         target_event_callback_t *next_callback;
565         
566         LOG_DEBUG("target event %i", event);
567         
568         while (callback)
569         {
570                 next_callback = callback->next;
571                 callback->callback(target, event, callback->priv);
572                 callback = next_callback;
573         }
574         
575         return ERROR_OK;
576 }
577
578 static int target_call_timer_callbacks_check_time(int checktime)
579 {
580         target_timer_callback_t *callback = target_timer_callbacks;
581         target_timer_callback_t *next_callback;
582         struct timeval now;
583
584         gettimeofday(&now, NULL);
585         
586         while (callback)
587         {
588                 next_callback = callback->next;
589                 
590                 if ((!checktime&&callback->periodic)||
591                                 (((now.tv_sec >= callback->when.tv_sec) && (now.tv_usec >= callback->when.tv_usec))
592                                                 || (now.tv_sec > callback->when.tv_sec)))
593                 {
594                         callback->callback(callback->priv);
595                         if (callback->periodic)
596                         {
597                                 int time_ms = callback->time_ms;
598                                 callback->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
599                                 time_ms -= (time_ms % 1000);
600                                 callback->when.tv_sec = now.tv_sec + time_ms / 1000;
601                                 if (callback->when.tv_usec > 1000000)
602                                 {
603                                         callback->when.tv_usec = callback->when.tv_usec - 1000000;
604                                         callback->when.tv_sec += 1;
605                                 }
606                         }
607                         else
608                                 target_unregister_timer_callback(callback->callback, callback->priv);
609                 }
610                         
611                 callback = next_callback;
612         }
613         
614         return ERROR_OK;
615 }
616
617 int target_call_timer_callbacks()
618 {
619         return target_call_timer_callbacks_check_time(1);
620 }
621
622 /* invoke periodic callbacks immediately */
623 int target_call_timer_callbacks_now()
624 {
625         return target_call_timer_callbacks(0);
626 }
627
628
629 int target_alloc_working_area(struct target_s *target, u32 size, working_area_t **area)
630 {
631         working_area_t *c = target->working_areas;
632         working_area_t *new_wa = NULL;
633         
634         /* Reevaluate working area address based on MMU state*/
635         if (target->working_areas == NULL)
636         {
637                 int retval;
638                 int enabled;
639                 retval = target->type->mmu(target, &enabled);
640                 if (retval != ERROR_OK)
641                 {
642                         return retval;
643                 }
644                 if (enabled)
645                 {
646                         target->working_area = target->working_area_virt;
647                 }
648                 else
649                 {
650                         target->working_area = target->working_area_phys;
651                 }
652         }
653         
654         /* only allocate multiples of 4 byte */
655         if (size % 4)
656         {
657                 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes, padding");
658                 size = CEIL(size, 4);
659         }
660         
661         /* see if there's already a matching working area */
662         while (c)
663         {
664                 if ((c->free) && (c->size == size))
665                 {
666                         new_wa = c;
667                         break;
668                 }
669                 c = c->next;
670         }
671         
672         /* if not, allocate a new one */
673         if (!new_wa)
674         {
675                 working_area_t **p = &target->working_areas;
676                 u32 first_free = target->working_area;
677                 u32 free_size = target->working_area_size;
678                 
679                 LOG_DEBUG("allocating new working area");
680                 
681                 c = target->working_areas;
682                 while (c)
683                 {
684                         first_free += c->size;
685                         free_size -= c->size;
686                         p = &c->next;
687                         c = c->next;
688                 }
689                 
690                 if (free_size < size)
691                 {
692                         LOG_WARNING("not enough working area available(requested %d, free %d)", size, free_size);
693                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
694                 }
695                 
696                 new_wa = malloc(sizeof(working_area_t));
697                 new_wa->next = NULL;
698                 new_wa->size = size;
699                 new_wa->address = first_free;
700                 
701                 if (target->backup_working_area)
702                 {
703                         new_wa->backup = malloc(new_wa->size);
704                         target->type->read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup);
705                 }
706                 else
707                 {
708                         new_wa->backup = NULL;
709                 }
710                 
711                 /* put new entry in list */
712                 *p = new_wa;
713         }
714         
715         /* mark as used, and return the new (reused) area */
716         new_wa->free = 0;
717         *area = new_wa;
718         
719         /* user pointer */
720         new_wa->user = area;
721         
722         return ERROR_OK;
723 }
724
725 int target_free_working_area(struct target_s *target, working_area_t *area)
726 {
727         if (area->free)
728                 return ERROR_OK;
729         
730         if (target->backup_working_area)
731                 target->type->write_memory(target, area->address, 4, area->size / 4, area->backup);
732         
733         area->free = 1;
734         
735         /* mark user pointer invalid */
736         *area->user = NULL;
737         area->user = NULL;
738         
739         return ERROR_OK;
740 }
741
742 int target_free_all_working_areas(struct target_s *target)
743 {
744         working_area_t *c = target->working_areas;
745
746         while (c)
747         {
748                 working_area_t *next = c->next;
749                 target_free_working_area(target, c);
750                 
751                 if (c->backup)
752                         free(c->backup);
753                 
754                 free(c);
755                 
756                 c = next;
757         }
758         
759         target->working_areas = NULL;
760         
761         return ERROR_OK;
762 }
763
764 int target_register_commands(struct command_context_s *cmd_ctx)
765 {
766         register_command(cmd_ctx, NULL, "target", handle_target_command, COMMAND_CONFIG, NULL);
767         register_command(cmd_ctx, NULL, "targets", handle_targets_command, COMMAND_EXEC, NULL);
768         register_command(cmd_ctx, NULL, "daemon_startup", handle_daemon_startup_command, COMMAND_CONFIG, NULL);
769         register_command(cmd_ctx, NULL, "target_script", handle_target_script_command, COMMAND_CONFIG, NULL);
770         register_command(cmd_ctx, NULL, "run_and_halt_time", handle_run_and_halt_time_command, COMMAND_CONFIG, "<target> <run time ms>");
771         register_command(cmd_ctx, NULL, "working_area", handle_working_area_command, COMMAND_ANY, "working_area <target#> <address> <size> <'backup'|'nobackup'> [virtual address]");
772         register_command(cmd_ctx, NULL, "virt2phys", handle_virt2phys_command, COMMAND_ANY, "virt2phys <virtual address>");
773         register_command(cmd_ctx, NULL, "profile", handle_profile_command, COMMAND_EXEC, "PRELIMINARY! - profile <seconds> <gmon.out>");
774
775         return ERROR_OK;
776 }
777
778 int target_arch_state(struct target_s *target)
779 {
780         int retval;
781         if (target==NULL)
782         {
783                 LOG_USER("No target has been configured");
784                 return ERROR_OK;
785         }
786         
787         LOG_USER("target state: %s", target_state_strings[target->state]);
788         
789         if (target->state!=TARGET_HALTED)
790                 return ERROR_OK;
791         
792         retval=target->type->arch_state(target);
793         return retval;
794 }
795
796 /* Single aligned words are guaranteed to use 16 or 32 bit access 
797  * mode respectively, otherwise data is handled as quickly as 
798  * possible
799  */
800 int target_write_buffer(struct target_s *target, u32 address, u32 size, u8 *buffer)
801 {
802         int retval;
803         
804         LOG_DEBUG("writing buffer of %i byte at 0x%8.8x", size, address);
805         
806         if (((address % 2) == 0) && (size == 2))
807         {
808                 return target->type->write_memory(target, address, 2, 1, buffer);
809         }
810         
811         /* handle unaligned head bytes */
812         if (address % 4)
813         {
814                 int unaligned = 4 - (address % 4);
815                 
816                 if (unaligned > size)
817                         unaligned = size;
818
819                 if ((retval = target->type->write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
820                         return retval;
821                 
822                 buffer += unaligned;
823                 address += unaligned;
824                 size -= unaligned;
825         }
826                 
827         /* handle aligned words */
828         if (size >= 4)
829         {
830                 int aligned = size - (size % 4);
831         
832                 /* use bulk writes above a certain limit. This may have to be changed */
833                 if (aligned > 128)
834                 {
835                         if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
836                                 return retval;
837                 }
838                 else
839                 {
840                         if ((retval = target->type->write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
841                                 return retval;
842                 }
843                 
844                 buffer += aligned;
845                 address += aligned;
846                 size -= aligned;
847         }
848         
849         /* handle tail writes of less than 4 bytes */
850         if (size > 0)
851         {
852                 if ((retval = target->type->write_memory(target, address, 1, size, buffer)) != ERROR_OK)
853                         return retval;
854         }
855         
856         return ERROR_OK;
857 }
858
859
860 /* Single aligned words are guaranteed to use 16 or 32 bit access 
861  * mode respectively, otherwise data is handled as quickly as 
862  * possible
863  */
864 int target_read_buffer(struct target_s *target, u32 address, u32 size, u8 *buffer)
865 {
866         int retval;
867         
868         LOG_DEBUG("reading buffer of %i byte at 0x%8.8x", size, address);
869         
870         if (((address % 2) == 0) && (size == 2))
871         {
872                 return target->type->read_memory(target, address, 2, 1, buffer);
873         }
874         
875         /* handle unaligned head bytes */
876         if (address % 4)
877         {
878                 int unaligned = 4 - (address % 4);
879                 
880                 if (unaligned > size)
881                         unaligned = size;
882
883                 if ((retval = target->type->read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
884                         return retval;
885                 
886                 buffer += unaligned;
887                 address += unaligned;
888                 size -= unaligned;
889         }
890                 
891         /* handle aligned words */
892         if (size >= 4)
893         {
894                 int aligned = size - (size % 4);
895         
896                 if ((retval = target->type->read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
897                         return retval;
898                 
899                 buffer += aligned;
900                 address += aligned;
901                 size -= aligned;
902         }
903         
904         /* handle tail writes of less than 4 bytes */
905         if (size > 0)
906         {
907                 if ((retval = target->type->read_memory(target, address, 1, size, buffer)) != ERROR_OK)
908                         return retval;
909         }
910         
911         return ERROR_OK;
912 }
913
914 int target_checksum_memory(struct target_s *target, u32 address, u32 size, u32* crc)
915 {
916         u8 *buffer;
917         int retval;
918         int i;
919         u32 checksum = 0;
920         
921         if ((retval = target->type->checksum_memory(target, address,
922                 size, &checksum)) == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
923         {
924                 buffer = malloc(size);
925                 if (buffer == NULL)
926                 {
927                         LOG_ERROR("error allocating buffer for section (%d bytes)", size);
928                         return ERROR_INVALID_ARGUMENTS;
929                 }
930                 retval = target_read_buffer(target, address, size, buffer);
931                 if (retval != ERROR_OK)
932                 {
933                         free(buffer);
934                         return retval;
935                 }
936
937                 /* convert to target endianess */
938                 for (i = 0; i < (size/sizeof(u32)); i++)
939                 {
940                         u32 target_data;
941                         target_data = target_buffer_get_u32(target, &buffer[i*sizeof(u32)]);
942                         target_buffer_set_u32(target, &buffer[i*sizeof(u32)], target_data);
943                 }
944
945                 retval = image_calculate_checksum( buffer, size, &checksum );
946                 free(buffer);
947         }
948         
949         *crc = checksum;
950         
951         return retval;
952 }
953
954 int target_read_u32(struct target_s *target, u32 address, u32 *value)
955 {
956         u8 value_buf[4];
957
958         int retval = target->type->read_memory(target, address, 4, 1, value_buf);
959         
960         if (retval == ERROR_OK)
961         {
962                 *value = target_buffer_get_u32(target, value_buf);
963                 LOG_DEBUG("address: 0x%8.8x, value: 0x%8.8x", address, *value);
964         }
965         else
966         {
967                 *value = 0x0;
968                 LOG_DEBUG("address: 0x%8.8x failed", address);
969         }
970         
971         return retval;
972 }
973
974 int target_read_u16(struct target_s *target, u32 address, u16 *value)
975 {
976         u8 value_buf[2];
977         
978         int retval = target->type->read_memory(target, address, 2, 1, value_buf);
979         
980         if (retval == ERROR_OK)
981         {
982                 *value = target_buffer_get_u16(target, value_buf);
983                 LOG_DEBUG("address: 0x%8.8x, value: 0x%4.4x", address, *value);
984         }
985         else
986         {
987                 *value = 0x0;
988                 LOG_DEBUG("address: 0x%8.8x failed", address);
989         }
990         
991         return retval;
992 }
993
994 int target_read_u8(struct target_s *target, u32 address, u8 *value)
995 {
996         int retval = target->type->read_memory(target, address, 1, 1, value);
997
998         if (retval == ERROR_OK)
999         {
1000                 LOG_DEBUG("address: 0x%8.8x, value: 0x%2.2x", address, *value);
1001         }
1002         else
1003         {
1004                 *value = 0x0;
1005                 LOG_DEBUG("address: 0x%8.8x failed", address);
1006         }
1007         
1008         return retval;
1009 }
1010
1011 int target_write_u32(struct target_s *target, u32 address, u32 value)
1012 {
1013         int retval;
1014         u8 value_buf[4];
1015
1016         LOG_DEBUG("address: 0x%8.8x, value: 0x%8.8x", address, value);
1017
1018         target_buffer_set_u32(target, value_buf, value);        
1019         if ((retval = target->type->write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1020         {
1021                 LOG_DEBUG("failed: %i", retval);
1022         }
1023         
1024         return retval;
1025 }
1026
1027 int target_write_u16(struct target_s *target, u32 address, u16 value)
1028 {
1029         int retval;
1030         u8 value_buf[2];
1031         
1032         LOG_DEBUG("address: 0x%8.8x, value: 0x%8.8x", address, value);
1033
1034         target_buffer_set_u16(target, value_buf, value);        
1035         if ((retval = target->type->write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1036         {
1037                 LOG_DEBUG("failed: %i", retval);
1038         }
1039         
1040         return retval;
1041 }
1042
1043 int target_write_u8(struct target_s *target, u32 address, u8 value)
1044 {
1045         int retval;
1046         
1047         LOG_DEBUG("address: 0x%8.8x, value: 0x%2.2x", address, value);
1048
1049         if ((retval = target->type->read_memory(target, address, 1, 1, &value)) != ERROR_OK)
1050         {
1051                 LOG_DEBUG("failed: %i", retval);
1052         }
1053         
1054         return retval;
1055 }
1056
1057 int target_register_user_commands(struct command_context_s *cmd_ctx)
1058 {
1059         register_command(cmd_ctx,  NULL, "reg", handle_reg_command, COMMAND_EXEC, NULL);
1060         register_command(cmd_ctx,  NULL, "poll", handle_poll_command, COMMAND_EXEC, "poll target state");
1061         register_command(cmd_ctx,  NULL, "wait_halt", handle_wait_halt_command, COMMAND_EXEC, "wait for target halt [time (s)]");
1062         register_command(cmd_ctx,  NULL, "halt", handle_halt_command, COMMAND_EXEC, "halt target");
1063         register_command(cmd_ctx,  NULL, "resume", handle_resume_command, COMMAND_EXEC, "resume target [addr]");
1064         register_command(cmd_ctx,  NULL, "step", handle_step_command, COMMAND_EXEC, "step one instruction from current PC or [addr]");
1065         register_command(cmd_ctx,  NULL, "reset", handle_reset_command, COMMAND_EXEC, "reset target [run|halt|init|run_and_halt|run_and_init]");
1066         register_command(cmd_ctx,  NULL, "soft_reset_halt", handle_soft_reset_halt_command, COMMAND_EXEC, "halt the target and do a soft reset");
1067
1068         register_command(cmd_ctx,  NULL, "mdw", handle_md_command, COMMAND_EXEC, "display memory words <addr> [count]");
1069         register_command(cmd_ctx,  NULL, "mdh", handle_md_command, COMMAND_EXEC, "display memory half-words <addr> [count]");
1070         register_command(cmd_ctx,  NULL, "mdb", handle_md_command, COMMAND_EXEC, "display memory bytes <addr> [count]");
1071         
1072         register_command(cmd_ctx,  NULL, "mww", handle_mw_command, COMMAND_EXEC, "write memory word <addr> <value>");
1073         register_command(cmd_ctx,  NULL, "mwh", handle_mw_command, COMMAND_EXEC, "write memory half-word <addr> <value>");
1074         register_command(cmd_ctx,  NULL, "mwb", handle_mw_command, COMMAND_EXEC, "write memory byte <addr> <value>");
1075         
1076         register_command(cmd_ctx,  NULL, "bp", handle_bp_command, COMMAND_EXEC, "set breakpoint <address> <length> [hw]");      
1077         register_command(cmd_ctx,  NULL, "rbp", handle_rbp_command, COMMAND_EXEC, "remove breakpoint <adress>");
1078         register_command(cmd_ctx,  NULL, "wp", handle_wp_command, COMMAND_EXEC, "set watchpoint <address> <length> <r/w/a> [value] [mask]");    
1079         register_command(cmd_ctx,  NULL, "rwp", handle_rwp_command, COMMAND_EXEC, "remove watchpoint <adress>");
1080         
1081         register_command(cmd_ctx,  NULL, "load_image", handle_load_image_command, COMMAND_EXEC, "load_image <file> <address> ['bin'|'ihex'|'elf'|'s19']");
1082         register_command(cmd_ctx,  NULL, "dump_image", handle_dump_image_command, COMMAND_EXEC, "dump_image <file> <address> <size>");
1083         register_command(cmd_ctx,  NULL, "verify_image", handle_verify_image_command, COMMAND_EXEC, "verify_image <file> [offset] [type]");
1084         register_command(cmd_ctx,  NULL, "load_binary", handle_load_image_command, COMMAND_EXEC, "[DEPRECATED] load_binary <file> <address>");
1085         register_command(cmd_ctx,  NULL, "dump_binary", handle_dump_image_command, COMMAND_EXEC, "[DEPRECATED] dump_binary <file> <address> <size>");
1086         
1087         target_request_register_commands(cmd_ctx);
1088         trace_register_commands(cmd_ctx);
1089         
1090         return ERROR_OK;
1091 }
1092
1093 int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1094 {
1095         target_t *target = targets;
1096         int count = 0;
1097         
1098         if (argc == 1)
1099         {
1100                 int num = strtoul(args[0], NULL, 0);
1101                 
1102                 while (target)
1103                 {
1104                         count++;
1105                         target = target->next;
1106                 }
1107                 
1108                 if (num < count)
1109                         cmd_ctx->current_target = num;
1110                 else
1111                         command_print(cmd_ctx, "%i is out of bounds, only %i targets are configured", num, count);
1112                         
1113                 return ERROR_OK;
1114         }
1115                 
1116         while (target)
1117         {
1118                 command_print(cmd_ctx, "%i: %s (%s), state: %s", count++, target->type->name, target_endianess_strings[target->endianness], target_state_strings[target->state]);
1119                 target = target->next;
1120         }
1121         
1122         return ERROR_OK;
1123 }
1124
1125 int handle_target_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1126 {
1127         int i;
1128         int found = 0;
1129         
1130         if (argc < 3)
1131         {
1132                 return ERROR_COMMAND_SYNTAX_ERROR;
1133         }
1134         
1135         /* search for the specified target */
1136         if (args[0] && (args[0][0] != 0))
1137         {
1138                 for (i = 0; target_types[i]; i++)
1139                 {
1140                         if (strcmp(args[0], target_types[i]->name) == 0)
1141                         {
1142                                 target_t **last_target_p = &targets;
1143                                 
1144                                 /* register target specific commands */
1145                                 if (target_types[i]->register_commands(cmd_ctx) != ERROR_OK)
1146                                 {
1147                                         LOG_ERROR("couldn't register '%s' commands", args[0]);
1148                                         exit(-1);
1149                                 }
1150
1151                                 if (*last_target_p)
1152                                 {
1153                                         while ((*last_target_p)->next)
1154                                                 last_target_p = &((*last_target_p)->next);
1155                                         last_target_p = &((*last_target_p)->next);
1156                                 }
1157
1158                                 *last_target_p = malloc(sizeof(target_t));
1159                                 
1160                                 (*last_target_p)->type = target_types[i];
1161                                 
1162                                 if (strcmp(args[1], "big") == 0)
1163                                         (*last_target_p)->endianness = TARGET_BIG_ENDIAN;
1164                                 else if (strcmp(args[1], "little") == 0)
1165                                         (*last_target_p)->endianness = TARGET_LITTLE_ENDIAN;
1166                                 else
1167                                 {
1168                                         LOG_ERROR("endianness must be either 'little' or 'big', not '%s'", args[1]);
1169                                         return ERROR_COMMAND_SYNTAX_ERROR;
1170                                 }
1171                                 
1172                                 /* what to do on a target reset */
1173                                 if (strcmp(args[2], "reset_halt") == 0)
1174                                         (*last_target_p)->reset_mode = RESET_HALT;
1175                                 else if (strcmp(args[2], "reset_run") == 0)
1176                                         (*last_target_p)->reset_mode = RESET_RUN;
1177                                 else if (strcmp(args[2], "reset_init") == 0)
1178                                         (*last_target_p)->reset_mode = RESET_INIT;
1179                                 else if (strcmp(args[2], "run_and_halt") == 0)
1180                                         (*last_target_p)->reset_mode = RESET_RUN_AND_HALT;
1181                                 else if (strcmp(args[2], "run_and_init") == 0)
1182                                         (*last_target_p)->reset_mode = RESET_RUN_AND_INIT;
1183                                 else
1184                                 {
1185                                         LOG_ERROR("unknown target startup mode %s", args[2]);
1186                                         return ERROR_COMMAND_SYNTAX_ERROR;
1187                                 }
1188                                 (*last_target_p)->run_and_halt_time = 1000; /* default 1s */
1189                                 
1190                                 (*last_target_p)->reset_script = NULL;
1191                                 (*last_target_p)->post_halt_script = NULL;
1192                                 (*last_target_p)->pre_resume_script = NULL;
1193                                 (*last_target_p)->gdb_program_script = NULL;
1194                                 
1195                                 (*last_target_p)->working_area = 0x0;
1196                                 (*last_target_p)->working_area_size = 0x0;
1197                                 (*last_target_p)->working_areas = NULL;
1198                                 (*last_target_p)->backup_working_area = 0;
1199                                 
1200                                 (*last_target_p)->state = TARGET_UNKNOWN;
1201                                 (*last_target_p)->debug_reason = DBG_REASON_UNDEFINED;
1202                                 (*last_target_p)->reg_cache = NULL;
1203                                 (*last_target_p)->breakpoints = NULL;
1204                                 (*last_target_p)->watchpoints = NULL;
1205                                 (*last_target_p)->next = NULL;
1206                                 (*last_target_p)->arch_info = NULL;
1207                                 
1208                                 /* initialize trace information */
1209                                 (*last_target_p)->trace_info = malloc(sizeof(trace_t));
1210                                 (*last_target_p)->trace_info->num_trace_points = 0;
1211                                 (*last_target_p)->trace_info->trace_points_size = 0;
1212                                 (*last_target_p)->trace_info->trace_points = NULL;
1213                                 (*last_target_p)->trace_info->trace_history_size = 0;
1214                                 (*last_target_p)->trace_info->trace_history = NULL;
1215                                 (*last_target_p)->trace_info->trace_history_pos = 0;
1216                                 (*last_target_p)->trace_info->trace_history_overflowed = 0;
1217                                 
1218                                 (*last_target_p)->dbgmsg = NULL;
1219                                 (*last_target_p)->dbg_msg_enabled = 0;
1220                                                                 
1221                                 (*last_target_p)->type->target_command(cmd_ctx, cmd, args, argc, *last_target_p);
1222                                 
1223                                 found = 1;
1224                                 break;
1225                         }
1226                 }
1227         }
1228         
1229         /* no matching target found */
1230         if (!found)
1231         {
1232                 LOG_ERROR("target '%s' not found", args[0]);
1233                 return ERROR_COMMAND_SYNTAX_ERROR;
1234         }
1235
1236         return ERROR_OK;
1237 }
1238
1239 /* usage: target_script <target#> <event> <script_file> */
1240 int handle_target_script_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1241 {
1242         target_t *target = NULL;
1243         
1244         if (argc < 3)
1245         {
1246                 LOG_ERROR("incomplete target_script command");
1247                 return ERROR_COMMAND_SYNTAX_ERROR;
1248         }
1249         
1250         target = get_target_by_num(strtoul(args[0], NULL, 0));
1251         
1252         if (!target)
1253         {
1254                 return ERROR_COMMAND_SYNTAX_ERROR;
1255         }
1256         
1257         if (strcmp(args[1], "reset") == 0)
1258         {
1259                 if (target->reset_script)
1260                         free(target->reset_script);
1261                 target->reset_script = strdup(args[2]);
1262         }
1263         else if (strcmp(args[1], "post_halt") == 0)
1264         {
1265                 if (target->post_halt_script)
1266                         free(target->post_halt_script);
1267                 target->post_halt_script = strdup(args[2]);
1268         }
1269         else if (strcmp(args[1], "pre_resume") == 0)
1270         {
1271                 if (target->pre_resume_script)
1272                         free(target->pre_resume_script);
1273                 target->pre_resume_script = strdup(args[2]);
1274         }
1275         else if (strcmp(args[1], "gdb_program_config") == 0)
1276         {
1277                 if (target->gdb_program_script)
1278                         free(target->gdb_program_script);
1279                 target->gdb_program_script = strdup(args[2]);
1280         }
1281         else
1282         {
1283                 LOG_ERROR("unknown event type: '%s", args[1]);
1284                 return ERROR_COMMAND_SYNTAX_ERROR;
1285         }
1286         
1287         return ERROR_OK;
1288 }
1289
1290 int handle_run_and_halt_time_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1291 {
1292         target_t *target = NULL;
1293         
1294         if (argc < 2)
1295         {
1296                 return ERROR_COMMAND_SYNTAX_ERROR;
1297         }
1298         
1299         target = get_target_by_num(strtoul(args[0], NULL, 0));
1300         if (!target)
1301         {
1302                 return ERROR_COMMAND_SYNTAX_ERROR;
1303         }
1304         
1305         target->run_and_halt_time = strtoul(args[1], NULL, 0);
1306         
1307         return ERROR_OK;
1308 }
1309
1310 int handle_working_area_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1311 {
1312         target_t *target = NULL;
1313         
1314         if ((argc < 4) || (argc > 5))
1315         {
1316                 return ERROR_COMMAND_SYNTAX_ERROR;
1317         }
1318         
1319         target = get_target_by_num(strtoul(args[0], NULL, 0));
1320         if (!target)
1321         {
1322                 return ERROR_COMMAND_SYNTAX_ERROR;
1323         }
1324         target_free_all_working_areas(target);
1325         
1326         target->working_area_phys = target->working_area_virt = strtoul(args[1], NULL, 0);
1327         if (argc == 5)
1328         {
1329                 target->working_area_virt = strtoul(args[4], NULL, 0);
1330         }
1331         target->working_area_size = strtoul(args[2], NULL, 0);
1332         
1333         if (strcmp(args[3], "backup") == 0)
1334         {
1335                 target->backup_working_area = 1;
1336         }
1337         else if (strcmp(args[3], "nobackup") == 0)
1338         {
1339                 target->backup_working_area = 0;
1340         }
1341         else
1342         {
1343                 LOG_ERROR("unrecognized <backup|nobackup> argument (%s)", args[3]);
1344                 return ERROR_COMMAND_SYNTAX_ERROR;
1345         }
1346         
1347         return ERROR_OK;
1348 }
1349
1350
1351 /* process target state changes */
1352 int handle_target(void *priv)
1353 {
1354         int retval;
1355         target_t *target = targets;
1356         
1357         while (target)
1358         {
1359                 /* only poll if target isn't already halted */
1360                 if (target->state != TARGET_HALTED)
1361                 {
1362                         if (target_continous_poll)
1363                                 if ((retval = target->type->poll(target)) != ERROR_OK)
1364                                 {
1365                                         LOG_ERROR("couldn't poll target(%d). It's due for a reset.", retval);
1366                                 }
1367                 }
1368         
1369                 target = target->next;
1370         }
1371         
1372         return ERROR_OK;
1373 }
1374
1375 int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1376 {
1377         target_t *target;
1378         reg_t *reg = NULL;
1379         int count = 0;
1380         char *value;
1381         
1382         LOG_DEBUG("-");
1383         
1384         target = get_current_target(cmd_ctx);
1385         
1386         /* list all available registers for the current target */
1387         if (argc == 0)
1388         {
1389                 reg_cache_t *cache = target->reg_cache;
1390                 
1391                 count = 0;
1392                 while(cache)
1393                 {
1394                         int i;
1395                         for (i = 0; i < cache->num_regs; i++)
1396                         {
1397                                 value = buf_to_str(cache->reg_list[i].value, cache->reg_list[i].size, 16);
1398                                 command_print(cmd_ctx, "(%i) %s (/%i): 0x%s (dirty: %i, valid: %i)", count++, cache->reg_list[i].name, cache->reg_list[i].size, value, cache->reg_list[i].dirty, cache->reg_list[i].valid);
1399                                 free(value);
1400                         }
1401                         cache = cache->next;
1402                 }
1403                 
1404                 return ERROR_OK;
1405         }
1406         
1407         /* access a single register by its ordinal number */
1408         if ((args[0][0] >= '0') && (args[0][0] <= '9'))
1409         {
1410                 int num = strtoul(args[0], NULL, 0);
1411                 reg_cache_t *cache = target->reg_cache;
1412                 
1413                 count = 0;
1414                 while(cache)
1415                 {
1416                         int i;
1417                         for (i = 0; i < cache->num_regs; i++)
1418                         {
1419                                 if (count++ == num)
1420                                 {
1421                                         reg = &cache->reg_list[i];
1422                                         break;
1423                                 }
1424                         }
1425                         if (reg)
1426                                 break;
1427                         cache = cache->next;
1428                 }
1429                 
1430                 if (!reg)
1431                 {
1432                         command_print(cmd_ctx, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1433                         return ERROR_OK;
1434                 }
1435         } else /* access a single register by its name */
1436         {
1437                 reg = register_get_by_name(target->reg_cache, args[0], 1);
1438                 
1439                 if (!reg)
1440                 {
1441                         command_print(cmd_ctx, "register %s not found in current target", args[0]);
1442                         return ERROR_OK;
1443                 }
1444         }
1445
1446         /* display a register */
1447         if ((argc == 1) || ((argc == 2) && !((args[1][0] >= '0') && (args[1][0] <= '9'))))
1448         {
1449                 if ((argc == 2) && (strcmp(args[1], "force") == 0))
1450                         reg->valid = 0;
1451                 
1452                 if (reg->valid == 0)
1453                 {
1454                         reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1455                         if (arch_type == NULL)
1456                         {
1457                                 LOG_ERROR("BUG: encountered unregistered arch type");
1458                                 return ERROR_OK;
1459                         }
1460                         arch_type->get(reg);
1461                 }
1462                 value = buf_to_str(reg->value, reg->size, 16);
1463                 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, reg->size, value);
1464                 free(value);
1465                 return ERROR_OK;
1466         }
1467         
1468         /* set register value */
1469         if (argc == 2)
1470         {
1471                 u8 *buf = malloc(CEIL(reg->size, 8));
1472                 str_to_buf(args[1], strlen(args[1]), buf, reg->size, 0);
1473
1474                 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1475                 if (arch_type == NULL)
1476                 {
1477                         LOG_ERROR("BUG: encountered unregistered arch type");
1478                         return ERROR_OK;
1479                 }
1480                 
1481                 arch_type->set(reg, buf);
1482                 
1483                 value = buf_to_str(reg->value, reg->size, 16);
1484                 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, reg->size, value);
1485                 free(value);
1486                 
1487                 free(buf);
1488                 
1489                 return ERROR_OK;
1490         }
1491         
1492         command_print(cmd_ctx, "usage: reg <#|name> [value]");
1493         
1494         return ERROR_OK;
1495 }
1496
1497 static int wait_state(struct command_context_s *cmd_ctx, char *cmd, enum target_state state, int ms);
1498
1499 int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1500 {
1501         target_t *target = get_current_target(cmd_ctx);
1502
1503         if (argc == 0)
1504         {
1505                 target->type->poll(target);
1506                 target_arch_state(target);
1507         }
1508         else
1509         {
1510                 if (strcmp(args[0], "on") == 0)
1511                 {
1512                         target_continous_poll = 1;
1513                 }
1514                 else if (strcmp(args[0], "off") == 0)
1515                 {
1516                         target_continous_poll = 0;
1517                 }
1518                 else
1519                 {
1520                         command_print(cmd_ctx, "arg is \"on\" or \"off\"");
1521                 }
1522         }
1523         
1524         
1525         return ERROR_OK;
1526 }
1527
1528 int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1529 {
1530         int ms = 5000;
1531         
1532         if (argc > 0)
1533         {
1534                 char *end;
1535
1536                 ms = strtoul(args[0], &end, 0) * 1000;
1537                 if (*end)
1538                 {
1539                         command_print(cmd_ctx, "usage: %s [seconds]", cmd);
1540                         return ERROR_OK;
1541                 }
1542         }
1543
1544         return wait_state(cmd_ctx, cmd, TARGET_HALTED, ms); 
1545 }
1546
1547 static void target_process_events(struct command_context_s *cmd_ctx)
1548 {
1549         target_t *target = get_current_target(cmd_ctx);
1550         target->type->poll(target);
1551         target_call_timer_callbacks_now();
1552 }
1553
1554 static int wait_state(struct command_context_s *cmd_ctx, char *cmd, enum target_state state, int ms)
1555 {
1556         int retval;
1557         struct timeval timeout, now;
1558         int once=1;
1559         gettimeofday(&timeout, NULL);
1560         timeval_add_time(&timeout, 0, ms * 1000);
1561         
1562         target_t *target = get_current_target(cmd_ctx);
1563         for (;;)
1564         {
1565                 if ((retval=target->type->poll(target))!=ERROR_OK)
1566                         return retval;
1567                 target_call_timer_callbacks_now();
1568                 if (target->state == state)
1569                 {
1570                         break;
1571                 }
1572                 if (once)
1573                 {
1574                         once=0;
1575                         command_print(cmd_ctx, "waiting for target %s...", target_state_strings[state]);
1576                 }
1577                 
1578                 gettimeofday(&now, NULL);
1579                 if ((now.tv_sec > timeout.tv_sec) || ((now.tv_sec == timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
1580                 {
1581                         LOG_ERROR("timed out while waiting for target %s", target_state_strings[state]);
1582                         break;
1583                 }
1584         }
1585         
1586         return ERROR_OK;
1587 }
1588
1589 int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1590 {
1591         int retval;
1592         target_t *target = get_current_target(cmd_ctx);
1593
1594         LOG_DEBUG("-");
1595
1596         if ((retval = target->type->halt(target)) != ERROR_OK)
1597         {
1598                 return retval;
1599         }
1600         
1601         return handle_wait_halt_command(cmd_ctx, cmd, args, argc);
1602 }
1603
1604 /* what to do on daemon startup */
1605 int handle_daemon_startup_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1606 {
1607         if (argc == 1)
1608         {
1609                 if (strcmp(args[0], "attach") == 0)
1610                 {
1611                         startup_mode = DAEMON_ATTACH;
1612                         return ERROR_OK;
1613                 }
1614                 else if (strcmp(args[0], "reset") == 0)
1615                 {
1616                         startup_mode = DAEMON_RESET;
1617                         return ERROR_OK;
1618                 }
1619         }
1620         
1621         LOG_WARNING("invalid daemon_startup configuration directive: %s", args[0]);
1622         return ERROR_OK;
1623
1624 }
1625                 
1626 int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1627 {
1628         target_t *target = get_current_target(cmd_ctx);
1629         
1630         LOG_USER("requesting target halt and executing a soft reset");
1631         
1632         target->type->soft_reset_halt(target);
1633         
1634         return ERROR_OK;
1635 }
1636
1637 int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1638 {
1639         target_t *target = get_current_target(cmd_ctx);
1640         enum target_reset_mode reset_mode = target->reset_mode;
1641         enum target_reset_mode save = target->reset_mode;
1642         
1643         LOG_DEBUG("-");
1644         
1645         if (argc >= 1)
1646         {
1647                 if (strcmp("run", args[0]) == 0)
1648                         reset_mode = RESET_RUN;
1649                 else if (strcmp("halt", args[0]) == 0)
1650                         reset_mode = RESET_HALT;
1651                 else if (strcmp("init", args[0]) == 0)
1652                         reset_mode = RESET_INIT;
1653                 else if (strcmp("run_and_halt", args[0]) == 0)
1654                 {
1655                         reset_mode = RESET_RUN_AND_HALT;
1656                         if (argc >= 2)
1657                         {
1658                                 target->run_and_halt_time = strtoul(args[1], NULL, 0);
1659                         }
1660                 }
1661                 else if (strcmp("run_and_init", args[0]) == 0)
1662                 {
1663                         reset_mode = RESET_RUN_AND_INIT;
1664                         if (argc >= 2)
1665                         {
1666                                 target->run_and_halt_time = strtoul(args[1], NULL, 0);
1667                         }
1668                 }
1669                 else
1670                 {
1671                         command_print(cmd_ctx, "usage: reset ['run', 'halt', 'init', 'run_and_halt', 'run_and_init]");
1672                         return ERROR_OK;
1673                 }
1674         }
1675         
1676         /* temporarily modify mode of current reset target */
1677         target->reset_mode = reset_mode;
1678
1679         /* reset *all* targets */
1680         target_process_reset(cmd_ctx);
1681         
1682         /* Restore default reset mode for this target */
1683     target->reset_mode = save;
1684         
1685         return ERROR_OK;
1686 }
1687
1688 int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1689 {
1690         int retval;
1691         target_t *target = get_current_target(cmd_ctx);
1692         
1693         if (argc == 0)
1694                 retval = target->type->resume(target, 1, 0, 1, 0); /* current pc, addr = 0, handle breakpoints, not debugging */
1695         else if (argc == 1)
1696                 retval = target->type->resume(target, 0, strtoul(args[0], NULL, 0), 1, 0); /* addr = args[0], handle breakpoints, not debugging */
1697         else
1698         {
1699                 return ERROR_COMMAND_SYNTAX_ERROR;
1700         }
1701
1702         target_process_events(cmd_ctx);
1703         
1704         return retval;
1705 }
1706
1707 int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1708 {
1709         target_t *target = get_current_target(cmd_ctx);
1710         
1711         LOG_DEBUG("-");
1712         
1713         if (argc == 0)
1714                 target->type->step(target, 1, 0, 1); /* current pc, addr = 0, handle breakpoints */
1715
1716         if (argc == 1)
1717                 target->type->step(target, 0, strtoul(args[0], NULL, 0), 1); /* addr = args[0], handle breakpoints */
1718         
1719         return ERROR_OK;
1720 }
1721
1722 int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1723 {
1724         const int line_bytecnt = 32;
1725         int count = 1;
1726         int size = 4;
1727         u32 address = 0;
1728         int line_modulo;
1729         int i;
1730
1731         char output[128];
1732         int output_len;
1733
1734         int retval;
1735
1736         u8 *buffer;
1737         target_t *target = get_current_target(cmd_ctx);
1738
1739         if (argc < 1)
1740                 return ERROR_OK;
1741
1742         if (argc == 2)
1743                 count = strtoul(args[1], NULL, 0);
1744
1745         address = strtoul(args[0], NULL, 0);
1746         
1747
1748         switch (cmd[2])
1749         {
1750                 case 'w':
1751                         size = 4; line_modulo = line_bytecnt / 4;
1752                         break;
1753                 case 'h':
1754                         size = 2; line_modulo = line_bytecnt / 2;
1755                         break;
1756                 case 'b':
1757                         size = 1; line_modulo = line_bytecnt / 1;
1758                         break;
1759                 default:
1760                         return ERROR_OK;
1761         }
1762
1763         buffer = calloc(count, size);
1764         retval  = target->type->read_memory(target, address, size, count, buffer);
1765         if (retval == ERROR_OK)
1766         {
1767                 output_len = 0;
1768         
1769                 for (i = 0; i < count; i++)
1770                 {
1771                         if (i%line_modulo == 0)
1772                                 output_len += snprintf(output + output_len, 128 - output_len, "0x%8.8x: ", address + (i*size));
1773                         
1774                         switch (size)
1775                         {
1776                                 case 4:
1777                                         output_len += snprintf(output + output_len, 128 - output_len, "%8.8x ", target_buffer_get_u32(target, &buffer[i*4]));
1778                                         break;
1779                                 case 2:
1780                                         output_len += snprintf(output + output_len, 128 - output_len, "%4.4x ", target_buffer_get_u16(target, &buffer[i*2]));
1781                                         break;
1782                                 case 1:
1783                                         output_len += snprintf(output + output_len, 128 - output_len, "%2.2x ", buffer[i*1]);
1784                                         break;
1785                         }
1786         
1787                         if ((i%line_modulo == line_modulo-1) || (i == count - 1))
1788                         {
1789                                 command_print(cmd_ctx, output);
1790                                 output_len = 0;
1791                         }
1792                 }
1793         } else
1794         {
1795                 LOG_ERROR("Failure examining memory");
1796         }
1797
1798         free(buffer);
1799         
1800         return ERROR_OK;
1801 }
1802
1803 int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1804 {
1805         u32 address = 0;
1806         u32 value = 0;
1807         int retval;
1808         target_t *target = get_current_target(cmd_ctx);
1809         u8 value_buf[4];
1810
1811         if (argc < 2)
1812                 return ERROR_OK;
1813
1814         address = strtoul(args[0], NULL, 0);
1815         value = strtoul(args[1], NULL, 0);
1816
1817         switch (cmd[2])
1818         {
1819                 case 'w':
1820                         target_buffer_set_u32(target, value_buf, value);
1821                         retval = target->type->write_memory(target, address, 4, 1, value_buf);
1822                         break;
1823                 case 'h':
1824                         target_buffer_set_u16(target, value_buf, value);
1825                         retval = target->type->write_memory(target, address, 2, 1, value_buf);
1826                         break;
1827                 case 'b':
1828                         value_buf[0] = value;
1829                         retval = target->type->write_memory(target, address, 1, 1, value_buf);
1830                         break;
1831                 default:
1832                         return ERROR_OK;
1833         }
1834         if (retval!=ERROR_OK)
1835         {
1836                 LOG_ERROR("Failure examining memory");
1837         }
1838
1839         return ERROR_OK;
1840
1841 }
1842
1843 int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1844 {
1845         u8 *buffer;
1846         u32 buf_cnt;
1847         u32 image_size;
1848         int i;
1849         int retval;
1850
1851         image_t image;  
1852         
1853         duration_t duration;
1854         char *duration_text;
1855         
1856         target_t *target = get_current_target(cmd_ctx);
1857
1858         if (argc < 1)
1859         {
1860                 command_print(cmd_ctx, "usage: load_image <filename> [address] [type]");
1861                 return ERROR_OK;
1862         }
1863         
1864         /* a base address isn't always necessary, default to 0x0 (i.e. don't relocate) */
1865         if (argc >= 2)
1866         {
1867                 image.base_address_set = 1;
1868                 image.base_address = strtoul(args[1], NULL, 0);
1869         }
1870         else
1871         {
1872                 image.base_address_set = 0;
1873         }
1874         
1875         image.start_address_set = 0;
1876
1877         duration_start_measure(&duration);
1878         
1879         if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
1880         {
1881                 return ERROR_OK;
1882         }
1883         
1884         image_size = 0x0;
1885         retval = ERROR_OK;
1886         for (i = 0; i < image.num_sections; i++)
1887         {
1888                 buffer = malloc(image.sections[i].size);
1889                 if (buffer == NULL)
1890                 {
1891                         command_print(cmd_ctx, "error allocating buffer for section (%d bytes)", image.sections[i].size);
1892                         break;
1893                 }
1894                 
1895                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
1896                 {
1897                         free(buffer);
1898                         break;
1899                 }
1900                 if ((retval = target_write_buffer(target, image.sections[i].base_address, buf_cnt, buffer)) != ERROR_OK)
1901                 {
1902                         free(buffer);
1903                         break;
1904                 }
1905                 image_size += buf_cnt;
1906                 command_print(cmd_ctx, "%u byte written at address 0x%8.8x", buf_cnt, image.sections[i].base_address);
1907                 
1908                 free(buffer);
1909         }
1910
1911         duration_stop_measure(&duration, &duration_text);
1912         if (retval==ERROR_OK)
1913         {
1914                 command_print(cmd_ctx, "downloaded %u byte in %s", image_size, duration_text);
1915         }
1916         free(duration_text);
1917         
1918         image_close(&image);
1919
1920         return retval;
1921
1922 }
1923
1924 int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1925 {
1926         fileio_t fileio;
1927         
1928         u32 address;
1929         u32 size;
1930         u8 buffer[560];
1931         int retval=ERROR_OK;
1932         
1933         duration_t duration;
1934         char *duration_text;
1935         
1936         target_t *target = get_current_target(cmd_ctx);
1937
1938         if (argc != 3)
1939         {
1940                 command_print(cmd_ctx, "usage: dump_image <filename> <address> <size>");
1941                 return ERROR_OK;
1942         }
1943
1944         address = strtoul(args[1], NULL, 0);
1945         size = strtoul(args[2], NULL, 0);
1946
1947         if ((address & 3) || (size & 3))
1948         {
1949                 command_print(cmd_ctx, "only 32-bit aligned address and size are supported");
1950                 return ERROR_OK;
1951         }
1952         
1953         if (fileio_open(&fileio, args[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
1954         {
1955                 return ERROR_OK;
1956         }
1957         
1958         duration_start_measure(&duration);
1959         
1960         while (size > 0)
1961         {
1962                 u32 size_written;
1963                 u32 this_run_size = (size > 560) ? 560 : size;
1964                 
1965                 retval = target->type->read_memory(target, address, 4, this_run_size / 4, buffer);
1966                 if (retval != ERROR_OK)
1967                 {
1968                         break;
1969                 }
1970                 
1971                 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
1972                 if (retval != ERROR_OK)
1973                 {
1974                         break;
1975                 }
1976                 
1977                 size -= this_run_size;
1978                 address += this_run_size;
1979         }
1980
1981         fileio_close(&fileio);
1982
1983         duration_stop_measure(&duration, &duration_text);
1984         if (retval==ERROR_OK)
1985         {
1986                 command_print(cmd_ctx, "dumped %"PRIi64" byte in %s", fileio.size, duration_text);
1987         }
1988         free(duration_text);
1989         
1990         return ERROR_OK;
1991 }
1992
1993 int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1994 {
1995         u8 *buffer;
1996         u32 buf_cnt;
1997         u32 image_size;
1998         int i;
1999         int retval;
2000         u32 checksum = 0;
2001         u32 mem_checksum = 0;
2002
2003         image_t image;  
2004         
2005         duration_t duration;
2006         char *duration_text;
2007         
2008         target_t *target = get_current_target(cmd_ctx);
2009         
2010         if (argc < 1)
2011         {
2012                 command_print(cmd_ctx, "usage: verify_image <file> [offset] [type]");
2013                 return ERROR_OK;
2014         }
2015         
2016         if (!target)
2017         {
2018                 LOG_ERROR("no target selected");
2019                 return ERROR_OK;
2020         }
2021         
2022         duration_start_measure(&duration);
2023         
2024         if (argc >= 2)
2025         {
2026                 image.base_address_set = 1;
2027                 image.base_address = strtoul(args[1], NULL, 0);
2028         }
2029         else
2030         {
2031                 image.base_address_set = 0;
2032                 image.base_address = 0x0;
2033         }
2034
2035         image.start_address_set = 0;
2036
2037         if (image_open(&image, args[0], (argc == 3) ? args[2] : NULL) != ERROR_OK)
2038         {
2039                 return ERROR_OK;
2040         }
2041         
2042         image_size = 0x0;
2043         retval=ERROR_OK;
2044         for (i = 0; i < image.num_sections; i++)
2045         {
2046                 buffer = malloc(image.sections[i].size);
2047                 if (buffer == NULL)
2048                 {
2049                         command_print(cmd_ctx, "error allocating buffer for section (%d bytes)", image.sections[i].size);
2050                         break;
2051                 }
2052                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2053                 {
2054                         free(buffer);
2055                         break;
2056                 }
2057                 
2058                 /* calculate checksum of image */
2059                 image_calculate_checksum( buffer, buf_cnt, &checksum );
2060                 
2061                 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2062                 if( retval != ERROR_OK )
2063                 {
2064                         free(buffer);
2065                         break;
2066                 }
2067                 
2068                 if( checksum != mem_checksum )
2069                 {
2070                         /* failed crc checksum, fall back to a binary compare */
2071                         u8 *data;
2072                         
2073                         command_print(cmd_ctx, "checksum mismatch - attempting binary compare");
2074                         
2075                         data = (u8*)malloc(buf_cnt);
2076                         
2077                         /* Can we use 32bit word accesses? */
2078                         int size = 1;
2079                         int count = buf_cnt;
2080                         if ((count % 4) == 0)
2081                         {
2082                                 size *= 4;
2083                                 count /= 4;
2084                         }
2085                         retval = target->type->read_memory(target, image.sections[i].base_address, size, count, data);
2086                         if (retval == ERROR_OK)
2087                         {
2088                                 int t;
2089                                 for (t = 0; t < buf_cnt; t++)
2090                                 {
2091                                         if (data[t] != buffer[t])
2092                                         {
2093                                                 command_print(cmd_ctx, "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n", t + image.sections[i].base_address, data[t], buffer[t]);
2094                                                 free(data);
2095                                                 free(buffer);
2096                                                 retval=ERROR_FAIL;
2097                                                 goto done;
2098                                         }
2099                                 }
2100                         }
2101                         
2102                         free(data);
2103                 }
2104                 
2105                 free(buffer);
2106                 image_size += buf_cnt;
2107         }
2108 done:   
2109         duration_stop_measure(&duration, &duration_text);
2110         if (retval==ERROR_OK)
2111         {
2112                 command_print(cmd_ctx, "verified %u bytes in %s", image_size, duration_text);
2113         }
2114         free(duration_text);
2115         
2116         image_close(&image);
2117         
2118         return retval;
2119 }
2120
2121 int handle_bp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2122 {
2123         int retval;
2124         target_t *target = get_current_target(cmd_ctx);
2125
2126         if (argc == 0)
2127         {
2128                 breakpoint_t *breakpoint = target->breakpoints;
2129
2130                 while (breakpoint)
2131                 {
2132                         if (breakpoint->type == BKPT_SOFT)
2133                         {
2134                                 char* buf = buf_to_str(breakpoint->orig_instr, breakpoint->length, 16);
2135                                 command_print(cmd_ctx, "0x%8.8x, 0x%x, %i, 0x%s", breakpoint->address, breakpoint->length, breakpoint->set, buf);
2136                                 free(buf);
2137                         }
2138                         else
2139                         {
2140                                 command_print(cmd_ctx, "0x%8.8x, 0x%x, %i", breakpoint->address, breakpoint->length, breakpoint->set);
2141                         }
2142                         breakpoint = breakpoint->next;
2143                 }
2144         }
2145         else if (argc >= 2)
2146         {
2147                 int hw = BKPT_SOFT;
2148                 u32 length = 0;
2149
2150                 length = strtoul(args[1], NULL, 0);
2151                 
2152                 if (argc >= 3)
2153                         if (strcmp(args[2], "hw") == 0)
2154                                 hw = BKPT_HARD;
2155
2156                 if ((retval = breakpoint_add(target, strtoul(args[0], NULL, 0), length, hw)) != ERROR_OK)
2157                 {
2158                         LOG_ERROR("Failure setting breakpoints");
2159                 }
2160                 else
2161                 {
2162                         command_print(cmd_ctx, "breakpoint added at address 0x%8.8x", strtoul(args[0], NULL, 0));
2163                 }
2164         }
2165         else
2166         {
2167                 command_print(cmd_ctx, "usage: bp <address> <length> ['hw']");
2168         }
2169
2170         return ERROR_OK;
2171 }
2172
2173 int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2174 {
2175         target_t *target = get_current_target(cmd_ctx);
2176
2177         if (argc > 0)
2178                 breakpoint_remove(target, strtoul(args[0], NULL, 0));
2179
2180         return ERROR_OK;
2181 }
2182
2183 int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2184 {
2185         target_t *target = get_current_target(cmd_ctx);
2186         int retval;
2187
2188         if (argc == 0)
2189         {
2190                 watchpoint_t *watchpoint = target->watchpoints;
2191
2192                 while (watchpoint)
2193                 {
2194                         command_print(cmd_ctx, "address: 0x%8.8x, mask: 0x%8.8x, r/w/a: %i, value: 0x%8.8x, mask: 0x%8.8x", watchpoint->address, watchpoint->length, watchpoint->rw, watchpoint->value, watchpoint->mask);
2195                         watchpoint = watchpoint->next;
2196                 }
2197         } 
2198         else if (argc >= 2)
2199         {
2200                 enum watchpoint_rw type = WPT_ACCESS;
2201                 u32 data_value = 0x0;
2202                 u32 data_mask = 0xffffffff;
2203                 
2204                 if (argc >= 3)
2205                 {
2206                         switch(args[2][0])
2207                         {
2208                                 case 'r':
2209                                         type = WPT_READ;
2210                                         break;
2211                                 case 'w':
2212                                         type = WPT_WRITE;
2213                                         break;
2214                                 case 'a':
2215                                         type = WPT_ACCESS;
2216                                         break;
2217                                 default:
2218                                         command_print(cmd_ctx, "usage: wp <address> <length> [r/w/a] [value] [mask]");
2219                                         return ERROR_OK;
2220                         }
2221                 }
2222                 if (argc >= 4)
2223                 {
2224                         data_value = strtoul(args[3], NULL, 0);
2225                 }
2226                 if (argc >= 5)
2227                 {
2228                         data_mask = strtoul(args[4], NULL, 0);
2229                 }
2230                 
2231                 if ((retval = watchpoint_add(target, strtoul(args[0], NULL, 0),
2232                                 strtoul(args[1], NULL, 0), type, data_value, data_mask)) != ERROR_OK)
2233                 {
2234                         LOG_ERROR("Failure setting breakpoints");
2235                 }
2236         }
2237         else
2238         {
2239                 command_print(cmd_ctx, "usage: wp <address> <length> [r/w/a] [value] [mask]");
2240         }
2241                 
2242         return ERROR_OK;
2243 }
2244
2245 int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2246 {
2247         target_t *target = get_current_target(cmd_ctx);
2248
2249         if (argc > 0)
2250                 watchpoint_remove(target, strtoul(args[0], NULL, 0));
2251         
2252         return ERROR_OK;
2253 }
2254
2255 int handle_virt2phys_command(command_context_t *cmd_ctx, char *cmd, char **args, int argc)
2256 {
2257         int retval;
2258         target_t *target = get_current_target(cmd_ctx);
2259         u32 va;
2260         u32 pa;
2261
2262         if (argc != 1)
2263         {
2264                 return ERROR_COMMAND_SYNTAX_ERROR;
2265         }
2266         va = strtoul(args[0], NULL, 0);
2267
2268         retval = target->type->virt2phys(target, va, &pa);
2269         if (retval == ERROR_OK)
2270         {
2271                 command_print(cmd_ctx, "Physical address 0x%08x", pa);
2272         }
2273         else
2274         {
2275                 /* lower levels will have logged a detailed error which is 
2276                  * forwarded to telnet/GDB session.  
2277                  */
2278         }
2279         return retval;
2280 }
2281 static void writeLong(FILE *f, int l)
2282 {
2283         int i;
2284         for (i=0; i<4; i++)
2285         {
2286                 char c=(l>>(i*8))&0xff;
2287                 fwrite(&c, 1, 1, f); 
2288         }
2289         
2290 }
2291 static void writeString(FILE *f, char *s)
2292 {
2293         fwrite(s, 1, strlen(s), f); 
2294 }
2295
2296
2297
2298 // Dump a gmon.out histogram file.
2299 static void writeGmon(u32 *samples, int sampleNum, char *filename)
2300 {
2301         int i;
2302         FILE *f=fopen(filename, "w");
2303         if (f==NULL)
2304                 return;
2305         fwrite("gmon", 1, 4, f);
2306         writeLong(f, 0x00000001); // Version
2307         writeLong(f, 0); // padding
2308         writeLong(f, 0); // padding
2309         writeLong(f, 0); // padding
2310                                 
2311         fwrite("", 1, 1, f);  // GMON_TAG_TIME_HIST 
2312
2313         // figure out bucket size
2314         u32 min=samples[0];
2315         u32 max=samples[0];
2316         for (i=0; i<sampleNum; i++)
2317         {
2318                 if (min>samples[i])
2319                 {
2320                         min=samples[i];
2321                 }
2322                 if (max<samples[i])
2323                 {
2324                         max=samples[i];
2325                 }
2326         }
2327
2328         int addressSpace=(max-min+1);
2329         
2330         static int const maxBuckets=256*1024; // maximum buckets.
2331         int length=addressSpace;
2332         if (length > maxBuckets)
2333         {
2334                 length=maxBuckets; 
2335         }
2336         int *buckets=malloc(sizeof(int)*length);
2337         if (buckets==NULL)
2338         {
2339                 fclose(f);
2340                 return;
2341         }
2342         memset(buckets, 0, sizeof(int)*length);
2343         for (i=0; i<sampleNum;i++)
2344         {
2345                 u32 address=samples[i];
2346                 long long a=address-min;
2347                 long long b=length-1;
2348                 long long c=addressSpace-1;
2349                 int index=(a*b)/c; // danger!!!! int32 overflows 
2350                 buckets[index]++;
2351         }
2352         
2353         //                         append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr))
2354         writeLong(f, min);                                      // low_pc
2355         writeLong(f, max);              // high_pc
2356         writeLong(f, length);           // # of samples
2357         writeLong(f, 64000000);                         // 64MHz
2358         writeString(f, "seconds");
2359         for (i=0; i<(15-strlen("seconds")); i++)
2360         {
2361                 fwrite("", 1, 1, f);  // padding
2362         }
2363         writeString(f, "s");
2364                 
2365 //                         append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size)
2366         
2367         char *data=malloc(2*length);
2368         if (data!=NULL)
2369         {
2370                 for (i=0; i<length;i++)
2371                 {
2372                         int val;
2373                         val=buckets[i];
2374                         if (val>65535)
2375                         {
2376                                 val=65535;
2377                         }
2378                         data[i*2]=val&0xff;
2379                         data[i*2+1]=(val>>8)&0xff;
2380                 }
2381                 free(buckets);
2382                 fwrite(data, 1, length*2, f);
2383                 free(data);
2384         } else
2385         {
2386                 free(buckets);
2387         }
2388
2389         fclose(f);
2390 }
2391
2392 /* profiling samples the CPU PC as quickly as OpenOCD is able, which will be used as a random sampling of PC */
2393 int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2394 {
2395         target_t *target = get_current_target(cmd_ctx);
2396         struct timeval timeout, now;
2397         
2398         gettimeofday(&timeout, NULL);
2399         if (argc!=2)
2400         {
2401                 return ERROR_COMMAND_SYNTAX_ERROR;
2402         }
2403         char *end;
2404         timeval_add_time(&timeout, strtoul(args[0], &end, 0), 0);
2405         if (*end) 
2406         {
2407                 return ERROR_OK;
2408         }
2409         
2410         command_print(cmd_ctx, "Starting profiling. Halting and resuming the target as often as we can...");
2411
2412         static const int maxSample=10000;
2413         u32 *samples=malloc(sizeof(u32)*maxSample);
2414         if (samples==NULL)
2415                 return ERROR_OK;
2416         
2417         int numSamples=0;
2418         int retval=ERROR_OK;
2419         // hopefully it is safe to cache! We want to stop/restart as quickly as possible.
2420         reg_t *reg = register_get_by_name(target->reg_cache, "pc", 1);
2421         
2422         for (;;)
2423         {
2424                 target->type->poll(target);
2425                 if (target->state == TARGET_HALTED)
2426                 {
2427                         u32 t=*((u32 *)reg->value);
2428                         samples[numSamples++]=t;
2429                         retval = target->type->resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
2430                         target->type->poll(target);
2431                         usleep(10*1000); // sleep 10ms, i.e. <100 samples/second.
2432                 } else if (target->state == TARGET_RUNNING)
2433                 {
2434                         // We want to quickly sample the PC.
2435                         target->type->halt(target);
2436                 } else
2437                 {
2438                         command_print(cmd_ctx, "Target not halted or running");
2439                         retval=ERROR_OK;
2440                         break;
2441                 }
2442                 if (retval!=ERROR_OK)
2443                 {
2444                         break;
2445                 }
2446                 
2447                 gettimeofday(&now, NULL);
2448                 if ((numSamples>=maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
2449                 {
2450                         command_print(cmd_ctx, "Profiling completed. %d samples.", numSamples);
2451                         target->type->poll(target);
2452                         if (target->state == TARGET_HALTED)
2453                         {
2454                                 target->type->resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
2455                         }
2456                         target->type->poll(target);
2457                         writeGmon(samples, numSamples, args[1]);
2458                         command_print(cmd_ctx, "Wrote %s", args[1]);
2459                         break;
2460                 }
2461         }
2462         free(samples);
2463         
2464         return ERROR_OK;
2465 }
2466