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