Improve target.c command argument parsing.
[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                 retval = target->type->mmu(target, &enabled);
1119                 if (retval != ERROR_OK)
1120                 {
1121                         return retval;
1122                 }
1123
1124                 if (enabled)
1125                 {
1126                         if (target->working_area_phys_spec)
1127                         {
1128                                 LOG_DEBUG("MMU disabled, using physical address for working memory 0x%08x", (unsigned)target->working_area_phys);
1129                                 target->working_area = target->working_area_phys;
1130                         } else
1131                         {
1132                                 LOG_ERROR("No working memory available. Specify -work-area-phys to target.");
1133                                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1134                         }
1135                 } else
1136                 {
1137                         if (target->working_area_virt_spec)
1138                         {
1139                                 LOG_DEBUG("MMU enabled, using virtual address for working memory 0x%08x", (unsigned)target->working_area_virt);
1140                                 target->working_area = target->working_area_virt;
1141                         } else
1142                         {
1143                                 LOG_ERROR("No working memory available. Specify -work-area-virt to target.");
1144                                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1145                         }
1146                 }
1147         }
1148
1149         /* only allocate multiples of 4 byte */
1150         if (size % 4)
1151         {
1152                 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes (0x%08x), padding", ((unsigned)(size)));
1153                 size = (size + 3) & (~3);
1154         }
1155
1156         /* see if there's already a matching working area */
1157         while (c)
1158         {
1159                 if ((c->free) && (c->size == size))
1160                 {
1161                         new_wa = c;
1162                         break;
1163                 }
1164                 c = c->next;
1165         }
1166
1167         /* if not, allocate a new one */
1168         if (!new_wa)
1169         {
1170                 working_area_t **p = &target->working_areas;
1171                 uint32_t first_free = target->working_area;
1172                 uint32_t free_size = target->working_area_size;
1173
1174                 c = target->working_areas;
1175                 while (c)
1176                 {
1177                         first_free += c->size;
1178                         free_size -= c->size;
1179                         p = &c->next;
1180                         c = c->next;
1181                 }
1182
1183                 if (free_size < size)
1184                 {
1185                         LOG_WARNING("not enough working area available(requested %u, free %u)",
1186                                     (unsigned)(size), (unsigned)(free_size));
1187                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1188                 }
1189
1190                 LOG_DEBUG("allocated new working area at address 0x%08x", (unsigned)first_free);
1191
1192                 new_wa = malloc(sizeof(working_area_t));
1193                 new_wa->next = NULL;
1194                 new_wa->size = size;
1195                 new_wa->address = first_free;
1196
1197                 if (target->backup_working_area)
1198                 {
1199                         int retval;
1200                         new_wa->backup = malloc(new_wa->size);
1201                         if ((retval = target_read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup)) != ERROR_OK)
1202                         {
1203                                 free(new_wa->backup);
1204                                 free(new_wa);
1205                                 return retval;
1206                         }
1207                 }
1208                 else
1209                 {
1210                         new_wa->backup = NULL;
1211                 }
1212
1213                 /* put new entry in list */
1214                 *p = new_wa;
1215         }
1216
1217         /* mark as used, and return the new (reused) area */
1218         new_wa->free = 0;
1219         *area = new_wa;
1220
1221         /* user pointer */
1222         new_wa->user = area;
1223
1224         return ERROR_OK;
1225 }
1226
1227 int target_free_working_area_restore(struct target_s *target, working_area_t *area, int restore)
1228 {
1229         if (area->free)
1230                 return ERROR_OK;
1231
1232         if (restore && target->backup_working_area)
1233         {
1234                 int retval;
1235                 if ((retval = target_write_memory(target, area->address, 4, area->size / 4, area->backup)) != ERROR_OK)
1236                         return retval;
1237         }
1238
1239         area->free = 1;
1240
1241         /* mark user pointer invalid */
1242         *area->user = NULL;
1243         area->user = NULL;
1244
1245         return ERROR_OK;
1246 }
1247
1248 int target_free_working_area(struct target_s *target, working_area_t *area)
1249 {
1250         return target_free_working_area_restore(target, area, 1);
1251 }
1252
1253 /* free resources and restore memory, if restoring memory fails,
1254  * free up resources anyway
1255  */
1256 void target_free_all_working_areas_restore(struct target_s *target, int restore)
1257 {
1258         working_area_t *c = target->working_areas;
1259
1260         while (c)
1261         {
1262                 working_area_t *next = c->next;
1263                 target_free_working_area_restore(target, c, restore);
1264
1265                 if (c->backup)
1266                         free(c->backup);
1267
1268                 free(c);
1269
1270                 c = next;
1271         }
1272
1273         target->working_areas = NULL;
1274 }
1275
1276 void target_free_all_working_areas(struct target_s *target)
1277 {
1278         target_free_all_working_areas_restore(target, 1);
1279 }
1280
1281 int target_register_commands(struct command_context_s *cmd_ctx)
1282 {
1283
1284         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)");
1285
1286
1287
1288
1289         register_jim(cmd_ctx, "target", jim_target, "configure target");
1290
1291         return ERROR_OK;
1292 }
1293
1294 int target_arch_state(struct target_s *target)
1295 {
1296         int retval;
1297         if (target == NULL)
1298         {
1299                 LOG_USER("No target has been configured");
1300                 return ERROR_OK;
1301         }
1302
1303         LOG_USER("target state: %s", target_state_name( target ));
1304
1305         if (target->state != TARGET_HALTED)
1306                 return ERROR_OK;
1307
1308         retval = target->type->arch_state(target);
1309         return retval;
1310 }
1311
1312 /* Single aligned words are guaranteed to use 16 or 32 bit access
1313  * mode respectively, otherwise data is handled as quickly as
1314  * possible
1315  */
1316 int target_write_buffer(struct target_s *target, uint32_t address, uint32_t size, uint8_t *buffer)
1317 {
1318         int retval;
1319         LOG_DEBUG("writing buffer of %i byte at 0x%8.8x",
1320                   (int)size, (unsigned)address);
1321
1322         if (!target_was_examined(target))
1323         {
1324                 LOG_ERROR("Target not examined yet");
1325                 return ERROR_FAIL;
1326         }
1327
1328         if (size == 0) {
1329                 return ERROR_OK;
1330         }
1331
1332         if ((address + size - 1) < address)
1333         {
1334                 /* GDB can request this when e.g. PC is 0xfffffffc*/
1335                 LOG_ERROR("address + size wrapped(0x%08x, 0x%08x)",
1336                                   (unsigned)address,
1337                                   (unsigned)size);
1338                 return ERROR_FAIL;
1339         }
1340
1341         if (((address % 2) == 0) && (size == 2))
1342         {
1343                 return target_write_memory(target, address, 2, 1, buffer);
1344         }
1345
1346         /* handle unaligned head bytes */
1347         if (address % 4)
1348         {
1349                 uint32_t unaligned = 4 - (address % 4);
1350
1351                 if (unaligned > size)
1352                         unaligned = size;
1353
1354                 if ((retval = target_write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1355                         return retval;
1356
1357                 buffer += unaligned;
1358                 address += unaligned;
1359                 size -= unaligned;
1360         }
1361
1362         /* handle aligned words */
1363         if (size >= 4)
1364         {
1365                 int aligned = size - (size % 4);
1366
1367                 /* use bulk writes above a certain limit. This may have to be changed */
1368                 if (aligned > 128)
1369                 {
1370                         if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
1371                                 return retval;
1372                 }
1373                 else
1374                 {
1375                         if ((retval = target_write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1376                                 return retval;
1377                 }
1378
1379                 buffer += aligned;
1380                 address += aligned;
1381                 size -= aligned;
1382         }
1383
1384         /* handle tail writes of less than 4 bytes */
1385         if (size > 0)
1386         {
1387                 if ((retval = target_write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1388                         return retval;
1389         }
1390
1391         return ERROR_OK;
1392 }
1393
1394 /* Single aligned words are guaranteed to use 16 or 32 bit access
1395  * mode respectively, otherwise data is handled as quickly as
1396  * possible
1397  */
1398 int target_read_buffer(struct target_s *target, uint32_t address, uint32_t size, uint8_t *buffer)
1399 {
1400         int retval;
1401         LOG_DEBUG("reading buffer of %i byte at 0x%8.8x",
1402                           (int)size, (unsigned)address);
1403
1404         if (!target_was_examined(target))
1405         {
1406                 LOG_ERROR("Target not examined yet");
1407                 return ERROR_FAIL;
1408         }
1409
1410         if (size == 0) {
1411                 return ERROR_OK;
1412         }
1413
1414         if ((address + size - 1) < address)
1415         {
1416                 /* GDB can request this when e.g. PC is 0xfffffffc*/
1417                 LOG_ERROR("address + size wrapped(0x%08" PRIx32 ", 0x%08" PRIx32 ")",
1418                                   address,
1419                                   size);
1420                 return ERROR_FAIL;
1421         }
1422
1423         if (((address % 2) == 0) && (size == 2))
1424         {
1425                 return target_read_memory(target, address, 2, 1, buffer);
1426         }
1427
1428         /* handle unaligned head bytes */
1429         if (address % 4)
1430         {
1431                 uint32_t unaligned = 4 - (address % 4);
1432
1433                 if (unaligned > size)
1434                         unaligned = size;
1435
1436                 if ((retval = target_read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1437                         return retval;
1438
1439                 buffer += unaligned;
1440                 address += unaligned;
1441                 size -= unaligned;
1442         }
1443
1444         /* handle aligned words */
1445         if (size >= 4)
1446         {
1447                 int aligned = size - (size % 4);
1448
1449                 if ((retval = target_read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1450                         return retval;
1451
1452                 buffer += aligned;
1453                 address += aligned;
1454                 size -= aligned;
1455         }
1456
1457         /*prevent byte access when possible (avoid AHB access limitations in some cases)*/
1458         if(size >=2)
1459         {
1460                 int aligned = size - (size%2);
1461                 retval = target_read_memory(target, address, 2, aligned / 2, buffer);
1462                 if (retval != ERROR_OK)
1463                         return retval;
1464
1465                 buffer += aligned;
1466                 address += aligned;
1467                 size -= aligned;
1468         }
1469         /* handle tail writes of less than 4 bytes */
1470         if (size > 0)
1471         {
1472                 if ((retval = target_read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1473                         return retval;
1474         }
1475
1476         return ERROR_OK;
1477 }
1478
1479 int target_checksum_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t* crc)
1480 {
1481         uint8_t *buffer;
1482         int retval;
1483         uint32_t i;
1484         uint32_t checksum = 0;
1485         if (!target_was_examined(target))
1486         {
1487                 LOG_ERROR("Target not examined yet");
1488                 return ERROR_FAIL;
1489         }
1490
1491         if ((retval = target->type->checksum_memory(target, address,
1492                 size, &checksum)) != ERROR_OK)
1493         {
1494                 buffer = malloc(size);
1495                 if (buffer == NULL)
1496                 {
1497                         LOG_ERROR("error allocating buffer for section (%d bytes)", (int)size);
1498                         return ERROR_INVALID_ARGUMENTS;
1499                 }
1500                 retval = target_read_buffer(target, address, size, buffer);
1501                 if (retval != ERROR_OK)
1502                 {
1503                         free(buffer);
1504                         return retval;
1505                 }
1506
1507                 /* convert to target endianess */
1508                 for (i = 0; i < (size/sizeof(uint32_t)); i++)
1509                 {
1510                         uint32_t target_data;
1511                         target_data = target_buffer_get_u32(target, &buffer[i*sizeof(uint32_t)]);
1512                         target_buffer_set_u32(target, &buffer[i*sizeof(uint32_t)], target_data);
1513                 }
1514
1515                 retval = image_calculate_checksum(buffer, size, &checksum);
1516                 free(buffer);
1517         }
1518
1519         *crc = checksum;
1520
1521         return retval;
1522 }
1523
1524 int target_blank_check_memory(struct target_s *target, uint32_t address, uint32_t size, uint32_t* blank)
1525 {
1526         int retval;
1527         if (!target_was_examined(target))
1528         {
1529                 LOG_ERROR("Target not examined yet");
1530                 return ERROR_FAIL;
1531         }
1532
1533         if (target->type->blank_check_memory == 0)
1534                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1535
1536         retval = target->type->blank_check_memory(target, address, size, blank);
1537
1538         return retval;
1539 }
1540
1541 int target_read_u32(struct target_s *target, uint32_t address, uint32_t *value)
1542 {
1543         uint8_t value_buf[4];
1544         if (!target_was_examined(target))
1545         {
1546                 LOG_ERROR("Target not examined yet");
1547                 return ERROR_FAIL;
1548         }
1549
1550         int retval = target_read_memory(target, address, 4, 1, value_buf);
1551
1552         if (retval == ERROR_OK)
1553         {
1554                 *value = target_buffer_get_u32(target, value_buf);
1555                 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1556                                   address,
1557                                   *value);
1558         }
1559         else
1560         {
1561                 *value = 0x0;
1562                 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1563                                   address);
1564         }
1565
1566         return retval;
1567 }
1568
1569 int target_read_u16(struct target_s *target, uint32_t address, uint16_t *value)
1570 {
1571         uint8_t value_buf[2];
1572         if (!target_was_examined(target))
1573         {
1574                 LOG_ERROR("Target not examined yet");
1575                 return ERROR_FAIL;
1576         }
1577
1578         int retval = target_read_memory(target, address, 2, 1, value_buf);
1579
1580         if (retval == ERROR_OK)
1581         {
1582                 *value = target_buffer_get_u16(target, value_buf);
1583                 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%4.4x",
1584                                   address,
1585                                   *value);
1586         }
1587         else
1588         {
1589                 *value = 0x0;
1590                 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1591                                   address);
1592         }
1593
1594         return retval;
1595 }
1596
1597 int target_read_u8(struct target_s *target, uint32_t address, uint8_t *value)
1598 {
1599         int retval = target_read_memory(target, address, 1, 1, value);
1600         if (!target_was_examined(target))
1601         {
1602                 LOG_ERROR("Target not examined yet");
1603                 return ERROR_FAIL;
1604         }
1605
1606         if (retval == ERROR_OK)
1607         {
1608                 LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1609                                   address,
1610                                   *value);
1611         }
1612         else
1613         {
1614                 *value = 0x0;
1615                 LOG_DEBUG("address: 0x%8.8" PRIx32 " failed",
1616                                   address);
1617         }
1618
1619         return retval;
1620 }
1621
1622 int target_write_u32(struct target_s *target, uint32_t address, uint32_t value)
1623 {
1624         int retval;
1625         uint8_t value_buf[4];
1626         if (!target_was_examined(target))
1627         {
1628                 LOG_ERROR("Target not examined yet");
1629                 return ERROR_FAIL;
1630         }
1631
1632         LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8" PRIx32 "",
1633                           address,
1634                           value);
1635
1636         target_buffer_set_u32(target, value_buf, value);
1637         if ((retval = target_write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1638         {
1639                 LOG_DEBUG("failed: %i", retval);
1640         }
1641
1642         return retval;
1643 }
1644
1645 int target_write_u16(struct target_s *target, uint32_t address, uint16_t value)
1646 {
1647         int retval;
1648         uint8_t value_buf[2];
1649         if (!target_was_examined(target))
1650         {
1651                 LOG_ERROR("Target not examined yet");
1652                 return ERROR_FAIL;
1653         }
1654
1655         LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%8.8x",
1656                           address,
1657                           value);
1658
1659         target_buffer_set_u16(target, value_buf, value);
1660         if ((retval = target_write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1661         {
1662                 LOG_DEBUG("failed: %i", retval);
1663         }
1664
1665         return retval;
1666 }
1667
1668 int target_write_u8(struct target_s *target, uint32_t address, uint8_t value)
1669 {
1670         int retval;
1671         if (!target_was_examined(target))
1672         {
1673                 LOG_ERROR("Target not examined yet");
1674                 return ERROR_FAIL;
1675         }
1676
1677         LOG_DEBUG("address: 0x%8.8" PRIx32 ", value: 0x%2.2x",
1678                           address, value);
1679
1680         if ((retval = target_write_memory(target, address, 1, 1, &value)) != ERROR_OK)
1681         {
1682                 LOG_DEBUG("failed: %i", retval);
1683         }
1684
1685         return retval;
1686 }
1687
1688 int target_register_user_commands(struct command_context_s *cmd_ctx)
1689 {
1690         int retval = ERROR_OK;
1691
1692
1693         /* script procedures */
1694         register_command(cmd_ctx, NULL, "profile", handle_profile_command, COMMAND_EXEC, "profiling samples the CPU PC");
1695         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>");
1696         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>");
1697
1698         register_command(cmd_ctx, NULL, "fast_load_image", handle_fast_load_image_command, COMMAND_ANY,
1699                         "same args as load_image, image stored in memory - mainly for profiling purposes");
1700
1701         register_command(cmd_ctx, NULL, "fast_load", handle_fast_load_command, COMMAND_ANY,
1702                         "loads active fast load image to current target - mainly for profiling purposes");
1703
1704
1705         register_command(cmd_ctx, NULL, "virt2phys", handle_virt2phys_command, COMMAND_ANY, "translate a virtual address into a physical address");
1706         register_command(cmd_ctx,  NULL, "reg", handle_reg_command, COMMAND_EXEC, "display or set a register");
1707         register_command(cmd_ctx,  NULL, "poll", handle_poll_command, COMMAND_EXEC, "poll target state");
1708         register_command(cmd_ctx,  NULL, "wait_halt", handle_wait_halt_command, COMMAND_EXEC, "wait for target halt [time (s)]");
1709         register_command(cmd_ctx,  NULL, "halt", handle_halt_command, COMMAND_EXEC, "halt target");
1710         register_command(cmd_ctx,  NULL, "resume", handle_resume_command, COMMAND_EXEC, "resume target [addr]");
1711         register_command(cmd_ctx,  NULL, "step", handle_step_command, COMMAND_EXEC, "step one instruction from current PC or [addr]");
1712         register_command(cmd_ctx,  NULL, "reset", handle_reset_command, COMMAND_EXEC, "reset target [run | halt | init] - default is run");
1713         register_command(cmd_ctx,  NULL, "soft_reset_halt", handle_soft_reset_halt_command, COMMAND_EXEC, "halt the target and do a soft reset");
1714
1715         register_command(cmd_ctx,  NULL, "mdw", handle_md_command, COMMAND_EXEC, "display memory words [phys] <addr> [count]");
1716         register_command(cmd_ctx,  NULL, "mdh", handle_md_command, COMMAND_EXEC, "display memory half-words [phys] <addr> [count]");
1717         register_command(cmd_ctx,  NULL, "mdb", handle_md_command, COMMAND_EXEC, "display memory bytes [phys] <addr> [count]");
1718
1719         register_command(cmd_ctx,  NULL, "mww", handle_mw_command, COMMAND_EXEC, "write memory word [phys]  <addr> <value> [count]");
1720         register_command(cmd_ctx,  NULL, "mwh", handle_mw_command, COMMAND_EXEC, "write memory half-word [phys]  <addr> <value> [count]");
1721         register_command(cmd_ctx,  NULL, "mwb", handle_mw_command, COMMAND_EXEC, "write memory byte [phys] <addr> <value> [count]");
1722
1723         register_command(cmd_ctx,  NULL, "bp",
1724                         handle_bp_command, COMMAND_EXEC,
1725                         "list or set breakpoint [<address> <length> [hw]]");
1726         register_command(cmd_ctx,  NULL, "rbp",
1727                         handle_rbp_command, COMMAND_EXEC,
1728                         "remove breakpoint <address>");
1729         register_command(cmd_ctx,  NULL, "wp",
1730                         handle_wp_command, COMMAND_EXEC,
1731                         "list or set watchpoint "
1732                                 "[<address> <length> <r/w/a> [value] [mask]]");
1733         register_command(cmd_ctx,  NULL, "rwp",
1734                         handle_rwp_command, COMMAND_EXEC,
1735                         "remove watchpoint <address>");
1736
1737         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]");
1738         register_command(cmd_ctx,  NULL, "dump_image", handle_dump_image_command, COMMAND_EXEC, "dump_image <file> <address> <size>");
1739         register_command(cmd_ctx,  NULL, "verify_image", handle_verify_image_command, COMMAND_EXEC, "verify_image <file> [offset] [type]");
1740         register_command(cmd_ctx,  NULL, "test_image", handle_test_image_command, COMMAND_EXEC, "test_image <file> [offset] [type]");
1741
1742         if ((retval = target_request_register_commands(cmd_ctx)) != ERROR_OK)
1743                 return retval;
1744         if ((retval = trace_register_commands(cmd_ctx)) != ERROR_OK)
1745                 return retval;
1746
1747         return retval;
1748 }
1749
1750 static int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1751 {
1752         target_t *target = all_targets;
1753
1754         if (argc == 1)
1755         {
1756                 target = get_target(args[0]);
1757                 if (target == NULL) {
1758                         command_print(cmd_ctx,"Target: %s is unknown, try one of:\n", args[0]);
1759                         goto DumpTargets;
1760                 }
1761                 if (!target->tap->enabled) {
1762                         command_print(cmd_ctx,"Target: TAP %s is disabled, "
1763                                         "can't be the current target\n",
1764                                         target->tap->dotted_name);
1765                         return ERROR_FAIL;
1766                 }
1767
1768                 cmd_ctx->current_target = target->target_number;
1769                 return ERROR_OK;
1770         }
1771 DumpTargets:
1772
1773         target = all_targets;
1774         command_print(cmd_ctx, "    TargetName         Type       Endian TapName            State       ");
1775         command_print(cmd_ctx, "--  ------------------ ---------- ------ ------------------ ------------");
1776         while (target)
1777         {
1778                 const char *state;
1779                 char marker = ' ';
1780
1781                 if (target->tap->enabled)
1782                         state = target_state_name( target );
1783                 else
1784                         state = "tap-disabled";
1785
1786                 if (cmd_ctx->current_target == target->target_number)
1787                         marker = '*';
1788
1789                 /* keep columns lined up to match the headers above */
1790                 command_print(cmd_ctx, "%2d%c %-18s %-10s %-6s %-18s %s",
1791                                           target->target_number,
1792                                           marker,
1793                                           target->cmd_name,
1794                                           target_get_name(target),
1795                                           Jim_Nvp_value2name_simple(nvp_target_endian,
1796                                                                 target->endianness)->name,
1797                                           target->tap->dotted_name,
1798                                           state);
1799                 target = target->next;
1800         }
1801
1802         return ERROR_OK;
1803 }
1804
1805 /* every 300ms we check for reset & powerdropout and issue a "reset halt" if so. */
1806
1807 static int powerDropout;
1808 static int srstAsserted;
1809
1810 static int runPowerRestore;
1811 static int runPowerDropout;
1812 static int runSrstAsserted;
1813 static int runSrstDeasserted;
1814
1815 static int sense_handler(void)
1816 {
1817         static int prevSrstAsserted = 0;
1818         static int prevPowerdropout = 0;
1819
1820         int retval;
1821         if ((retval = jtag_power_dropout(&powerDropout)) != ERROR_OK)
1822                 return retval;
1823
1824         int powerRestored;
1825         powerRestored = prevPowerdropout && !powerDropout;
1826         if (powerRestored)
1827         {
1828                 runPowerRestore = 1;
1829         }
1830
1831         long long current = timeval_ms();
1832         static long long lastPower = 0;
1833         int waitMore = lastPower + 2000 > current;
1834         if (powerDropout && !waitMore)
1835         {
1836                 runPowerDropout = 1;
1837                 lastPower = current;
1838         }
1839
1840         if ((retval = jtag_srst_asserted(&srstAsserted)) != ERROR_OK)
1841                 return retval;
1842
1843         int srstDeasserted;
1844         srstDeasserted = prevSrstAsserted && !srstAsserted;
1845
1846         static long long lastSrst = 0;
1847         waitMore = lastSrst + 2000 > current;
1848         if (srstDeasserted && !waitMore)
1849         {
1850                 runSrstDeasserted = 1;
1851                 lastSrst = current;
1852         }
1853
1854         if (!prevSrstAsserted && srstAsserted)
1855         {
1856                 runSrstAsserted = 1;
1857         }
1858
1859         prevSrstAsserted = srstAsserted;
1860         prevPowerdropout = powerDropout;
1861
1862         if (srstDeasserted || powerRestored)
1863         {
1864                 /* Other than logging the event we can't do anything here.
1865                  * Issuing a reset is a particularly bad idea as we might
1866                  * be inside a reset already.
1867                  */
1868         }
1869
1870         return ERROR_OK;
1871 }
1872
1873 static void target_call_event_callbacks_all(enum target_event e) {
1874         target_t *target;
1875         target = all_targets;
1876         while (target) {
1877                 target_call_event_callbacks(target, e);
1878                 target = target->next;
1879         }
1880 }
1881
1882 /* process target state changes */
1883 int handle_target(void *priv)
1884 {
1885         int retval = ERROR_OK;
1886
1887         /* we do not want to recurse here... */
1888         static int recursive = 0;
1889         if (! recursive)
1890         {
1891                 recursive = 1;
1892                 sense_handler();
1893                 /* danger! running these procedures can trigger srst assertions and power dropouts.
1894                  * We need to avoid an infinite loop/recursion here and we do that by
1895                  * clearing the flags after running these events.
1896                  */
1897                 int did_something = 0;
1898                 if (runSrstAsserted)
1899                 {
1900                         target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1901                         Jim_Eval(interp, "srst_asserted");
1902                         did_something = 1;
1903                 }
1904                 if (runSrstDeasserted)
1905                 {
1906                         Jim_Eval(interp, "srst_deasserted");
1907                         did_something = 1;
1908                 }
1909                 if (runPowerDropout)
1910                 {
1911                         target_call_event_callbacks_all(TARGET_EVENT_GDB_HALT);
1912                         Jim_Eval(interp, "power_dropout");
1913                         did_something = 1;
1914                 }
1915                 if (runPowerRestore)
1916                 {
1917                         Jim_Eval(interp, "power_restore");
1918                         did_something = 1;
1919                 }
1920
1921                 if (did_something)
1922                 {
1923                         /* clear detect flags */
1924                         sense_handler();
1925                 }
1926
1927                 /* clear action flags */
1928
1929                 runSrstAsserted = 0;
1930                 runSrstDeasserted = 0;
1931                 runPowerRestore = 0;
1932                 runPowerDropout = 0;
1933
1934                 recursive = 0;
1935         }
1936
1937         /* Poll targets for state changes unless that's globally disabled.
1938          * Skip targets that are currently disabled.
1939          */
1940         for (target_t *target = all_targets;
1941                         is_jtag_poll_safe() && target;
1942                         target = target->next)
1943         {
1944                 if (!target->tap->enabled)
1945                         continue;
1946
1947                 /* only poll target if we've got power and srst isn't asserted */
1948                 if (!powerDropout && !srstAsserted)
1949                 {
1950                         /* polling may fail silently until the target has been examined */
1951                         if ((retval = target_poll(target)) != ERROR_OK)
1952                         {
1953                                 target_call_event_callbacks(target, TARGET_EVENT_GDB_HALT);
1954                                 return retval;
1955                         }
1956                 }
1957         }
1958
1959         return retval;
1960 }
1961
1962 static int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1963 {
1964         target_t *target;
1965         reg_t *reg = NULL;
1966         int count = 0;
1967         char *value;
1968
1969         LOG_DEBUG("-");
1970
1971         target = get_current_target(cmd_ctx);
1972
1973         /* list all available registers for the current target */
1974         if (argc == 0)
1975         {
1976                 reg_cache_t *cache = target->reg_cache;
1977
1978                 count = 0;
1979                 while (cache)
1980                 {
1981                         int i;
1982
1983                         command_print(cmd_ctx, "===== %s", cache->name);
1984
1985                         for (i = 0, reg = cache->reg_list;
1986                                         i < cache->num_regs;
1987                                         i++, reg++, count++)
1988                         {
1989                                 /* only print cached values if they are valid */
1990                                 if (reg->valid) {
1991                                         value = buf_to_str(reg->value,
1992                                                         reg->size, 16);
1993                                         command_print(cmd_ctx,
1994                                                         "(%i) %s (/%" PRIu32 "): 0x%s%s",
1995                                                         count, reg->name,
1996                                                         reg->size, value,
1997                                                         reg->dirty
1998                                                                 ? " (dirty)"
1999                                                                 : "");
2000                                         free(value);
2001                                 } else {
2002                                         command_print(cmd_ctx, "(%i) %s (/%" PRIu32 ")",
2003                                                           count, reg->name,
2004                                                           reg->size) ;
2005                                 }
2006                         }
2007                         cache = cache->next;
2008                 }
2009
2010                 return ERROR_OK;
2011         }
2012
2013         /* access a single register by its ordinal number */
2014         if ((args[0][0] >= '0') && (args[0][0] <= '9'))
2015         {
2016                 unsigned num;
2017                 COMMAND_PARSE_NUMBER(uint, args[0], num);
2018
2019                 reg_cache_t *cache = target->reg_cache;
2020                 count = 0;
2021                 while (cache)
2022                 {
2023                         int i;
2024                         for (i = 0; i < cache->num_regs; i++)
2025                         {
2026                                 if (count++ == (int)num)
2027                                 {
2028                                         reg = &cache->reg_list[i];
2029                                         break;
2030                                 }
2031                         }
2032                         if (reg)
2033                                 break;
2034                         cache = cache->next;
2035                 }
2036
2037                 if (!reg)
2038                 {
2039                         command_print(cmd_ctx, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
2040                         return ERROR_OK;
2041                 }
2042         } else /* access a single register by its name */
2043         {
2044                 reg = register_get_by_name(target->reg_cache, args[0], 1);
2045
2046                 if (!reg)
2047                 {
2048                         command_print(cmd_ctx, "register %s not found in current target", args[0]);
2049                         return ERROR_OK;
2050                 }
2051         }
2052
2053         /* display a register */
2054         if ((argc == 1) || ((argc == 2) && !((args[1][0] >= '0') && (args[1][0] <= '9'))))
2055         {
2056                 if ((argc == 2) && (strcmp(args[1], "force") == 0))
2057                         reg->valid = 0;
2058
2059                 if (reg->valid == 0)
2060                 {
2061                         reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
2062                         arch_type->get(reg);
2063                 }
2064                 value = buf_to_str(reg->value, reg->size, 16);
2065                 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2066                 free(value);
2067                 return ERROR_OK;
2068         }
2069
2070         /* set register value */
2071         if (argc == 2)
2072         {
2073                 uint8_t *buf = malloc(CEIL(reg->size, 8));
2074                 str_to_buf(args[1], strlen(args[1]), buf, reg->size, 0);
2075
2076                 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
2077                 arch_type->set(reg, buf);
2078
2079                 value = buf_to_str(reg->value, reg->size, 16);
2080                 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, (int)(reg->size), value);
2081                 free(value);
2082
2083                 free(buf);
2084
2085                 return ERROR_OK;
2086         }
2087
2088         command_print(cmd_ctx, "usage: reg <#|name> [value]");
2089
2090         return ERROR_OK;
2091 }
2092
2093 static int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2094 {
2095         int retval = ERROR_OK;
2096         target_t *target = get_current_target(cmd_ctx);
2097
2098         if (argc == 0)
2099         {
2100                 command_print(cmd_ctx, "background polling: %s",
2101                                 jtag_poll_get_enabled() ? "on" : "off");
2102                 command_print(cmd_ctx, "TAP: %s (%s)",
2103                                 target->tap->dotted_name,
2104                                 target->tap->enabled ? "enabled" : "disabled");
2105                 if (!target->tap->enabled)
2106                         return ERROR_OK;
2107                 if ((retval = target_poll(target)) != ERROR_OK)
2108                         return retval;
2109                 if ((retval = target_arch_state(target)) != ERROR_OK)
2110                         return retval;
2111
2112         }
2113         else if (argc == 1)
2114         {
2115                 if (strcmp(args[0], "on") == 0)
2116                 {
2117                         jtag_poll_set_enabled(true);
2118                 }
2119                 else if (strcmp(args[0], "off") == 0)
2120                 {
2121                         jtag_poll_set_enabled(false);
2122                 }
2123                 else
2124                 {
2125                         command_print(cmd_ctx, "arg is \"on\" or \"off\"");
2126                 }
2127         } else
2128         {
2129                 return ERROR_COMMAND_SYNTAX_ERROR;
2130         }
2131
2132         return retval;
2133 }
2134
2135 static int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2136 {
2137         if (argc > 1)
2138                 return ERROR_COMMAND_SYNTAX_ERROR;
2139
2140         unsigned ms = 5000;
2141         if (1 == argc)
2142         {
2143                 int retval = parse_uint(args[0], &ms);
2144                 if (ERROR_OK != retval)
2145                 {
2146                         command_print(cmd_ctx, "usage: %s [seconds]", cmd);
2147                         return ERROR_COMMAND_SYNTAX_ERROR;
2148                 }
2149                 // convert seconds (given) to milliseconds (needed)
2150                 ms *= 1000;
2151         }
2152
2153         target_t *target = get_current_target(cmd_ctx);
2154         return target_wait_state(target, TARGET_HALTED, ms);
2155 }
2156
2157 /* wait for target state to change. The trick here is to have a low
2158  * latency for short waits and not to suck up all the CPU time
2159  * on longer waits.
2160  *
2161  * After 500ms, keep_alive() is invoked
2162  */
2163 int target_wait_state(target_t *target, enum target_state state, int ms)
2164 {
2165         int retval;
2166         long long then = 0, cur;
2167         int once = 1;
2168
2169         for (;;)
2170         {
2171                 if ((retval = target_poll(target)) != ERROR_OK)
2172                         return retval;
2173                 if (target->state == state)
2174                 {
2175                         break;
2176                 }
2177                 cur = timeval_ms();
2178                 if (once)
2179                 {
2180                         once = 0;
2181                         then = timeval_ms();
2182                         LOG_DEBUG("waiting for target %s...",
2183                                 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2184                 }
2185
2186                 if (cur-then > 500)
2187                 {
2188                         keep_alive();
2189                 }
2190
2191                 if ((cur-then) > ms)
2192                 {
2193                         LOG_ERROR("timed out while waiting for target %s",
2194                                 Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
2195                         return ERROR_FAIL;
2196                 }
2197         }
2198
2199         return ERROR_OK;
2200 }
2201
2202 static int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2203 {
2204         LOG_DEBUG("-");
2205
2206         target_t *target = get_current_target(cmd_ctx);
2207         int retval = target_halt(target);
2208         if (ERROR_OK != retval)
2209                 return retval;
2210
2211         if (argc == 1)
2212         {
2213                 unsigned wait;
2214                 retval = parse_uint(args[0], &wait);
2215                 if (ERROR_OK != retval)
2216                         return ERROR_COMMAND_SYNTAX_ERROR;
2217                 if (!wait)
2218                         return ERROR_OK;
2219         }
2220
2221         return handle_wait_halt_command(cmd_ctx, cmd, args, argc);
2222 }
2223
2224 static int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2225 {
2226         target_t *target = get_current_target(cmd_ctx);
2227
2228         LOG_USER("requesting target halt and executing a soft reset");
2229
2230         target->type->soft_reset_halt(target);
2231
2232         return ERROR_OK;
2233 }
2234
2235 static int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2236 {
2237         if (argc > 1)
2238                 return ERROR_COMMAND_SYNTAX_ERROR;
2239
2240         enum target_reset_mode reset_mode = RESET_RUN;
2241         if (argc == 1)
2242         {
2243                 const Jim_Nvp *n;
2244                 n = Jim_Nvp_name2value_simple(nvp_reset_modes, args[0]);
2245                 if ((n->name == NULL) || (n->value == RESET_UNKNOWN)) {
2246                         return ERROR_COMMAND_SYNTAX_ERROR;
2247                 }
2248                 reset_mode = n->value;
2249         }
2250
2251         /* reset *all* targets */
2252         return target_process_reset(cmd_ctx, reset_mode);
2253 }
2254
2255
2256 static int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2257 {
2258         int current = 1;
2259         if (argc > 1)
2260                 return ERROR_COMMAND_SYNTAX_ERROR;
2261
2262         target_t *target = get_current_target(cmd_ctx);
2263         target_handle_event(target, TARGET_EVENT_OLD_pre_resume);
2264
2265         /* with no args, resume from current pc, addr = 0,
2266          * with one arguments, addr = args[0],
2267          * handle breakpoints, not debugging */
2268         uint32_t addr = 0;
2269         if (argc == 1)
2270         {
2271                 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2272                 current = 0;
2273         }
2274
2275         return target_resume(target, current, addr, 1, 0);
2276 }
2277
2278 static int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2279 {
2280         if (argc > 1)
2281                 return ERROR_COMMAND_SYNTAX_ERROR;
2282
2283         LOG_DEBUG("-");
2284
2285         /* with no args, step from current pc, addr = 0,
2286          * with one argument addr = args[0],
2287          * handle breakpoints, debugging */
2288         uint32_t addr = 0;
2289         int current_pc = 1;
2290         if (argc == 1)
2291         {
2292                 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2293                 current_pc = 0;
2294         }
2295
2296         target_t *target = get_current_target(cmd_ctx);
2297
2298         return target->type->step(target, current_pc, addr, 1);
2299 }
2300
2301 static void handle_md_output(struct command_context_s *cmd_ctx,
2302                 struct target_s *target, uint32_t address, unsigned size,
2303                 unsigned count, const uint8_t *buffer)
2304 {
2305         const unsigned line_bytecnt = 32;
2306         unsigned line_modulo = line_bytecnt / size;
2307
2308         char output[line_bytecnt * 4 + 1];
2309         unsigned output_len = 0;
2310
2311         const char *value_fmt;
2312         switch (size) {
2313         case 4: value_fmt = "%8.8x "; break;
2314         case 2: value_fmt = "%4.2x "; break;
2315         case 1: value_fmt = "%2.2x "; break;
2316         default:
2317                 LOG_ERROR("invalid memory read size: %u", size);
2318                 exit(-1);
2319         }
2320
2321         for (unsigned i = 0; i < count; i++)
2322         {
2323                 if (i % line_modulo == 0)
2324                 {
2325                         output_len += snprintf(output + output_len,
2326                                         sizeof(output) - output_len,
2327                                         "0x%8.8x: ",
2328                                         (unsigned)(address + (i*size)));
2329                 }
2330
2331                 uint32_t value = 0;
2332                 const uint8_t *value_ptr = buffer + i * size;
2333                 switch (size) {
2334                 case 4: value = target_buffer_get_u32(target, value_ptr); break;
2335                 case 2: value = target_buffer_get_u16(target, value_ptr); break;
2336                 case 1: value = *value_ptr;
2337                 }
2338                 output_len += snprintf(output + output_len,
2339                                 sizeof(output) - output_len,
2340                                 value_fmt, value);
2341
2342                 if ((i % line_modulo == line_modulo - 1) || (i == count - 1))
2343                 {
2344                         command_print(cmd_ctx, "%s", output);
2345                         output_len = 0;
2346                 }
2347         }
2348 }
2349
2350 static int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2351 {
2352         if (argc < 1)
2353                 return ERROR_COMMAND_SYNTAX_ERROR;
2354
2355         unsigned size = 0;
2356         switch (cmd[2]) {
2357         case 'w': size = 4; break;
2358         case 'h': size = 2; break;
2359         case 'b': size = 1; break;
2360         default: return ERROR_COMMAND_SYNTAX_ERROR;
2361         }
2362
2363         bool physical=strcmp(args[0], "phys")==0;
2364         int (*fn)(struct target_s *target,
2365                         uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2366         if (physical)
2367         {
2368                 argc--;
2369                 args++;
2370                 fn=target_read_phys_memory;
2371         } else
2372         {
2373                 fn=target_read_memory;
2374         }
2375         if ((argc < 1) || (argc > 2))
2376         {
2377                 return ERROR_COMMAND_SYNTAX_ERROR;
2378         }
2379
2380         uint32_t address;
2381         COMMAND_PARSE_NUMBER(u32, args[0], address);
2382
2383         unsigned count = 1;
2384         if (argc == 2)
2385                 COMMAND_PARSE_NUMBER(uint, args[1], count);
2386
2387         uint8_t *buffer = calloc(count, size);
2388
2389         target_t *target = get_current_target(cmd_ctx);
2390         int retval = fn(target, address, size, count, buffer);
2391         if (ERROR_OK == retval)
2392                 handle_md_output(cmd_ctx, target, address, size, count, buffer);
2393
2394         free(buffer);
2395
2396         return retval;
2397 }
2398
2399 static int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2400 {
2401         if (argc < 2)
2402         {
2403                 return ERROR_COMMAND_SYNTAX_ERROR;
2404         }
2405         bool physical=strcmp(args[0], "phys")==0;
2406         int (*fn)(struct target_s *target,
2407                         uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer);
2408         if (physical)
2409         {
2410                 argc--;
2411                 args++;
2412                 fn=target_write_phys_memory;
2413         } else
2414         {
2415                 fn=target_write_memory;
2416         }
2417         if ((argc < 2) || (argc > 3))
2418                 return ERROR_COMMAND_SYNTAX_ERROR;
2419
2420         uint32_t address;
2421         COMMAND_PARSE_NUMBER(u32, args[0], address);
2422
2423         uint32_t value;
2424         COMMAND_PARSE_NUMBER(u32, args[1], value);
2425
2426         unsigned count = 1;
2427         if (argc == 3)
2428                 COMMAND_PARSE_NUMBER(uint, args[2], count);
2429
2430         target_t *target = get_current_target(cmd_ctx);
2431         unsigned wordsize;
2432         uint8_t value_buf[4];
2433         switch (cmd[2])
2434         {
2435                 case 'w':
2436                         wordsize = 4;
2437                         target_buffer_set_u32(target, value_buf, value);
2438                         break;
2439                 case 'h':
2440                         wordsize = 2;
2441                         target_buffer_set_u16(target, value_buf, value);
2442                         break;
2443                 case 'b':
2444                         wordsize = 1;
2445                         value_buf[0] = value;
2446                         break;
2447                 default:
2448                         return ERROR_COMMAND_SYNTAX_ERROR;
2449         }
2450         for (unsigned i = 0; i < count; i++)
2451         {
2452                 int retval = fn(target,
2453                                 address + i * wordsize, wordsize, 1, value_buf);
2454                 if (ERROR_OK != retval)
2455                         return retval;
2456                 keep_alive();
2457         }
2458
2459         return ERROR_OK;
2460
2461 }
2462
2463 static int parse_load_image_command_args(struct command_context_s *cmd_ctx,
2464                 char **args, int argc, image_t *image,
2465                 uint32_t *min_address, uint32_t *max_address)
2466 {
2467         if (argc < 1 || argc > 5)
2468                 return ERROR_COMMAND_SYNTAX_ERROR;
2469
2470         /* a base address isn't always necessary,
2471          * default to 0x0 (i.e. don't relocate) */
2472         if (argc >= 2)
2473         {
2474                 uint32_t addr;
2475                 COMMAND_PARSE_NUMBER(u32, args[1], addr);
2476                 image->base_address = addr;
2477                 image->base_address_set = 1;
2478         }
2479         else
2480                 image->base_address_set = 0;
2481
2482         image->start_address_set = 0;
2483
2484         if (argc >= 4)
2485         {
2486                 COMMAND_PARSE_NUMBER(u32, args[3], *min_address);
2487         }
2488         if (argc == 5)
2489         {
2490                 COMMAND_PARSE_NUMBER(u32, args[4], *max_address);
2491                 // use size (given) to find max (required)
2492                 *max_address += *min_address;
2493         }
2494
2495         if (*min_address > *max_address)
2496                 return ERROR_COMMAND_SYNTAX_ERROR;
2497
2498         return ERROR_OK;
2499 }
2500
2501 static int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2502 {
2503         uint8_t *buffer;
2504         uint32_t buf_cnt;
2505         uint32_t image_size;
2506         uint32_t min_address = 0;
2507         uint32_t max_address = 0xffffffff;
2508         int i;
2509         int retvaltemp;
2510
2511         image_t image;
2512
2513         duration_t duration;
2514         char *duration_text;
2515
2516         int retval = parse_load_image_command_args(cmd_ctx, args, argc,
2517                         &image, &min_address, &max_address);
2518         if (ERROR_OK != retval)
2519                 return retval;
2520
2521         target_t *target = get_current_target(cmd_ctx);
2522         duration_start_measure(&duration);
2523
2524         if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
2525         {
2526                 return ERROR_OK;
2527         }
2528
2529         image_size = 0x0;
2530         retval = ERROR_OK;
2531         for (i = 0; i < image.num_sections; i++)
2532         {
2533                 buffer = malloc(image.sections[i].size);
2534                 if (buffer == NULL)
2535                 {
2536                         command_print(cmd_ctx,
2537                                                   "error allocating buffer for section (%d bytes)",
2538                                                   (int)(image.sections[i].size));
2539                         break;
2540                 }
2541
2542                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2543                 {
2544                         free(buffer);
2545                         break;
2546                 }
2547
2548                 uint32_t offset = 0;
2549                 uint32_t length = buf_cnt;
2550
2551                 /* DANGER!!! beware of unsigned comparision here!!! */
2552
2553                 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
2554                                 (image.sections[i].base_address < max_address))
2555                 {
2556                         if (image.sections[i].base_address < min_address)
2557                         {
2558                                 /* clip addresses below */
2559                                 offset += min_address-image.sections[i].base_address;
2560                                 length -= offset;
2561                         }
2562
2563                         if (image.sections[i].base_address + buf_cnt > max_address)
2564                         {
2565                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
2566                         }
2567
2568                         if ((retval = target_write_buffer(target, image.sections[i].base_address + offset, length, buffer + offset)) != ERROR_OK)
2569                         {
2570                                 free(buffer);
2571                                 break;
2572                         }
2573                         image_size += length;
2574                         command_print(cmd_ctx, "%u bytes written at address 0x%8.8" PRIx32 "",
2575                                                   (unsigned int)length,
2576                                                   image.sections[i].base_address + offset);
2577                 }
2578
2579                 free(buffer);
2580         }
2581
2582         if ((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2583         {
2584                 image_close(&image);
2585                 return retvaltemp;
2586         }
2587
2588         if (retval == ERROR_OK)
2589         {
2590                 command_print(cmd_ctx, "downloaded %u byte in %s",
2591                                           (unsigned int)image_size,
2592                                           duration_text);
2593         }
2594         free(duration_text);
2595
2596         image_close(&image);
2597
2598         return retval;
2599
2600 }
2601
2602 static int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2603 {
2604         fileio_t fileio;
2605
2606         uint8_t buffer[560];
2607         int retvaltemp;
2608
2609         duration_t duration;
2610         char *duration_text;
2611
2612         target_t *target = get_current_target(cmd_ctx);
2613
2614         if (argc != 3)
2615         {
2616                 command_print(cmd_ctx, "usage: dump_image <filename> <address> <size>");
2617                 return ERROR_OK;
2618         }
2619
2620         uint32_t address;
2621         COMMAND_PARSE_NUMBER(u32, args[1], address);
2622         uint32_t size;
2623         COMMAND_PARSE_NUMBER(u32, args[2], size);
2624
2625         if (fileio_open(&fileio, args[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2626         {
2627                 return ERROR_OK;
2628         }
2629
2630         duration_start_measure(&duration);
2631
2632         int retval = ERROR_OK;
2633         while (size > 0)
2634         {
2635                 uint32_t size_written;
2636                 uint32_t this_run_size = (size > 560) ? 560 : size;
2637                 retval = target_read_buffer(target, address, this_run_size, buffer);
2638                 if (retval != ERROR_OK)
2639                 {
2640                         break;
2641                 }
2642
2643                 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2644                 if (retval != ERROR_OK)
2645                 {
2646                         break;
2647                 }
2648
2649                 size -= this_run_size;
2650                 address += this_run_size;
2651         }
2652
2653         if ((retvaltemp = fileio_close(&fileio)) != ERROR_OK)
2654                 return retvaltemp;
2655
2656         if ((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2657                 return retvaltemp;
2658
2659         if (retval == ERROR_OK)
2660         {
2661                 command_print(cmd_ctx, "dumped %lld byte in %s",
2662                                 fileio.size, duration_text);
2663                 free(duration_text);
2664         }
2665
2666         return retval;
2667 }
2668
2669 static int handle_verify_image_command_internal(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc, int verify)
2670 {
2671         uint8_t *buffer;
2672         uint32_t buf_cnt;
2673         uint32_t image_size;
2674         int i;
2675         int retval, retvaltemp;
2676         uint32_t checksum = 0;
2677         uint32_t mem_checksum = 0;
2678
2679         image_t image;
2680
2681         duration_t duration;
2682         char *duration_text;
2683
2684         target_t *target = get_current_target(cmd_ctx);
2685
2686         if (argc < 1)
2687         {
2688                 return ERROR_COMMAND_SYNTAX_ERROR;
2689         }
2690
2691         if (!target)
2692         {
2693                 LOG_ERROR("no target selected");
2694                 return ERROR_FAIL;
2695         }
2696
2697         duration_start_measure(&duration);
2698
2699         if (argc >= 2)
2700         {
2701                 uint32_t addr;
2702                 COMMAND_PARSE_NUMBER(u32, args[1], addr);
2703                 image.base_address = addr;
2704                 image.base_address_set = 1;
2705         }
2706         else
2707         {
2708                 image.base_address_set = 0;
2709                 image.base_address = 0x0;
2710         }
2711
2712         image.start_address_set = 0;
2713
2714         if ((retval = image_open(&image, args[0], (argc == 3) ? args[2] : NULL)) != ERROR_OK)
2715         {
2716                 return retval;
2717         }
2718
2719         image_size = 0x0;
2720         retval = ERROR_OK;
2721         for (i = 0; i < image.num_sections; i++)
2722         {
2723                 buffer = malloc(image.sections[i].size);
2724                 if (buffer == NULL)
2725                 {
2726                         command_print(cmd_ctx,
2727                                                   "error allocating buffer for section (%d bytes)",
2728                                                   (int)(image.sections[i].size));
2729                         break;
2730                 }
2731                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2732                 {
2733                         free(buffer);
2734                         break;
2735                 }
2736
2737                 if (verify)
2738                 {
2739                         /* calculate checksum of image */
2740                         image_calculate_checksum(buffer, buf_cnt, &checksum);
2741
2742                         retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2743                         if (retval != ERROR_OK)
2744                         {
2745                                 free(buffer);
2746                                 break;
2747                         }
2748
2749                         if (checksum != mem_checksum)
2750                         {
2751                                 /* failed crc checksum, fall back to a binary compare */
2752                                 uint8_t *data;
2753
2754                                 command_print(cmd_ctx, "checksum mismatch - attempting binary compare");
2755
2756                                 data = (uint8_t*)malloc(buf_cnt);
2757
2758                                 /* Can we use 32bit word accesses? */
2759                                 int size = 1;
2760                                 int count = buf_cnt;
2761                                 if ((count % 4) == 0)
2762                                 {
2763                                         size *= 4;
2764                                         count /= 4;
2765                                 }
2766                                 retval = target_read_memory(target, image.sections[i].base_address, size, count, data);
2767                                 if (retval == ERROR_OK)
2768                                 {
2769                                         uint32_t t;
2770                                         for (t = 0; t < buf_cnt; t++)
2771                                         {
2772                                                 if (data[t] != buffer[t])
2773                                                 {
2774                                                         command_print(cmd_ctx,
2775                                                                                   "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n",
2776                                                                                   (unsigned)(t + image.sections[i].base_address),
2777                                                                                   data[t],
2778                                                                                   buffer[t]);
2779                                                         free(data);
2780                                                         free(buffer);
2781                                                         retval = ERROR_FAIL;
2782                                                         goto done;
2783                                                 }
2784                                                 if ((t%16384) == 0)
2785                                                 {
2786                                                         keep_alive();
2787                                                 }
2788                                         }
2789                                 }
2790
2791                                 free(data);
2792                         }
2793                 } else
2794                 {
2795                         command_print(cmd_ctx, "address 0x%08" PRIx32 " length 0x%08" PRIx32 "",
2796                                                   image.sections[i].base_address,
2797                                                   buf_cnt);
2798                 }
2799
2800                 free(buffer);
2801                 image_size += buf_cnt;
2802         }
2803 done:
2804
2805         if ((retvaltemp = duration_stop_measure(&duration, &duration_text)) != ERROR_OK)
2806         {
2807                 image_close(&image);
2808                 return retvaltemp;
2809         }
2810
2811         if (retval == ERROR_OK)
2812         {
2813                 command_print(cmd_ctx, "verified %u bytes in %s",
2814                                           (unsigned int)image_size,
2815                                           duration_text);
2816         }
2817         free(duration_text);
2818
2819         image_close(&image);
2820
2821         return retval;
2822 }
2823
2824 static int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2825 {
2826         return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 1);
2827 }
2828
2829 static int handle_test_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2830 {
2831         return handle_verify_image_command_internal(cmd_ctx, cmd, args, argc, 0);
2832 }
2833
2834 static int handle_bp_command_list(struct command_context_s *cmd_ctx)
2835 {
2836         target_t *target = get_current_target(cmd_ctx);
2837         breakpoint_t *breakpoint = target->breakpoints;
2838         while (breakpoint)
2839         {
2840                 if (breakpoint->type == BKPT_SOFT)
2841                 {
2842                         char* buf = buf_to_str(breakpoint->orig_instr,
2843                                         breakpoint->length, 16);
2844                         command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i, 0x%s",
2845                                         breakpoint->address,
2846                                         breakpoint->length,
2847                                         breakpoint->set, buf);
2848                         free(buf);
2849                 }
2850                 else
2851                 {
2852                         command_print(cmd_ctx, "0x%8.8" PRIx32 ", 0x%x, %i",
2853                                                   breakpoint->address,
2854                                                   breakpoint->length, breakpoint->set);
2855                 }
2856
2857                 breakpoint = breakpoint->next;
2858         }
2859         return ERROR_OK;
2860 }
2861
2862 static int handle_bp_command_set(struct command_context_s *cmd_ctx,
2863                 uint32_t addr, uint32_t length, int hw)
2864 {
2865         target_t *target = get_current_target(cmd_ctx);
2866         int retval = breakpoint_add(target, addr, length, hw);
2867         if (ERROR_OK == retval)
2868                 command_print(cmd_ctx, "breakpoint set at 0x%8.8" PRIx32 "", addr);
2869         else
2870                 LOG_ERROR("Failure setting breakpoint");
2871         return retval;
2872 }
2873
2874 static int handle_bp_command(struct command_context_s *cmd_ctx,
2875                 char *cmd, char **args, int argc)
2876 {
2877         if (argc == 0)
2878                 return handle_bp_command_list(cmd_ctx);
2879
2880         if (argc < 2 || argc > 3)
2881         {
2882                 command_print(cmd_ctx, "usage: bp <address> <length> ['hw']");
2883                 return ERROR_COMMAND_SYNTAX_ERROR;
2884         }
2885
2886         uint32_t addr;
2887         COMMAND_PARSE_NUMBER(u32, args[0], addr);
2888         uint32_t length;
2889         COMMAND_PARSE_NUMBER(u32, args[1], length);
2890
2891         int hw = BKPT_SOFT;
2892         if (argc == 3)
2893         {
2894                 if (strcmp(args[2], "hw") == 0)
2895                         hw = BKPT_HARD;
2896                 else
2897                         return ERROR_COMMAND_SYNTAX_ERROR;
2898         }
2899
2900         return handle_bp_command_set(cmd_ctx, addr, length, hw);
2901 }
2902
2903 static int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2904 {
2905         if (argc != 1)
2906                 return ERROR_COMMAND_SYNTAX_ERROR;
2907
2908         uint32_t addr;
2909         COMMAND_PARSE_NUMBER(u32, args[0], addr);
2910
2911         target_t *target = get_current_target(cmd_ctx);
2912         breakpoint_remove(target, addr);
2913
2914         return ERROR_OK;
2915 }
2916
2917 static int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2918 {
2919         target_t *target = get_current_target(cmd_ctx);
2920
2921         if (argc == 0)
2922         {
2923                 watchpoint_t *watchpoint = target->watchpoints;
2924
2925                 while (watchpoint)
2926                 {
2927                         command_print(cmd_ctx,
2928                                                   "address: 0x%8.8" PRIx32 ", len: 0x%8.8x, r/w/a: %i, value: 0x%8.8" PRIx32 ", mask: 0x%8.8" PRIx32 "",
2929                                                   watchpoint->address,
2930                                                   watchpoint->length,
2931                                                   (int)(watchpoint->rw),
2932                                                   watchpoint->value,
2933                                                   watchpoint->mask);
2934                         watchpoint = watchpoint->next;
2935                 }
2936                 return ERROR_OK;
2937         }
2938
2939         enum watchpoint_rw type = WPT_ACCESS;
2940         uint32_t addr = 0;
2941         uint32_t length = 0;
2942         uint32_t data_value = 0x0;
2943         uint32_t data_mask = 0xffffffff;
2944
2945         switch (argc)
2946         {
2947         case 5:
2948                 COMMAND_PARSE_NUMBER(u32, args[4], data_mask);
2949                 // fall through
2950         case 4:
2951                 COMMAND_PARSE_NUMBER(u32, args[3], data_value);
2952                 // fall through
2953         case 3:
2954                 switch (args[2][0])
2955                 {
2956                 case 'r':
2957                         type = WPT_READ;
2958                         break;
2959                 case 'w':
2960                         type = WPT_WRITE;
2961                         break;
2962                 case 'a':
2963                         type = WPT_ACCESS;
2964                         break;
2965                 default:
2966                         LOG_ERROR("invalid watchpoint mode ('%c')", args[2][0]);
2967                         return ERROR_COMMAND_SYNTAX_ERROR;
2968                 }
2969                 // fall through
2970         case 2:
2971                 COMMAND_PARSE_NUMBER(u32, args[1], length);
2972                 COMMAND_PARSE_NUMBER(u32, args[0], addr);
2973                 break;
2974
2975         default:
2976                 command_print(cmd_ctx, "usage: wp [address length "
2977                                 "[(r|w|a) [value [mask]]]]");
2978                 return ERROR_COMMAND_SYNTAX_ERROR;
2979         }
2980
2981         int retval = watchpoint_add(target, addr, length, type,
2982                         data_value, data_mask);
2983         if (ERROR_OK != retval)
2984                 LOG_ERROR("Failure setting watchpoints");
2985
2986         return retval;
2987 }
2988
2989 static int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2990 {
2991         if (argc != 1)
2992                 return ERROR_COMMAND_SYNTAX_ERROR;
2993
2994         uint32_t addr;
2995         COMMAND_PARSE_NUMBER(u32, args[0], addr);
2996
2997         target_t *target = get_current_target(cmd_ctx);
2998         watchpoint_remove(target, addr);
2999
3000         return ERROR_OK;
3001 }
3002
3003
3004 /**
3005  * Translate a virtual address to a physical address.
3006  *
3007  * The low-level target implementation must have logged a detailed error
3008  * which is forwarded to telnet/GDB session.
3009  */
3010 static int handle_virt2phys_command(command_context_t *cmd_ctx,
3011                 char *cmd, char **args, int argc)
3012 {
3013         if (argc != 1)
3014                 return ERROR_COMMAND_SYNTAX_ERROR;
3015
3016         uint32_t va;
3017         COMMAND_PARSE_NUMBER(u32, args[0], va);
3018         uint32_t pa;
3019
3020         target_t *target = get_current_target(cmd_ctx);
3021         int retval = target->type->virt2phys(target, va, &pa);
3022         if (retval == ERROR_OK)
3023                 command_print(cmd_ctx, "Physical address 0x%08" PRIx32 "", pa);
3024
3025         return retval;
3026 }
3027
3028 static void writeData(FILE *f, const void *data, size_t len)
3029 {
3030         size_t written = fwrite(data, 1, len, f);
3031         if (written != len)
3032                 LOG_ERROR("failed to write %zu bytes: %s", len, strerror(errno));
3033 }
3034
3035 static void writeLong(FILE *f, int l)
3036 {
3037         int i;
3038         for (i = 0; i < 4; i++)
3039         {
3040                 char c = (l >> (i*8))&0xff;
3041                 writeData(f, &c, 1);
3042         }
3043
3044 }
3045
3046 static void writeString(FILE *f, char *s)
3047 {
3048         writeData(f, s, strlen(s));
3049 }
3050
3051 /* Dump a gmon.out histogram file. */
3052 static void writeGmon(uint32_t *samples, uint32_t sampleNum, char *filename)
3053 {
3054         uint32_t i;
3055         FILE *f = fopen(filename, "w");
3056         if (f == NULL)
3057                 return;
3058         writeString(f, "gmon");
3059         writeLong(f, 0x00000001); /* Version */
3060         writeLong(f, 0); /* padding */
3061         writeLong(f, 0); /* padding */
3062         writeLong(f, 0); /* padding */
3063
3064         uint8_t zero = 0;  /* GMON_TAG_TIME_HIST */
3065         writeData(f, &zero, 1);
3066
3067         /* figure out bucket size */
3068         uint32_t min = samples[0];
3069         uint32_t max = samples[0];
3070         for (i = 0; i < sampleNum; i++)
3071         {
3072                 if (min > samples[i])
3073                 {
3074                         min = samples[i];
3075                 }
3076                 if (max < samples[i])
3077                 {
3078                         max = samples[i];
3079                 }
3080         }
3081
3082         int addressSpace = (max-min + 1);
3083
3084         static const uint32_t maxBuckets = 256 * 1024; /* maximum buckets. */
3085         uint32_t length = addressSpace;
3086         if (length > maxBuckets)
3087         {
3088                 length = maxBuckets;
3089         }
3090         int *buckets = malloc(sizeof(int)*length);
3091         if (buckets == NULL)
3092         {
3093                 fclose(f);
3094                 return;
3095         }
3096         memset(buckets, 0, sizeof(int)*length);
3097         for (i = 0; i < sampleNum;i++)
3098         {
3099                 uint32_t address = samples[i];
3100                 long long a = address-min;
3101                 long long b = length-1;
3102                 long long c = addressSpace-1;
3103                 int index = (a*b)/c; /* danger!!!! int32 overflows */
3104                 buckets[index]++;
3105         }
3106
3107         /* append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr)) */
3108         writeLong(f, min);                      /* low_pc */
3109         writeLong(f, max);                      /* high_pc */
3110         writeLong(f, length);           /* # of samples */
3111         writeLong(f, 64000000);         /* 64MHz */
3112         writeString(f, "seconds");
3113         for (i = 0; i < (15-strlen("seconds")); i++)
3114                 writeData(f, &zero, 1);
3115         writeString(f, "s");
3116
3117         /*append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size) */
3118
3119         char *data = malloc(2*length);
3120         if (data != NULL)
3121         {
3122                 for (i = 0; i < length;i++)
3123                 {
3124                         int val;
3125                         val = buckets[i];
3126                         if (val > 65535)
3127                         {
3128                                 val = 65535;
3129                         }
3130                         data[i*2]=val&0xff;
3131                         data[i*2 + 1]=(val >> 8)&0xff;
3132                 }
3133                 free(buckets);
3134                 writeData(f, data, length * 2);
3135                 free(data);
3136         } else
3137         {
3138                 free(buckets);
3139         }
3140
3141         fclose(f);
3142 }
3143
3144 /* profiling samples the CPU PC as quickly as OpenOCD is able, which will be used as a random sampling of PC */
3145 static int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
3146 {
3147         target_t *target = get_current_target(cmd_ctx);
3148         struct timeval timeout, now;
3149
3150         gettimeofday(&timeout, NULL);
3151         if (argc != 2)
3152         {
3153                 return ERROR_COMMAND_SYNTAX_ERROR;
3154         }
3155         unsigned offset;
3156         COMMAND_PARSE_NUMBER(uint, args[0], offset);
3157
3158         timeval_add_time(&timeout, offset, 0);
3159
3160         command_print(cmd_ctx, "Starting profiling. Halting and resuming the target as often as we can...");
3161
3162         static const int maxSample = 10000;
3163         uint32_t *samples = malloc(sizeof(uint32_t)*maxSample);
3164         if (samples == NULL)
3165                 return ERROR_OK;
3166
3167         int numSamples = 0;
3168         /* hopefully it is safe to cache! We want to stop/restart as quickly as possible. */
3169         reg_t *reg = register_get_by_name(target->reg_cache, "pc", 1);
3170
3171         for (;;)
3172         {
3173                 int retval;
3174                 target_poll(target);
3175                 if (target->state == TARGET_HALTED)
3176                 {
3177                         uint32_t t=*((uint32_t *)reg->value);
3178                         samples[numSamples++]=t;
3179                         retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3180                         target_poll(target);
3181                         alive_sleep(10); /* sleep 10ms, i.e. <100 samples/second. */
3182                 } else if (target->state == TARGET_RUNNING)
3183                 {
3184                         /* We want to quickly sample the PC. */
3185                         if ((retval = target_halt(target)) != ERROR_OK)
3186                         {
3187                                 free(samples);
3188                                 return retval;
3189                         }
3190                 } else
3191                 {
3192                         command_print(cmd_ctx, "Target not halted or running");
3193                         retval = ERROR_OK;
3194                         break;
3195                 }
3196                 if (retval != ERROR_OK)
3197                 {
3198                         break;
3199                 }
3200
3201                 gettimeofday(&now, NULL);
3202                 if ((numSamples >= maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
3203                 {
3204                         command_print(cmd_ctx, "Profiling completed. %d samples.", numSamples);
3205                         if ((retval = target_poll(target)) != ERROR_OK)
3206                         {
3207                                 free(samples);
3208                                 return retval;
3209                         }
3210                         if (target->state == TARGET_HALTED)
3211                         {
3212                                 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
3213                         }
3214                         if ((retval = target_poll(target)) != ERROR_OK)
3215                         {
3216                                 free(samples);
3217                                 return retval;
3218                         }
3219                         writeGmon(samples, numSamples, args[1]);
3220                         command_print(cmd_ctx, "Wrote %s", args[1]);
3221                         break;
3222                 }
3223         }
3224         free(samples);
3225
3226         return ERROR_OK;
3227 }
3228
3229 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t val)
3230 {
3231         char *namebuf;
3232         Jim_Obj *nameObjPtr, *valObjPtr;
3233         int result;
3234
3235         namebuf = alloc_printf("%s(%d)", varname, idx);
3236         if (!namebuf)
3237                 return JIM_ERR;
3238
3239         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3240         valObjPtr = Jim_NewIntObj(interp, val);
3241         if (!nameObjPtr || !valObjPtr)
3242         {
3243                 free(namebuf);
3244                 return JIM_ERR;
3245         }
3246
3247         Jim_IncrRefCount(nameObjPtr);
3248         Jim_IncrRefCount(valObjPtr);
3249         result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
3250         Jim_DecrRefCount(interp, nameObjPtr);
3251         Jim_DecrRefCount(interp, valObjPtr);
3252         free(namebuf);
3253         /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
3254         return result;
3255 }
3256
3257 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3258 {
3259         command_context_t *context;
3260         target_t *target;
3261
3262         context = Jim_GetAssocData(interp, "context");
3263         if (context == NULL)
3264         {
3265                 LOG_ERROR("mem2array: no command context");
3266                 return JIM_ERR;
3267         }
3268         target = get_current_target(context);
3269         if (target == NULL)
3270         {
3271                 LOG_ERROR("mem2array: no current target");
3272                 return JIM_ERR;
3273         }
3274
3275         return  target_mem2array(interp, target, argc-1, argv + 1);
3276 }
3277
3278 static int target_mem2array(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
3279 {
3280         long l;
3281         uint32_t width;
3282         int len;
3283         uint32_t addr;
3284         uint32_t count;
3285         uint32_t v;
3286         const char *varname;
3287         uint8_t buffer[4096];
3288         int  n, e, retval;
3289         uint32_t i;
3290
3291         /* argv[1] = name of array to receive the data
3292          * argv[2] = desired width
3293          * argv[3] = memory address
3294          * argv[4] = count of times to read
3295          */
3296         if (argc != 4) {
3297                 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3298                 return JIM_ERR;
3299         }
3300         varname = Jim_GetString(argv[0], &len);
3301         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3302
3303         e = Jim_GetLong(interp, argv[1], &l);
3304         width = l;
3305         if (e != JIM_OK) {
3306                 return e;
3307         }
3308
3309         e = Jim_GetLong(interp, argv[2], &l);
3310         addr = l;
3311         if (e != JIM_OK) {
3312                 return e;
3313         }
3314         e = Jim_GetLong(interp, argv[3], &l);
3315         len = l;
3316         if (e != JIM_OK) {
3317                 return e;
3318         }
3319         switch (width) {
3320                 case 8:
3321                         width = 1;
3322                         break;
3323                 case 16:
3324                         width = 2;
3325                         break;
3326                 case 32:
3327                         width = 4;
3328                         break;
3329                 default:
3330                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3331                         Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3332                         return JIM_ERR;
3333         }
3334         if (len == 0) {
3335                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3336                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
3337                 return JIM_ERR;
3338         }
3339         if ((addr + (len * width)) < addr) {
3340                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3341                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
3342                 return JIM_ERR;
3343         }
3344         /* absurd transfer size? */
3345         if (len > 65536) {
3346                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3347                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
3348                 return JIM_ERR;
3349         }
3350
3351         if ((width == 1) ||
3352                 ((width == 2) && ((addr & 1) == 0)) ||
3353                 ((width == 4) && ((addr & 3) == 0))) {
3354                 /* all is well */
3355         } else {
3356                 char buf[100];
3357                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3358                 sprintf(buf, "mem2array address: 0x%08" PRIx32 " is not aligned for %" PRId32 " byte reads",
3359                                 addr,
3360                                 width);
3361                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3362                 return JIM_ERR;
3363         }
3364
3365         /* Transfer loop */
3366
3367         /* index counter */
3368         n = 0;
3369         /* assume ok */
3370         e = JIM_OK;
3371         while (len) {
3372                 /* Slurp... in buffer size chunks */
3373
3374                 count = len; /* in objects.. */
3375                 if (count > (sizeof(buffer)/width)) {
3376                         count = (sizeof(buffer)/width);
3377                 }
3378
3379                 retval = target_read_memory(target, addr, width, count, buffer);
3380                 if (retval != ERROR_OK) {
3381                         /* BOO !*/
3382                         LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed",
3383                                           (unsigned int)addr,
3384                                           (int)width,
3385                                           (int)count);
3386                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3387                         Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
3388                         e = JIM_ERR;
3389                         len = 0;
3390                 } else {
3391                         v = 0; /* shut up gcc */
3392                         for (i = 0 ;i < count ;i++, n++) {
3393                                 switch (width) {
3394                                         case 4:
3395                                                 v = target_buffer_get_u32(target, &buffer[i*width]);
3396                                                 break;
3397                                         case 2:
3398                                                 v = target_buffer_get_u16(target, &buffer[i*width]);
3399                                                 break;
3400                                         case 1:
3401                                                 v = buffer[i] & 0x0ff;
3402                                                 break;
3403                                 }
3404                                 new_int_array_element(interp, varname, n, v);
3405                         }
3406                         len -= count;
3407                 }
3408         }
3409
3410         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3411
3412         return JIM_OK;
3413 }
3414
3415 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, uint32_t *val)
3416 {
3417         char *namebuf;
3418         Jim_Obj *nameObjPtr, *valObjPtr;
3419         int result;
3420         long l;
3421
3422         namebuf = alloc_printf("%s(%d)", varname, idx);
3423         if (!namebuf)
3424                 return JIM_ERR;
3425
3426         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
3427         if (!nameObjPtr)
3428         {
3429                 free(namebuf);
3430                 return JIM_ERR;
3431         }
3432
3433         Jim_IncrRefCount(nameObjPtr);
3434         valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
3435         Jim_DecrRefCount(interp, nameObjPtr);
3436         free(namebuf);
3437         if (valObjPtr == NULL)
3438                 return JIM_ERR;
3439
3440         result = Jim_GetLong(interp, valObjPtr, &l);
3441         /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
3442         *val = l;
3443         return result;
3444 }
3445
3446 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3447 {
3448         command_context_t *context;
3449         target_t *target;
3450
3451         context = Jim_GetAssocData(interp, "context");
3452         if (context == NULL) {
3453                 LOG_ERROR("array2mem: no command context");
3454                 return JIM_ERR;
3455         }
3456         target = get_current_target(context);
3457         if (target == NULL) {
3458                 LOG_ERROR("array2mem: no current target");
3459                 return JIM_ERR;
3460         }
3461
3462         return target_array2mem(interp,target, argc-1, argv + 1);
3463 }
3464 static int target_array2mem(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
3465 {
3466         long l;
3467         uint32_t width;
3468         int len;
3469         uint32_t addr;
3470         uint32_t count;
3471         uint32_t v;
3472         const char *varname;
3473         uint8_t buffer[4096];
3474         int  n, e, retval;
3475         uint32_t i;
3476
3477         /* argv[1] = name of array to get the data
3478          * argv[2] = desired width
3479          * argv[3] = memory address
3480          * argv[4] = count to write
3481          */
3482         if (argc != 4) {
3483                 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
3484                 return JIM_ERR;
3485         }
3486         varname = Jim_GetString(argv[0], &len);
3487         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
3488
3489         e = Jim_GetLong(interp, argv[1], &l);
3490         width = l;
3491         if (e != JIM_OK) {
3492                 return e;
3493         }
3494
3495         e = Jim_GetLong(interp, argv[2], &l);
3496         addr = l;
3497         if (e != JIM_OK) {
3498                 return e;
3499         }
3500         e = Jim_GetLong(interp, argv[3], &l);
3501         len = l;
3502         if (e != JIM_OK) {
3503                 return e;
3504         }
3505         switch (width) {
3506                 case 8:
3507                         width = 1;
3508                         break;
3509                 case 16:
3510                         width = 2;
3511                         break;
3512                 case 32:
3513                         width = 4;
3514                         break;
3515                 default:
3516                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3517                         Jim_AppendStrings(interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL);
3518                         return JIM_ERR;
3519         }
3520         if (len == 0) {
3521                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3522                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
3523                 return JIM_ERR;
3524         }
3525         if ((addr + (len * width)) < addr) {
3526                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3527                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
3528                 return JIM_ERR;
3529         }
3530         /* absurd transfer size? */
3531         if (len > 65536) {
3532                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3533                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
3534                 return JIM_ERR;
3535         }
3536
3537         if ((width == 1) ||
3538                 ((width == 2) && ((addr & 1) == 0)) ||
3539                 ((width == 4) && ((addr & 3) == 0))) {
3540                 /* all is well */
3541         } else {
3542                 char buf[100];
3543                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3544                 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads",
3545                                 (unsigned int)addr,
3546                                 (int)width);
3547                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
3548                 return JIM_ERR;
3549         }
3550
3551         /* Transfer loop */
3552
3553         /* index counter */
3554         n = 0;
3555         /* assume ok */
3556         e = JIM_OK;
3557         while (len) {
3558                 /* Slurp... in buffer size chunks */
3559
3560                 count = len; /* in objects.. */
3561                 if (count > (sizeof(buffer)/width)) {
3562                         count = (sizeof(buffer)/width);
3563                 }
3564
3565                 v = 0; /* shut up gcc */
3566                 for (i = 0 ;i < count ;i++, n++) {
3567                         get_int_array_element(interp, varname, n, &v);
3568                         switch (width) {
3569                         case 4:
3570                                 target_buffer_set_u32(target, &buffer[i*width], v);
3571                                 break;
3572                         case 2:
3573                                 target_buffer_set_u16(target, &buffer[i*width], v);
3574                                 break;
3575                         case 1:
3576                                 buffer[i] = v & 0x0ff;
3577                                 break;
3578                         }
3579                 }
3580                 len -= count;
3581
3582                 retval = target_write_memory(target, addr, width, count, buffer);
3583                 if (retval != ERROR_OK) {
3584                         /* BOO !*/
3585                         LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed",
3586                                           (unsigned int)addr,
3587                                           (int)width,
3588                                           (int)count);
3589                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3590                         Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3591                         e = JIM_ERR;
3592                         len = 0;
3593                 }
3594         }
3595
3596         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3597
3598         return JIM_OK;
3599 }
3600
3601 void target_all_handle_event(enum target_event e)
3602 {
3603         target_t *target;
3604
3605         LOG_DEBUG("**all*targets: event: %d, %s",
3606                            (int)e,
3607                            Jim_Nvp_value2name_simple(nvp_target_event, e)->name);
3608
3609         target = all_targets;
3610         while (target) {
3611                 target_handle_event(target, e);
3612                 target = target->next;
3613         }
3614 }
3615
3616
3617 /* FIX? should we propagate errors here rather than printing them
3618  * and continuing?
3619  */
3620 void target_handle_event(target_t *target, enum target_event e)
3621 {
3622         target_event_action_t *teap;
3623
3624         for (teap = target->event_action; teap != NULL; teap = teap->next) {
3625                 if (teap->event == e) {
3626                         LOG_DEBUG("target: (%d) %s (%s) event: %d (%s) action: %s",
3627                                            target->target_number,
3628                                            target->cmd_name,
3629                                            target_get_name(target),
3630                                            e,
3631                                            Jim_Nvp_value2name_simple(nvp_target_event, e)->name,
3632                                            Jim_GetString(teap->body, NULL));
3633                         if (Jim_EvalObj(interp, teap->body) != JIM_OK)
3634                         {
3635                                 Jim_PrintErrorMessage(interp);
3636                         }
3637                 }
3638         }
3639 }
3640
3641 enum target_cfg_param {
3642         TCFG_TYPE,
3643         TCFG_EVENT,
3644         TCFG_WORK_AREA_VIRT,
3645         TCFG_WORK_AREA_PHYS,
3646         TCFG_WORK_AREA_SIZE,
3647         TCFG_WORK_AREA_BACKUP,
3648         TCFG_ENDIAN,
3649         TCFG_VARIANT,
3650         TCFG_CHAIN_POSITION,
3651 };
3652
3653 static Jim_Nvp nvp_config_opts[] = {
3654         { .name = "-type",             .value = TCFG_TYPE },
3655         { .name = "-event",            .value = TCFG_EVENT },
3656         { .name = "-work-area-virt",   .value = TCFG_WORK_AREA_VIRT },
3657         { .name = "-work-area-phys",   .value = TCFG_WORK_AREA_PHYS },
3658         { .name = "-work-area-size",   .value = TCFG_WORK_AREA_SIZE },
3659         { .name = "-work-area-backup", .value = TCFG_WORK_AREA_BACKUP },
3660         { .name = "-endian" ,          .value = TCFG_ENDIAN },
3661         { .name = "-variant",          .value = TCFG_VARIANT },
3662         { .name = "-chain-position",   .value = TCFG_CHAIN_POSITION },
3663
3664         { .name = NULL, .value = -1 }
3665 };
3666
3667 static int target_configure(Jim_GetOptInfo *goi, target_t *target)
3668 {
3669         Jim_Nvp *n;
3670         Jim_Obj *o;
3671         jim_wide w;
3672         char *cp;
3673         int e;
3674
3675         /* parse config or cget options ... */
3676         while (goi->argc > 0) {
3677                 Jim_SetEmptyResult(goi->interp);
3678                 /* Jim_GetOpt_Debug(goi); */
3679
3680                 if (target->type->target_jim_configure) {
3681                         /* target defines a configure function */
3682                         /* target gets first dibs on parameters */
3683                         e = (*(target->type->target_jim_configure))(target, goi);
3684                         if (e == JIM_OK) {
3685                                 /* more? */
3686                                 continue;
3687                         }
3688                         if (e == JIM_ERR) {
3689                                 /* An error */
3690                                 return e;
3691                         }
3692                         /* otherwise we 'continue' below */
3693                 }
3694                 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
3695                 if (e != JIM_OK) {
3696                         Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
3697                         return e;
3698                 }
3699                 switch (n->value) {
3700                 case TCFG_TYPE:
3701                         /* not setable */
3702                         if (goi->isconfigure) {
3703                                 Jim_SetResult_sprintf(goi->interp, "not setable: %s", n->name);
3704                                 return JIM_ERR;
3705                         } else {
3706                         no_params:
3707                                 if (goi->argc != 0) {
3708                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "NO PARAMS");
3709                                         return JIM_ERR;
3710                                 }
3711                         }
3712                         Jim_SetResultString(goi->interp, target_get_name(target), -1);
3713                         /* loop for more */
3714                         break;
3715                 case TCFG_EVENT:
3716                         if (goi->argc == 0) {
3717                                 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ...");
3718                                 return JIM_ERR;
3719                         }
3720
3721                         e = Jim_GetOpt_Nvp(goi, nvp_target_event, &n);
3722                         if (e != JIM_OK) {
3723                                 Jim_GetOpt_NvpUnknown(goi, nvp_target_event, 1);
3724                                 return e;
3725                         }
3726
3727                         if (goi->isconfigure) {
3728                                 if (goi->argc != 1) {
3729                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
3730                                         return JIM_ERR;
3731                                 }
3732                         } else {
3733                                 if (goi->argc != 0) {
3734                                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
3735                                         return JIM_ERR;
3736                                 }
3737                         }
3738
3739                         {
3740                                 target_event_action_t *teap;
3741
3742                                 teap = target->event_action;
3743                                 /* replace existing? */
3744                                 while (teap) {
3745                                         if (teap->event == (enum target_event)n->value) {
3746                                                 break;
3747                                         }
3748                                         teap = teap->next;
3749                                 }
3750
3751                                 if (goi->isconfigure) {
3752                                         bool replace = true;
3753                                         if (teap == NULL) {
3754                                                 /* create new */
3755                                                 teap = calloc(1, sizeof(*teap));
3756                                                 replace = false;
3757                                         }
3758                                         teap->event = n->value;
3759                                         Jim_GetOpt_Obj(goi, &o);
3760                                         if (teap->body) {
3761                                                 Jim_DecrRefCount(interp, teap->body);
3762                                         }
3763                                         teap->body  = Jim_DuplicateObj(goi->interp, o);
3764                                         /*
3765                                          * FIXME:
3766                                          *     Tcl/TK - "tk events" have a nice feature.
3767                                          *     See the "BIND" command.
3768                                          *    We should support that here.
3769                                          *     You can specify %X and %Y in the event code.
3770                                          *     The idea is: %T - target name.
3771                                          *     The idea is: %N - target number
3772                                          *     The idea is: %E - event name.
3773                                          */
3774                                         Jim_IncrRefCount(teap->body);
3775
3776                                         if (!replace)
3777                                         {
3778                                                 /* add to head of event list */
3779                                                 teap->next = target->event_action;
3780                                                 target->event_action = teap;
3781                                         }
3782                                         Jim_SetEmptyResult(goi->interp);
3783                                 } else {
3784                                         /* get */
3785                                         if (teap == NULL) {
3786                                                 Jim_SetEmptyResult(goi->interp);
3787                                         } else {
3788                                                 Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, teap->body));
3789                                         }
3790                                 }
3791                         }
3792                         /* loop for more */
3793                         break;
3794
3795                 case TCFG_WORK_AREA_VIRT:
3796                         if (goi->isconfigure) {
3797                                 target_free_all_working_areas(target);
3798                                 e = Jim_GetOpt_Wide(goi, &w);
3799                                 if (e != JIM_OK) {
3800                                         return e;
3801                                 }
3802                                 target->working_area_virt = w;
3803                                 target->working_area_virt_spec = true;
3804                         } else {
3805                                 if (goi->argc != 0) {
3806                                         goto no_params;
3807                                 }
3808                         }
3809                         Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_virt));
3810                         /* loop for more */
3811                         break;
3812
3813                 case TCFG_WORK_AREA_PHYS:
3814                         if (goi->isconfigure) {
3815                                 target_free_all_working_areas(target);
3816                                 e = Jim_GetOpt_Wide(goi, &w);
3817                                 if (e != JIM_OK) {
3818                                         return e;
3819                                 }
3820                                 target->working_area_phys = w;
3821                                 target->working_area_phys_spec = true;
3822                         } else {
3823                                 if (goi->argc != 0) {
3824                                         goto no_params;
3825                                 }
3826                         }
3827                         Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_phys));
3828                         /* loop for more */
3829                         break;
3830
3831                 case TCFG_WORK_AREA_SIZE:
3832                         if (goi->isconfigure) {
3833                                 target_free_all_working_areas(target);
3834                                 e = Jim_GetOpt_Wide(goi, &w);
3835                                 if (e != JIM_OK) {
3836                                         return e;
3837                                 }
3838                                 target->working_area_size = w;
3839                         } else {
3840                                 if (goi->argc != 0) {
3841                                         goto no_params;
3842                                 }
3843                         }
3844                         Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->working_area_size));
3845                         /* loop for more */
3846                         break;
3847
3848                 case TCFG_WORK_AREA_BACKUP:
3849                         if (goi->isconfigure) {
3850                                 target_free_all_working_areas(target);
3851                                 e = Jim_GetOpt_Wide(goi, &w);
3852                                 if (e != JIM_OK) {
3853                                         return e;
3854                                 }
3855                                 /* make this exactly 1 or 0 */
3856                                 target->backup_working_area = (!!w);
3857                         } else {
3858                                 if (goi->argc != 0) {
3859                                         goto no_params;
3860                                 }
3861                         }
3862                         Jim_SetResult(interp, Jim_NewIntObj(goi->interp, target->backup_working_area));
3863                         /* loop for more e*/
3864                         break;
3865
3866                 case TCFG_ENDIAN:
3867                         if (goi->isconfigure) {
3868                                 e = Jim_GetOpt_Nvp(goi, nvp_target_endian, &n);
3869                                 if (e != JIM_OK) {
3870                                         Jim_GetOpt_NvpUnknown(goi, nvp_target_endian, 1);
3871                                         return e;
3872                                 }
3873                                 target->endianness = n->value;
3874                         } else {
3875                                 if (goi->argc != 0) {
3876                                         goto no_params;
3877                                 }
3878                         }
3879                         n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3880                         if (n->name == NULL) {
3881                                 target->endianness = TARGET_LITTLE_ENDIAN;
3882                                 n = Jim_Nvp_value2name_simple(nvp_target_endian, target->endianness);
3883                         }
3884                         Jim_SetResultString(goi->interp, n->name, -1);
3885                         /* loop for more */
3886                         break;
3887
3888                 case TCFG_VARIANT:
3889                         if (goi->isconfigure) {
3890                                 if (goi->argc < 1) {
3891                                         Jim_SetResult_sprintf(goi->interp,
3892                                                                                    "%s ?STRING?",
3893                                                                                    n->name);
3894                                         return JIM_ERR;
3895                                 }
3896                                 if (target->variant) {
3897                                         free((void *)(target->variant));
3898                                 }
3899                                 e = Jim_GetOpt_String(goi, &cp, NULL);
3900                                 target->variant = strdup(cp);
3901                         } else {
3902                                 if (goi->argc != 0) {
3903                                         goto no_params;
3904                                 }
3905                         }
3906                         Jim_SetResultString(goi->interp, target->variant,-1);
3907                         /* loop for more */
3908                         break;
3909                 case TCFG_CHAIN_POSITION:
3910                         if (goi->isconfigure) {
3911                                 Jim_Obj *o;
3912                                 jtag_tap_t *tap;
3913                                 target_free_all_working_areas(target);
3914                                 e = Jim_GetOpt_Obj(goi, &o);
3915                                 if (e != JIM_OK) {
3916                                         return e;
3917                                 }
3918                                 tap = jtag_tap_by_jim_obj(goi->interp, o);
3919                                 if (tap == NULL) {
3920                                         return JIM_ERR;
3921                                 }
3922                                 /* make this exactly 1 or 0 */
3923                                 target->tap = tap;
3924                         } else {
3925                                 if (goi->argc != 0) {
3926                                         goto no_params;
3927                                 }
3928                         }
3929                         Jim_SetResultString(interp, target->tap->dotted_name, -1);
3930                         /* loop for more e*/
3931                         break;
3932                 }
3933         } /* while (goi->argc) */
3934
3935
3936                 /* done - we return */
3937         return JIM_OK;
3938 }
3939
3940 /** this is the 'tcl' handler for the target specific command */
3941 static int tcl_target_func(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
3942 {
3943         Jim_GetOptInfo goi;
3944         jim_wide a,b,c;
3945         int x,y,z;
3946         uint8_t  target_buf[32];
3947         Jim_Nvp *n;
3948         target_t *target;
3949         struct command_context_s *cmd_ctx;
3950         int e;
3951
3952         enum {
3953                 TS_CMD_CONFIGURE,
3954                 TS_CMD_CGET,
3955
3956                 TS_CMD_MWW, TS_CMD_MWH, TS_CMD_MWB,
3957                 TS_CMD_MDW, TS_CMD_MDH, TS_CMD_MDB,
3958                 TS_CMD_MRW, TS_CMD_MRH, TS_CMD_MRB,
3959                 TS_CMD_MEM2ARRAY, TS_CMD_ARRAY2MEM,
3960                 TS_CMD_EXAMINE,
3961                 TS_CMD_POLL,
3962                 TS_CMD_RESET,
3963                 TS_CMD_HALT,
3964                 TS_CMD_WAITSTATE,
3965                 TS_CMD_EVENTLIST,
3966                 TS_CMD_CURSTATE,
3967                 TS_CMD_INVOKE_EVENT,
3968         };
3969
3970         static const Jim_Nvp target_options[] = {
3971                 { .name = "configure", .value = TS_CMD_CONFIGURE },
3972                 { .name = "cget", .value = TS_CMD_CGET },
3973                 { .name = "mww", .value = TS_CMD_MWW },
3974                 { .name = "mwh", .value = TS_CMD_MWH },
3975                 { .name = "mwb", .value = TS_CMD_MWB },
3976                 { .name = "mdw", .value = TS_CMD_MDW },
3977                 { .name = "mdh", .value = TS_CMD_MDH },
3978                 { .name = "mdb", .value = TS_CMD_MDB },
3979                 { .name = "mem2array", .value = TS_CMD_MEM2ARRAY },
3980                 { .name = "array2mem", .value = TS_CMD_ARRAY2MEM },
3981                 { .name = "eventlist", .value = TS_CMD_EVENTLIST },
3982                 { .name = "curstate",  .value = TS_CMD_CURSTATE },
3983
3984                 { .name = "arp_examine", .value = TS_CMD_EXAMINE },
3985                 { .name = "arp_poll", .value = TS_CMD_POLL },
3986                 { .name = "arp_reset", .value = TS_CMD_RESET },
3987                 { .name = "arp_halt", .value = TS_CMD_HALT },
3988                 { .name = "arp_waitstate", .value = TS_CMD_WAITSTATE },
3989                 { .name = "invoke-event", .value = TS_CMD_INVOKE_EVENT },
3990
3991                 { .name = NULL, .value = -1 },
3992         };
3993
3994         /* go past the "command" */
3995         Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
3996
3997         target = Jim_CmdPrivData(goi.interp);
3998         cmd_ctx = Jim_GetAssocData(goi.interp, "context");
3999
4000         /* commands here are in an NVP table */
4001         e = Jim_GetOpt_Nvp(&goi, target_options, &n);
4002         if (e != JIM_OK) {
4003                 Jim_GetOpt_NvpUnknown(&goi, target_options, 0);
4004                 return e;
4005         }
4006         /* Assume blank result */
4007         Jim_SetEmptyResult(goi.interp);
4008
4009         switch (n->value) {
4010         case TS_CMD_CONFIGURE:
4011                 if (goi.argc < 2) {
4012                         Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "missing: -option VALUE ...");
4013                         return JIM_ERR;
4014                 }
4015                 goi.isconfigure = 1;
4016                 return target_configure(&goi, target);
4017         case TS_CMD_CGET:
4018                 // some things take params
4019                 if (goi.argc < 1) {
4020                         Jim_WrongNumArgs(goi.interp, 0, goi.argv, "missing: ?-option?");
4021                         return JIM_ERR;
4022                 }
4023                 goi.isconfigure = 0;
4024                 return target_configure(&goi, target);
4025                 break;
4026         case TS_CMD_MWW:
4027         case TS_CMD_MWH:
4028         case TS_CMD_MWB:
4029                 /* argv[0] = cmd
4030                  * argv[1] = address
4031                  * argv[2] = data
4032                  * argv[3] = optional count.
4033                  */
4034
4035                 if ((goi.argc == 2) || (goi.argc == 3)) {
4036                         /* all is well */
4037                 } else {
4038                 mwx_error:
4039                         Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR DATA [COUNT]", n->name);
4040                         return JIM_ERR;
4041                 }
4042
4043                 e = Jim_GetOpt_Wide(&goi, &a);
4044                 if (e != JIM_OK) {
4045                         goto mwx_error;
4046                 }
4047
4048                 e = Jim_GetOpt_Wide(&goi, &b);
4049                 if (e != JIM_OK) {
4050                         goto mwx_error;
4051                 }
4052                 if (goi.argc == 3) {
4053                         e = Jim_GetOpt_Wide(&goi, &c);
4054                         if (e != JIM_OK) {
4055                                 goto mwx_error;
4056                         }
4057                 } else {
4058                         c = 1;
4059                 }
4060
4061                 switch (n->value) {
4062                 case TS_CMD_MWW:
4063                         target_buffer_set_u32(target, target_buf, b);
4064                         b = 4;
4065                         break;
4066                 case TS_CMD_MWH:
4067                         target_buffer_set_u16(target, target_buf, b);
4068                         b = 2;
4069                         break;
4070                 case TS_CMD_MWB:
4071                         target_buffer_set_u8(target, target_buf, b);
4072                         b = 1;
4073                         break;
4074                 }
4075                 for (x = 0 ; x < c ; x++) {
4076                         e = target_write_memory(target, a, b, 1, target_buf);
4077                         if (e != ERROR_OK) {
4078                                 Jim_SetResult_sprintf(interp, "Error writing @ 0x%08x: %d\n", (int)(a), e);
4079                                 return JIM_ERR;
4080                         }
4081                         /* b = width */
4082                         a = a + b;
4083                 }
4084                 return JIM_OK;
4085                 break;
4086
4087                 /* display */
4088         case TS_CMD_MDW:
4089         case TS_CMD_MDH:
4090         case TS_CMD_MDB:
4091                 /* argv[0] = command
4092                  * argv[1] = address
4093                  * argv[2] = optional count
4094                  */
4095                 if ((goi.argc == 2) || (goi.argc == 3)) {
4096                         Jim_SetResult_sprintf(goi.interp, "expected: %s ADDR [COUNT]", n->name);
4097                         return JIM_ERR;
4098                 }
4099                 e = Jim_GetOpt_Wide(&goi, &a);
4100                 if (e != JIM_OK) {
4101                         return JIM_ERR;
4102                 }
4103                 if (goi.argc) {
4104                         e = Jim_GetOpt_Wide(&goi, &c);
4105                         if (e != JIM_OK) {
4106                                 return JIM_ERR;
4107                         }
4108                 } else {
4109                         c = 1;
4110                 }
4111                 b = 1; /* shut up gcc */
4112                 switch (n->value) {
4113                 case TS_CMD_MDW:
4114                         b =  4;
4115                         break;
4116                 case TS_CMD_MDH:
4117                         b = 2;
4118                         break;
4119                 case TS_CMD_MDB:
4120                         b = 1;
4121                         break;
4122                 }
4123
4124                 /* convert to "bytes" */
4125                 c = c * b;
4126                 /* count is now in 'BYTES' */
4127                 while (c > 0) {
4128                         y = c;
4129                         if (y > 16) {
4130                                 y = 16;
4131                         }
4132                         e = target_read_memory(target, a, b, y / b, target_buf);
4133                         if (e != ERROR_OK) {
4134                                 Jim_SetResult_sprintf(interp, "error reading target @ 0x%08lx", (int)(a));
4135                                 return JIM_ERR;
4136                         }
4137
4138                         Jim_fprintf(interp, interp->cookie_stdout, "0x%08x ", (int)(a));
4139                         switch (b) {
4140                         case 4:
4141                                 for (x = 0 ; (x < 16) && (x < y) ; x += 4) {
4142                                         z = target_buffer_get_u32(target, &(target_buf[ x * 4 ]));
4143                                         Jim_fprintf(interp, interp->cookie_stdout, "%08x ", (int)(z));
4144                                 }
4145                                 for (; (x < 16) ; x += 4) {
4146                                         Jim_fprintf(interp, interp->cookie_stdout, "         ");
4147                                 }
4148                                 break;
4149                         case 2:
4150                                 for (x = 0 ; (x < 16) && (x < y) ; x += 2) {
4151                                         z = target_buffer_get_u16(target, &(target_buf[ x * 2 ]));
4152                                         Jim_fprintf(interp, interp->cookie_stdout, "%04x ", (int)(z));
4153                                 }
4154                                 for (; (x < 16) ; x += 2) {
4155                                         Jim_fprintf(interp, interp->cookie_stdout, "     ");
4156                                 }
4157                                 break;
4158                         case 1:
4159                         default:
4160                                 for (x = 0 ; (x < 16) && (x < y) ; x += 1) {
4161                                         z = target_buffer_get_u8(target, &(target_buf[ x * 4 ]));
4162                                         Jim_fprintf(interp, interp->cookie_stdout, "%02x ", (int)(z));
4163                                 }
4164                                 for (; (x < 16) ; x += 1) {
4165                                         Jim_fprintf(interp, interp->cookie_stdout, "   ");
4166                                 }
4167                                 break;
4168                         }
4169                         /* ascii-ify the bytes */
4170                         for (x = 0 ; x < y ; x++) {
4171                                 if ((target_buf[x] >= 0x20) &&
4172                                         (target_buf[x] <= 0x7e)) {
4173                                         /* good */
4174                                 } else {
4175                                         /* smack it */
4176                                         target_buf[x] = '.';
4177                                 }
4178                         }
4179                         /* space pad  */
4180                         while (x < 16) {
4181                                 target_buf[x] = ' ';
4182                                 x++;
4183                         }
4184                         /* terminate */
4185                         target_buf[16] = 0;
4186                         /* print - with a newline */
4187                         Jim_fprintf(interp, interp->cookie_stdout, "%s\n", target_buf);
4188                         /* NEXT... */
4189                         c -= 16;
4190                         a += 16;
4191                 }
4192                 return JIM_OK;
4193         case TS_CMD_MEM2ARRAY:
4194                 return target_mem2array(goi.interp, target, goi.argc, goi.argv);
4195                 break;
4196         case TS_CMD_ARRAY2MEM:
4197                 return target_array2mem(goi.interp, target, goi.argc, goi.argv);
4198                 break;
4199         case TS_CMD_EXAMINE:
4200                 if (goi.argc) {
4201                         Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4202                         return JIM_ERR;
4203                 }
4204                 if (!target->tap->enabled)
4205                         goto err_tap_disabled;
4206                 e = target->type->examine(target);
4207                 if (e != ERROR_OK) {
4208                         Jim_SetResult_sprintf(interp, "examine-fails: %d", e);
4209                         return JIM_ERR;
4210                 }
4211                 return JIM_OK;
4212         case TS_CMD_POLL:
4213                 if (goi.argc) {
4214                         Jim_WrongNumArgs(goi.interp, 2, argv, "[no parameters]");
4215                         return JIM_ERR;
4216                 }
4217                 if (!target->tap->enabled)
4218                         goto err_tap_disabled;
4219                 if (!(target_was_examined(target))) {
4220                         e = ERROR_TARGET_NOT_EXAMINED;
4221                 } else {
4222                         e = target->type->poll(target);
4223                 }
4224                 if (e != ERROR_OK) {
4225                         Jim_SetResult_sprintf(interp, "poll-fails: %d", e);
4226                         return JIM_ERR;
4227                 } else {
4228                         return JIM_OK;
4229                 }
4230                 break;
4231         case TS_CMD_RESET:
4232                 if (goi.argc != 2) {
4233                         Jim_WrongNumArgs(interp, 2, argv,
4234                                         "([tT]|[fF]|assert|deassert) BOOL");
4235                         return JIM_ERR;
4236                 }
4237                 e = Jim_GetOpt_Nvp(&goi, nvp_assert, &n);
4238                 if (e != JIM_OK) {
4239                         Jim_GetOpt_NvpUnknown(&goi, nvp_assert, 1);
4240                         return e;
4241                 }
4242                 /* the halt or not param */
4243                 e = Jim_GetOpt_Wide(&goi, &a);
4244                 if (e != JIM_OK) {
4245                         return e;
4246                 }
4247                 if (!target->tap->enabled)
4248                         goto err_tap_disabled;
4249                 if (!target->type->assert_reset
4250                                 || !target->type->deassert_reset) {
4251                         Jim_SetResult_sprintf(interp,
4252                                         "No target-specific reset for %s",
4253                                         target->cmd_name);
4254                         return JIM_ERR;
4255                 }
4256                 /* determine if we should halt or not. */
4257                 target->reset_halt = !!a;
4258                 /* When this happens - all workareas are invalid. */
4259                 target_free_all_working_areas_restore(target, 0);
4260
4261                 /* do the assert */
4262                 if (n->value == NVP_ASSERT) {
4263                         e = target->type->assert_reset(target);
4264                 } else {
4265                         e = target->type->deassert_reset(target);
4266                 }
4267                 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4268         case TS_CMD_HALT:
4269                 if (goi.argc) {
4270                         Jim_WrongNumArgs(goi.interp, 0, argv, "halt [no parameters]");
4271                         return JIM_ERR;
4272                 }
4273                 if (!target->tap->enabled)
4274                         goto err_tap_disabled;
4275                 e = target->type->halt(target);
4276                 return (e == ERROR_OK) ? JIM_OK : JIM_ERR;
4277         case TS_CMD_WAITSTATE:
4278                 /* params:  <name>  statename timeoutmsecs */
4279                 if (goi.argc != 2) {
4280                         Jim_SetResult_sprintf(goi.interp, "%s STATENAME TIMEOUTMSECS", n->name);
4281                         return JIM_ERR;
4282                 }
4283                 e = Jim_GetOpt_Nvp(&goi, nvp_target_state, &n);
4284                 if (e != JIM_OK) {
4285                         Jim_GetOpt_NvpUnknown(&goi, nvp_target_state,1);
4286                         return e;
4287                 }
4288                 e = Jim_GetOpt_Wide(&goi, &a);
4289                 if (e != JIM_OK) {
4290                         return e;
4291                 }
4292                 if (!target->tap->enabled)
4293                         goto err_tap_disabled;
4294                 e = target_wait_state(target, n->value, a);
4295                 if (e != ERROR_OK) {
4296                         Jim_SetResult_sprintf(goi.interp,
4297                                                                    "target: %s wait %s fails (%d) %s",
4298                                                                    target->cmd_name,
4299                                                                    n->name,
4300                                                                    e, target_strerror_safe(e));
4301                         return JIM_ERR;
4302                 } else {
4303                         return JIM_OK;
4304                 }
4305         case TS_CMD_EVENTLIST:
4306                 /* List for human, Events defined for this target.
4307                  * scripts/programs should use 'name cget -event NAME'
4308                  */
4309                 {
4310                         target_event_action_t *teap;
4311                         teap = target->event_action;
4312                         command_print(cmd_ctx, "Event actions for target (%d) %s\n",
4313                                                    target->target_number,
4314                                                    target->cmd_name);
4315                         command_print(cmd_ctx, "%-25s | Body", "Event");
4316                         command_print(cmd_ctx, "------------------------- | ----------------------------------------");
4317                         while (teap) {
4318                                 command_print(cmd_ctx,
4319                                                            "%-25s | %s",
4320                                                            Jim_Nvp_value2name_simple(nvp_target_event, teap->event)->name,
4321                                                            Jim_GetString(teap->body, NULL));
4322                                 teap = teap->next;
4323                         }
4324                         command_print(cmd_ctx, "***END***");
4325                         return JIM_OK;
4326                 }
4327         case TS_CMD_CURSTATE:
4328                 if (goi.argc != 0) {
4329                         Jim_WrongNumArgs(goi.interp, 0, argv, "[no parameters]");
4330                         return JIM_ERR;
4331                 }
4332                 Jim_SetResultString(goi.interp,
4333                                                         target_state_name( target ),
4334                                                         -1);
4335                 return JIM_OK;
4336         case TS_CMD_INVOKE_EVENT:
4337                 if (goi.argc != 1) {
4338                         Jim_SetResult_sprintf(goi.interp, "%s ?EVENTNAME?",n->name);
4339                         return JIM_ERR;
4340                 }
4341                 e = Jim_GetOpt_Nvp(&goi, nvp_target_event, &n);
4342                 if (e != JIM_OK) {
4343                         Jim_GetOpt_NvpUnknown(&goi, nvp_target_event, 1);
4344                         return e;
4345                 }
4346                 target_handle_event(target, n->value);
4347                 return JIM_OK;
4348         }
4349         return JIM_ERR;
4350
4351 err_tap_disabled:
4352         Jim_SetResult_sprintf(interp, "[TAP is disabled]");
4353         return JIM_ERR;
4354 }
4355
4356 static int target_create(Jim_GetOptInfo *goi)
4357 {
4358         Jim_Obj *new_cmd;
4359         Jim_Cmd *cmd;
4360         const char *cp;
4361         char *cp2;
4362         int e;
4363         int x;
4364         target_t *target;
4365         struct command_context_s *cmd_ctx;
4366
4367         cmd_ctx = Jim_GetAssocData(goi->interp, "context");
4368         if (goi->argc < 3) {
4369                 Jim_WrongNumArgs(goi->interp, 1, goi->argv, "?name? ?type? ..options...");
4370                 return JIM_ERR;
4371         }
4372
4373         /* COMMAND */
4374         Jim_GetOpt_Obj(goi, &new_cmd);
4375         /* does this command exist? */
4376         cmd = Jim_GetCommand(goi->interp, new_cmd, JIM_ERRMSG);
4377         if (cmd) {
4378                 cp = Jim_GetString(new_cmd, NULL);
4379                 Jim_SetResult_sprintf(goi->interp, "Command/target: %s Exists", cp);
4380                 return JIM_ERR;
4381         }
4382
4383         /* TYPE */
4384         e = Jim_GetOpt_String(goi, &cp2, NULL);
4385         cp = cp2;
4386         /* now does target type exist */
4387         for (x = 0 ; target_types[x] ; x++) {
4388                 if (0 == strcmp(cp, target_types[x]->name)) {
4389                         /* found */
4390                         break;
4391                 }
4392         }
4393         if (target_types[x] == NULL) {
4394                 Jim_SetResult_sprintf(goi->interp, "Unknown target type %s, try one of ", cp);
4395                 for (x = 0 ; target_types[x] ; x++) {
4396                         if (target_types[x + 1]) {
4397                                 Jim_AppendStrings(goi->interp,
4398                                                                    Jim_GetResult(goi->interp),
4399                                                                    target_types[x]->name,
4400                                                                    ", ", NULL);
4401                         } else {
4402                                 Jim_AppendStrings(goi->interp,
4403                                                                    Jim_GetResult(goi->interp),
4404                                                                    " or ",
4405                                                                    target_types[x]->name,NULL);
4406                         }
4407                 }
4408                 return JIM_ERR;
4409         }
4410
4411         /* Create it */
4412         target = calloc(1,sizeof(target_t));
4413         /* set target number */
4414         target->target_number = new_target_number();
4415
4416         /* allocate memory for each unique target type */
4417         target->type = (target_type_t*)calloc(1,sizeof(target_type_t));
4418
4419         memcpy(target->type, target_types[x], sizeof(target_type_t));
4420
4421         /* will be set by "-endian" */
4422         target->endianness = TARGET_ENDIAN_UNKNOWN;
4423
4424         target->working_area        = 0x0;
4425         target->working_area_size   = 0x0;
4426         target->working_areas       = NULL;
4427         target->backup_working_area = 0;
4428
4429         target->state               = TARGET_UNKNOWN;
4430         target->debug_reason        = DBG_REASON_UNDEFINED;
4431         target->reg_cache           = NULL;
4432         target->breakpoints         = NULL;
4433         target->watchpoints         = NULL;
4434         target->next                = NULL;
4435         target->arch_info           = NULL;
4436
4437         target->display             = 1;
4438
4439         target->halt_issued                     = false;
4440
4441         /* initialize trace information */
4442         target->trace_info = malloc(sizeof(trace_t));
4443         target->trace_info->num_trace_points         = 0;
4444         target->trace_info->trace_points_size        = 0;
4445         target->trace_info->trace_points             = NULL;
4446         target->trace_info->trace_history_size       = 0;
4447         target->trace_info->trace_history            = NULL;
4448         target->trace_info->trace_history_pos        = 0;
4449         target->trace_info->trace_history_overflowed = 0;
4450
4451         target->dbgmsg          = NULL;
4452         target->dbg_msg_enabled = 0;
4453
4454         target->endianness = TARGET_ENDIAN_UNKNOWN;
4455
4456         /* Do the rest as "configure" options */
4457         goi->isconfigure = 1;
4458         e = target_configure(goi, target);
4459
4460         if (target->tap == NULL)
4461         {
4462                 Jim_SetResultString(interp, "-chain-position required when creating target", -1);
4463                 e = JIM_ERR;
4464         }
4465
4466         if (e != JIM_OK) {
4467                 free(target->type);
4468                 free(target);
4469                 return e;
4470         }
4471
4472         if (target->endianness == TARGET_ENDIAN_UNKNOWN) {
4473                 /* default endian to little if not specified */
4474                 target->endianness = TARGET_LITTLE_ENDIAN;
4475         }
4476
4477         /* incase variant is not set */
4478         if (!target->variant)
4479                 target->variant = strdup("");
4480
4481         /* create the target specific commands */
4482         if (target->type->register_commands) {
4483                 (*(target->type->register_commands))(cmd_ctx);
4484         }
4485         if (target->type->target_create) {
4486                 (*(target->type->target_create))(target, goi->interp);
4487         }
4488
4489         /* append to end of list */
4490         {
4491                 target_t **tpp;
4492                 tpp = &(all_targets);
4493                 while (*tpp) {
4494                         tpp = &((*tpp)->next);
4495                 }
4496                 *tpp = target;
4497         }
4498
4499         cp = Jim_GetString(new_cmd, NULL);
4500         target->cmd_name = strdup(cp);
4501
4502         /* now - create the new target name command */
4503         e = Jim_CreateCommand(goi->interp,
4504                                                    /* name */
4505                                                    cp,
4506                                                    tcl_target_func, /* C function */
4507                                                    target, /* private data */
4508                                                    NULL); /* no del proc */
4509
4510         return e;
4511 }
4512
4513 static int jim_target(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4514 {
4515         int x,r,e;
4516         jim_wide w;
4517         struct command_context_s *cmd_ctx;
4518         target_t *target;
4519         Jim_GetOptInfo goi;
4520         enum tcmd {
4521                 /* TG = target generic */
4522                 TG_CMD_CREATE,
4523                 TG_CMD_TYPES,
4524                 TG_CMD_NAMES,
4525                 TG_CMD_CURRENT,
4526                 TG_CMD_NUMBER,
4527                 TG_CMD_COUNT,
4528         };
4529         const char *target_cmds[] = {
4530                 "create", "types", "names", "current", "number",
4531                 "count",
4532                 NULL /* terminate */
4533         };
4534
4535         LOG_DEBUG("Target command params:");
4536         LOG_DEBUG("%s", Jim_Debug_ArgvString(interp, argc, argv));
4537
4538         cmd_ctx = Jim_GetAssocData(interp, "context");
4539
4540         Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
4541
4542         if (goi.argc == 0) {
4543                 Jim_WrongNumArgs(interp, 1, argv, "missing: command ...");
4544                 return JIM_ERR;
4545         }
4546
4547         /* Jim_GetOpt_Debug(&goi); */
4548         r = Jim_GetOpt_Enum(&goi, target_cmds, &x);
4549         if (r != JIM_OK) {
4550                 return r;
4551         }
4552
4553         switch (x) {
4554         default:
4555                 Jim_Panic(goi.interp,"Why am I here?");
4556                 return JIM_ERR;
4557         case TG_CMD_CURRENT:
4558                 if (goi.argc != 0) {
4559                         Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4560                         return JIM_ERR;
4561                 }
4562                 Jim_SetResultString(goi.interp, get_current_target(cmd_ctx)->cmd_name, -1);
4563                 return JIM_OK;
4564         case TG_CMD_TYPES:
4565                 if (goi.argc != 0) {
4566                         Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4567                         return JIM_ERR;
4568                 }
4569                 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4570                 for (x = 0 ; target_types[x] ; x++) {
4571                         Jim_ListAppendElement(goi.interp,
4572                                                                    Jim_GetResult(goi.interp),
4573                                                                    Jim_NewStringObj(goi.interp, target_types[x]->name, -1));
4574                 }
4575                 return JIM_OK;
4576         case TG_CMD_NAMES:
4577                 if (goi.argc != 0) {
4578                         Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
4579                         return JIM_ERR;
4580                 }
4581                 Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
4582                 target = all_targets;
4583                 while (target) {
4584                         Jim_ListAppendElement(goi.interp,
4585                                                                    Jim_GetResult(goi.interp),
4586                                                                    Jim_NewStringObj(goi.interp, target->cmd_name, -1));
4587                         target = target->next;
4588                 }
4589                 return JIM_OK;
4590         case TG_CMD_CREATE:
4591                 if (goi.argc < 3) {
4592                         Jim_WrongNumArgs(goi.interp, goi.argc, goi.argv, "?name  ... config options ...");
4593                         return JIM_ERR;
4594                 }
4595                 return target_create(&goi);
4596                 break;
4597         case TG_CMD_NUMBER:
4598                 /* It's OK to remove this mechanism sometime after August 2010 or so */
4599                 LOG_WARNING("don't use numbers as target identifiers; use names");
4600                 if (goi.argc != 1) {
4601                         Jim_SetResult_sprintf(goi.interp, "expected: target number ?NUMBER?");
4602                         return JIM_ERR;
4603                 }
4604                 e = Jim_GetOpt_Wide(&goi, &w);
4605                 if (e != JIM_OK) {
4606                         return JIM_ERR;
4607                 }
4608                 for (x = 0, target = all_targets; target; target = target->next, x++) {
4609                         if (target->target_number == w)
4610                                 break;
4611                 }
4612                 if (target == NULL) {
4613                         Jim_SetResult_sprintf(goi.interp,
4614                                         "Target: number %d does not exist", (int)(w));
4615                         return JIM_ERR;
4616                 }
4617                 Jim_SetResultString(goi.interp, target->cmd_name, -1);
4618                 return JIM_OK;
4619         case TG_CMD_COUNT:
4620                 if (goi.argc != 0) {
4621                         Jim_WrongNumArgs(goi.interp, 0, goi.argv, "<no parameters>");
4622                         return JIM_ERR;
4623                 }
4624                 for (x = 0, target = all_targets; target; target = target->next, x++)
4625                         continue;
4626                 Jim_SetResult(goi.interp, Jim_NewIntObj(goi.interp, x));
4627                 return JIM_OK;
4628         }
4629
4630         return JIM_ERR;
4631 }
4632
4633
4634 struct FastLoad
4635 {
4636         uint32_t address;
4637         uint8_t *data;
4638         int length;
4639
4640 };
4641
4642 static int fastload_num;
4643 static struct FastLoad *fastload;
4644
4645 static void free_fastload(void)
4646 {
4647         if (fastload != NULL)
4648         {
4649                 int i;
4650                 for (i = 0; i < fastload_num; i++)
4651                 {
4652                         if (fastload[i].data)
4653                                 free(fastload[i].data);
4654                 }
4655                 free(fastload);
4656                 fastload = NULL;
4657         }
4658 }
4659
4660
4661
4662
4663 static int handle_fast_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4664 {
4665         uint8_t *buffer;
4666         uint32_t buf_cnt;
4667         uint32_t image_size;
4668         uint32_t min_address = 0;
4669         uint32_t max_address = 0xffffffff;
4670         int i;
4671
4672         image_t image;
4673
4674         duration_t duration;
4675         char *duration_text;
4676
4677         int retval = parse_load_image_command_args(cmd_ctx, args, argc,
4678                         &image, &min_address, &max_address);
4679         if (ERROR_OK != retval)
4680                 return retval;
4681
4682         duration_start_measure(&duration);
4683
4684         if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
4685         {
4686                 return ERROR_OK;
4687         }
4688
4689         image_size = 0x0;
4690         retval = ERROR_OK;
4691         fastload_num = image.num_sections;
4692         fastload = (struct FastLoad *)malloc(sizeof(struct FastLoad)*image.num_sections);
4693         if (fastload == NULL)
4694         {
4695                 image_close(&image);
4696                 return ERROR_FAIL;
4697         }
4698         memset(fastload, 0, sizeof(struct FastLoad)*image.num_sections);
4699         for (i = 0; i < image.num_sections; i++)
4700         {
4701                 buffer = malloc(image.sections[i].size);
4702                 if (buffer == NULL)
4703                 {
4704                         command_print(cmd_ctx, "error allocating buffer for section (%d bytes)",
4705                                                   (int)(image.sections[i].size));
4706                         break;
4707                 }
4708
4709                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
4710                 {
4711                         free(buffer);
4712                         break;
4713                 }
4714
4715                 uint32_t offset = 0;
4716                 uint32_t length = buf_cnt;
4717
4718
4719                 /* DANGER!!! beware of unsigned comparision here!!! */
4720
4721                 if ((image.sections[i].base_address + buf_cnt >= min_address)&&
4722                                 (image.sections[i].base_address < max_address))
4723                 {
4724                         if (image.sections[i].base_address < min_address)
4725                         {
4726                                 /* clip addresses below */
4727                                 offset += min_address-image.sections[i].base_address;
4728                                 length -= offset;
4729                         }
4730
4731                         if (image.sections[i].base_address + buf_cnt > max_address)
4732                         {
4733                                 length -= (image.sections[i].base_address + buf_cnt)-max_address;
4734                         }
4735
4736                         fastload[i].address = image.sections[i].base_address + offset;
4737                         fastload[i].data = malloc(length);
4738                         if (fastload[i].data == NULL)
4739                         {
4740                                 free(buffer);
4741                                 break;
4742                         }
4743                         memcpy(fastload[i].data, buffer + offset, length);
4744                         fastload[i].length = length;
4745
4746                         image_size += length;
4747                         command_print(cmd_ctx, "%u bytes written at address 0x%8.8x",
4748                                                   (unsigned int)length,
4749                                                   ((unsigned int)(image.sections[i].base_address + offset)));
4750                 }
4751
4752                 free(buffer);
4753         }
4754
4755         duration_stop_measure(&duration, &duration_text);
4756         if (retval == ERROR_OK)
4757         {
4758                 command_print(cmd_ctx, "Loaded %u bytes in %s", (unsigned int)image_size, duration_text);
4759                 command_print(cmd_ctx, "NB!!! image has not been loaded to target, issue a subsequent 'fast_load' to do so.");
4760         }
4761         free(duration_text);
4762
4763         image_close(&image);
4764
4765         if (retval != ERROR_OK)
4766         {
4767                 free_fastload();
4768         }
4769
4770         return retval;
4771 }
4772
4773 static int handle_fast_load_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
4774 {
4775         if (argc > 0)
4776                 return ERROR_COMMAND_SYNTAX_ERROR;
4777         if (fastload == NULL)
4778         {
4779                 LOG_ERROR("No image in memory");
4780                 return ERROR_FAIL;
4781         }
4782         int i;
4783         int ms = timeval_ms();
4784         int size = 0;
4785         int retval = ERROR_OK;
4786         for (i = 0; i < fastload_num;i++)
4787         {
4788                 target_t *target = get_current_target(cmd_ctx);
4789                 command_print(cmd_ctx, "Write to 0x%08x, length 0x%08x",
4790                                           (unsigned int)(fastload[i].address),
4791                                           (unsigned int)(fastload[i].length));
4792                 if (retval == ERROR_OK)
4793                 {
4794                         retval = target_write_buffer(target, fastload[i].address, fastload[i].length, fastload[i].data);
4795                 }
4796                 size += fastload[i].length;
4797         }
4798         int after = timeval_ms();
4799         command_print(cmd_ctx, "Loaded image %f kBytes/s", (float)(size/1024.0)/((float)(after-ms)/1000.0));
4800         return retval;
4801 }
4802
4803 static int jim_mcrmrc(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
4804 {
4805         command_context_t *context;
4806         target_t *target;
4807         int retval;
4808
4809         context = Jim_GetAssocData(interp, "context");
4810         if (context == NULL) {
4811                 LOG_ERROR("array2mem: no command context");
4812                 return JIM_ERR;
4813         }
4814         target = get_current_target(context);
4815         if (target == NULL) {
4816                 LOG_ERROR("array2mem: no current target");
4817                 return JIM_ERR;
4818         }
4819
4820         if ((argc < 6) || (argc > 7))
4821         {
4822                 return JIM_ERR;
4823         }
4824
4825         int cpnum;
4826         uint32_t op1;
4827         uint32_t op2;
4828         uint32_t CRn;
4829         uint32_t CRm;
4830         uint32_t value;
4831
4832         int e;
4833         long l;
4834         e = Jim_GetLong(interp, argv[1], &l);
4835         if (e != JIM_OK) {
4836                 return e;
4837         }
4838         cpnum = l;
4839
4840         e = Jim_GetLong(interp, argv[2], &l);
4841         if (e != JIM_OK) {
4842                 return e;
4843         }
4844         op1 = l;
4845
4846         e = Jim_GetLong(interp, argv[3], &l);
4847         if (e != JIM_OK) {
4848                 return e;
4849         }
4850         CRn = l;
4851
4852         e = Jim_GetLong(interp, argv[4], &l);
4853         if (e != JIM_OK) {
4854                 return e;
4855         }
4856         CRm = l;
4857
4858         e = Jim_GetLong(interp, argv[5], &l);
4859         if (e != JIM_OK) {
4860                 return e;
4861         }
4862         op2 = l;
4863
4864         value = 0;
4865
4866         if (argc == 7)
4867         {
4868                 e = Jim_GetLong(interp, argv[6], &l);
4869                 if (e != JIM_OK) {
4870                         return e;
4871                 }
4872                 value = l;
4873
4874                 retval = target_mcr(target, cpnum, op1, op2, CRn, CRm, value);
4875                 if (retval != ERROR_OK)
4876                         return JIM_ERR;
4877         } else
4878         {
4879                 retval = target_mrc(target, cpnum, op1, op2, CRn, CRm, &value);
4880                 if (retval != ERROR_OK)
4881                         return JIM_ERR;
4882
4883                 Jim_SetResult(interp, Jim_NewIntObj(interp, value));
4884         }
4885
4886         return JIM_OK;
4887 }