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