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