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