Overhaul time support API
[fw/openocd] / src / target / target.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2007-2009 Ã˜yvind Harboe                                 *
6  *   oyvind.harboe@zylin.com                                               *
7  *                                                                         *
8  *   Copyright (C) 2008, Duane Ellis                                       *
9  *   openocd@duaneeellis.com                                               *
10  *                                                                         *
11  *   Copyright (C) 2008 by Spencer Oliver                                  *
12  *   spen@spen-soft.co.uk                                                  *
13  *                                                                         *
14  *   Copyright (C) 2008 by Rick Altherr                                    *
15  *   kc8apf@kc8apf.net>                                                    *
16  *                                                                         *
17  *   This program is free software; you can redistribute it and/or modify  *
18  *   it under the terms of the GNU General Public License as published by  *
19  *   the Free Software Foundation; either version 2 of the License, or     *
20  *   (at your option) any later version.                                   *
21  *                                                                         *
22  *   This program is distributed in the hope that it will be useful,       *
23  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
24  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
25  *   GNU General Public License for more details.                          *
26  *                                                                         *
27  *   You should have received a copy of the GNU General Public License     *
28  *   along with this program; if not, write to the                         *
29  *   Free Software Foundation, Inc.,                                       *
30  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
31  ***************************************************************************/
32 #ifdef HAVE_CONFIG_H
33 #include "config.h"
34 #endif
35
36 #include "target.h"
37 #include "target_type.h"
38 #include "target_request.h"
39 #include "time_support.h"
40 #include "register.h"
41 #include "trace.h"
42 #include "image.h"
43 #include "jtag.h"
44
45
46 static int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
47
48 static int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
49 static int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
50 static int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
51 static int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
52 static int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
53 static int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
54 static int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
55 static int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
56 static int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
57 static int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
58 static int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
59 static int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
60 static int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
61 static int handle_test_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
62 static int handle_bp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
63 static int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
64 static int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
65 static int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
66 static int handle_virt2phys_command(command_context_t *cmd_ctx, char *cmd, char **args, int argc);
67 static int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
68 static int handle_fast_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
69 static int handle_fast_load_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
70
71 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
72 static int jim_mcrmrc(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
73 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
74 static int jim_target(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
75
76 static int target_array2mem(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv);
77 static int target_mem2array(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv);
78
79 /* targets */
80 extern target_type_t arm7tdmi_target;
81 extern target_type_t arm720t_target;
82 extern target_type_t arm9tdmi_target;
83 extern target_type_t arm920t_target;
84 extern target_type_t arm966e_target;
85 extern target_type_t arm926ejs_target;
86 extern target_type_t fa526_target;
87 extern target_type_t feroceon_target;
88 extern target_type_t dragonite_target;
89 extern target_type_t xscale_target;
90 extern target_type_t cortexm3_target;
91 extern target_type_t cortexa8_target;
92 extern target_type_t arm11_target;
93 extern target_type_t mips_m4k_target;
94 extern target_type_t avr_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         &fa526_target,
105         &feroceon_target,
106         &dragonite_target,
107         &xscale_target,
108         &cortexm3_target,
109         &cortexa8_target,
110         &arm11_target,
111         &mips_m4k_target,
112         &avr_target,
113         NULL,
114 };
115
116 target_t *all_targets = NULL;
117 target_event_callback_t *target_event_callbacks = NULL;
118 target_timer_callback_t *target_timer_callbacks = NULL;
119
120 const Jim_Nvp nvp_assert[] = {
121         { .name = "assert", NVP_ASSERT },
122         { .name = "deassert", NVP_DEASSERT },
123         { .name = "T", NVP_ASSERT },
124         { .name = "F", NVP_DEASSERT },
125         { .name = "t", NVP_ASSERT },
126         { .name = "f", NVP_DEASSERT },
127         { .name = NULL, .value = -1 }
128 };
129
130 const Jim_Nvp nvp_error_target[] = {
131         { .value = ERROR_TARGET_INVALID, .name = "err-invalid" },
132         { .value = ERROR_TARGET_INIT_FAILED, .name = "err-init-failed" },
133         { .value = ERROR_TARGET_TIMEOUT, .name = "err-timeout" },
134         { .value = ERROR_TARGET_NOT_HALTED, .name = "err-not-halted" },
135         { .value = ERROR_TARGET_FAILURE, .name = "err-failure" },
136         { .value = ERROR_TARGET_UNALIGNED_ACCESS   , .name = "err-unaligned-access" },
137         { .value = ERROR_TARGET_DATA_ABORT , .name = "err-data-abort" },
138         { .value = ERROR_TARGET_RESOURCE_NOT_AVAILABLE , .name = "err-resource-not-available" },
139         { .value = ERROR_TARGET_TRANSLATION_FAULT  , .name = "err-translation-fault" },
140         { .value = ERROR_TARGET_NOT_RUNNING, .name = "err-not-running" },
141         { .value = ERROR_TARGET_NOT_EXAMINED, .name = "err-not-examined" },
142         { .value = -1, .name = NULL }
143 };
144
145 const char *target_strerror_safe(int err)
146 {
147         const Jim_Nvp *n;
148
149         n = Jim_Nvp_value2name_simple(nvp_error_target, err);
150         if (n->name == NULL) {
151                 return "unknown";
152         } else {
153                 return n->name;
154         }
155 }
156
157 static const Jim_Nvp nvp_target_event[] = {
158         { .value = TARGET_EVENT_OLD_gdb_program_config , .name = "old-gdb_program_config" },
159         { .value = TARGET_EVENT_OLD_pre_resume         , .name = "old-pre_resume" },
160
161         { .value = TARGET_EVENT_GDB_HALT, .name = "gdb-halt" },
162         { .value = TARGET_EVENT_HALTED, .name = "halted" },
163         { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
164         { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
165         { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
166
167         { .name = "gdb-start", .value = TARGET_EVENT_GDB_START },
168         { .name = "gdb-end", .value = TARGET_EVENT_GDB_END },
169
170         /* historical name */
171
172         { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
173
174         { .value = TARGET_EVENT_RESET_ASSERT_PRE,    .name = "reset-assert-pre" },
175         { .value = TARGET_EVENT_RESET_ASSERT_POST,   .name = "reset-assert-post" },
176         { .value = TARGET_EVENT_RESET_DEASSERT_PRE,  .name = "reset-deassert-pre" },
177         { .value = TARGET_EVENT_RESET_DEASSERT_POST, .name = "reset-deassert-post" },
178         { .value = TARGET_EVENT_RESET_HALT_PRE,      .name = "reset-halt-pre" },
179         { .value = TARGET_EVENT_RESET_HALT_POST,     .name = "reset-halt-post" },
180         { .value = TARGET_EVENT_RESET_WAIT_PRE,      .name = "reset-wait-pre" },
181         { .value = TARGET_EVENT_RESET_WAIT_POST,     .name = "reset-wait-post" },
182         { .value = TARGET_EVENT_RESET_INIT , .name = "reset-init" },
183         { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
184
185         { .value = TARGET_EVENT_EXAMINE_START, .name = "examine-start" },
186         { .value = TARGET_EVENT_EXAMINE_END, .name = "examine-end" },
187
188         { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
189         { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
190
191         { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
192         { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
193
194         { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
195         { .value = TARGET_EVENT_GDB_FLASH_WRITE_END  , .name = "gdb-flash-write-end"   },
196
197         { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
198         { .value = TARGET_EVENT_GDB_FLASH_ERASE_END  , .name = "gdb-flash-erase-end" },
199
200         { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
201         { .value = TARGET_EVENT_RESUMED     , .name = "resume-ok" },
202         { .value = TARGET_EVENT_RESUME_END  , .name = "resume-end" },
203
204         { .name = NULL, .value = -1 }
205 };
206
207 const Jim_Nvp nvp_target_state[] = {
208         { .name = "unknown", .value = TARGET_UNKNOWN },
209         { .name = "running", .value = TARGET_RUNNING },
210         { .name = "halted",  .value = TARGET_HALTED },
211         { .name = "reset",   .value = TARGET_RESET },
212         { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
213         { .name = NULL, .value = -1 },
214 };
215
216 const Jim_Nvp nvp_target_debug_reason [] = {
217         { .name = "debug-request"            , .value = DBG_REASON_DBGRQ },
218         { .name = "breakpoint"               , .value = DBG_REASON_BREAKPOINT },
219         { .name = "watchpoint"               , .value = DBG_REASON_WATCHPOINT },
220         { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
221         { .name = "single-step"              , .value = DBG_REASON_SINGLESTEP },
222         { .name = "target-not-halted"        , .value = DBG_REASON_NOTHALTED  },
223         { .name = "undefined"                , .value = DBG_REASON_UNDEFINED },
224         { .name = NULL, .value = -1 },
225 };
226
227 const Jim_Nvp nvp_target_endian[] = {
228         { .name = "big",    .value = TARGET_BIG_ENDIAN },
229         { .name = "little", .value = TARGET_LITTLE_ENDIAN },
230         { .name = "be",     .value = TARGET_BIG_ENDIAN },
231         { .name = "le",     .value = TARGET_LITTLE_ENDIAN },
232         { .name = NULL,     .value = -1 },
233 };
234
235 const Jim_Nvp nvp_reset_modes[] = {
236         { .name = "unknown", .value = RESET_UNKNOWN },
237         { .name = "run"    , .value = RESET_RUN },
238         { .name = "halt"   , .value = RESET_HALT },
239         { .name = "init"   , .value = RESET_INIT },
240         { .name = NULL     , .value = -1 },
241 };
242
243 const char *
244 target_state_name( target_t *t )
245 {
246         const char *cp;
247         cp = Jim_Nvp_value2name_simple(nvp_target_state, t->state)->name;
248         if( !cp ){
249                 LOG_ERROR("Invalid target state: %d", (int)(t->state));
250                 cp = "(*BUG*unknown*BUG*)";
251         }
252         return cp;
253 }
254
255 /* determine the number of the new target */
256 static int new_target_number(void)
257 {
258         target_t *t;
259         int x;
260
261         /* number is 0 based */
262         x = -1;
263         t = all_targets;
264         while (t) {
265                 if (x < t->target_number) {
266                         x = t->target_number;
267                 }
268                 t = t->next;
269         }
270         return x + 1;
271 }
272
273 /* read a uint32_t from a buffer in target memory endianness */
274 uint32_t target_buffer_get_u32(target_t *target, const uint8_t *buffer)
275 {
276         if (target->endianness == TARGET_LITTLE_ENDIAN)
277                 return le_to_h_u32(buffer);
278         else
279                 return be_to_h_u32(buffer);
280 }
281
282 /* read a uint16_t from a buffer in target memory endianness */
283 uint16_t target_buffer_get_u16(target_t *target, const uint8_t *buffer)
284 {
285         if (target->endianness == TARGET_LITTLE_ENDIAN)
286                 return le_to_h_u16(buffer);
287         else
288                 return be_to_h_u16(buffer);
289 }
290
291 /* read a uint8_t from a buffer in target memory endianness */
292 uint8_t target_buffer_get_u8(target_t *target, const uint8_t *buffer)
293 {
294         return *buffer & 0x0ff;
295 }
296
297 /* write a uint32_t to a buffer in target memory endianness */
298 void target_buffer_set_u32(target_t *target, uint8_t *buffer, uint32_t value)
299 {
300         if (target->endianness == TARGET_LITTLE_ENDIAN)
301                 h_u32_to_le(buffer, value);
302         else
303                 h_u32_to_be(buffer, value);
304 }
305
306 /* write a uint16_t to a buffer in target memory endianness */
307 void target_buffer_set_u16(target_t *target, uint8_t *buffer, uint16_t value)
308 {
309         if (target->endianness == TARGET_LITTLE_ENDIAN)
310                 h_u16_to_le(buffer, value);
311         else
312                 h_u16_to_be(buffer, value);
313 }
314
315 /* write a uint8_t to a buffer in target memory endianness */
316 void target_buffer_set_u8(target_t *target, uint8_t *buffer, uint8_t value)
317 {
318         *buffer = value;
319 }
320
321 /* return a pointer to a configured target; id is name or number */
322 target_t *get_target(const char *id)
323 {
324         target_t *target;
325
326         /* try as tcltarget name */
327         for (target = all_targets; target; target = target->next) {
328                 if (target->cmd_name == NULL)
329                         continue;
330                 if (strcmp(id, target->cmd_name) == 0)
331                         return target;
332         }
333
334         /* It's OK to remove this fallback sometime after August 2010 or so */
335
336         /* no match, try as number */
337         unsigned num;
338         if (parse_uint(id, &num) != ERROR_OK)
339                 return NULL;
340
341         for (target = all_targets; target; target = target->next) {
342                 if (target->target_number == (int)num) {
343                         LOG_WARNING("use '%s' as target identifier, not '%u'",
344                                         target->cmd_name, num);
345                         return target;
346                 }
347         }
348
349         return NULL;
350 }
351
352 /* returns a pointer to the n-th configured target */
353 static target_t *get_target_by_num(int num)
354 {
355         target_t *target = all_targets;
356
357         while (target) {
358                 if (target->target_number == num) {
359                         return target;
360                 }
361                 target = target->next;
362         }
363
364         return NULL;
365 }
366
367 target_t* get_current_target(command_context_t *cmd_ctx)
368 {
369         target_t *target = get_target_by_num(cmd_ctx->current_target);
370
371         if (target == NULL)
372         {
373                 LOG_ERROR("BUG: current_target out of bounds");
374                 exit(-1);
375         }
376
377         return target;
378 }
379
380 int target_poll(struct target_s *target)
381 {
382         int retval;
383
384         /* We can't poll until after examine */
385         if (!target_was_examined(target))
386         {
387                 /* Fail silently lest we pollute the log */
388                 return ERROR_FAIL;
389         }
390
391         retval = target->type->poll(target);
392         if (retval != ERROR_OK)
393                 return retval;
394
395         if (target->halt_issued)
396         {
397                 if (target->state == TARGET_HALTED)
398                 {
399                         target->halt_issued = false;
400                 } else
401                 {
402                         long long t = timeval_ms() - target->halt_issued_time;
403                         if (t>1000)
404                         {
405                                 target->halt_issued = false;
406                                 LOG_INFO("Halt timed out, wake up GDB.");
407                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
408                         }
409                 }
410         }
411
412         return ERROR_OK;
413 }
414
415 int target_halt(struct target_s *target)
416 {
417         int retval;
418         /* We can't poll until after examine */
419         if (!target_was_examined(target))
420         {
421                 LOG_ERROR("Target not examined yet");
422                 return ERROR_FAIL;
423         }
424
425         retval = target->type->halt(target);
426         if (retval != ERROR_OK)
427                 return retval;
428
429         target->halt_issued = true;
430         target->halt_issued_time = timeval_ms();
431
432         return ERROR_OK;
433 }
434
435 int target_resume(struct target_s *target, int current, uint32_t address, int handle_breakpoints, int debug_execution)
436 {
437         int retval;
438
439         /* We can't poll until after examine */
440         if (!target_was_examined(target))
441         {
442                 LOG_ERROR("Target not examined yet");
443                 return ERROR_FAIL;
444         }
445
446         /* note that resume *must* be asynchronous. The CPU can halt before we poll. The CPU can
447          * even halt at the current PC as a result of a software breakpoint being inserted by (a bug?)
448          * the application.
449          */
450         if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
451                 return retval;
452
453         return retval;
454 }
455
456 int target_process_reset(struct command_context_s *cmd_ctx, enum target_reset_mode reset_mode)
457 {
458         char buf[100];
459         int retval;
460         Jim_Nvp *n;
461         n = Jim_Nvp_value2name_simple(nvp_reset_modes, reset_mode);
462         if (n->name == NULL) {
463                 LOG_ERROR("invalid reset mode");
464                 return ERROR_FAIL;
465         }
466
467         /* disable polling during reset to make reset event scripts
468          * more predictable, i.e. dr/irscan & pathmove in events will
469          * not have JTAG operations injected into the middle of a sequence.
470          */
471         bool save_poll = jtag_poll_get_enabled();
472
473         jtag_poll_set_enabled(false);
474
475         sprintf(buf, "ocd_process_reset %s", n->name);
476         retval = Jim_Eval(interp, buf);
477
478         jtag_poll_set_enabled(save_poll);
479
480         if (retval != JIM_OK) {
481                 Jim_PrintErrorMessage(interp);
482                 return ERROR_FAIL;
483         }
484
485         /* We want any events to be processed before the prompt */
486         retval = target_call_timer_callbacks_now();
487
488         return retval;
489 }
490
491 static int default_virt2phys(struct target_s *target, uint32_t virtual, uint32_t *physical)
492 {
493         *physical = virtual;
494         return ERROR_OK;
495 }
496
497 static int default_mmu(struct target_s *target, int *enabled)
498 {
499         LOG_ERROR("Not implemented.");
500         return ERROR_FAIL;
501 }
502
503 static int default_has_mmu(struct target_s *target, bool *has_mmu)
504 {
505         *has_mmu = true;
506         return ERROR_OK;
507 }
508
509 static int default_examine(struct target_s *target)
510 {
511         target_set_examined(target);
512         return ERROR_OK;
513 }
514
515 int target_examine_one(struct target_s *target)
516 {
517         return target->type->examine(target);
518 }
519
520 static int jtag_enable_callback(enum jtag_event event, void *priv)
521 {
522         target_t *target = priv;
523
524         if (event != JTAG_TAP_EVENT_ENABLE || !target->tap->enabled)
525                 return ERROR_OK;
526
527         jtag_unregister_event_callback(jtag_enable_callback, target);
528         return target_examine_one(target);
529 }
530
531
532 /* Targets that correctly implement init + examine, i.e.
533  * no communication with target during init:
534  *
535  * XScale
536  */
537 int target_examine(void)
538 {
539         int retval = ERROR_OK;
540         target_t *target;
541
542         for (target = all_targets; target; target = target->next)
543         {
544                 /* defer examination, but don't skip it */
545                 if (!target->tap->enabled) {
546                         jtag_register_event_callback(jtag_enable_callback,
547                                         target);
548                         continue;
549                 }
550                 if ((retval = target_examine_one(target)) != ERROR_OK)
551                         return retval;
552         }
553         return retval;
554 }
555 const char *target_get_name(struct target_s *target)
556 {
557         return target->type->name;
558 }
559
560 static int target_write_memory_imp(struct target_s *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
561 {
562         if (!target_was_examined(target))
563         {
564                 LOG_ERROR("Target not examined yet");
565                 return ERROR_FAIL;
566         }
567         return target->type->write_memory_imp(target, address, size, count, buffer);
568 }
569
570 static int target_read_memory_imp(struct target_s *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
571 {
572         if (!target_was_examined(target))
573         {
574                 LOG_ERROR("Target not examined yet");
575                 return ERROR_FAIL;
576         }
577         return target->type->read_memory_imp(target, address, size, count, buffer);
578 }
579
580 static int target_soft_reset_halt_imp(struct target_s *target)
581 {
582         if (!target_was_examined(target))
583         {
584                 LOG_ERROR("Target not examined yet");
585                 return ERROR_FAIL;
586         }
587         if (!target->type->soft_reset_halt_imp) {
588                 LOG_ERROR("Target %s does not support soft_reset_halt",
589                                 target->cmd_name);
590                 return ERROR_FAIL;
591         }
592         return target->type->soft_reset_halt_imp(target);
593 }
594
595 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, uint32_t entry_point, uint32_t exit_point, int timeout_ms, void *arch_info)
596 {
597         if (!target_was_examined(target))
598         {
599                 LOG_ERROR("Target not examined yet");
600                 return ERROR_FAIL;
601         }
602         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);
603 }
604
605 int target_read_memory(struct target_s *target,
606                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
607 {
608         return target->type->read_memory(target, address, size, count, buffer);
609 }
610
611 int target_read_phys_memory(struct target_s *target,
612                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
613 {
614         return target->type->read_phys_memory(target, address, size, count, buffer);
615 }
616
617 int target_write_memory(struct target_s *target,
618                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
619 {
620         return target->type->write_memory(target, address, size, count, buffer);
621 }
622
623 int target_write_phys_memory(struct target_s *target,
624                 uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
625 {
626         return target->type->write_phys_memory(target, address, size, count, buffer);
627 }
628
629 int target_bulk_write_memory(struct target_s *target,
630                 uint32_t address, uint32_t count, uint8_t *buffer)
631 {
632         return target->type->bulk_write_memory(target, address, count, buffer);
633 }
634
635 int target_add_breakpoint(struct target_s *target,
636                 struct breakpoint_s *breakpoint)
637 {
638         return target->type->add_breakpoint(target, breakpoint);
639 }
640 int target_remove_breakpoint(struct target_s *target,
641                 struct breakpoint_s *breakpoint)
642 {
643         return target->type->remove_breakpoint(target, breakpoint);
644 }
645
646 int target_add_watchpoint(struct target_s *target,
647                 struct watchpoint_s *watchpoint)
648 {
649         return target->type->add_watchpoint(target, watchpoint);
650 }
651 int target_remove_watchpoint(struct target_s *target,
652                 struct watchpoint_s *watchpoint)
653 {
654         return target->type->remove_watchpoint(target, watchpoint);
655 }
656
657 int target_get_gdb_reg_list(struct target_s *target,
658                 struct reg_s **reg_list[], int *reg_list_size)
659 {
660         return target->type->get_gdb_reg_list(target, reg_list, reg_list_size);
661 }
662 int target_step(struct target_s *target,
663                 int current, uint32_t address, int handle_breakpoints)
664 {
665         return target->type->step(target, current, address, handle_breakpoints);
666 }
667
668
669 int target_run_algorithm(struct target_s *target,
670                 int num_mem_params, mem_param_t *mem_params,
671                 int num_reg_params, reg_param_t *reg_param,
672                 uint32_t entry_point, uint32_t exit_point,
673                 int timeout_ms, void *arch_info)
674 {
675         return target->type->run_algorithm(target,
676                         num_mem_params, mem_params, num_reg_params, reg_param,
677                         entry_point, exit_point, timeout_ms, arch_info);
678 }
679
680 /// @returns @c true if the target has been examined.
681 bool target_was_examined(struct target_s *target)
682 {
683         return target->type->examined;
684 }
685 /// Sets the @c examined flag for the given target.
686 void target_set_examined(struct target_s *target)
687 {
688         target->type->examined = true;
689 }
690 // Reset the @c examined flag for the given target.
691 void target_reset_examined(struct target_s *target)
692 {
693         target->type->examined = false;
694 }
695
696
697
698 static int default_mrc(struct target_s *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t *value)
699 {
700         LOG_ERROR("Not implemented");
701         return ERROR_FAIL;
702 }
703
704 static int default_mcr(struct target_s *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t value)
705 {
706         LOG_ERROR("Not implemented");
707         return ERROR_FAIL;
708 }
709
710 static int arm_cp_check(struct target_s *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm)
711 {
712         /* basic check */
713         if (!target_was_examined(target))
714         {
715                 LOG_ERROR("Target not examined yet");
716                 return ERROR_FAIL;
717         }
718
719         if ((cpnum <0) || (cpnum > 15))
720         {
721                 LOG_ERROR("Illegal co-processor %d", cpnum);
722                 return ERROR_FAIL;
723         }
724
725         if (op1 > 7)
726         {
727                 LOG_ERROR("Illegal op1");
728                 return ERROR_FAIL;
729         }
730
731         if (op2 > 7)
732         {
733                 LOG_ERROR("Illegal op2");
734                 return ERROR_FAIL;
735         }
736
737         if (CRn > 15)
738         {
739                 LOG_ERROR("Illegal CRn");
740                 return ERROR_FAIL;
741         }
742
743         if (CRm > 15)
744         {
745                 LOG_ERROR("Illegal CRm");
746                 return ERROR_FAIL;
747         }
748
749         return ERROR_OK;
750 }
751
752 int target_mrc(struct target_s *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t *value)
753 {
754         int retval;
755
756         retval = arm_cp_check(target, cpnum, op1, op2, CRn, CRm);
757         if (retval != ERROR_OK)
758                 return retval;
759
760         return target->type->mrc(target, cpnum, op1, op2, CRn, CRm, value);
761 }
762
763 int target_mcr(struct target_s *target, int cpnum, uint32_t op1, uint32_t op2, uint32_t CRn, uint32_t CRm, uint32_t value)
764 {
765         int retval;
766
767         retval = arm_cp_check(target, cpnum, op1, op2, CRn, CRm);
768         if (retval != ERROR_OK)
769                 return retval;
770
771         return target->type->mcr(target, cpnum, op1, op2, CRn, CRm, value);
772 }
773
774 static int default_read_phys_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
775 {
776         int retval;
777         bool mmu;
778         retval = target->type->has_mmu(target, &mmu);
779         if (retval != ERROR_OK)
780                 return retval;
781         if (mmu)
782         {
783                 LOG_ERROR("Not implemented");
784                 return ERROR_FAIL;
785         }
786         return target_read_memory(target, address, size, count, buffer);
787 }
788
789 static int default_write_phys_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer)
790 {
791         int retval;
792         bool mmu;
793         retval = target->type->has_mmu(target, &mmu);
794         if (retval != ERROR_OK)
795                 return retval;
796         if (mmu)
797         {
798                 LOG_ERROR("Not implemented");
799                 return ERROR_FAIL;
800         }
801         return target_write_memory(target, address, size, count, buffer);
802 }
803
804
805 int target_init(struct command_context_s *cmd_ctx)
806 {
807         target_t *target = all_targets;
808         int retval;
809
810         while (target)
811         {
812                 target_reset_examined(target);
813                 if (target->type->examine == NULL)
814                 {
815                         target->type->examine = default_examine;
816                 }
817
818                 if ((retval = target->type->init_target(cmd_ctx, target)) != ERROR_OK)
819                 {
820                         LOG_ERROR("target '%s' init failed", target_get_name(target));
821                         return retval;
822                 }
823
824                 /* Set up default functions if none are provided by target */
825                 if (target->type->virt2phys == NULL)
826                 {
827                         target->type->virt2phys = default_virt2phys;
828                 }
829
830                 if (target->type->read_phys_memory == NULL)
831                 {
832                         target->type->read_phys_memory = default_read_phys_memory;
833                 }
834
835                 if (target->type->write_phys_memory == NULL)
836                 {
837                         target->type->write_phys_memory = default_write_phys_memory;
838                 }
839
840                 if (target->type->mcr == NULL)
841                 {
842                         target->type->mcr = default_mcr;
843                 } else
844                 {
845                         /* FIX! multiple targets will generally register global commands
846                          * multiple times. Only register this one if *one* of the
847                          * targets need the command. Hmm... make it a command on the
848                          * Jim Tcl target object?
849                          */
850                         register_jim(cmd_ctx, "mcr", jim_mcrmrc, "write coprocessor <cpnum> <op1> <op2> <CRn> <CRm> <value>");
851                 }
852
853                 if (target->type->mrc == NULL)
854                 {
855                         target->type->mrc = default_mrc;
856                 } else
857                 {
858                         register_jim(cmd_ctx, "mrc", jim_mcrmrc, "read coprocessor <cpnum> <op1> <op2> <CRn> <CRm>");
859                 }
860
861
862                 /* a non-invasive way(in terms of patches) to add some code that
863                  * runs before the type->write/read_memory implementation
864                  */
865                 target->type->write_memory_imp = target->type->write_memory;
866                 target->type->write_memory = target_write_memory_imp;
867                 target->type->read_memory_imp = target->type->read_memory;
868                 target->type->read_memory = target_read_memory_imp;
869                 target->type->soft_reset_halt_imp = target->type->soft_reset_halt;
870                 target->type->soft_reset_halt = target_soft_reset_halt_imp;
871                 target->type->run_algorithm_imp = target->type->run_algorithm;
872                 target->type->run_algorithm = target_run_algorithm_imp;
873
874                 if (target->type->mmu == NULL)
875                 {
876                         target->type->mmu = default_mmu;
877                 }
878                 if (target->type->has_mmu == NULL)
879                 {
880                         target->type->has_mmu = default_has_mmu;
881                 }
882                 target = target->next;
883         }
884
885         if (all_targets)
886         {
887                 if ((retval = target_register_user_commands(cmd_ctx)) != ERROR_OK)
888                         return retval;
889                 if ((retval = target_register_timer_callback(handle_target, 100, 1, NULL)) != ERROR_OK)
890                         return retval;
891         }
892
893         return ERROR_OK;
894 }
895
896 int target_register_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
897 {
898         target_event_callback_t **callbacks_p = &target_event_callbacks;
899
900         if (callback == NULL)
901         {
902                 return ERROR_INVALID_ARGUMENTS;
903         }
904
905         if (*callbacks_p)
906         {
907                 while ((*callbacks_p)->next)
908                         callbacks_p = &((*callbacks_p)->next);
909                 callbacks_p = &((*callbacks_p)->next);
910         }
911
912         (*callbacks_p) = malloc(sizeof(target_event_callback_t));
913         (*callbacks_p)->callback = callback;
914         (*callbacks_p)->priv = priv;
915         (*callbacks_p)->next = NULL;
916
917         return ERROR_OK;
918 }
919
920 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
921 {
922         target_timer_callback_t **callbacks_p = &target_timer_callbacks;
923         struct timeval now;
924
925         if (callback == NULL)
926         {
927                 return ERROR_INVALID_ARGUMENTS;
928         }
929
930         if (*callbacks_p)
931         {
932                 while ((*callbacks_p)->next)
933                         callbacks_p = &((*callbacks_p)->next);
934                 callbacks_p = &((*callbacks_p)->next);
935         }
936
937         (*callbacks_p) = malloc(sizeof(target_timer_callback_t));
938         (*callbacks_p)->callback = callback;
939         (*callbacks_p)->periodic = periodic;
940         (*callbacks_p)->time_ms = time_ms;
941
942         gettimeofday(&now, NULL);
943         (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
944         time_ms -= (time_ms % 1000);
945         (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
946         if ((*callbacks_p)->when.tv_usec > 1000000)
947         {
948                 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
949                 (*callbacks_p)->when.tv_sec += 1;
950         }
951
952         (*callbacks_p)->priv = priv;
953         (*callbacks_p)->next = NULL;
954
955         return ERROR_OK;
956 }
957
958 int target_unregister_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
959 {
960         target_event_callback_t **p = &target_event_callbacks;
961         target_event_callback_t *c = target_event_callbacks;
962
963         if (callback == NULL)
964         {
965                 return ERROR_INVALID_ARGUMENTS;
966         }
967
968         while (c)
969         {
970                 target_event_callback_t *next = c->next;
971                 if ((c->callback == callback) && (c->priv == priv))
972                 {
973                         *p = next;
974                         free(c);
975                         return ERROR_OK;
976                 }
977                 else
978                         p = &(c->next);
979                 c = next;
980         }
981
982         return ERROR_OK;
983 }
984
985 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
986 {
987         target_timer_callback_t **p = &target_timer_callbacks;
988         target_timer_callback_t *c = target_timer_callbacks;
989
990         if (callback == NULL)
991         {
992                 return ERROR_INVALID_ARGUMENTS;
993         }
994
995         while (c)
996         {
997                 target_timer_callback_t *next = c->next;
998                 if ((c->callback == callback) && (c->priv == priv))
999                 {
1000                         *p = next;
1001                         free(c);
1002                         return ERROR_OK;
1003                 }
1004                 else
1005                         p = &(c->next);
1006                 c = next;
1007         }
1008
1009         return ERROR_OK;
1010 }
1011
1012 int target_call_event_callbacks(target_t *target, enum target_event event)
1013 {
1014         target_event_callback_t *callback = target_event_callbacks;
1015         target_event_callback_t *next_callback;
1016
1017         if (event == TARGET_EVENT_HALTED)
1018         {
1019                 /* execute early halted first */
1020                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1021         }
1022
1023         LOG_DEBUG("target event %i (%s)",
1024                           event,
1025                           Jim_Nvp_value2name_simple(nvp_target_event, event)->name);
1026
1027         target_handle_event(target, event);
1028
1029         while (callback)
1030         {
1031                 next_callback = callback->next;
1032                 callback->callback(target, event, callback->priv);
1033                 callback = next_callback;
1034         }
1035
1036         return ERROR_OK;
1037 }
1038
1039 static int target_timer_callback_periodic_restart(
1040                 target_timer_callback_t *cb, struct timeval *now)
1041 {
1042         int time_ms = cb->time_ms;
1043         cb->when.tv_usec = now->tv_usec + (time_ms % 1000) * 1000;
1044         time_ms -= (time_ms % 1000);
1045         cb->when.tv_sec = now->tv_sec + time_ms / 1000;
1046         if (cb->when.tv_usec > 1000000)
1047         {
1048                 cb->when.tv_usec = cb->when.tv_usec - 1000000;
1049                 cb->when.tv_sec += 1;
1050         }
1051         return ERROR_OK;
1052 }
1053
1054 static int target_call_timer_callback(target_timer_callback_t *cb,
1055                 struct timeval *now)
1056 {
1057         cb->callback(cb->priv);
1058
1059         if (cb->periodic)
1060                 return target_timer_callback_periodic_restart(cb, now);
1061
1062         return target_unregister_timer_callback(cb->callback, cb->priv);
1063 }
1064
1065 static int target_call_timer_callbacks_check_time(int checktime)
1066 {
1067         keep_alive();
1068
1069         struct timeval now;
1070         gettimeofday(&now, NULL);
1071
1072         target_timer_callback_t *callback = target_timer_callbacks;
1073         while (callback)
1074         {
1075                 // cleaning up may unregister and free this callback
1076                 target_timer_callback_t *next_callback = callback->next;
1077
1078                 bool call_it = callback->callback &&
1079                         ((!checktime && callback->periodic) ||
1080                           now.tv_sec > callback->when.tv_sec ||
1081                          (now.tv_sec == callback->when.tv_sec &&
1082                           now.tv_usec >= callback->when.tv_usec));
1083
1084                 if (call_it)
1085                 {
1086                         int retval = target_call_timer_callback(callback, &now);
1087                         if (retval != ERROR_OK)
1088                                 return retval;
1089                 }
1090
1091                 callback = next_callback;
1092         }
1093
1094         return ERROR_OK;
1095 }
1096
1097 int target_call_timer_callbacks(void)
1098 {
1099         return target_call_timer_callbacks_check_time(1);
1100 }
1101
1102 /* invoke periodic callbacks immediately */
1103 int target_call_timer_callbacks_now(void)
1104 {
1105         return target_call_timer_callbacks_check_time(0);
1106 }
1107
1108 int target_alloc_working_area(struct target_s *target, uint32_t size, working_area_t **area)
1109 {
1110         working_area_t *c = target->working_areas;
1111         working_area_t *new_wa = NULL;
1112
1113         /* Reevaluate working area address based on MMU state*/
1114         if (target->working_areas == NULL)
1115         {
1116                 int retval;
1117                 int enabled;
1118
1119                 retval = target->type->mmu(target, &enabled);
1120                 if (retval != ERROR_OK)
1121                 {
1122                         return retval;
1123                 }
1124
1125                 if (!enabled) {
1126                         if (target->working_area_phys_spec) {
1127                                 LOG_DEBUG("MMU disabled, using physical "
1128                                         "address for working memory 0x%08x",
1129                                         (unsigned)target->working_area_phys);
1130                                 target->working_area = target->working_area_phys;
1131                         } else {
1132                                 LOG_ERROR("No working memory available. "
1133                                         "Specify -work-area-phys to target.");
1134                                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1135                         }
1136                 } else {
1137                         if (target->working_area_virt_spec) {
1138                                 LOG_DEBUG("MMU enabled, using virtual "
1139                                         "address for working memory 0x%08x",
1140                                         (unsigned)target->working_area_virt);
1141                                 target->working_area = target->working_area_virt;
1142                         } else {
1143                                 LOG_ERROR("No working memory available. "
1144                                         "Specify -work-area-virt to target.");
1145                                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1146                         }
1147                 }
1148         }
1149
1150         /* only allocate multiples of 4 byte */
1151         if (size % 4)
1152         {
1153                 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1154                 size = (size + 3) & (~3);
1155         }
1156
1157         /* see if there's already a matching working area */
1158         while (c)
1159         {
1160                 if ((c->free) && (c->size == size))
1161                 {
1162                         new_wa = c;
1163                         break;
1164                 }
1165                 c = c->next;
1166         }
1167
1168         /* if not, allocate a new one */
1169         if (!new_wa)
1170         {
1171                 working_area_t **p = &target->working_areas;
1172                 uint32_t first_free = target->working_area;
1173                 uint32_t free_size = target->working_area_size;
1174
1175                 c = target->working_areas;
1176                 while (c)
1177                 {
1178                         first_free += c->size;
1179                         free_size -= c->size;
1180                         p = &c->next;
1181                         c = c->next;
1182                 }
1183
1184                 if (free_size < size)
1185                 {
1186                         LOG_WARNING("not enough working area available(requested %u, free %u)",
1187                                     (unsigned)(size), (unsigned)(free_size));
1188                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1189                 }
1190
1191                 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1192
1193                 new_wa = malloc(sizeof(working_area_t));
1194                 new_wa->next = NULL;
1195                 new_wa->size = size;
1196                 new_wa->address = first_free;
1197
1198                 if (target->backup_working_area)
1199                 {
1200                         int retval;
1201                         new_wa->backup = malloc(new_wa->size);
1202                         if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1203                         {
1204                                 free(new_wa->backup);
1205                                 free(new_wa);
1206                                 return retval;
1207                         }
1208                 }
1209                 else
1210                 {
1211                         new_wa->backup = NULL;
1212                 }
1213
1214                 /* put new entry in list */
1215                 *p = new_wa;
1216         }
1217
1218         /* mark as used, and return the new (reused) area */
1219         new_wa->free = 0;
1220         *area = new_wa;
1221
1222         /* user pointer */
1223         new_wa->user = area;
1224
1225         return ERROR_OK;
1226 }
1227
1228 int target_free_working_area_restore(struct target_s *target, working_area_t *area, int restore)
1229 {
1230         if (area->free)
1231                 return ERROR_OK;
1232
1233         if (restore && target->backup_working_area)
1234         {
1235                 int retval;
1236                 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1237                         return retval;
1238         }
1239
1240         area->free = 1;
1241
1242         /* mark user pointer invalid */
1243         *area->user = NULL;
1244         area->user = NULL;
1245
1246         return ERROR_OK;
1247 }
1248
1249 int target_free_working_area(struct target_s *target, working_area_t *area)
1250 {
1251         return target_free_working_area_restore(target, area, 1);
1252 }
1253
1254 /* free resources and restore memory, if restoring memory fails,
1255  * free up resources anyway
1256  */
1257 void target_free_all_working_areas_restore(struct target_s *target, int restore)
1258 {
1259         working_area_t *c = target->working_areas;
1260
1261         while (c)
1262         {
1263                 working_area_t *next = c->next;
1264                 target_free_working_area_restore(target, c, restore);
1265
1266                 if (c->backup)
1267                         free(c->backup);
1268
1269                 free(c);
1270
1271                 c = next;
1272         }
1273
1274         target->working_areas = NULL;
1275 }
1276
1277 void target_free_all_working_areas(struct target_s *target)
1278 {
1279         target_free_all_working_areas_restore(target, 1);
1280 }
1281
1282 int target_register_commands(struct command_context_s *cmd_ctx)
1283 {
1284
1285         register_command(cmd_ctx, NULL, "targets", handle_targets_command, COMMAND_EXEC, "change the current command line target (one parameter) or lists targets (with no parameter)");
1286
1287
1288
1289
1290         register_jim(cmd_ctx, "target", jim_target, "configure target");
1291
1292         return ERROR_OK;
1293 }
1294
1295 int target_arch_state(struct target_s *target)
1296 {
1297         int retval;
1298         if (target == NULL)
1299         {
1300                 LOG_USER("No target has been configured");
1301                 return ERROR_OK;
1302         }
1303
1304         LOG_USER("target state: %s", target_state_name( target ));
1305
1306         if (target->state != TARGET_HALTED)
1307                 return ERROR_OK;
1308
1309         retval = target->type->arch_state(target);
1310         return retval;
1311 }
1312
1313 /* Single aligned words are guaranteed to use 16 or 32 bit access
1314  * mode respectively, otherwise data is handled as quickly as
1315  * possible
1316  */
1317 int target_write_buffer(struct target_s *target, uint32_t address, uint32_t size, uint8_t *buffer)
1318 {
1319         int retval;
1320         LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1321                   (int)size, (unsigned)address);
1322
1323         if (!target_was_examined(target))
1324         {
1325                 LOG_ERROR("Target not examined yet");
1326                 return ERROR_FAIL;
1327         }
1328
1329         if (size == 0) {
1330                 return ERROR_OK;
1331         }
1332
1333         if ((address + size - 1) < address)
1334         {
1335                 /* GDB can request this when e.g. PC is 0xfffffffc*/
1336                 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1337                                   (unsigned)address,
1338                                   (unsigned)size);
1339                 return ERROR_FAIL;
1340         }
1341
1342         if (((address % 2) == 0) && (size == 2))
1343         {
1344                 return target_write_memory(target, address, 2, 1, buffer);
1345         }
1346
1347         /* handle unaligned head bytes */
1348         if (address % 4)
1349         {
1350                 uint32_t unaligned = 4 - (address % 4);
1351
1352                 if (unaligned > size)
1353                         unaligned = size;
1354
1355                 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1356                         return retval;
1357
1358                 buffer += unaligned;
1359                 address += unaligned;
1360                 size -= unaligned;
1361         }
1362
1363         /* handle aligned words */
1364         if (size >= 4)
1365         {
1366                 int aligned = size - (size % 4);
1367
1368                 /* use bulk writes above a certain limit. This may have to be changed */
1369                 if (aligned > 128)
1370                 {
1371                         if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1372                                 return retval;
1373                 }
1374                 else
1375                 {
1376                         if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1377                                 return retval;
1378                 }
1379
1380                 buffer += aligned;
1381                 address += aligned;
1382                 size -= aligned;
1383         }
1384
1385         /* handle tail writes of less than 4 bytes */
1386         if (size > 0)
1387         {
1388                 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1389                         return retval;
1390         }
1391
1392         return ERROR_OK;
1393 }
1394
1395 /* Single aligned words are guaranteed to use 16 or 32 bit access
1396  * mode respectively, otherwise data is handled as quickly as
1397  * possible
1398  */
1399 int target_read_buffer(struct target_s *target, uint32_t address, uint32_t size, uint8_t *buffer)
1400 {
1401         int retval;
1402         LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1403                           (int)size, (unsigned)address);
1404
1405         if (!target_was_examined(target))
1406         {
1407                 LOG_ERROR("Target not examined yet");
1408                 return ERROR_FAIL;
1409         }
1410
1411         if (size == 0) {
1412                 return ERROR_OK;
1413         }
1414
1415         if ((address + size - 1) < address)
1416         {
1417                 /* GDB can request this when e.g. PC is 0xfffffffc*/
1418                 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1419                                   address,
1420                                   size);
1421                 return ERROR_FAIL;
1422         }
1423
1424         if (((address % 2) == 0) && (size == 2))
1425         {
1426                 return target_read_memory(target, address, 2, 1, buffer);
1427         }
1428
1429         /* handle unaligned head bytes */
1430         if (address % 4)
1431         {
1432                 uint32_t unaligned = 4 - (address % 4);
1433
1434                 if (unaligned > size)
1435                         unaligned = size;
1436
1437                 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1438                         return retval;
1439
1440                 buffer += unaligned;
1441                 address += unaligned;
1442                 size -= unaligned;
1443         }
1444
1445         /* handle aligned words */
1446         if (size >= 4)
1447         {
1448                 int aligned = size - (size % 4);
1449
1450                 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1451                         return retval;
1452
1453                 buffer += aligned;
1454                 address += aligned;
1455                 size -= aligned;
1456         }
1457
1458         /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1459         if(size >=2)
1460         {
1461                 int aligned = size - (size%2);
1462                 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1463                 if (retval != ERROR_OK)
1464                         return retval;
1465
1466                 buffer += aligned;
1467                 address += aligned;
1468                 size -= aligned;
1469         }
1470         /* handle tail writes of less than 4 bytes */
1471         if (size > 0)
1472         {
1473                 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1474                         return retval;
1475         }
1476
1477         return ERROR_OK;
1478 }
1479
1480 int target_checksum_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t* crc)
1481 {
1482         uint8_t *buffer;
1483         int retval;
1484         uint32_t i;
1485         uint32_t checksum = 0;
1486         if (!target_was_examined(target))
1487         {
1488                 LOG_ERROR("Target not examined yet");
1489                 return ERROR_FAIL;
1490         }
1491
1492         if ((retval = target->type->checksum_memory(target, address,
1493                 size, &checksum)) != ERROR_OK)
1494         {
1495                 buffer = malloc(size);
1496                 if (buffer == NULL)
1497                 {
1498                         LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1499                         return ERROR_INVALID_ARGUMENTS;
1500                 }
1501                 retval = target_read_buffer(target, address, size, buffer);
1502                 if (retval != ERROR_OK)
1503                 {
1504                         free(buffer);
1505                         return retval;
1506                 }
1507
1508                 /* convert to target endianess */
1509                 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1510                 {
1511                         uint32_t target_data;
1512                         target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1513                         target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1514                 }
1515
1516                 retval = image_calculate_checksum(buffer, size, &checksum);
1517                 free(buffer);
1518         }
1519
1520         *crc = checksum;
1521
1522         return retval;
1523 }
1524
1525 int target_blank_check_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t* blank)
1526 {
1527         int retval;
1528         if (!target_was_examined(target))
1529         {
1530                 LOG_ERROR("Target not examined yet");
1531                 return ERROR_FAIL;
1532         }
1533
1534         if (target->type->blank_check_memory == 0)
1535                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1536
1537         retval = target->type->blank_check_memory(target, address, size, blank);
1538
1539         return retval;
1540 }
1541
1542 int target_read_u32(struct target_s *target, uint32_t address, uint32_t *value)
1543 {
1544         uint8_t value_buf[4];
1545         if (!target_was_examined(target))
1546         {
1547                 LOG_ERROR("Target not examined yet");
1548                 return ERROR_FAIL;
1549         }
1550
1551         int retval = target_read_memory(target, address, 4, 1, value_buf);
1552
1553         if (retval == ERROR_OK)
1554         {
1555                 *value = target_buffer_get_u32(target, value_buf);
1556                 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1557                                   address,
1558                                   *value);
1559         }
1560         else
1561         {
1562                 *value = 0x0;
1563                 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1564                                   address);
1565         }
1566
1567         return retval;
1568 }
1569
1570 int target_read_u16(struct target_s *target, uint32_t address, uint16_t *value)
1571 {
1572         uint8_t value_buf[2];
1573         if (!target_was_examined(target))
1574         {
1575                 LOG_ERROR("Target not examined yet");
1576                 return ERROR_FAIL;
1577         }
1578
1579         int retval = target_read_memory(target, address, 2, 1, value_buf);
1580
1581         if (retval == ERROR_OK)
1582         {
1583                 *value = target_buffer_get_u16(target, value_buf);
1584                 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1585                                   address,
1586                                   *value);
1587         }
1588         else
1589         {
1590                 *value = 0x0;
1591                 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1592                                   address);
1593         }
1594
1595         return retval;
1596 }
1597
1598 int target_read_u8(struct target_s *target, uint32_t address, uint8_t *value)
1599 {
1600         int retval = target_read_memory(target, address, 1, 1, value);
1601         if (!target_was_examined(target))
1602         {
1603                 LOG_ERROR("Target not examined yet");
1604                 return ERROR_FAIL;
1605         }
1606
1607         if (retval == ERROR_OK)
1608         {
1609                 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1610                                   address,
1611                                   *value);
1612         }
1613         else
1614         {
1615                 *value = 0x0;
1616                 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1617                                   address);
1618         }
1619
1620         return retval;
1621 }
1622
1623 int target_write_u32(struct target_s *target, uint32_t address, uint32_t value)
1624 {
1625         int retval;
1626         uint8_t value_buf[4];
1627         if (!target_was_examined(target))
1628         {
1629                 LOG_ERROR("Target not examined yet");
1630                 return ERROR_FAIL;
1631         }
1632
1633         LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1634                           address,
1635                           value);
1636
1637         target_buffer_set_u32(target, value_buf, value);
1638         if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1639         {
1640                 LOG_DEBUG("failed: %i", retval);
1641         }
1642
1643         return retval;
1644 }
1645
1646 int target_write_u16(struct target_s *target, uint32_t address, uint16_t value)
1647 {
1648         int retval;
1649         uint8_t value_buf[2];
1650         if (!target_was_examined(target))
1651         {
1652                 LOG_ERROR("Target not examined yet");
1653                 return ERROR_FAIL;
1654         }
1655
1656         LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1657                           address,
1658                           value);
1659
1660         target_buffer_set_u16(target, value_buf, value);
1661         if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1662         {
1663                 LOG_DEBUG("failed: %i", retval);
1664         }
1665
1666         return retval;
1667 }
1668
1669 int target_write_u8(struct target_s *target, uint32_t address, uint8_t value)
1670 {
1671         int retval;
1672         if (!target_was_examined(target))
1673         {
1674                 LOG_ERROR("Target not examined yet");
1675                 return ERROR_FAIL;
1676         }
1677
1678         LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1679                           address, value);
1680
1681         if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1682         {
1683                 LOG_DEBUG("failed: %i", retval);
1684         }
1685
1686         return retval;
1687 }
1688
1689 int target_register_user_commands(struct command_context_s *cmd_ctx)
1690 {
1691         int retval = ERROR_OK;
1692
1693
1694         /* script procedures */
1695         register_command(cmd_ctx, NULL, "profile", handle_profile_command, COMMAND_EXEC, "profiling samples the CPU PC");
1696         register_jim(cmd_ctx, "ocd_mem2array", jim_mem2array, "read memory and return as a TCL array for script processing <ARRAYNAME> <WIDTH = 32/16/8> <ADDRESS> <COUNT>");
1697         register_jim(cmd_ctx, "ocd_array2mem", jim_array2mem, "convert a TCL array to memory locations and write the values  <ARRAYNAME> <WIDTH = 32/16/8> <ADDRESS> <COUNT>");
1698
1699         register_command(cmd_ctx, NULL, "fast_load_image", handle_fast_load_image_command, COMMAND_ANY,
1700                         "same args as load_image, image stored in memory - mainly for profiling purposes");
1701
1702         register_command(cmd_ctx, NULL, "fast_load", handle_fast_load_command, COMMAND_ANY,
1703                         "loads active fast load image to current target - mainly for profiling purposes");
1704
1705
1706         register_command(cmd_ctx, NULL, "virt2phys", handle_virt2phys_command, COMMAND_ANY, "translate a virtual address into a physical address");
1707         register_command(cmd_ctx,  NULL, "reg", handle_reg_command, COMMAND_EXEC, "display or set a register");
1708         register_command(cmd_ctx,  NULL, "poll", handle_poll_command, COMMAND_EXEC, "poll target state");
1709         register_command(cmd_ctx,  NULL, "wait_halt", handle_wait_halt_command, COMMAND_EXEC, "wait for target halt [time (s)]");
1710         register_command(cmd_ctx,  NULL, "halt", handle_halt_command, COMMAND_EXEC, "halt target");
1711         register_command(cmd_ctx,  NULL, "resume", handle_resume_command, COMMAND_EXEC, "resume target [addr]");
1712         register_command(cmd_ctx,  NULL, "step", handle_step_command, COMMAND_EXEC, "step one instruction from current PC or [addr]");
1713         register_command(cmd_ctx,  NULL, "reset", handle_reset_command, COMMAND_EXEC, "reset target [run | halt | init] - default is run");
1714         register_command(cmd_ctx,  NULL, "soft_reset_halt", handle_soft_reset_halt_command, COMMAND_EXEC, "halt the target and do a soft reset");
1715
1716         register_command(cmd_ctx,  NULL, "mdw", handle_md_command, COMMAND_EXEC, "display memory words [phys] <addr> [count]");
1717         register_command(cmd_ctx,  NULL, "mdh", handle_md_command, COMMAND_EXEC, "display memory half-words [phys] <addr> [count]");
1718         register_command(cmd_ctx,  NULL, "mdb", handle_md_command, COMMAND_EXEC, "display memory bytes [phys] <addr> [count]");
1719
1720         register_command(cmd_ctx,  NULL, "mww", handle_mw_command, COMMAND_EXEC, "write memory word [phys]  <addr> <value> [count]");
1721         register_command(cmd_ctx,  NULL, "mwh", handle_mw_command, COMMAND_EXEC, "write memory half-word [phys]  <addr> <value> [count]");
1722         register_command(cmd_ctx,  NULL, "mwb", handle_mw_command, COMMAND_EXEC, "write memory byte [phys] <addr> <value> [count]");
1723
1724         register_command(cmd_ctx,  NULL, "bp",
1725                         handle_bp_command, COMMAND_EXEC,
1726                         "list or set breakpoint [<address> <length> [hw]]");
1727         register_command(cmd_ctx,  NULL, "rbp",
1728                         handle_rbp_command, COMMAND_EXEC,
1729                         "remove breakpoint <address>");
1730         register_command(cmd_ctx,  NULL, "wp",
1731                         handle_wp_command, COMMAND_EXEC,
1732                         "list or set watchpoint "
1733                                 "[<address> <length> <r/w/a> [value] [mask]]");
1734         register_command(cmd_ctx,  NULL, "rwp",
1735                         handle_rwp_command, COMMAND_EXEC,
1736                         "remove watchpoint <address>");
1737
1738         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]");
1739         register_command(cmd_ctx,  NULL, "dump_image", handle_dump_image_command, COMMAND_EXEC, "dump_image <file> <address> <size>");
1740         register_command(cmd_ctx,  NULL, "verify_image", handle_verify_image_command, COMMAND_EXEC, "verify_image <file> [offset] [type]");
1741         register_command(cmd_ctx,  NULL, "test_image", handle_test_image_command, COMMAND_EXEC, "test_image <file> [offset] [type]");
1742
1743         if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
1744                 return retval;
1745         if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
1746                 return retval;
1747
1748         return retval;
1749 }
1750
1751 static int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1752 {
1753         target_t *target = all_targets;
1754
1755         if (argc == 1)
1756         {
1757                 target = get_target(args[0]);
1758                 if (target == NULL) {
1759                         command_print(cmd_ctx,"Target: %s is unknown, try one of:\n", args[0]);
1760                         goto DumpTargets;
1761                 }
1762                 if (!target->tap->enabled) {
1763                         command_print(cmd_ctx,"Target: TAP %s is disabled, "
1764                                         "can't be the current target\n",
1765                                         target->tap->dotted_name);
1766                         return ERROR_FAIL;
1767                 }
1768
1769                 cmd_ctx->current_target = target->target_number;
1770                 return ERROR_OK;
1771         }
1772 DumpTargets:
1773
1774         target = all_targets;
1775         command_print(cmd_ctx, "    TargetName         Type       Endian TapName            State       ");
1776         command_print(cmd_ctx, "--  ------------------ ---------- ------ ------------------ ------------");
1777         while (target)
1778         {
1779                 const char *state;
1780                 char marker = ' ';
1781
1782                 if (target->tap->enabled)
1783                         state = target_state_name( target );
1784                 else
1785                         state = "tap-disabled";
1786
1787                 if (cmd_ctx->current_target == target->target_number)
1788                         marker = '*';
1789
1790                 /* keep columns lined up to match the headers above */
1791                 command_print(cmd_ctx, "%2d%c %-18s %-10s %-6s %-18s %s",
1792                                           target->target_number,
1793                                           marker,
1794                                           target->cmd_name,
1795                                           target_get_name(target),
1796                                           Jim_Nvp_value2name_simple(nvp_target_endian,
1797                                                                 target->endianness)->name,
1798                                           target->tap->dotted_name,
1799                                           state);
1800                 target = target->next;
1801         }
1802
1803         return ERROR_OK;
1804 }
1805
1806 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1807
1808 static int powerDropout;
1809 static int srstAsserted;
1810
1811 static int runPowerRestore;
1812 static int runPowerDropout;
1813 static int runSrstAsserted;
1814 static int runSrstDeasserted;
1815
1816 static int sense_handler(void)
1817 {
1818         static int prevSrstAsserted = 0;
1819         static int prevPowerdropout = 0;
1820
1821         int retval;
1822         if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1823                 return retval;
1824
1825         int powerRestored;
1826         powerRestored = prevPowerdropout && !powerDropout;
1827         if (powerRestored)
1828         {
1829                 runPowerRestore = 1;
1830         }
1831
1832         long long current = timeval_ms();
1833         static long long lastPower = 0;
1834         int waitMore = lastPower + 2000 > current;
1835         if (powerDropout && !waitMore)
1836         {
1837                 runPowerDropout = 1;
1838                 lastPower = current;
1839         }
1840
1841         if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1842                 return retval;
1843
1844         int srstDeasserted;
1845         srstDeasserted = prevSrstAsserted && !srstAsserted;
1846
1847         static long long lastSrst = 0;
1848         waitMore = lastSrst + 2000 > current;
1849         if (srstDeasserted && !waitMore)
1850         {
1851                 runSrstDeasserted = 1;
1852                 lastSrst = current;
1853         }
1854
1855         if (!prevSrstAsserted && srstAsserted)
1856         {
1857                 runSrstAsserted = 1;
1858         }
1859
1860         prevSrstAsserted = srstAsserted;
1861         prevPowerdropout = powerDropout;
1862
1863         if (srstDeasserted || powerRestored)
1864         {
1865                 /* Other than logging the event we can't do anything here.
1866                  * Issuing a reset is a particularly bad idea as we might
1867                  * be inside a reset already.
1868                  */
1869         }
1870
1871         return ERROR_OK;
1872 }
1873
1874 static void target_call_event_callbacks_all(enum target_event e) {
1875         target_t *target;
1876         target = all_targets;
1877         while (target) {
1878                 target_call_event_callbacks(target, e);
1879                 target = target->next;
1880         }
1881 }
1882
1883 /* process target state changes */
1884 int handle_target(void *priv)
1885 {
1886         int retval = ERROR_OK;
1887
1888         /* we do not want to recurse here... */
1889         static int recursive = 0;
1890         if (! recursive)
1891         {
1892                 recursive = 1;
1893                 sense_handler();
1894                 /* danger! running these procedures can trigger srst assertions and power dropouts.
1895                  * We need to avoid an infinite loop/recursion here and we do that by
1896                  * clearing the flags after running these events.
1897                  */
1898                 int did_something = 0;
1899                 if (runSrstAsserted)
1900                 {
1901                         target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1902                         Jim_Eval(interp, "srst_asserted");
1903                         did_something = 1;
1904                 }
1905                 if (runSrstDeasserted)
1906                 {
1907                         Jim_Eval(interp, "srst_deasserted");
1908                         did_something = 1;
1909                 }
1910                 if (runPowerDropout)
1911                 {
1912                         target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1913                         Jim_Eval(interp, "power_dropout");
1914                         did_something = 1;
1915                 }
1916                 if (runPowerRestore)
1917                 {
1918                         Jim_Eval(interp, "power_restore");
1919                         did_something = 1;
1920                 }
1921
1922                 if (did_something)
1923                 {
1924                         /* clear detect flags */
1925                         sense_handler();
1926                 }
1927
1928                 /* clear action flags */
1929
1930                 runSrstAsserted = 0;
1931                 runSrstDeasserted = 0;
1932                 runPowerRestore = 0;
1933                 runPowerDropout = 0;
1934
1935                 recursive = 0;
1936         }
1937
1938         /* Poll targets for state changes unless that's globally disabled.
1939          * Skip targets that are currently disabled.
1940          */
1941         for (target_t *target = all_targets;
1942                         is_jtag_poll_safe() && target;
1943                         target = target->next)
1944         {
1945                 if (!target->tap->enabled)
1946                         continue;
1947
1948                 /* only poll target if we've got power and srst isn't asserted */
1949                 if (!powerDropout && !srstAsserted)
1950                 {
1951                         /* polling may fail silently until the target has been examined */
1952                         if ((retval = target_poll(target)) != ERROR_OK)
1953                         {
1954                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1955                                 return retval;
1956                         }
1957                 }
1958         }
1959
1960         return retval;
1961 }
1962
1963 static int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1964 {
1965         target_t *target;
1966         reg_t *reg = NULL;
1967         int count = 0;
1968         char *value;
1969
1970         LOG_DEBUG("-");
1971
1972         target = get_current_target(cmd_ctx);
1973
1974         /* list all available registers for the current target */
1975         if (argc == 0)
1976         {
1977                 reg_cache_t *cache = target->reg_cache;
1978
1979                 count = 0;
1980                 while (cache)
1981                 {
1982                         int i;
1983
1984                         command_print(cmd_ctx, "===== %s", cache->name);
1985
1986                         for (i = 0, reg = cache->reg_list;
1987                                         i < cache->num_regs;
1988                                         i++, reg++, count++)
1989                         {
1990                                 /* only print cached values if they are valid */
1991                                 if (reg->valid) {
1992                                         value = buf_to_str(reg->value,
1993                                                         reg->size, 16);
1994                                         command_print(cmd_ctx,
1995                                                         "(%i) %s (/%" PRIu32 "): 0x%s%s",
1996                                                         count, reg->name,
1997                                                         reg->size, value,
1998                                                         reg->dirty
1999                                                                 ? " (dirty)"
2000                                                                 : "");
2001                                         free(value);
2002                                 } else {
2003                                         command_print(cmd_ctx, "(%i) %s (/%" PRIu32 ")",
2004                                                           count, reg->name,
2005                                                           reg->size) ;
2006                                 }
2007                         }
2008                         cache = cache->next;
2009                 }
2010
2011                 return ERROR_OK;
2012         }
2013
2014         /* access a single register by its ordinal number */
2015         if ((args[0][0] >= '0') && (args[0][0] <= '9'))
2016         {
2017                 unsigned num;
2018                 COMMAND_PARSE_NUMBER(uint, args[0], num);
2019
2020                 reg_cache_t *cache = target->reg_cache;
2021                 count = 0;
2022                 while (cache)
2023                 {
2024                         int i;
2025                         for (i = 0; i < cache->num_regs; i++)
2026                         {
2027                                 if (count++ == (int)num)
2028                                 {
2029                                         reg = &cache->reg_list[i];
2030                                         break;
2031                                 }
2032                         }
2033                         if (reg)
2034                                 break;
2035                         cache = cache->next;
2036                 }
2037
2038                 if (!reg)
2039                 {
2040                         command_print(cmd_ctx, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
2041                         return ERROR_OK;
2042                 }
2043         } else /* access a single register by its name */
2044         {
2045                 reg = register_get_by_name(target->reg_cache, args[0], 1);
2046
2047                 if (!reg)
2048                 {
2049                         command_print(cmd_ctx, "register %s not found in current target", args[0]);
2050                         return ERROR_OK;
2051                 }
2052         }
2053
2054         /* display a register */
2055         if ((argc == 1) || ((argc == 2) && !((args[1][0] >= '0') && (args[1][0] <= '9'))))
2056         {
2057                 if ((argc == 2) && (strcmp(args[1], "force") == 0))
2058                         reg->valid = 0;
2059
2060                 if (reg->valid == 0)
2061                 {
2062                         reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
2063                         arch_type->get(reg);
2064                 }
2065                 value = buf_to_str(reg->value, reg->size, 16);
2066                 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2067                 free(value);
2068                 return ERROR_OK;
2069         }
2070
2071         /* set register value */
2072         if (argc == 2)
2073         {
2074                 uint8_t *buf = malloc(CEIL(reg->size, 8));
2075                 str_to_buf(args[1], strlen(args[1]), buf, reg->size, 0);
2076
2077                 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
2078                 arch_type->set(reg, buf);
2079
2080                 value = buf_to_str(reg->value, reg->size, 16);
2081                 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2082                 free(value);
2083
2084                 free(buf);
2085
2086                 return ERROR_OK;
2087         }
2088
2089         command_print(cmd_ctx, "usage: reg <#|name> [value]");
2090
2091         return ERROR_OK;
2092 }
2093
2094 static int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2095 {
2096         int retval = ERROR_OK;
2097         target_t *target = get_current_target(cmd_ctx);
2098
2099         if (argc == 0)
2100         {
2101                 command_print(cmd_ctx, "background polling: %s",
2102                                 jtag_poll_get_enabled() ? "on" : "off");
2103                 command_print(cmd_ctx, "TAP: %s (%s)",
2104                                 target->tap->dotted_name,
2105                                 target->tap->enabled ? "enabled" : "disabled");
2106                 if (!target->tap->enabled)
2107                         return ERROR_OK;
2108                 if ((retval = target_poll(target)) != ERROR_OK)
2109                         return retval;
2110                 if ((retval = target_arch_state(target)) != ERROR_OK)
2111                         return retval;
2112
2113         }
2114         else if (argc == 1)
2115         {
2116                 if (strcmp(args[0], "on") == 0)
2117                 {
2118                         jtag_poll_set_enabled(true);
2119                 }
2120                 else if (strcmp(args[0], "off") == 0)
2121                 {
2122                         jtag_poll_set_enabled(false);
2123                 }
2124                 else
2125                 {
2126                         command_print(cmd_ctx, "arg is \"on\" or \"off\"");
2127                 }
2128         } else
2129         {
2130                 return ERROR_COMMAND_SYNTAX_ERROR;
2131         }
2132
2133         return retval;
2134 }
2135
2136 static int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2137 {
2138         if (argc > 1)
2139                 return ERROR_COMMAND_SYNTAX_ERROR;
2140
2141         unsigned ms = 5000;
2142         if (1 == argc)
2143         {
2144                 int retval = parse_uint(args[0], &ms);
2145                 if (ERROR_OK != retval)
2146                 {
2147                         command_print(cmd_ctx, "usage: %s [seconds]", cmd);
2148                         return ERROR_COMMAND_SYNTAX_ERROR;
2149                 }
2150                 // convert seconds (given) to milliseconds (needed)
2151                 ms *= 1000;
2152         }
2153
2154         target_t *target = get_current_target(cmd_ctx);
2155         return target_wait_state(target, TARGET_HALTED, ms);
2156 }
2157
2158 /* wait for target state to change. The trick here is to have a low
2159  * latency for short waits and not to suck up all the CPU time
2160  * on longer waits.
2161  *
2162  * After 500ms, keep_alive() is invoked
2163  */
2164 int target_wait_state(target_t *target, enum target_state state, int ms)
2165 {
2166         int retval;
2167         long long then = 0, cur;
2168         int once = 1;
2169
2170         for (;;)
2171         {
2172                 if ((retval = target_poll(target)) != ERROR_OK)
2173                         return retval;
2174                 if (target->state == state)
2175                 {
2176                         break;
2177                 }
2178                 cur = timeval_ms();
2179                 if (once)
2180                 {
2181                         once = 0;
2182                         then = timeval_ms();
2183                         LOG_DEBUG("waiting for target %s...",
2184                                 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2185                 }
2186
2187                 if (cur-then > 500)
2188                 {
2189                         keep_alive();
2190                 }
2191
2192                 if ((cur-then) > ms)
2193                 {
2194                         LOG_ERROR("timed out while waiting for target %s",
2195                                 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2196                         return ERROR_FAIL;
2197                 }
2198         }
2199
2200         return ERROR_OK;
2201 }
2202
2203 static int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2204 {
2205         LOG_DEBUG("-");
2206
2207         target_t *target = get_current_target(cmd_ctx);
2208         int retval = target_halt(target);
2209         if (ERROR_OK != retval)
2210                 return retval;
2211
2212         if (argc == 1)
2213         {
2214                 unsigned wait;
2215                 retval = parse_uint(args[0], &wait);
2216                 if (ERROR_OK != retval)
2217                         return ERROR_COMMAND_SYNTAX_ERROR;
2218                 if (!wait)
2219                         return ERROR_OK;
2220         }
2221
2222         return handle_wait_halt_command(cmd_ctx, cmd, args, argc);
2223 }
2224
2225 static int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2226 {
2227         target_t *target = get_current_target(cmd_ctx);
2228
2229         LOG_USER("requesting target halt and executing a soft reset");
2230
2231         target->type->soft_reset_halt(target);
2232
2233         return ERROR_OK;
2234 }
2235
2236 static int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2237 {
2238         if (argc > 1)
2239                 return ERROR_COMMAND_SYNTAX_ERROR;
2240
2241         enum target_reset_mode reset_mode = RESET_RUN;
2242         if (argc == 1)
2243         {
2244                 const Jim_Nvp *n;
2245                 n = Jim_Nvp_name2value_simple(nvp_reset_modes, args[0]);
2246                 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2247                         return ERROR_COMMAND_SYNTAX_ERROR;
2248                 }
2249                 reset_mode = n->value;
2250         }
2251
2252         /* reset *all* targets */
2253         return target_process_reset(cmd_ctx, reset_mode);
2254 }
2255
2256
2257 static int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2258 {
2259         int current = 1;
2260         if (argc > 1)
2261                 return ERROR_COMMAND_SYNTAX_ERROR;
2262
2263         target_t *target = get_current_target(cmd_ctx);
2264         target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2265
2266         /* with no args, resume from current pc, addr = 0,
2267          * with one arguments, addr = args[0],
2268          * handle breakpoints, not debugging */
2269         uint32_t addr = 0;
2270         if (argc == 1)
2271         {
2272                 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2273                 current = 0;
2274         }
2275
2276         return target_resume(target, current, addr, 1, 0);
2277 }
2278
2279 static int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2280 {
2281         if (argc > 1)
2282                 return ERROR_COMMAND_SYNTAX_ERROR;
2283
2284         LOG_DEBUG("-");
2285
2286         /* with no args, step from current pc, addr = 0,
2287          * with one argument addr = args[0],
2288          * handle breakpoints, debugging */
2289         uint32_t addr = 0;
2290         int current_pc = 1;
2291         if (argc == 1)
2292         {
2293                 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2294                 current_pc = 0;
2295         }
2296
2297         target_t *target = get_current_target(cmd_ctx);
2298
2299         return target->type->step(target, current_pc, addr, 1);
2300 }
2301
2302 static void handle_md_output(struct command_context_s *cmd_ctx,
2303                 struct target_s *target, uint32_t address, unsigned size,
2304                 unsigned count, const uint8_t *buffer)
2305 {
2306         const unsigned line_bytecnt = 32;
2307         unsigned line_modulo = line_bytecnt / size;
2308
2309         char output[line_bytecnt * 4 + 1];
2310         unsigned output_len = 0;
2311
2312         const char *value_fmt;
2313         switch (size) {
2314         case 4: value_fmt = "%8.8x "; break;
2315         case 2: value_fmt = "%4.2x "; break;
2316         case 1: value_fmt = "%2.2x "; break;
2317         default:
2318                 LOG_ERROR("invalid memory read size: %u", size);
2319                 exit(-1);
2320         }
2321
2322         for (unsigned i = 0; i < count; i++)
2323         {
2324                 if (i % line_modulo == 0)
2325                 {
2326                         output_len += snprintf(output + output_len,
2327                                         sizeof(output) - output_len,
2328                                         "0x%8.8x: ",
2329                                         (unsigned)(address + (i*size)));
2330                 }
2331
2332                 uint32_t value = 0;
2333                 const uint8_t *value_ptr = buffer + i * size;
2334                 switch (size) {
2335                 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2336                 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2337                 case 1: value = *value_ptr;
2338                 }
2339                 output_len += snprintf(output + output_len,
2340                                 sizeof(output) - output_len,
2341                                 value_fmt, value);
2342
2343                 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2344                 {
2345                         command_print(cmd_ctx, "%s", output);
2346                         output_len = 0;
2347                 }
2348         }
2349 }
2350
2351 static int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2352 {
2353         if (argc < 1)
2354                 return ERROR_COMMAND_SYNTAX_ERROR;
2355
2356         unsigned size = 0;
2357         switch (cmd[2]) {
2358         case 'w': size = 4; break;
2359         case 'h': size = 2; break;
2360         case 'b': size = 1; break;
2361         default: return ERROR_COMMAND_SYNTAX_ERROR;
2362         }
2363
2364         bool physical=strcmp(args[0], "phys")==0;
2365         int (*fn)(struct target_s *target,
2366                         uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2367         if (physical)
2368         {
2369                 argc--;
2370                 args++;
2371                 fn=target_read_phys_memory;
2372         } else
2373         {
2374                 fn=target_read_memory;
2375         }
2376         if ((argc < 1) || (argc > 2))
2377         {
2378                 return ERROR_COMMAND_SYNTAX_ERROR;
2379         }
2380
2381         uint32_t address;
2382         COMMAND_PARSE_NUMBER(u32, args[0], address);
2383
2384         unsigned count = 1;
2385         if (argc == 2)
2386                 COMMAND_PARSE_NUMBER(uint, args[1], count);
2387
2388         uint8_t *buffer = calloc(count, size);
2389
2390         target_t *target = get_current_target(cmd_ctx);
2391         int retval = fn(target, address, size, count, buffer);
2392         if (ERROR_OK == retval)
2393                 handle_md_output(cmd_ctx, target, address, size, count, buffer);
2394
2395         free(buffer);
2396
2397         return retval;
2398 }
2399
2400 static int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2401 {
2402         if (argc < 2)
2403         {
2404                 return ERROR_COMMAND_SYNTAX_ERROR;
2405         }
2406         bool physical=strcmp(args[0], "phys")==0;
2407         int (*fn)(struct target_s *target,
2408                         uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2409         if (physical)
2410         {
2411                 argc--;
2412                 args++;
2413                 fn=target_write_phys_memory;
2414         } else
2415         {
2416                 fn=target_write_memory;
2417         }
2418         if ((argc < 2) || (argc > 3))
2419                 return ERROR_COMMAND_SYNTAX_ERROR;
2420
2421         uint32_t address;
2422         COMMAND_PARSE_NUMBER(u32, args[0], address);
2423
2424         uint32_t value;
2425         COMMAND_PARSE_NUMBER(u32, args[1], value);
2426
2427         unsigned count = 1;
2428         if (argc == 3)
2429                 COMMAND_PARSE_NUMBER(uint, args[2], count);
2430
2431         target_t *target = get_current_target(cmd_ctx);
2432         unsigned wordsize;
2433         uint8_t value_buf[4];
2434         switch (cmd[2])
2435         {
2436                 case 'w':
2437                         wordsize = 4;
2438                         target_buffer_set_u32(target, value_buf, value);
2439                         break;
2440                 case 'h':
2441                         wordsize = 2;
2442                         target_buffer_set_u16(target, value_buf, value);
2443                         break;
2444                 case 'b':
2445                         wordsize = 1;
2446                         value_buf[0] = value;
2447                         break;
2448                 default:
2449                         return ERROR_COMMAND_SYNTAX_ERROR;
2450         }
2451         for (unsigned i = 0; i < count; i++)
2452         {
2453                 int retval = fn(target,
2454                                 address + i * wordsize, wordsize, 1, value_buf);
2455                 if (ERROR_OK != retval)
2456                         return retval;
2457                 keep_alive();
2458         }
2459
2460         return ERROR_OK;
2461
2462 }
2463
2464 static int parse_load_image_command_args(struct command_context_s *cmd_ctx,
2465                 char **args, int argc, image_t *image,
2466                 uint32_t *min_address, uint32_t *max_address)
2467 {
2468         if (argc < 1 || argc > 5)
2469                 return ERROR_COMMAND_SYNTAX_ERROR;
2470
2471         /* a base address isn't always necessary,
2472          * default to 0x0 (i.e. don't relocate) */
2473         if (argc >= 2)
2474         {
2475                 uint32_t addr;
2476                 COMMAND_PARSE_NUMBER(u32, args[1], addr);
2477                 image->base_address = addr;
2478                 image->base_address_set = 1;
2479         }
2480         else
2481                 image->base_address_set = 0;
2482
2483         image->start_address_set = 0;
2484
2485         if (argc >= 4)
2486         {
2487                 COMMAND_PARSE_NUMBER(u32, args[3], *min_address);
2488         }
2489         if (argc == 5)
2490         {
2491                 COMMAND_PARSE_NUMBER(u32, args[4], *max_address);
2492                 // use size (given) to find max (required)
2493                 *max_address += *min_address;
2494         }
2495
2496         if (*min_address > *max_address)
2497                 return ERROR_COMMAND_SYNTAX_ERROR;
2498
2499         return ERROR_OK;
2500 }
2501
2502 static int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2503 {
2504         uint8_t *buffer;
2505         uint32_t buf_cnt;
2506         uint32_t image_size;
2507         uint32_t min_address = 0;
2508         uint32_t max_address = 0xffffffff;
2509         int i;
2510         image_t image;
2511
2512         int retval = parse_load_image_command_args(cmd_ctx, args, argc,
2513                         &image, &min_address, &max_address);
2514         if (ERROR_OK != retval)
2515                 return retval;
2516
2517         target_t *target = get_current_target(cmd_ctx);
2518
2519         struct duration bench;
2520         duration_start(&bench);
2521
2522         if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
2523         {
2524                 return ERROR_OK;
2525         }
2526
2527         image_size = 0x0;
2528         retval = ERROR_OK;
2529         for (i = 0; i < image.num_sections; i++)
2530         {
2531                 buffer = malloc(image.sections[i].size);
2532                 if (buffer == NULL)
2533                 {
2534                         command_print(cmd_ctx,
2535                                                   "error allocating buffer for section (%d bytes)",
2536                                                   (int)(image.sections[i].size));
2537                         break;
2538                 }
2539
2540                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2541                 {
2542                         free(buffer);
2543                         break;
2544                 }
2545
2546                 uint32_t offset = 0;
2547                 uint32_t length = buf_cnt;
2548
2549                 /* DANGER!!! beware of unsigned comparision here!!! */
2550
2551                 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2552                                 (image.sections[i].base_address < max_address))
2553                 {
2554                         if (image.sections[i].base_address < min_address)
2555                         {
2556                                 /* clip addresses below */
2557                                 offset += min_address-image.sections[i].base_address;
2558                                 length -= offset;
2559                         }
2560
2561                         if (image.sections[i].base_address + buf_cnt > max_address)
2562                         {
2563                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2564                         }
2565
2566                         if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2567                         {
2568                                 free(buffer);
2569                                 break;
2570                         }
2571                         image_size += length;
2572                         command_print(cmd_ctx, "%u bytes written at address 0x%8.8" PRIx32 "",
2573                                                   (unsigned int)length,
2574                                                   image.sections[i].base_address + offset);
2575                 }
2576
2577                 free(buffer);
2578         }
2579
2580         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2581         {
2582                 command_print(cmd_ctx, "downloaded %" PRIu32 " bytes "
2583                                 "in %fs (%0.3f kb/s)", image_size,
2584                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2585         }
2586
2587         image_close(&image);
2588
2589         return retval;
2590
2591 }
2592
2593 static int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2594 {
2595         fileio_t fileio;
2596
2597         uint8_t buffer[560];
2598         int retvaltemp;
2599
2600
2601         target_t *target = get_current_target(cmd_ctx);
2602
2603         if (argc != 3)
2604         {
2605                 command_print(cmd_ctx, "usage: dump_image <filename> <address> <size>");
2606                 return ERROR_OK;
2607         }
2608
2609         uint32_t address;
2610         COMMAND_PARSE_NUMBER(u32, args[1], address);
2611         uint32_t size;
2612         COMMAND_PARSE_NUMBER(u32, args[2], size);
2613
2614         if (fileio_open(&fileio, args[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2615         {
2616                 return ERROR_OK;
2617         }
2618
2619         struct duration bench;
2620         duration_start(&bench);
2621
2622         int retval = ERROR_OK;
2623         while (size > 0)
2624         {
2625                 uint32_t size_written;
2626                 uint32_t this_run_size = (size > 560) ? 560 : size;
2627                 retval = target_read_buffer(target, address, this_run_size, buffer);
2628                 if (retval != ERROR_OK)
2629                 {
2630                         break;
2631                 }
2632
2633                 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2634                 if (retval != ERROR_OK)
2635                 {
2636                         break;
2637                 }
2638
2639                 size -= this_run_size;
2640                 address += this_run_size;
2641         }
2642
2643         if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2644                 return retvaltemp;
2645
2646         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2647         {
2648                 command_print(cmd_ctx,
2649                                 "dumped %lld bytes in %fs (%0.3f kb/s)", fileio.size,
2650                                 duration_elapsed(&bench), duration_kbps(&bench, fileio.size));
2651         }
2652
2653         return retval;
2654 }
2655
2656 static int handle_verify_image_command_internal(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc, int verify)
2657 {
2658         uint8_t *buffer;
2659         uint32_t buf_cnt;
2660         uint32_t image_size;
2661         int i;
2662         int retval;
2663         uint32_t checksum = 0;
2664         uint32_t mem_checksum = 0;
2665
2666         image_t image;
2667
2668         target_t *target = get_current_target(cmd_ctx);
2669
2670         if (argc < 1)
2671         {
2672                 return ERROR_COMMAND_SYNTAX_ERROR;
2673         }
2674
2675         if (!target)
2676         {
2677                 LOG_ERROR("no target selected");
2678                 return ERROR_FAIL;
2679         }
2680
2681         struct duration bench;
2682         duration_start(&bench);
2683
2684         if (argc >= 2)
2685         {
2686                 uint32_t addr;
2687                 COMMAND_PARSE_NUMBER(u32, args[1], addr);
2688                 image.base_address = addr;
2689                 image.base_address_set = 1;
2690         }
2691         else
2692         {
2693                 image.base_address_set = 0;
2694                 image.base_address = 0x0;
2695         }
2696
2697         image.start_address_set = 0;
2698
2699         if ((retval = image_open(&image, args[0], (argc == 3) ? args[2] : NULL)) != ERROR_OK)
2700         {
2701                 return retval;
2702         }
2703
2704         image_size = 0x0;
2705         retval = ERROR_OK;
2706         for (i = 0; i < image.num_sections; i++)
2707         {
2708                 buffer = malloc(image.sections[i].size);
2709                 if (buffer == NULL)
2710                 {
2711                         command_print(cmd_ctx,
2712                                                   "error allocating buffer for section (%d bytes)",
2713                                                   (int)(image.sections[i].size));
2714                         break;
2715                 }
2716                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2717                 {
2718                         free(buffer);
2719                         break;
2720                 }
2721
2722                 if (verify)
2723                 {
2724                         /* calculate checksum of image */
2725                         image_calculate_checksum(buffer, buf_cnt, &checksum);
2726
2727                         retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2728                         if (retval != ERROR_OK)
2729                         {
2730                                 free(buffer);
2731                                 break;
2732                         }
2733
2734                         if (checksum != mem_checksum)
2735                         {
2736                                 /* failed crc checksum, fall back to a binary compare */
2737                                 uint8_t *data;
2738
2739                                 command_print(cmd_ctx, "checksum mismatch - attempting binary compare");
2740
2741                                 data = (uint8_t*)malloc(buf_cnt);
2742
2743                                 /* Can we use 32bit word accesses? */
2744                                 int size = 1;
2745                                 int count = buf_cnt;
2746                                 if ((count % 4) == 0)
2747                                 {
2748                                         size *= 4;
2749                                         count /= 4;
2750                                 }
2751                                 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2752                                 if (retval == ERROR_OK)
2753                                 {
2754                                         uint32_t t;
2755                                         for (t = 0; t < buf_cnt; t++)
2756                                         {
2757                                                 if (data[t] != buffer[t])
2758                                                 {
2759                                                         command_print(cmd_ctx,
2760                                                                                   "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n",
2761                                                                                   (unsigned)(t + image.sections[i].base_address),
2762                                                                                   data[t],
2763                                                                                   buffer[t]);
2764                                                         free(data);
2765                                                         free(buffer);
2766                                                         retval = ERROR_FAIL;
2767                                                         goto done;
2768                                                 }
2769                                                 if ((t%16384) == 0)
2770                                                 {
2771                                                         keep_alive();
2772                                                 }
2773                                         }
2774                                 }
2775
2776                                 free(data);
2777                         }
2778                 } else
2779                 {
2780                         command_print(cmd_ctx, "address 0x%08" PRIx32 " length 0x%08" PRIx32 "",
2781                                                   image.sections[i].base_address,
2782                                                   buf_cnt);
2783                 }
2784
2785                 free(buffer);
2786                 image_size += buf_cnt;
2787         }
2788 done:
2789         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
2790         {
2791                 command_print(cmd_ctx, "verified %" PRIu32 " bytes "
2792                                 "in %fs (%0.3f kb/s)", image_size,
2793                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
2794         }
2795
2796         image_close(&image);
2797
2798         return retval;
2799 }
2800
2801 static int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2802 {
2803         return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 1);
2804 }
2805
2806 static int handle_test_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2807 {
2808         return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 0);
2809 }
2810
2811 static int handle_bp_command_list(struct command_context_s *cmd_ctx)
2812 {
2813         target_t *target = get_current_target(cmd_ctx);
2814         breakpoint_t *breakpoint = target->breakpoints;
2815         while (breakpoint)
2816         {
2817                 if (breakpoint->type == BKPT_SOFT)
2818                 {
2819                         char* buf = buf_to_str(breakpoint->orig_instr,
2820                                         breakpoint->length, 16);
2821                         command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2822                                         breakpoint->address,
2823                                         breakpoint->length,
2824                                         breakpoint->set, buf);
2825                         free(buf);
2826                 }
2827                 else
2828                 {
2829                         command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2830                                                   breakpoint->address,
2831                                                   breakpoint->length, breakpoint->set);
2832                 }
2833
2834                 breakpoint = breakpoint->next;
2835         }
2836         return ERROR_OK;
2837 }
2838
2839 static int handle_bp_command_set(struct command_context_s *cmd_ctx,
2840                 uint32_t addr, uint32_t length, int hw)
2841 {
2842         target_t *target = get_current_target(cmd_ctx);
2843         int retval = breakpoint_add(target, addr, length, hw);
2844         if (ERROR_OK == retval)
2845                 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2846         else
2847                 LOG_ERROR("Failure setting breakpoint");
2848         return retval;
2849 }
2850
2851 static int handle_bp_command(struct command_context_s *cmd_ctx,
2852                 char *cmd, char **args, int argc)
2853 {
2854         if (argc == 0)
2855                 return handle_bp_command_list(cmd_ctx);
2856
2857         if (argc < 2 || argc > 3)
2858         {
2859                 command_print(cmd_ctx, "usage: bp <address> <length> ['hw']");
2860                 return ERROR_COMMAND_SYNTAX_ERROR;
2861         }
2862
2863         uint32_t addr;
2864         COMMAND_PARSE_NUMBER(u32, args[0], addr);
2865         uint32_t length;
2866         COMMAND_PARSE_NUMBER(u32, args[1], length);
2867
2868         int hw = BKPT_SOFT;
2869         if (argc == 3)
2870         {
2871                 if (strcmp(args[2], "hw") == 0)
2872                         hw = BKPT_HARD;
2873                 else
2874                         return ERROR_COMMAND_SYNTAX_ERROR;
2875         }
2876
2877         return handle_bp_command_set(cmd_ctx, addr, length, hw);
2878 }
2879
2880 static int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2881 {
2882         if (argc != 1)
2883                 return ERROR_COMMAND_SYNTAX_ERROR;
2884
2885         uint32_t addr;
2886         COMMAND_PARSE_NUMBER(u32, args[0], addr);
2887
2888         target_t *target = get_current_target(cmd_ctx);
2889         breakpoint_remove(target, addr);
2890
2891         return ERROR_OK;
2892 }
2893
2894 static int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2895 {
2896         target_t *target = get_current_target(cmd_ctx);
2897
2898         if (argc == 0)
2899         {
2900                 watchpoint_t *watchpoint = target->watchpoints;
2901
2902                 while (watchpoint)
2903                 {
2904                         command_print(cmd_ctx,
2905                                                   "address: 0x%8.8" PRIx32 ", len: 0x%8.8x, r/w/a: %i, value: 0x%8.8" PRIx32 ", mask: 0x%8.8" PRIx32 "",
2906                                                   watchpoint->address,
2907                                                   watchpoint->length,
2908                                                   (int)(watchpoint->rw),
2909                                                   watchpoint->value,
2910                                                   watchpoint->mask);
2911                         watchpoint = watchpoint->next;
2912                 }
2913                 return ERROR_OK;
2914         }
2915
2916         enum watchpoint_rw type = WPT_ACCESS;
2917         uint32_t addr = 0;
2918         uint32_t length = 0;
2919         uint32_t data_value = 0x0;
2920         uint32_t data_mask = 0xffffffff;
2921
2922         switch (argc)
2923         {
2924         case 5:
2925                 COMMAND_PARSE_NUMBER(u32, args[4], data_mask);
2926                 // fall through
2927         case 4:
2928                 COMMAND_PARSE_NUMBER(u32, args[3], data_value);
2929                 // fall through
2930         case 3:
2931                 switch (args[2][0])
2932                 {
2933                 case 'r':
2934                         type = WPT_READ;
2935                         break;
2936                 case 'w':
2937                         type = WPT_WRITE;
2938                         break;
2939                 case 'a':
2940                         type = WPT_ACCESS;
2941                         break;
2942                 default:
2943                         LOG_ERROR("invalid watchpoint mode ('%c')", args[2][0]);
2944                         return ERROR_COMMAND_SYNTAX_ERROR;
2945                 }
2946                 // fall through
2947         case 2:
2948                 COMMAND_PARSE_NUMBER(u32, args[1], length);
2949                 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2950                 break;
2951
2952         default:
2953                 command_print(cmd_ctx, "usage: wp [address length "
2954                                 "[(r|w|a) [value [mask]]]]");
2955                 return ERROR_COMMAND_SYNTAX_ERROR;
2956         }
2957
2958         int retval = watchpoint_add(target, addr, length, type,
2959                         data_value, data_mask);
2960         if (ERROR_OK != retval)
2961                 LOG_ERROR("Failure setting watchpoints");
2962
2963         return retval;
2964 }
2965
2966 static int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2967 {
2968         if (argc != 1)
2969                 return ERROR_COMMAND_SYNTAX_ERROR;
2970
2971         uint32_t addr;
2972         COMMAND_PARSE_NUMBER(u32, args[0], addr);
2973
2974         target_t *target = get_current_target(cmd_ctx);
2975         watchpoint_remove(target, addr);
2976
2977         return ERROR_OK;
2978 }
2979
2980
2981 /**
2982  * Translate a virtual address to a physical address.
2983  *
2984  * The low-level target implementation must have logged a detailed error
2985  * which is forwarded to telnet/GDB session.
2986  */
2987 static int handle_virt2phys_command(command_context_t *cmd_ctx,
2988                 char *cmd, char **args, int argc)
2989 {
2990         if (argc != 1)
2991                 return ERROR_COMMAND_SYNTAX_ERROR;
2992
2993         uint32_t va;
2994         COMMAND_PARSE_NUMBER(u32, args[0], va);
2995         uint32_t pa;
2996
2997         target_t *target = get_current_target(cmd_ctx);
2998         int retval = target->type->virt2phys(target, va, &pa);
2999         if (retval == ERROR_OK)
3000                 command_print(cmd_ctx, "Physical address 0x%08" PRIx32 "", pa);
3001
3002         return retval;
3003 }
3004
3005 static void writeData(FILE *f, const void *data, size_t len)
3006 {
3007         size_t written = fwrite(data, 1, len, f);
3008         if (written != len)
3009                 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3010 }
3011
3012 static void writeLong(FILE *f, int l)
3013 {
3014         int i;
3015         for (i = 0; i < 4; i++)
3016         {
3017                 char c = (l >> (i*8))&0xff;
3018                 writeData(f, &c, 1);
3019         }
3020
3021 }
3022
3023 static void writeString(FILE *f, char *s)
3024 {
3025         writeData(f, s, strlen(s));
3026 }
3027
3028 /* Dump a gmon.out histogram file. */
3029 static void writeGmon(uint32_t *samples, uint32_t sampleNum, char *filename)
3030 {
3031         uint32_t i;
3032         FILE *f = fopen(filename, "w");
3033         if (f == NULL)
3034                 return;
3035         writeString(f, "gmon");
3036         writeLong(f, 0x00000001); /* Version */
3037         writeLong(f, 0); /* padding */
3038         writeLong(f, 0); /* padding */
3039         writeLong(f, 0); /* padding */
3040
3041         uint8_t zero = 0;  /* GMON_TAG_TIME_HIST */
3042         writeData(f, &zero, 1);
3043
3044         /* figure out bucket size */
3045         uint32_t min = samples[0];
3046         uint32_t max = samples[0];
3047         for (i = 0; i < sampleNum; i++)
3048         {
3049                 if (min > samples[i])
3050                 {
3051                         min = samples[i];
3052                 }
3053                 if (max < samples[i])
3054                 {
3055                         max = samples[i];
3056                 }
3057         }
3058
3059         int addressSpace = (max-min + 1);
3060
3061         static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
3062         uint32_t length = addressSpace;
3063         if (length > maxBuckets)
3064         {
3065                 length = maxBuckets;
3066         }
3067         int *buckets = malloc(sizeof(int)*length);
3068         if (buckets == NULL)
3069         {
3070                 fclose(f);
3071                 return;
3072         }
3073         memset(buckets, 0, sizeof(int)*length);
3074         for (i = 0; i < sampleNum;i++)
3075         {
3076                 uint32_t address = samples[i];
3077                 long long a = address-min;
3078                 long long b = length-1;
3079                 long long c = addressSpace-1;
3080                 int index = (a*b)/c; /* danger!!!! int32 overflows */
3081                 buckets[index]++;
3082         }
3083
3084         /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3085         writeLong(f, min);                      /* low_pc */
3086         writeLong(f, max);                      /* high_pc */
3087         writeLong(f, length);           /* # of samples */
3088         writeLong(f, 64000000);         /* 64MHz */
3089         writeString(f, "seconds");
3090         for (i = 0; i < (15-strlen("seconds")); i++)
3091                 writeData(f, &zero, 1);
3092         writeString(f, "s");
3093
3094         /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3095
3096         char *data = malloc(2*length);
3097         if (data != NULL)
3098         {
3099                 for (i = 0; i < length;i++)
3100                 {
3101                         int val;
3102                         val = buckets[i];
3103                         if (val > 65535)
3104                         {
3105                                 val = 65535;
3106                         }
3107                         data[i*2]=val&0xff;
3108                         data[i*2 + 1]=(val >> 8)&0xff;
3109                 }
3110                 free(buckets);
3111                 writeData(f, data, length * 2);
3112                 free(data);
3113         } else
3114         {
3115                 free(buckets);
3116         }
3117
3118         fclose(f);
3119 }
3120
3121 /* profiling samples the CPU PC as quickly as OpenOCD is able, which will be used as a random sampling of PC */
3122 static int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
3123 {
3124         target_t *target = get_current_target(cmd_ctx);
3125         struct timeval timeout, now;
3126
3127         gettimeofday(&timeout, NULL);
3128         if (argc != 2)
3129         {
3130                 return ERROR_COMMAND_SYNTAX_ERROR;
3131         }
3132         unsigned offset;
3133         COMMAND_PARSE_NUMBER(uint, args[0], offset);
3134
3135         timeval_add_time(&timeout, offset, 0);
3136
3137         command_print(cmd_ctx, "Starting profiling. Halting and resuming the target as often as we can...");
3138
3139         static const int maxSample = 10000;
3140         uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3141         if (samples == NULL)
3142                 return ERROR_OK;
3143
3144         int numSamples = 0;
3145         /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3146         reg_t *reg = register_get_by_name(target->reg_cache, "pc", 1);
3147
3148         for (;;)
3149         {
3150                 int retval;
3151                 target_poll(target);
3152                 if (target->state == TARGET_HALTED)
3153                 {
3154                         uint32_t t=*((uint32_t *)reg->value);
3155                         samples[numSamples++]=t;
3156                         retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3157                         target_poll(target);
3158                         alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3159                 } else if (target->state == TARGET_RUNNING)
3160                 {
3161                         /* We want to quickly sample the PC. */
3162                         if ((retval = target_halt(target)) != ERROR_OK)
3163                         {
3164                                 free(samples);
3165                                 return retval;
3166                         }
3167                 } else
3168                 {
3169                         command_print(cmd_ctx, "Target not halted or running");
3170                         retval = ERROR_OK;
3171                         break;
3172                 }
3173                 if (retval != ERROR_OK)
3174                 {
3175                         break;
3176                 }
3177
3178                 gettimeofday(&now, NULL);
3179                 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3180                 {
3181                         command_print(cmd_ctx, "Profiling completed. %d samples.", numSamples);
3182                         if ((retval = target_poll(target)) != ERROR_OK)
3183                         {
3184                                 free(samples);
3185                                 return retval;
3186                         }
3187                         if (target->state == TARGET_HALTED)
3188                         {
3189                                 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3190                         }
3191                         if ((retval = target_poll(target)) != ERROR_OK)
3192                         {
3193                                 free(samples);
3194                                 return retval;
3195                         }
3196                         writeGmon(samples, numSamples, args[1]);
3197                         command_print(cmd_ctx, "Wrote %s", args[1]);
3198                         break;
3199                 }
3200         }
3201         free(samples);
3202
3203         return ERROR_OK;
3204 }
3205
3206 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3207 {
3208         char *namebuf;
3209         Jim_Obj *nameObjPtr, *valObjPtr;
3210         int result;
3211
3212         namebuf = alloc_printf("%s(%d)", varname, idx);
3213         if (!namebuf)
3214                 return JIM_ERR;
3215
3216         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3217         valObjPtr = Jim_NewIntObj(interp, val);
3218         if (!nameObjPtr || !valObjPtr)
3219         {
3220                 free(namebuf);
3221                 return JIM_ERR;
3222         }
3223
3224         Jim_IncrRefCount(nameObjPtr);
3225         Jim_IncrRefCount(valObjPtr);
3226         result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3227         Jim_DecrRefCount(interp, nameObjPtr);
3228         Jim_DecrRefCount(interp, valObjPtr);
3229         free(namebuf);
3230         /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3231         return result;
3232 }
3233
3234 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3235 {
3236         command_context_t *context;
3237         target_t *target;
3238
3239         context = Jim_GetAssocData(interp, "context");
3240         if (context == NULL)
3241         {
3242                 LOG_ERROR("mem2array: no command context");
3243                 return JIM_ERR;
3244         }
3245         target = get_current_target(context);
3246         if (target == NULL)
3247         {
3248                 LOG_ERROR("mem2array: no current target");
3249                 return JIM_ERR;
3250         }
3251
3252         return  target_mem2array(interp, target, argc-1, argv + 1);
3253 }
3254
3255 static int target_mem2array(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
3256 {
3257         long l;
3258         uint32_t width;
3259         int len;
3260         uint32_t addr;
3261         uint32_t count;
3262         uint32_t v;
3263         const char *varname;
3264         uint8_t buffer[4096];
3265         int  n, e, retval;
3266         uint32_t i;
3267
3268         /* argv[1] = name of array to receive the data
3269          * argv[2] = desired width
3270          * argv[3] = memory address
3271          * argv[4] = count of times to read
3272          */
3273         if (argc != 4) {
3274                 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3275                 return JIM_ERR;
3276         }
3277         varname = Jim_GetString(argv[0], &len);
3278         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3279
3280         e = Jim_GetLong(interp, argv[1], &l);
3281         width = l;
3282         if (e != JIM_OK) {
3283                 return e;
3284         }
3285
3286         e = Jim_GetLong(interp, argv[2], &l);
3287         addr = l;
3288         if (e != JIM_OK) {
3289                 return e;
3290         }
3291         e = Jim_GetLong(interp, argv[3], &l);
3292         len = l;
3293         if (e != JIM_OK) {
3294                 return e;
3295         }
3296         switch (width) {
3297                 case 8:
3298                         width = 1;
3299                         break;
3300                 case 16:
3301                         width = 2;
3302                         break;
3303                 case 32:
3304                         width = 4;
3305                         break;
3306                 default:
3307                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3308                         Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3309                         return JIM_ERR;
3310         }
3311         if (len == 0) {
3312                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3313                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3314                 return JIM_ERR;
3315         }
3316         if ((addr + (len * width)) < addr) {
3317                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3318                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3319                 return JIM_ERR;
3320         }
3321         /* absurd transfer size? */
3322         if (len > 65536) {
3323                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3324                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3325                 return JIM_ERR;
3326         }
3327
3328         if ((width == 1) ||
3329                 ((width == 2) && ((addr & 1) == 0)) ||
3330                 ((width == 4) && ((addr & 3) == 0))) {
3331                 /* all is well */
3332         } else {
3333                 char buf[100];
3334                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3335                 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3336                                 addr,
3337                                 width);
3338                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3339                 return JIM_ERR;
3340         }
3341
3342         /* Transfer loop */
3343
3344         /* index counter */
3345         n = 0;
3346         /* assume ok */
3347         e = JIM_OK;
3348         while (len) {
3349                 /* Slurp... in buffer size chunks */
3350
3351                 count = len; /* in objects.. */
3352                 if (count > (sizeof(buffer)/width)) {
3353                         count = (sizeof(buffer)/width);
3354                 }
3355
3356                 retval = target_read_memory(target, addr, width, count, buffer);
3357                 if (retval != ERROR_OK) {
3358                         /* BOO !*/
3359                         LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3360                                           (unsigned int)addr,
3361                                           (int)width,
3362                                           (int)count);
3363                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3364                         Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3365                         e = JIM_ERR;
3366                         len = 0;
3367                 } else {
3368                         v = 0; /* shut up gcc */
3369                         for (i = 0 ;i < count ;i++, n++) {
3370                                 switch (width) {
3371                                         case 4:
3372                                                 v = target_buffer_get_u32(target, &buffer[i*width]);
3373                                                 break;
3374                                         case 2:
3375                                                 v = target_buffer_get_u16(target, &buffer[i*width]);
3376                                                 break;
3377                                         case 1:
3378                                                 v = buffer[i] & 0x0ff;
3379                                                 break;
3380                                 }
3381                                 new_int_array_element(interp, varname, n, v);
3382                         }
3383                         len -= count;
3384                 }
3385         }
3386
3387         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3388
3389         return JIM_OK;
3390 }
3391
3392 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3393 {
3394         char *namebuf;
3395         Jim_Obj *nameObjPtr, *valObjPtr;
3396         int result;
3397         long l;
3398
3399         namebuf = alloc_printf("%s(%d)", varname, idx);
3400         if (!namebuf)
3401                 return JIM_ERR;
3402
3403         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3404         if (!nameObjPtr)
3405         {
3406                 free(namebuf);
3407                 return JIM_ERR;
3408         }
3409
3410         Jim_IncrRefCount(nameObjPtr);
3411         valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3412         Jim_DecrRefCount(interp, nameObjPtr);
3413         free(namebuf);
3414         if (valObjPtr == NULL)
3415                 return JIM_ERR;
3416
3417         result = Jim_GetLong(interp, valObjPtr, &l);
3418         /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3419         *val = l;
3420         return result;
3421 }
3422
3423 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3424 {
3425         command_context_t *context;
3426         target_t *target;
3427
3428         context = Jim_GetAssocData(interp, "context");
3429         if (context == NULL) {
3430                 LOG_ERROR("array2mem: no command context");
3431                 return JIM_ERR;
3432         }
3433         target = get_current_target(context);
3434         if (target == NULL) {
3435                 LOG_ERROR("array2mem: no current target");
3436                 return JIM_ERR;
3437         }
3438
3439         return target_array2mem(interp,target, argc-1, argv + 1);
3440 }
3441 static int target_array2mem(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
3442 {
3443         long l;
3444         uint32_t width;
3445         int len;
3446         uint32_t addr;
3447         uint32_t count;
3448         uint32_t v;
3449         const char *varname;
3450         uint8_t buffer[4096];
3451         int  n, e, retval;
3452         uint32_t i;
3453
3454         /* argv[1] = name of array to get the data
3455          * argv[2] = desired width
3456          * argv[3] = memory address
3457          * argv[4] = count to write
3458          */
3459         if (argc != 4) {
3460                 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3461                 return JIM_ERR;
3462         }
3463         varname = Jim_GetString(argv[0], &len);
3464         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3465
3466         e = Jim_GetLong(interp, argv[1], &l);
3467         width = l;
3468         if (e != JIM_OK) {
3469                 return e;
3470         }
3471
3472         e = Jim_GetLong(interp, argv[2], &l);
3473         addr = l;
3474         if (e != JIM_OK) {
3475                 return e;
3476         }
3477         e = Jim_GetLong(interp, argv[3], &l);
3478         len = l;
3479         if (e != JIM_OK) {
3480                 return e;
3481         }
3482         switch (width) {
3483                 case 8:
3484                         width = 1;
3485                         break;
3486                 case 16:
3487                         width = 2;
3488                         break;
3489                 case 32:
3490                         width = 4;
3491                         break;
3492                 default:
3493                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3494                         Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3495                         return JIM_ERR;
3496         }
3497         if (len == 0) {
3498                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3499                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3500                 return JIM_ERR;
3501         }
3502         if ((addr + (len * width)) < addr) {
3503                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3504                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3505                 return JIM_ERR;
3506         }
3507         /* absurd transfer size? */
3508         if (len > 65536) {
3509                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3510                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3511                 return JIM_ERR;
3512         }
3513
3514         if ((width == 1) ||
3515                 ((width == 2) && ((addr & 1) == 0)) ||
3516                 ((width == 4) && ((addr & 3) == 0))) {
3517                 /* all is well */
3518         } else {
3519                 char buf[100];
3520                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3521                 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3522                                 (unsigned int)addr,
3523                                 (int)width);
3524                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3525                 return JIM_ERR;
3526         }
3527
3528         /* Transfer loop */
3529
3530         /* index counter */
3531         n = 0;
3532         /* assume ok */
3533         e = JIM_OK;
3534         while (len) {
3535                 /* Slurp... in buffer size chunks */
3536
3537                 count = len; /* in objects.. */
3538                 if (count > (sizeof(buffer)/width)) {
3539                         count = (sizeof(buffer)/width);
3540                 }
3541
3542                 v = 0; /* shut up gcc */
3543                 for (i = 0 ;i < count ;i++, n++) {
3544                         get_int_array_element(interp, varname, n, &v);
3545                         switch (width) {
3546                         case 4:
3547                                 target_buffer_set_u32(target, &buffer[i*width], v);
3548                                 break;
3549                         case 2:
3550                                 target_buffer_set_u16(target, &buffer[i*width], v);
3551                                 break;
3552                         case 1:
3553                                 buffer[i] = v & 0x0ff;
3554                                 break;
3555                         }
3556                 }
3557                 len -= count;
3558
3559                 retval = target_write_memory(target, addr, width, count, buffer);
3560                 if (retval != ERROR_OK) {
3561                         /* BOO !*/
3562                         LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3563                                           (unsigned int)addr,
3564                                           (int)width,
3565                                           (int)count);
3566                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3567                         Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3568                         e = JIM_ERR;
3569                         len = 0;
3570                 }
3571         }
3572
3573         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3574
3575         return JIM_OK;
3576 }
3577
3578 void target_all_handle_event(enum target_event e)
3579 {
3580         target_t *target;
3581
3582         LOG_DEBUG("**all*targets: event: %d, %s",
3583                            (int)e,
3584                            Jim_Nvp_value2name_simple(nvp_target_event, e)->name);
3585
3586         target = all_targets;
3587         while (target) {
3588                 target_handle_event(target, e);
3589                 target = target->next;
3590         }
3591 }
3592
3593
3594 /* FIX? should we propagate errors here rather than printing them
3595  * and continuing?
3596  */
3597 void target_handle_event(target_t *target, enum target_event e)
3598 {
3599         target_event_action_t *teap;
3600
3601         for (teap = target->event_action; teap != NULL; teap = teap->next) {
3602                 if (teap->event == e) {
3603                         LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3604                                            target->target_number,
3605                                            target->cmd_name,
3606                                            target_get_name(target),
3607                                            e,
3608                                            Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3609                                            Jim_GetString(teap->body, NULL));
3610                         if (Jim_EvalObj(interp, teap->body) != JIM_OK)
3611                         {
3612                                 Jim_PrintErrorMessage(interp);
3613                         }
3614                 }
3615         }
3616 }
3617
3618 enum target_cfg_param {
3619         TCFG_TYPE,
3620         TCFG_EVENT,
3621         TCFG_WORK_AREA_VIRT,
3622         TCFG_WORK_AREA_PHYS,
3623         TCFG_WORK_AREA_SIZE,
3624         TCFG_WORK_AREA_BACKUP,
3625         TCFG_ENDIAN,
3626         TCFG_VARIANT,
3627         TCFG_CHAIN_POSITION,
3628 };
3629
3630 static Jim_Nvp nvp_config_opts[] = {
3631         { .name = "-type",             .value = TCFG_TYPE },
3632         { .name = "-event",            .value = TCFG_EVENT },
3633         { .name = "-work-area-virt",   .value = TCFG_WORK_AREA_VIRT },
3634         { .name = "-work-area-phys",   .value = TCFG_WORK_AREA_PHYS },
3635         { .name = "-work-area-size",   .value = TCFG_WORK_AREA_SIZE },
3636         { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3637         { .name = "-endian" ,          .value = TCFG_ENDIAN },
3638         { .name = "-variant",          .value = TCFG_VARIANT },
3639         { .name = "-chain-position",   .value = TCFG_CHAIN_POSITION },
3640
3641         { .name = NULL, .value = -1 }
3642 };
3643
3644 static int target_configure(Jim_GetOptInfo *goi, target_t *target)
3645 {
3646         Jim_Nvp *n;
3647         Jim_Obj *o;
3648         jim_wide w;
3649         char *cp;
3650         int e;
3651
3652         /* parse config or cget options ... */
3653         while (goi->argc > 0) {
3654                 Jim_SetEmptyResult(goi->interp);
3655                 /* Jim_GetOpt_Debug(goi); */
3656
3657                 if (target->type->target_jim_configure) {
3658                         /* target defines a configure function */
3659                         /* target gets first dibs on parameters */
3660                         e = (*(target->type->target_jim_configure))(target, goi);
3661                         if (e == JIM_OK) {
3662                                 /* more? */
3663                                 continue;
3664                         }
3665                         if (e == JIM_ERR) {
3666                                 /* An error */
3667                                 return e;
3668                         }
3669                         /* otherwise we 'continue' below */
3670                 }
3671                 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3672                 if (e != JIM_OK) {
3673                         Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3674                         return e;
3675                 }
3676                 switch (n->value) {
3677                 case TCFG_TYPE:
3678                         /* not setable */
3679                         if (goi->isconfigure) {
3680                                 Jim_SetResult_sprintf(goi->interp, "not setable: %s", n->name);
3681                                 return JIM_ERR;
3682                         } else {
3683                         no_params:
3684                                 if (goi->argc != 0) {
3685                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "NO PARAMS");
3686                                         return JIM_ERR;
3687                                 }
3688                         }
3689                         Jim_SetResultString(goi->interp, target_get_name(target), -1);
3690                         /* loop for more */
3691                         break;
3692                 case TCFG_EVENT:
3693                         if (goi->argc == 0) {
3694                                 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3695                                 return JIM_ERR;
3696                         }
3697
3698                         e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3699                         if (e != JIM_OK) {
3700                                 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3701                                 return e;
3702                         }
3703
3704                         if (goi->isconfigure) {
3705                                 if (goi->argc != 1) {
3706                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3707                                         return JIM_ERR;
3708                                 }
3709                         } else {
3710                                 if (goi->argc != 0) {
3711                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3712                                         return JIM_ERR;
3713                                 }
3714                         }
3715
3716                         {
3717                                 target_event_action_t *teap;
3718
3719                                 teap = target->event_action;
3720                                 /* replace existing? */
3721                                 while (teap) {
3722                                         if (teap->event == (enum target_event)n->value) {
3723                                                 break;
3724                                         }
3725                                         teap = teap->next;
3726                                 }
3727
3728                                 if (goi->isconfigure) {
3729                                         bool replace = true;
3730                                         if (teap == NULL) {
3731                                                 /* create new */
3732                                                 teap = calloc(1, sizeof(*teap));
3733                                                 replace = false;
3734                                         }
3735                                         teap->event = n->value;
3736                                         Jim_GetOpt_Obj(goi, &o);
3737                                         if (teap->body) {
3738                                                 Jim_DecrRefCount(interp, teap->body);
3739                                         }
3740                                         teap->body  = Jim_DuplicateObj(goi->interp, o);
3741                                         /*
3742                                          * FIXME:
3743                                          *     Tcl/TK - "tk events" have a nice feature.
3744                                          *     See the "BIND" command.
3745                                          *    We should support that here.
3746                                          *     You can specify %X and %Y in the event code.
3747                                          *     The idea is: %T - target name.
3748                                          *     The idea is: %N - target number
3749                                          *     The idea is: %E - event name.
3750                                          */
3751                                         Jim_IncrRefCount(teap->body);
3752
3753                                         if (!replace)
3754                                         {
3755                                                 /* add to head of event list */
3756                                                 teap->next = target->event_action;
3757                                                 target->event_action = teap;
3758                                         }
3759                                         Jim_SetEmptyResult(goi->interp);
3760                                 } else {
3761                                         /* get */
3762                                         if (teap == NULL) {
3763                                                 Jim_SetEmptyResult(goi->interp);
3764                                         } else {
3765                                                 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3766                                         }
3767                                 }
3768                         }
3769                         /* loop for more */
3770                         break;
3771
3772                 case TCFG_WORK_AREA_VIRT:
3773                         if (goi->isconfigure) {
3774                                 target_free_all_working_areas(target);
3775                                 e = Jim_GetOpt_Wide(goi, &w);
3776                                 if (e != JIM_OK) {
3777                                         return e;
3778                                 }
3779                                 target->working_area_virt = w;
3780                                 target->working_area_virt_spec = true;
3781                         } else {
3782                                 if (goi->argc != 0) {
3783                                         goto no_params;
3784                                 }
3785                         }
3786                         Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3787                         /* loop for more */
3788                         break;
3789
3790                 case TCFG_WORK_AREA_PHYS:
3791                         if (goi->isconfigure) {
3792                                 target_free_all_working_areas(target);
3793                                 e = Jim_GetOpt_Wide(goi, &w);
3794                                 if (e != JIM_OK) {
3795                                         return e;
3796                                 }
3797                                 target->working_area_phys = w;
3798                                 target->working_area_phys_spec = true;
3799                         } else {
3800                                 if (goi->argc != 0) {
3801                                         goto no_params;
3802                                 }
3803                         }
3804                         Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3805                         /* loop for more */
3806                         break;
3807
3808                 case TCFG_WORK_AREA_SIZE:
3809                         if (goi->isconfigure) {
3810                                 target_free_all_working_areas(target);
3811                                 e = Jim_GetOpt_Wide(goi, &w);
3812                                 if (e != JIM_OK) {
3813                                         return e;
3814                                 }
3815                                 target->working_area_size = w;
3816                         } else {
3817                                 if (goi->argc != 0) {
3818                                         goto no_params;
3819                                 }
3820                         }
3821                         Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3822                         /* loop for more */
3823                         break;
3824
3825                 case TCFG_WORK_AREA_BACKUP:
3826                         if (goi->isconfigure) {
3827                                 target_free_all_working_areas(target);
3828                                 e = Jim_GetOpt_Wide(goi, &w);
3829                                 if (e != JIM_OK) {
3830                                         return e;
3831                                 }
3832                                 /* make this exactly 1 or 0 */
3833                                 target->backup_working_area = (!!w);
3834                         } else {
3835                                 if (goi->argc != 0) {
3836                                         goto no_params;
3837                                 }
3838                         }
3839                         Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3840                         /* loop for more e*/
3841                         break;
3842
3843                 case TCFG_ENDIAN:
3844                         if (goi->isconfigure) {
3845                                 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3846                                 if (e != JIM_OK) {
3847                                         Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3848                                         return e;
3849                                 }
3850                                 target->endianness = n->value;
3851                         } else {
3852                                 if (goi->argc != 0) {
3853                                         goto no_params;
3854                                 }
3855                         }
3856                         n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3857                         if (n->name == NULL) {
3858                                 target->endianness = TARGET_LITTLE_ENDIAN;
3859                                 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3860                         }
3861                         Jim_SetResultString(goi->interp, n->name, -1);
3862                         /* loop for more */
3863                         break;
3864
3865                 case TCFG_VARIANT:
3866                         if (goi->isconfigure) {
3867                                 if (goi->argc < 1) {
3868                                         Jim_SetResult_sprintf(goi->interp,
3869                                                                                    "%s ?STRING?",
3870                                                                                    n->name);
3871                                         return JIM_ERR;
3872                                 }
3873                                 if (target->variant) {
3874                                         free((void *)(target->variant));
3875                                 }
3876                                 e = Jim_GetOpt_String(goi, &cp, NULL);
3877                                 target->variant = strdup(cp);
3878                         } else {
3879                                 if (goi->argc != 0) {
3880                                         goto no_params;
3881                                 }
3882                         }
3883                         Jim_SetResultString(goi->interp, target->variant,-1);
3884                         /* loop for more */
3885                         break;
3886                 case TCFG_CHAIN_POSITION:
3887                         if (goi->isconfigure) {
3888                                 Jim_Obj *o;
3889                                 jtag_tap_t *tap;
3890                                 target_free_all_working_areas(target);
3891                                 e = Jim_GetOpt_Obj(goi, &o);
3892                                 if (e != JIM_OK) {
3893                                         return e;
3894                                 }
3895                                 tap = jtag_tap_by_jim_obj(goi->interp, o);
3896                                 if (tap == NULL) {
3897                                         return JIM_ERR;
3898                                 }
3899                                 /* make this exactly 1 or 0 */
3900                                 target->tap = tap;
3901                         } else {
3902                                 if (goi->argc != 0) {
3903                                         goto no_params;
3904                                 }
3905                         }
3906                         Jim_SetResultString(interp, target->tap->dotted_name, -1);
3907                         /* loop for more e*/
3908                         break;
3909                 }
3910         } /* while (goi->argc) */
3911
3912
3913                 /* done - we return */
3914         return JIM_OK;
3915 }
3916
3917 /** this is the 'tcl' handler for the target specific command */
3918 static int tcl_target_func(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3919 {
3920         Jim_GetOptInfo goi;
3921         jim_wide a,b,c;
3922         int x,y,z;
3923         uint8_t  target_buf[32];
3924         Jim_Nvp *n;
3925         target_t *target;
3926         struct command_context_s *cmd_ctx;
3927         int e;
3928
3929         enum {
3930                 TS_CMD_CONFIGURE,
3931                 TS_CMD_CGET,
3932
3933                 TS_CMD_MWW, TS_CMD_MWH, TS_CMD_MWB,
3934                 TS_CMD_MDW, TS_CMD_MDH, TS_CMD_MDB,
3935                 TS_CMD_MRW, TS_CMD_MRH, TS_CMD_MRB,
3936                 TS_CMD_MEM2ARRAY, TS_CMD_ARRAY2MEM,
3937                 TS_CMD_EXAMINE,
3938                 TS_CMD_POLL,
3939                 TS_CMD_RESET,
3940                 TS_CMD_HALT,
3941                 TS_CMD_WAITSTATE,
3942                 TS_CMD_EVENTLIST,
3943                 TS_CMD_CURSTATE,
3944                 TS_CMD_INVOKE_EVENT,
3945         };
3946
3947         static const Jim_Nvp target_options[] = {
3948                 { .name = "configure", .value = TS_CMD_CONFIGURE },
3949                 { .name = "cget", .value = TS_CMD_CGET },
3950                 { .name = "mww", .value = TS_CMD_MWW },
3951                 { .name = "mwh", .value = TS_CMD_MWH },
3952                 { .name = "mwb", .value = TS_CMD_MWB },
3953                 { .name = "mdw", .value = TS_CMD_MDW },
3954                 { .name = "mdh", .value = TS_CMD_MDH },
3955                 { .name = "mdb", .value = TS_CMD_MDB },
3956                 { .name = "mem2array", .value = TS_CMD_MEM2ARRAY },
3957                 { .name = "array2mem", .value = TS_CMD_ARRAY2MEM },
3958                 { .name = "eventlist", .value = TS_CMD_EVENTLIST },
3959                 { .name = "curstate",  .value = TS_CMD_CURSTATE },
3960
3961                 { .name = "arp_examine", .value = TS_CMD_EXAMINE },
3962                 { .name = "arp_poll", .value = TS_CMD_POLL },
3963                 { .name = "arp_reset", .value = TS_CMD_RESET },
3964                 { .name = "arp_halt", .value = TS_CMD_HALT },
3965                 { .name = "arp_waitstate", .value = TS_CMD_WAITSTATE },
3966                 { .name = "invoke-event", .value = TS_CMD_INVOKE_EVENT },
3967
3968                 { .name = NULL, .value = -1 },
3969         };
3970
3971         /* go past the "command" */
3972         Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
3973
3974         target = Jim_CmdPrivData(goi.interp);
3975         cmd_ctx = Jim_GetAssocData(goi.interp, "context");
3976
3977         /* commands here are in an NVP table */
3978         e = Jim_GetOpt_Nvp(&goi, target_options, &n);
3979         if (e != JIM_OK) {
3980                 Jim_GetOpt_NvpUnknown(&goi, target_options, 0);
3981                 return e;
3982         }
3983         /* Assume blank result */
3984         Jim_SetEmptyResult(goi.interp);
3985
3986         switch (n->value) {
3987         case TS_CMD_CONFIGURE:
3988                 if (goi.argc < 2) {
3989                         Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "missing: -option VALUE ...");
3990                         return JIM_ERR;
3991                 }
3992                 goi.isconfigure = 1;
3993                 return target_configure(&goi, target);
3994         case TS_CMD_CGET:
3995                 // some things take params
3996                 if (goi.argc < 1) {
3997                         Jim_WrongNumArgs(goi.interp, 0, goi.argv, "missing: ?-option?");
3998                         return JIM_ERR;
3999                 }
4000                 goi.isconfigure = 0;
4001                 return target_configure(&goi, target);
4002                 break;
4003         case TS_CMD_MWW:
4004         case TS_CMD_MWH:
4005         case TS_CMD_MWB:
4006                 /* argv[0] = cmd
4007                  * argv[1] = address
4008                  * argv[2] = data
4009                  * argv[3] = optional count.
4010                  */
4011
4012                 if ((goi.argc == 2) || (goi.argc == 3)) {
4013                         /* all is well */
4014                 } else {
4015                 mwx_error:
4016                         Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR DATA [COUNT]", n->name);
4017                         return JIM_ERR;
4018                 }
4019
4020                 e = Jim_GetOpt_Wide(&goi, &a);
4021                 if (e != JIM_OK) {
4022                         goto mwx_error;
4023                 }
4024
4025                 e = Jim_GetOpt_Wide(&goi, &b);
4026                 if (e != JIM_OK) {
4027                         goto mwx_error;
4028                 }
4029                 if (goi.argc == 3) {
4030                         e = Jim_GetOpt_Wide(&goi, &c);
4031                         if (e != JIM_OK) {
4032                                 goto mwx_error;
4033                         }
4034                 } else {
4035                         c = 1;
4036                 }
4037
4038                 switch (n->value) {
4039                 case TS_CMD_MWW:
4040                         target_buffer_set_u32(target, target_buf, b);
4041                         b = 4;
4042                         break;
4043                 case TS_CMD_MWH:
4044                         target_buffer_set_u16(target, target_buf, b);
4045                         b = 2;
4046                         break;
4047                 case TS_CMD_MWB:
4048                         target_buffer_set_u8(target, target_buf, b);
4049                         b = 1;
4050                         break;
4051                 }
4052                 for (x = 0 ; x < c ; x++) {
4053                         e = target_write_memory(target, a, b, 1, target_buf);
4054                         if (e != ERROR_OK) {
4055                                 Jim_SetResult_sprintf(interp, "Error writing @ 0x%08x: %d\n", (int)(a), e);
4056                                 return JIM_ERR;
4057                         }
4058                         /* b = width */
4059                         a = a + b;
4060                 }
4061                 return JIM_OK;
4062                 break;
4063
4064                 /* display */
4065         case TS_CMD_MDW:
4066         case TS_CMD_MDH:
4067         case TS_CMD_MDB:
4068                 /* argv[0] = command
4069                  * argv[1] = address
4070                  * argv[2] = optional count
4071                  */
4072                 if ((goi.argc == 2) || (goi.argc == 3)) {
4073                         Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR [COUNT]", n->name);
4074                         return JIM_ERR;
4075                 }
4076                 e = Jim_GetOpt_Wide(&goi, &a);
4077                 if (e != JIM_OK) {
4078                         return JIM_ERR;
4079                 }
4080                 if (goi.argc) {
4081                         e = Jim_GetOpt_Wide(&goi, &c);
4082                         if (e != JIM_OK) {
4083                                 return JIM_ERR;
4084                         }
4085                 } else {
4086                         c = 1;
4087                 }
4088                 b = 1; /* shut up gcc */
4089                 switch (n->value) {
4090                 case TS_CMD_MDW:
4091                         b =  4;
4092                         break;
4093                 case TS_CMD_MDH:
4094                         b = 2;
4095                         break;
4096                 case TS_CMD_MDB:
4097                         b = 1;
4098                         break;
4099                 }
4100
4101                 /* convert to "bytes" */
4102                 c = c * b;
4103                 /* count is now in 'BYTES' */
4104                 while (c > 0) {
4105                         y = c;
4106                         if (y > 16) {
4107                                 y = 16;
4108                         }
4109                         e = target_read_memory(target, a, b, y / b, target_buf);
4110                         if (e != ERROR_OK) {
4111                                 Jim_SetResult_sprintf(interp, "error reading target @ 0x%08lx", (int)(a));
4112                                 return JIM_ERR;
4113                         }
4114
4115                         Jim_fprintf(interp, interp->cookie_stdout, "0x%08x ", (int)(a));
4116                         switch (b) {
4117                         case 4:
4118                                 for (x = 0 ; (x < 16) && (x < y) ; x += 4) {
4119                                         z = target_buffer_get_u32(target, &(target_buf[ x * 4 ]));
4120                                         Jim_fprintf(interp, interp->cookie_stdout, "%08x ", (int)(z));
4121                                 }
4122                                 for (; (x < 16) ; x += 4) {
4123                                         Jim_fprintf(interp, interp->cookie_stdout, "         ");
4124                                 }
4125                                 break;
4126                         case 2:
4127                                 for (x = 0 ; (x < 16) && (x < y) ; x += 2) {
4128                                         z = target_buffer_get_u16(target, &(target_buf[ x * 2 ]));
4129                                         Jim_fprintf(interp, interp->cookie_stdout, "%04x ", (int)(z));
4130                                 }
4131                                 for (; (x < 16) ; x += 2) {
4132                                         Jim_fprintf(interp, interp->cookie_stdout, "     ");
4133                                 }
4134                                 break;
4135                         case 1:
4136                         default:
4137                                 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4138                                         z = target_buffer_get_u8(target, &(target_buf[ x * 4 ]));
4139                                         Jim_fprintf(interp, interp->cookie_stdout, "%02x ", (int)(z));
4140                                 }
4141                                 for (; (x < 16) ; x += 1) {
4142                                         Jim_fprintf(interp, interp->cookie_stdout, "   ");
4143                                 }
4144                                 break;
4145                         }
4146                         /* ascii-ify the bytes */
4147                         for (x = 0 ; x < y ; x++) {
4148                                 if ((target_buf[x] >= 0x20) &&
4149                                         (target_buf[x] <= 0x7e)) {
4150                                         /* good */
4151                                 } else {
4152                                         /* smack it */
4153                                         target_buf[x] = '.';
4154                                 }
4155                         }
4156                         /* space pad  */
4157                         while (x < 16) {
4158                                 target_buf[x] = ' ';
4159                                 x++;
4160                         }
4161                         /* terminate */
4162                         target_buf[16] = 0;
4163                         /* print - with a newline */
4164                         Jim_fprintf(interp, interp->cookie_stdout, "%s\n", target_buf);
4165                         /* NEXT... */
4166                         c -= 16;
4167                         a += 16;
4168                 }
4169                 return JIM_OK;
4170         case TS_CMD_MEM2ARRAY:
4171                 return target_mem2array(goi.interp, target, goi.argc, goi.argv);
4172                 break;
4173         case TS_CMD_ARRAY2MEM:
4174                 return target_array2mem(goi.interp, target, goi.argc, goi.argv);
4175                 break;
4176         case TS_CMD_EXAMINE:
4177                 if (goi.argc) {
4178                         Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4179                         return JIM_ERR;
4180                 }
4181                 if (!target->tap->enabled)
4182                         goto err_tap_disabled;
4183                 e = target->type->examine(target);
4184                 if (e != ERROR_OK) {
4185                         Jim_SetResult_sprintf(interp, "examine-fails: %d", e);
4186                         return JIM_ERR;
4187                 }
4188                 return JIM_OK;
4189         case TS_CMD_POLL:
4190                 if (goi.argc) {
4191                         Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4192                         return JIM_ERR;
4193                 }
4194                 if (!target->tap->enabled)
4195                         goto err_tap_disabled;
4196                 if (!(target_was_examined(target))) {
4197                         e = ERROR_TARGET_NOT_EXAMINED;
4198                 } else {
4199                         e = target->type->poll(target);
4200                 }
4201                 if (e != ERROR_OK) {
4202                         Jim_SetResult_sprintf(interp, "poll-fails: %d", e);
4203                         return JIM_ERR;
4204                 } else {
4205                         return JIM_OK;
4206                 }
4207                 break;
4208         case TS_CMD_RESET:
4209                 if (goi.argc != 2) {
4210                         Jim_WrongNumArgs(interp, 2, argv,
4211                                         "([tT]|[fF]|assert|deassert) BOOL");
4212                         return JIM_ERR;
4213                 }
4214                 e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4215                 if (e != JIM_OK) {
4216                         Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4217                         return e;
4218                 }
4219                 /* the halt or not param */
4220                 e = Jim_GetOpt_Wide(&goi, &a);
4221                 if (e != JIM_OK) {
4222                         return e;
4223                 }
4224                 if (!target->tap->enabled)
4225                         goto err_tap_disabled;
4226                 if (!target->type->assert_reset
4227                                 || !target->type->deassert_reset) {
4228                         Jim_SetResult_sprintf(interp,
4229                                         "No target-specific reset for %s",
4230                                         target->cmd_name);
4231                         return JIM_ERR;
4232                 }
4233                 /* determine if we should halt or not. */
4234                 target->reset_halt = !!a;
4235                 /* When this happens - all workareas are invalid. */
4236                 target_free_all_working_areas_restore(target, 0);
4237
4238                 /* do the assert */
4239                 if (n->value == NVP_ASSERT) {
4240                         e = target->type->assert_reset(target);
4241                 } else {
4242                         e = target->type->deassert_reset(target);
4243                 }
4244                 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4245         case TS_CMD_HALT:
4246                 if (goi.argc) {
4247                         Jim_WrongNumArgs(goi.interp, 0, argv, "halt [no parameters]");
4248                         return JIM_ERR;
4249                 }
4250                 if (!target->tap->enabled)
4251                         goto err_tap_disabled;
4252                 e = target->type->halt(target);
4253                 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4254         case TS_CMD_WAITSTATE:
4255                 /* params:  <name>  statename timeoutmsecs */
4256                 if (goi.argc != 2) {
4257                         Jim_SetResult_sprintf(goi.interp, "%s STATENAME TIMEOUTMSECS", n->name);
4258                         return JIM_ERR;
4259                 }
4260                 e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4261                 if (e != JIM_OK) {
4262                         Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4263                         return e;
4264                 }
4265                 e = Jim_GetOpt_Wide(&goi, &a);
4266                 if (e != JIM_OK) {
4267                         return e;
4268                 }
4269                 if (!target->tap->enabled)
4270                         goto err_tap_disabled;
4271                 e = target_wait_state(target, n->value, a);
4272                 if (e != ERROR_OK) {
4273                         Jim_SetResult_sprintf(goi.interp,
4274                                                                    "target: %s wait %s fails (%d) %s",
4275                                                                    target->cmd_name,
4276                                                                    n->name,
4277                                                                    e, target_strerror_safe(e));
4278                         return JIM_ERR;
4279                 } else {
4280                         return JIM_OK;
4281                 }
4282         case TS_CMD_EVENTLIST:
4283                 /* List for human, Events defined for this target.
4284                  * scripts/programs should use 'name cget -event NAME'
4285                  */
4286                 {
4287                         target_event_action_t *teap;
4288                         teap = target->event_action;
4289                         command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4290                                                    target->target_number,
4291                                                    target->cmd_name);
4292                         command_print(cmd_ctx, "%-25s | Body", "Event");
4293                         command_print(cmd_ctx, "------------------------- | ----------------------------------------");
4294                         while (teap) {
4295                                 command_print(cmd_ctx,
4296                                                            "%-25s | %s",
4297                                                            Jim_Nvp_value2name_simple(nvp_target_event, teap->event)->name,
4298                                                            Jim_GetString(teap->body, NULL));
4299                                 teap = teap->next;
4300                         }
4301                         command_print(cmd_ctx, "***END***");
4302                         return JIM_OK;
4303                 }
4304         case TS_CMD_CURSTATE:
4305                 if (goi.argc != 0) {
4306                         Jim_WrongNumArgs(goi.interp, 0, argv, "[no parameters]");
4307                         return JIM_ERR;
4308                 }
4309                 Jim_SetResultString(goi.interp,
4310                                                         target_state_name( target ),
4311                                                         -1);
4312                 return JIM_OK;
4313         case TS_CMD_INVOKE_EVENT:
4314                 if (goi.argc != 1) {
4315                         Jim_SetResult_sprintf(goi.interp, "%s ?EVENTNAME?",n->name);
4316                         return JIM_ERR;
4317                 }
4318                 e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4319                 if (e != JIM_OK) {
4320                         Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4321                         return e;
4322                 }
4323                 target_handle_event(target, n->value);
4324                 return JIM_OK;
4325         }
4326         return JIM_ERR;
4327
4328 err_tap_disabled:
4329         Jim_SetResult_sprintf(interp, "[TAP is disabled]");
4330         return JIM_ERR;
4331 }
4332
4333 static int target_create(Jim_GetOptInfo *goi)
4334 {
4335         Jim_Obj *new_cmd;
4336         Jim_Cmd *cmd;
4337         const char *cp;
4338         char *cp2;
4339         int e;
4340         int x;
4341         target_t *target;
4342         struct command_context_s *cmd_ctx;
4343
4344         cmd_ctx = Jim_GetAssocData(goi->interp, "context");
4345         if (goi->argc < 3) {
4346                 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4347                 return JIM_ERR;
4348         }
4349
4350         /* COMMAND */
4351         Jim_GetOpt_Obj(goi, &new_cmd);
4352         /* does this command exist? */
4353         cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4354         if (cmd) {
4355                 cp = Jim_GetString(new_cmd, NULL);
4356                 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4357                 return JIM_ERR;
4358         }
4359
4360         /* TYPE */
4361         e = Jim_GetOpt_String(goi, &cp2, NULL);
4362         cp = cp2;
4363         /* now does target type exist */
4364         for (x = 0 ; target_types[x] ; x++) {
4365                 if (0 == strcmp(cp, target_types[x]->name)) {
4366                         /* found */
4367                         break;
4368                 }
4369         }
4370         if (target_types[x] == NULL) {
4371                 Jim_SetResult_sprintf(goi->interp, "Unknown target type %s, try one of ", cp);
4372                 for (x = 0 ; target_types[x] ; x++) {
4373                         if (target_types[x + 1]) {
4374                                 Jim_AppendStrings(goi->interp,
4375                                                                    Jim_GetResult(goi->interp),
4376                                                                    target_types[x]->name,
4377                                                                    ", ", NULL);
4378                         } else {
4379                                 Jim_AppendStrings(goi->interp,
4380                                                                    Jim_GetResult(goi->interp),
4381                                                                    " or ",
4382                                                                    target_types[x]->name,NULL);
4383                         }
4384                 }
4385                 return JIM_ERR;
4386         }
4387
4388         /* Create it */
4389         target = calloc(1,sizeof(target_t));
4390         /* set target number */
4391         target->target_number = new_target_number();
4392
4393         /* allocate memory for each unique target type */
4394         target->type = (target_type_t*)calloc(1,sizeof(target_type_t));
4395
4396         memcpy(target->type, target_types[x], sizeof(target_type_t));
4397
4398         /* will be set by "-endian" */
4399         target->endianness = TARGET_ENDIAN_UNKNOWN;
4400
4401         target->working_area        = 0x0;
4402         target->working_area_size   = 0x0;
4403         target->working_areas       = NULL;
4404         target->backup_working_area = 0;
4405
4406         target->state               = TARGET_UNKNOWN;
4407         target->debug_reason        = DBG_REASON_UNDEFINED;
4408         target->reg_cache           = NULL;
4409         target->breakpoints         = NULL;
4410         target->watchpoints         = NULL;
4411         target->next                = NULL;
4412         target->arch_info           = NULL;
4413
4414         target->display             = 1;
4415
4416         target->halt_issued                     = false;
4417
4418         /* initialize trace information */
4419         target->trace_info = malloc(sizeof(trace_t));
4420         target->trace_info->num_trace_points         = 0;
4421         target->trace_info->trace_points_size        = 0;
4422         target->trace_info->trace_points             = NULL;
4423         target->trace_info->trace_history_size       = 0;
4424         target->trace_info->trace_history            = NULL;
4425         target->trace_info->trace_history_pos        = 0;
4426         target->trace_info->trace_history_overflowed = 0;
4427
4428         target->dbgmsg          = NULL;
4429         target->dbg_msg_enabled = 0;
4430
4431         target->endianness = TARGET_ENDIAN_UNKNOWN;
4432
4433         /* Do the rest as "configure" options */
4434         goi->isconfigure = 1;
4435         e = target_configure(goi, target);
4436
4437         if (target->tap == NULL)
4438         {
4439                 Jim_SetResultString(interp, "-chain-position required when creating target", -1);
4440                 e = JIM_ERR;
4441         }
4442
4443         if (e != JIM_OK) {
4444                 free(target->type);
4445                 free(target);
4446                 return e;
4447         }
4448
4449         if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4450                 /* default endian to little if not specified */
4451                 target->endianness = TARGET_LITTLE_ENDIAN;
4452         }
4453
4454         /* incase variant is not set */
4455         if (!target->variant)
4456                 target->variant = strdup("");
4457
4458         /* create the target specific commands */
4459         if (target->type->register_commands) {
4460                 (*(target->type->register_commands))(cmd_ctx);
4461         }
4462         if (target->type->target_create) {
4463                 (*(target->type->target_create))(target, goi->interp);
4464         }
4465
4466         /* append to end of list */
4467         {
4468                 target_t **tpp;
4469                 tpp = &(all_targets);
4470                 while (*tpp) {
4471                         tpp = &((*tpp)->next);
4472                 }
4473                 *tpp = target;
4474         }
4475
4476         cp = Jim_GetString(new_cmd, NULL);
4477         target->cmd_name = strdup(cp);
4478
4479         /* now - create the new target name command */
4480         e = Jim_CreateCommand(goi->interp,
4481                                                    /* name */
4482                                                    cp,
4483                                                    tcl_target_func, /* C function */
4484                                                    target, /* private data */
4485                                                    NULL); /* no del proc */
4486
4487         return e;
4488 }
4489
4490 static int jim_target(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4491 {
4492         int x,r,e;
4493         jim_wide w;
4494         struct command_context_s *cmd_ctx;
4495         target_t *target;
4496         Jim_GetOptInfo goi;
4497         enum tcmd {
4498                 /* TG = target generic */
4499                 TG_CMD_CREATE,
4500                 TG_CMD_TYPES,
4501                 TG_CMD_NAMES,
4502                 TG_CMD_CURRENT,
4503                 TG_CMD_NUMBER,
4504                 TG_CMD_COUNT,
4505         };
4506         const char *target_cmds[] = {
4507                 "create", "types", "names", "current", "number",
4508                 "count",
4509                 NULL /* terminate */
4510         };
4511
4512         LOG_DEBUG("Target command params:");
4513         LOG_DEBUG("%s", Jim_Debug_ArgvString(interp, argc, argv));
4514
4515         cmd_ctx = Jim_GetAssocData(interp, "context");
4516
4517         Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
4518
4519         if (goi.argc == 0) {
4520                 Jim_WrongNumArgs(interp, 1, argv, "missing: command ...");
4521                 return JIM_ERR;
4522         }
4523
4524         /* Jim_GetOpt_Debug(&goi); */
4525         r = Jim_GetOpt_Enum(&goi, target_cmds, &x);
4526         if (r != JIM_OK) {
4527                 return r;
4528         }
4529
4530         switch (x) {
4531         default:
4532                 Jim_Panic(goi.interp,"Why am I here?");
4533                 return JIM_ERR;
4534         case TG_CMD_CURRENT:
4535                 if (goi.argc != 0) {
4536                         Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4537                         return JIM_ERR;
4538                 }
4539                 Jim_SetResultString(goi.interp, get_current_target(cmd_ctx)->cmd_name, -1);
4540                 return JIM_OK;
4541         case TG_CMD_TYPES:
4542                 if (goi.argc != 0) {
4543                         Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4544                         return JIM_ERR;
4545                 }
4546                 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4547                 for (x = 0 ; target_types[x] ; x++) {
4548                         Jim_ListAppendElement(goi.interp,
4549                                                                    Jim_GetResult(goi.interp),
4550                                                                    Jim_NewStringObj(goi.interp, target_types[x]->name, -1));
4551                 }
4552                 return JIM_OK;
4553         case TG_CMD_NAMES:
4554                 if (goi.argc != 0) {
4555                         Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4556                         return JIM_ERR;
4557                 }
4558                 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4559                 target = all_targets;
4560                 while (target) {
4561                         Jim_ListAppendElement(goi.interp,
4562                                                                    Jim_GetResult(goi.interp),
4563                                                                    Jim_NewStringObj(goi.interp, target->cmd_name, -1));
4564                         target = target->next;
4565                 }
4566                 return JIM_OK;
4567         case TG_CMD_CREATE:
4568                 if (goi.argc < 3) {
4569                         Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "?name  ... config options ...");
4570                         return JIM_ERR;
4571                 }
4572                 return target_create(&goi);
4573                 break;
4574         case TG_CMD_NUMBER:
4575                 /* It's OK to remove this mechanism sometime after August 2010 or so */
4576                 LOG_WARNING("don't use numbers as target identifiers; use names");
4577                 if (goi.argc != 1) {
4578                         Jim_SetResult_sprintf(goi.interp, "expected: target number ?NUMBER?");
4579                         return JIM_ERR;
4580                 }
4581                 e = Jim_GetOpt_Wide(&goi, &w);
4582                 if (e != JIM_OK) {
4583                         return JIM_ERR;
4584                 }
4585                 for (x = 0, target = all_targets; target; target = target->next, x++) {
4586                         if (target->target_number == w)
4587                                 break;
4588                 }
4589                 if (target == NULL) {
4590                         Jim_SetResult_sprintf(goi.interp,
4591                                         "Target: number %d does not exist", (int)(w));
4592                         return JIM_ERR;
4593                 }
4594                 Jim_SetResultString(goi.interp, target->cmd_name, -1);
4595                 return JIM_OK;
4596         case TG_CMD_COUNT:
4597                 if (goi.argc != 0) {
4598                         Jim_WrongNumArgs(goi.interp, 0, goi.argv, "<no parameters>");
4599                         return JIM_ERR;
4600                 }
4601                 for (x = 0, target = all_targets; target; target = target->next, x++)
4602                         continue;
4603                 Jim_SetResult(goi.interp, Jim_NewIntObj(goi.interp, x));
4604                 return JIM_OK;
4605         }
4606
4607         return JIM_ERR;
4608 }
4609
4610
4611 struct FastLoad
4612 {
4613         uint32_t address;
4614         uint8_t *data;
4615         int length;
4616
4617 };
4618
4619 static int fastload_num;
4620 static struct FastLoad *fastload;
4621
4622 static void free_fastload(void)
4623 {
4624         if (fastload != NULL)
4625         {
4626                 int i;
4627                 for (i = 0; i < fastload_num; i++)
4628                 {
4629                         if (fastload[i].data)
4630                                 free(fastload[i].data);
4631                 }
4632                 free(fastload);
4633                 fastload = NULL;
4634         }
4635 }
4636
4637
4638
4639
4640 static int handle_fast_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4641 {
4642         uint8_t *buffer;
4643         uint32_t buf_cnt;
4644         uint32_t image_size;
4645         uint32_t min_address = 0;
4646         uint32_t max_address = 0xffffffff;
4647         int i;
4648
4649         image_t image;
4650
4651         int retval = parse_load_image_command_args(cmd_ctx, args, argc,
4652                         &image, &min_address, &max_address);
4653         if (ERROR_OK != retval)
4654                 return retval;
4655
4656         struct duration bench;
4657         duration_start(&bench);
4658
4659         if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
4660         {
4661                 return ERROR_OK;
4662         }
4663
4664         image_size = 0x0;
4665         retval = ERROR_OK;
4666         fastload_num = image.num_sections;
4667         fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4668         if (fastload == NULL)
4669         {
4670                 image_close(&image);
4671                 return ERROR_FAIL;
4672         }
4673         memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4674         for (i = 0; i < image.num_sections; i++)
4675         {
4676                 buffer = malloc(image.sections[i].size);
4677                 if (buffer == NULL)
4678                 {
4679                         command_print(cmd_ctx, "error allocating buffer for section (%d bytes)",
4680                                                   (int)(image.sections[i].size));
4681                         break;
4682                 }
4683
4684                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4685                 {
4686                         free(buffer);
4687                         break;
4688                 }
4689
4690                 uint32_t offset = 0;
4691                 uint32_t length = buf_cnt;
4692
4693
4694                 /* DANGER!!! beware of unsigned comparision here!!! */
4695
4696                 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
4697                                 (image.sections[i].base_address < max_address))
4698                 {
4699                         if (image.sections[i].base_address < min_address)
4700                         {
4701                                 /* clip addresses below */
4702                                 offset += min_address-image.sections[i].base_address;
4703                                 length -= offset;
4704                         }
4705
4706                         if (image.sections[i].base_address + buf_cnt > max_address)
4707                         {
4708                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
4709                         }
4710
4711                         fastload[i].address = image.sections[i].base_address + offset;
4712                         fastload[i].data = malloc(length);
4713                         if (fastload[i].data == NULL)
4714                         {
4715                                 free(buffer);
4716                                 break;
4717                         }
4718                         memcpy(fastload[i].data, buffer + offset, length);
4719                         fastload[i].length = length;
4720
4721                         image_size += length;
4722                         command_print(cmd_ctx, "%u bytes written at address 0x%8.8x",
4723                                                   (unsigned int)length,
4724                                                   ((unsigned int)(image.sections[i].base_address + offset)));
4725                 }
4726
4727                 free(buffer);
4728         }
4729
4730         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
4731         {
4732                 command_print(cmd_ctx, "Loaded %" PRIu32 " bytes "
4733                                 "in %fs (%0.3f kb/s)", image_size, 
4734                                 duration_elapsed(&bench), duration_kbps(&bench, image_size));
4735
4736                 command_print(cmd_ctx,
4737                                 "WARNING: image has not been loaded to target!"
4738                                 "You can issue a 'fast_load' to finish loading.");
4739         }
4740
4741         image_close(&image);
4742
4743         if (retval != ERROR_OK)
4744         {
4745                 free_fastload();
4746         }
4747
4748         return retval;
4749 }
4750
4751 static int handle_fast_load_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4752 {
4753         if (argc > 0)
4754                 return ERROR_COMMAND_SYNTAX_ERROR;
4755         if (fastload == NULL)
4756         {
4757                 LOG_ERROR("No image in memory");
4758                 return ERROR_FAIL;
4759         }
4760         int i;
4761         int ms = timeval_ms();
4762         int size = 0;
4763         int retval = ERROR_OK;
4764         for (i = 0; i < fastload_num;i++)
4765         {
4766                 target_t *target = get_current_target(cmd_ctx);
4767                 command_print(cmd_ctx, "Write to 0x%08x, length 0x%08x",
4768                                           (unsigned int)(fastload[i].address),
4769                                           (unsigned int)(fastload[i].length));
4770                 if (retval == ERROR_OK)
4771                 {
4772                         retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
4773                 }
4774                 size += fastload[i].length;
4775         }
4776         int after = timeval_ms();
4777         command_print(cmd_ctx, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
4778         return retval;
4779 }
4780
4781 static int jim_mcrmrc(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4782 {
4783         command_context_t *context;
4784         target_t *target;
4785         int retval;
4786
4787         context = Jim_GetAssocData(interp, "context");
4788         if (context == NULL) {
4789                 LOG_ERROR("array2mem: no command context");
4790                 return JIM_ERR;
4791         }
4792         target = get_current_target(context);
4793         if (target == NULL) {
4794                 LOG_ERROR("array2mem: no current target");
4795                 return JIM_ERR;
4796         }
4797
4798         if ((argc < 6) || (argc > 7))
4799         {
4800                 return JIM_ERR;
4801         }
4802
4803         int cpnum;
4804         uint32_t op1;
4805         uint32_t op2;
4806         uint32_t CRn;
4807         uint32_t CRm;
4808         uint32_t value;
4809
4810         int e;
4811         long l;
4812         e = Jim_GetLong(interp, argv[1], &l);
4813         if (e != JIM_OK) {
4814                 return e;
4815         }
4816         cpnum = l;
4817
4818         e = Jim_GetLong(interp, argv[2], &l);
4819         if (e != JIM_OK) {
4820                 return e;
4821         }
4822         op1 = l;
4823
4824         e = Jim_GetLong(interp, argv[3], &l);
4825         if (e != JIM_OK) {
4826                 return e;
4827         }
4828         CRn = l;
4829
4830         e = Jim_GetLong(interp, argv[4], &l);
4831         if (e != JIM_OK) {
4832                 return e;
4833         }
4834         CRm = l;
4835
4836         e = Jim_GetLong(interp, argv[5], &l);
4837         if (e != JIM_OK) {
4838                 return e;
4839         }
4840         op2 = l;
4841
4842         value = 0;
4843
4844         if (argc == 7)
4845         {
4846                 e = Jim_GetLong(interp, argv[6], &l);
4847                 if (e != JIM_OK) {
4848                         return e;
4849                 }
4850                 value = l;
4851
4852                 retval = target_mcr(target, cpnum, op1, op2, CRn, CRm, value);
4853                 if (retval != ERROR_OK)
4854                         return JIM_ERR;
4855         } else
4856         {
4857                 retval = target_mrc(target, cpnum, op1, op2, CRn, CRm, &value);
4858                 if (retval != ERROR_OK)
4859                         return JIM_ERR;
4860
4861                 Jim_SetResult(interp, Jim_NewIntObj(interp, value));
4862         }
4863
4864         return JIM_OK;
4865 }