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