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