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