]> git.sur5r.net Git - openocd/blob - src/target/target.c
f79156ad645d0cdafd3d1afafe19913e0e0a6147
[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  *   This program is free software; you can redistribute it and/or modify  *
9  *   it under the terms of the GNU General Public License as published by  *
10  *   the Free Software Foundation; either version 2 of the License, or     *
11  *   (at your option) any later version.                                   *
12  *                                                                         *
13  *   This program is distributed in the hope that it will be useful,       *
14  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
15  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
16  *   GNU General Public License for more details.                          *
17  *                                                                         *
18  *   You should have received a copy of the GNU General Public License     *
19  *   along with this program; if not, write to the                         *
20  *   Free Software Foundation, Inc.,                                       *
21  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
22  ***************************************************************************/
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26
27 #include "replacements.h"
28 #include "target.h"
29 #include "target_request.h"
30
31 #include "log.h"
32 #include "configuration.h"
33 #include "binarybuffer.h"
34 #include "jtag.h"
35
36 #include <string.h>
37 #include <stdlib.h>
38 #include <inttypes.h>
39
40 #include <sys/types.h>
41 #include <sys/stat.h>
42 #include <unistd.h>
43 #include <errno.h>
44
45 #include <sys/time.h>
46 #include <time.h>
47
48 #include <time_support.h>
49
50 #include <fileio.h>
51 #include <image.h>
52
53 int cli_target_callback_event_handler(struct target_s *target, enum target_event event, void *priv);
54
55 int handle_target_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
56 int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
57
58 int handle_working_area_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
59
60 int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
61 int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
62 int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
63 int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
64 int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
65 int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
66 int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
67 int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
68 int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
69 int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
70 int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
71 int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
72 int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
73 int handle_bp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
74 int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
75 int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
76 int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
77 int handle_virt2phys_command(command_context_t *cmd_ctx, char *cmd, char **args, int argc);
78 int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
79 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
80 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
81
82
83 static int target_array2mem(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv);
84 static int target_mem2array(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv);
85
86
87
88 /* targets */
89 extern target_type_t arm7tdmi_target;
90 extern target_type_t arm720t_target;
91 extern target_type_t arm9tdmi_target;
92 extern target_type_t arm920t_target;
93 extern target_type_t arm966e_target;
94 extern target_type_t arm926ejs_target;
95 extern target_type_t feroceon_target;
96 extern target_type_t xscale_target;
97 extern target_type_t cortexm3_target;
98 extern target_type_t arm11_target;
99 extern target_type_t mips_m4k_target;
100
101 target_type_t *target_types[] =
102 {
103         &arm7tdmi_target,
104         &arm9tdmi_target,
105         &arm920t_target,
106         &arm720t_target,
107         &arm966e_target,
108         &arm926ejs_target,
109         &feroceon_target,
110         &xscale_target,
111         &cortexm3_target,
112         &arm11_target,
113         &mips_m4k_target,
114         NULL,
115 };
116
117 target_t *all_targets = NULL;
118 target_event_callback_t *target_event_callbacks = NULL;
119 target_timer_callback_t *target_timer_callbacks = NULL;
120
121 const Jim_Nvp nvp_assert[] = {
122         { .name = "assert", NVP_ASSERT },
123         { .name = "deassert", NVP_DEASSERT },
124         { .name = "T", NVP_ASSERT },
125         { .name = "F", NVP_DEASSERT },
126         { .name = "t", NVP_ASSERT },
127         { .name = "f", NVP_DEASSERT },
128         { .name = NULL, .value = -1 }
129 };
130
131 const Jim_Nvp nvp_target_event[] = {
132         { .value = TARGET_EVENT_HALTED, .name = "halted" },
133         { .value = TARGET_EVENT_RESUMED, .name = "resumed" },
134         { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
135         { .value = TARGET_EVENT_RESUME_END, .name = "resume-end" },
136
137         /* historical name */
138         { .value = TARGET_EVENT_RESET_START  , .name = "pre_reset" },
139         { .value = TARGET_EVENT_RESET_START, .name = "reset-start" },
140         /* historical name */
141         { .value = TARGET_EVENT_RESET      , .name = "reset" },
142         { .value = TARGET_EVENT_RESET_INIT , .name = "reset-init" },
143         { .value = TARGET_EVENT_RESET_END, .name = "reset-end" },
144
145         { .value = TARGET_EVENT_DEBUG_HALTED, .name = "debug-halted" },
146         { .value = TARGET_EVENT_DEBUG_RESUMED, .name = "debug-resumed" },
147
148         { .value = TARGET_EVENT_GDB_ATTACH, .name = "gdb-attach" },
149         { .value = TARGET_EVENT_GDB_DETACH, .name = "gdb-detach" },
150
151         { .value = TARGET_EVENT_GDB_FLASH_WRITE_START, .name = "gdb-flash-write-start" },
152         { .value = TARGET_EVENT_GDB_FLASH_WRITE_END  , .name = "gdb-flash-write-end"   },
153
154         { .value = TARGET_EVENT_GDB_FLASH_ERASE_START , .name = "gdb_program_config" },
155
156         { .value = TARGET_EVENT_GDB_FLASH_ERASE_START, .name = "gdb-flash-erase-start" },
157         { .value = TARGET_EVENT_GDB_FLASH_ERASE_END  , .name = "gdb-flash-erase-end" },
158
159         { .value = TARGET_EVENT_RESUME_START, .name = "resume-start" },
160         { .value = TARGET_EVENT_RESUMED     , .name = "resume-ok" },
161         { .value = TARGET_EVENT_RESUME_END  , .name = "resume-end" },
162
163         { .name = NULL, .value = -1 }
164 };
165
166 const Jim_Nvp nvp_target_state[] = {
167         { .name = "unknown", .value = TARGET_UNKNOWN },
168         { .name = "running", .value = TARGET_RUNNING },
169         { .name = "halted",  .value = TARGET_HALTED },
170         { .name = "reset",   .value = TARGET_RESET },
171         { .name = "debug-running", .value = TARGET_DEBUG_RUNNING },
172         { .name = NULL, .value = -1 },
173 };
174
175
176 const Jim_Nvp nvp_target_debug_reason [] = {
177         { .name = "debug-request"            , .value = DBG_REASON_DBGRQ },
178         { .name = "breakpoint"               , .value = DBG_REASON_BREAKPOINT },
179         { .name = "watchpoint"               , .value = DBG_REASON_WATCHPOINT },
180         { .name = "watchpoint-and-breakpoint", .value = DBG_REASON_WPTANDBKPT },
181         { .name = "single-step"              , .value = DBG_REASON_SINGLESTEP },
182         { .name = "target-not-halted"        , .value = DBG_REASON_NOTHALTED  },
183         { .name = "undefined"                , .value = DBG_REASON_UNDEFINED },
184         { .name = NULL, .value = -1 },
185 };
186
187
188 const Jim_Nvp nvp_target_endian[] = {
189         { .name = "big",    .value = TARGET_BIG_ENDIAN },
190         { .name = "little", .value = TARGET_LITTLE_ENDIAN },
191         { .name = "be",     .value = TARGET_BIG_ENDIAN },
192         { .name = "le",     .value = TARGET_LITTLE_ENDIAN },
193         { .name = NULL,     .value = -1 },
194 };
195
196
197 /* determine the number of the new target */
198 static int
199 new_target_number( void )
200 {
201         target_t *t;
202         int x;
203
204         /* number is 0 based */
205         x = -1;
206         t = all_targets;
207         while(t){
208                 if( x < t->target_number ){
209                         x = t->target_number;
210                 }
211                 t = t->next;
212         }
213         return x+1;
214 }
215
216 static int target_continous_poll = 1;
217
218 /* read a u32 from a buffer in target memory endianness */
219 u32 target_buffer_get_u32(target_t *target, u8 *buffer)
220 {
221         if (target->endianness == TARGET_LITTLE_ENDIAN)
222                 return le_to_h_u32(buffer);
223         else
224                 return be_to_h_u32(buffer);
225 }
226
227 /* read a u16 from a buffer in target memory endianness */
228 u16 target_buffer_get_u16(target_t *target, u8 *buffer)
229 {
230         if (target->endianness == TARGET_LITTLE_ENDIAN)
231                 return le_to_h_u16(buffer);
232         else
233                 return be_to_h_u16(buffer);
234 }
235
236 /* read a u8 from a buffer in target memory endianness */
237 u8 target_buffer_get_u8(target_t *target, u8 *buffer)
238 {
239         return *buffer & 0x0ff;
240 }
241
242 /* write a u32 to a buffer in target memory endianness */
243 void target_buffer_set_u32(target_t *target, u8 *buffer, u32 value)
244 {
245         if (target->endianness == TARGET_LITTLE_ENDIAN)
246                 h_u32_to_le(buffer, value);
247         else
248                 h_u32_to_be(buffer, value);
249 }
250
251 /* write a u16 to a buffer in target memory endianness */
252 void target_buffer_set_u16(target_t *target, u8 *buffer, u16 value)
253 {
254         if (target->endianness == TARGET_LITTLE_ENDIAN)
255                 h_u16_to_le(buffer, value);
256         else
257                 h_u16_to_be(buffer, value);
258 }
259
260 /* write a u8 to a buffer in target memory endianness */
261 void target_buffer_set_u8(target_t *target, u8 *buffer, u8 value)
262 {
263         *buffer = value;
264 }
265
266 /* returns a pointer to the n-th configured target */
267 target_t* get_target_by_num(int num)
268 {
269         target_t *target = all_targets;
270
271         while (target){
272                 if( target->target_number == num ){
273                         return target;
274                 } 
275                 target = target->next;
276         }
277
278         return NULL;
279 }
280
281 int get_num_by_target(target_t *query_target)
282 {
283         return query_target->target_number;
284 }
285
286 target_t* get_current_target(command_context_t *cmd_ctx)
287 {
288         target_t *target = get_target_by_num(cmd_ctx->current_target);
289
290         if (target == NULL)
291         {
292                 LOG_ERROR("BUG: current_target out of bounds");
293                 exit(-1);
294         }
295
296         return target;
297 }
298
299
300 int target_poll(struct target_s *target)
301 {
302         /* We can't poll until after examine */
303         if (!target->type->examined)
304         {
305                 /* Fail silently lest we pollute the log */
306                 return ERROR_FAIL;
307         }
308         return target->type->poll(target);
309 }
310
311 int target_halt(struct target_s *target)
312 {
313         /* We can't poll until after examine */
314         if (!target->type->examined)
315         {
316                 LOG_ERROR("Target not examined yet");
317                 return ERROR_FAIL;
318         }
319         return target->type->halt(target);
320 }
321
322 int target_resume(struct target_s *target, int current, u32 address, int handle_breakpoints, int debug_execution)
323 {
324         int retval;
325
326         /* We can't poll until after examine */
327         if (!target->type->examined)
328         {
329                 LOG_ERROR("Target not examined yet");
330                 return ERROR_FAIL;
331         }
332
333         /* note that resume *must* be asynchronous. The CPU can halt before we poll. The CPU can
334          * even halt at the current PC as a result of a software breakpoint being inserted by (a bug?)
335          * the application.
336          */
337         if ((retval = target->type->resume(target, current, address, handle_breakpoints, debug_execution)) != ERROR_OK)
338                 return retval;
339
340         return retval;
341 }
342
343 int target_process_reset(struct command_context_s *cmd_ctx, enum target_reset_mode reset_mode)
344 {
345         int retval = ERROR_OK;
346         target_t *target;
347
348         target = all_targets;
349         while (target)
350         {
351                 target_invoke_script(cmd_ctx, target, "pre_reset");
352                 target = target->next;
353         }
354
355         if ((retval = jtag_init_reset(cmd_ctx)) != ERROR_OK)
356                 return retval;
357
358         keep_alive(); /* we might be running on a very slow JTAG clk */
359
360         /* First time this is executed after launching OpenOCD, it will read out
361          * the type of CPU, etc. and init Embedded ICE registers in host
362          * memory.
363          *
364          * It will also set up ICE registers in the target.
365          *
366          * However, if we assert TRST later, we need to set up the registers again.
367          *
368          * For the "reset halt/init" case we must only set up the registers here.
369          */
370         if ((retval = target_examine()) != ERROR_OK)
371                 return retval;
372
373         keep_alive(); /* we might be running on a very slow JTAG clk */
374
375         target = all_targets;
376         while (target)
377         {
378                 /* we have no idea what state the target is in, so we
379                  * have to drop working areas
380                  */
381                 target_free_all_working_areas_restore(target, 0);
382                 target->reset_halt=((reset_mode==RESET_HALT)||(reset_mode==RESET_INIT));
383                 if ((retval = target->type->assert_reset(target))!=ERROR_OK)
384                         return retval;
385                 target = target->next;
386         }
387
388         target = all_targets;
389         while (target)
390         {
391                 if ((retval = target->type->deassert_reset(target))!=ERROR_OK)
392                         return retval;
393                 target = target->next;
394         }
395
396         target = all_targets;
397         while (target)
398         {
399                 /* We can fail to bring the target into the halted state, try after reset has been deasserted  */
400                 if (target->reset_halt)
401                 {
402                         /* wait up to 1 second for halt. */
403                         target_wait_state(target, TARGET_HALTED, 1000);
404                         if (target->state != TARGET_HALTED)
405                         {
406                                 LOG_WARNING("Failed to reset target into halted mode - issuing halt");
407                                 if ((retval = target->type->halt(target))!=ERROR_OK)
408                                         return retval;
409                         }
410                 }
411
412                 target = target->next;
413         }
414
415
416         LOG_DEBUG("Waiting for halted stated as appropriate");
417
418         if ((reset_mode == RESET_HALT) || (reset_mode == RESET_INIT))
419         {
420                 target = all_targets;
421                 while (target)
422                 {
423                         /* Wait for reset to complete, maximum 5 seconds. */
424                         if (((retval=target_wait_state(target, TARGET_HALTED, 5000)))==ERROR_OK)
425                         {
426                           if (reset_mode == RESET_INIT)
427                                         target_invoke_script(cmd_ctx, target, "post_reset");
428
429                         }
430                         target = target->next;
431                 }
432         }
433
434         /* We want any events to be processed before the prompt */
435         target_call_timer_callbacks_now();
436
437         return retval;
438 }
439
440 static int default_virt2phys(struct target_s *target, u32 virtual, u32 *physical)
441 {
442         *physical = virtual;
443         return ERROR_OK;
444 }
445
446 static int default_mmu(struct target_s *target, int *enabled)
447 {
448         *enabled = 0;
449         return ERROR_OK;
450 }
451
452 static int default_examine(struct target_s *target)
453 {
454         target->type->examined = 1;
455         return ERROR_OK;
456 }
457
458
459 /* Targets that correctly implement init+examine, i.e.
460  * no communication with target during init:
461  *
462  * XScale
463  */
464 int target_examine(void)
465 {
466         int retval = ERROR_OK;
467         target_t *target = all_targets;
468         while (target)
469         {
470                 if ((retval = target->type->examine(target))!=ERROR_OK)
471                         return retval;
472                 target = target->next;
473         }
474         return retval;
475 }
476
477 static int target_write_memory_imp(struct target_s *target, u32 address, u32 size, u32 count, u8 *buffer)
478 {
479         if (!target->type->examined)
480         {
481                 LOG_ERROR("Target not examined yet");
482                 return ERROR_FAIL;
483         }
484         return target->type->write_memory_imp(target, address, size, count, buffer);
485 }
486
487 static int target_read_memory_imp(struct target_s *target, u32 address, u32 size, u32 count, u8 *buffer)
488 {
489         if (!target->type->examined)
490         {
491                 LOG_ERROR("Target not examined yet");
492                 return ERROR_FAIL;
493         }
494         return target->type->read_memory_imp(target, address, size, count, buffer);
495 }
496
497 static int target_soft_reset_halt_imp(struct target_s *target)
498 {
499         if (!target->type->examined)
500         {
501                 LOG_ERROR("Target not examined yet");
502                 return ERROR_FAIL;
503         }
504         return target->type->soft_reset_halt_imp(target);
505 }
506
507 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, u32 entry_point, u32 exit_point, int timeout_ms, void *arch_info)
508 {
509         if (!target->type->examined)
510         {
511                 LOG_ERROR("Target not examined yet");
512                 return ERROR_FAIL;
513         }
514         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);
515 }
516
517 int target_init(struct command_context_s *cmd_ctx)
518 {
519         target_t *target = all_targets;
520
521         while (target)
522         {
523                 target->type->examined = 0;
524                 if (target->type->examine == NULL)
525                 {
526                         target->type->examine = default_examine;
527                 }
528
529                 if (target->type->init_target(cmd_ctx, target) != ERROR_OK)
530                 {
531                         LOG_ERROR("target '%s' init failed", target->type->name);
532                         exit(-1);
533                 }
534
535                 /* Set up default functions if none are provided by target */
536                 if (target->type->virt2phys == NULL)
537                 {
538                         target->type->virt2phys = default_virt2phys;
539                 }
540                 target->type->virt2phys = default_virt2phys;
541                 /* a non-invasive way(in terms of patches) to add some code that
542                  * runs before the type->write/read_memory implementation
543                  */
544                 target->type->write_memory_imp = target->type->write_memory;
545                 target->type->write_memory = target_write_memory_imp;
546                 target->type->read_memory_imp = target->type->read_memory;
547                 target->type->read_memory = target_read_memory_imp;
548                 target->type->soft_reset_halt_imp = target->type->soft_reset_halt;
549                 target->type->soft_reset_halt = target_soft_reset_halt_imp;
550                 target->type->run_algorithm_imp = target->type->run_algorithm;
551                 target->type->run_algorithm = target_run_algorithm_imp;
552
553
554                 if (target->type->mmu == NULL)
555                 {
556                         target->type->mmu = default_mmu;
557                 }
558                 target = target->next;
559         }
560
561         if (all_targets)
562         {
563                 target_register_user_commands(cmd_ctx);
564                 target_register_timer_callback(handle_target, 100, 1, NULL);
565         }
566
567         return ERROR_OK;
568 }
569
570 int target_register_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
571 {
572         target_event_callback_t **callbacks_p = &target_event_callbacks;
573
574         if (callback == NULL)
575         {
576                 return ERROR_INVALID_ARGUMENTS;
577         }
578
579         if (*callbacks_p)
580         {
581                 while ((*callbacks_p)->next)
582                         callbacks_p = &((*callbacks_p)->next);
583                 callbacks_p = &((*callbacks_p)->next);
584         }
585
586         (*callbacks_p) = malloc(sizeof(target_event_callback_t));
587         (*callbacks_p)->callback = callback;
588         (*callbacks_p)->priv = priv;
589         (*callbacks_p)->next = NULL;
590
591         return ERROR_OK;
592 }
593
594 int target_register_timer_callback(int (*callback)(void *priv), int time_ms, int periodic, void *priv)
595 {
596         target_timer_callback_t **callbacks_p = &target_timer_callbacks;
597         struct timeval now;
598
599         if (callback == NULL)
600         {
601                 return ERROR_INVALID_ARGUMENTS;
602         }
603
604         if (*callbacks_p)
605         {
606                 while ((*callbacks_p)->next)
607                         callbacks_p = &((*callbacks_p)->next);
608                 callbacks_p = &((*callbacks_p)->next);
609         }
610
611         (*callbacks_p) = malloc(sizeof(target_timer_callback_t));
612         (*callbacks_p)->callback = callback;
613         (*callbacks_p)->periodic = periodic;
614         (*callbacks_p)->time_ms = time_ms;
615
616         gettimeofday(&now, NULL);
617         (*callbacks_p)->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
618         time_ms -= (time_ms % 1000);
619         (*callbacks_p)->when.tv_sec = now.tv_sec + (time_ms / 1000);
620         if ((*callbacks_p)->when.tv_usec > 1000000)
621         {
622                 (*callbacks_p)->when.tv_usec = (*callbacks_p)->when.tv_usec - 1000000;
623                 (*callbacks_p)->when.tv_sec += 1;
624         }
625
626         (*callbacks_p)->priv = priv;
627         (*callbacks_p)->next = NULL;
628
629         return ERROR_OK;
630 }
631
632 int target_unregister_event_callback(int (*callback)(struct target_s *target, enum target_event event, void *priv), void *priv)
633 {
634         target_event_callback_t **p = &target_event_callbacks;
635         target_event_callback_t *c = target_event_callbacks;
636
637         if (callback == NULL)
638         {
639                 return ERROR_INVALID_ARGUMENTS;
640         }
641
642         while (c)
643         {
644                 target_event_callback_t *next = c->next;
645                 if ((c->callback == callback) && (c->priv == priv))
646                 {
647                         *p = next;
648                         free(c);
649                         return ERROR_OK;
650                 }
651                 else
652                         p = &(c->next);
653                 c = next;
654         }
655
656         return ERROR_OK;
657 }
658
659 int target_unregister_timer_callback(int (*callback)(void *priv), void *priv)
660 {
661         target_timer_callback_t **p = &target_timer_callbacks;
662         target_timer_callback_t *c = target_timer_callbacks;
663
664         if (callback == NULL)
665         {
666                 return ERROR_INVALID_ARGUMENTS;
667         }
668
669         while (c)
670         {
671                 target_timer_callback_t *next = c->next;
672                 if ((c->callback == callback) && (c->priv == priv))
673                 {
674                         *p = next;
675                         free(c);
676                         return ERROR_OK;
677                 }
678                 else
679                         p = &(c->next);
680                 c = next;
681         }
682
683         return ERROR_OK;
684 }
685
686 int target_call_event_callbacks(target_t *target, enum target_event event)
687 {
688         target_event_callback_t *callback = target_event_callbacks;
689         target_event_callback_t *next_callback;
690
691         LOG_DEBUG("target event %i", event);
692
693
694         while (callback)
695         {
696                 next_callback = callback->next;
697                 callback->callback(target, event, callback->priv);
698                 callback = next_callback;
699         }
700
701         return ERROR_OK;
702 }
703
704 static int target_call_timer_callbacks_check_time(int checktime)
705 {
706         target_timer_callback_t *callback = target_timer_callbacks;
707         target_timer_callback_t *next_callback;
708         struct timeval now;
709
710         keep_alive();
711
712         gettimeofday(&now, NULL);
713
714         while (callback)
715         {
716                 next_callback = callback->next;
717
718                 if ((!checktime&&callback->periodic)||
719                                 (((now.tv_sec >= callback->when.tv_sec) && (now.tv_usec >= callback->when.tv_usec))
720                                                 || (now.tv_sec > callback->when.tv_sec)))
721                 {
722                         if(callback->callback != NULL)
723                         {
724                                 callback->callback(callback->priv);
725                                 if (callback->periodic)
726                                 {
727                                         int time_ms = callback->time_ms;
728                                         callback->when.tv_usec = now.tv_usec + (time_ms % 1000) * 1000;
729                                         time_ms -= (time_ms % 1000);
730                                         callback->when.tv_sec = now.tv_sec + time_ms / 1000;
731                                         if (callback->when.tv_usec > 1000000)
732                                         {
733                                                 callback->when.tv_usec = callback->when.tv_usec - 1000000;
734                                                 callback->when.tv_sec += 1;
735                                         }
736                                 }
737                                 else
738                                         target_unregister_timer_callback(callback->callback, callback->priv);
739                         }
740                 }
741
742                 callback = next_callback;
743         }
744
745         return ERROR_OK;
746 }
747
748 int target_call_timer_callbacks(void)
749 {
750         return target_call_timer_callbacks_check_time(1);
751 }
752
753 /* invoke periodic callbacks immediately */
754 int target_call_timer_callbacks_now(void)
755 {
756         return target_call_timer_callbacks();
757 }
758
759 int target_alloc_working_area(struct target_s *target, u32 size, working_area_t **area)
760 {
761         working_area_t *c = target->working_areas;
762         working_area_t *new_wa = NULL;
763
764         /* Reevaluate working area address based on MMU state*/
765         if (target->working_areas == NULL)
766         {
767                 int retval;
768                 int enabled;
769                 retval = target->type->mmu(target, &enabled);
770                 if (retval != ERROR_OK)
771                 {
772                         return retval;
773                 }
774                 if (enabled)
775                 {
776                         target->working_area = target->working_area_virt;
777                 }
778                 else
779                 {
780                         target->working_area = target->working_area_phys;
781                 }
782         }
783
784         /* only allocate multiples of 4 byte */
785         if (size % 4)
786         {
787                 LOG_ERROR("BUG: code tried to allocate unaligned number of bytes, padding");
788                 size = CEIL(size, 4);
789         }
790
791         /* see if there's already a matching working area */
792         while (c)
793         {
794                 if ((c->free) && (c->size == size))
795                 {
796                         new_wa = c;
797                         break;
798                 }
799                 c = c->next;
800         }
801
802         /* if not, allocate a new one */
803         if (!new_wa)
804         {
805                 working_area_t **p = &target->working_areas;
806                 u32 first_free = target->working_area;
807                 u32 free_size = target->working_area_size;
808
809                 LOG_DEBUG("allocating new working area");
810
811                 c = target->working_areas;
812                 while (c)
813                 {
814                         first_free += c->size;
815                         free_size -= c->size;
816                         p = &c->next;
817                         c = c->next;
818                 }
819
820                 if (free_size < size)
821                 {
822                         LOG_WARNING("not enough working area available(requested %d, free %d)", size, free_size);
823                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
824                 }
825
826                 new_wa = malloc(sizeof(working_area_t));
827                 new_wa->next = NULL;
828                 new_wa->size = size;
829                 new_wa->address = first_free;
830
831                 if (target->backup_working_area)
832                 {
833                         new_wa->backup = malloc(new_wa->size);
834                         target->type->read_memory(target, new_wa->address, 4, new_wa->size / 4, new_wa->backup);
835                 }
836                 else
837                 {
838                         new_wa->backup = NULL;
839                 }
840
841                 /* put new entry in list */
842                 *p = new_wa;
843         }
844
845         /* mark as used, and return the new (reused) area */
846         new_wa->free = 0;
847         *area = new_wa;
848
849         /* user pointer */
850         new_wa->user = area;
851
852         return ERROR_OK;
853 }
854
855 int target_free_working_area_restore(struct target_s *target, working_area_t *area, int restore)
856 {
857         if (area->free)
858                 return ERROR_OK;
859
860         if (restore&&target->backup_working_area)
861                 target->type->write_memory(target, area->address, 4, area->size / 4, area->backup);
862
863         area->free = 1;
864
865         /* mark user pointer invalid */
866         *area->user = NULL;
867         area->user = NULL;
868
869         return ERROR_OK;
870 }
871
872 int target_free_working_area(struct target_s *target, working_area_t *area)
873 {
874         return target_free_working_area_restore(target, area, 1);
875 }
876
877 int target_free_all_working_areas_restore(struct target_s *target, int restore)
878 {
879         working_area_t *c = target->working_areas;
880
881         while (c)
882         {
883                 working_area_t *next = c->next;
884                 target_free_working_area_restore(target, c, restore);
885
886                 if (c->backup)
887                         free(c->backup);
888
889                 free(c);
890
891                 c = next;
892         }
893
894         target->working_areas = NULL;
895
896         return ERROR_OK;
897 }
898
899 int target_free_all_working_areas(struct target_s *target)
900 {
901         return target_free_all_working_areas_restore(target, 1);
902 }
903
904 int target_register_commands(struct command_context_s *cmd_ctx)
905 {
906         register_command(cmd_ctx, NULL, "target", handle_target_command, COMMAND_CONFIG, "target <cpu> [reset_init default - DEPRECATED] <chainpos> <endianness> <variant> [cpu type specifc args]");
907         register_command(cmd_ctx, NULL, "targets", handle_targets_command, COMMAND_EXEC, NULL);
908         register_command(cmd_ctx, NULL, "working_area", handle_working_area_command, COMMAND_ANY, "working_area <target#> <address> <size> <'backup'|'nobackup'> [virtual address]");
909         register_command(cmd_ctx, NULL, "virt2phys", handle_virt2phys_command, COMMAND_ANY, "virt2phys <virtual address>");
910         register_command(cmd_ctx, NULL, "profile", handle_profile_command, COMMAND_EXEC, "PRELIMINARY! - profile <seconds> <gmon.out>");
911
912
913
914         /* script procedures */
915         register_jim(cmd_ctx, "ocd_mem2array", jim_mem2array, "read memory and return as a TCL array for script processing");
916         register_jim(cmd_ctx, "ocd_array2mem", jim_array2mem, "convert a TCL array to memory locations and write the values");
917         return ERROR_OK;
918 }
919
920 int target_arch_state(struct target_s *target)
921 {
922         int retval;
923         if (target==NULL)
924         {
925                 LOG_USER("No target has been configured");
926                 return ERROR_OK;
927         }
928
929         LOG_USER("target state: %s", 
930                  Jim_Nvp_value2name_simple(nvp_target_state,target->state)->name);
931
932         if (target->state!=TARGET_HALTED)
933                 return ERROR_OK;
934
935         retval=target->type->arch_state(target);
936         return retval;
937 }
938
939 /* Single aligned words are guaranteed to use 16 or 32 bit access
940  * mode respectively, otherwise data is handled as quickly as
941  * possible
942  */
943 int target_write_buffer(struct target_s *target, u32 address, u32 size, u8 *buffer)
944 {
945         int retval;
946         LOG_DEBUG("writing buffer of %i byte at 0x%8.8x", size, address);
947
948         if (!target->type->examined)
949         {
950                 LOG_ERROR("Target not examined yet");
951                 return ERROR_FAIL;
952         }
953
954         if ((address + size - 1) < address)
955         {
956                 /* GDB can request this when e.g. PC is 0xfffffffc*/
957                 LOG_ERROR("address+size wrapped(0x%08x, 0x%08x)", address, size);
958                 return ERROR_FAIL;
959         }
960
961         if (((address % 2) == 0) && (size == 2))
962         {
963                 return target->type->write_memory(target, address, 2, 1, buffer);
964         }
965
966         /* handle unaligned head bytes */
967         if (address % 4)
968         {
969                 int unaligned = 4 - (address % 4);
970
971                 if (unaligned > size)
972                         unaligned = size;
973
974                 if ((retval = target->type->write_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
975                         return retval;
976
977                 buffer += unaligned;
978                 address += unaligned;
979                 size -= unaligned;
980         }
981
982         /* handle aligned words */
983         if (size >= 4)
984         {
985                 int aligned = size - (size % 4);
986
987                 /* use bulk writes above a certain limit. This may have to be changed */
988                 if (aligned > 128)
989                 {
990                         if ((retval = target->type->bulk_write_memory(target, address, aligned / 4, buffer)) != ERROR_OK)
991                                 return retval;
992                 }
993                 else
994                 {
995                         if ((retval = target->type->write_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
996                                 return retval;
997                 }
998
999                 buffer += aligned;
1000                 address += aligned;
1001                 size -= aligned;
1002         }
1003
1004         /* handle tail writes of less than 4 bytes */
1005         if (size > 0)
1006         {
1007                 if ((retval = target->type->write_memory(target, address, 1, size, buffer)) != ERROR_OK)
1008                         return retval;
1009         }
1010
1011         return ERROR_OK;
1012 }
1013
1014
1015 /* Single aligned words are guaranteed to use 16 or 32 bit access
1016  * mode respectively, otherwise data is handled as quickly as
1017  * possible
1018  */
1019 int target_read_buffer(struct target_s *target, u32 address, u32 size, u8 *buffer)
1020 {
1021         int retval;
1022         LOG_DEBUG("reading buffer of %i byte at 0x%8.8x", size, address);
1023
1024         if (!target->type->examined)
1025         {
1026                 LOG_ERROR("Target not examined yet");
1027                 return ERROR_FAIL;
1028         }
1029
1030         if ((address + size - 1) < address)
1031         {
1032                 /* GDB can request this when e.g. PC is 0xfffffffc*/
1033                 LOG_ERROR("address+size wrapped(0x%08x, 0x%08x)", address, size);
1034                 return ERROR_FAIL;
1035         }
1036
1037         if (((address % 2) == 0) && (size == 2))
1038         {
1039                 return target->type->read_memory(target, address, 2, 1, buffer);
1040         }
1041
1042         /* handle unaligned head bytes */
1043         if (address % 4)
1044         {
1045                 int unaligned = 4 - (address % 4);
1046
1047                 if (unaligned > size)
1048                         unaligned = size;
1049
1050                 if ((retval = target->type->read_memory(target, address, 1, unaligned, buffer)) != ERROR_OK)
1051                         return retval;
1052
1053                 buffer += unaligned;
1054                 address += unaligned;
1055                 size -= unaligned;
1056         }
1057
1058         /* handle aligned words */
1059         if (size >= 4)
1060         {
1061                 int aligned = size - (size % 4);
1062
1063                 if ((retval = target->type->read_memory(target, address, 4, aligned / 4, buffer)) != ERROR_OK)
1064                         return retval;
1065
1066                 buffer += aligned;
1067                 address += aligned;
1068                 size -= aligned;
1069         }
1070
1071         /* handle tail writes of less than 4 bytes */
1072         if (size > 0)
1073         {
1074                 if ((retval = target->type->read_memory(target, address, 1, size, buffer)) != ERROR_OK)
1075                         return retval;
1076         }
1077
1078         return ERROR_OK;
1079 }
1080
1081 int target_checksum_memory(struct target_s *target, u32 address, u32 size, u32* crc)
1082 {
1083         u8 *buffer;
1084         int retval;
1085         int i;
1086         u32 checksum = 0;
1087         if (!target->type->examined)
1088         {
1089                 LOG_ERROR("Target not examined yet");
1090                 return ERROR_FAIL;
1091         }
1092
1093         if ((retval = target->type->checksum_memory(target, address,
1094                 size, &checksum)) == ERROR_TARGET_RESOURCE_NOT_AVAILABLE)
1095         {
1096                 buffer = malloc(size);
1097                 if (buffer == NULL)
1098                 {
1099                         LOG_ERROR("error allocating buffer for section (%d bytes)", size);
1100                         return ERROR_INVALID_ARGUMENTS;
1101                 }
1102                 retval = target_read_buffer(target, address, size, buffer);
1103                 if (retval != ERROR_OK)
1104                 {
1105                         free(buffer);
1106                         return retval;
1107                 }
1108
1109                 /* convert to target endianess */
1110                 for (i = 0; i < (size/sizeof(u32)); i++)
1111                 {
1112                         u32 target_data;
1113                         target_data = target_buffer_get_u32(target, &buffer[i*sizeof(u32)]);
1114                         target_buffer_set_u32(target, &buffer[i*sizeof(u32)], target_data);
1115                 }
1116
1117                 retval = image_calculate_checksum( buffer, size, &checksum );
1118                 free(buffer);
1119         }
1120
1121         *crc = checksum;
1122
1123         return retval;
1124 }
1125
1126 int target_blank_check_memory(struct target_s *target, u32 address, u32 size, u32* blank)
1127 {
1128         int retval;
1129         if (!target->type->examined)
1130         {
1131                 LOG_ERROR("Target not examined yet");
1132                 return ERROR_FAIL;
1133         }
1134
1135         if (target->type->blank_check_memory == 0)
1136                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1137
1138         retval = target->type->blank_check_memory(target, address, size, blank);
1139
1140         return retval;
1141 }
1142
1143 int target_read_u32(struct target_s *target, u32 address, u32 *value)
1144 {
1145         u8 value_buf[4];
1146         if (!target->type->examined)
1147         {
1148                 LOG_ERROR("Target not examined yet");
1149                 return ERROR_FAIL;
1150         }
1151
1152         int retval = target->type->read_memory(target, address, 4, 1, value_buf);
1153
1154         if (retval == ERROR_OK)
1155         {
1156                 *value = target_buffer_get_u32(target, value_buf);
1157                 LOG_DEBUG("address: 0x%8.8x, value: 0x%8.8x", address, *value);
1158         }
1159         else
1160         {
1161                 *value = 0x0;
1162                 LOG_DEBUG("address: 0x%8.8x failed", address);
1163         }
1164
1165         return retval;
1166 }
1167
1168 int target_read_u16(struct target_s *target, u32 address, u16 *value)
1169 {
1170         u8 value_buf[2];
1171         if (!target->type->examined)
1172         {
1173                 LOG_ERROR("Target not examined yet");
1174                 return ERROR_FAIL;
1175         }
1176
1177         int retval = target->type->read_memory(target, address, 2, 1, value_buf);
1178
1179         if (retval == ERROR_OK)
1180         {
1181                 *value = target_buffer_get_u16(target, value_buf);
1182                 LOG_DEBUG("address: 0x%8.8x, value: 0x%4.4x", address, *value);
1183         }
1184         else
1185         {
1186                 *value = 0x0;
1187                 LOG_DEBUG("address: 0x%8.8x failed", address);
1188         }
1189
1190         return retval;
1191 }
1192
1193 int target_read_u8(struct target_s *target, u32 address, u8 *value)
1194 {
1195         int retval = target->type->read_memory(target, address, 1, 1, value);
1196         if (!target->type->examined)
1197         {
1198                 LOG_ERROR("Target not examined yet");
1199                 return ERROR_FAIL;
1200         }
1201
1202         if (retval == ERROR_OK)
1203         {
1204                 LOG_DEBUG("address: 0x%8.8x, value: 0x%2.2x", address, *value);
1205         }
1206         else
1207         {
1208                 *value = 0x0;
1209                 LOG_DEBUG("address: 0x%8.8x failed", address);
1210         }
1211
1212         return retval;
1213 }
1214
1215 int target_write_u32(struct target_s *target, u32 address, u32 value)
1216 {
1217         int retval;
1218         u8 value_buf[4];
1219         if (!target->type->examined)
1220         {
1221                 LOG_ERROR("Target not examined yet");
1222                 return ERROR_FAIL;
1223         }
1224
1225         LOG_DEBUG("address: 0x%8.8x, value: 0x%8.8x", address, value);
1226
1227         target_buffer_set_u32(target, value_buf, value);
1228         if ((retval = target->type->write_memory(target, address, 4, 1, value_buf)) != ERROR_OK)
1229         {
1230                 LOG_DEBUG("failed: %i", retval);
1231         }
1232
1233         return retval;
1234 }
1235
1236 int target_write_u16(struct target_s *target, u32 address, u16 value)
1237 {
1238         int retval;
1239         u8 value_buf[2];
1240         if (!target->type->examined)
1241         {
1242                 LOG_ERROR("Target not examined yet");
1243                 return ERROR_FAIL;
1244         }
1245
1246         LOG_DEBUG("address: 0x%8.8x, value: 0x%8.8x", address, value);
1247
1248         target_buffer_set_u16(target, value_buf, value);
1249         if ((retval = target->type->write_memory(target, address, 2, 1, value_buf)) != ERROR_OK)
1250         {
1251                 LOG_DEBUG("failed: %i", retval);
1252         }
1253
1254         return retval;
1255 }
1256
1257 int target_write_u8(struct target_s *target, u32 address, u8 value)
1258 {
1259         int retval;
1260         if (!target->type->examined)
1261         {
1262                 LOG_ERROR("Target not examined yet");
1263                 return ERROR_FAIL;
1264         }
1265
1266         LOG_DEBUG("address: 0x%8.8x, value: 0x%2.2x", address, value);
1267
1268         if ((retval = target->type->read_memory(target, address, 1, 1, &value)) != ERROR_OK)
1269         {
1270                 LOG_DEBUG("failed: %i", retval);
1271         }
1272
1273         return retval;
1274 }
1275
1276 int target_register_user_commands(struct command_context_s *cmd_ctx)
1277 {
1278         register_command(cmd_ctx,  NULL, "reg", handle_reg_command, COMMAND_EXEC, NULL);
1279         register_command(cmd_ctx,  NULL, "poll", handle_poll_command, COMMAND_EXEC, "poll target state");
1280         register_command(cmd_ctx,  NULL, "wait_halt", handle_wait_halt_command, COMMAND_EXEC, "wait for target halt [time (s)]");
1281         register_command(cmd_ctx,  NULL, "halt", handle_halt_command, COMMAND_EXEC, "halt target");
1282         register_command(cmd_ctx,  NULL, "resume", handle_resume_command, COMMAND_EXEC, "resume target [addr]");
1283         register_command(cmd_ctx,  NULL, "step", handle_step_command, COMMAND_EXEC, "step one instruction from current PC or [addr]");
1284         register_command(cmd_ctx,  NULL, "reset", handle_reset_command, COMMAND_EXEC, "reset target [run|halt|init] - default is run");
1285         register_command(cmd_ctx,  NULL, "soft_reset_halt", handle_soft_reset_halt_command, COMMAND_EXEC, "halt the target and do a soft reset");
1286
1287         register_command(cmd_ctx,  NULL, "mdw", handle_md_command, COMMAND_EXEC, "display memory words <addr> [count]");
1288         register_command(cmd_ctx,  NULL, "mdh", handle_md_command, COMMAND_EXEC, "display memory half-words <addr> [count]");
1289         register_command(cmd_ctx,  NULL, "mdb", handle_md_command, COMMAND_EXEC, "display memory bytes <addr> [count]");
1290
1291         register_command(cmd_ctx,  NULL, "mww", handle_mw_command, COMMAND_EXEC, "write memory word <addr> <value> [count]");
1292         register_command(cmd_ctx,  NULL, "mwh", handle_mw_command, COMMAND_EXEC, "write memory half-word <addr> <value> [count]");
1293         register_command(cmd_ctx,  NULL, "mwb", handle_mw_command, COMMAND_EXEC, "write memory byte <addr> <value> [count]");
1294
1295         register_command(cmd_ctx,  NULL, "bp", handle_bp_command, COMMAND_EXEC, "set breakpoint <address> <length> [hw]");
1296         register_command(cmd_ctx,  NULL, "rbp", handle_rbp_command, COMMAND_EXEC, "remove breakpoint <adress>");
1297         register_command(cmd_ctx,  NULL, "wp", handle_wp_command, COMMAND_EXEC, "set watchpoint <address> <length> <r/w/a> [value] [mask]");
1298         register_command(cmd_ctx,  NULL, "rwp", handle_rwp_command, COMMAND_EXEC, "remove watchpoint <adress>");
1299
1300         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]");
1301         register_command(cmd_ctx,  NULL, "dump_image", handle_dump_image_command, COMMAND_EXEC, "dump_image <file> <address> <size>");
1302         register_command(cmd_ctx,  NULL, "verify_image", handle_verify_image_command, COMMAND_EXEC, "verify_image <file> [offset] [type]");
1303
1304         target_request_register_commands(cmd_ctx);
1305         trace_register_commands(cmd_ctx);
1306
1307         return ERROR_OK;
1308 }
1309
1310 int handle_targets_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1311 {
1312         char *cp;
1313         target_t *target = all_targets;
1314
1315         if (argc == 1)
1316         {
1317                 /* try as tcltarget name */
1318                 for( target = all_targets ; target ; target++ ){
1319                   if( target->cmd_name ){
1320                         if( 0 == strcmp( args[0], target->cmd_name ) ){
1321                                 /* MATCH */
1322                                 goto Match;
1323                         } 
1324                   }
1325                 }
1326                 /* no match, try as number */
1327                 
1328                 int num = strtoul(args[0], &cp, 0 );
1329                 if( *cp != 0 ){
1330                         /* then it was not a number */
1331                         command_print( cmd_ctx, "Target: %s unknown, try one of:\n", args[0] );
1332                         goto DumpTargets;
1333                 }
1334                         
1335                 target = get_target_by_num( num );
1336                 if( target == NULL ){
1337                         command_print(cmd_ctx,"Target: %s is unknown, try one of:\n", args[0] );
1338                         goto DumpTargets;
1339                 }
1340         Match:
1341                 cmd_ctx->current_target = target->target_number;
1342                 return ERROR_OK;
1343         }
1344  DumpTargets:
1345
1346         command_print(cmd_ctx, "    CmdName    Type       Endian     State     ");
1347         command_print(cmd_ctx, "--  ---------- ---------- ---------- ----------");
1348         while (target)
1349         {
1350                 /* XX: abcdefghij abcdefghij abcdefghij abcdefghij */
1351                 command_print(cmd_ctx, "%2d: %-10s %-10s %-10s %s", 
1352                                           target->target_number,
1353                                           "", // future: target->cmd_name
1354                                           target->type->name, 
1355                                           Jim_Nvp_value2name_simple( nvp_target_endian, target->endianness )->name, 
1356                                           Jim_Nvp_value2name_simple( nvp_target_state, target->state )->name );
1357                 target = target->next;
1358         }
1359
1360         return ERROR_OK;
1361 }
1362
1363 int handle_target_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1364 {
1365         int i;
1366         int found = 0;
1367
1368         if (argc < 3)
1369         {
1370                 return ERROR_COMMAND_SYNTAX_ERROR;
1371         }
1372
1373         /* search for the specified target */
1374         if (args[0] && (args[0][0] != 0))
1375         {
1376                 for (i = 0; target_types[i]; i++)
1377                 {
1378                         if (strcmp(args[0], target_types[i]->name) == 0)
1379                         {
1380                                 target_t **last_target_p = &all_targets;
1381
1382                                 /* register target specific commands */
1383                                 if (target_types[i]->register_commands(cmd_ctx) != ERROR_OK)
1384                                 {
1385                                         LOG_ERROR("couldn't register '%s' commands", args[0]);
1386                                         exit(-1);
1387                                 }
1388
1389                                 if (*last_target_p)
1390                                 {
1391                                         while ((*last_target_p)->next)
1392                                                 last_target_p = &((*last_target_p)->next);
1393                                         last_target_p = &((*last_target_p)->next);
1394                                 }
1395
1396                                 // get target number *before* adding new target to the list */
1397                                 int n = new_target_number();
1398                                 // calloc will init the memory to zero for us
1399                                 *last_target_p = calloc(1,sizeof(target_t));
1400                                 // save target number.
1401                                 (*last_target_p)->cmd_name = NULL;
1402                                 (*last_target_p)->target_number = n;
1403
1404                                 /* allocate memory for each unique target type */
1405                                 (*last_target_p)->type = (target_type_t*)malloc(sizeof(target_type_t));
1406                                 *((*last_target_p)->type) = *target_types[i];
1407
1408                                 if (strcmp(args[1], "big") == 0)
1409                                         (*last_target_p)->endianness = TARGET_BIG_ENDIAN;
1410                                 else if (strcmp(args[1], "little") == 0)
1411                                         (*last_target_p)->endianness = TARGET_LITTLE_ENDIAN;
1412                                 else
1413                                 {
1414                                         LOG_ERROR("endianness must be either 'little' or 'big', not '%s'", args[1]);
1415                                         return ERROR_COMMAND_SYNTAX_ERROR;
1416                                 }
1417
1418                                 if (strcmp(args[2], "reset_halt") == 0)
1419                                 {
1420                                         LOG_WARNING("reset_mode argument is obsolete.");
1421                                         return ERROR_COMMAND_SYNTAX_ERROR;
1422                                 }
1423                                 else if (strcmp(args[2], "reset_run") == 0)
1424                                 {
1425                                         LOG_WARNING("reset_mode argument is obsolete.");
1426                                         return ERROR_COMMAND_SYNTAX_ERROR;
1427                                 }
1428                                 else if (strcmp(args[2], "reset_init") == 0)
1429                                 {
1430                                         LOG_WARNING("reset_mode argument is obsolete.");
1431                                         return ERROR_COMMAND_SYNTAX_ERROR;
1432                                 }
1433                                 else if (strcmp(args[2], "run_and_halt") == 0)
1434                                 {
1435                                         LOG_WARNING("reset_mode argument is obsolete.");
1436                                         return ERROR_COMMAND_SYNTAX_ERROR;
1437                                 }
1438                                 else if (strcmp(args[2], "run_and_init") == 0)
1439                                 {
1440                                         LOG_WARNING("reset_mode argument is obsolete.");
1441                                         return ERROR_COMMAND_SYNTAX_ERROR;
1442                                 }
1443                                 else
1444                                 {
1445                                         /* Kludge! we want to make this reset arg optional while remaining compatible! */
1446                                         args--;
1447                                         argc++;
1448                                 }
1449
1450                                 (*last_target_p)->working_area = 0x0;
1451                                 (*last_target_p)->working_area_size = 0x0;
1452                                 (*last_target_p)->working_areas = NULL;
1453                                 (*last_target_p)->backup_working_area = 0;
1454
1455                                 (*last_target_p)->state = TARGET_UNKNOWN;
1456                                 (*last_target_p)->debug_reason = DBG_REASON_UNDEFINED;
1457                                 (*last_target_p)->reg_cache = NULL;
1458                                 (*last_target_p)->breakpoints = NULL;
1459                                 (*last_target_p)->watchpoints = NULL;
1460                                 (*last_target_p)->next = NULL;
1461                                 (*last_target_p)->arch_info = NULL;
1462
1463                                 /* initialize trace information */
1464                                 (*last_target_p)->trace_info = malloc(sizeof(trace_t));
1465                                 (*last_target_p)->trace_info->num_trace_points = 0;
1466                                 (*last_target_p)->trace_info->trace_points_size = 0;
1467                                 (*last_target_p)->trace_info->trace_points = NULL;
1468                                 (*last_target_p)->trace_info->trace_history_size = 0;
1469                                 (*last_target_p)->trace_info->trace_history = NULL;
1470                                 (*last_target_p)->trace_info->trace_history_pos = 0;
1471                                 (*last_target_p)->trace_info->trace_history_overflowed = 0;
1472
1473                                 (*last_target_p)->dbgmsg = NULL;
1474                                 (*last_target_p)->dbg_msg_enabled = 0;
1475
1476                                 (*last_target_p)->type->target_command(cmd_ctx, cmd, args, argc, *last_target_p);
1477
1478                                 found = 1;
1479                                 break;
1480                         }
1481                 }
1482         }
1483
1484         /* no matching target found */
1485         if (!found)
1486         {
1487                 LOG_ERROR("target '%s' not found", args[0]);
1488                 return ERROR_COMMAND_SYNTAX_ERROR;
1489         }
1490
1491         return ERROR_OK;
1492 }
1493
1494 int target_invoke_script(struct command_context_s *cmd_ctx, target_t *target, char *name)
1495 {
1496         return command_run_linef(cmd_ctx, " if {[catch {info body target_%d_%s} t]==0} {target_%d_%s}",
1497                         get_num_by_target(target), name,
1498                         get_num_by_target(target), name);
1499 }
1500
1501 int handle_working_area_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1502 {
1503         target_t *target = NULL;
1504
1505         if ((argc < 4) || (argc > 5))
1506         {
1507                 return ERROR_COMMAND_SYNTAX_ERROR;
1508         }
1509
1510         target = get_target_by_num(strtoul(args[0], NULL, 0));
1511         if (!target)
1512         {
1513                 return ERROR_COMMAND_SYNTAX_ERROR;
1514         }
1515         target_free_all_working_areas(target);
1516
1517         target->working_area_phys = target->working_area_virt = strtoul(args[1], NULL, 0);
1518         if (argc == 5)
1519         {
1520                 target->working_area_virt = strtoul(args[4], NULL, 0);
1521         }
1522         target->working_area_size = strtoul(args[2], NULL, 0);
1523
1524         if (strcmp(args[3], "backup") == 0)
1525         {
1526                 target->backup_working_area = 1;
1527         }
1528         else if (strcmp(args[3], "nobackup") == 0)
1529         {
1530                 target->backup_working_area = 0;
1531         }
1532         else
1533         {
1534                 LOG_ERROR("unrecognized <backup|nobackup> argument (%s)", args[3]);
1535                 return ERROR_COMMAND_SYNTAX_ERROR;
1536         }
1537
1538         return ERROR_OK;
1539 }
1540
1541
1542 /* process target state changes */
1543 int handle_target(void *priv)
1544 {
1545         target_t *target = all_targets;
1546
1547         while (target)
1548         {
1549                 if (target_continous_poll)
1550                 {
1551                         /* polling may fail silently until the target has been examined */
1552                         target_poll(target);
1553                 }
1554
1555                 target = target->next;
1556         }
1557
1558         return ERROR_OK;
1559 }
1560
1561 int handle_reg_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1562 {
1563         target_t *target;
1564         reg_t *reg = NULL;
1565         int count = 0;
1566         char *value;
1567
1568         LOG_DEBUG("-");
1569
1570         target = get_current_target(cmd_ctx);
1571
1572         /* list all available registers for the current target */
1573         if (argc == 0)
1574         {
1575                 reg_cache_t *cache = target->reg_cache;
1576
1577                 count = 0;
1578                 while(cache)
1579                 {
1580                         int i;
1581                         for (i = 0; i < cache->num_regs; i++)
1582                         {
1583                                 value = buf_to_str(cache->reg_list[i].value, cache->reg_list[i].size, 16);
1584                                 command_print(cmd_ctx, "(%i) %s (/%i): 0x%s (dirty: %i, valid: %i)", count++, cache->reg_list[i].name, cache->reg_list[i].size, value, cache->reg_list[i].dirty, cache->reg_list[i].valid);
1585                                 free(value);
1586                         }
1587                         cache = cache->next;
1588                 }
1589
1590                 return ERROR_OK;
1591         }
1592
1593         /* access a single register by its ordinal number */
1594         if ((args[0][0] >= '0') && (args[0][0] <= '9'))
1595         {
1596                 int num = strtoul(args[0], NULL, 0);
1597                 reg_cache_t *cache = target->reg_cache;
1598
1599                 count = 0;
1600                 while(cache)
1601                 {
1602                         int i;
1603                         for (i = 0; i < cache->num_regs; i++)
1604                         {
1605                                 if (count++ == num)
1606                                 {
1607                                         reg = &cache->reg_list[i];
1608                                         break;
1609                                 }
1610                         }
1611                         if (reg)
1612                                 break;
1613                         cache = cache->next;
1614                 }
1615
1616                 if (!reg)
1617                 {
1618                         command_print(cmd_ctx, "%i is out of bounds, the current target has only %i registers (0 - %i)", num, count, count - 1);
1619                         return ERROR_OK;
1620                 }
1621         } else /* access a single register by its name */
1622         {
1623                 reg = register_get_by_name(target->reg_cache, args[0], 1);
1624
1625                 if (!reg)
1626                 {
1627                         command_print(cmd_ctx, "register %s not found in current target", args[0]);
1628                         return ERROR_OK;
1629                 }
1630         }
1631
1632         /* display a register */
1633         if ((argc == 1) || ((argc == 2) && !((args[1][0] >= '0') && (args[1][0] <= '9'))))
1634         {
1635                 if ((argc == 2) && (strcmp(args[1], "force") == 0))
1636                         reg->valid = 0;
1637
1638                 if (reg->valid == 0)
1639                 {
1640                         reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1641                         if (arch_type == NULL)
1642                         {
1643                                 LOG_ERROR("BUG: encountered unregistered arch type");
1644                                 return ERROR_OK;
1645                         }
1646                         arch_type->get(reg);
1647                 }
1648                 value = buf_to_str(reg->value, reg->size, 16);
1649                 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, reg->size, value);
1650                 free(value);
1651                 return ERROR_OK;
1652         }
1653
1654         /* set register value */
1655         if (argc == 2)
1656         {
1657                 u8 *buf = malloc(CEIL(reg->size, 8));
1658                 str_to_buf(args[1], strlen(args[1]), buf, reg->size, 0);
1659
1660                 reg_arch_type_t *arch_type = register_get_arch_type(reg->arch_type);
1661                 if (arch_type == NULL)
1662                 {
1663                         LOG_ERROR("BUG: encountered unregistered arch type");
1664                         return ERROR_OK;
1665                 }
1666
1667                 arch_type->set(reg, buf);
1668
1669                 value = buf_to_str(reg->value, reg->size, 16);
1670                 command_print(cmd_ctx, "%s (/%i): 0x%s", reg->name, reg->size, value);
1671                 free(value);
1672
1673                 free(buf);
1674
1675                 return ERROR_OK;
1676         }
1677
1678         command_print(cmd_ctx, "usage: reg <#|name> [value]");
1679
1680         return ERROR_OK;
1681 }
1682
1683
1684 int handle_poll_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1685 {
1686         target_t *target = get_current_target(cmd_ctx);
1687
1688         if (argc == 0)
1689         {
1690                 target_poll(target);
1691                 target_arch_state(target);
1692         }
1693         else
1694         {
1695                 if (strcmp(args[0], "on") == 0)
1696                 {
1697                         target_continous_poll = 1;
1698                 }
1699                 else if (strcmp(args[0], "off") == 0)
1700                 {
1701                         target_continous_poll = 0;
1702                 }
1703                 else
1704                 {
1705                         command_print(cmd_ctx, "arg is \"on\" or \"off\"");
1706                 }
1707         }
1708
1709
1710         return ERROR_OK;
1711 }
1712
1713 int handle_wait_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1714 {
1715         int ms = 5000;
1716
1717         if (argc > 0)
1718         {
1719                 char *end;
1720
1721                 ms = strtoul(args[0], &end, 0) * 1000;
1722                 if (*end)
1723                 {
1724                         command_print(cmd_ctx, "usage: %s [seconds]", cmd);
1725                         return ERROR_OK;
1726                 }
1727         }
1728         target_t *target = get_current_target(cmd_ctx);
1729
1730         return target_wait_state(target, TARGET_HALTED, ms);
1731 }
1732
1733 int target_wait_state(target_t *target, enum target_state state, int ms)
1734 {
1735         int retval;
1736         struct timeval timeout, now;
1737         int once=1;
1738         gettimeofday(&timeout, NULL);
1739         timeval_add_time(&timeout, 0, ms * 1000);
1740
1741         for (;;)
1742         {
1743                 if ((retval=target_poll(target))!=ERROR_OK)
1744                         return retval;
1745                 keep_alive();
1746                 if (target->state == state)
1747                 {
1748                         break;
1749                 }
1750                 if (once)
1751                 {
1752                         once=0;
1753                         LOG_DEBUG("waiting for target %s...", 
1754                               Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
1755                 }
1756
1757                 gettimeofday(&now, NULL);
1758                 if ((now.tv_sec > timeout.tv_sec) || ((now.tv_sec == timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
1759                 {
1760                         LOG_ERROR("timed out while waiting for target %s", 
1761                               Jim_Nvp_value2name_simple(nvp_target_state,state)->name);
1762                         return ERROR_FAIL;
1763                 }
1764         }
1765
1766         return ERROR_OK;
1767 }
1768
1769 int handle_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1770 {
1771         int retval;
1772         target_t *target = get_current_target(cmd_ctx);
1773
1774         LOG_DEBUG("-");
1775
1776         if ((retval = target_halt(target)) != ERROR_OK)
1777         {
1778                 return retval;
1779         }
1780
1781         return handle_wait_halt_command(cmd_ctx, cmd, args, argc);
1782 }
1783
1784 int handle_soft_reset_halt_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1785 {
1786         target_t *target = get_current_target(cmd_ctx);
1787
1788         LOG_USER("requesting target halt and executing a soft reset");
1789
1790         target->type->soft_reset_halt(target);
1791
1792         return ERROR_OK;
1793 }
1794
1795 int handle_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1796 {
1797         enum target_reset_mode reset_mode = RESET_RUN;
1798
1799         if (argc >= 1)
1800         {
1801                 if (strcmp("run", args[0]) == 0)
1802                         reset_mode = RESET_RUN;
1803                 else if (strcmp("halt", args[0]) == 0)
1804                         reset_mode = RESET_HALT;
1805                 else if (strcmp("init", args[0]) == 0)
1806                         reset_mode = RESET_INIT;
1807                 else
1808                 {
1809                         return ERROR_COMMAND_SYNTAX_ERROR;
1810                 }
1811         }
1812
1813         /* reset *all* targets */
1814         return target_process_reset(cmd_ctx, reset_mode);
1815 }
1816
1817 int handle_resume_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1818 {
1819         int retval;
1820         target_t *target = get_current_target(cmd_ctx);
1821
1822         target_invoke_script(cmd_ctx, target, "pre_resume");
1823
1824         if (argc == 0)
1825                 retval = target_resume(target, 1, 0, 1, 0); /* current pc, addr = 0, handle breakpoints, not debugging */
1826         else if (argc == 1)
1827                 retval = target_resume(target, 0, strtoul(args[0], NULL, 0), 1, 0); /* addr = args[0], handle breakpoints, not debugging */
1828         else
1829         {
1830                 return ERROR_COMMAND_SYNTAX_ERROR;
1831         }
1832
1833         return retval;
1834 }
1835
1836 int handle_step_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1837 {
1838         target_t *target = get_current_target(cmd_ctx);
1839
1840         LOG_DEBUG("-");
1841
1842         if (argc == 0)
1843                 target->type->step(target, 1, 0, 1); /* current pc, addr = 0, handle breakpoints */
1844
1845         if (argc == 1)
1846                 target->type->step(target, 0, strtoul(args[0], NULL, 0), 1); /* addr = args[0], handle breakpoints */
1847
1848         return ERROR_OK;
1849 }
1850
1851 int handle_md_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1852 {
1853         const int line_bytecnt = 32;
1854         int count = 1;
1855         int size = 4;
1856         u32 address = 0;
1857         int line_modulo;
1858         int i;
1859
1860         char output[128];
1861         int output_len;
1862
1863         int retval;
1864
1865         u8 *buffer;
1866         target_t *target = get_current_target(cmd_ctx);
1867
1868         if (argc < 1)
1869                 return ERROR_OK;
1870
1871         if (argc == 2)
1872                 count = strtoul(args[1], NULL, 0);
1873
1874         address = strtoul(args[0], NULL, 0);
1875
1876
1877         switch (cmd[2])
1878         {
1879                 case 'w':
1880                         size = 4; line_modulo = line_bytecnt / 4;
1881                         break;
1882                 case 'h':
1883                         size = 2; line_modulo = line_bytecnt / 2;
1884                         break;
1885                 case 'b':
1886                         size = 1; line_modulo = line_bytecnt / 1;
1887                         break;
1888                 default:
1889                         return ERROR_OK;
1890         }
1891
1892         buffer = calloc(count, size);
1893         retval  = target->type->read_memory(target, address, size, count, buffer);
1894         if (retval == ERROR_OK)
1895         {
1896                 output_len = 0;
1897
1898                 for (i = 0; i < count; i++)
1899                 {
1900                         if (i%line_modulo == 0)
1901                                 output_len += snprintf(output + output_len, 128 - output_len, "0x%8.8x: ", address + (i*size));
1902
1903                         switch (size)
1904                         {
1905                                 case 4:
1906                                         output_len += snprintf(output + output_len, 128 - output_len, "%8.8x ", target_buffer_get_u32(target, &buffer[i*4]));
1907                                         break;
1908                                 case 2:
1909                                         output_len += snprintf(output + output_len, 128 - output_len, "%4.4x ", target_buffer_get_u16(target, &buffer[i*2]));
1910                                         break;
1911                                 case 1:
1912                                         output_len += snprintf(output + output_len, 128 - output_len, "%2.2x ", buffer[i*1]);
1913                                         break;
1914                         }
1915
1916                         if ((i%line_modulo == line_modulo-1) || (i == count - 1))
1917                         {
1918                                 command_print(cmd_ctx, output);
1919                                 output_len = 0;
1920                         }
1921                 }
1922         }
1923
1924         free(buffer);
1925
1926         return retval;
1927 }
1928
1929 int handle_mw_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1930 {
1931         u32 address = 0;
1932         u32 value = 0;
1933         int count = 1;
1934         int i;
1935         int wordsize;
1936         target_t *target = get_current_target(cmd_ctx);
1937         u8 value_buf[4];
1938
1939          if ((argc < 2) || (argc > 3))
1940                 return ERROR_COMMAND_SYNTAX_ERROR;
1941
1942         address = strtoul(args[0], NULL, 0);
1943         value = strtoul(args[1], NULL, 0);
1944         if (argc == 3)
1945                 count = strtoul(args[2], NULL, 0);
1946
1947         switch (cmd[2])
1948         {
1949                 case 'w':
1950                         wordsize = 4;
1951                         target_buffer_set_u32(target, value_buf, value);
1952                         break;
1953                 case 'h':
1954                         wordsize = 2;
1955                         target_buffer_set_u16(target, value_buf, value);
1956                         break;
1957                 case 'b':
1958                         wordsize = 1;
1959                         value_buf[0] = value;
1960                         break;
1961                 default:
1962                         return ERROR_COMMAND_SYNTAX_ERROR;
1963         }
1964         for (i=0; i<count; i++)
1965         {
1966                 int retval;
1967                 switch (wordsize)
1968                 {
1969                         case 4:
1970                                 retval = target->type->write_memory(target, address + i*wordsize, 4, 1, value_buf);
1971                                 break;
1972                         case 2:
1973                                 retval = target->type->write_memory(target, address + i*wordsize, 2, 1, value_buf);
1974                                 break;
1975                         case 1:
1976                                 retval = target->type->write_memory(target, address + i*wordsize, 1, 1, value_buf);
1977                         break;
1978                         default:
1979                         return ERROR_OK;
1980                 }
1981                 if (retval!=ERROR_OK)
1982                 {
1983                         return retval;
1984                 }
1985         }
1986
1987         return ERROR_OK;
1988
1989 }
1990
1991 int handle_load_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1992 {
1993         u8 *buffer;
1994         u32 buf_cnt;
1995         u32 image_size;
1996         u32 min_address=0;
1997         u32 max_address=0xffffffff;
1998         int i;
1999         int retval;
2000
2001         image_t image;
2002
2003         duration_t duration;
2004         char *duration_text;
2005
2006         target_t *target = get_current_target(cmd_ctx);
2007
2008         if ((argc < 1)||(argc > 5))
2009         {
2010                 return ERROR_COMMAND_SYNTAX_ERROR;
2011         }
2012
2013         /* a base address isn't always necessary, default to 0x0 (i.e. don't relocate) */
2014         if (argc >= 2)
2015         {
2016                 image.base_address_set = 1;
2017                 image.base_address = strtoul(args[1], NULL, 0);
2018         }
2019         else
2020         {
2021                 image.base_address_set = 0;
2022         }
2023
2024
2025         image.start_address_set = 0;
2026
2027         if (argc>=4)
2028         {
2029                 min_address=strtoul(args[3], NULL, 0);
2030         }
2031         if (argc>=5)
2032         {
2033                 max_address=strtoul(args[4], NULL, 0)+min_address;
2034         }
2035
2036         if (min_address>max_address)
2037         {
2038                 return ERROR_COMMAND_SYNTAX_ERROR;
2039         }
2040
2041
2042         duration_start_measure(&duration);
2043
2044         if (image_open(&image, args[0], (argc >= 3) ? args[2] : NULL) != ERROR_OK)
2045         {
2046                 return ERROR_OK;
2047         }
2048
2049         image_size = 0x0;
2050         retval = ERROR_OK;
2051         for (i = 0; i < image.num_sections; i++)
2052         {
2053                 buffer = malloc(image.sections[i].size);
2054                 if (buffer == NULL)
2055                 {
2056                         command_print(cmd_ctx, "error allocating buffer for section (%d bytes)", image.sections[i].size);
2057                         break;
2058                 }
2059
2060                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2061                 {
2062                         free(buffer);
2063                         break;
2064                 }
2065
2066                 u32 offset=0;
2067                 u32 length=buf_cnt;
2068
2069
2070                 /* DANGER!!! beware of unsigned comparision here!!! */
2071
2072                 if ((image.sections[i].base_address+buf_cnt>=min_address)&&
2073                                 (image.sections[i].base_address<max_address))
2074                 {
2075                         if (image.sections[i].base_address<min_address)
2076                         {
2077                                 /* clip addresses below */
2078                                 offset+=min_address-image.sections[i].base_address;
2079                                 length-=offset;
2080                         }
2081
2082                         if (image.sections[i].base_address+buf_cnt>max_address)
2083                         {
2084                                 length-=(image.sections[i].base_address+buf_cnt)-max_address;
2085                         }
2086
2087                         if ((retval = target_write_buffer(target, image.sections[i].base_address+offset, length, buffer+offset)) != ERROR_OK)
2088                         {
2089                                 free(buffer);
2090                                 break;
2091                         }
2092                         image_size += length;
2093                         command_print(cmd_ctx, "%u byte written at address 0x%8.8x", length, image.sections[i].base_address+offset);
2094                 }
2095
2096                 free(buffer);
2097         }
2098
2099         duration_stop_measure(&duration, &duration_text);
2100         if (retval==ERROR_OK)
2101         {
2102                 command_print(cmd_ctx, "downloaded %u byte in %s", image_size, duration_text);
2103         }
2104         free(duration_text);
2105
2106         image_close(&image);
2107
2108         return retval;
2109
2110 }
2111
2112 int handle_dump_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2113 {
2114         fileio_t fileio;
2115
2116         u32 address;
2117         u32 size;
2118         u8 buffer[560];
2119         int retval=ERROR_OK;
2120
2121         duration_t duration;
2122         char *duration_text;
2123
2124         target_t *target = get_current_target(cmd_ctx);
2125
2126         if (argc != 3)
2127         {
2128                 command_print(cmd_ctx, "usage: dump_image <filename> <address> <size>");
2129                 return ERROR_OK;
2130         }
2131
2132         address = strtoul(args[1], NULL, 0);
2133         size = strtoul(args[2], NULL, 0);
2134
2135         if ((address & 3) || (size & 3))
2136         {
2137                 command_print(cmd_ctx, "only 32-bit aligned address and size are supported");
2138                 return ERROR_OK;
2139         }
2140
2141         if (fileio_open(&fileio, args[0], FILEIO_WRITE, FILEIO_BINARY) != ERROR_OK)
2142         {
2143                 return ERROR_OK;
2144         }
2145
2146         duration_start_measure(&duration);
2147
2148         while (size > 0)
2149         {
2150                 u32 size_written;
2151                 u32 this_run_size = (size > 560) ? 560 : size;
2152
2153                 retval = target->type->read_memory(target, address, 4, this_run_size / 4, buffer);
2154                 if (retval != ERROR_OK)
2155                 {
2156                         break;
2157                 }
2158
2159                 retval = fileio_write(&fileio, this_run_size, buffer, &size_written);
2160                 if (retval != ERROR_OK)
2161                 {
2162                         break;
2163                 }
2164
2165                 size -= this_run_size;
2166                 address += this_run_size;
2167         }
2168
2169         fileio_close(&fileio);
2170
2171         duration_stop_measure(&duration, &duration_text);
2172         if (retval==ERROR_OK)
2173         {
2174                 command_print(cmd_ctx, "dumped %"PRIi64" byte in %s", fileio.size, duration_text);
2175         }
2176         free(duration_text);
2177
2178         return ERROR_OK;
2179 }
2180
2181 int handle_verify_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2182 {
2183         u8 *buffer;
2184         u32 buf_cnt;
2185         u32 image_size;
2186         int i;
2187         int retval;
2188         u32 checksum = 0;
2189         u32 mem_checksum = 0;
2190
2191         image_t image;
2192
2193         duration_t duration;
2194         char *duration_text;
2195
2196         target_t *target = get_current_target(cmd_ctx);
2197
2198         if (argc < 1)
2199         {
2200                 return ERROR_COMMAND_SYNTAX_ERROR;
2201         }
2202
2203         if (!target)
2204         {
2205                 LOG_ERROR("no target selected");
2206                 return ERROR_FAIL;
2207         }
2208
2209         duration_start_measure(&duration);
2210
2211         if (argc >= 2)
2212         {
2213                 image.base_address_set = 1;
2214                 image.base_address = strtoul(args[1], NULL, 0);
2215         }
2216         else
2217         {
2218                 image.base_address_set = 0;
2219                 image.base_address = 0x0;
2220         }
2221
2222         image.start_address_set = 0;
2223
2224         if ((retval=image_open(&image, args[0], (argc == 3) ? args[2] : NULL)) != ERROR_OK)
2225         {
2226                 return retval;
2227         }
2228
2229         image_size = 0x0;
2230         retval=ERROR_OK;
2231         for (i = 0; i < image.num_sections; i++)
2232         {
2233                 buffer = malloc(image.sections[i].size);
2234                 if (buffer == NULL)
2235                 {
2236                         command_print(cmd_ctx, "error allocating buffer for section (%d bytes)", image.sections[i].size);
2237                         break;
2238                 }
2239                 if ((retval = image_read_section(&image, i, 0x0, image.sections[i].size, buffer, &buf_cnt)) != ERROR_OK)
2240                 {
2241                         free(buffer);
2242                         break;
2243                 }
2244
2245                 /* calculate checksum of image */
2246                 image_calculate_checksum( buffer, buf_cnt, &checksum );
2247
2248                 retval = target_checksum_memory(target, image.sections[i].base_address, buf_cnt, &mem_checksum);
2249                 if( retval != ERROR_OK )
2250                 {
2251                         free(buffer);
2252                         break;
2253                 }
2254
2255                 if( checksum != mem_checksum )
2256                 {
2257                         /* failed crc checksum, fall back to a binary compare */
2258                         u8 *data;
2259
2260                         command_print(cmd_ctx, "checksum mismatch - attempting binary compare");
2261
2262                         data = (u8*)malloc(buf_cnt);
2263
2264                         /* Can we use 32bit word accesses? */
2265                         int size = 1;
2266                         int count = buf_cnt;
2267                         if ((count % 4) == 0)
2268                         {
2269                                 size *= 4;
2270                                 count /= 4;
2271                         }
2272                         retval = target->type->read_memory(target, image.sections[i].base_address, size, count, data);
2273                         if (retval == ERROR_OK)
2274                         {
2275                                 int t;
2276                                 for (t = 0; t < buf_cnt; t++)
2277                                 {
2278                                         if (data[t] != buffer[t])
2279                                         {
2280                                                 command_print(cmd_ctx, "Verify operation failed address 0x%08x. Was 0x%02x instead of 0x%02x\n", t + image.sections[i].base_address, data[t], buffer[t]);
2281                                                 free(data);
2282                                                 free(buffer);
2283                                                 retval=ERROR_FAIL;
2284                                                 goto done;
2285                                         }
2286                                 }
2287                         }
2288
2289                         free(data);
2290                 }
2291
2292                 free(buffer);
2293                 image_size += buf_cnt;
2294         }
2295 done:
2296         duration_stop_measure(&duration, &duration_text);
2297         if (retval==ERROR_OK)
2298         {
2299                 command_print(cmd_ctx, "verified %u bytes in %s", image_size, duration_text);
2300         }
2301         free(duration_text);
2302
2303         image_close(&image);
2304
2305         return retval;
2306 }
2307
2308 int handle_bp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2309 {
2310         int retval;
2311         target_t *target = get_current_target(cmd_ctx);
2312
2313         if (argc == 0)
2314         {
2315                 breakpoint_t *breakpoint = target->breakpoints;
2316
2317                 while (breakpoint)
2318                 {
2319                         if (breakpoint->type == BKPT_SOFT)
2320                         {
2321                                 char* buf = buf_to_str(breakpoint->orig_instr, breakpoint->length, 16);
2322                                 command_print(cmd_ctx, "0x%8.8x, 0x%x, %i, 0x%s", breakpoint->address, breakpoint->length, breakpoint->set, buf);
2323                                 free(buf);
2324                         }
2325                         else
2326                         {
2327                                 command_print(cmd_ctx, "0x%8.8x, 0x%x, %i", breakpoint->address, breakpoint->length, breakpoint->set);
2328                         }
2329                         breakpoint = breakpoint->next;
2330                 }
2331         }
2332         else if (argc >= 2)
2333         {
2334                 int hw = BKPT_SOFT;
2335                 u32 length = 0;
2336
2337                 length = strtoul(args[1], NULL, 0);
2338
2339                 if (argc >= 3)
2340                         if (strcmp(args[2], "hw") == 0)
2341                                 hw = BKPT_HARD;
2342
2343                 if ((retval = breakpoint_add(target, strtoul(args[0], NULL, 0), length, hw)) != ERROR_OK)
2344                 {
2345                         LOG_ERROR("Failure setting breakpoints");
2346                 }
2347                 else
2348                 {
2349                         command_print(cmd_ctx, "breakpoint added at address 0x%8.8x", strtoul(args[0], NULL, 0));
2350                 }
2351         }
2352         else
2353         {
2354                 command_print(cmd_ctx, "usage: bp <address> <length> ['hw']");
2355         }
2356
2357         return ERROR_OK;
2358 }
2359
2360 int handle_rbp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2361 {
2362         target_t *target = get_current_target(cmd_ctx);
2363
2364         if (argc > 0)
2365                 breakpoint_remove(target, strtoul(args[0], NULL, 0));
2366
2367         return ERROR_OK;
2368 }
2369
2370 int handle_wp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2371 {
2372         target_t *target = get_current_target(cmd_ctx);
2373         int retval;
2374
2375         if (argc == 0)
2376         {
2377                 watchpoint_t *watchpoint = target->watchpoints;
2378
2379                 while (watchpoint)
2380                 {
2381                         command_print(cmd_ctx, "address: 0x%8.8x, len: 0x%8.8x, r/w/a: %i, value: 0x%8.8x, mask: 0x%8.8x", watchpoint->address, watchpoint->length, watchpoint->rw, watchpoint->value, watchpoint->mask);
2382                         watchpoint = watchpoint->next;
2383                 }
2384         }
2385         else if (argc >= 2)
2386         {
2387                 enum watchpoint_rw type = WPT_ACCESS;
2388                 u32 data_value = 0x0;
2389                 u32 data_mask = 0xffffffff;
2390
2391                 if (argc >= 3)
2392                 {
2393                         switch(args[2][0])
2394                         {
2395                                 case 'r':
2396                                         type = WPT_READ;
2397                                         break;
2398                                 case 'w':
2399                                         type = WPT_WRITE;
2400                                         break;
2401                                 case 'a':
2402                                         type = WPT_ACCESS;
2403                                         break;
2404                                 default:
2405                                         command_print(cmd_ctx, "usage: wp <address> <length> [r/w/a] [value] [mask]");
2406                                         return ERROR_OK;
2407                         }
2408                 }
2409                 if (argc >= 4)
2410                 {
2411                         data_value = strtoul(args[3], NULL, 0);
2412                 }
2413                 if (argc >= 5)
2414                 {
2415                         data_mask = strtoul(args[4], NULL, 0);
2416                 }
2417
2418                 if ((retval = watchpoint_add(target, strtoul(args[0], NULL, 0),
2419                                 strtoul(args[1], NULL, 0), type, data_value, data_mask)) != ERROR_OK)
2420                 {
2421                         LOG_ERROR("Failure setting breakpoints");
2422                 }
2423         }
2424         else
2425         {
2426                 command_print(cmd_ctx, "usage: wp <address> <length> [r/w/a] [value] [mask]");
2427         }
2428
2429         return ERROR_OK;
2430 }
2431
2432 int handle_rwp_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2433 {
2434         target_t *target = get_current_target(cmd_ctx);
2435
2436         if (argc > 0)
2437                 watchpoint_remove(target, strtoul(args[0], NULL, 0));
2438
2439         return ERROR_OK;
2440 }
2441
2442 int handle_virt2phys_command(command_context_t *cmd_ctx, char *cmd, char **args, int argc)
2443 {
2444         int retval;
2445         target_t *target = get_current_target(cmd_ctx);
2446         u32 va;
2447         u32 pa;
2448
2449         if (argc != 1)
2450         {
2451                 return ERROR_COMMAND_SYNTAX_ERROR;
2452         }
2453         va = strtoul(args[0], NULL, 0);
2454
2455         retval = target->type->virt2phys(target, va, &pa);
2456         if (retval == ERROR_OK)
2457         {
2458                 command_print(cmd_ctx, "Physical address 0x%08x", pa);
2459         }
2460         else
2461         {
2462                 /* lower levels will have logged a detailed error which is
2463                  * forwarded to telnet/GDB session.
2464                  */
2465         }
2466         return retval;
2467 }
2468 static void writeLong(FILE *f, int l)
2469 {
2470         int i;
2471         for (i=0; i<4; i++)
2472         {
2473                 char c=(l>>(i*8))&0xff;
2474                 fwrite(&c, 1, 1, f);
2475         }
2476
2477 }
2478 static void writeString(FILE *f, char *s)
2479 {
2480         fwrite(s, 1, strlen(s), f);
2481 }
2482
2483
2484
2485 // Dump a gmon.out histogram file.
2486 static void writeGmon(u32 *samples, int sampleNum, char *filename)
2487 {
2488         int i;
2489         FILE *f=fopen(filename, "w");
2490         if (f==NULL)
2491                 return;
2492         fwrite("gmon", 1, 4, f);
2493         writeLong(f, 0x00000001); // Version
2494         writeLong(f, 0); // padding
2495         writeLong(f, 0); // padding
2496         writeLong(f, 0); // padding
2497
2498         fwrite("", 1, 1, f);  // GMON_TAG_TIME_HIST
2499
2500         // figure out bucket size
2501         u32 min=samples[0];
2502         u32 max=samples[0];
2503         for (i=0; i<sampleNum; i++)
2504         {
2505                 if (min>samples[i])
2506                 {
2507                         min=samples[i];
2508                 }
2509                 if (max<samples[i])
2510                 {
2511                         max=samples[i];
2512                 }
2513         }
2514
2515         int addressSpace=(max-min+1);
2516
2517         static int const maxBuckets=256*1024; // maximum buckets.
2518         int length=addressSpace;
2519         if (length > maxBuckets)
2520         {
2521                 length=maxBuckets;
2522         }
2523         int *buckets=malloc(sizeof(int)*length);
2524         if (buckets==NULL)
2525         {
2526                 fclose(f);
2527                 return;
2528         }
2529         memset(buckets, 0, sizeof(int)*length);
2530         for (i=0; i<sampleNum;i++)
2531         {
2532                 u32 address=samples[i];
2533                 long long a=address-min;
2534                 long long b=length-1;
2535                 long long c=addressSpace-1;
2536                 int index=(a*b)/c; // danger!!!! int32 overflows
2537                 buckets[index]++;
2538         }
2539
2540         //                         append binary memory gmon.out &profile_hist_hdr ((char*)&profile_hist_hdr + sizeof(struct gmon_hist_hdr))
2541         writeLong(f, min);                                      // low_pc
2542         writeLong(f, max);              // high_pc
2543         writeLong(f, length);           // # of samples
2544         writeLong(f, 64000000);                         // 64MHz
2545         writeString(f, "seconds");
2546         for (i=0; i<(15-strlen("seconds")); i++)
2547         {
2548                 fwrite("", 1, 1, f);  // padding
2549         }
2550         writeString(f, "s");
2551
2552 //                         append binary memory gmon.out profile_hist_data (profile_hist_data + profile_hist_hdr.hist_size)
2553
2554         char *data=malloc(2*length);
2555         if (data!=NULL)
2556         {
2557                 for (i=0; i<length;i++)
2558                 {
2559                         int val;
2560                         val=buckets[i];
2561                         if (val>65535)
2562                         {
2563                                 val=65535;
2564                         }
2565                         data[i*2]=val&0xff;
2566                         data[i*2+1]=(val>>8)&0xff;
2567                 }
2568                 free(buckets);
2569                 fwrite(data, 1, length*2, f);
2570                 free(data);
2571         } else
2572         {
2573                 free(buckets);
2574         }
2575
2576         fclose(f);
2577 }
2578
2579 /* profiling samples the CPU PC as quickly as OpenOCD is able, which will be used as a random sampling of PC */
2580 int handle_profile_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2581 {
2582         target_t *target = get_current_target(cmd_ctx);
2583         struct timeval timeout, now;
2584
2585         gettimeofday(&timeout, NULL);
2586         if (argc!=2)
2587         {
2588                 return ERROR_COMMAND_SYNTAX_ERROR;
2589         }
2590         char *end;
2591         timeval_add_time(&timeout, strtoul(args[0], &end, 0), 0);
2592         if (*end)
2593         {
2594                 return ERROR_OK;
2595         }
2596
2597         command_print(cmd_ctx, "Starting profiling. Halting and resuming the target as often as we can...");
2598
2599         static const int maxSample=10000;
2600         u32 *samples=malloc(sizeof(u32)*maxSample);
2601         if (samples==NULL)
2602                 return ERROR_OK;
2603
2604         int numSamples=0;
2605         int retval=ERROR_OK;
2606         // hopefully it is safe to cache! We want to stop/restart as quickly as possible.
2607         reg_t *reg = register_get_by_name(target->reg_cache, "pc", 1);
2608
2609         for (;;)
2610         {
2611                 target_poll(target);
2612                 if (target->state == TARGET_HALTED)
2613                 {
2614                         u32 t=*((u32 *)reg->value);
2615                         samples[numSamples++]=t;
2616                         retval = target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
2617                         target_poll(target);
2618                         alive_sleep(10); // sleep 10ms, i.e. <100 samples/second.
2619                 } else if (target->state == TARGET_RUNNING)
2620                 {
2621                         // We want to quickly sample the PC.
2622                         target_halt(target);
2623                 } else
2624                 {
2625                         command_print(cmd_ctx, "Target not halted or running");
2626                         retval=ERROR_OK;
2627                         break;
2628                 }
2629                 if (retval!=ERROR_OK)
2630                 {
2631                         break;
2632                 }
2633
2634                 gettimeofday(&now, NULL);
2635                 if ((numSamples>=maxSample) || ((now.tv_sec >= timeout.tv_sec) && (now.tv_usec >= timeout.tv_usec)))
2636                 {
2637                         command_print(cmd_ctx, "Profiling completed. %d samples.", numSamples);
2638                         target_poll(target);
2639                         if (target->state == TARGET_HALTED)
2640                         {
2641                                 target_resume(target, 1, 0, 0, 0); /* current pc, addr = 0, do not handle breakpoints, not debugging */
2642                         }
2643                         target_poll(target);
2644                         writeGmon(samples, numSamples, args[1]);
2645                         command_print(cmd_ctx, "Wrote %s", args[1]);
2646                         break;
2647                 }
2648         }
2649         free(samples);
2650
2651         return ERROR_OK;
2652 }
2653
2654 static int new_int_array_element(Jim_Interp * interp, const char *varname, int idx, u32 val)
2655 {
2656         char *namebuf;
2657         Jim_Obj *nameObjPtr, *valObjPtr;
2658         int result;
2659
2660         namebuf = alloc_printf("%s(%d)", varname, idx);
2661         if (!namebuf)
2662                 return JIM_ERR;
2663
2664         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
2665         valObjPtr = Jim_NewIntObj(interp, val);
2666         if (!nameObjPtr || !valObjPtr)
2667         {
2668                 free(namebuf);
2669                 return JIM_ERR;
2670         }
2671
2672         Jim_IncrRefCount(nameObjPtr);
2673         Jim_IncrRefCount(valObjPtr);
2674         result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
2675         Jim_DecrRefCount(interp, nameObjPtr);
2676         Jim_DecrRefCount(interp, valObjPtr);
2677         free(namebuf);
2678         /* printf("%s(%d) <= 0%08x\n", varname, idx, val); */
2679         return result;
2680 }
2681
2682 static int jim_mem2array(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
2683 {
2684         command_context_t *context;
2685         target_t *target;
2686
2687         context = Jim_GetAssocData(interp, "context");
2688         if (context == NULL)
2689         {
2690                 LOG_ERROR("mem2array: no command context");
2691                 return JIM_ERR;
2692         }
2693         target = get_current_target(context);
2694         if (target == NULL)
2695         {
2696                 LOG_ERROR("mem2array: no current target");
2697                 return JIM_ERR;
2698         }
2699
2700         return  target_mem2array(interp, target, argc,argv);
2701 }
2702
2703 static int target_mem2array(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
2704 {
2705         long l;
2706         u32 width;
2707         u32 len;
2708         u32 addr;
2709         u32 count;
2710         u32 v;
2711         const char *varname;
2712         u8 buffer[4096];
2713         int  i, n, e, retval;
2714
2715         /* argv[1] = name of array to receive the data
2716          * argv[2] = desired width
2717          * argv[3] = memory address
2718          * argv[4] = count of times to read
2719          */
2720         if (argc != 5) {
2721                 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
2722                 return JIM_ERR;
2723         }
2724         varname = Jim_GetString(argv[1], &len);
2725         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
2726
2727         e = Jim_GetLong(interp, argv[2], &l);
2728         width = l;
2729         if (e != JIM_OK) {
2730                 return e;
2731         }
2732
2733         e = Jim_GetLong(interp, argv[3], &l);
2734         addr = l;
2735         if (e != JIM_OK) {
2736                 return e;
2737         }
2738         e = Jim_GetLong(interp, argv[4], &l);
2739         len = l;
2740         if (e != JIM_OK) {
2741                 return e;
2742         }
2743         switch (width) {
2744                 case 8:
2745                         width = 1;
2746                         break;
2747                 case 16:
2748                         width = 2;
2749                         break;
2750                 case 32:
2751                         width = 4;
2752                         break;
2753                 default:
2754                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2755                         Jim_AppendStrings( interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL );
2756                         return JIM_ERR;
2757         }
2758         if (len == 0) {
2759                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2760                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: zero width read?", NULL);
2761                 return JIM_ERR;
2762         }
2763         if ((addr + (len * width)) < addr) {
2764                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2765                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: addr + len - wraps to zero?", NULL);
2766                 return JIM_ERR;
2767         }
2768         /* absurd transfer size? */
2769         if (len > 65536) {
2770                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2771                 Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: absurd > 64K item request", NULL);
2772                 return JIM_ERR;
2773         }
2774
2775         if ((width == 1) ||
2776                 ((width == 2) && ((addr & 1) == 0)) ||
2777                 ((width == 4) && ((addr & 3) == 0))) {
2778                 /* all is well */
2779         } else {
2780                 char buf[100];
2781                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2782                 sprintf(buf, "mem2array address: 0x%08x is not aligned for %d byte reads", addr, width);
2783                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
2784                 return JIM_ERR;
2785         }
2786
2787         /* Transfer loop */
2788
2789         /* index counter */
2790         n = 0;
2791         /* assume ok */
2792         e = JIM_OK;
2793         while (len) {
2794                 /* Slurp... in buffer size chunks */
2795
2796                 count = len; /* in objects.. */
2797                 if (count > (sizeof(buffer)/width)) {
2798                         count = (sizeof(buffer)/width);
2799                 }
2800
2801                 retval = target->type->read_memory( target, addr, width, count, buffer );
2802                 if (retval != ERROR_OK) {
2803                         /* BOO !*/
2804                         LOG_ERROR("mem2array: Read @ 0x%08x, w=%d, cnt=%d, failed", addr, width, count);
2805                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2806                         Jim_AppendStrings(interp, Jim_GetResult(interp), "mem2array: cannot read memory", NULL);
2807                         e = JIM_ERR;
2808                         len = 0;
2809                 } else {
2810                         v = 0; /* shut up gcc */
2811                         for (i = 0 ;i < count ;i++, n++) {
2812                                 switch (width) {
2813                                         case 4:
2814                                                 v = target_buffer_get_u32(target, &buffer[i*width]);
2815                                                 break;
2816                                         case 2:
2817                                                 v = target_buffer_get_u16(target, &buffer[i*width]);
2818                                                 break;
2819                                         case 1:
2820                                                 v = buffer[i] & 0x0ff;
2821                                                 break;
2822                                 }
2823                                 new_int_array_element(interp, varname, n, v);
2824                         }
2825                         len -= count;
2826                 }
2827         }
2828
2829         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2830
2831         return JIM_OK;
2832 }
2833
2834 static int get_int_array_element(Jim_Interp * interp, const char *varname, int idx, u32 *val)
2835 {
2836         char *namebuf;
2837         Jim_Obj *nameObjPtr, *valObjPtr;
2838         int result;
2839         long l;
2840
2841         namebuf = alloc_printf("%s(%d)", varname, idx);
2842         if (!namebuf)
2843                 return JIM_ERR;
2844
2845         nameObjPtr = Jim_NewStringObj(interp, namebuf, -1);
2846         if (!nameObjPtr)
2847         {
2848                 free(namebuf);
2849                 return JIM_ERR;
2850         }
2851
2852         Jim_IncrRefCount(nameObjPtr);
2853         valObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_ERRMSG);
2854         Jim_DecrRefCount(interp, nameObjPtr);
2855         free(namebuf);
2856         if (valObjPtr == NULL)
2857                 return JIM_ERR;
2858
2859         result = Jim_GetLong(interp, valObjPtr, &l);
2860         /* printf("%s(%d) => 0%08x\n", varname, idx, val); */
2861         *val = l;
2862         return result;
2863 }
2864
2865 static int jim_array2mem(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
2866 {
2867         command_context_t *context;
2868         target_t *target;
2869         
2870         context = Jim_GetAssocData(interp, "context");
2871         if (context == NULL){
2872                 LOG_ERROR("array2mem: no command context");
2873                 return JIM_ERR;
2874         }
2875         target = get_current_target(context);
2876         if (target == NULL){
2877                 LOG_ERROR("array2mem: no current target");
2878                 return JIM_ERR;
2879         }
2880         
2881         return target_array2mem( interp,target, argc, argv );
2882 }
2883                            
2884
2885 static int target_array2mem(Jim_Interp *interp, target_t *target, int argc, Jim_Obj *const *argv)
2886 {
2887         long l;
2888         u32 width;
2889         u32 len;
2890         u32 addr;
2891         u32 count;
2892         u32 v;
2893         const char *varname;
2894         u8 buffer[4096];
2895         int  i, n, e, retval;
2896
2897         /* argv[1] = name of array to get the data
2898          * argv[2] = desired width
2899          * argv[3] = memory address
2900          * argv[4] = count to write
2901          */
2902         if (argc != 5) {
2903                 Jim_WrongNumArgs(interp, 1, argv, "varname width addr nelems");
2904                 return JIM_ERR;
2905         }
2906         varname = Jim_GetString(argv[1], &len);
2907         /* given "foo" get space for worse case "foo(%d)" .. add 20 */
2908
2909         e = Jim_GetLong(interp, argv[2], &l);
2910         width = l;
2911         if (e != JIM_OK) {
2912                 return e;
2913         }
2914
2915         e = Jim_GetLong(interp, argv[3], &l);
2916         addr = l;
2917         if (e != JIM_OK) {
2918                 return e;
2919         }
2920         e = Jim_GetLong(interp, argv[4], &l);
2921         len = l;
2922         if (e != JIM_OK) {
2923                 return e;
2924         }
2925         switch (width) {
2926                 case 8:
2927                         width = 1;
2928                         break;
2929                 case 16:
2930                         width = 2;
2931                         break;
2932                 case 32:
2933                         width = 4;
2934                         break;
2935                 default:
2936                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2937                         Jim_AppendStrings( interp, Jim_GetResult(interp), "Invalid width param, must be 8/16/32", NULL );
2938                         return JIM_ERR;
2939         }
2940         if (len == 0) {
2941                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2942                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: zero width read?", NULL);
2943                 return JIM_ERR;
2944         }
2945         if ((addr + (len * width)) < addr) {
2946                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2947                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: addr + len - wraps to zero?", NULL);
2948                 return JIM_ERR;
2949         }
2950         /* absurd transfer size? */
2951         if (len > 65536) {
2952                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2953                 Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: absurd > 64K item request", NULL);
2954                 return JIM_ERR;
2955         }
2956
2957         if ((width == 1) ||
2958                 ((width == 2) && ((addr & 1) == 0)) ||
2959                 ((width == 4) && ((addr & 3) == 0))) {
2960                 /* all is well */
2961         } else {
2962                 char buf[100];
2963                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2964                 sprintf(buf, "array2mem address: 0x%08x is not aligned for %d byte reads", addr, width);
2965                 Jim_AppendStrings(interp, Jim_GetResult(interp), buf , NULL);
2966                 return JIM_ERR;
2967         }
2968
2969
2970         /* Transfer loop */
2971
2972         /* index counter */
2973         n = 0;
2974         /* assume ok */
2975         e = JIM_OK;
2976         while (len) {
2977                 /* Slurp... in buffer size chunks */
2978
2979                 count = len; /* in objects.. */
2980                 if (count > (sizeof(buffer)/width)) {
2981                         count = (sizeof(buffer)/width);
2982                 }
2983
2984                 v = 0; /* shut up gcc */
2985                 for (i = 0 ;i < count ;i++, n++) {
2986                         get_int_array_element(interp, varname, n, &v);
2987                         switch (width) {
2988                         case 4:
2989                                 target_buffer_set_u32(target, &buffer[i*width], v);
2990                                 break;
2991                         case 2:
2992                                 target_buffer_set_u16(target, &buffer[i*width], v);
2993                                 break;
2994                         case 1:
2995                                 buffer[i] = v & 0x0ff;
2996                                 break;
2997                         }
2998                 }
2999                 len -= count;
3000
3001                 retval = target->type->write_memory(target, addr, width, count, buffer);
3002                 if (retval != ERROR_OK) {
3003                         /* BOO !*/
3004                         LOG_ERROR("array2mem: Write @ 0x%08x, w=%d, cnt=%d, failed", addr, width, count);
3005                         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3006                         Jim_AppendStrings(interp, Jim_GetResult(interp), "array2mem: cannot read memory", NULL);
3007                         e = JIM_ERR;
3008                         len = 0;
3009                 }
3010         }
3011
3012         Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
3013
3014         return JIM_OK;
3015 }
3016
3017
3018 /*
3019  * Local Variables: ***
3020  * c-basic-offset: 4 ***
3021  * tab-width: 4 ***
3022  * End: ***
3023  */