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