build: cleanup src/helper directory

Change-Id: I71a312df783995e9083c345c25e73902d5aef59e
Signed-off-by: Spencer Oliver <spen@spen-soft.co.uk>
Reviewed-on: http://openocd.zylin.com/415
Tested-by: jenkins
__archive__
Spencer Oliver 2012-01-30 14:31:21 +00:00
parent 9ad57e96b3
commit 8b00e56e64
25 changed files with 969 additions and 1185 deletions

View File

@ -20,6 +20,7 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
@ -27,8 +28,7 @@
#include "log.h" #include "log.h"
#include "binarybuffer.h" #include "binarybuffer.h"
static const unsigned char bit_reverse_table256[] = static const unsigned char bit_reverse_table256[] = {
{
0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0, 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8, 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4, 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
@ -47,19 +47,17 @@ static const unsigned char bit_reverse_table256[] =
0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
}; };
void *buf_cpy(const void *from, void *_to, unsigned size)
void* buf_cpy(const void *from, void *_to, unsigned size)
{ {
if (NULL == from || NULL == _to) if (NULL == from || NULL == _to)
return NULL; return NULL;
// copy entire buffer /* copy entire buffer */
memcpy(_to, from, DIV_ROUND_UP(size, 8)); memcpy(_to, from, DIV_ROUND_UP(size, 8));
/* mask out bits that don't belong to the buffer */ /* mask out bits that don't belong to the buffer */
unsigned trailing_bits = size % 8; unsigned trailing_bits = size % 8;
if (trailing_bits) if (trailing_bits) {
{
uint8_t *to = _to; uint8_t *to = _to;
to[size / 8] &= (1 << trailing_bits) - 1; to[size / 8] &= (1 << trailing_bits) - 1;
} }
@ -101,8 +99,7 @@ bool buf_cmp_mask(const void *_buf1, const void *_buf2,
const uint8_t *buf1 = _buf1, *buf2 = _buf2, *mask = _mask; const uint8_t *buf1 = _buf1, *buf2 = _buf2, *mask = _mask;
unsigned last = size / 8; unsigned last = size / 8;
for (unsigned i = 0; i < last; i++) for (unsigned i = 0; i < last; i++) {
{
if (buf_cmp_masked(buf1[i], buf2[i], mask[i])) if (buf_cmp_masked(buf1[i], buf2[i], mask[i]))
return true; return true;
} }
@ -113,7 +110,7 @@ bool buf_cmp_mask(const void *_buf1, const void *_buf2,
} }
void* buf_set_ones(void *_buf, unsigned size) void *buf_set_ones(void *_buf, unsigned size)
{ {
uint8_t *buf = _buf; uint8_t *buf = _buf;
if (!buf) if (!buf)
@ -128,12 +125,12 @@ void* buf_set_ones(void *_buf, unsigned size)
return buf; return buf;
} }
void* buf_set_buf(const void *_src, unsigned src_start, void *buf_set_buf(const void *_src, unsigned src_start,
void *_dst, unsigned dst_start, unsigned len) void *_dst, unsigned dst_start, unsigned len)
{ {
const uint8_t *src = _src; const uint8_t *src = _src;
uint8_t *dst = _dst; uint8_t *dst = _dst;
unsigned i,sb,db,sq,dq, lb,lq; unsigned i, sb, db, sq, dq, lb, lq;
sb = src_start / 8; sb = src_start / 8;
db = dst_start / 8; db = dst_start / 8;
@ -148,33 +145,29 @@ void* buf_set_buf(const void *_src, unsigned src_start,
/* check if both buffers are on byte boundary and /* check if both buffers are on byte boundary and
* len is a multiple of 8bit so we can simple copy * len is a multiple of 8bit so we can simple copy
* the buffer */ * the buffer */
if ( (sq == 0) && (dq == 0) && (lq == 0) ) if ((sq == 0) && (dq == 0) && (lq == 0)) {
{
for (i = 0; i < lb; i++) for (i = 0; i < lb; i++)
*dst++ = *src++; *dst++ = *src++;
return (uint8_t*)_dst; return (uint8_t *)_dst;
} }
/* fallback to slow bit copy */ /* fallback to slow bit copy */
for (i = 0; i < len; i++) for (i = 0; i < len; i++) {
{
if (((*src >> (sq&7)) & 1) == 1) if (((*src >> (sq&7)) & 1) == 1)
*dst |= 1 << (dq&7); *dst |= 1 << (dq&7);
else else
*dst &= ~(1 << (dq&7)); *dst &= ~(1 << (dq&7));
if ( sq++ == 7 ) if (sq++ == 7) {
{
sq = 0; sq = 0;
src++; src++;
} }
if ( dq++ == 7 ) if (dq++ == 7) {
{
dq = 0; dq = 0;
dst++; dst++;
} }
} }
return (uint8_t*)_dst; return (uint8_t *)_dst;
} }
uint32_t flip_u32(uint32_t value, unsigned int num) uint32_t flip_u32(uint32_t value, unsigned int num)
@ -203,7 +196,7 @@ static int ceil_f_to_u32(float x)
return y; return y;
} }
char* buf_to_str(const void *_buf, unsigned buf_len, unsigned radix) char *buf_to_str(const void *_buf, unsigned buf_len, unsigned radix)
{ {
float factor; float factor;
switch (radix) { switch (radix) {
@ -225,15 +218,13 @@ char* buf_to_str(const void *_buf, unsigned buf_len, unsigned radix)
const uint8_t *buf = _buf; const uint8_t *buf = _buf;
int b256_len = DIV_ROUND_UP(buf_len, 8); int b256_len = DIV_ROUND_UP(buf_len, 8);
for (int i = b256_len - 1; i >= 0; i--) for (int i = b256_len - 1; i >= 0; i--) {
{
uint32_t tmp = buf[i]; uint32_t tmp = buf[i];
if (((unsigned)i == (buf_len / 8)) && (buf_len % 8)) if (((unsigned)i == (buf_len / 8)) && (buf_len % 8))
tmp &= (0xff >> (8 - (buf_len % 8))); tmp &= (0xff >> (8 - (buf_len % 8)));
/* base-256 digits */ /* base-256 digits */
for (unsigned j = str_len; j > 0; j--) for (unsigned j = str_len; j > 0; j--) {
{
tmp += (uint32_t)str[j-1] * 256; tmp += (uint32_t)str[j-1] * 256;
str[j-1] = (uint8_t)(tmp % radix); str[j-1] = (uint8_t)(tmp % radix);
tmp /= radix; tmp /= radix;
@ -247,7 +238,7 @@ char* buf_to_str(const void *_buf, unsigned buf_len, unsigned radix)
return str; return str;
} }
/// identify radix, and skip radix-prefix (0, 0x or 0X) /* / identify radix, and skip radix-prefix (0, 0x or 0X) */
static void str_radix_guess(const char **_str, unsigned *_str_len, static void str_radix_guess(const char **_str, unsigned *_str_len,
unsigned *_radix) unsigned *_radix)
{ {
@ -256,22 +247,16 @@ static void str_radix_guess(const char **_str, unsigned *_str_len,
return; return;
const char *str = *_str; const char *str = *_str;
unsigned str_len = *_str_len; unsigned str_len = *_str_len;
if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) {
{
radix = 16; radix = 16;
str += 2; str += 2;
str_len -= 2; str_len -= 2;
} } else if ((str[0] == '0') && (str_len != 1)) {
else if ((str[0] == '0') && (str_len != 1))
{
radix = 8; radix = 8;
str += 1; str += 1;
str_len -= 1; str_len -= 1;
} } else
else
{
radix = 10; radix = 10;
}
*_str = str; *_str = str;
*_str_len = str_len; *_str_len = str_len;
*_radix = radix; *_radix = radix;
@ -299,11 +284,10 @@ int str_to_buf(const char *str, unsigned str_len,
unsigned b256_len = ceil_f_to_u32(str_len * factor); unsigned b256_len = ceil_f_to_u32(str_len * factor);
uint8_t *b256_buf = calloc(b256_len, 1); uint8_t *b256_buf = calloc(b256_len, 1);
/* go through zero terminated buffer */ /* go through zero terminated buffer
/* input digits (ASCII) */ * input digits (ASCII) */
unsigned i; unsigned i;
for (i = 0; charbuf[i]; i++) for (i = 0; charbuf[i]; i++) {
{
uint32_t tmp = charbuf[i]; uint32_t tmp = charbuf[i];
if ((tmp >= '0') && (tmp <= '9')) if ((tmp >= '0') && (tmp <= '9'))
tmp = (tmp - '0'); tmp = (tmp - '0');
@ -311,14 +295,14 @@ int str_to_buf(const char *str, unsigned str_len,
tmp = (tmp - 'a' + 10); tmp = (tmp - 'a' + 10);
else if ((tmp >= 'A') && (tmp <= 'F')) else if ((tmp >= 'A') && (tmp <= 'F'))
tmp = (tmp - 'A' + 10); tmp = (tmp - 'A' + 10);
else continue; /* skip characters other than [0-9,a-f,A-F] */ else
continue; /* skip characters other than [0-9,a-f,A-F] */
if (tmp >= radix) if (tmp >= radix)
continue; /* skip digits invalid for the current radix */ continue; /* skip digits invalid for the current radix */
/* base-256 digits */ /* base-256 digits */
for (unsigned j = 0; j < b256_len; j++) for (unsigned j = 0; j < b256_len; j++) {
{
tmp += (uint32_t)b256_buf[j] * radix; tmp += (uint32_t)b256_buf[j] * radix;
b256_buf[j] = (uint8_t)(tmp & 0xFF); b256_buf[j] = (uint8_t)(tmp & 0xFF);
tmp >>= 8; tmp >>= 8;
@ -327,8 +311,7 @@ int str_to_buf(const char *str, unsigned str_len,
} }
uint8_t *buf = _buf; uint8_t *buf = _buf;
for (unsigned j = 0; j < DIV_ROUND_UP(buf_len, 8); j++) for (unsigned j = 0; j < DIV_ROUND_UP(buf_len, 8); j++) {
{
if (j < b256_len) if (j < b256_len)
buf[j] = b256_buf[j]; buf[j] = b256_buf[j];
else else

View File

@ -20,6 +20,7 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#ifndef BINARYBUFFER_H #ifndef BINARYBUFFER_H
#define BINARYBUFFER_H #define BINARYBUFFER_H
@ -49,8 +50,7 @@ static inline void buf_set_u32(void *_buffer,
buffer[1] = (value >> 8) & 0xff; buffer[1] = (value >> 8) & 0xff;
buffer[0] = (value >> 0) & 0xff; buffer[0] = (value >> 0) & 0xff;
} else { } else {
for (unsigned i = first; i < first + num; i++) for (unsigned i = first; i < first + num; i++) {
{
if (((value >> (i - first)) & 1) == 1) if (((value >> (i - first)) & 1) == 1)
buffer[i / 8] |= 1 << (i % 8); buffer[i / 8] |= 1 << (i % 8);
else else
@ -79,8 +79,7 @@ static inline uint32_t buf_get_u32(const void *_buffer,
(((uint32_t)buffer[0]) << 0); (((uint32_t)buffer[0]) << 0);
} else { } else {
uint32_t result = 0; uint32_t result = 0;
for (unsigned i = first; i < first + num; i++) for (unsigned i = first; i < first + num; i++) {
{
if (((buffer[i / 8] >> (i % 8)) & 1) == 1) if (((buffer[i / 8] >> (i % 8)) & 1) == 1)
result |= 1 << (i - first); result |= 1 << (i - first);
} }
@ -109,7 +108,7 @@ bool buf_cmp_mask(const void *buf1, const void *buf2,
* @param to The buffer that will receive the copy of @c from. * @param to The buffer that will receive the copy of @c from.
* @param size The number of bits to copy. * @param size The number of bits to copy.
*/ */
void* buf_cpy(const void *from, void *to, unsigned size); void *buf_cpy(const void *from, void *to, unsigned size);
/** /**
* Set the contents of @c buf with @c count bits, all set to 1. * Set the contents of @c buf with @c count bits, all set to 1.
@ -117,14 +116,14 @@ void* buf_cpy(const void *from, void *to, unsigned size);
* @param size The number of bits. * @param size The number of bits.
* @returns The original buffer (@c buf). * @returns The original buffer (@c buf).
*/ */
void* buf_set_ones(void *buf, unsigned size); void *buf_set_ones(void *buf, unsigned size);
void* buf_set_buf(const void *src, unsigned src_start, void *buf_set_buf(const void *src, unsigned src_start,
void *dst, unsigned dst_start, unsigned len); void *dst, unsigned dst_start, unsigned len);
int str_to_buf(const char *str, unsigned len, int str_to_buf(const char *str, unsigned len,
void *bin_buf, unsigned buf_size, unsigned radix); void *bin_buf, unsigned buf_size, unsigned radix);
char* buf_to_str(const void *buf, unsigned size, unsigned radix); char *buf_to_str(const void *buf, unsigned size, unsigned radix);
/* read a uint32_t from a buffer in target memory endianness */ /* read a uint32_t from a buffer in target memory endianness */
static inline uint32_t fast_target_buffer_get_u32(const void *p, bool le) static inline uint32_t fast_target_buffer_get_u32(const void *p, bool le)

View File

@ -26,6 +26,7 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
@ -35,7 +36,7 @@
#define JIM_EMBEDDED #define JIM_EMBEDDED
#endif #endif
// @todo the inclusion of target.h here is a layering violation /* @todo the inclusion of target.h here is a layering violation */
#include <jtag/jtag.h> #include <jtag/jtag.h>
#include <target/target.h> #include <target/target.h>
#include "command.h" #include "command.h"
@ -44,11 +45,9 @@
#include "time_support.h" #include "time_support.h"
#include "jim-eventloop.h" #include "jim-eventloop.h"
/* nice short description of source file */ /* nice short description of source file */
#define __THIS__FILE__ "command.c" #define __THIS__FILE__ "command.c"
static int run_command(struct command_context *context, static int run_command(struct command_context *context,
struct command *c, const char *words[], unsigned num_words); struct command *c, const char *words[], unsigned num_words);
@ -108,10 +107,8 @@ static void command_log_capture_finish(struct log_capture_state *state)
Jim_GetString(state->output, &length); Jim_GetString(state->output, &length);
if (length > 0) if (length > 0)
{
Jim_SetResult(state->interp, state->output); Jim_SetResult(state->interp, state->output);
} else else {
{
/* No output captured, use tcl return value (which could /* No output captured, use tcl return value (which could
* be empty too). */ * be empty too). */
} }
@ -134,18 +131,17 @@ extern struct command_context *global_cmd_ctx;
/* dump a single line to the log for the command. /* dump a single line to the log for the command.
* Do nothing in case we are not at debug level 3 */ * Do nothing in case we are not at debug level 3 */
void script_debug(Jim_Interp *interp, const char *name, void script_debug(Jim_Interp *interp, const char *name,
unsigned argc, Jim_Obj *const *argv) unsigned argc, Jim_Obj * const *argv)
{ {
if (debug_level < LOG_LVL_DEBUG) if (debug_level < LOG_LVL_DEBUG)
return; return;
char * dbg = alloc_printf("command - %s", name); char *dbg = alloc_printf("command - %s", name);
for (unsigned i = 0; i < argc; i++) for (unsigned i = 0; i < argc; i++) {
{
int len; int len;
const char *w = Jim_GetString(argv[i], &len); const char *w = Jim_GetString(argv[i], &len);
char * t = alloc_printf("%s %s", dbg, w); char *t = alloc_printf("%s %s", dbg, w);
free (dbg); free(dbg);
dbg = t; dbg = t;
} }
LOG_DEBUG("%s", dbg); LOG_DEBUG("%s", dbg);
@ -159,20 +155,18 @@ static void script_command_args_free(const char **words, unsigned nwords)
free(words); free(words);
} }
static const char **script_command_args_alloc( static const char **script_command_args_alloc(
unsigned argc, Jim_Obj *const *argv, unsigned *nwords) unsigned argc, Jim_Obj * const *argv, unsigned *nwords)
{ {
const char **words = malloc(argc * sizeof(char *)); const char **words = malloc(argc * sizeof(char *));
if (NULL == words) if (NULL == words)
return NULL; return NULL;
unsigned i; unsigned i;
for (i = 0; i < argc; i++) for (i = 0; i < argc; i++) {
{
int len; int len;
const char *w = Jim_GetString(argv[i], &len); const char *w = Jim_GetString(argv[i], &len);
words[i] = strdup(w); words[i] = strdup(w);
if (words[i] == NULL) if (words[i] == NULL) {
{
script_command_args_free(words, i); script_command_args_free(words, i);
return NULL; return NULL;
} }
@ -185,8 +179,7 @@ struct command_context *current_command_context(Jim_Interp *interp)
{ {
/* grab the command context from the associated data */ /* grab the command context from the associated data */
struct command_context *cmd_ctx = Jim_GetAssocData(interp, "context"); struct command_context *cmd_ctx = Jim_GetAssocData(interp, "context");
if (NULL == cmd_ctx) if (NULL == cmd_ctx) {
{
/* Tcl can invoke commands directly instead of via command_run_line(). This would /* Tcl can invoke commands directly instead of via command_run_line(). This would
* happen when the Jim Tcl interpreter is provided by eCos or if we are running * happen when the Jim Tcl interpreter is provided by eCos or if we are running
* commands in a startup script. * commands in a startup script.
@ -200,7 +193,7 @@ struct command_context *current_command_context(Jim_Interp *interp)
} }
static int script_command_run(Jim_Interp *interp, static int script_command_run(Jim_Interp *interp,
int argc, Jim_Obj *const *argv, struct command *c, bool capture) int argc, Jim_Obj * const *argv, struct command *c, bool capture)
{ {
target_call_timer_callbacks_now(); target_call_timer_callbacks_now();
LOG_USER_N("%s", ""); /* Keep GDB connection alive*/ LOG_USER_N("%s", ""); /* Keep GDB connection alive*/
@ -247,8 +240,7 @@ static struct command *command_root(struct command *c)
*/ */
static struct command *command_find(struct command *head, const char *name) static struct command *command_find(struct command *head, const char *name)
{ {
for (struct command *cc = head; cc; cc = cc->next) for (struct command *cc = head; cc; cc = cc->next) {
{
if (strcmp(cc->name, name) == 0) if (strcmp(cc->name, name) == 0)
return cc; return cc;
} }
@ -274,8 +266,7 @@ struct command *command_find_in_parent(struct command *parent,
static void command_add_child(struct command **head, struct command *c) static void command_add_child(struct command **head, struct command *c)
{ {
assert(head); assert(head);
if (NULL == *head) if (NULL == *head) {
{
*head = c; *head = c;
return; return;
} }
@ -300,10 +291,9 @@ static struct command **command_list_for_parent(
static void command_free(struct command *c) static void command_free(struct command *c)
{ {
/// @todo if command has a handler, unregister its jim command! /* / @todo if command has a handler, unregister its jim command! */
while (NULL != c->children) while (NULL != c->children) {
{
struct command *tmp = c->children; struct command *tmp = c->children;
c->children = tmp->next; c->children = tmp->next;
command_free(tmp); command_free(tmp);
@ -312,9 +302,9 @@ static void command_free(struct command *c)
if (c->name) if (c->name)
free((void *)c->name); free((void *)c->name);
if (c->help) if (c->help)
free((void*)c->help); free((void *)c->help);
if (c->usage) if (c->usage)
free((void*)c->usage); free((void *)c->usage);
free(c); free(c);
} }
@ -324,14 +314,13 @@ static struct command *command_new(struct command_context *cmd_ctx,
assert(cr->name); assert(cr->name);
/* /*
If it is a non-jim command with no .usage specified, * If it is a non-jim command with no .usage specified,
log an error. * log an error.
*
strlen(.usage) == 0 means that the command takes no * strlen(.usage) == 0 means that the command takes no
arguments. * arguments.
*/ */
if ((cr->jim_handler == NULL) && if ((cr->jim_handler == NULL) && (cr->usage == NULL)) {
(cr->usage == NULL)) {
LOG_DEBUG("BUG: command '%s%s%s' does not have the " LOG_DEBUG("BUG: command '%s%s%s' does not have the "
"'.usage' field filled out", "'.usage' field filled out",
parent && parent->name ? parent->name : "", parent && parent->name ? parent->name : "",
@ -398,7 +387,7 @@ static int register_command_handler(struct command_context *cmd_ctx,
return retval; return retval;
} }
struct command* register_command(struct command_context *context, struct command *register_command(struct command_context *context,
struct command *parent, const struct command_registration *cr) struct command *parent, const struct command_registration *cr)
{ {
if (!context || !cr->name) if (!context || !cr->name)
@ -407,8 +396,7 @@ struct command* register_command(struct command_context *context,
const char *name = cr->name; const char *name = cr->name;
struct command **head = command_list_for_parent(context, parent); struct command **head = command_list_for_parent(context, parent);
struct command *c = command_find(*head, name); struct command *c = command_find(*head, name);
if (NULL != c) if (NULL != c) {
{
/* TODO: originally we treated attempting to register a cmd twice as an error /* TODO: originally we treated attempting to register a cmd twice as an error
* Sometimes we need this behaviour, such as with flash banks. * Sometimes we need this behaviour, such as with flash banks.
* http://www.mail-archive.com/openocd-development@lists.berlios.de/msg11152.html */ * http://www.mail-archive.com/openocd-development@lists.berlios.de/msg11152.html */
@ -422,16 +410,13 @@ struct command* register_command(struct command_context *context,
return NULL; return NULL;
int retval = ERROR_OK; int retval = ERROR_OK;
if (NULL != cr->jim_handler && NULL == parent) if (NULL != cr->jim_handler && NULL == parent) {
{
retval = Jim_CreateCommand(context->interp, cr->name, retval = Jim_CreateCommand(context->interp, cr->name,
cr->jim_handler, cr->jim_handler_data, NULL); cr->jim_handler, cr->jim_handler_data, NULL);
} } else if (NULL != cr->handler || NULL != parent)
else if (NULL != cr->handler || NULL != parent)
retval = register_command_handler(context, command_root(c)); retval = register_command_handler(context, command_root(c));
if (ERROR_OK != retval) if (ERROR_OK != retval) {
{
unregister_command(context, parent, name); unregister_command(context, parent, name);
c = NULL; c = NULL;
} }
@ -443,30 +428,25 @@ int register_commands(struct command_context *cmd_ctx, struct command *parent,
{ {
int retval = ERROR_OK; int retval = ERROR_OK;
unsigned i; unsigned i;
for (i = 0; cmds[i].name || cmds[i].chain; i++) for (i = 0; cmds[i].name || cmds[i].chain; i++) {
{
const struct command_registration *cr = cmds + i; const struct command_registration *cr = cmds + i;
struct command *c = NULL; struct command *c = NULL;
if (NULL != cr->name) if (NULL != cr->name) {
{
c = register_command(cmd_ctx, parent, cr); c = register_command(cmd_ctx, parent, cr);
if (NULL == c) if (NULL == c) {
{
retval = ERROR_FAIL; retval = ERROR_FAIL;
break; break;
} }
} }
if (NULL != cr->chain) if (NULL != cr->chain) {
{
struct command *p = c ? : parent; struct command *p = c ? : parent;
retval = register_commands(cmd_ctx, p, cr->chain); retval = register_commands(cmd_ctx, p, cr->chain);
if (ERROR_OK != retval) if (ERROR_OK != retval)
break; break;
} }
} }
if (ERROR_OK != retval) if (ERROR_OK != retval) {
{
for (unsigned j = 0; j < i; j++) for (unsigned j = 0; j < i; j++)
unregister_command(cmd_ctx, parent, cmds[j].name); unregister_command(cmd_ctx, parent, cmds[j].name);
} }
@ -480,8 +460,7 @@ int unregister_all_commands(struct command_context *context,
return ERROR_OK; return ERROR_OK;
struct command **head = command_list_for_parent(context, parent); struct command **head = command_list_for_parent(context, parent);
while (NULL != *head) while (NULL != *head) {
{
struct command *tmp = *head; struct command *tmp = *head;
*head = tmp->next; *head = tmp->next;
command_free(tmp); command_free(tmp);
@ -498,8 +477,7 @@ int unregister_command(struct command_context *context,
struct command *p = NULL; struct command *p = NULL;
struct command **head = command_list_for_parent(context, parent); struct command **head = command_list_for_parent(context, parent);
for (struct command *c = *head; NULL != c; p = c, c = c->next) for (struct command *c = *head; NULL != c; p = c, c = c->next) {
{
if (strcmp(name, c->name) != 0) if (strcmp(name, c->name) != 0)
continue; continue;
@ -525,9 +503,8 @@ void command_set_handler_data(struct command *c, void *p)
void command_output_text(struct command_context *context, const char *data) void command_output_text(struct command_context *context, const char *data)
{ {
if (context && context->output_handler && data) { if (context && context->output_handler && data)
context->output_handler(context, data); context->output_handler(context, data);
}
} }
void command_print_sameline(struct command_context *context, const char *format, ...) void command_print_sameline(struct command_context *context, const char *format, ...)
@ -538,16 +515,15 @@ void command_print_sameline(struct command_context *context, const char *format,
va_start(ap, format); va_start(ap, format);
string = alloc_vprintf(format, ap); string = alloc_vprintf(format, ap);
if (string != NULL) if (string != NULL) {
{
/* we want this collected in the log + we also want to pick it up as a tcl return /* we want this collected in the log + we also want to pick it up as a tcl return
* value. * value.
* *
* The latter bit isn't precisely neat, but will do for now. * The latter bit isn't precisely neat, but will do for now.
*/ */
LOG_USER_N("%s", string); LOG_USER_N("%s", string);
/* We already printed it above */ /* We already printed it above
/* command_output_text(context, string); */ * command_output_text(context, string); */
free(string); free(string);
} }
@ -562,17 +538,17 @@ void command_print(struct command_context *context, const char *format, ...)
va_start(ap, format); va_start(ap, format);
string = alloc_vprintf(format, ap); string = alloc_vprintf(format, ap);
if (string != NULL) if (string != NULL) {
{ strcat(string, "\n"); /* alloc_vprintf guaranteed the buffer to be at least one
strcat(string, "\n"); /* alloc_vprintf guaranteed the buffer to be at least one char longer */ *char longer */
/* we want this collected in the log + we also want to pick it up as a tcl return /* we want this collected in the log + we also want to pick it up as a tcl return
* value. * value.
* *
* The latter bit isn't precisely neat, but will do for now. * The latter bit isn't precisely neat, but will do for now.
*/ */
LOG_USER_N("%s", string); LOG_USER_N("%s", string);
/* We already printed it above */ /* We already printed it above
/* command_output_text(context, string); */ * command_output_text(context, string); */
free(string); free(string);
} }
@ -584,11 +560,11 @@ static char *__command_name(struct command *c, char delim, unsigned extra)
char *name; char *name;
unsigned len = strlen(c->name); unsigned len = strlen(c->name);
if (NULL == c->parent) { if (NULL == c->parent) {
// allocate enough for the name, child names, and '\0' /* allocate enough for the name, child names, and '\0' */
name = malloc(len + extra + 1); name = malloc(len + extra + 1);
strcpy(name, c->name); strcpy(name, c->name);
} else { } else {
// parent's extra must include both the space and name /* parent's extra must include both the space and name */
name = __command_name(c->parent, delim, 1 + len + extra); name = __command_name(c->parent, delim, 1 + len + extra);
char dstr[2] = { delim, 0 }; char dstr[2] = { delim, 0 };
strcat(name, dstr); strcat(name, dstr);
@ -609,15 +585,20 @@ static bool command_can_run(struct command_context *cmd_ctx, struct command *c)
static int run_command(struct command_context *context, static int run_command(struct command_context *context,
struct command *c, const char *words[], unsigned num_words) struct command *c, const char *words[], unsigned num_words)
{ {
if (!command_can_run(context, c)) if (!command_can_run(context, c)) {
{
/* Many commands may be run only before/after 'init' */ /* Many commands may be run only before/after 'init' */
const char *when; const char *when;
switch (c->mode) { switch (c->mode) {
case COMMAND_CONFIG: when = "before"; break; case COMMAND_CONFIG:
case COMMAND_EXEC: when = "after"; break; when = "before";
// handle the impossible with humor; it guarantees a bug report! break;
default: when = "if Cthulhu is summoned by"; break; case COMMAND_EXEC:
when = "after";
break;
/* handle the impossible with humor; it guarantees a bug report! */
default:
when = "if Cthulhu is summoned by";
break;
} }
LOG_ERROR("The '%s' command must be used %s 'init'.", LOG_ERROR("The '%s' command must be used %s 'init'.",
c->name, when); c->name, when);
@ -632,8 +613,7 @@ static int run_command(struct command_context *context,
.argv = words + 1, .argv = words + 1,
}; };
int retval = c->handler(&cmd); int retval = c->handler(&cmd);
if (retval == ERROR_COMMAND_SYNTAX_ERROR) if (retval == ERROR_COMMAND_SYNTAX_ERROR) {
{
/* Print help for command */ /* Print help for command */
char *full_name = command_name(c, ' '); char *full_name = command_name(c, ' ');
if (NULL != full_name) { if (NULL != full_name) {
@ -641,13 +621,9 @@ static int run_command(struct command_context *context,
free(full_name); free(full_name);
} else } else
retval = -ENOMEM; retval = -ENOMEM;
} } else if (retval == ERROR_COMMAND_CLOSE_CONNECTION) {
else if (retval == ERROR_COMMAND_CLOSE_CONNECTION)
{
/* just fall through for a shutdown request */ /* just fall through for a shutdown request */
} } else if (retval != ERROR_OK) {
else if (retval != ERROR_OK)
{
/* we do not print out an error message because the command *should* /* we do not print out an error message because the command *should*
* have printed out an error * have printed out an error
*/ */
@ -674,13 +650,11 @@ int command_run_line(struct command_context *context, char *line)
Jim_Interp *interp = context->interp; Jim_Interp *interp = context->interp;
Jim_DeleteAssocData(interp, "context"); Jim_DeleteAssocData(interp, "context");
retcode = Jim_SetAssocData(interp, "context", NULL, context); retcode = Jim_SetAssocData(interp, "context", NULL, context);
if (retcode == JIM_OK) if (retcode == JIM_OK) {
{
/* associated the return value */ /* associated the return value */
Jim_DeleteAssocData(interp, "retval"); Jim_DeleteAssocData(interp, "retval");
retcode = Jim_SetAssocData(interp, "retval", NULL, &retval); retcode = Jim_SetAssocData(interp, "retval", NULL, &retval);
if (retcode == JIM_OK) if (retcode == JIM_OK) {
{
retcode = Jim_Eval_Named(interp, line, 0, 0); retcode = Jim_Eval_Named(interp, line, 0, 0);
Jim_DeleteAssocData(interp, "retval"); Jim_DeleteAssocData(interp, "retval");
@ -688,32 +662,28 @@ int command_run_line(struct command_context *context, char *line)
Jim_DeleteAssocData(interp, "context"); Jim_DeleteAssocData(interp, "context");
} }
if (retcode == JIM_ERR) { if (retcode == JIM_ERR) {
if (retval != ERROR_COMMAND_CLOSE_CONNECTION) if (retval != ERROR_COMMAND_CLOSE_CONNECTION) {
{
/* We do not print the connection closed error message */ /* We do not print the connection closed error message */
Jim_MakeErrorMessage(interp); Jim_MakeErrorMessage(interp);
LOG_USER("%s", Jim_GetString(Jim_GetResult(interp), NULL)); LOG_USER("%s", Jim_GetString(Jim_GetResult(interp), NULL));
} }
if (retval == ERROR_OK) if (retval == ERROR_OK) {
{
/* It wasn't a low level OpenOCD command that failed */ /* It wasn't a low level OpenOCD command that failed */
return ERROR_FAIL; return ERROR_FAIL;
} }
return retval; return retval;
} else if (retcode == JIM_EXIT) { } else if (retcode == JIM_EXIT) {
/* ignore. */ /* ignore.
/* exit(Jim_GetExitCode(interp)); */ * exit(Jim_GetExitCode(interp)); */
} else { } else {
const char *result; const char *result;
int reslen; int reslen;
result = Jim_GetString(Jim_GetResult(interp), &reslen); result = Jim_GetString(Jim_GetResult(interp), &reslen);
if (reslen > 0) if (reslen > 0) {
{
int i; int i;
char buff[256 + 1]; char buff[256 + 1];
for (i = 0; i < reslen; i += 256) for (i = 0; i < reslen; i += 256) {
{
int chunk; int chunk;
chunk = reslen - i; chunk = reslen - i;
if (chunk > 256) if (chunk > 256)
@ -736,8 +706,7 @@ int command_run_linef(struct command_context *context, const char *format, ...)
va_list ap; va_list ap;
va_start(ap, format); va_start(ap, format);
string = alloc_vprintf(format, ap); string = alloc_vprintf(format, ap);
if (string != NULL) if (string != NULL) {
{
retval = command_run_line(context, string); retval = command_run_line(context, string);
free(string); free(string);
} }
@ -745,16 +714,16 @@ int command_run_linef(struct command_context *context, const char *format, ...)
return retval; return retval;
} }
void command_set_output_handler(struct command_context* context, void command_set_output_handler(struct command_context *context,
command_output_handler_t output_handler, void *priv) command_output_handler_t output_handler, void *priv)
{ {
context->output_handler = output_handler; context->output_handler = output_handler;
context->output_handler_priv = priv; context->output_handler_priv = priv;
} }
struct command_context* copy_command_context(struct command_context* context) struct command_context *copy_command_context(struct command_context *context)
{ {
struct command_context* copy_context = malloc(sizeof(struct command_context)); struct command_context *copy_context = malloc(sizeof(struct command_context));
*copy_context = *context; *copy_context = *context;
@ -787,8 +756,7 @@ static int jim_find(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
COMMAND_HANDLER(jim_echo) COMMAND_HANDLER(jim_echo)
{ {
if (CMD_ARGC == 2 && !strcmp(CMD_ARGV[0], "-n")) if (CMD_ARGC == 2 && !strcmp(CMD_ARGV[0], "-n")) {
{
LOG_USER_N("%s", CMD_ARGV[1]); LOG_USER_N("%s", CMD_ARGV[1]);
return JIM_OK; return JIM_OK;
} }
@ -865,8 +833,7 @@ static void command_help_show_indent(unsigned n)
static void command_help_show_wrap(const char *str, unsigned n, unsigned n2) static void command_help_show_wrap(const char *str, unsigned n, unsigned n2)
{ {
const char *cp = str, *last = str; const char *cp = str, *last = str;
while (*cp) while (*cp) {
{
const char *next = last; const char *next = last;
do { do {
cp = next; cp = next;
@ -895,25 +862,21 @@ static COMMAND_HELPER(command_help_show, struct command *c, unsigned n,
((c->usage != NULL) && (strstr(c->usage, match) != NULL)) || ((c->usage != NULL) && (strstr(c->usage, match) != NULL)) ||
((c->help != NULL) && (strstr(c->help, match) != NULL)); ((c->help != NULL) && (strstr(c->help, match) != NULL));
if (is_match) if (is_match) {
{
command_help_show_indent(n); command_help_show_indent(n);
LOG_USER_N("%s", cmd_name); LOG_USER_N("%s", cmd_name);
} }
free(cmd_name); free(cmd_name);
if (is_match) if (is_match) {
{
if (c->usage) { if (c->usage) {
LOG_USER_N(" "); LOG_USER_N(" ");
command_help_show_wrap(c->usage, 0, n + 5); command_help_show_wrap(c->usage, 0, n + 5);
} } else
else
LOG_USER_N("\n"); LOG_USER_N("\n");
} }
if (is_match && show_help) if (is_match && show_help) {
{
char *msg; char *msg;
/* Normal commands are runtime-only; highlight exceptions */ /* Normal commands are runtime-only; highlight exceptions */
@ -935,8 +898,7 @@ static COMMAND_HELPER(command_help_show, struct command *c, unsigned n,
} else } else
msg = alloc_printf("%s", c->help ? : ""); msg = alloc_printf("%s", c->help ? : "");
if (NULL != msg) if (NULL != msg) {
{
command_help_show_wrap(msg, n + 3, n + 3); command_help_show_wrap(msg, n + 3, n + 3);
free(msg); free(msg);
} else } else
@ -1010,12 +972,10 @@ static int command_unknown_find(unsigned argc, Jim_Obj *const *argv,
return command_unknown_find(--argc, ++argv, (*out)->children, out, false); return command_unknown_find(--argc, ++argv, (*out)->children, out, false);
} }
static int command_unknown(Jim_Interp *interp, int argc, Jim_Obj *const *argv) static int command_unknown(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{ {
const char *cmd_name = Jim_GetString(argv[0], NULL); const char *cmd_name = Jim_GetString(argv[0], NULL);
if (strcmp(cmd_name, "unknown") == 0) if (strcmp(cmd_name, "unknown") == 0) {
{
if (argc == 1) if (argc == 1)
return JIM_OK; return JIM_OK;
argc--; argc--;
@ -1026,9 +986,8 @@ static int command_unknown(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
struct command_context *cmd_ctx = current_command_context(interp); struct command_context *cmd_ctx = current_command_context(interp);
struct command *c = cmd_ctx->commands; struct command *c = cmd_ctx->commands;
int remaining = command_unknown_find(argc, argv, c, &c, true); int remaining = command_unknown_find(argc, argv, c, &c, true);
// if nothing could be consumed, then it's really an unknown command /* if nothing could be consumed, then it's really an unknown command */
if (remaining == argc) if (remaining == argc) {
{
const char *cmd = Jim_GetString(argv[0], NULL); const char *cmd = Jim_GetString(argv[0], NULL);
LOG_ERROR("Unknown command:\n %s", cmd); LOG_ERROR("Unknown command:\n %s", cmd);
return JIM_OK; return JIM_OK;
@ -1037,17 +996,13 @@ static int command_unknown(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
bool found = true; bool found = true;
Jim_Obj *const *start; Jim_Obj *const *start;
unsigned count; unsigned count;
if (c->handler || c->jim_handler) if (c->handler || c->jim_handler) {
{ /* include the command name in the list */
// include the command name in the list
count = remaining + 1; count = remaining + 1;
start = argv + (argc - remaining - 1); start = argv + (argc - remaining - 1);
} } else {
else
{
c = command_find(cmd_ctx->commands, "usage"); c = command_find(cmd_ctx->commands, "usage");
if (NULL == c) if (NULL == c) {
{
LOG_ERROR("unknown command, but usage is missing too"); LOG_ERROR("unknown command, but usage is missing too");
return JIM_ERR; return JIM_ERR;
} }
@ -1055,9 +1010,8 @@ static int command_unknown(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
start = argv; start = argv;
found = false; found = false;
} }
// pass the command through to the intended handler /* pass the command through to the intended handler */
if (c->jim_handler) if (c->jim_handler) {
{
interp->cmdPrivData = c->jim_handler_data; interp->cmdPrivData = c->jim_handler_data;
return (*c->jim_handler)(interp, count, start); return (*c->jim_handler)(interp, count, start);
} }
@ -1070,27 +1024,32 @@ static int jim_command_mode(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
struct command_context *cmd_ctx = current_command_context(interp); struct command_context *cmd_ctx = current_command_context(interp);
enum command_mode mode; enum command_mode mode;
if (argc > 1) if (argc > 1) {
{
struct command *c = cmd_ctx->commands; struct command *c = cmd_ctx->commands;
int remaining = command_unknown_find(argc - 1, argv + 1, c, &c, true); int remaining = command_unknown_find(argc - 1, argv + 1, c, &c, true);
// if nothing could be consumed, then it's an unknown command /* if nothing could be consumed, then it's an unknown command */
if (remaining == argc - 1) if (remaining == argc - 1) {
{
Jim_SetResultString(interp, "unknown", -1); Jim_SetResultString(interp, "unknown", -1);
return JIM_OK; return JIM_OK;
} }
mode = c->mode; mode = c->mode;
} } else
else
mode = cmd_ctx->mode; mode = cmd_ctx->mode;
const char *mode_str; const char *mode_str;
switch (mode) { switch (mode) {
case COMMAND_ANY: mode_str = "any"; break; case COMMAND_ANY:
case COMMAND_CONFIG: mode_str = "config"; break; mode_str = "any";
case COMMAND_EXEC: mode_str = "exec"; break; break;
default: mode_str = "unknown"; break; case COMMAND_CONFIG:
mode_str = "config";
break;
case COMMAND_EXEC:
mode_str = "exec";
break;
default:
mode_str = "unknown";
break;
} }
Jim_SetResultString(interp, mode_str, -1); Jim_SetResultString(interp, mode_str, -1);
return JIM_OK; return JIM_OK;
@ -1104,9 +1063,8 @@ static int jim_command_type(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
struct command_context *cmd_ctx = current_command_context(interp); struct command_context *cmd_ctx = current_command_context(interp);
struct command *c = cmd_ctx->commands; struct command *c = cmd_ctx->commands;
int remaining = command_unknown_find(argc - 1, argv + 1, c, &c, true); int remaining = command_unknown_find(argc - 1, argv + 1, c, &c, true);
// if nothing could be consumed, then it's an unknown command /* if nothing could be consumed, then it's an unknown command */
if (remaining == argc - 1) if (remaining == argc - 1) {
{
Jim_SetResultString(interp, "unknown", -1); Jim_SetResultString(interp, "unknown", -1);
return JIM_OK; return JIM_OK;
} }
@ -1126,9 +1084,8 @@ int help_add_command(struct command_context *cmd_ctx, struct command *parent,
{ {
struct command **head = command_list_for_parent(cmd_ctx, parent); struct command **head = command_list_for_parent(cmd_ctx, parent);
struct command *nc = command_find(*head, cmd_name); struct command *nc = command_find(*head, cmd_name);
if (NULL == nc) if (NULL == nc) {
{ /* add a new command with help text */
// add a new command with help text
struct command_registration cr = { struct command_registration cr = {
.name = cmd_name, .name = cmd_name,
.mode = COMMAND_ANY, .mode = COMMAND_ANY,
@ -1136,19 +1093,16 @@ int help_add_command(struct command_context *cmd_ctx, struct command *parent,
.usage = usage, .usage = usage,
}; };
nc = register_command(cmd_ctx, parent, &cr); nc = register_command(cmd_ctx, parent, &cr);
if (NULL == nc) if (NULL == nc) {
{
LOG_ERROR("failed to add '%s' help text", cmd_name); LOG_ERROR("failed to add '%s' help text", cmd_name);
return ERROR_FAIL; return ERROR_FAIL;
} }
LOG_DEBUG("added '%s' help text", cmd_name); LOG_DEBUG("added '%s' help text", cmd_name);
return ERROR_OK; return ERROR_OK;
} }
if (help_text) if (help_text) {
{
bool replaced = false; bool replaced = false;
if (nc->help) if (nc->help) {
{
free((void *)nc->help); free((void *)nc->help);
replaced = true; replaced = true;
} }
@ -1158,11 +1112,9 @@ int help_add_command(struct command_context *cmd_ctx, struct command *parent,
else else
LOG_DEBUG("added '%s' help text", cmd_name); LOG_DEBUG("added '%s' help text", cmd_name);
} }
if (usage) if (usage) {
{
bool replaced = false; bool replaced = false;
if (nc->usage) if (nc->usage) {
{
free((void *)nc->usage); free((void *)nc->usage);
replaced = true; replaced = true;
} }
@ -1177,27 +1129,24 @@ int help_add_command(struct command_context *cmd_ctx, struct command *parent,
COMMAND_HANDLER(handle_help_add_command) COMMAND_HANDLER(handle_help_add_command)
{ {
if (CMD_ARGC < 2) if (CMD_ARGC < 2) {
{
LOG_ERROR("%s: insufficient arguments", CMD_NAME); LOG_ERROR("%s: insufficient arguments", CMD_NAME);
return ERROR_COMMAND_SYNTAX_ERROR; return ERROR_COMMAND_SYNTAX_ERROR;
} }
// save help text and remove it from argument list /* save help text and remove it from argument list */
const char *str = CMD_ARGV[--CMD_ARGC]; const char *str = CMD_ARGV[--CMD_ARGC];
const char *help = !strcmp(CMD_NAME, "add_help_text") ? str : NULL; const char *help = !strcmp(CMD_NAME, "add_help_text") ? str : NULL;
const char *usage = !strcmp(CMD_NAME, "add_usage_text") ? str : NULL; const char *usage = !strcmp(CMD_NAME, "add_usage_text") ? str : NULL;
if (!help && !usage) if (!help && !usage) {
{
LOG_ERROR("command name '%s' is unknown", CMD_NAME); LOG_ERROR("command name '%s' is unknown", CMD_NAME);
return ERROR_COMMAND_SYNTAX_ERROR; return ERROR_COMMAND_SYNTAX_ERROR;
} }
// likewise for the leaf command name /* likewise for the leaf command name */
const char *cmd_name = CMD_ARGV[--CMD_ARGC]; const char *cmd_name = CMD_ARGV[--CMD_ARGC];
struct command *c = NULL; struct command *c = NULL;
if (CMD_ARGC > 0) if (CMD_ARGC > 0) {
{
c = CMD_CTX->commands; c = CMD_CTX->commands;
int retval = CALL_COMMAND_HANDLER(command_help_find, c, &c); int retval = CALL_COMMAND_HANDLER(command_help_find, c, &c);
if (ERROR_OK != retval) if (ERROR_OK != retval)
@ -1212,14 +1161,12 @@ COMMAND_HANDLER(handle_help_add_command)
COMMAND_HANDLER(handle_sleep_command) COMMAND_HANDLER(handle_sleep_command)
{ {
bool busy = false; bool busy = false;
if (CMD_ARGC == 2) if (CMD_ARGC == 2) {
{
if (strcmp(CMD_ARGV[1], "busy") == 0) if (strcmp(CMD_ARGV[1], "busy") == 0)
busy = true; busy = true;
else else
return ERROR_COMMAND_SYNTAX_ERROR; return ERROR_COMMAND_SYNTAX_ERROR;
} } else if (CMD_ARGC < 1 || CMD_ARGC > 2)
else if (CMD_ARGC < 1 || CMD_ARGC > 2)
return ERROR_COMMAND_SYNTAX_ERROR; return ERROR_COMMAND_SYNTAX_ERROR;
unsigned long duration = 0; unsigned long duration = 0;
@ -1227,16 +1174,13 @@ COMMAND_HANDLER(handle_sleep_command)
if (ERROR_OK != retval) if (ERROR_OK != retval)
return retval; return retval;
if (!busy) if (!busy) {
{
long long then = timeval_ms(); long long then = timeval_ms();
while (timeval_ms() - then < (long long)duration) while (timeval_ms() - then < (long long)duration) {
{
target_call_timer_callbacks_now(); target_call_timer_callbacks_now();
usleep(1000); usleep(1000);
} }
} } else
else
busy_sleep(duration); busy_sleep(duration);
return ERROR_OK; return ERROR_OK;
@ -1318,16 +1262,16 @@ static const struct command_registration command_builtin_handlers[] = {
}, },
{ {
.name = "command", .name = "command",
.mode= COMMAND_ANY, .mode = COMMAND_ANY,
.help = "core command group (introspection)", .help = "core command group (introspection)",
.chain = command_subcommand_handlers, .chain = command_subcommand_handlers,
}, },
COMMAND_REGISTRATION_DONE COMMAND_REGISTRATION_DONE
}; };
struct command_context* command_init(const char *startup_tcl, Jim_Interp *interp) struct command_context *command_init(const char *startup_tcl, Jim_Interp *interp)
{ {
struct command_context* context = malloc(sizeof(struct command_context)); struct command_context *context = malloc(sizeof(struct command_context));
const char *HostOs; const char *HostOs;
context->mode = COMMAND_EXEC; context->mode = COMMAND_EXEC;
@ -1338,8 +1282,7 @@ struct command_context* command_init(const char *startup_tcl, Jim_Interp *interp
#if !BUILD_ECOSBOARD #if !BUILD_ECOSBOARD
/* Create a jim interpreter if we were not handed one */ /* Create a jim interpreter if we were not handed one */
if (interp == NULL) if (interp == NULL) {
{
/* Create an interpreter */ /* Create an interpreter */
interp = Jim_CreateInterp(); interp = Jim_CreateInterp();
/* Add all the Jim core commands */ /* Add all the Jim core commands */
@ -1376,7 +1319,7 @@ struct command_context* command_init(const char *startup_tcl, Jim_Interp *interp
HostOs = "other"; HostOs = "other";
#endif #endif
Jim_SetGlobalVariableStr(interp, "ocd_HOSTOS", Jim_SetGlobalVariableStr(interp, "ocd_HOSTOS",
Jim_NewStringObj(interp, HostOs , strlen(HostOs))); Jim_NewStringObj(interp, HostOs, strlen(HostOs)));
Jim_CreateCommand(interp, "ocd_find", jim_find, NULL, NULL); Jim_CreateCommand(interp, "ocd_find", jim_find, NULL, NULL);
Jim_CreateCommand(interp, "capture", jim_capture, NULL, NULL); Jim_CreateCommand(interp, "capture", jim_capture, NULL, NULL);
@ -1384,8 +1327,7 @@ struct command_context* command_init(const char *startup_tcl, Jim_Interp *interp
register_commands(context, NULL, command_builtin_handlers); register_commands(context, NULL, command_builtin_handlers);
Jim_SetAssocData(interp, "context", NULL, context); Jim_SetAssocData(interp, "context", NULL, context);
if (Jim_Eval_Named(interp, startup_tcl, "embedded:startup.tcl",1) == JIM_ERR) if (Jim_Eval_Named(interp, startup_tcl, "embedded:startup.tcl", 1) == JIM_ERR) {
{
LOG_ERROR("Failed to run startup.tcl (embedded into OpenOCD)"); LOG_ERROR("Failed to run startup.tcl (embedded into OpenOCD)");
Jim_MakeErrorMessage(interp); Jim_MakeErrorMessage(interp);
LOG_USER_N("%s", Jim_GetString(Jim_GetResult(interp), NULL)); LOG_USER_N("%s", Jim_GetString(Jim_GetResult(interp), NULL));
@ -1408,7 +1350,7 @@ int command_context_mode(struct command_context *cmd_ctx, enum command_mode mode
void process_jim_events(struct command_context *cmd_ctx) void process_jim_events(struct command_context *cmd_ctx)
{ {
#if !BUILD_ECOSBOARD #if !BUILD_ECOSBOARD
static int recursion = 0; static int recursion;
if (recursion) if (recursion)
return; return;
@ -1419,42 +1361,38 @@ void process_jim_events(struct command_context *cmd_ctx)
} }
#define DEFINE_PARSE_NUM_TYPE(name, type, func, min, max) \ #define DEFINE_PARSE_NUM_TYPE(name, type, func, min, max) \
int parse##name(const char *str, type *ul) \ int parse ## name(const char *str, type * ul) \
{ \
if (!*str) \
{ \ { \
if (!*str) { \
LOG_ERROR("Invalid command argument"); \ LOG_ERROR("Invalid command argument"); \
return ERROR_COMMAND_ARGUMENT_INVALID; \ return ERROR_COMMAND_ARGUMENT_INVALID; \
} \ } \
char *end; \ char *end; \
*ul = func(str, &end, 0); \ *ul = func(str, &end, 0); \
if (*end) \ if (*end) { \
{ \
LOG_ERROR("Invalid command argument"); \ LOG_ERROR("Invalid command argument"); \
return ERROR_COMMAND_ARGUMENT_INVALID; \ return ERROR_COMMAND_ARGUMENT_INVALID; \
} \ } \
if ((max == *ul) && (ERANGE == errno)) \ if ((max == *ul) && (ERANGE == errno)) { \
{ \
LOG_ERROR("Argument overflow"); \ LOG_ERROR("Argument overflow"); \
return ERROR_COMMAND_ARGUMENT_OVERFLOW; \ return ERROR_COMMAND_ARGUMENT_OVERFLOW; \
} \ } \
if (min && (min == *ul) && (ERANGE == errno)) \ if (min && (min == *ul) && (ERANGE == errno)) { \
{ \
LOG_ERROR("Argument underflow"); \ LOG_ERROR("Argument underflow"); \
return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \ return ERROR_COMMAND_ARGUMENT_UNDERFLOW; \
} \ } \
return ERROR_OK; \ return ERROR_OK; \
} }
DEFINE_PARSE_NUM_TYPE(_ulong, unsigned long , strtoul, 0, ULONG_MAX) DEFINE_PARSE_NUM_TYPE(_ulong, unsigned long, strtoul, 0, ULONG_MAX)
DEFINE_PARSE_NUM_TYPE(_ullong, unsigned long long, strtoull, 0, ULLONG_MAX) DEFINE_PARSE_NUM_TYPE(_ullong, unsigned long long, strtoull, 0, ULLONG_MAX)
DEFINE_PARSE_NUM_TYPE(_long, long , strtol, LONG_MIN, LONG_MAX) DEFINE_PARSE_NUM_TYPE(_long, long, strtol, LONG_MIN, LONG_MAX)
DEFINE_PARSE_NUM_TYPE(_llong, long long, strtoll, LLONG_MIN, LLONG_MAX) DEFINE_PARSE_NUM_TYPE(_llong, long long, strtoll, LLONG_MIN, LLONG_MAX)
#define DEFINE_PARSE_WRAPPER(name, type, min, max, functype, funcname) \ #define DEFINE_PARSE_WRAPPER(name, type, min, max, functype, funcname) \
int parse##name(const char *str, type *ul) \ int parse ## name(const char *str, type * ul) \
{ \ { \
functype n; \ functype n; \
int retval = parse##funcname(str, &n); \ int retval = parse ## funcname(str, &n); \
if (ERROR_OK != retval) \ if (ERROR_OK != retval) \
return retval; \ return retval; \
if (n > max) \ if (n > max) \
@ -1511,12 +1449,11 @@ COMMAND_HELPER(handle_command_parse_bool, bool *out, const char *label)
switch (CMD_ARGC) { switch (CMD_ARGC) {
case 1: { case 1: {
const char *in = CMD_ARGV[0]; const char *in = CMD_ARGV[0];
if (command_parse_bool_arg(in, out) != ERROR_OK) if (command_parse_bool_arg(in, out) != ERROR_OK) {
{
LOG_ERROR("%s: argument '%s' is not valid", CMD_NAME, in); LOG_ERROR("%s: argument '%s' is not valid", CMD_NAME, in);
return ERROR_COMMAND_SYNTAX_ERROR; return ERROR_COMMAND_SYNTAX_ERROR;
} }
// fall through /* fall through */
} }
case 0: case 0:
LOG_INFO("%s is %s", label, *out ? "enabled" : "disabled"); LOG_INFO("%s is %s", label, *out ? "enabled" : "disabled");

View File

@ -20,6 +20,7 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#ifndef COMMAND_H #ifndef COMMAND_H
#define COMMAND_H #define COMMAND_H
@ -43,8 +44,7 @@
#define PRINTF_ATTRIBUTE_FORMAT printf #define PRINTF_ATTRIBUTE_FORMAT printf
#endif #endif
enum command_mode enum command_mode {
{
COMMAND_EXEC, COMMAND_EXEC,
COMMAND_CONFIG, COMMAND_CONFIG,
COMMAND_ANY, COMMAND_ANY,
@ -52,12 +52,11 @@ enum command_mode
struct command_context; struct command_context;
/// The type signature for command context's output handler. /* / The type signature for command context's output handler. */
typedef int (*command_output_handler_t)(struct command_context *context, typedef int (*command_output_handler_t)(struct command_context *context,
const char* line); const char *line);
struct command_context struct command_context {
{
Jim_Interp *interp; Jim_Interp *interp;
enum command_mode mode; enum command_mode mode;
struct command *commands; struct command *commands;
@ -86,8 +85,8 @@ struct command_invocation {
* set provided by command.c. This macro uses C99 magic to allow * set provided by command.c. This macro uses C99 magic to allow
* defining all such derivative types using this macro. * defining all such derivative types using this macro.
*/ */
#define __COMMAND_HANDLER(name, extra...) \ #define __COMMAND_HANDLER(name, extra ...) \
int name(struct command_invocation *cmd, ##extra) int name(struct command_invocation *cmd, ## extra)
/** /**
* Use this to macro to call a command helper (or a nested handler). * Use this to macro to call a command helper (or a nested handler).
@ -102,8 +101,8 @@ struct command_invocation {
* helper function, or care must be taken to avoid redefining the same * helper function, or care must be taken to avoid redefining the same
* variables in intervening scope(s) by accident. * variables in intervening scope(s) by accident.
*/ */
#define CALL_COMMAND_HANDLER(name, extra...) \ #define CALL_COMMAND_HANDLER(name, extra ...) \
name(cmd, ##extra) name(cmd, ## extra)
/** /**
* Always use this macro to define new command handler functions. * Always use this macro to define new command handler functions.
@ -111,46 +110,46 @@ struct command_invocation {
* they be can be used by other macros (e.g. COMMAND_PARSE_NUMBER). * they be can be used by other macros (e.g. COMMAND_PARSE_NUMBER).
* All command handler functions must be defined as static in scope. * All command handler functions must be defined as static in scope.
*/ */
#define COMMAND_HANDLER(name) static __COMMAND_HANDLER(name) #define COMMAND_HANDLER(name) \
static __COMMAND_HANDLER(name)
/** /**
* Similar to COMMAND_HANDLER, except some parameters are expected. * Similar to COMMAND_HANDLER, except some parameters are expected.
* A helper is globally-scoped because it may be shared between several * A helper is globally-scoped because it may be shared between several
* source files (e.g. the s3c24xx device command helper). * source files (e.g. the s3c24xx device command helper).
*/ */
#define COMMAND_HELPER(name, extra...) __COMMAND_HANDLER(name, extra) #define COMMAND_HELPER(name, extra ...) __COMMAND_HANDLER(name, extra)
/** /**
* Use this macro to access the context of the command being handled, * Use this macro to access the context of the command being handled,
* rather than accessing the variable directly. It may be moved. * rather than accessing the variable directly. It may be moved.
*/ */
#define CMD_CTX cmd->ctx #define CMD_CTX (cmd->ctx)
/** /**
* Use this macro to access the number of arguments for the command being * Use this macro to access the number of arguments for the command being
* handled, rather than accessing the variable directly. It may be moved. * handled, rather than accessing the variable directly. It may be moved.
*/ */
#define CMD_ARGC cmd->argc #define CMD_ARGC (cmd->argc)
/** /**
* Use this macro to access the arguments for the command being handled, * Use this macro to access the arguments for the command being handled,
* rather than accessing the variable directly. It may be moved. * rather than accessing the variable directly. It may be moved.
*/ */
#define CMD_ARGV cmd->argv #define CMD_ARGV (cmd->argv)
/** /**
* Use this macro to access the name of the command being handled, * Use this macro to access the name of the command being handled,
* rather than accessing the variable directly. It may be moved. * rather than accessing the variable directly. It may be moved.
*/ */
#define CMD_NAME cmd->name #define CMD_NAME (cmd->name)
/** /**
* Use this macro to access the current command being handled, * Use this macro to access the current command being handled,
* rather than accessing the variable directly. It may be moved. * rather than accessing the variable directly. It may be moved.
*/ */
#define CMD_CURRENT cmd->current #define CMD_CURRENT (cmd->current)
/** /**
* Use this macro to access the invoked command handler's data pointer, * Use this macro to access the invoked command handler's data pointer,
* rather than accessing the variable directly. It may be moved. * rather than accessing the variable directly. It may be moved.
*/ */
#define CMD_DATA CMD_CURRENT->jim_handler_data #define CMD_DATA (CMD_CURRENT->jim_handler_data)
/** /**
* The type signature for command handling functions. They are * The type signature for command handling functions. They are
@ -171,8 +170,7 @@ struct command_invocation {
*/ */
typedef __COMMAND_HANDLER((*command_handler_t)); typedef __COMMAND_HANDLER((*command_handler_t));
struct command struct command {
{
const char *name; const char *name;
const char *help; const char *help;
const char *usage; const char *usage;
@ -219,7 +217,7 @@ struct command_registration {
void *jim_handler_data; void *jim_handler_data;
enum command_mode mode; enum command_mode mode;
const char *help; const char *help;
/// a string listing the options and arguments, required or optional /* / a string listing the options and arguments, required or optional */
const char *usage; const char *usage;
/** /**
@ -231,7 +229,7 @@ struct command_registration {
const struct command_registration *chain; const struct command_registration *chain;
}; };
/// Use this as the last entry in an array of command_registration records. /* / Use this as the last entry in an array of command_registration records. */
#define COMMAND_REGISTRATION_DONE { .name = NULL, .chain = NULL } #define COMMAND_REGISTRATION_DONE { .name = NULL, .chain = NULL }
/** /**
@ -249,7 +247,7 @@ struct command_registration {
* command parameters. * command parameters.
* @returns The new command, if successful; otherwise, NULL. * @returns The new command, if successful; otherwise, NULL.
*/ */
struct command* register_command(struct command_context *cmd_ctx, struct command *register_command(struct command_context *cmd_ctx,
struct command *parent, const struct command_registration *rec); struct command *parent, const struct command_registration *rec);
/** /**
@ -304,7 +302,7 @@ struct command *command_find_in_parent(struct command *parent,
*/ */
void command_set_handler_data(struct command *c, void *p); void command_set_handler_data(struct command *c, void *p);
void command_set_output_handler(struct command_context* context, void command_set_output_handler(struct command_context *context,
command_output_handler_t output_handler, void *priv); command_output_handler_t output_handler, void *priv);
@ -319,7 +317,7 @@ struct command_context *current_command_context(Jim_Interp *interp);
* the existing Jim interpreter, if any. If interp == NULL, then command_init * the existing Jim interpreter, if any. If interp == NULL, then command_init
* creates a command interpreter. * creates a command interpreter.
*/ */
struct command_context* command_init(const char *startup_tcl, Jim_Interp *interp); struct command_context *command_init(const char *startup_tcl, Jim_Interp *interp);
/** /**
* Creates a copy of an existing command context. This does not create * Creates a copy of an existing command context. This does not create
* a deep copy of the command list, so modifications in one context will * a deep copy of the command list, so modifications in one context will
@ -328,7 +326,7 @@ struct command_context* command_init(const char *startup_tcl, Jim_Interp *interp
* @param cmd_ctx The command_context that will be copied. * @param cmd_ctx The command_context that will be copied.
* @returns A new command_context with the same state as the original. * @returns A new command_context with the same state as the original.
*/ */
struct command_context* copy_command_context(struct command_context* cmd_ctx); struct command_context *copy_command_context(struct command_context *cmd_ctx);
/** /**
* Frees the resources associated with a command context. The commands * Frees the resources associated with a command context. The commands
* are not removed, so unregister_all_commands() must be called first. * are not removed, so unregister_all_commands() must be called first.
@ -337,12 +335,12 @@ struct command_context* copy_command_context(struct command_context* cmd_ctx);
void command_done(struct command_context *context); void command_done(struct command_context *context);
void command_print(struct command_context *context, const char *format, ...) void command_print(struct command_context *context, const char *format, ...)
__attribute__ ((format (PRINTF_ATTRIBUTE_FORMAT, 2, 3))); __attribute__ ((format (PRINTF_ATTRIBUTE_FORMAT, 2, 3)));
void command_print_sameline(struct command_context *context, const char *format, ...) void command_print_sameline(struct command_context *context, const char *format, ...)
__attribute__ ((format (PRINTF_ATTRIBUTE_FORMAT, 2, 3))); __attribute__ ((format (PRINTF_ATTRIBUTE_FORMAT, 2, 3)));
int command_run_line(struct command_context *context, char *line); int command_run_line(struct command_context *context, char *line);
int command_run_linef(struct command_context *context, const char *format, ...) int command_run_linef(struct command_context *context, const char *format, ...)
__attribute__ ((format (PRINTF_ATTRIBUTE_FORMAT, 2, 3))); __attribute__ ((format (PRINTF_ATTRIBUTE_FORMAT, 2, 3)));
void command_output_text(struct command_context *context, const char *data); void command_output_text(struct command_context *context, const char *data);
void process_jim_events(struct command_context *cmd_ctx); void process_jim_events(struct command_context *cmd_ctx);
@ -361,7 +359,7 @@ int parse_long(const char *str, long *ul);
int parse_llong(const char *str, long long *ul); int parse_llong(const char *str, long long *ul);
#define DECLARE_PARSE_WRAPPER(name, type) \ #define DECLARE_PARSE_WRAPPER(name, type) \
int parse##name(const char *str, type *ul) int parse ## name(const char *str, type * ul)
DECLARE_PARSE_WRAPPER(_uint, unsigned); DECLARE_PARSE_WRAPPER(_uint, unsigned);
DECLARE_PARSE_WRAPPER(_u32, uint32_t); DECLARE_PARSE_WRAPPER(_u32, uint32_t);
@ -386,7 +384,7 @@ DECLARE_PARSE_WRAPPER(_s8, int8_t);
*/ */
#define COMMAND_PARSE_NUMBER(type, in, out) \ #define COMMAND_PARSE_NUMBER(type, in, out) \
do { \ do { \
int retval_macro_tmp = parse_##type(in, &(out)); \ int retval_macro_tmp = parse_ ## type(in, &(out)); \
if (ERROR_OK != retval_macro_tmp) { \ if (ERROR_OK != retval_macro_tmp) { \
command_print(CMD_CTX, stringify(out) \ command_print(CMD_CTX, stringify(out) \
" option value ('%s') is not valid", in); \ " option value ('%s') is not valid", in); \
@ -417,14 +415,14 @@ DECLARE_PARSE_WRAPPER(_s8, int8_t);
int command_parse_bool_arg(const char *in, bool *out); int command_parse_bool_arg(const char *in, bool *out);
COMMAND_HELPER(handle_command_parse_bool, bool *out, const char *label); COMMAND_HELPER(handle_command_parse_bool, bool *out, const char *label);
/// parses an on/off command argument /* / parses an on/off command argument */
#define COMMAND_PARSE_ON_OFF(in, out) \ #define COMMAND_PARSE_ON_OFF(in, out) \
COMMAND_PARSE_BOOL(in, out, "on", "off") COMMAND_PARSE_BOOL(in, out, "on", "off")
/// parses an enable/disable command argument /* / parses an enable/disable command argument */
#define COMMAND_PARSE_ENABLE(in, out) \ #define COMMAND_PARSE_ENABLE(in, out) \
COMMAND_PARSE_BOOL(in, out, "enable", "disable") COMMAND_PARSE_BOOL(in, out, "enable", "disable")
void script_debug(Jim_Interp *interp, const char *cmd, void script_debug(Jim_Interp *interp, const char *cmd,
unsigned argc, Jim_Obj *const *argv); unsigned argc, Jim_Obj * const *argv);
#endif /* COMMAND_H */ #endif /* COMMAND_H */

View File

@ -27,17 +27,17 @@
#include "configuration.h" #include "configuration.h"
#include "log.h" #include "log.h"
static size_t num_config_files; static size_t num_config_files;
static char** config_file_names; static char **config_file_names;
static size_t num_script_dirs; static size_t num_script_dirs;
static char** script_search_dirs; static char **script_search_dirs;
void add_script_search_dir (const char *dir) void add_script_search_dir(const char *dir)
{ {
num_script_dirs++; num_script_dirs++;
script_search_dirs = (char **)realloc(script_search_dirs, (num_script_dirs + 1) * sizeof (char *)); script_search_dirs =
(char **)realloc(script_search_dirs, (num_script_dirs + 1) * sizeof(char *));
script_search_dirs[num_script_dirs-1] = strdup(dir); script_search_dirs[num_script_dirs-1] = strdup(dir);
script_search_dirs[num_script_dirs] = NULL; script_search_dirs[num_script_dirs] = NULL;
@ -45,10 +45,11 @@ void add_script_search_dir (const char *dir)
LOG_DEBUG("adding %s", dir); LOG_DEBUG("adding %s", dir);
} }
void add_config_command (const char *cfg) void add_config_command(const char *cfg)
{ {
num_config_files++; num_config_files++;
config_file_names = (char **)realloc(config_file_names, (num_config_files + 1) * sizeof (char *)); config_file_names =
(char **)realloc(config_file_names, (num_config_files + 1) * sizeof(char *));
config_file_names[num_config_files-1] = strdup(cfg); config_file_names[num_config_files-1] = strdup(cfg);
config_file_names[num_config_files] = NULL; config_file_names[num_config_files] = NULL;
@ -60,7 +61,7 @@ char *find_file(const char *file)
FILE *fp = NULL; FILE *fp = NULL;
char **search_dirs = script_search_dirs; char **search_dirs = script_search_dirs;
char *dir; char *dir;
char const *mode="r"; char const *mode = "r";
char *full_path; char *full_path;
/* Check absolute and relative to current working dir first. /* Check absolute and relative to current working dir first.
@ -68,8 +69,7 @@ char *find_file(const char *file)
full_path = alloc_printf("%s", file); full_path = alloc_printf("%s", file);
fp = fopen(full_path, mode); fp = fopen(full_path, mode);
while (!fp) while (!fp) {
{
free(full_path); free(full_path);
full_path = NULL; full_path = NULL;
dir = *search_dirs++; dir = *search_dirs++;
@ -81,8 +81,7 @@ char *find_file(const char *file)
fp = fopen(full_path, mode); fp = fopen(full_path, mode);
} }
if (fp) if (fp) {
{
fclose(fp); fclose(fp);
LOG_DEBUG("found %s", full_path); LOG_DEBUG("found %s", full_path);
return full_path; return full_path;
@ -95,11 +94,9 @@ char *find_file(const char *file)
FILE *open_file_from_path(const char *file, const char *mode) FILE *open_file_from_path(const char *file, const char *mode)
{ {
if (mode[0]!='r') if (mode[0] != 'r')
{
return fopen(file, mode); return fopen(file, mode);
} else else {
{
char *full_path = find_file(file); char *full_path = find_file(file);
if (full_path == NULL) if (full_path == NULL)
return NULL; return NULL;
@ -122,8 +119,7 @@ int parse_config_file(struct command_context *cmd_ctx)
cfg = config_file_names; cfg = config_file_names;
while (*cfg) while (*cfg) {
{
retval = command_run_line(cmd_ctx, *cfg); retval = command_run_line(cmd_ctx, *cfg);
if (retval != ERROR_OK) if (retval != ERROR_OK)
return retval; return retval;

View File

@ -20,6 +20,7 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#ifndef CONFIGURATION_H #ifndef CONFIGURATION_H
#define CONFIGURATION_H #define CONFIGURATION_H

View File

@ -23,6 +23,7 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
@ -44,8 +45,7 @@ static inline int fileio_open_local(struct fileio_internal *fileio)
{ {
char file_access[4]; char file_access[4];
switch (fileio->access) switch (fileio->access) {
{
case FILEIO_READ: case FILEIO_READ:
strcpy(file_access, "r"); strcpy(file_access, "r");
break; break;
@ -70,18 +70,15 @@ static inline int fileio_open_local(struct fileio_internal *fileio)
#ifndef _WIN32 #ifndef _WIN32
if (fileio->type == FILEIO_BINARY) if (fileio->type == FILEIO_BINARY)
#endif #endif
{
strcat(file_access, "b"); strcat(file_access, "b");
}
if (!(fileio->file = open_file_from_path (fileio->url, file_access))) fileio->file = open_file_from_path(fileio->url, file_access);
{ if (!fileio->file) {
LOG_ERROR("couldn't open %s", fileio->url); LOG_ERROR("couldn't open %s", fileio->url);
return ERROR_FILEIO_OPERATION_FAILED; return ERROR_FILEIO_OPERATION_FAILED;
} }
if ((fileio->access != FILEIO_WRITE) || (fileio->access == FILEIO_READWRITE)) if ((fileio->access != FILEIO_WRITE) || (fileio->access == FILEIO_READWRITE)) {
{
/* NB! Here we use fseek() instead of stat(), since stat is a /* NB! Here we use fseek() instead of stat(), since stat is a
* more advanced operation that might not apply to e.g. a disk path * more advanced operation that might not apply to e.g. a disk path
* that refers to e.g. a tftp client */ * that refers to e.g. a tftp client */
@ -93,21 +90,20 @@ static inline int fileio_open_local(struct fileio_internal *fileio)
result2 = fseek(fileio->file, 0, SEEK_SET); result2 = fseek(fileio->file, 0, SEEK_SET);
if ((fileio->size < 0)||(result < 0)||(result2 < 0)) if ((fileio->size < 0) || (result < 0) || (result2 < 0)) {
{
fileio_close_local(fileio); fileio_close_local(fileio);
return ERROR_FILEIO_OPERATION_FAILED; return ERROR_FILEIO_OPERATION_FAILED;
} }
} } else
else
{
fileio->size = 0x0; fileio->size = 0x0;
}
return ERROR_OK; return ERROR_OK;
} }
int fileio_open(struct fileio *fileio_p, const char *url, enum fileio_access access_type, enum fileio_type type) int fileio_open(struct fileio *fileio_p,
const char *url,
enum fileio_access access_type,
enum fileio_type type)
{ {
int retval = ERROR_OK; int retval = ERROR_OK;
@ -125,17 +121,12 @@ int fileio_open(struct fileio *fileio_p, const char *url, enum fileio_access acc
static inline int fileio_close_local(struct fileio_internal *fileio) static inline int fileio_close_local(struct fileio_internal *fileio)
{ {
int retval; int retval = fclose(fileio->file);
if ((retval = fclose(fileio->file)) != 0) if (retval != 0) {
{
if (retval == EBADF) if (retval == EBADF)
{
LOG_ERROR("BUG: fileio_local->file not a valid file descriptor"); LOG_ERROR("BUG: fileio_local->file not a valid file descriptor");
}
else else
{
LOG_ERROR("couldn't close %s: %s", fileio->url, strerror(errno)); LOG_ERROR("couldn't close %s: %s", fileio->url, strerror(errno));
}
return ERROR_FILEIO_OPERATION_FAILED; return ERROR_FILEIO_OPERATION_FAILED;
} }
@ -150,7 +141,7 @@ int fileio_close(struct fileio *fileio_p)
retval = fileio_close_local(fileio); retval = fileio_close_local(fileio);
free((void*)fileio->url); free((void *)fileio->url);
fileio->url = NULL; fileio->url = NULL;
free(fileio); free(fileio);
@ -163,8 +154,8 @@ int fileio_seek(struct fileio *fileio_p, size_t position)
{ {
int retval; int retval;
struct fileio_internal *fileio = fileio_p->fp; struct fileio_internal *fileio = fileio_p->fp;
if ((retval = fseek(fileio->file, position, SEEK_SET)) != 0) retval = fseek(fileio->file, position, SEEK_SET);
{ if (retval != 0) {
LOG_ERROR("couldn't seek file %s: %s", fileio->url, strerror(errno)); LOG_ERROR("couldn't seek file %s: %s", fileio->url, strerror(errno));
return ERROR_FILEIO_OPERATION_FAILED; return ERROR_FILEIO_OPERATION_FAILED;
} }

View File

@ -23,6 +23,7 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#ifndef FILEIO_H #ifndef FILEIO_H
#define FILEIO_H #define FILEIO_H
@ -30,14 +31,12 @@
#define FILEIO_MAX_ERROR_STRING (128) #define FILEIO_MAX_ERROR_STRING (128)
enum fileio_type enum fileio_type {
{
FILEIO_TEXT, FILEIO_TEXT,
FILEIO_BINARY, FILEIO_BINARY,
}; };
enum fileio_access enum fileio_access {
{
FILEIO_NONE, /* open without any access (invalid mode) */ FILEIO_NONE, /* open without any access (invalid mode) */
FILEIO_READ, /* open for reading, position at beginning */ FILEIO_READ, /* open for reading, position at beginning */
FILEIO_WRITE, /* open for writing, position at beginning */ FILEIO_WRITE, /* open for writing, position at beginning */
@ -46,8 +45,7 @@ enum fileio_access
FILEIO_APPENDREAD, /* open for writing, position at end, allow reading */ FILEIO_APPENDREAD, /* open for writing, position at end, allow reading */
}; };
struct fileio struct fileio {
{
/* The structure is opaque */ /* The structure is opaque */
struct fileio_internal *fp; struct fileio_internal *fp;
}; };

View File

@ -53,52 +53,45 @@
#endif #endif
#endif #endif
/* loads a file and returns a pointer to it in memory. The file contains /* loads a file and returns a pointer to it in memory. The file contains
* a 0 byte(sentinel) after len bytes - the length of the file. */ * a 0 byte(sentinel) after len bytes - the length of the file. */
int loadFile(const char *fileName, void **data, size_t *len) int loadFile(const char *fileName, void **data, size_t *len)
{ {
// ensure returned length is always sane /* ensure returned length is always sane */
*len = 0; *len = 0;
FILE * pFile; FILE *pFile;
pFile = fopen(fileName,"rb"); pFile = fopen(fileName, "rb");
if (pFile == NULL) if (pFile == NULL) {
{
LOG_ERROR("Can't open %s", fileName); LOG_ERROR("Can't open %s", fileName);
return ERROR_FAIL; return ERROR_FAIL;
} }
if (fseek(pFile, 0, SEEK_END) != 0) if (fseek(pFile, 0, SEEK_END) != 0) {
{
LOG_ERROR("Can't open %s", fileName); LOG_ERROR("Can't open %s", fileName);
fclose(pFile); fclose(pFile);
return ERROR_FAIL; return ERROR_FAIL;
} }
long fsize = ftell(pFile); long fsize = ftell(pFile);
if (fsize == -1) if (fsize == -1) {
{
LOG_ERROR("Can't open %s", fileName); LOG_ERROR("Can't open %s", fileName);
fclose(pFile); fclose(pFile);
return ERROR_FAIL; return ERROR_FAIL;
} }
*len = fsize; *len = fsize;
if (fseek(pFile, 0, SEEK_SET) != 0) if (fseek(pFile, 0, SEEK_SET) != 0) {
{
LOG_ERROR("Can't open %s", fileName); LOG_ERROR("Can't open %s", fileName);
fclose(pFile); fclose(pFile);
return ERROR_FAIL; return ERROR_FAIL;
} }
*data = malloc(*len + 1); *data = malloc(*len + 1);
if (*data == NULL) if (*data == NULL) {
{
LOG_ERROR("Can't open %s", fileName); LOG_ERROR("Can't open %s", fileName);
fclose(pFile); fclose(pFile);
return ERROR_FAIL; return ERROR_FAIL;
} }
if (fread(*data, 1, *len, pFile)!=*len) if (fread(*data, 1, *len, pFile) != *len) {
{
fclose(pFile); fclose(pFile);
free(*data); free(*data);
LOG_ERROR("Can't open %s", fileName); LOG_ERROR("Can't open %s", fileName);
@ -106,7 +99,7 @@ int loadFile(const char *fileName, void **data, size_t *len)
} }
fclose(pFile); fclose(pFile);
// 0-byte after buffer (not included in *len) serves as a sentinel /* 0-byte after buffer (not included in *len) serves as a sentinel */
char *buf = (char *)*data; char *buf = (char *)*data;
buf[*len] = 0; buf[*len] = 0;
@ -116,24 +109,19 @@ int loadFile(const char *fileName, void **data, size_t *len)
COMMAND_HANDLER(handle_cat_command) COMMAND_HANDLER(handle_cat_command)
{ {
if (CMD_ARGC != 1) if (CMD_ARGC != 1)
{
return ERROR_COMMAND_SYNTAX_ERROR; return ERROR_COMMAND_SYNTAX_ERROR;
}
// NOTE!!! we only have line printing capability so we print the entire file as a single line. /* NOTE!!! we only have line printing capability so we print the entire file as a single
* line. */
void *data; void *data;
size_t len; size_t len;
int retval = loadFile(CMD_ARGV[0], &data, &len); int retval = loadFile(CMD_ARGV[0], &data, &len);
if (retval == ERROR_OK) if (retval == ERROR_OK) {
{
command_print(CMD_CTX, "%s", (char *)data); command_print(CMD_CTX, "%s", (char *)data);
free(data); free(data);
} } else
else
{
command_print(CMD_CTX, "%s not found", CMD_ARGV[0]); command_print(CMD_CTX, "%s not found", CMD_ARGV[0]);
}
return ERROR_OK; return ERROR_OK;
} }
@ -141,9 +129,7 @@ COMMAND_HANDLER(handle_cat_command)
COMMAND_HANDLER(handle_trunc_command) COMMAND_HANDLER(handle_trunc_command)
{ {
if (CMD_ARGC != 1) if (CMD_ARGC != 1)
{
return ERROR_COMMAND_SYNTAX_ERROR; return ERROR_COMMAND_SYNTAX_ERROR;
}
FILE *config_file = NULL; FILE *config_file = NULL;
config_file = fopen(CMD_ARGV[0], "w"); config_file = fopen(CMD_ARGV[0], "w");
@ -155,20 +141,16 @@ COMMAND_HANDLER(handle_trunc_command)
COMMAND_HANDLER(handle_meminfo_command) COMMAND_HANDLER(handle_meminfo_command)
{ {
static int prev = 0; static int prev;
struct mallinfo info; struct mallinfo info;
if (CMD_ARGC != 0) if (CMD_ARGC != 0)
{
return ERROR_COMMAND_SYNTAX_ERROR; return ERROR_COMMAND_SYNTAX_ERROR;
}
info = mallinfo(); info = mallinfo();
if (prev > 0) if (prev > 0)
{
command_print(CMD_CTX, "Diff: %d", prev - info.fordblks); command_print(CMD_CTX, "Diff: %d", prev - info.fordblks);
}
prev = info.fordblks; prev = info.fordblks;
command_print(CMD_CTX, "Available ram: %d", info.fordblks); command_print(CMD_CTX, "Available ram: %d", info.fordblks);
@ -180,26 +162,21 @@ COMMAND_HANDLER(handle_meminfo_command)
COMMAND_HANDLER(handle_append_command) COMMAND_HANDLER(handle_append_command)
{ {
if (CMD_ARGC < 1) if (CMD_ARGC < 1)
{
return ERROR_COMMAND_SYNTAX_ERROR; return ERROR_COMMAND_SYNTAX_ERROR;
}
int retval = ERROR_FAIL; int retval = ERROR_FAIL;
FILE *config_file = NULL; FILE *config_file = NULL;
config_file = fopen(CMD_ARGV[0], "a"); config_file = fopen(CMD_ARGV[0], "a");
if (config_file != NULL) if (config_file != NULL) {
{
fseek(config_file, 0, SEEK_END); fseek(config_file, 0, SEEK_END);
unsigned i; unsigned i;
for (i = 1; i < CMD_ARGC; i++) for (i = 1; i < CMD_ARGC; i++) {
{
if (fwrite(CMD_ARGV[i], 1, strlen(CMD_ARGV[i]), if (fwrite(CMD_ARGV[i], 1, strlen(CMD_ARGV[i]),
config_file) != strlen(CMD_ARGV[i])) config_file) != strlen(CMD_ARGV[i]))
break; break;
if (i != CMD_ARGC - 1) if (i != CMD_ARGC - 1) {
{
if (fwrite(" ", 1, 1, config_file) != 1) if (fwrite(" ", 1, 1, config_file) != 1)
break; break;
} }
@ -213,16 +190,13 @@ COMMAND_HANDLER(handle_append_command)
return retval; return retval;
} }
COMMAND_HANDLER(handle_cp_command) COMMAND_HANDLER(handle_cp_command)
{ {
if (CMD_ARGC != 2) if (CMD_ARGC != 2)
{
return ERROR_COMMAND_SYNTAX_ERROR; return ERROR_COMMAND_SYNTAX_ERROR;
}
// NOTE!!! we only have line printing capability so we print the entire file as a single line. /* NOTE!!! we only have line printing capability so we print the entire file as a single
* line. */
void *data; void *data;
size_t len; size_t len;
@ -235,22 +209,17 @@ COMMAND_HANDLER(handle_cp_command)
retval = ERROR_COMMAND_SYNTAX_ERROR; retval = ERROR_COMMAND_SYNTAX_ERROR;
size_t pos = 0; size_t pos = 0;
for (;;) for (;; ) {
{
size_t chunk = len - pos; size_t chunk = len - pos;
static const size_t maxChunk = 512 * 1024; // ~1/sec static const size_t maxChunk = 512 * 1024; /* ~1/sec */
if (chunk > maxChunk) if (chunk > maxChunk)
{
chunk = maxChunk; chunk = maxChunk;
}
if ((retval == ERROR_OK) && (fwrite(((char *)data) + pos, 1, chunk, f) != chunk)) if ((retval == ERROR_OK) && (fwrite(((char *)data) + pos, 1, chunk, f) != chunk))
retval = ERROR_COMMAND_SYNTAX_ERROR; retval = ERROR_COMMAND_SYNTAX_ERROR;
if (retval != ERROR_OK) if (retval != ERROR_OK)
{
break; break;
}
command_print(CMD_CTX, "%zu", len - pos); command_print(CMD_CTX, "%zu", len - pos);
@ -261,12 +230,9 @@ COMMAND_HANDLER(handle_cp_command)
} }
if (retval == ERROR_OK) if (retval == ERROR_OK)
{
command_print(CMD_CTX, "Copied %s to %s", CMD_ARGV[0], CMD_ARGV[1]); command_print(CMD_CTX, "Copied %s to %s", CMD_ARGV[0], CMD_ARGV[1]);
} else else
{
command_print(CMD_CTX, "copy failed"); command_print(CMD_CTX, "copy failed");
}
if (data != NULL) if (data != NULL)
free(data); free(data);
@ -279,10 +245,7 @@ COMMAND_HANDLER(handle_cp_command)
return retval; return retval;
} }
#define SHOW_RESULT(a, b) LOG_ERROR(# a " failed %d\n", (int)b)
#define SHOW_RESULT(a, b) LOG_ERROR(#a " failed %d\n", (int)b)
#define IOSIZE 512 #define IOSIZE 512
void copyfile(char *name2, char *name1) void copyfile(char *name2, char *name1)
@ -301,29 +264,31 @@ void copyfile(char *name2, char *name1)
if (fd2 < 0) if (fd2 < 0)
SHOW_RESULT(open, fd2); SHOW_RESULT(open, fd2);
for (;;) for (;; ) {
{
done = read(fd2, buf, IOSIZE); done = read(fd2, buf, IOSIZE);
if (done < 0) if (done < 0) {
{
SHOW_RESULT(read, done); SHOW_RESULT(read, done);
break; break;
} }
if (done == 0) break; if (done == 0)
break;
wrote = write(fd1, buf, done); wrote = write(fd1, buf, done);
if (wrote != done) SHOW_RESULT(write, wrote); if (wrote != done)
SHOW_RESULT(write, wrote);
if (wrote != done) break; if (wrote != done)
break;
} }
err = close(fd1); err = close(fd1);
if (err < 0) SHOW_RESULT(close, err); if (err < 0)
SHOW_RESULT(close, err);
err = close(fd2); err = close(fd2);
if (err < 0) SHOW_RESULT(close, err); if (err < 0)
SHOW_RESULT(close, err);
} }
/* utility fn to copy a directory */ /* utility fn to copy a directory */
@ -334,18 +299,15 @@ void copydir(char *name, char *destdir)
dirp = opendir(destdir); dirp = opendir(destdir);
if (dirp == NULL) if (dirp == NULL)
{
mkdir(destdir, 0777); mkdir(destdir, 0777);
} else else
{
err = closedir(dirp); err = closedir(dirp);
}
dirp = opendir(name); dirp = opendir(name);
if (dirp == NULL) SHOW_RESULT(opendir, -1); if (dirp == NULL)
SHOW_RESULT(opendir, -1);
for (;;) for (;; ) {
{
struct dirent *entry = readdir(dirp); struct dirent *entry = readdir(dirp);
if (entry == NULL) if (entry == NULL)
@ -363,8 +325,7 @@ void copydir(char *name, char *destdir)
strcat(fullPath, "/"); strcat(fullPath, "/");
strncat(fullPath, entry->d_name, PATH_MAX - strlen(fullPath)); strncat(fullPath, entry->d_name, PATH_MAX - strlen(fullPath));
if (stat(fullPath, &buf) == -1) if (stat(fullPath, &buf) == -1) {
{
LOG_ERROR("unable to read status from %s", fullPath); LOG_ERROR("unable to read status from %s", fullPath);
break; break;
} }
@ -373,7 +334,7 @@ void copydir(char *name, char *destdir)
if (isDir) if (isDir)
continue; continue;
// diag_printf("<INFO>: entry %14s",entry->d_name); /* diag_printf("<INFO>: entry %14s",entry->d_name); */
char fullname[PATH_MAX]; char fullname[PATH_MAX];
char fullname2[PATH_MAX]; char fullname2[PATH_MAX];
@ -384,19 +345,17 @@ void copydir(char *name, char *destdir)
strcpy(fullname2, destdir); strcpy(fullname2, destdir);
strcat(fullname2, "/"); strcat(fullname2, "/");
strcat(fullname2, entry->d_name); strcat(fullname2, entry->d_name);
// diag_printf("from %s to %s\n", fullname, fullname2); /* diag_printf("from %s to %s\n", fullname, fullname2); */
copyfile(fullname, fullname2); copyfile(fullname, fullname2);
// diag_printf("\n"); /* diag_printf("\n"); */
} }
err = closedir(dirp); err = closedir(dirp);
if (err < 0) SHOW_RESULT(stat, err); if (err < 0)
SHOW_RESULT(stat, err);
} }
COMMAND_HANDLER(handle_rm_command) COMMAND_HANDLER(handle_rm_command)
{ {
if (CMD_ARGC != 1) if (CMD_ARGC != 1)
@ -411,39 +370,34 @@ COMMAND_HANDLER(handle_rm_command)
return del ? ERROR_OK : ERROR_FAIL; return del ? ERROR_OK : ERROR_FAIL;
} }
static int ioutil_Jim_Command_ls(Jim_Interp *interp,
static int
ioutil_Jim_Command_ls(Jim_Interp *interp,
int argc, int argc,
Jim_Obj * const *argv) Jim_Obj * const *argv)
{ {
if (argc != 2) if (argc != 2) {
{
Jim_WrongNumArgs(interp, 1, argv, "ls ?dir?"); Jim_WrongNumArgs(interp, 1, argv, "ls ?dir?");
return JIM_ERR; return JIM_ERR;
} }
char *name = (char*) Jim_GetString(argv[1], NULL); char *name = (char *) Jim_GetString(argv[1], NULL);
DIR *dirp = NULL; DIR *dirp = NULL;
dirp = opendir(name); dirp = opendir(name);
if (dirp == NULL) if (dirp == NULL)
{
return JIM_ERR; return JIM_ERR;
}
Jim_Obj *objPtr = Jim_NewListObj(interp, NULL, 0); Jim_Obj *objPtr = Jim_NewListObj(interp, NULL, 0);
for (;;) for (;; ) {
{
struct dirent *entry = NULL; struct dirent *entry = NULL;
entry = readdir(dirp); entry = readdir(dirp);
if (entry == NULL) if (entry == NULL)
break; break;
if ((strcmp(".", entry->d_name) == 0)||(strcmp("..", entry->d_name) == 0)) if ((strcmp(".", entry->d_name) == 0) || (strcmp("..", entry->d_name) == 0))
continue; continue;
Jim_ListAppendElement(interp, objPtr, Jim_NewStringObj(interp, entry->d_name, strlen(entry->d_name))); Jim_ListAppendElement(interp, objPtr,
Jim_NewStringObj(interp, entry->d_name, strlen(entry->d_name)));
} }
closedir(dirp); closedir(dirp);
@ -452,13 +406,11 @@ ioutil_Jim_Command_ls(Jim_Interp *interp,
return JIM_OK; return JIM_OK;
} }
static int static int ioutil_Jim_Command_peek(Jim_Interp *interp,
ioutil_Jim_Command_peek(Jim_Interp *interp,
int argc, int argc,
Jim_Obj * const *argv) Jim_Obj *const *argv)
{ {
if (argc != 2) if (argc != 2) {
{
Jim_WrongNumArgs(interp, 1, argv, "peek ?address?"); Jim_WrongNumArgs(interp, 1, argv, "peek ?address?");
return JIM_ERR; return JIM_ERR;
} }
@ -474,13 +426,11 @@ ioutil_Jim_Command_peek(Jim_Interp *interp,
return JIM_OK; return JIM_OK;
} }
static int static int ioutil_Jim_Command_poke(Jim_Interp *interp,
ioutil_Jim_Command_poke(Jim_Interp *interp,
int argc, int argc,
Jim_Obj * const *argv) Jim_Obj *const *argv)
{ {
if (argc != 3) if (argc != 3) {
{
Jim_WrongNumArgs(interp, 1, argv, "poke ?address? ?value?"); Jim_WrongNumArgs(interp, 1, argv, "poke ?address? ?value?");
return JIM_ERR; return JIM_ERR;
} }
@ -497,10 +447,9 @@ ioutil_Jim_Command_poke(Jim_Interp *interp,
return JIM_OK; return JIM_OK;
} }
/* not so pretty code to fish out ip number*/ /* not so pretty code to fish out ip number*/
static int ioutil_Jim_Command_ip(Jim_Interp *interp, int argc, static int ioutil_Jim_Command_ip(Jim_Interp *interp, int argc,
Jim_Obj * const *argv) Jim_Obj *const *argv)
{ {
#if !defined(__CYGWIN__) #if !defined(__CYGWIN__)
Jim_Obj *tclOutput = Jim_NewStringObj(interp, "", 0); Jim_Obj *tclOutput = Jim_NewStringObj(interp, "", 0);
@ -508,12 +457,9 @@ static int ioutil_Jim_Command_ip(Jim_Interp *interp, int argc,
struct ifaddrs *ifa = NULL, *ifp = NULL; struct ifaddrs *ifa = NULL, *ifp = NULL;
if (getifaddrs(&ifp) < 0) if (getifaddrs(&ifp) < 0)
{
return JIM_ERR; return JIM_ERR;
}
for (ifa = ifp; ifa; ifa = ifa->ifa_next) for (ifa = ifp; ifa; ifa = ifa->ifa_next) {
{
char ip[200]; char ip[200];
socklen_t salen; socklen_t salen;
@ -526,9 +472,7 @@ static int ioutil_Jim_Command_ip(Jim_Interp *interp, int argc,
if (getnameinfo(ifa->ifa_addr, salen, ip, sizeof(ip), NULL, 0, if (getnameinfo(ifa->ifa_addr, salen, ip, sizeof(ip), NULL, 0,
NI_NUMERICHOST) < 0) NI_NUMERICHOST) < 0)
{
continue; continue;
}
Jim_AppendString(interp, tclOutput, ip, strlen(ip)); Jim_AppendString(interp, tclOutput, ip, strlen(ip));
break; break;
@ -547,10 +491,8 @@ static int ioutil_Jim_Command_ip(Jim_Interp *interp, int argc,
/* not so pretty code to fish out eth0 mac address */ /* not so pretty code to fish out eth0 mac address */
static int ioutil_Jim_Command_mac(Jim_Interp *interp, int argc, static int ioutil_Jim_Command_mac(Jim_Interp *interp, int argc,
Jim_Obj * const *argv) Jim_Obj *const *argv)
{ {
struct ifreq *ifr, *ifend; struct ifreq *ifr, *ifend;
struct ifreq ifreq; struct ifreq ifreq;
struct ifconf ifc; struct ifconf ifc;
@ -559,35 +501,29 @@ static int ioutil_Jim_Command_mac(Jim_Interp *interp, int argc,
SockFD = socket(AF_INET, SOCK_DGRAM, 0); SockFD = socket(AF_INET, SOCK_DGRAM, 0);
if (SockFD < 0) if (SockFD < 0)
{
return JIM_ERR; return JIM_ERR;
}
ifc.ifc_len = sizeof(ifs); ifc.ifc_len = sizeof(ifs);
ifc.ifc_req = ifs; ifc.ifc_req = ifs;
if (ioctl(SockFD, SIOCGIFCONF, &ifc) < 0) if (ioctl(SockFD, SIOCGIFCONF, &ifc) < 0) {
{
close(SockFD); close(SockFD);
return JIM_ERR; return JIM_ERR;
} }
ifend = ifs + (ifc.ifc_len / sizeof(struct ifreq)); ifend = ifs + (ifc.ifc_len / sizeof(struct ifreq));
for (ifr = ifc.ifc_req; ifr < ifend; ifr++) for (ifr = ifc.ifc_req; ifr < ifend; ifr++) {
{ /* if (ifr->ifr_addr.sa_family == AF_INET) */
//if (ifr->ifr_addr.sa_family == AF_INET)
{ {
if (strcmp("eth0", ifr->ifr_name) != 0) if (strcmp("eth0", ifr->ifr_name) != 0)
continue; continue;
strncpy(ifreq.ifr_name, ifr->ifr_name, sizeof(ifreq.ifr_name)); strncpy(ifreq.ifr_name, ifr->ifr_name, sizeof(ifreq.ifr_name));
if (ioctl(SockFD, SIOCGIFHWADDR, &ifreq) < 0) if (ioctl(SockFD, SIOCGIFHWADDR, &ifreq) < 0) {
{
close(SockFD); close(SockFD);
return JIM_ERR; return JIM_ERR;
} }
close(SockFD); close(SockFD);
Jim_Obj *tclOutput = Jim_NewStringObj(interp, "", 0); Jim_Obj *tclOutput = Jim_NewStringObj(interp, "", 0);
char buffer[256]; char buffer[256];
@ -618,14 +554,14 @@ static const struct command_registration ioutil_command_handlers[] = {
.handler = handle_cat_command, .handler = handle_cat_command,
.mode = COMMAND_ANY, .mode = COMMAND_ANY,
.help = "display text file content", .help = "display text file content",
.usage= "file_name", .usage = "file_name",
}, },
{ {
.name = "trunc", .name = "trunc",
.handler = handle_trunc_command, .handler = handle_trunc_command,
.mode = COMMAND_ANY, .mode = COMMAND_ANY,
.help = "truncate a file to zero length", .help = "truncate a file to zero length",
.usage= "file_name", .usage = "file_name",
}, },
{ {
.name = "cp", .name = "cp",
@ -660,7 +596,7 @@ static const struct command_registration ioutil_command_handlers[] = {
* server-internal addresses. * server-internal addresses.
*/ */
// jim handlers /* jim handlers */
{ {
.name = "peek", .name = "peek",
.mode = COMMAND_ANY, .mode = COMMAND_ANY,

View File

@ -24,4 +24,4 @@ struct command_context;
int ioutil_init(struct command_context *cmd_ctx); int ioutil_init(struct command_context *cmd_ctx);
#endif // HELPER_IOUTILS_H #endif /* HELPER_IOUTILS_H */

View File

@ -45,147 +45,128 @@
#include <jim-nvp.h> #include <jim-nvp.h>
int Jim_GetNvp(Jim_Interp *interp, int Jim_GetNvp(Jim_Interp *interp,
Jim_Obj *objPtr, const Jim_Nvp * nvp_table, const Jim_Nvp ** result) Jim_Obj *objPtr, const Jim_Nvp *nvp_table, const Jim_Nvp **result)
{ {
Jim_Nvp *n; Jim_Nvp *n;
int e; int e;
e = Jim_Nvp_name2value_obj(interp, nvp_table, objPtr, &n); e = Jim_Nvp_name2value_obj(interp, nvp_table, objPtr, &n);
if (e == JIM_ERR) { if (e == JIM_ERR)
return e; return e;
}
/* Success? found? */ /* Success? found? */
if (n->name) { if (n->name) {
/* remove const */ /* remove const */
*result = (Jim_Nvp *) n; *result = (Jim_Nvp *) n;
return JIM_OK; return JIM_OK;
} } else
else {
return JIM_ERR; return JIM_ERR;
}
} }
Jim_Nvp *Jim_Nvp_name2value_simple(const Jim_Nvp * p, const char *name) Jim_Nvp *Jim_Nvp_name2value_simple(const Jim_Nvp *p, const char *name)
{ {
while (p->name) { while (p->name) {
if (0 == strcmp(name, p->name)) { if (0 == strcmp(name, p->name))
break; break;
}
p++; p++;
} }
return ((Jim_Nvp *) (p)); return (Jim_Nvp *) (p);
} }
Jim_Nvp *Jim_Nvp_name2value_nocase_simple(const Jim_Nvp * p, const char *name) Jim_Nvp *Jim_Nvp_name2value_nocase_simple(const Jim_Nvp *p, const char *name)
{ {
while (p->name) { while (p->name) {
if (0 == strcasecmp(name, p->name)) { if (0 == strcasecmp(name, p->name))
break; break;
}
p++; p++;
} }
return ((Jim_Nvp *) (p)); return (Jim_Nvp *) (p);
} }
int Jim_Nvp_name2value_obj(Jim_Interp *interp, const Jim_Nvp * p, Jim_Obj *o, Jim_Nvp ** result) int Jim_Nvp_name2value_obj(Jim_Interp *interp, const Jim_Nvp *p, Jim_Obj *o, Jim_Nvp **result)
{ {
return Jim_Nvp_name2value(interp, p, Jim_String(o), result); return Jim_Nvp_name2value(interp, p, Jim_String(o), result);
} }
int Jim_Nvp_name2value(Jim_Interp *interp, const Jim_Nvp *_p, const char *name, Jim_Nvp **result)
int Jim_Nvp_name2value(Jim_Interp *interp, const Jim_Nvp * _p, const char *name, Jim_Nvp ** result)
{ {
const Jim_Nvp *p; const Jim_Nvp *p;
p = Jim_Nvp_name2value_simple(_p, name); p = Jim_Nvp_name2value_simple(_p, name);
/* result */ /* result */
if (result) { if (result)
*result = (Jim_Nvp *) (p); *result = (Jim_Nvp *) (p);
}
/* found? */ /* found? */
if (p->name) { if (p->name)
return JIM_OK; return JIM_OK;
} else
else {
return JIM_ERR; return JIM_ERR;
}
} }
int int Jim_Nvp_name2value_obj_nocase(Jim_Interp *interp,
Jim_Nvp_name2value_obj_nocase(Jim_Interp *interp, const Jim_Nvp * p, Jim_Obj *o, Jim_Nvp ** puthere) const Jim_Nvp *p,
Jim_Obj *o,
Jim_Nvp **puthere)
{ {
return Jim_Nvp_name2value_nocase(interp, p, Jim_String(o), puthere); return Jim_Nvp_name2value_nocase(interp, p, Jim_String(o), puthere);
} }
int int Jim_Nvp_name2value_nocase(Jim_Interp *interp, const Jim_Nvp *_p, const char *name,
Jim_Nvp_name2value_nocase(Jim_Interp *interp, const Jim_Nvp * _p, const char *name, Jim_Nvp **puthere)
Jim_Nvp ** puthere)
{ {
const Jim_Nvp *p; const Jim_Nvp *p;
p = Jim_Nvp_name2value_nocase_simple(_p, name); p = Jim_Nvp_name2value_nocase_simple(_p, name);
if (puthere) { if (puthere)
*puthere = (Jim_Nvp *) (p); *puthere = (Jim_Nvp *) (p);
}
/* found */ /* found */
if (p->name) { if (p->name)
return JIM_OK; return JIM_OK;
} else
else {
return JIM_ERR; return JIM_ERR;
}
} }
int Jim_Nvp_value2name_obj(Jim_Interp *interp, const Jim_Nvp *p, Jim_Obj *o, Jim_Nvp **result)
int Jim_Nvp_value2name_obj(Jim_Interp *interp, const Jim_Nvp * p, Jim_Obj *o, Jim_Nvp ** result)
{ {
int e;; int e;
jim_wide w; jim_wide w;
e = Jim_GetWide(interp, o, &w); e = Jim_GetWide(interp, o, &w);
if (e != JIM_OK) { if (e != JIM_OK)
return e; return e;
}
return Jim_Nvp_value2name(interp, p, w, result); return Jim_Nvp_value2name(interp, p, w, result);
} }
Jim_Nvp *Jim_Nvp_value2name_simple(const Jim_Nvp * p, int value) Jim_Nvp *Jim_Nvp_value2name_simple(const Jim_Nvp *p, int value)
{ {
while (p->name) { while (p->name) {
if (value == p->value) { if (value == p->value)
break; break;
}
p++; p++;
} }
return ((Jim_Nvp *) (p)); return (Jim_Nvp *) (p);
} }
int Jim_Nvp_value2name(Jim_Interp *interp, const Jim_Nvp *_p, int value, Jim_Nvp **result)
int Jim_Nvp_value2name(Jim_Interp *interp, const Jim_Nvp * _p, int value, Jim_Nvp ** result)
{ {
const Jim_Nvp *p; const Jim_Nvp *p;
p = Jim_Nvp_value2name_simple(_p, value); p = Jim_Nvp_value2name_simple(_p, value);
if (result) { if (result)
*result = (Jim_Nvp *) (p); *result = (Jim_Nvp *) (p);
}
if (p->name) { if (p->name)
return JIM_OK; return JIM_OK;
} else
else {
return JIM_ERR; return JIM_ERR;
}
} }
int Jim_GetOpt_Setup(Jim_GetOptInfo *p, Jim_Interp *interp, int argc, Jim_Obj *const *argv)
int Jim_GetOpt_Setup(Jim_GetOptInfo * p, Jim_Interp *interp, int argc, Jim_Obj *const *argv)
{ {
memset(p, 0, sizeof(*p)); memset(p, 0, sizeof(*p));
p->interp = interp; p->interp = interp;
@ -195,47 +176,41 @@ int Jim_GetOpt_Setup(Jim_GetOptInfo * p, Jim_Interp *interp, int argc, Jim_Obj *
return JIM_OK; return JIM_OK;
} }
void Jim_GetOpt_Debug(Jim_GetOptInfo * p) void Jim_GetOpt_Debug(Jim_GetOptInfo *p)
{ {
int x; int x;
fprintf(stderr, "---args---\n"); fprintf(stderr, "---args---\n");
for (x = 0; x < p->argc; x++) { for (x = 0; x < p->argc; x++)
fprintf(stderr, "%2d) %s\n", x, Jim_String(p->argv[x])); fprintf(stderr, "%2d) %s\n", x, Jim_String(p->argv[x]));
}
fprintf(stderr, "-------\n"); fprintf(stderr, "-------\n");
} }
int Jim_GetOpt_Obj(Jim_GetOptInfo *goi, Jim_Obj **puthere)
int Jim_GetOpt_Obj(Jim_GetOptInfo * goi, Jim_Obj **puthere)
{ {
Jim_Obj *o; Jim_Obj *o;
o = NULL; // failure o = NULL; /* failure */
if (goi->argc) { if (goi->argc) {
// success /* success */
o = goi->argv[0]; o = goi->argv[0];
goi->argc -= 1; goi->argc -= 1;
goi->argv += 1; goi->argv += 1;
} }
if (puthere) { if (puthere)
*puthere = o; *puthere = o;
} if (o != NULL)
if (o != NULL) {
return JIM_OK; return JIM_OK;
} else
else {
return JIM_ERR; return JIM_ERR;
}
} }
int Jim_GetOpt_String(Jim_GetOptInfo * goi, char **puthere, int *len) int Jim_GetOpt_String(Jim_GetOptInfo *goi, char **puthere, int *len)
{ {
int r; int r;
Jim_Obj *o; Jim_Obj *o;
const char *cp; const char *cp;
r = Jim_GetOpt_Obj(goi, &o); r = Jim_GetOpt_Obj(goi, &o);
if (r == JIM_OK) { if (r == JIM_OK) {
cp = Jim_GetString(o, len); cp = Jim_GetString(o, len);
@ -247,98 +222,87 @@ int Jim_GetOpt_String(Jim_GetOptInfo * goi, char **puthere, int *len)
return r; return r;
} }
int Jim_GetOpt_Double(Jim_GetOptInfo * goi, double *puthere) int Jim_GetOpt_Double(Jim_GetOptInfo *goi, double *puthere)
{ {
int r; int r;
Jim_Obj *o; Jim_Obj *o;
double _safe; double _safe;
if (puthere == NULL) { if (puthere == NULL)
puthere = &_safe; puthere = &_safe;
}
r = Jim_GetOpt_Obj(goi, &o); r = Jim_GetOpt_Obj(goi, &o);
if (r == JIM_OK) { if (r == JIM_OK) {
r = Jim_GetDouble(goi->interp, o, puthere); r = Jim_GetDouble(goi->interp, o, puthere);
if (r != JIM_OK) { if (r != JIM_OK)
Jim_SetResultFormatted(goi->interp, "not a number: %#s", o); Jim_SetResultFormatted(goi->interp, "not a number: %#s", o);
} }
}
return r; return r;
} }
int Jim_GetOpt_Wide(Jim_GetOptInfo * goi, jim_wide * puthere) int Jim_GetOpt_Wide(Jim_GetOptInfo *goi, jim_wide *puthere)
{ {
int r; int r;
Jim_Obj *o; Jim_Obj *o;
jim_wide _safe; jim_wide _safe;
if (puthere == NULL) { if (puthere == NULL)
puthere = &_safe; puthere = &_safe;
}
r = Jim_GetOpt_Obj(goi, &o); r = Jim_GetOpt_Obj(goi, &o);
if (r == JIM_OK) { if (r == JIM_OK)
r = Jim_GetWide(goi->interp, o, puthere); r = Jim_GetWide(goi->interp, o, puthere);
}
return r; return r;
} }
int Jim_GetOpt_Nvp(Jim_GetOptInfo * goi, const Jim_Nvp * nvp, Jim_Nvp ** puthere) int Jim_GetOpt_Nvp(Jim_GetOptInfo *goi, const Jim_Nvp *nvp, Jim_Nvp **puthere)
{ {
Jim_Nvp *_safe; Jim_Nvp *_safe;
Jim_Obj *o; Jim_Obj *o;
int e; int e;
if (puthere == NULL) { if (puthere == NULL)
puthere = &_safe; puthere = &_safe;
}
e = Jim_GetOpt_Obj(goi, &o); e = Jim_GetOpt_Obj(goi, &o);
if (e == JIM_OK) { if (e == JIM_OK)
e = Jim_Nvp_name2value_obj(goi->interp, nvp, o, puthere); e = Jim_Nvp_name2value_obj(goi->interp, nvp, o, puthere);
}
return e; return e;
} }
void Jim_GetOpt_NvpUnknown(Jim_GetOptInfo * goi, const Jim_Nvp * nvptable, int hadprefix) void Jim_GetOpt_NvpUnknown(Jim_GetOptInfo *goi, const Jim_Nvp *nvptable, int hadprefix)
{ {
if (hadprefix) { if (hadprefix)
Jim_SetResult_NvpUnknown(goi->interp, goi->argv[-2], goi->argv[-1], nvptable); Jim_SetResult_NvpUnknown(goi->interp, goi->argv[-2], goi->argv[-1], nvptable);
} else
else {
Jim_SetResult_NvpUnknown(goi->interp, NULL, goi->argv[-1], nvptable); Jim_SetResult_NvpUnknown(goi->interp, NULL, goi->argv[-1], nvptable);
}
} }
int Jim_GetOpt_Enum(Jim_GetOptInfo *goi, const char *const *lookup, int *puthere)
int Jim_GetOpt_Enum(Jim_GetOptInfo * goi, const char *const *lookup, int *puthere)
{ {
int _safe; int _safe;
Jim_Obj *o; Jim_Obj *o;
int e; int e;
if (puthere == NULL) { if (puthere == NULL)
puthere = &_safe; puthere = &_safe;
}
e = Jim_GetOpt_Obj(goi, &o); e = Jim_GetOpt_Obj(goi, &o);
if (e == JIM_OK) { if (e == JIM_OK)
e = Jim_GetEnum(goi->interp, o, lookup, puthere, "option", JIM_ERRMSG); e = Jim_GetEnum(goi->interp, o, lookup, puthere, "option", JIM_ERRMSG);
}
return e; return e;
} }
void void Jim_SetResult_NvpUnknown(Jim_Interp *interp,
Jim_SetResult_NvpUnknown(Jim_Interp *interp, Jim_Obj *param_name, Jim_Obj *param_value, const Jim_Nvp *nvp)
Jim_Obj *param_name, Jim_Obj *param_value, const Jim_Nvp * nvp)
{ {
if (param_name) { if (param_name)
Jim_SetResultFormatted(interp, "%#s: Unknown: %#s, try one of: ", param_name, param_value); Jim_SetResultFormatted(interp,
} "%#s: Unknown: %#s, try one of: ",
else { param_name,
param_value);
else
Jim_SetResultFormatted(interp, "Unknown param: %#s, try one of: ", param_value); Jim_SetResultFormatted(interp, "Unknown param: %#s, try one of: ", param_value);
}
while (nvp->name) { while (nvp->name) {
const char *a; const char *a;
const char *b; const char *b;
@ -346,8 +310,7 @@ Jim_SetResult_NvpUnknown(Jim_Interp *interp,
if ((nvp + 1)->name) { if ((nvp + 1)->name) {
a = nvp->name; a = nvp->name;
b = ", "; b = ", ";
} } else {
else {
a = "or "; a = "or ";
b = nvp->name; b = nvp->name;
} }
@ -362,14 +325,12 @@ const char *Jim_Debug_ArgvString(Jim_Interp *interp, int argc, Jim_Obj *const *a
int x; int x;
if (debug_string_obj) { if (debug_string_obj)
Jim_FreeObj(interp, debug_string_obj); Jim_FreeObj(interp, debug_string_obj);
}
debug_string_obj = Jim_NewEmptyStringObj(interp); debug_string_obj = Jim_NewEmptyStringObj(interp);
for (x = 0; x < argc; x++) { for (x = 0; x < argc; x++)
Jim_AppendStrings(interp, debug_string_obj, Jim_String(argv[x]), " ", NULL); Jim_AppendStrings(interp, debug_string_obj, Jim_String(argv[x]), " ", NULL);
}
return Jim_String(debug_string_obj); return Jim_String(debug_string_obj);
} }

View File

@ -86,8 +86,7 @@ typedef struct {
int value; int value;
} Jim_Nvp; } Jim_Nvp;
int Jim_GetNvp(Jim_Interp *interp,
int Jim_GetNvp (Jim_Interp *interp,
Jim_Obj *objPtr, Jim_Obj *objPtr,
const Jim_Nvp *nvp_table, const Jim_Nvp *nvp_table,
const Jim_Nvp **result); const Jim_Nvp **result);
@ -97,13 +96,28 @@ Jim_Nvp *Jim_Nvp_name2value_simple(const Jim_Nvp *nvp_table, const char *name);
Jim_Nvp *Jim_Nvp_name2value_nocase_simple(const Jim_Nvp *nvp_table, const char *name); Jim_Nvp *Jim_Nvp_name2value_nocase_simple(const Jim_Nvp *nvp_table, const char *name);
Jim_Nvp *Jim_Nvp_value2name_simple(const Jim_Nvp *nvp_table, int v); Jim_Nvp *Jim_Nvp_value2name_simple(const Jim_Nvp *nvp_table, int v);
int Jim_Nvp_name2value(Jim_Interp *interp, const Jim_Nvp *nvp_table, const char *name, Jim_Nvp **result); int Jim_Nvp_name2value(Jim_Interp *interp,
int Jim_Nvp_name2value_nocase(Jim_Interp *interp, const Jim_Nvp *nvp_table, const char *name, Jim_Nvp **result); const Jim_Nvp *nvp_table,
const char *name,
Jim_Nvp **result);
int Jim_Nvp_name2value_nocase(Jim_Interp *interp,
const Jim_Nvp *nvp_table,
const char *name,
Jim_Nvp **result);
int Jim_Nvp_value2name(Jim_Interp *interp, const Jim_Nvp *nvp_table, int value, Jim_Nvp **result); int Jim_Nvp_value2name(Jim_Interp *interp, const Jim_Nvp *nvp_table, int value, Jim_Nvp **result);
int Jim_Nvp_name2value_obj(Jim_Interp *interp, const Jim_Nvp *nvp_table, Jim_Obj *name_obj, Jim_Nvp **result); int Jim_Nvp_name2value_obj(Jim_Interp *interp,
int Jim_Nvp_name2value_obj_nocase(Jim_Interp *interp, const Jim_Nvp *nvp_table, Jim_Obj *name_obj, Jim_Nvp **result); const Jim_Nvp *nvp_table,
int Jim_Nvp_value2name_obj(Jim_Interp *interp, const Jim_Nvp *nvp_table, Jim_Obj *value_obj, Jim_Nvp **result); Jim_Obj *name_obj,
Jim_Nvp **result);
int Jim_Nvp_name2value_obj_nocase(Jim_Interp *interp,
const Jim_Nvp *nvp_table,
Jim_Obj *name_obj,
Jim_Nvp **result);
int Jim_Nvp_value2name_obj(Jim_Interp *interp,
const Jim_Nvp *nvp_table,
Jim_Obj *value_obj,
Jim_Nvp **result);
/** prints a nice 'unknown' parameter error message to the 'result' */ /** prints a nice 'unknown' parameter error message to the 'result' */
void Jim_SetResult_NvpUnknown(Jim_Interp *interp, void Jim_SetResult_NvpUnknown(Jim_Interp *interp,
@ -111,7 +125,6 @@ void Jim_SetResult_NvpUnknown(Jim_Interp *interp,
Jim_Obj *param_value, Jim_Obj *param_value,
const Jim_Nvp *nvp_table); const Jim_Nvp *nvp_table);
/** Debug: convert argc/argv into a printable string for printf() debug /** Debug: convert argc/argv into a printable string for printf() debug
* *
* \param interp - the interpeter * \param interp - the interpeter
@ -147,7 +160,7 @@ const char *Jim_Debug_ArgvString(Jim_Interp *interp, int argc, Jim_Obj *const *a
typedef struct jim_getopt { typedef struct jim_getopt {
Jim_Interp *interp; Jim_Interp *interp;
int argc; int argc;
Jim_Obj * const * argv; Jim_Obj *const *argv;
int isconfigure; /* non-zero if configure */ int isconfigure; /* non-zero if configure */
} Jim_GetOptInfo; } Jim_GetOptInfo;
@ -210,7 +223,7 @@ typedef struct jim_getopt {
int Jim_GetOpt_Setup(Jim_GetOptInfo *goi, int Jim_GetOpt_Setup(Jim_GetOptInfo *goi,
Jim_Interp *interp, Jim_Interp *interp,
int argc, int argc,
Jim_Obj * const * argv); Jim_Obj *const *argv);
/** Debug - Dump parameters to stderr /** Debug - Dump parameters to stderr
@ -218,8 +231,6 @@ int Jim_GetOpt_Setup(Jim_GetOptInfo *goi,
*/ */
void Jim_GetOpt_Debug(Jim_GetOptInfo *goi); void Jim_GetOpt_Debug(Jim_GetOptInfo *goi);
/** Remove argv[0] from the list. /** Remove argv[0] from the list.
* *
* \param goi - get opt info * \param goi - get opt info
@ -313,6 +324,6 @@ void Jim_GetOpt_NvpUnknown(Jim_GetOptInfo *goi, const Jim_Nvp *lookup, int hadpr
* \param puthere - where param is put. * \param puthere - where param is put.
* *
*/ */
int Jim_GetOpt_Enum(Jim_GetOptInfo *goi, const char * const * lookup, int *puthere); int Jim_GetOpt_Enum(Jim_GetOptInfo *goi, const char *const *lookup, int *puthere);
#endif #endif

View File

@ -23,12 +23,13 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "time_support.h" #include "time_support.h"
// @todo the inclusion of server.h here is a layering violation /* @todo the inclusion of server.h here is a layering violation */
#include <server/server.h> #include <server/server.h>
#include <stdarg.h> #include <stdarg.h>
@ -43,16 +44,15 @@
int debug_level = -1; int debug_level = -1;
static FILE* log_output; static FILE *log_output;
static struct log_callback *log_callbacks = NULL; static struct log_callback *log_callbacks;
static long long last_time; static long long last_time;
static long long current_time; static long long current_time;
static long long start; static long long start;
static char *log_strings[5] = static char *log_strings[5] = {
{
"User : ", "User : ",
"Error: ", "Error: ",
"Warn : ", /* want a space after each colon, all same width, colons aligned */ "Warn : ", /* want a space after each colon, all same width, colons aligned */
@ -60,55 +60,46 @@ static char *log_strings[5] =
"Debug: " "Debug: "
}; };
static int count;
static int count = 0; static struct store_log_forward *log_head;
static int log_forward_count;
struct store_log_forward {
static struct store_log_forward * log_head = NULL; struct store_log_forward *next;
static int log_forward_count = 0; const char *file;
struct store_log_forward
{
struct store_log_forward * next;
const char * file;
int line; int line;
const char * function; const char *function;
const char * string; const char *string;
}; };
/* either forward the log to the listeners or store it for possible forwarding later */ /* either forward the log to the listeners or store it for possible forwarding later */
static void log_forward(const char *file, unsigned line, const char *function, const char *string) static void log_forward(const char *file, unsigned line, const char *function, const char *string)
{ {
if (log_forward_count==0) if (log_forward_count == 0) {
{
struct log_callback *cb, *next; struct log_callback *cb, *next;
cb = log_callbacks; cb = log_callbacks;
/* DANGER!!!! the log callback can remove itself!!!! */ /* DANGER!!!! the log callback can remove itself!!!! */
while (cb) while (cb) {
{
next = cb->next; next = cb->next;
cb->fn(cb->priv, file, line, function, string); cb->fn(cb->priv, file, line, function, string);
cb = next; cb = next;
} }
} else } else {
{ struct store_log_forward *log = malloc(sizeof(struct store_log_forward));
struct store_log_forward *log = malloc(sizeof (struct store_log_forward));
log->file = strdup(file); log->file = strdup(file);
log->line = line; log->line = line;
log->function = strdup(function); log->function = strdup(function);
log->string = strdup(string); log->string = strdup(string);
log->next = NULL; log->next = NULL;
if (log_head==NULL) if (log_head == NULL)
log_head = log; log_head = log;
else else {
{
/* append to tail */ /* append to tail */
struct store_log_forward * t; struct store_log_forward *t;
t = log_head; t = log_head;
while (t->next!=NULL) while (t->next != NULL)
{
t = t->next; t = t->next;
}
t->next = log; t->next = log;
} }
} }
@ -124,11 +115,14 @@ static void log_forward(const char *file, unsigned line, const char *function, c
* target_request.c). * target_request.c).
* *
*/ */
static void log_puts(enum log_levels level, const char *file, int line, const char *function, const char *string) static void log_puts(enum log_levels level,
const char *file,
int line,
const char *function,
const char *string)
{ {
char *f; char *f;
if (level == LOG_LVL_OUTPUT) if (level == LOG_LVL_OUTPUT) {
{
/* do not prepend any headers, just print out what we were given and return */ /* do not prepend any headers, just print out what we were given and return */
fputs(string, log_output); fputs(string, log_output);
fflush(log_output); fflush(log_output);
@ -139,10 +133,8 @@ static void log_puts(enum log_levels level, const char *file, int line, const ch
if (f != NULL) if (f != NULL)
file = f + 1; file = f + 1;
if (strlen(string) > 0) if (strlen(string) > 0) {
{ if (debug_level >= LOG_LVL_DEBUG) {
if (debug_level >= LOG_LVL_DEBUG)
{
/* print with count and time information */ /* print with count and time information */
int t = (int)(timeval_ms()-start); int t = (int)(timeval_ms()-start);
#ifdef _DEBUG_FREE_SPACE_ #ifdef _DEBUG_FREE_SPACE_
@ -158,30 +150,30 @@ static void log_puts(enum log_levels level, const char *file, int line, const ch
info.fordblks, info.fordblks,
#endif #endif
string); string);
} } else {
else
{
/* if we are using gdb through pipes then we do not want any output /* if we are using gdb through pipes then we do not want any output
* to the pipe otherwise we get repeated strings */ * to the pipe otherwise we get repeated strings */
fprintf(log_output, "%s%s", fprintf(log_output, "%s%s",
(level > LOG_LVL_USER)?log_strings[level + 1]:"", string); (level > LOG_LVL_USER) ? log_strings[level + 1] : "", string);
} }
} else } else {
{ /* Empty strings are sent to log callbacks to keep e.g. gdbserver alive, here we do
/* Empty strings are sent to log callbacks to keep e.g. gdbserver alive, here we do nothing. */ *nothing. */
} }
fflush(log_output); fflush(log_output);
/* Never forward LOG_LVL_DEBUG, too verbose and they can be found in the log if need be */ /* Never forward LOG_LVL_DEBUG, too verbose and they can be found in the log if need be */
if (level <= LOG_LVL_INFO) if (level <= LOG_LVL_INFO)
{
log_forward(file, line, function, string); log_forward(file, line, function, string);
}
} }
void log_printf(enum log_levels level,
void log_printf(enum log_levels level, const char *file, unsigned line, const char *function, const char *format, ...) const char *file,
unsigned line,
const char *function,
const char *format,
...)
{ {
char *string; char *string;
va_list ap; va_list ap;
@ -193,8 +185,7 @@ void log_printf(enum log_levels level, const char *file, unsigned line, const ch
va_start(ap, format); va_start(ap, format);
string = alloc_vprintf(format, ap); string = alloc_vprintf(format, ap);
if (string != NULL) if (string != NULL) {
{
log_puts(level, file, line, function, string); log_puts(level, file, line, function, string);
free(string); free(string);
} }
@ -202,7 +193,12 @@ void log_printf(enum log_levels level, const char *file, unsigned line, const ch
va_end(ap); va_end(ap);
} }
void log_printf_lf(enum log_levels level, const char *file, unsigned line, const char *function, const char *format, ...) void log_printf_lf(enum log_levels level,
const char *file,
unsigned line,
const char *function,
const char *format,
...)
{ {
char *string; char *string;
va_list ap; va_list ap;
@ -214,9 +210,9 @@ void log_printf_lf(enum log_levels level, const char *file, unsigned line, const
va_start(ap, format); va_start(ap, format);
string = alloc_vprintf(format, ap); string = alloc_vprintf(format, ap);
if (string != NULL) if (string != NULL) {
{ strcat(string, "\n"); /* alloc_vprintf guaranteed the buffer to be at least one
strcat(string, "\n"); /* alloc_vprintf guaranteed the buffer to be at least one char longer */ *char longer */
log_puts(level, file, line, function, string); log_puts(level, file, line, function, string);
free(string); free(string);
} }
@ -226,18 +222,15 @@ void log_printf_lf(enum log_levels level, const char *file, unsigned line, const
COMMAND_HANDLER(handle_debug_level_command) COMMAND_HANDLER(handle_debug_level_command)
{ {
if (CMD_ARGC == 1) if (CMD_ARGC == 1) {
{
int new_level; int new_level;
COMMAND_PARSE_NUMBER(int, CMD_ARGV[0], new_level); COMMAND_PARSE_NUMBER(int, CMD_ARGV[0], new_level);
if ((debug_level > LOG_LVL_DEBUG) || (new_level < LOG_LVL_SILENT)) if ((debug_level > LOG_LVL_DEBUG) || (new_level < LOG_LVL_SILENT)) {
{
LOG_ERROR("level must be between %d and %d", LOG_LVL_SILENT, LOG_LVL_DEBUG); LOG_ERROR("level must be between %d and %d", LOG_LVL_SILENT, LOG_LVL_DEBUG);
return ERROR_COMMAND_SYNTAX_ERROR; return ERROR_COMMAND_SYNTAX_ERROR;
} }
debug_level = new_level; debug_level = new_level;
} } else if (CMD_ARGC > 1)
else if (CMD_ARGC > 1)
return ERROR_COMMAND_SYNTAX_ERROR; return ERROR_COMMAND_SYNTAX_ERROR;
command_print(CMD_CTX, "debug_level: %i", debug_level); command_print(CMD_CTX, "debug_level: %i", debug_level);
@ -247,15 +240,12 @@ COMMAND_HANDLER(handle_debug_level_command)
COMMAND_HANDLER(handle_log_output_command) COMMAND_HANDLER(handle_log_output_command)
{ {
if (CMD_ARGC == 1) if (CMD_ARGC == 1) {
{ FILE *file = fopen(CMD_ARGV[0], "w");
FILE* file = fopen(CMD_ARGV[0], "w");
if (file) if (file)
{
log_output = file; log_output = file;
} }
}
return ERROR_OK; return ERROR_OK;
} }
@ -293,17 +283,14 @@ void log_init(void)
debug_level = LOG_LVL_INFO; debug_level = LOG_LVL_INFO;
char *debug_env = getenv("OPENOCD_DEBUG_LEVEL"); char *debug_env = getenv("OPENOCD_DEBUG_LEVEL");
if (NULL != debug_env) if (NULL != debug_env) {
{
int value; int value;
int retval = parse_int(debug_env, &value); int retval = parse_int(debug_env, &value);
if (ERROR_OK == retval && if (ERROR_OK == retval &&
debug_level >= LOG_LVL_SILENT && debug_level >= LOG_LVL_SILENT &&
debug_level <= LOG_LVL_DEBUG) debug_level <= LOG_LVL_DEBUG)
{
debug_level = value; debug_level = value;
} }
}
if (log_output == NULL) if (log_output == NULL)
log_output = stderr; log_output = stderr;
@ -323,14 +310,15 @@ int log_add_callback(log_callback_fn fn, void *priv)
struct log_callback *cb; struct log_callback *cb;
/* prevent the same callback to be registered more than once, just for sure */ /* prevent the same callback to be registered more than once, just for sure */
for (cb = log_callbacks; cb; cb = cb->next) for (cb = log_callbacks; cb; cb = cb->next) {
{
if (cb->fn == fn && cb->priv == priv) if (cb->fn == fn && cb->priv == priv)
return ERROR_COMMAND_SYNTAX_ERROR; return ERROR_COMMAND_SYNTAX_ERROR;
} }
/* alloc memory, it is safe just to return in case of an error, no need for the caller to check this */ /* alloc memory, it is safe just to return in case of an error, no need for the caller to
if ((cb = malloc(sizeof(struct log_callback))) == NULL) *check this */
cb = malloc(sizeof(struct log_callback));
if (cb == NULL)
return ERROR_BUF_TOO_SMALL; return ERROR_BUF_TOO_SMALL;
/* add item to the beginning of the linked list */ /* add item to the beginning of the linked list */
@ -346,10 +334,8 @@ int log_remove_callback(log_callback_fn fn, void *priv)
{ {
struct log_callback *cb, **p; struct log_callback *cb, **p;
for (p = &log_callbacks; (cb = *p); p = &(*p)->next) for (p = &log_callbacks; (cb = *p); p = &(*p)->next) {
{ if (cb->fn == fn && cb->priv == priv) {
if (cb->fn == fn && cb->priv == priv)
{
*p = cb->next; *p = cb->next;
free(cb); free(cb);
return ERROR_OK; return ERROR_OK;
@ -420,8 +406,7 @@ char *alloc_printf(const char *format, ...)
void keep_alive() void keep_alive()
{ {
current_time = timeval_ms(); current_time = timeval_ms();
if (current_time-last_time > 1000) if (current_time-last_time > 1000) {
{
extern int gdb_actual_connections; extern int gdb_actual_connections;
if (gdb_actual_connections) if (gdb_actual_connections)
@ -436,8 +421,7 @@ void keep_alive()
"trouble with GDB connections.", "trouble with GDB connections.",
current_time-last_time); current_time-last_time);
} }
if (current_time-last_time > 500) if (current_time-last_time > 500) {
{
/* this will keep the GDB connection alive */ /* this will keep the GDB connection alive */
LOG_USER_N("%s", ""); LOG_USER_N("%s", "");
@ -464,8 +448,7 @@ void kept_alive()
void alive_sleep(uint64_t ms) void alive_sleep(uint64_t ms)
{ {
uint64_t napTime = 10; uint64_t napTime = 10;
for (uint64_t i = 0; i < ms; i += napTime) for (uint64_t i = 0; i < ms; i += napTime) {
{
uint64_t sleep_a_bit = ms - i; uint64_t sleep_a_bit = ms - i;
if (sleep_a_bit > napTime) if (sleep_a_bit > napTime)
sleep_a_bit = napTime; sleep_a_bit = napTime;
@ -478,8 +461,9 @@ void alive_sleep(uint64_t ms)
void busy_sleep(uint64_t ms) void busy_sleep(uint64_t ms)
{ {
uint64_t then = timeval_ms(); uint64_t then = timeval_ms();
while (timeval_ms() - then < ms) while (timeval_ms() - then < ms) {
{ /*
/* busy wait */ * busy wait
*/
} }
} }

View File

@ -23,6 +23,7 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#ifndef ERROR_H #ifndef ERROR_H
#define ERROR_H #define ERROR_H
@ -48,8 +49,7 @@
* LOG_LVL_INFO - state information, etc. * LOG_LVL_INFO - state information, etc.
* LOG_LVL_DEBUG - debug statements, execution trace * LOG_LVL_DEBUG - debug statements, execution trace
*/ */
enum log_levels enum log_levels {
{
LOG_LVL_SILENT = -3, LOG_LVL_SILENT = -3,
LOG_LVL_OUTPUT = -2, LOG_LVL_OUTPUT = -2,
LOG_LVL_USER = -1, LOG_LVL_USER = -1,
@ -111,22 +111,22 @@ extern int debug_level;
} while (0) } while (0)
#define LOG_INFO(expr ...) \ #define LOG_INFO(expr ...) \
log_printf_lf (LOG_LVL_INFO, __FILE__, __LINE__, __FUNCTION__, expr) log_printf_lf(LOG_LVL_INFO, __FILE__, __LINE__, __func__, expr)
#define LOG_WARNING(expr ...) \ #define LOG_WARNING(expr ...) \
log_printf_lf (LOG_LVL_WARNING, __FILE__, __LINE__, __FUNCTION__, expr) log_printf_lf(LOG_LVL_WARNING, __FILE__, __LINE__, __func__, expr)
#define LOG_ERROR(expr ...) \ #define LOG_ERROR(expr ...) \
log_printf_lf (LOG_LVL_ERROR, __FILE__, __LINE__, __FUNCTION__, expr) log_printf_lf(LOG_LVL_ERROR, __FILE__, __LINE__, __func__, expr)
#define LOG_USER(expr ...) \ #define LOG_USER(expr ...) \
log_printf_lf (LOG_LVL_USER, __FILE__, __LINE__, __FUNCTION__, expr) log_printf_lf(LOG_LVL_USER, __FILE__, __LINE__, __func__, expr)
#define LOG_USER_N(expr ...) \ #define LOG_USER_N(expr ...) \
log_printf (LOG_LVL_USER, __FILE__, __LINE__, __FUNCTION__, expr) log_printf(LOG_LVL_USER, __FILE__, __LINE__, __func__, expr)
#define LOG_OUTPUT(expr ...) \ #define LOG_OUTPUT(expr ...) \
log_printf (LOG_LVL_OUTPUT, __FILE__, __LINE__, __FUNCTION__, expr) log_printf(LOG_LVL_OUTPUT, __FILE__, __LINE__, __func__, expr)
/* general failures /* general failures
* error codes < 100 * error codes < 100

View File

@ -20,20 +20,20 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
#include "configuration.h" #include "configuration.h"
// @todo the inclusion of server.h here is a layering violation /* @todo the inclusion of server.h here is a layering violation */
#include <server/server.h> #include <server/server.h>
#include <getopt.h> #include <getopt.h>
static int help_flag, version_flag; static int help_flag, version_flag;
static const struct option long_options[] = static const struct option long_options[] = {
{
{"help", no_argument, &help_flag, 1}, {"help", no_argument, &help_flag, 1},
{"version", no_argument, &version_flag, 1}, {"version", no_argument, &version_flag, 1},
{"debug", optional_argument, 0, 'd'}, {"debug", optional_argument, 0, 'd'},
@ -45,7 +45,7 @@ static const struct option long_options[] =
{0, 0, 0, 0} {0, 0, 0, 0}
}; };
int configuration_output_handler(struct command_context *context, const char* line) int configuration_output_handler(struct command_context *context, const char *line)
{ {
LOG_USER_N("%s", line); LOG_USER_N("%s", line);
@ -64,8 +64,8 @@ static void add_default_dirs(void)
* target\at91eb40a.cfg * target\at91eb40a.cfg
*/ */
{ {
char strExePath [MAX_PATH]; char strExePath[MAX_PATH];
GetModuleFileName (NULL, strExePath, MAX_PATH); GetModuleFileName(NULL, strExePath, MAX_PATH);
/* Either this code will *always* work or it will SEGFAULT giving /* Either this code will *always* work or it will SEGFAULT giving
* excellent information on the culprit. * excellent information on the culprit.
*/ */
@ -84,11 +84,11 @@ static void add_default_dirs(void)
* share/openocd/scripts/target/at91eb40a.cfg * share/openocd/scripts/target/at91eb40a.cfg
*/ */
{ {
char strExePath [MAX_PATH]; char strExePath[MAX_PATH];
char *p; char *p;
GetModuleFileName (NULL, strExePath, MAX_PATH); GetModuleFileName(NULL, strExePath, MAX_PATH);
*strrchr(strExePath, '\\') = 0; *strrchr(strExePath, '\\') = 0;
strcat(strExePath, "/../share/"PACKAGE"/scripts"); strcat(strExePath, "/../share/"PACKAGE "/scripts");
for (p = strExePath; *p; p++) { for (p = strExePath; *p; p++) {
if (*p == '\\') if (*p == '\\')
*p = '/'; *p = '/';
@ -104,14 +104,12 @@ static void add_default_dirs(void)
const char *home = getenv("HOME"); const char *home = getenv("HOME");
if (home) if (home) {
{
char *path; char *path;
path = alloc_printf("%s/.openocd", home); path = alloc_printf("%s/.openocd", home);
if (path) if (path) {
{
add_script_search_dir(path); add_script_search_dir(path);
free(path); free(path);
} }
@ -127,8 +125,7 @@ int parse_cmdline_args(struct command_context *cmd_ctx, int argc, char *argv[])
int c; int c;
char command_buffer[128]; char command_buffer[128];
while (1) while (1) {
{
/* getopt_long stores the option index here. */ /* getopt_long stores the option index here. */
int option_index = 0; int option_index = 0;
@ -138,8 +135,7 @@ int parse_cmdline_args(struct command_context *cmd_ctx, int argc, char *argv[])
if (c == -1) if (c == -1)
break; break;
switch (c) switch (c) {
{
case 0: case 0:
break; break;
case 'h': /* --help | -h */ case 'h': /* --help | -h */
@ -165,29 +161,26 @@ int parse_cmdline_args(struct command_context *cmd_ctx, int argc, char *argv[])
command_run_line(cmd_ctx, command_buffer); command_run_line(cmd_ctx, command_buffer);
break; break;
case 'l': /* --log_output | -l */ case 'l': /* --log_output | -l */
if (optarg) if (optarg) {
{
snprintf(command_buffer, 128, "log_output %s", optarg); snprintf(command_buffer, 128, "log_output %s", optarg);
command_run_line(cmd_ctx, command_buffer); command_run_line(cmd_ctx, command_buffer);
} }
break; break;
case 'c': /* --command | -c */ case 'c': /* --command | -c */
if (optarg) if (optarg)
{
add_config_command(optarg); add_config_command(optarg);
}
break; break;
case 'p': case 'p':
/* to replicate the old syntax this needs to be synchronous /* to replicate the old syntax this needs to be synchronous
* otherwise the gdb stdin will overflow with the warning message */ * otherwise the gdb stdin will overflow with the warning message */
command_run_line(cmd_ctx, "gdb_port pipe; log_output openocd.log"); command_run_line(cmd_ctx, "gdb_port pipe; log_output openocd.log");
LOG_WARNING("deprecated option: -p/--pipe. Use '-c \"gdb_port pipe; log_output openocd.log\"' instead."); LOG_WARNING("deprecated option: -p/--pipe. Use '-c \"gdb_port pipe; "
"log_output openocd.log\"' instead.");
break; break;
} }
} }
if (help_flag) if (help_flag) {
{
LOG_OUTPUT("Open On-Chip Debugger\nLicensed under GNU GPL v2\n"); LOG_OUTPUT("Open On-Chip Debugger\nLicensed under GNU GPL v2\n");
LOG_OUTPUT("--help | -h\tdisplay this help\n"); LOG_OUTPUT("--help | -h\tdisplay this help\n");
LOG_OUTPUT("--version | -v\tdisplay OpenOCD version\n"); LOG_OUTPUT("--version | -v\tdisplay OpenOCD version\n");
@ -199,10 +192,9 @@ int parse_cmdline_args(struct command_context *cmd_ctx, int argc, char *argv[])
exit(-1); exit(-1);
} }
if (version_flag) if (version_flag) {
{
/* Nothing to do, version gets printed automatically. */ /* Nothing to do, version gets printed automatically. */
// It is not an error to request the VERSION number. /* It is not an error to request the VERSION number. */
exit(0); exit(0);
} }

View File

@ -36,22 +36,19 @@ void *clear_malloc(size_t size)
{ {
void *t = malloc(size); void *t = malloc(size);
if (t != NULL) if (t != NULL)
{
memset(t, 0x00, size); memset(t, 0x00, size);
}
return t; return t;
} }
void *fill_malloc(size_t size) void *fill_malloc(size_t size)
{ {
void *t = malloc(size); void *t = malloc(size);
if (t != NULL) if (t != NULL) {
{ /* We want to initialize memory to some known bad state.
/* We want to initialize memory to some known bad state. */ * 0 and 0xff yields 0 and -1 as integers, which often
/* 0 and 0xff yields 0 and -1 as integers, which often */ * have meaningful values. 0x5555... is not often a valid
/* have meaningful values. 0x5555... is not often a valid */ * integer and is quite easily spotted in the debugger
/* integer and is quite easily spotted in the debugger */ * also it is almost certainly an invalid address */
/* also it is almost certainly an invalid address */
memset(t, 0x55, size); memset(t, 0x55, size);
} }
return t; return t;
@ -88,22 +85,22 @@ int gettimeofday(struct timeval *tv, struct timezone *tz)
__int64 t; __int64 t;
static int tzflag; static int tzflag;
if (tv) if (tv) {
{
GetSystemTimeAsFileTime(&ft); GetSystemTimeAsFileTime(&ft);
li.LowPart = ft.dwLowDateTime; li.LowPart = ft.dwLowDateTime;
li.HighPart = ft.dwHighDateTime; li.HighPart = ft.dwHighDateTime;
t = li.QuadPart; /* In 100-nanosecond intervals */ t = li.QuadPart; /* In 100-nanosecond
t -= EPOCHFILETIME; /* Offset to the Epoch time */ *intervals */
t /= 10; /* In microseconds */ t -= EPOCHFILETIME; /* Offset to the Epoch time
**/
t /= 10; /* In microseconds
**/
tv->tv_sec = (long)(t / 1000000); tv->tv_sec = (long)(t / 1000000);
tv->tv_usec = (long)(t % 1000000); tv->tv_usec = (long)(t % 1000000);
} }
if (tz) if (tz) {
{ if (!tzflag) {
if (!tzflag)
{
_tzset(); _tzset();
tzflag++; tzflag++;
} }
@ -120,22 +117,22 @@ int gettimeofday(struct timeval *tv, struct timezone *tz)
#ifndef HAVE_STRNLEN #ifndef HAVE_STRNLEN
size_t strnlen(const char *s, size_t maxlen) size_t strnlen(const char *s, size_t maxlen)
{ {
const char *end= (const char *)memchr(s, '\0', maxlen); const char *end = (const char *)memchr(s, '\0', maxlen);
return end ? (size_t) (end - s) : maxlen; return end ? (size_t) (end - s) : maxlen;
} }
#endif #endif
#ifndef HAVE_STRNDUP #ifndef HAVE_STRNDUP
char* strndup(const char *s, size_t n) char *strndup(const char *s, size_t n)
{ {
size_t len = strnlen (s, n); size_t len = strnlen(s, n);
char *new = (char *) malloc (len + 1); char *new = (char *) malloc(len + 1);
if (new == NULL) if (new == NULL)
return NULL; return NULL;
new[len] = '\0'; new[len] = '\0';
return (char *) memcpy (new, s, len); return (char *) memcpy(new, s, len);
} }
#endif #endif
@ -155,9 +152,9 @@ int win_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *efds, struct time
#define SAFE_FD_ISSET(fd, set) (set != NULL && FD_ISSET(fd, set)) #define SAFE_FD_ISSET(fd, set) (set != NULL && FD_ISSET(fd, set))
/* calculate how long we need to wait in milliseconds */ /* calculate how long we need to wait in milliseconds */
if (tv == NULL) { if (tv == NULL)
ms_total = INFINITE; ms_total = INFINITE;
} else { else {
ms_total = tv->tv_sec * 1000; ms_total = tv->tv_sec * 1000;
ms_total += tv->tv_usec / 1000; ms_total += tv->tv_usec / 1000;
} }
@ -173,18 +170,14 @@ int win_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *efds, struct time
handles[n_handles] = (HANDLE)handle; handles[n_handles] = (HANDLE)handle;
if (handles[n_handles] == INVALID_HANDLE_VALUE) { if (handles[n_handles] == INVALID_HANDLE_VALUE) {
/* socket */ /* socket */
if (SAFE_FD_ISSET(i, rfds)) { if (SAFE_FD_ISSET(i, rfds))
FD_SET(i, &sock_read); FD_SET(i, &sock_read);
} if (SAFE_FD_ISSET(i, wfds))
if (SAFE_FD_ISSET(i, wfds)) {
FD_SET(i, &sock_write); FD_SET(i, &sock_write);
} if (SAFE_FD_ISSET(i, efds))
if (SAFE_FD_ISSET(i, efds)) {
FD_SET(i, &sock_except); FD_SET(i, &sock_except);
} if (i > sock_max_fd)
if (i > sock_max_fd) {
sock_max_fd = i; sock_max_fd = i;
}
} else { } else {
handle_slot_to_fd[n_handles] = i; handle_slot_to_fd[n_handles] = i;
n_handles++; n_handles++;
@ -224,7 +217,11 @@ int win_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *efds, struct time
/* check handles */ /* check handles */
DWORD wret; DWORD wret;
wret = MsgWaitForMultipleObjects(n_handles, handles, FALSE, retcode > 0 ? 0 : 100, QS_ALLEVENTS); wret = MsgWaitForMultipleObjects(n_handles,
handles,
FALSE,
retcode > 0 ? 0 : 100,
QS_ALLEVENTS);
if (wret == WAIT_TIMEOUT) { if (wret == WAIT_TIMEOUT) {
/* set retcode to 0; this is the default. /* set retcode to 0; this is the default.
@ -233,31 +230,30 @@ int win_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *efds, struct time
* does nothing */ * does nothing */
; ;
} else if (wret == WAIT_FAILED) { } else if (wret == WAIT_FAILED) {
if (retcode == 0) { if (retcode == 0)
retcode = -1; retcode = -1;
}
} else { } else {
if (retcode < 0) { if (retcode < 0)
retcode = 0; retcode = 0;
}
for (i = 0; i < n_handles; i++) { for (i = 0; i < n_handles; i++) {
if (WAIT_OBJECT_0 == WaitForSingleObject(handles[i], 0)) { if (WAIT_OBJECT_0 == WaitForSingleObject(handles[i], 0)) {
if (SAFE_FD_ISSET(handle_slot_to_fd[i], rfds)) { if (SAFE_FD_ISSET(handle_slot_to_fd[i], rfds)) {
DWORD dwBytes; DWORD dwBytes;
intptr_t handle = (intptr_t) _get_osfhandle(handle_slot_to_fd[i]); intptr_t handle = (intptr_t) _get_osfhandle(
handle_slot_to_fd[i]);
if (PeekNamedPipe((HANDLE)handle, NULL, 0, NULL, &dwBytes, NULL)) if (PeekNamedPipe((HANDLE)handle, NULL, 0,
{ NULL, &dwBytes, NULL)) {
/* check to see if gdb pipe has data available */ /* check to see if gdb pipe has data
if (dwBytes) *available */
{ if (dwBytes) {
FD_SET(handle_slot_to_fd[i], &aread); FD_SET(handle_slot_to_fd[i],
&aread);
retcode++; retcode++;
} }
} } else {
else FD_SET(handle_slot_to_fd[i],
{ &aread);
FD_SET(handle_slot_to_fd[i], &aread);
retcode++; retcode++;
} }
} }
@ -275,15 +271,12 @@ int win_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *efds, struct time
} }
} while (retcode == 0 && (ms_total == INFINITE || GetTickCount() < limit)); } while (retcode == 0 && (ms_total == INFINITE || GetTickCount() < limit));
if (rfds) { if (rfds)
*rfds = aread; *rfds = aread;
} if (wfds)
if (wfds) {
*wfds = awrite; *wfds = awrite;
} if (efds)
if (efds) {
*efds = aexcept; *efds = aexcept;
}
return retcode; return retcode;
} }

View File

@ -23,15 +23,16 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#ifndef REPLACEMENTS_H #ifndef REPLACEMENTS_H
#define REPLACEMENTS_H #define REPLACEMENTS_H
/* MIN,MAX macros */ /* MIN,MAX macros */
#ifndef MIN #ifndef MIN
#define MIN(a,b) (((a) < (b))?(a):(b)) #define MIN(a, b) (((a) < (b)) ? (a) : (b))
#endif #endif
#ifndef MAX #ifndef MAX
#define MAX(a,b) (((a) > (b))?(a):(b)) #define MAX(a, b) (((a) > (b)) ? (a) : (b))
#endif #endif
/* for systems that do not support ENOTSUP /* for systems that do not support ENOTSUP
@ -107,12 +108,12 @@ void *fill_malloc(size_t size);
* the following macros. Which is the default way. * the following macros. Which is the default way.
*/ */
/* #define malloc(_a) clear_malloc(_a) */ /* #define malloc(_a) clear_malloc(_a)
/* #define malloc(_a) fill_malloc(_a) */ * #define malloc(_a) fill_malloc(_a) */
/* GNU extensions to the C library that may be missing on some systems */ /* GNU extensions to the C library that may be missing on some systems */
#ifndef HAVE_STRNDUP #ifndef HAVE_STRNDUP
char* strndup(const char *s, size_t n); char *strndup(const char *s, size_t n);
#endif /* HAVE_STRNDUP */ #endif /* HAVE_STRNDUP */
#ifndef HAVE_STRNLEN #ifndef HAVE_STRNLEN
@ -121,7 +122,7 @@ size_t strnlen(const char *s, size_t maxlen);
#ifndef HAVE_USLEEP #ifndef HAVE_USLEEP
#ifdef _WIN32 #ifdef _WIN32
static __inline unsigned usleep(unsigned int usecs) static inline unsigned usleep(unsigned int usecs)
{ {
Sleep((usecs/1000)); Sleep((usecs/1000));
return 0; return 0;
@ -149,16 +150,16 @@ void usleep(int us);
#endif #endif
#if IS_MINGW == 1 #if IS_MINGW == 1
static __inline unsigned char inb(unsigned short int port) static inline unsigned char inb(unsigned short int port)
{ {
unsigned char _v; unsigned char _v;
__asm__ __volatile__ ("inb %w1,%0":"=a" (_v):"Nd" (port)); __asm__ __volatile__ ("inb %w1,%0" : "=a" (_v) : "Nd" (port));
return _v; return _v;
} }
static __inline void outb(unsigned char value, unsigned short int port) static inline void outb(unsigned char value, unsigned short int port)
{ {
__asm__ __volatile__ ("outb %b0,%w1": :"a" (value), "Nd" (port)); __asm__ __volatile__ ("outb %b0,%w1" : : "a" (value), "Nd" (port));
} }
/* mingw does not have ffs, so use gcc builtin types */ /* mingw does not have ffs, so use gcc builtin types */
@ -171,7 +172,7 @@ int win_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *efds, struct time
#endif /* _WIN32 */ #endif /* _WIN32 */
/* generic socket functions for Windows and Posix */ /* generic socket functions for Windows and Posix */
static __inline int write_socket(int handle, const void *buffer, unsigned int count) static inline int write_socket(int handle, const void *buffer, unsigned int count)
{ {
#ifdef _WIN32 #ifdef _WIN32
return send(handle, buffer, count, 0); return send(handle, buffer, count, 0);
@ -180,7 +181,7 @@ static __inline int write_socket(int handle, const void *buffer, unsigned int co
#endif #endif
} }
static __inline int read_socket(int handle, void *buffer, unsigned int count) static inline int read_socket(int handle, void *buffer, unsigned int count)
{ {
#ifdef _WIN32 #ifdef _WIN32
return recv(handle, buffer, count, 0); return recv(handle, buffer, count, 0);
@ -189,7 +190,7 @@ static __inline int read_socket(int handle, void *buffer, unsigned int count)
#endif #endif
} }
static __inline int close_socket(int sock) static inline int close_socket(int sock)
{ {
#ifdef _WIN32 #ifdef _WIN32
return closesocket(sock); return closesocket(sock);
@ -198,7 +199,7 @@ static __inline int close_socket(int sock)
#endif #endif
} }
static __inline void socket_nonblock(int fd) static inline void socket_nonblock(int fd)
{ {
#ifdef _WIN32 #ifdef _WIN32
unsigned long nonblock = 1; unsigned long nonblock = 1;
@ -209,7 +210,11 @@ static __inline void socket_nonblock(int fd)
#endif #endif
} }
static __inline int socket_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *efds, struct timeval *tv) static inline int socket_select(int max_fd,
fd_set *rfds,
fd_set *wfds,
fd_set *efds,
struct timeval *tv)
{ {
#ifdef _WIN32 #ifdef _WIN32
return win_select(max_fd, rfds, wfds, efds, tv); return win_select(max_fd, rfds, wfds, efds, tv);
@ -230,8 +235,7 @@ typedef uint32_t Elf32_Word;
typedef uint32_t Elf32_Size; typedef uint32_t Elf32_Size;
typedef Elf32_Off Elf32_Hashelt; typedef Elf32_Off Elf32_Hashelt;
typedef struct typedef struct {
{
unsigned char e_ident[16]; /* Magic number and other info */ unsigned char e_ident[16]; /* Magic number and other info */
Elf32_Half e_type; /* Object file type */ Elf32_Half e_type; /* Object file type */
Elf32_Half e_machine; /* Architecture */ Elf32_Half e_machine; /* Architecture */
@ -259,8 +263,7 @@ typedef struct
#define ELFDATA2LSB 1 /* 2's complement, little endian */ #define ELFDATA2LSB 1 /* 2's complement, little endian */
#define ELFDATA2MSB 2 /* 2's complement, big endian */ #define ELFDATA2MSB 2 /* 2's complement, big endian */
typedef struct typedef struct {
{
Elf32_Word p_type; /* Segment type */ Elf32_Word p_type; /* Segment type */
Elf32_Off p_offset; /* Segment file offset */ Elf32_Off p_offset; /* Segment file offset */
Elf32_Addr p_vaddr; /* Segment virtual address */ Elf32_Addr p_vaddr; /* Segment virtual address */

View File

@ -19,10 +19,11 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#ifndef SYSTEM_H #ifndef SYSTEM_H
#define SYSTEM_H #define SYSTEM_H
// standard C library header files /* standard C library header files */
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
@ -30,7 +31,7 @@
#include <ctype.h> #include <ctype.h>
#include <errno.h> #include <errno.h>
// +++ AC_HEADER_TIME +++ /* +++ AC_HEADER_TIME +++ */
#ifdef TIME_WITH_SYS_TIME #ifdef TIME_WITH_SYS_TIME
# include <sys/time.h> # include <sys/time.h>
# include <time.h> # include <time.h>
@ -41,9 +42,9 @@
# include <time.h> # include <time.h>
# endif # endif
#endif #endif
// --- AC_HEADER_TIME --- /* --- AC_HEADER_TIME --- */
// +++ platform specific headers +++ /* +++ platform specific headers +++ */
#if BUILD_ECOSBOARD == 1 #if BUILD_ECOSBOARD == 1
#include <pkgconf/system.h> #include <pkgconf/system.h>
#endif #endif
@ -53,7 +54,7 @@
#include <sys/types.h> #include <sys/types.h>
#include <sys/stat.h> #include <sys/stat.h>
#endif #endif
// --- platform specific headers --- /* --- platform specific headers --- */
#ifdef HAVE_SYS_SOCKET_H #ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h> #include <sys/socket.h>
@ -90,4 +91,4 @@
#define false 0 #define false 0
#endif #endif
#endif // SYSTEM_H #endif /* SYSTEM_H */

View File

@ -23,6 +23,7 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif
@ -32,8 +33,7 @@
/* calculate difference between two struct timeval values */ /* calculate difference between two struct timeval values */
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{ {
if (x->tv_usec < y->tv_usec) if (x->tv_usec < y->tv_usec) {
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec; y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec; y->tv_sec += nsec;
@ -56,8 +56,7 @@ int timeval_add_time(struct timeval *result, long sec, long usec)
result->tv_sec += sec; result->tv_sec += sec;
result->tv_usec += usec; result->tv_usec += usec;
while (result->tv_usec > 1000000) while (result->tv_usec > 1000000) {
{
result->tv_usec -= 1000000; result->tv_usec -= 1000000;
result->tv_sec++; result->tv_sec++;
} }

View File

@ -23,6 +23,7 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#ifndef TIME_SUPPORT_H #ifndef TIME_SUPPORT_H
#define TIME_SUPPORT_H #define TIME_SUPPORT_H
@ -40,23 +41,22 @@
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y); int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y);
int timeval_add_time(struct timeval *result, long sec, long usec); int timeval_add_time(struct timeval *result, long sec, long usec);
/// @returns gettimeofday() timeval as 64-bit in ms /* / @returns gettimeofday() timeval as 64-bit in ms */
int64_t timeval_ms(void); int64_t timeval_ms(void);
struct duration struct duration {
{
struct timeval start; struct timeval start;
struct timeval elapsed; struct timeval elapsed;
}; };
/// Update the duration->start field to start the @a duration measurement. /* / Update the duration->start field to start the @a duration measurement. */
int duration_start(struct duration *duration); int duration_start(struct duration *duration);
/// Update the duration->elapsed field to finish the @a duration measurment. /* / Update the duration->elapsed field to finish the @a duration measurment. */
int duration_measure(struct duration *duration); int duration_measure(struct duration *duration);
/// @returns Elapsed time in seconds. /* / @returns Elapsed time in seconds. */
float duration_elapsed(struct duration *duration); float duration_elapsed(struct duration *duration);
/// @returns KB/sec for the elapsed @a duration and @a count bytes. /* / @returns KB/sec for the elapsed @a duration and @a count bytes. */
float duration_kbps(struct duration *duration, size_t count); float duration_kbps(struct duration *duration, size_t count);
#endif /* TIME_SUPPORT_H */ #endif /* TIME_SUPPORT_H */

View File

@ -23,6 +23,7 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif

View File

@ -23,6 +23,7 @@
* Free Software Foundation, Inc., * * Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/ ***************************************************************************/
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
#include "config.h" #include "config.h"
#endif #endif

View File

@ -26,13 +26,11 @@
#include "log.h" #include "log.h"
#include "time_support.h" #include "time_support.h"
static int static int util_Jim_Command_ms(Jim_Interp *interp,
util_Jim_Command_ms(Jim_Interp *interp,
int argc, int argc,
Jim_Obj * const *argv) Jim_Obj * const *argv)
{ {
if (argc != 1) if (argc != 1) {
{
Jim_WrongNumArgs(interp, 1, argv, "ls ?dir?"); Jim_WrongNumArgs(interp, 1, argv, "ls ?dir?");
return JIM_ERR; return JIM_ERR;
} }
@ -45,12 +43,13 @@ util_Jim_Command_ms(Jim_Interp *interp,
} }
static const struct command_registration util_command_handlers[] = { static const struct command_registration util_command_handlers[] = {
// jim handlers /* jim handlers */
{ {
.name = "ms", .name = "ms",
.mode = COMMAND_ANY, .mode = COMMAND_ANY,
.jim_handler = util_Jim_Command_ms, .jim_handler = util_Jim_Command_ms,
.help = "Returns ever increasing milliseconds. Used to calculuate differences in time.", .help =
"Returns ever increasing milliseconds. Used to calculuate differences in time.",
.usage = "", .usage = "",
}, },
COMMAND_REGISTRATION_DONE COMMAND_REGISTRATION_DONE

View File

@ -24,4 +24,4 @@ struct command_context;
int util_init(struct command_context *cmd_ctx); int util_init(struct command_context *cmd_ctx);
#endif // HELPER_UTILS_H #endif /* HELPER_UTILS_H */