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