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