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