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