Example #1
0
void set_offset (char *command_line)

{
	long mult=1;
	long new_offset;
	char *ptr,new_offset_buffer [80];
	
	if (device_handle==NULL) {
		wprintw (command_win,"Error - No device opened\n");refresh_command_win ();
		return;
	}
	
	ptr=parse_word (command_line,new_offset_buffer);
	
	if (*ptr==0) {
		wprintw (command_win,"Error - No argument specified\n");refresh_command_win ();
		return;
	}

	ptr=parse_word (ptr,new_offset_buffer);

	if (strcmp (new_offset_buffer,"block")==0) {
		mult=file_system_info.block_size;
		ptr=parse_word (ptr,new_offset_buffer);
	}

	if (strcmp (new_offset_buffer,"type")==0) {
		if (current_type==NULL) {
			wprintw (command_win,"Error - No type set\n");refresh_command_win ();
			return;
		}

		mult=current_type->length;
		ptr=parse_word (ptr,new_offset_buffer);
	}

	if (*new_offset_buffer==0) {
		wprintw (command_win,"Error - No offset specified\n");refresh_command_win ();
		return;
	}

	if (new_offset_buffer [0]=='+') {
		if (device_offset==-1) {
			wprintw (command_win,"Error - Select a fixed offset first\n");refresh_command_win ();
			return;
		}
		new_offset=device_offset+atol (new_offset_buffer+1)*mult;
	}
	
	else if (new_offset_buffer [0]=='-') {
		if (device_offset==-1) {
			wprintw (command_win,"Error - Select a fixed offset first\n");refresh_command_win ();
			return;
		}
		new_offset=device_offset-atol (new_offset_buffer+1)*mult;
		if (new_offset<0) new_offset=0;
	}
	
	else 
		new_offset=atol (new_offset_buffer)*mult;
	
	if ( (fseek (device_handle,new_offset,SEEK_SET))==-1) {
		wprintw (command_win,"Error - Failed to seek to offset %ld in device %s\n",new_offset,device_name);
		refresh_command_win ();
		return;
	};
	device_offset=new_offset;
	wprintw (command_win,"Device offset changed to %ld\n",device_offset);refresh_command_win ();
	load_type_data ();
	type_data.offset_in_block=0;
}
/*
 * Helper function which checks a file in /etc/mtab format to see if a
 * filesystem is mounted.  Returns an error if the file doesn't exist
 * or can't be opened.
 */
static errcode_t check_mntent_file(const char *mtab_file, const char *file,
				   int *mount_flags)
{
#ifdef HAVE_SETMNTENT
	struct stat	st_buf;
	errcode_t	retval = 0;
	dev_t		file_dev=0, file_rdev=0;
	ino_t		file_ino=0;
	FILE 		*f;
	char		buf[1024], *device = 0, *mnt_dir = 0, *cp;

	*mount_flags = 0;
	if ((f = setmntent (mtab_file, "r")) == NULL)
		return errno;
	if (stat(file, &st_buf) == 0) {
		if (S_ISBLK(st_buf.st_mode)) {
#ifndef __GNU__ /* The GNU hurd is broken with respect to stat devices */
			file_rdev = st_buf.st_rdev;
#endif	/* __GNU__ */
		} else {
			file_dev = st_buf.st_dev;
			file_ino = st_buf.st_ino;
		}
	}
	while (1) {
		if (!fgets(buf, sizeof(buf), f)) {
			device = mnt_dir = 0;
			break;
		}
		buf[sizeof(buf)-1] = 0;

		cp = buf;
		device = parse_word(&cp);
		if (!device || *device == '#')
			return 0;	/* Ignore blank lines and comments */
		mnt_dir = parse_word(&cp);

		if (device[0] != '/')
			continue;

		if (strcmp(file, device) == 0)
			break;
		if (stat(device, &st_buf) == 0) {
			if (S_ISBLK(st_buf.st_mode)) {
#ifndef __GNU__
				if (file_rdev && (file_rdev == st_buf.st_rdev))
					break;
#endif	/* __GNU__ */
			} else {
				if (file_dev && ((file_dev == st_buf.st_dev) &&
						 (file_ino == st_buf.st_ino)))
					break;
			}
		}
	}

	if (mnt_dir == 0) {
#ifndef __GNU__ /* The GNU hurd is broken with respect to stat devices */
		/*
		 * Do an extra check to see if this is the root device.  We
		 * can't trust /etc/mtab, and /proc/mounts will only list
		 * /dev/root for the root filesystem.  Argh.  Instead we
		 * check if the given device has the same major/minor number
		 * as the device that the root directory is on.
		 */
		if (file_rdev && (stat("/", &st_buf) == 0) &&
		    (st_buf.st_dev == file_rdev))
			*mount_flags = MF_MOUNTED;
#endif	/* __GNU__ */
		goto errout;
	}
#ifndef __GNU__ /* The GNU hurd is deficient; what else is new? */
	/* Validate the entry in case /etc/mtab is out of date */
	/*
	 * We need to be paranoid, because some broken distributions
	 * (read: Slackware) don't initialize /etc/mtab before checking
	 * all of the non-root filesystems on the disk.
	 */
	if (stat(mnt_dir, &st_buf) < 0) {
		retval = errno;
		if (retval == ENOENT) {
#ifdef DEBUG
			printf("Bogus entry in %s!  (%s does not exist)\n",
			       mtab_file, mnt_dir);
#endif /* DEBUG */
			retval = 0;
		}
		goto errout;
	}
	if (file_rdev && (st_buf.st_dev != file_rdev)) {
#ifdef DEBUG
		printf("Bogus entry in %s!  (%s not mounted on %s)\n",
		       mtab_file, file, mnt_dir);
#endif /* DEBUG */
		goto errout;
	}
#endif /* __GNU__ */
	*mount_flags = MF_MOUNTED;

	retval = 0;
errout:
	endmntent (f);
	return retval;
#else /* !HAVE_SETMNTENT */
	return 0;
#endif /* HAVE_MNTENT_H */
}
Example #3
0
SCOPE2 void
create_word(int cf, int up)
{
    int len = parse_word(up+TMP1, up);
    str_create(V(TMP1), len, cf, up);
}
Example #4
0
static errcode_t check_mntent_file(const char *mtab_file, const char *file,
				   int *mount_flags)
{
#ifdef HAVE_MNTENT_H
	struct stat	st_buf;
	errcode_t	retval = 0;
	dev_t		file_dev=0, file_rdev=0;
	ino_t		file_ino=0;
	FILE 		*f;
	char		buf[1024], *device = 0, *mnt_dir = 0, *cp;

	*mount_flags = 0;
	if ((f = setmntent (mtab_file, "r")) == NULL)
		return errno;
	if (stat(file, &st_buf) == 0) {
		if (S_ISBLK(st_buf.st_mode)) {
#ifndef __GNU__ 
			file_rdev = st_buf.st_rdev;
#endif	
		} else {
			file_dev = st_buf.st_dev;
			file_ino = st_buf.st_ino;
		}
	}
	while (1) {
		if (!fgets(buf, sizeof(buf), f)) {
			device = mnt_dir = 0;
			break;
		}
		buf[sizeof(buf)-1] = 0;

		cp = buf;
		device = parse_word(&cp);
		if (!device || *device == '#')
			return 0;	
		mnt_dir = parse_word(&cp);

		if (device[0] != '/')
			continue;

		if (strcmp(file, device) == 0)
			break;
		if (stat(device, &st_buf) == 0) {
			if (S_ISBLK(st_buf.st_mode)) {
#ifndef __GNU__
				if (file_rdev && (file_rdev == st_buf.st_rdev))
					break;
#endif	
			} else {
				if (file_dev && ((file_dev == st_buf.st_dev) &&
						 (file_ino == st_buf.st_ino)))
					break;
			}
		}
	}

	if (mnt_dir == 0) {
#ifndef __GNU__ 
		if (file_rdev && (stat("/", &st_buf) == 0) &&
		    (st_buf.st_dev == file_rdev))
			*mount_flags = MF_MOUNTED;
#endif	
		goto errout;
	}
#ifndef __GNU__ 
	
	if (stat(mnt_dir, &st_buf) < 0) {
		retval = errno;
		if (retval == ENOENT) {
#ifdef DEBUG
			printf("Bogus entry in %s!  (%s does not exist)\n",
			       mtab_file, mnt_dir);
#endif 
			retval = 0;
		}
		goto errout;
	}
	if (file_rdev && (st_buf.st_dev != file_rdev)) {
#ifdef DEBUG
		printf("Bogus entry in %s!  (%s not mounted on %s)\n",
		       mtab_file, file, mnt_dir);
#endif 
		goto errout;
	}
#endif 
	*mount_flags = MF_MOUNTED;

	retval = 0;
errout:
	endmntent (f);
	return retval;
#else 
	return 0;
#endif 
}
Example #5
0
/**
 * Skips the next bit of whatever and returns the type of block.
 *
 * pc.str is the input text.
 * pc.len in the output length.
 * pc.type is the output type
 * pc.column is output column
 *
 * @param pc      The structure to update, str is an input.
 * @return        true/false - whether anything was parsed
 */
static bool parse_next(tok_ctx& ctx, chunk_t& pc)
{
   const chunk_tag_t *punc;
   int               ch, ch1;

   if (!ctx.more())
   {
      //fprintf(stderr, "All done!\n");
      return(false);
   }

   /* Save off the current column */
   pc.orig_line = ctx.c.row;
   pc.column    = ctx.c.col;
   pc.orig_col  = ctx.c.col;
   pc.type      = CT_NONE;
   pc.nl_count  = 0;
   pc.flags     = 0;

   /* If it is turned off, we put everything except newlines into CT_UNKNOWN */
   if (cpd.unc_off)
   {
      if (parse_ignored(ctx, pc))
      {
         return(true);
      }
   }

   /**
    * Parse whitespace
    */
   if (parse_whitespace(ctx, pc))
   {
      return(true);
   }

   /**
    * Handle unknown/unhandled preprocessors
    */
   if ((cpd.in_preproc > CT_PP_BODYCHUNK) &&
       (cpd.in_preproc <= CT_PP_OTHER))
   {
      pc.str.clear();
      tok_info ss;
      ctx.save(ss);
      /* Chunk to a newline or comment */
      pc.type = CT_PREPROC_BODY;
      int last = 0;
      while (ctx.more())
      {
         int ch = ctx.peek();

         if ((ch == '\n') || (ch == '\r'))
         {
            /* Back off if this is an escaped newline */
            if (last == '\\')
            {
               ctx.restore(ss);
               pc.str.pop_back();
            }
            break;
         }

         /* Quit on a C++ comment start */
         if ((ch == '/') && (ctx.peek(1) == '/'))
         {
            break;
         }
         last = ch;
         ctx.save(ss);

         pc.str.append(ctx.get());
      }
      if (pc.str.size() > 0)
      {
         return(true);
      }
   }

   /**
    * Detect backslash-newline
    */
   if ((ctx.peek() == '\\') && parse_bs_newline(ctx, pc))
   {
      return(true);
   }

   /**
    * Parse comments
    */
   if (parse_comment(ctx, pc))
   {
      return(true);
   }

   /* Parse code placeholders */
   if (parse_code_placeholder(ctx, pc))
   {
      return(true);
   }

   /* Check for C# literal strings, ie @"hello" and identifiers @for*/
   if ((cpd.lang_flags & LANG_CS) && (ctx.peek() == '@'))
   {
      if (ctx.peek(1) == '"')
      {
         parse_cs_string(ctx, pc);
         return(true);
      }
      /* check for non-keyword identifiers such as @if @switch, etc */
      if (CharTable::IsKw1(ctx.peek(1)))
      {
         parse_word(ctx, pc, true);
         return(true);
      }
   }

   /* Check for C# Interpolated strings */
   if ((cpd.lang_flags & LANG_CS) && (ctx.peek() == '$') && (ctx.peek(1) == '"'))
   {
      parse_cs_interpolated_string(ctx, pc);
      return(true);
   }

   /* handle VALA """ strings """ */
   if ((cpd.lang_flags & LANG_VALA) &&
       (ctx.peek() == '"') &&
       (ctx.peek(1) == '"') &&
       (ctx.peek(2) == '"'))
   {
      parse_verbatim_string(ctx, pc);
      return(true);
   }

   /* handle C++0x strings u8"x" u"x" U"x" R"x" u8R"XXX(I'm a "raw UTF-8" string.)XXX" */
   ch = ctx.peek();
   if ((cpd.lang_flags & LANG_CPP) &&
       ((ch == 'u') || (ch == 'U') || (ch == 'R')))
   {
      int  idx     = 0;
      bool is_real = false;

      if ((ch == 'u') && (ctx.peek(1) == '8'))
      {
         idx = 2;
      }
      else if (unc_tolower(ch) == 'u')
      {
         idx++;
      }

      if (ctx.peek(idx) == 'R')
      {
         idx++;
         is_real = true;
      }
      if (ctx.peek(idx) == '"')
      {
         if (is_real)
         {
            if (parse_cr_string(ctx, pc, idx))
            {
               return(true);
            }
         }
         else
         {
            if (parse_string(ctx, pc, idx, true))
            {
               parse_suffix(ctx, pc, true);
               return(true);
            }
         }
      }
   }

   /* PAWN specific stuff */
   if (cpd.lang_flags & LANG_PAWN)
   {
      if ((cpd.preproc_ncnl_count == 1) &&
          ((cpd.in_preproc == CT_PP_DEFINE) ||
           (cpd.in_preproc == CT_PP_EMIT)))
      {
         parse_pawn_pattern(ctx, pc, CT_MACRO);
         return(true);
      }
      /* Check for PAWN strings: \"hi" or !"hi" or !\"hi" or \!"hi" */
      if ((ctx.peek() == '\\') || (ctx.peek() == '!'))
      {
         if (ctx.peek(1) == '"')
         {
            parse_string(ctx, pc, 1, (ctx.peek() == '!'));
            return(true);
         }
         else if (((ctx.peek(1) == '\\') || (ctx.peek(1) == '!')) &&
                  (ctx.peek(2) == '"'))
         {
            parse_string(ctx, pc, 2, false);
            return(true);
         }
      }

      /* handle PAWN preprocessor args %0 .. %9 */
      if ((cpd.in_preproc == CT_PP_DEFINE) &&
          (ctx.peek() == '%') &&
          unc_isdigit(ctx.peek(1)))
      {
         pc.str.clear();
         pc.str.append(ctx.get());
         pc.str.append(ctx.get());
         pc.type = CT_WORD;
         return(true);
      }
   }

   /**
    * Parse strings and character constants
    */

   if (parse_number(ctx, pc))
   {
      return(true);
   }

   if (cpd.lang_flags & LANG_D)
   {
      /* D specific stuff */
      if (d_parse_string(ctx, pc))
      {
         return(true);
      }
   }
   else
   {
      /* Not D stuff */

      /* Check for L'a', L"abc", 'a', "abc", <abc> strings */
      ch  = ctx.peek();
      ch1 = ctx.peek(1);
      if ((((ch == 'L') || (ch == 'S')) &&
           ((ch1 == '"') || (ch1 == '\''))) ||
          (ch == '"') ||
          (ch == '\'') ||
          ((ch == '<') && (cpd.in_preproc == CT_PP_INCLUDE)))
      {
         parse_string(ctx, pc, unc_isalpha(ch) ? 1 : 0, true);
         return(true);
      }

      if ((ch == '<') && (cpd.in_preproc == CT_PP_DEFINE))
      {
         if (chunk_get_tail()->type == CT_MACRO)
         {
            /* We have "#define XXX <", assume '<' starts an include string */
            parse_string(ctx, pc, 0, false);
            return(true);
         }
      }
   }

   /* Check for Objective C literals and VALA identifiers ('@1', '@if')*/
   if ((cpd.lang_flags & (LANG_OC | LANG_VALA)) && (ctx.peek() == '@'))
   {
      int nc = ctx.peek(1);
      if ((nc == '"') || (nc == '\''))
      {
         /* literal string */
         parse_string(ctx, pc, 1, true);
         return(true);
      }
      else if ((nc >= '0') && (nc <= '9'))
      {
         /* literal number */
         pc.str.append(ctx.get());  /* store the '@' */
         parse_number(ctx, pc);
         return(true);
      }
   }

   /* Check for pawn/ObjectiveC/Java and normal identifiers */
   if (CharTable::IsKw1(ctx.peek()) ||
       ((ctx.peek() == '@') && CharTable::IsKw1(ctx.peek(1))))
   {
      parse_word(ctx, pc, false);
      return(true);
   }

   /* see if we have a punctuator */
   char punc_txt[4];
   punc_txt[0] = ctx.peek();
   punc_txt[1] = ctx.peek(1);
   punc_txt[2] = ctx.peek(2);
   punc_txt[3] = ctx.peek(3);
   if ((punc = find_punctuator(punc_txt, cpd.lang_flags)) != NULL)
   {
      int cnt = strlen(punc->tag);
      while (cnt--)
      {
         pc.str.append(ctx.get());
      }
      pc.type   = punc->type;
      pc.flags |= PCF_PUNCTUATOR;
      return(true);
   }

   /* throw away this character */
   pc.type = CT_UNKNOWN;
   pc.str.append(ctx.get());

   LOG_FMT(LWARN, "%s:%d Garbage in col %d: %x\n",
           cpd.filename, pc.orig_line, (int)ctx.c.col, pc.str[0]);
   cpd.error_count++;
   return(true);
} // parse_next
static int interpret_source(char *fil)
{
	FILE *f;
	char tib[160];
        cell num;
	char *test;

	const ucell SEMIS = (ucell)findword("(semis)");
	const ucell LIT = (ucell)findword("(lit)");
	const ucell DOBRANCH = (ucell)findword("dobranch");

	if ((f = fopen_include(fil)) == NULL) {
		printk("error while loading source file '%s'\n", fil);
		errors++;
		exit(1);
	}

	/* FIXME: We should read this file at
	 * once. No need to get it char by char
	 */

	while (!feof(f)) {
		xt_t res;
		parse_word(f, tib);

		/* if there is actually no word, we continue right away */
		if (strlen(tib) == 0) {
			continue;
		}

		/* Checking for builtin words that are needed to
		 * bootstrap the forth base dictionary.
		 */

		if (!strcmp(tib, "(")) {
			parse(f, tib, ')');
			continue;
		}

		if (!strcmp(tib, "\\")) {
			parse(f, tib, '\n');
			continue;
		}

		if (!strcmp(tib, ":")) {
			parse_word(f, tib);

#ifdef CONFIG_DEBUG_INTERPRETER
			printk("create colon word %s\n\n", tib);
#endif
			fcreate(tib, DOCOL);	/* see dict.h for DOCOL and other CFA ids */
			*state = (ucell) (-1);
			continue;
		}

		if (!strcmp(tib, ";")) {
#ifdef CONFIG_DEBUG_INTERPRETER
			printk("finish colon definition\n\n");
#endif
			writecell((cell)SEMIS);
			*state = (ucell) 0;
			reveal();
			continue;
		}

		if (!strcasecmp(tib, "variable")) {
			parse_word(f, tib);
#ifdef CONFIG_DEBUG_INTERPRETER
			printk("defining variable %s\n\n", tib);
#endif
			buildvariable(tib, 0);
			reveal();
			continue;
		}

		if (!strcasecmp(tib, "constant")) {
			parse_word(f, tib);
#ifdef CONFIG_DEBUG_INTERPRETER
			printk("defining constant %s\n\n", tib);
#endif
			buildconstant(tib, POP());
			reveal();
			continue;
		}

		if (!strcasecmp(tib, "value")) {
			parse_word(f, tib);
#ifdef CONFIG_DEBUG_INTERPRETER
			printk("defining value %s\n\n", tib);
#endif
			buildconstant(tib, POP());
			reveal();
			continue;
		}

		if (!strcasecmp(tib, "defer")) {
			parse_word(f, tib);
#ifdef CONFIG_DEBUG_INTERPRETER
			printk("defining defer word %s\n\n", tib);
#endif
			builddefer(tib);
			reveal();
			continue;
		}

		if (!strcasecmp(tib, "include")) {
			parse_word(f, tib);
#ifdef CONFIG_DEBUG_INTERPRETER
			printk("including file %s\n\n", tib);
#endif
			interpret_source(tib);
			continue;
		}

		if (!strcmp(tib, "[']")) {
			xt_t xt;
			parse_word(f, tib);
			xt = findword(tib);
			if (*state == 0) {
#ifdef CONFIG_DEBUG_INTERPRETER
				printk
				    ("writing address of %s to stack\n\n",
				     tib);
#endif
				PUSH_xt(xt);
			} else {
#ifdef CONFIG_DEBUG_INTERPRETER
				printk("writing lit, addr(%s) to dict\n\n",
				       tib);
#endif
				writecell(LIT);	/* lit */
				writecell((cell)xt);
			}
			continue;
			/* we have no error detection here */
		}

		if (!strcasecmp(tib, "s\"")) {
			int cnt;
			cell loco;

			cnt = parse(f, tib, '"');
#ifdef CONFIG_DEBUG_INTERPRETER
			printk("compiling string %s\n", tib);
#endif
			loco = dicthead + (6 * sizeof(cell));
			writecell(LIT);
			writecell(pointer2cell(dict) + loco);
			writecell(LIT);
                        writecell((ucell)cnt);
			writecell(DOBRANCH);
			loco = cnt + sizeof(cell) - 1;
			loco &= ~(sizeof(cell) - 1);
			writecell(loco);
			memcpy(dict + dicthead, tib, cnt);
			dicthead += cnt;
			paddict(sizeof(cell));
			continue;
		}

		/* look if tib is in dictionary. */
		/* should the dictionary be searched before the builtins ? */
		res = findword(tib);
		if (res) {
			u8 flags = read_byte((u8*)cell2pointer(res) -
						sizeof(cell) - 1);
#ifdef CONFIG_DEBUG_INTERPRETER
                        printk("%s is 0x%" FMT_CELL_x "\n", tib, (ucell) res);
#endif
			if (!(*state) || (flags & 3)) {
#ifdef CONFIG_DEBUG_INTERPRETER
                                printk("executing %s, %" FMT_CELL_d
                                       " (flags: %s %s)\n",
				       tib, res,
				       (flags & 1) ? "immediate" : "",
				       (flags & 2) ? "compile-only" : "");
#endif
				PC = (ucell)res;
				enterforth(res);
			} else {
#ifdef CONFIG_DEBUG_INTERPRETER
				printk("writing %s to dict\n\n", tib);
#endif
				writecell((cell)res);
			}
			continue;
		}

		/* if not look if it's a number */
		if (tib[0] == '-')
			num = strtoll(tib, &test, read_ucell(base));
		else
			num = strtoull(tib, &test, read_ucell(base));


		if (*test != 0) {
			/* what is it?? */
			printk("%s:%d: %s is not defined.\n\n", srcfilenames[cursrc - 1], srclines[cursrc - 1], tib);
			errors++;
#ifdef CONFIG_DEBUG_INTERPRETER
			continue;
#else
			return -1;
#endif
		}

		if (*state == 0) {
#ifdef CONFIG_DEBUG_INTERPRETER
                        printk("pushed %" FMT_CELL_x " to stack\n\n", num);
#endif
			PUSH(num);
		} else {
#ifdef CONFIG_DEBUG_INTERPRETER
                        printk("writing lit, %" FMT_CELL_x " to dict\n\n", num);
#endif
			writecell(LIT);	/* lit */
			writecell(num);
		}
	}

	fclose(f);
	cursrc--;

	return 0;
}
Example #7
0
/* Funcion que va a parsear todas las funciones de un archivo, extrayendo
 * tanto el FUNC_COMPLETED como el FUNC_WEIGHT, y el nombre.
 * RETURNS:
 * 	list<Function *>*	if not error
 * 	NULL			on error
 * NOTE: genera memoria para cada funcion y para la lista
 */
list<Function *> *parser_functions(string &data)
{
	list<Function *> *result = NULL;
	Function *func = NULL;
	string *comment = NULL;
	string opCmt = PARSER_OPEN_COMMENT, cCmt = PARSER_CLOSE_COMMENT;
	string funCmp = FUNC_COMPLETED;
	string funWt = FUNC_WEIGHT;
	string funTest = FUNC_TESTED;
	string aux = "";
	string *funcName = NULL,blanks = PARSER_BLANKS;
	int pos = 0;
	uint32_t upos = 0;
	int completed = 0, weight = 0;
	bool tested = false;
	
	if (data.size() == 0)
		return result;
	
	result = new list<Function *>();
	if (result == NULL)
		return result;
	
	while (pos >= 0) {
		comment = parser_get_comment(data, pos, opCmt, cCmt);
		if (comment == NULL)
			/* no hay mas comentarios... salimos */
			break;
		
		/* buscamos el FUNC_COMPLETED */
		if ((parser_search_int_key(*comment, funCmp, completed) < 0) ||
			(completed > 100) || (completed < 0)) {
			/* no es un comentario valido.. */
			delete comment;
			continue;
		}
		/* extraemos el peso de la funcion */
		if ((parser_search_int_key(*comment, funWt, weight) < 0) ||
			(weight < 0)) {
			/* no es un comentario valido.. */
			delete comment;
			continue;
		}
		if ((parser_search_key(*comment,funTest, aux) < 0)) {
			delete comment;
			continue;
		}
		/* verificamos si fue testeada la funcion */
		convert_upper(aux);
		if((int)aux.find("TRUE") >= 0)
			tested = true;
		else 
			tested = false;
		
		delete comment;
		/* salteamos los blancos */
		pos = pos + 1;
		upos = pos;
		while (upos < data.size())
			if((int)blanks.find(data[upos]) >= 0)
				upos++;
			else
				break;
		/* extraemos el nombre de la funcion ahora */
		funcName = parse_word(data, upos, "{;");
		if ((funcName == NULL) || (funcName->size() > 400)){
			/* error no estamos tomando una funcion */
			cerr << "Error al intentar obtener el prototipo de ";
			cerr << "la funcion, no estan respetando el formato?" << endl;
			continue;
		}
		/* si estamos aca entonces podemos decir que tenemos una func */
		func = new Function(*funcName, completed, weight);
		delete funcName;
		if (func == NULL){
			cerr << "no hay memoria para crear la funcion\n";
			break;
		}
		func->setTested(tested);
		result->push_back(func);
	}
		
	return result;
	
}
Example #8
0
/**
 * @brief Loop event.
 * @param ui user interface.
 */
void ui_loop_edax(UI *ui)
{
	char *cmd = NULL, *param = NULL;
	Play *play = ui->play;
	char book_file[FILENAME_MAX];
	unsigned long long histogram[129][65];
	int repeat = options.repeat;

	histogram_init(histogram);

	// loop forever
	for (;;) {
		errno = 0;

		if (options.verbosity) {
			putchar('\n');
			play_print(play, stdout);
			if (play_is_game_over(play)) printf("\n*** Game Over ***\n");
			putchar('\n');
		}

		if (log_is_open(edax_log)) {
			putc('\n', edax_log->f);
			play_print(play, edax_log->f);
			if (play_is_game_over(play)) fputs("\n*** Game Over ***\n", edax_log->f);
			putc('\n', edax_log->f);
		}

		// edax turn ? (automatic play mode)
		if (!ui_event_exist(ui) && !play_is_game_over(play) && (ui->mode == !play->player || ui->mode == 2)) {
			putchar('\n');
			play_go(play, true);
			printf("\nEdax plays "); move_print(play_get_last_move(play)->x, 0, stdout); putchar('\n');
			if (ui->mode != 2) play_ponder(play);

		// proceed by reading a command
		} else {

			/* automatic rules after a game over*/
			if (play_is_game_over(play)) {
				if (options.auto_store) play_store(play);
				if (options.auto_swap && ui->mode < 2) ui->mode = !ui->mode;
				if (options.repeat && repeat > 1) {
					--repeat;
					play_new(play);
					continue;
				}
				if (options.auto_quit) {
					return;
				}
				if (options.auto_start) {
					play_new(play);
					continue;
				}
			}

			putchar('>'); fflush(stdout);
			ui_event_wait(ui, &cmd, &param);
			log_print(edax_log, "cmd=\"%s\" ; param=\"%s\"\n", cmd, param);
			putchar('\n');

			if (cmd == NULL) {
				warn("unexpected null command?\n");
				continue;
			}

			// skip empty lines or commented lines
			if (*cmd == '\0' || *cmd == '#') {
			
			// help
			} else if (strcmp(cmd, "help") == 0 || strcmp(cmd, "?") == 0) {
				if (*param == '\0' || strcmp(param, "options") == 0) help_options();
				if (*param == '\0' || strcmp(param, "commands") == 0) help_commands();
				if (*param == '\0' || strcmp(param, "book") == 0) help_book();
				if (*param == '\0' || strcmp(param, "base") == 0) help_base();
				if (*param == '\0' || strcmp(param, "test") == 0) help_test(); 

			// new game from standard position
			} else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "init") == 0) {
				board_init(play->initial_board);
				play_new(play);

			// new game from personnalized position
			} else if ((strcmp(cmd, "n") == 0 || strcmp(cmd, "new") == 0) && *param == '\0') {
				play_new(play);

			// open a saved game
			} else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "open") == 0 || strcmp(cmd, "load") == 0) {
				play_load(play, param);

			// save a game
			} else if (strcmp(cmd, "s") == 0 || strcmp(cmd, "save") == 0) {
				play_save(play, param);

			// quit
			} else if (strcmp(cmd, "quit") == 0 || strcmp(cmd, "q") == 0 || strcmp(cmd, "exit") == 0) {
				free(cmd); free(param);
				return;

			} else if (!options.auto_quit && (strcmp(cmd, "eof") == 0 && (ui->mode != 2 || play_is_game_over(play)))){
				free(cmd); free(param);
				return;

			// undo last move
			} else if (strcmp(cmd, "u") == 0 || strcmp(cmd, "undo") == 0) {
				play_undo(play);
				if (ui->mode == 0 || ui->mode == 1) play_undo(play);

			// redo last move
			} else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "redo") == 0) {
				play_redo(play);
				if (ui->mode == 0 || ui->mode == 1) play_undo(play);

			// mode
			} else if (strcmp(cmd, "m") == 0 || strcmp(cmd, "mode") == 0) {
				ui->mode = string_to_int(param, 3);

			// analyze a game
			} else if (strcmp(cmd, "a") == 0 || strcmp(cmd, "analyze") == 0 || strcmp(cmd, "analyse") == 0) {
				play_analyze(play, string_to_int(param, play->n_game));

			// set a new initial position
			} else if (strcmp(cmd, "setboard") == 0) {
				play_set_board(play, param);

			// vertical mirror
			} else if (strcmp(cmd, "vmirror") == 0) {
				play_symetry(play, 2);

			// horizontal mirror
			} else if (strcmp(cmd, "hmirror") == 0) {
				play_symetry(play, 1);

			// rotate
			} else if (strcmp(cmd, "rotate") == 0) {
				int angle = string_to_int(param, 90) % 360;
				if (angle < 0) angle += 360;
				switch (angle) {
				case 90: 
					play_symetry(play, 5);
					break; 
				case 180:
					play_symetry(play, 3);
					break; 
				case 270:
					play_symetry(play, 6);
					break; 
				default:
					warn("Rotate angle should be 90°, 180° or 270°");
					break;
				}

			// direct symetry...
			} else if (strcmp(cmd, "symetry") == 0) {
				int sym = string_to_int(param, 1);
				if (sym < 0 || sym >= 16) warn("symetry parameter should be a number between 0 and 15\n");
				else {
					if (sym & 8) play->player ^= 1;
					play_symetry(play, sym & 7);
				}

			// play a serie of moves
			} else if (strcmp(cmd, "play") == 0) {
				string_to_lowercase(param);
				play_game(play, param);

			// force edax to play an opening
			} else if (strcmp(cmd, "force") == 0) {
				string_to_lowercase(param);
				play_force_init(play, param);

			// solve a set of problems
			} else if (strcmp(cmd, "solve") == 0) {
				char problem_file[FILENAME_MAX + 1], *hard_file;
				hard_file = parse_word(param, problem_file, FILENAME_MAX);
				parse_word(hard_file, hard_file, FILENAME_MAX);
				obf_test(play->search, problem_file, hard_file);
				search_set_observer(play->search, edax_observer);

			// convert a set of problems in a .script file to a .obf file
			} else if (strcmp(cmd, "script-to-obf") == 0) {
				char script_file[FILENAME_MAX + 1], *obf_file;
				obf_file = parse_word(param, script_file, FILENAME_MAX);
				parse_word(obf_file, obf_file, FILENAME_MAX);
				script_to_obf(play->search, script_file, obf_file);
				search_set_observer(play->search, edax_observer);

			} else if (strcmp(cmd, "select-hard") == 0) {
				char full_file[FILENAME_MAX + 1], *hard_file;
				hard_file = parse_word(param, full_file, FILENAME_MAX);
				parse_word(hard_file, hard_file, FILENAME_MAX);
				obf_filter(full_file, hard_file);

			// game/position enumeration
			} else if (strcmp(cmd, "count") == 0) {
				char count_cmd[16], *count_param;
				int depth = 10, size = 8;

				count_param = parse_word(param, count_cmd, 15);
				count_param = parse_int(count_param, &depth); BOUND(depth, 1, 90, "max-ply");
				if (count_param) parse_int(count_param, &size); BOUND(size, 6, 8, "board-size");

				if (strcmp(count_cmd, "games") == 0) { // game enumeration
					quick_count_games(play->board, depth, size);
				} else if (strcmp(count_cmd, "positions") == 0) { // position enumeration
					count_positions(play->board, depth, size);
				} else if (strcmp(count_cmd, "shapes") == 0) { // shape enumeration
					count_shapes(play->board, depth, size);
				} else {
					warn("Unknown count command: \"%s %s\"\n", cmd, param);
				}

			} else if (strcmp(cmd, "perft") == 0) {
				int depth = 14;
				depth = string_to_int(param, 10); BOUND(depth, 1, 90, "max-ply");
				count_games(play->board, depth);
			
			// game/position enumeration
			} else if (strcmp(cmd, "estimate") == 0) {
				int n = 1000;
				n = string_to_int(param, 10); BOUND(n, 1, 2000000000, "max-trials");

				estimate_games(play->board, n);
	
			// seek highest mobility
			} else if (strcmp(cmd, "mobility") == 0) {
				int t = 3600; // 1 hour
				t = string_to_int(param, 10); BOUND(t, 1, 3600*24*365*10, "max time");

				seek_highest_mobility(play->board, t);

			// seek a position
			} else if (strcmp(cmd, "seek") == 0) {
				Board target;
				Line solution;
				
				board_set(&target, param);
				line_init(&solution, play->player);
				
				if (seek_position(&target, play->board, &solution)) {
					printf("Solution found:\n");
					line_print(&solution, 200, " ", stdout);
					putchar('\n');
				}
			
			// bench (a serie of low level tests).
			} else if (strcmp(cmd, "bench") == 0) {
				bench();

			// wtest test the engine against wthor theoretical scores
			} else if (strcmp(cmd, "wtest") == 0) {
				wthor_test(param, play->search);

			// make wthor games played by "Edax (Delorme)" as "Etudes" tournament.
			} else if (strcmp(cmd, "edaxify") == 0) {
				wthor_edaxify(param);

			// wtest test the engine against wthor theoretical scores
			} else if (strcmp(cmd, "weval") == 0) {
				wthor_eval(param, play->search, histogram);
				histogram_print(histogram);
				histogram_stats(histogram);
				histogram_to_ppm("weval.ppm", histogram);

			// go think!
			} else if (strcmp(cmd, "go") == 0) {
				if (play_is_game_over(play)) printf("\n*** Game Over ***\n");
				else {
					play_go(play, true);
					printf("\nEdax plays "); move_print(play_get_last_move(play)->x, 0, stdout); putchar('\n');
				}

			// hint for [n] moves
			} else if (strcmp(cmd, "hint") == 0) {
				int n = string_to_int(param, 1); BOUND(n, 1, 60, "n_moves");
				play_hint(play, n);

			// stop thinking
			} else if (strcmp(cmd, "stop") == 0) {
				ui->mode = 3;

			// user move
			} else if (play_user_move(play, cmd)) {
				printf("\nYou play "); move_print(play_get_last_move(play)->x, 0, stdout); putchar('\n');

			// debug pv
			} else if (strcmp(cmd, "debug-pv") == 0) {
				Move move[1];
				if (parse_move(param, play->board, move) != param) {
					search_set_board(play->search, play->board, play->player);
					pv_debug(play->search, move, stdout);
				}
			} else if (strcmp(cmd, "options") == 0) {
					options_dump(stdout);
#ifdef __unix__
			} else if (strcmp(cmd, "resources") == 0) {
				struct rusage u;
				long long t;
	 			getrusage(RUSAGE_SELF, &u);
				t = 1000 * u.ru_utime.tv_sec + u.ru_utime.tv_usec / 1000;
				printf("user cpu time: "); time_print(t, false, stdout); printf("\n");	
				t = 1000 * u.ru_stime.tv_sec + u.ru_stime.tv_usec / 1000;
				printf("system cpu time: "); time_print(t, false, stdout); printf("\n");	
				printf("max resident memory: %ld\n", u.ru_maxrss); 
				printf("page fault without I/O: %ld\n", u.ru_minflt); 
				printf("page fault with I/O: %ld\n", u.ru_majflt); 
				printf("number of input: %ld\n", u.ru_inblock); 
				printf("number of output: %ld\n", u.ru_oublock); 
				printf("number of voluntary context switch: %ld\n", u.ru_nvcsw); 
				printf("number of unvoluntary context switch: %ld\n\n", u.ru_nivcsw); 
#endif		
			// opening name
			} else if (strcmp(cmd, "opening") == 0) {
				const char *name;
				name = play_show_opening_name(play, opening_get_english_name);
				if (name == NULL) name = "?";
				puts(name);  

			// opening name in french
			} else if (strcmp(cmd, "ouverture") == 0) {
				const char *name;
				name = play_show_opening_name(play, opening_get_french_name);
				if (name == NULL) name = "?";
				puts(name); 

			// opening book commands
			} else if (strcmp(cmd, "book") == 0 || strcmp(cmd, "b") == 0) {
				char book_cmd[FILENAME_MAX + 1], *book_param;
				int val_1, val_2;
				Book *book = play->book;

				book->search = play->search;
				book->search->options.verbosity = book->options.verbosity;
				book_param = parse_word(param, book_cmd, FILENAME_MAX);
				// store the last played game
				if (strcmp(book_cmd, "store") == 0) {
					play_store(play);

				// turn book usage on
				} else if (strcmp(book_cmd, "on") == 0) { // learn
					options.book_allowed = true;

				// turn book usage off
				} else if (strcmp(book_cmd, "off") == 0) { // learn
					options.book_allowed = false;

				// set book randomness
				} else if (strcmp(book_cmd, "randomness") == 0) { // learn
					val_1 = 0; book_param = parse_int(book_param, &val_1);
					options.book_randomness = val_1;

				// set book depth (until which to learn)
				} else if (strcmp(book_cmd, "depth") == 0) { // learn
					val_1 = 36; book_param = parse_int(book_param, &val_1);
					book->options.n_empties = 61 - val_1;

				// create a new empty book
				} else if (strcmp(book_cmd, "new") == 0) {
					val_1 = 21; book_param = parse_int(book_param, &val_1);
					val_2 = 36;	book_param = parse_int(book_param, &val_2);
					book_free(book) ;
					book_new(book, val_1, 61 - val_2);

				// load an opening book (binary format) from the disc
				} else if (strcmp(book_cmd, "load") == 0 || strcmp(book_cmd, "open") == 0) {
					book_free(book) ;
					parse_word(book_param, book_file, FILENAME_MAX);
					book_load(book, book_file);

				// save an opening book (binary format) to the disc
				} else if (strcmp(book_cmd, "save") == 0) {
					parse_word(book_param, book_file, FILENAME_MAX);
					book_save(book, book_file);

				// import an opening book (text format)
				} else if (strcmp(book_cmd, "import") == 0) {
					book_free(book);
					parse_word(book_param, book_file, FILENAME_MAX);
					book_import(book, book_file);
					book_link(book);
					book_fix(book);
					book_negamax(book);
					book_sort(book);

				// export an opening book (text format)
				} else if (strcmp(book_cmd, "export") == 0) {
					parse_word(book_param, book_file, FILENAME_MAX);
					book_export(book, book_file);

				// merge an opening book to the current one
				} else if (strcmp(book_cmd, "merge") == 0) {
					Book src[1];
					parse_word(book_param, book_file, FILENAME_MAX);
					src->search = play->search;
					book_load(src, book_file);
					book_merge(book, src);
					book_free(src);
					warn("Book needs to be fixed before usage\n");

				// fix an opening book
				} else if (strcmp(book_cmd, "fix") == 0) {
					book_fix(book); // do nothing (or edax is buggy)
					book_link(book); // links nodes
					book_negamax(book); // negamax nodes
					book_sort(book); // sort moves

				// negamax an opening book
				} else if (strcmp(book_cmd, "negamax") == 0) {
					book_negamax(book); // negamax nodes
					book_sort(book); // sort moves

				// check and correct solved positions of the book
				} else if (strcmp(book_cmd, "correct") == 0) {
					book_correct_solved(book); // do nothing (or edax is buggy)
					book_fix(book); // do nothing (or edax is buggy)
					book_link(book); // links nodes
					book_negamax(book); // negamax nodes
					book_sort(book); // sort moves

				// prune an opening book
				} else if (strcmp(book_cmd, "prune") == 0) {
					book_prune(book); // remove unreachable lines.
					book_fix(book); // do nothing (or edax is buggy)
					book_link(book); // links nodes
					book_negamax(book); // negamax nodes
					book_sort(book); // sort moves

				// show the current position as stored in the book
				} else if (strcmp(book_cmd, "show") == 0) {
					book_show(book, play->board);

				// show book general information
				} else if (strcmp(book_cmd, "info") == 0) {
					book_info(book);

				// show book general information
				} else if (strcmp(book_cmd, "stats") == 0) {
					book_stats(book);


				// set book verbosity
				} else if (strcmp(book_cmd, "verbose") == 0) {
					parse_int(book_param, &book->options.verbosity);
					book->search->options.verbosity = book->options.verbosity;

				// analyze a game from the opening book point of view
				} else if (strcmp(book_cmd, "a") == 0 || strcmp(book_cmd, "analyze") == 0 || strcmp(book_cmd, "analyse") == 0) {
					val_1 = string_to_int(book_param, play->n_game); BOUND(val_1, 1, play->n_game, "depth");
					play_book_analyze(play, val_1);

				// add positions from a game database
				} else if (strcmp(book_cmd, "add") == 0) {
					Base base[1];
					parse_word(book_param, book_file, FILENAME_MAX);
					base_init(base);
					base_load(base, book_file);
					book_add_base(book, base);
					base_free(base);

				// check positions from a game database
				} else if (strcmp(book_cmd, "check") == 0) {
					Base base[1];
					parse_word(book_param, book_file, FILENAME_MAX);
					base_init(base);
					base_load(base, book_file);
					book_check_base(book, base);
					base_free(base);

				// extract positions
				} else if (strcmp(book_cmd, "problem") == 0) {
					val_1 = 24; book_param = parse_int(book_param, &val_1); BOUND(val_1, 0, 60, "number of empties");
					val_2 = 10; book_param = parse_int(book_param, &val_2); BOUND(val_2, 1, 1000000, "number of positions");
					book_extract_positions(book, val_1, val_2);
					
				// extract pv to a game database
				} else if (strcmp(book_cmd, "extract") == 0) {
					Base base[1];
					parse_word(book_param, book_file, FILENAME_MAX);
					base_init(base);
					book_extract_skeleton(book, base);
					base_save(base, book_file);
					base_free(base);

				// add position using the "deviate algorithm"
				} else if (strcmp(book_cmd, "deviate") == 0) {
					val_1 = 2; book_param = parse_int(book_param, &val_1); BOUND(val_1, -129, 129, "relative error");
					val_2 = 4; book_param = parse_int(book_param, &val_2); BOUND(val_2, 0, 65, "absolute error");
					book_deviate(book, play->board, val_1, val_2);

				// add position using the "enhance algorithm"
				} else if (strcmp(book_cmd, "enhance") == 0) {
					val_1 = 2; book_param = parse_int(book_param, &val_1); BOUND(val_1, 0, 129, "midgame error");
					val_2 = 4; book_param = parse_int(book_param, &val_2); BOUND(val_2, 0, 129, "endcut error");
					book_enhance(book, play->board, val_1, val_2);

				// add position by filling hole in the book
				} else if (strcmp(book_cmd, "fill") == 0) {
					val_1 = 1; book_param = parse_int(book_param, &val_1); BOUND(val_1, 1, 61, "fill depth");
					book_fill(book, val_1);

				// add positions by expanding positions with no-link
				} else if (strcmp(book_cmd, "play") == 0) {
					book_play(book);

				// add positions by expanding positions with no-link
				} else if (strcmp(book_cmd, "deepen") == 0) {
					book_deepen(book);

				// add book positions to the hash table
				} else if (strcmp(book_cmd, "feed-hash") == 0) {
					book_feed_hash(book, play->board, play->search);

				// wrong command ?
				} else {
					warn("Unknown book command: \"%s %s\"\n", cmd, param);
				}
				book->options.verbosity = book->search->options.verbosity;
				book->search->options.verbosity = options.verbosity;

			/* base TODO: add more actions... */
			} else if (strcmp(cmd, "base") == 0) {
				char base_file[FILENAME_MAX + 1];
				char base_cmd[512], *base_param;
				Base base[1];

				base_init(base);
				base_param = parse_word(param, base_cmd, 511);
				base_param = parse_word(base_param, base_file, FILENAME_MAX);

				// extract problem from a game base
				if (strcmp(base_cmd, "problem") == 0) {
					char problem_file[FILENAME_MAX + 1];
					int n_empties = 24;
					base_param = parse_int(base_param, &n_empties);
					base_param = parse_word(base_param, problem_file, FILENAME_MAX);

					base_load(base, base_file);
					base_to_problem(base, n_empties, problem_file);

				// extract FEN 
				} else if (strcmp(base_cmd, "tofen") == 0) {
					char problem_file[FILENAME_MAX + 1];
					int n_empties = 24;
					base_param = parse_int(base_param, &n_empties);
					base_param = parse_word(base_param, problem_file, FILENAME_MAX);

					base_load(base, base_file);
					base_to_FEN(base, n_empties, problem_file);
	
				// correct erroneous games
				} else if (strcmp(base_cmd, "correct") == 0) {
					int n_empties = 24;
					base_param = parse_int(base_param, &n_empties);

					base_load(base, base_file);
					base_analyze(base, play->search, n_empties, true);
					remove(base_file);
					base_save(base, base_file);

				// check erroneous games
				} else if (strcmp(base_cmd, "check") == 0) {
					int n_empties = 24;
					base_param = parse_int(base_param, &n_empties);

					base_load(base, base_file);
					base_analyze(base, play->search, n_empties, false);

				// terminate unfinished base
				} else if (strcmp(base_cmd, "complete") == 0) {
					base_load(base, base_file);
					base_complete(base, play->search);
					remove(base_file);
					base_save(base, base_file);

				// convert a base to another format
				} else if (strcmp(base_cmd, "convert") == 0) {
					base_load(base, base_file);
					base_param = parse_word(base_param, base_file, FILENAME_MAX);
					base_save(base, base_file);

				// make a base unique by removing identical games
				} else if (strcmp(base_cmd, "unique") == 0) {
					base_load(base, base_file);
					base_param = parse_word(base_param, base_file, FILENAME_MAX);
					base_unique(base);
					base_save(base, base_file);

				// compare two game bases
				} else if (strcmp(base_cmd, "compare") == 0) {
					char base_file_2[FILENAME_MAX + 1];
					base_param = parse_word(base_param, base_file_2, FILENAME_MAX);
					base_compare(base_file, base_file_2);

				} else {
					warn("Unknown base command: \"%s %s\"\n", cmd, param);
				}

				base_free(base);

			/* edax options */
			} else if (options_read(cmd, param)) {
				options_bound();
				// parallel search changes:
				if (search_count_tasks(play->search) != options.n_task) {
					play_stop_pondering(play);
					search_set_task_number(play->search, options.n_task);
				}

			/* switch to another protocol */
			} else if (strcmp(cmd, "nboard") == 0 && strcmp(param, "1") == 0) {
				free(cmd); free(param);
				play_stop_pondering(play);
				ui->free(ui);
				ui_switch(ui, "nboard");
				ui->init(ui);
				ui->loop(ui);
				return;

			} else if (strcmp(cmd, "xboard") == 0) {
				free(cmd); free(param);
				play_stop_pondering(play);
				ui->free(ui);
				ui_switch(ui, "xboard");
				ui->init(ui);
				ui->loop(ui);
				return;

			} else if (strcmp(cmd, "engine-protocol") == 0 && strcmp(param, "init") == 0) {
				free(cmd); free(param);
				play_stop_pondering(play);
				ui->free(ui);
				ui_switch(ui, "cassio");
				engine_loop();
				return;

			} else if (strcmp(cmd, "protocol_version") == 0) {
				free(cmd); free(param);
				play_stop_pondering(play);
				ui->free(ui);
				ui_switch(ui, "gtp");
				ui->init(ui);
				puts("= 2\n"); fflush(stdout);
				ui->loop(ui);
				return;

#ifdef TUNE_EDAX
			/* edax tuning */
			} else if (strcmp(cmd, "tune") == 0) {
				char problem[FILENAME_MAX];
				char *w_name;
				play_stop_pondering(play);
				w_name = parse_word(param, problem, FILENAME_MAX);
				tune_move_evaluate(play->search, problem, parse_skip_spaces(w_name));
				search_set_observer(play->search, edax_observer);
#endif
			/* illegal cmd/move */
			} else {
				warn("Unknown command/Illegal move: \"%s %s\"\n", cmd, param);
			}
		}
	}
}
Example #9
0
/**
 * @brief ggs_board
 *
 * Parse a "GGS board" from a GGS input text.
 *
 * @param board GGS board.
 * @param text GGS input text.
 * @return 'true' if the text is a valid board.
 */
static bool ggs_board(GGSBoard *board, Text *text)
{
	const char *line = text->line[0];
	char word[WORD_SIZE];
	int ii = 1, i, j;

	if (text->n_lines < 17) return false;

	if (*line == '\0') return false;

	line = parse_word(line, word, WORD_SIZE);
	if (strcmp("/os:", word) != 0) return false;

	if (*line == '\0') return false;
	line = parse_word(line, word, WORD_SIZE);
	board->is_join = (strcmp("join", word) == 0);
	board->is_update = (strcmp("update", word) == 0);

	if ( !board->is_update && !board->is_join) {
		return false;
	}

	if (*line == '\0') return false;
	line = parse_word(line, word, WORD_SIZE);
	board->id = string_duplicate(word);

	if (*line == '\0') return false;
	line = parse_word(line, word, WORD_SIZE);
	ggs_match_type_set(board->match_type, word);

	if (*line) {
		line = parse_word(line, word, WORD_SIZE);
		if (word[1] == '?') {
			board->match_type->is_komi = 0;
			board->komi = 0;
		} else {
			board->match_type->is_komi = 1;
			ggs_parse_double(&board->komi, word + 1);
		}
	}

	if (board->is_join) {
		if (!ggs_parse_int(&board->move_list_n, text->line[1] + 1))
			return false;
		if (board->move_list_n > 0) {
			if (text->n_lines < board->move_list_n + 30)
				return false;
			ii = 5;
			for (i = 0; i < 8; i++) {
	    		++ii;
				for (j = 0; j < 8; j++)
					board->board_init[i * 8 + j] = text->line[ii][4 + j * 2];
			}
			ii += 3;
			board->turn_init = text->line[ii][1];

			for (i = 0; i < board->move_list_n; i++) {
				++ii;
				parse_field(text->line[ii] + 6, word, WORD_SIZE, '/');
				ggs_parse_move(board->move_list + i, word);
			}
		} else ii = 2;
	}
	if (text->n_lines < ii + 14)
		return false;

	line = parse_skip_word(text->line[ii]);
	line = parse_word(line, word, WORD_SIZE);
	ggs_parse_int(&board->move_no, word);
	ggs_parse_move(&board->move, line);

	++ii;
	line = parse_word(text->line[ii], word, WORD_SIZE);
	if (!ggs_player_set(board->player, word + 1, line))
		return false;
	line = parse_skip_word(line + 1);
	line = parse_word(line, word, WORD_SIZE);
	board->color[0] = word[0];
	if (!ggs_parse_clock(board->clock, line))	return false;

	++ii;
	line = parse_word(text->line[ii], word, WORD_SIZE);
	if (!ggs_player_set(board->player + 1, word + 1, line))
		return false;
	line = parse_skip_word(line + 1);
	line = parse_word(line, word, WORD_SIZE);
	board->color[1] = word[0];
	if (!ggs_parse_clock(board->clock + 1, line)) return false;

	ii += 2;

	for (i = 0; i < 8; i++) {
	    ++ii;
		for (j = 0; j < 8; j++)
			board->board[i * 8 + j] = text->line[ii][4 + j * 2];
	}
	ii += 3;
	board->turn = text->line[ii][1];

	if (board->is_join && board->move_list_n == 0) {
		memcpy(board->board_init, board->board, 64);
		board->turn_init = board->turn;
	}

	return true;
}
Example #10
0
void type_dir___cd (char *command_line)


{
	int status;
	char *ptr,full_dir_name [500],dir_name [500],temp [500],temp2 [500];
	struct struct_file_info info;
	struct ext2_dir_entry_2 *dir_entry_ptr;

	dir_entry_ptr=(struct ext2_dir_entry_2 *) (file_info.buffer+file_info.dir_entry_offset);
		
	ptr=parse_word (command_line,dir_name);
	
	if (*ptr==0) {						/* cd alone will enter the highlighted directory */
		strncpy (full_dir_name,dir_entry_ptr->name,dir_entry_ptr->name_len);
		full_dir_name [dir_entry_ptr->name_len]=0;
	}
	else
		ptr=parse_word (ptr,full_dir_name);

	ptr=strchr (full_dir_name,'/');
	
	if (ptr==full_dir_name) {				/* Pathname is from root - Let the general cd do the job */
		sprintf (temp,"cd %s",full_dir_name);type_ext2___cd (temp);return;
	}
	
	if (ptr==NULL) {
		strcpy (dir_name,full_dir_name);
		full_dir_name [0]=0;
	}

	else {
		strncpy (dir_name,full_dir_name,ptr-full_dir_name);
		dir_name [ptr-full_dir_name]=0;
		strcpy (full_dir_name,++ptr);
	}
								/* dir_name contains the current entry, while */
								/* full_dir_name contains the rest */

	strcpy (name_search,dir_name);				/* name_search is used to hold the required entry name */
	
	if (dir_entry_ptr->name_len != strlen (dir_name) ||
	    strncmp (dir_name,dir_entry_ptr->name,dir_entry_ptr->name_len)!=0)
		info=search_dir_entries (&action_name,&status);	/* Search for the entry. Answer in info. */
	else {
		status=FOUND;info=file_info;
	}

	if (status==FOUND) {					/* If found */
		file_info=info;					/* Switch to it, by setting the global file_info */
		dispatch ("remember internal_variable");	/* Move the inode into the objects memory */
		
		dispatch ("followinode");			/* Go to the inode pointed by this directory entry */
		
		if (S_ISLNK (type_data.u.t_ext2_inode.i_mode)) {/* Symbolic link ? */

			if (type_data.u.t_ext2_inode.i_size > 60) {	/* I'm lazy, I guess :-) */
				wprintw (command_win,"Error - Sorry, Only fast symbolic link following is currently supported\n");
				refresh_command_win ();
				return;				
			}
								/* Get the pointed name and append the previous path */

			strcpy (temp2,(unsigned char *) &type_data.u.t_ext2_inode.i_block);
			strcat (temp2,"/");
			strcat (temp2,full_dir_name);

			dispatch ("recall internal_variable");	/* Return to the original inode */
			dispatch ("dir");			/* and to the directory */
			
			sprintf (temp,"cd %s",temp2);		/* And continue from there by dispatching a cd command */
			dispatch (temp);			/* (which can call ourself or the general cd) */
			
			return;
		}

		if (S_ISDIR (type_data.u.t_ext2_inode.i_mode)) { /* Is it an inode of a directory ? */

			dispatch ("dir");			/* Yes - Pass to the pointed directory */

			if (full_dir_name [0] != 0) {		/* And call ourself with the rest of the pathname */
				sprintf (temp,"cd %s",full_dir_name);
				dispatch (temp);
			}
			
			return;
		}
		
		else {						/* If we can't continue from here, we'll just stop */
			wprintw (command_win,"Can\'t continue - Stopping at last inode\n");refresh_command_win ();
			return;
		}
	}
	
	wprintw (command_win,"Error - Directory entry %s not found.\n",dir_name);	/* Hmm, an invalid path somewhere */
	refresh_command_win ();
}
Example #11
0
void type_dir___set (char *command_line)


{
	int found=0;
	unsigned char *ptr,buffer [80],variable [80],value [80],temp [80];
	struct ext2_dir_entry_2 *dir_entry_ptr;
	
	dir_entry_ptr=(struct ext2_dir_entry_2 *) (file_info.buffer+file_info.dir_entry_offset);
	
	ptr=parse_word (command_line,buffer);
	if (*ptr==0) {
		wprintw (command_win,"Error - Missing arguments\n");refresh_command_win ();
		return;
	}
	parse_word (ptr,buffer);
	ptr=strchr (buffer,'=');
	if (ptr==NULL) {
		wprintw (command_win,"Error - Bad syntax\n");refresh_command_win ();return;
	}
	strncpy (variable,buffer,ptr-buffer);variable [ptr-buffer]=0;
	strcpy (value,++ptr);

	if (strcasecmp ("inode",variable)==0) {
		found=1;
		dir_entry_ptr->inode=atol (value);
		wprintw (command_win,"Variable %s set to %lu\n",variable,dir_entry_ptr->inode);refresh_command_win ();

	}

	if (strcasecmp ("rec_len",variable)==0) {
		found=1;
		dir_entry_ptr->rec_len=(unsigned int) atol (value);
		wprintw (command_win,"Variable %s set to %lu\n",variable,dir_entry_ptr->rec_len);refresh_command_win ();

	}

	if (strcasecmp ("name_len",variable)==0) {
		found=1;
		dir_entry_ptr->name_len=(unsigned int) atol (value);
		wprintw (command_win,"Variable %s set to %lu\n",variable,dir_entry_ptr->name_len);refresh_command_win ();

	}

	if (strcasecmp ("name",variable)==0) {
		found=1;
		if (strlen (value) > dir_entry_ptr->name_len) {
			wprintw (command_win,"Error - Length of name greater then name_len\n");
			refresh_command_win ();return;
		}
		strncpy (dir_entry_ptr->name,value,strlen (value));
		wprintw (command_win,"Variable %s set to %s\n",variable,value);refresh_command_win ();

	}
	
	if (found) {
		wattrset (show_pad,A_REVERSE);
		strncpy (temp,dir_entry_ptr->name,dir_entry_ptr->name_len);
		temp [dir_entry_ptr->name_len]=0;
		wmove (show_pad,file_info.dir_entry_num,0);
		wprintw (show_pad,"inode = %-8lu rec_len = %-4lu name_len = %-3lu name = %s\n",
			 dir_entry_ptr->inode,dir_entry_ptr->rec_len,dir_entry_ptr->name_len,temp);
		wattrset (show_pad,A_NORMAL);
		show_pad_info.line=file_info.dir_entry_num-show_pad_info.display_lines/2;
		refresh_show_pad ();
		show_dir_status ();
	}
	
	else {
		wprintw (command_win,"Error - Variable %s not found\n",variable);
		refresh_command_win ();
	}

}
Example #12
0
void type_dir___cd (char *command_line)

/*
	Changes to a directory, relative to the current directory.

	This is a complicated operation, so I would repeat here the explanation from the design and
	implementation document.

1.	The path is checked that it is not an absolute path (from /). If it is, we let the general cd to do the job by
	calling directly type_ext2___cd.

2.	The path is divided into the nearest path and the rest of the path. For example, cd 1/2/3/4 is divided into
	1 and into 2/3/4.

3.	It is the first part of the path that we need to search for in the current directory. We search for it using
	search_dir_entries, which accepts the action_name function as the client function. 

4.	search_dir_entries will scan the entire entries and will call our action_name function for each entry.
	In action_name, the required name will be checked against the name of the current entry, and FOUND will be
	returned when a match occurs.

5.	If the required entry is found, we dispatch a remember command to insert the current inode (remember that
	type_data is still intact and contains the inode of the current directory) into the object memory.
	This is required to easily support symbolic links - If we find later that the inode pointed by the entry is
	actually a symbolic link, we'll need to return to this point, and the above inode doesn't have (and can't have,
	because of hard links) the information necessary to "move back".

6.	We then dispatch a followinode command to reach the inode pointed by the required entry. This command will
	automatically change the type to ext2_inode - We are now at an inode, and all the inode commands are available.

7.	We check the inode's type to see if it is a directory. If it is, we dispatch a dir command to "enter the directory",
	and recursively call ourself (The type is dir again) by dispatching a cd command, with the rest of the path
	as an argument.
	
8.	If the inode's type is a symbolic link (only fast symbolic link were meanwhile implemented. I guess this is
	typically the case.), we note the path it is pointing at, the saved inode is recalled, we dispatch dir to
	get back to the original directory, and we call ourself again with the link path/rest of the path argument.

9.	In any other case, we just stop at the resulting inode.

*/

{
	int status;
	char *ptr,full_dir_name [500],dir_name [500],temp [500],temp2 [500];
	struct struct_file_info info;
	struct ext2_dir_entry_2 *dir_entry_ptr;

	dir_entry_ptr=(struct ext2_dir_entry_2 *) (file_info.buffer+file_info.dir_entry_offset);
		
	ptr=parse_word (command_line,dir_name);
	
	if (*ptr==0) {						/* cd alone will enter the highlighted directory */
		strncpy (full_dir_name,dir_entry_ptr->name,dir_entry_ptr->name_len);
		full_dir_name [dir_entry_ptr->name_len]=0;
	}
	else
		ptr=parse_word (ptr,full_dir_name);

	ptr=strchr (full_dir_name,'/');
	
	if (ptr==full_dir_name) {				/* Pathname is from root - Let the general cd do the job */
		sprintf (temp,"cd %s",full_dir_name);type_ext2___cd (temp);return;
	}
	
	if (ptr==NULL) {
		strcpy (dir_name,full_dir_name);
		full_dir_name [0]=0;
	}

	else {
		strncpy (dir_name,full_dir_name,ptr-full_dir_name);
		dir_name [ptr-full_dir_name]=0;
		strcpy (full_dir_name,++ptr);
	}
								/* dir_name contains the current entry, while */
								/* full_dir_name contains the rest */

	strcpy (name_search,dir_name);				/* name_search is used to hold the required entry name */
	
	if (dir_entry_ptr->name_len != strlen (dir_name) ||
	    strncmp (dir_name,dir_entry_ptr->name,dir_entry_ptr->name_len)!=0)
		info=search_dir_entries (&action_name,&status);	/* Search for the entry. Answer in info. */
	else {
		status=FOUND;info=file_info;
	}

	if (status==FOUND) {					/* If found */
		file_info=info;					/* Switch to it, by setting the global file_info */
		dispatch ("remember internal_variable");	/* Move the inode into the objects memory */
		
		dispatch ("followinode");			/* Go to the inode pointed by this directory entry */
		
		if (S_ISLNK (type_data.u.t_ext2_inode.i_mode)) {/* Symbolic link ? */

			if (type_data.u.t_ext2_inode.i_size > 60) {	/* I'm lazy, I guess :-) */
				wprintw (command_win,"Error - Sorry, Only fast symbolic link following is currently supported\n");
				refresh_command_win ();
				return;				
			}
								/* Get the pointed name and append the previous path */

			strcpy (temp2,(unsigned char *) &type_data.u.t_ext2_inode.i_block);
			strcat (temp2,"/");
			strcat (temp2,full_dir_name);

			dispatch ("recall internal_variable");	/* Return to the original inode */
			dispatch ("dir");			/* and to the directory */
			
			sprintf (temp,"cd %s",temp2);		/* And continue from there by dispatching a cd command */
			dispatch (temp);			/* (which can call ourself or the general cd) */
			
			return;
		}

		if (S_ISDIR (type_data.u.t_ext2_inode.i_mode)) { /* Is it an inode of a directory ? */

			dispatch ("dir");			/* Yes - Pass to the pointed directory */

			if (full_dir_name [0] != 0) {		/* And call ourself with the rest of the pathname */
				sprintf (temp,"cd %s",full_dir_name);
				dispatch (temp);
			}
			
			return;
		}
		
		else {						/* If we can't continue from here, we'll just stop */
			wprintw (command_win,"Can\'t continue - Stopping at last inode\n");refresh_command_win ();
			return;
		}
	}
	
	wprintw (command_win,"Error - Directory entry %s not found.\n",dir_name);	/* Hmm, an invalid path somewhere */
	refresh_command_win ();
}
void help (char *command_line)

{
	int i,max_line=0;
	char argument [80],*ptr;

	werase (show_pad);wmove (show_pad,0,0);

	ptr=parse_word (command_line,argument);

	if (*ptr!=0) {
		 ptr=parse_word (ptr,argument);
		 if (*argument!=0) {
			 detailed_help (argument);
			 return;
		}
	}

	if (current_type!=NULL) {

		wprintw (show_pad,"Type %s specific commands:\n",current_type->name);max_line++;

		if (current_type->type_commands.last_command==-1) {
			wprintw (show_pad,"\nnone\n");max_line+=2;
		}
		else
			for (i=0;i<=current_type->type_commands.last_command;i++) {
				if (i%5==0) {
					wprintw (show_pad,"\n");max_line++;
				}
				wprintw (show_pad,"%-13s",current_type->type_commands.names [i]);
				if (i%5!=4)
					wprintw (show_pad,";  ");
			}

		wprintw (show_pad,"\n\n");max_line+=2;
	}

	if (ext2_commands.last_command != -1) {
		wprintw (show_pad,"ext2 filesystem general commands: \n");max_line++;
		for (i=0;i<=ext2_commands.last_command;i++) {
			if (i%5==0) {
				wprintw (show_pad,"\n");max_line++;
			}
			wprintw (show_pad,"%-13s",ext2_commands.names [i]);
			if (i%5!=4)
				wprintw (show_pad,";  ");

		}
		wprintw (show_pad,"\n\n");max_line+=2;
	}

	wprintw (show_pad,"General commands: \n");

	for (i=0;i<=general_commands.last_command;i++) {
		if (i%5==0) {
			wprintw (show_pad,"\n");max_line++;
		}
		wprintw (show_pad,"%-13s",general_commands.names [i]);
		if (i%5!=4)
			wprintw (show_pad,";  ");
	}

	wprintw (show_pad,"\n\n");max_line+=2;

	wprintw (show_pad,"EXT2ED ver %s (%s)\n",E2FSPROGS_VERSION, E2FSPROGS_DATE);
	wprintw (show_pad,"Copyright (C) 1995 Gadi Oxman\n");
	wprintw (show_pad,"Reviewed 2001 Christian Bac\n");
	wprintw (show_pad,"Modified and enchanced by Theodore Ts'o, 2002\n");
	wprintw (show_pad,"EXT2ED is hereby placed under the terms of the GNU General Public License.\n\n");
	wprintw (show_pad,"EXT2ED was programmed as a student project in the software laboratory\n");
	wprintw (show_pad,"of the faculty of electrical engineering in the\n");
	wprintw (show_pad,"Technion - Israel Institute of Technology\n");
	wprintw (show_pad,"with the guide of Avner Lottem and Dr. Ilana David.\n");

	max_line+=10;

	show_pad_info.line=0;show_pad_info.max_line=max_line;

	werase (show_win);wmove (show_win,0,0);
	wprintw (show_win,"EXT2ED help");

	refresh_show_win ();
	refresh_show_pad ();
}
Example #14
0
// Parses command together with its arguments, returns ParseResult enum
ParseResult parse_command(FILE *stream)
{
	ParseResult command = {QUIT, NULL, {-1, -1, -1}};
	char *input = NULL;

	char line[BUF_LEN];
	if (stream == NULL)
		return command;

	char *readline = fgets(line, BUF_LEN, stream);
	if (readline == NULL)
		return command;

	command.result = IGNORE;

	// Skip spaces on the beginning
	input = &line[0];
	while (input[0] == ' ')
		input++;

	if (!isalpha(input[0]))
		return command; // No command supplied

	switch (input[0]) {
	case 'i': // insert
		if (prefix("insert", input)) {
			input += (strlen("insert"));
			if (!is_sp(input[0]))
				return command;

			while (input[0] == ' ')
				input++;

			int end_pos = parse_word(input);
			if (!end_pos)
				return command;

			command.result = INSERT;
			command.arg =
			    (char *)malloc(end_pos + 1 * sizeof(char));
			strncpy(command.arg, input, end_pos);
			command.arg[end_pos] = 0;
		}
		break;
	case 'f': // find
		if (prefix("find", input)) {
			input += (strlen("find"));
			if (!is_sp(input[0]))
				return command;

			while (input[0] == ' ')
				input++;

			int end_pos = parse_word(input);
			if (!end_pos)
				return command;

			command.result = FIND;
			command.arg =
			    (char *)malloc(end_pos + 1 * sizeof(char));
			strncpy(command.arg, input, end_pos);
			command.arg[end_pos] = 0;
		}
		break;
	case 'c': // clear
		if (prefix("clear", input)) {
			input += (strlen("clear"));
			while (is_sp(input[0]))
				input++;

			if (input[0] == '\n')
				command.result = CLEAR;
		}
		break;
	case 'd': // delete
		if (prefix("delete", input)) {
			input += (strlen("delete"));
			if (!is_sp(input[0]))
				return command; // Check for space delimiter
			while (is_sp(input[0]))
				input++;
			int arg = parse_number(input);
			command.result = DELETE;
			command.args[0] = arg;
		}
		break;
	case 'p': // prev
		if (prefix("prev", input)) {
			input += (strlen("prev"));
			while (is_sp(input[0]))
				input++;
			int res = parse_number_args(input, &command);
			if (res != -1) {
				command.result = PREV;
			}
		}
		break;
	default:
		break;
	}
	return command;
}
Example #15
0
void set (char *command_line)

{
	unsigned short *int_ptr;
	unsigned char *char_ptr;
	unsigned long *long_ptr,offset=0;
	int i,len, found=0;
	char *ptr,buffer [80],variable [80],value [80];
	
	if (device_handle==NULL) {
		wprintw (command_win,"Error - No device opened\n");refresh_command_win ();
		return;
	}

	if (current_type==NULL) {
		hex_set (command_line);
		return;
	}

	ptr=parse_word (command_line,buffer);
	if (ptr==NULL || *ptr==0) {
		wprintw (command_win,"Error - Missing arguments\n");refresh_command_win ();
		return;
	}
	parse_word (ptr,buffer);
	ptr=strchr (buffer,'=');
	if (ptr==NULL) {
		wprintw (command_win,"Error - Bad syntax\n");refresh_command_win ();return;
	}
	strncpy (variable,buffer,ptr-buffer);variable [ptr-buffer]=0;
	strcpy (value,++ptr);

	if (current_type==NULL) {
		wprintw (command_win,"Sorry, not yet supported\n");refresh_command_win ();return;
	}
	
	for (i=0;i<current_type->fields_num && !found;i++) {
		if (strcmp (current_type->field_names [i],variable)==0) {
			found=1;
			ptr=type_data.u.buffer+offset;
			len = current_type->field_lengths [i];
			switch (current_type->field_types [i]) {
			case FIELD_TYPE_INT:
				set_int(len, ptr, variable, value);
				break;
			case FIELD_TYPE_UINT:
				set_uint(len, ptr, variable, value);
				break;
			case FIELD_TYPE_CHAR:
				set_char(len, ptr, variable, value);
				break;
			default:
				wprintw (command_win,
					 "set: unhandled type %d\n",
					 current_type->field_types [i]);
				break;
			}
			refresh_command_win ();
		}
		offset+=current_type->field_lengths [i];
	}
	if (found)
		dispatch ("show");
	else {
		wprintw (command_win,"Error - Variable %s not found\n",variable);
		refresh_command_win ();
	}
}
Example #16
0
File: fl.c Project: pavel-krush/fl
void do_command(const char *command_line) {
	skip_spaces(&command_line);

	char *command = parse_word(&command_line);
	if (command == NULL)
		return;

	skip_spaces(&command_line);

	int command_length = strlen(command);

	#define CMD_COND1(str) ( ( command_length == sizeof(str) - 1 && !strcmp(command, str) ) )
	#define CMD_COND2(str) ( ( command_length == 1 && command[0] == str[0] ) || ( ( command_length == sizeof(str) - 1 ) && !strcmp(command, str) ) )

	#define  PARSE_ID(fail_label) int *id; id = parse_int(&command_line); \
		if (!id) { printf("ID required\n"); goto fail_label; } \
		if (*id < 0 || *id >= files_count) { printf("Invalid ID. Valid values are from %d to %d\n", 0, files_count); goto fail_label; }

	if (CMD_COND2("help")) {
		exec_help();
	}
	else if (CMD_COND2("info")) {
		exec_info();
	}
	// open ID mode
	else if (CMD_COND2("open")) {
		char *mode = NULL;
		PARSE_ID(open_cleanup)

		skip_spaces(&command_line);

		mode = parse_until_space(&command_line);
		if (!mode) {
			printf("MODE required\n");
			goto open_cleanup;
		}

		exec_open(*id, mode);

		open_cleanup:
			if (id) free(id);
			if (mode) free(mode);
			goto cleanup;
	}
	else if (CMD_COND2("lock")) {
		char *operation = NULL;

		PARSE_ID(lock_cleanup)

		skip_spaces(&command_line);

		operation = parse_until_space(&command_line);
		if (!operation) {
			printf("Operation required\n");
			goto lock_cleanup;
		}

		int op;

		if (!strcmp(operation, "shnb"))
			op = LOCK_SH | LOCK_NB;
		else if (!strcmp(operation, "sh"))
			op = LOCK_SH;
		else if (!strcmp(operation ,"exnb"))
			op = LOCK_EX | LOCK_NB;
		else if (!strcmp(operation, "ex"))
			op = LOCK_EX;
		else if (!strcmp(operation, "unnb"))
			op = LOCK_UN | LOCK_NB;
		else if (!strcmp(operation, "un"))
			op = LOCK_UN;
		else {
			printf("Invalid <operation>\n");
			goto lock_cleanup;
		}

		exec_lock(*id, op);

		lock_cleanup:
			if (id) free(id);
			if (operation) free(operation);
			goto cleanup;
	}
	else if (CMD_COND2("close")) {
		PARSE_ID(close_cleaup)

		exec_close(*id);

		close_cleaup:
			if (id) free(id);
			goto cleanup;
	}
	else if (CMD_COND2("seek")) {
		int *offset = NULL;
		char *whence_str = NULL;

		PARSE_ID(seek_cleanup)

		skip_spaces(&command_line);

		int sign = 1;
		if (command_line[0] == '-') {
			sign = -1;
			command_line++;
		}

		offset = parse_int(&command_line);
		if (!offset) {
			printf("Invalid <offset>\n");
			goto seek_cleanup;
		}
		*offset = *offset * sign;

		skip_spaces(&command_line);

		whence_str = parse_until_space(&command_line);
		if (!whence_str) {
			printf("Invalid <whence>. Valid values are: set, end, cur\n");
			goto seek_cleanup;
		}

		int whence = 0;

		if (!strcmp(whence_str, "set")) {
			whence = SEEK_SET;
		}
		else if (!strcmp(whence_str, "end")) {
			whence = SEEK_END;
		}
		else if (!strcmp(whence_str, "cur")) {
			whence = SEEK_CUR;
		}

		exec_seek(*id, *offset, whence);

		seek_cleanup:
			if (id) free(id);
			if (offset) free(offset);
			if (whence_str) free(whence_str);
			goto cleanup;
	}
	else if (CMD_COND2("tell")) {
		PARSE_ID(tell_cleanup)

		skip_spaces(&command_line);

		exec_tell(*id);

		tell_cleanup:
			if (id) free(id);
			goto cleanup;
	}
	else if (CMD_COND2("write")) {
		printf("not implemented\n");
		goto write_cleanup;
		write_cleanup:
			goto cleanup;
	}
	else if (CMD_COND2("read")) {
		int *length = NULL;
		PARSE_ID(read_cleanup);

		skip_spaces(&command_line);

		int hex = 0;

		if (command_line[0] == 'x') {
			hex = 1;
			command_line++;
			skip_spaces(&command_line);
		}

		length = parse_int(&command_line);
		if (!length) {
			printf("Invalid <length>\n");
			goto read_cleanup;
		}

		exec_read(*id, *length, hex);

		read_cleanup:
			if (id) free(id);
			if (length) free(length);
			goto cleanup;
	}
	else if (CMD_COND1("truncate")) {
		int *length = NULL;
		PARSE_ID(truncate_cleanup)

		skip_spaces(&command_line);

		length = parse_int(&command_line);
		if (!length) {
			printf("Invalid <length>\n");
			goto truncate_cleanup;
		}

		exec_truncate(*id, *length);

		truncate_cleanup:
			if (id) free(id);
			if (length) free(length);
			goto cleanup;
	}
	else {
		printf("Unknown command\n");
	}

cleanup:
	free(command);
}
Example #17
0
void hex_set (char *command_line)

{
	unsigned char tmp;
	char *ptr,buffer [80],*ch_ptr;
	int mode=HEX;
	
	ptr=parse_word (command_line,buffer);
	if (*ptr==0) {
		wprintw (command_win,"Error - Argument not specified\n");refresh_command_win ();return;
	}

	ptr=parse_word (ptr,buffer);

	if (strcasecmp (buffer,"text")==0) {
		mode=TEXT;
		strcpy (buffer,ptr);
	}

	else if (strcasecmp (buffer,"hex")==0) {
		mode=HEX;
		ptr=parse_word (ptr,buffer);
	}

	if (*buffer==0) {
		wprintw (command_win,"Error - Data not specified\n");refresh_command_win ();return;
	}

	if (mode==HEX) {
		do {
			tmp=(unsigned char) strtol (buffer,NULL,16);
			type_data.u.buffer [type_data.offset_in_block]=tmp;
			type_data.offset_in_block++;
			ptr=parse_word (ptr,buffer);
			if (type_data.offset_in_block==file_system_info.block_size) {
				if (*ptr) {
					wprintw (command_win,"Error - Ending offset outside block, only partial string changed\n");
					refresh_command_win ();
				}
				type_data.offset_in_block--;
			}
		} while (*buffer) ;
	}

	else {
		ch_ptr=buffer;
		while (*ch_ptr) {
			tmp=(unsigned char) *ch_ptr++;
			type_data.u.buffer [type_data.offset_in_block]=tmp;
			type_data.offset_in_block++;
			if (type_data.offset_in_block==file_system_info.block_size) {
				if (*ch_ptr) {
					wprintw (command_win,"Error - Ending offset outside block, only partial string changed\n");
					refresh_command_win ();
				}
				type_data.offset_in_block--;
			}
		}
	}
	
	strcpy (buffer,"show");dispatch (buffer);
}
Example #18
0
/*
 * BEGIN_MANUAL_ENTRY()
 *
 *	int smt_parse_arg(struct s_smc *,char _far *keyword,int type,
		char _far *value)
 *
 *	parse SMT parameter
 *	*keyword
 *		pointer to keyword, must be \0, \n or \r terminated
 *	*value	pointer to value, either char * or u_long *
 *		if char *
 *			pointer to value, must be \0, \n or \r terminated
 *		if u_long *
 *			contains binary value
 *
 *	type	0: integer
 *		1: string
 *	return
 *		0	parameter parsed ok
 *		!= 0	error
 *	NOTE:
 *		function can be called with DS != SS
 *
 *
 * END_MANUAL_ENTRY()
 */
int smt_parse_arg(struct s_smc *smc, char _far *keyword, int type,
		  char _far *value)
{
	char		keybuf[MAX_VAL+1];
	char		valbuf[MAX_VAL+1];
	char		c ;
	char 		*p ;
	char		*v ;
	char		*d ;
	u_long		val = 0 ;
	struct s_ptab	*pt ;
	int		st ;
	int		i ;

	/*
	 * parse keyword
	 */
	if ((st = parse_word(keybuf,keyword)))
		return(st) ;
	/*
	 * parse value if given as string
	 */
	if (type == 1) {
		if ((st = parse_word(valbuf,value)))
			return(st) ;
	}
	/*
	 * search in table
	 */
	st = 0 ;
	for (pt = ptab ; (v = pt->pt_name) ; pt++) {
		for (p = keybuf ; (c = *p) ; p++,v++) {
			if (c != *v)
				break ;
		}
		if (!c && !*v)
			break ;
	}
	if (!v)
		return(-1) ;
#if	0
	printf("=>%s<==>%s<=\n",pt->pt_name,valbuf) ;
#endif
	/*
	 * set value in MIB
	 */
	if (pt->pt_type)
		val = parse_num(type,value,valbuf,pt->pt_min,pt->pt_max,1) ;
	switch (pt->pt_num) {
	case 0 :
		v = valbuf ;
		d = (char *) smc->mib.fddiPRPMFPasswd ;
		for (i = 0 ; i < (signed)sizeof(smc->mib.fddiPRPMFPasswd) ; i++)
			*d++ = *v++ ;
		DB_MAIN("SET %s = %s\n",pt->pt_name,smc->mib.fddiPRPMFPasswd) ;
		break ;
	case 1 :
		v = valbuf ;
		d = (char *) smc->mib.fddiSMTUserData ;
		for (i = 0 ; i < (signed)sizeof(smc->mib.fddiSMTUserData) ; i++)
			*d++ = *v++ ;
		DB_MAIN("SET %s = %s\n",pt->pt_name,smc->mib.fddiSMTUserData) ;
		break ;
	case 2 :
		smc->mib.p[PA].fddiPORTLer_Cutoff = (u_char) val ;
		DB_MAIN("SET %s = %d\n",
			pt->pt_name,smc->mib.p[PA].fddiPORTLer_Cutoff) ;
		break ;
	case 3 :
		smc->mib.p[PB].fddiPORTLer_Cutoff = (u_char) val ;
		DB_MAIN("SET %s = %d\n",
			pt->pt_name,smc->mib.p[PB].fddiPORTLer_Cutoff) ;
		break ;
	case 4 :
		smc->mib.p[PA].fddiPORTLer_Alarm = (u_char) val ;
		DB_MAIN("SET %s = %d\n",
			pt->pt_name,smc->mib.p[PA].fddiPORTLer_Alarm) ;
		break ;
	case 5 :
		smc->mib.p[PB].fddiPORTLer_Alarm = (u_char) val ;
		DB_MAIN("SET %s = %d\n",
			pt->pt_name,smc->mib.p[PB].fddiPORTLer_Alarm) ;
		break ;
	case 6 :			/* TMAX */
		DB_MAIN("SET %s = %d\n",pt->pt_name,val) ;
		smc->mib.a[PATH0].fddiPATHT_MaxLowerBound =
			(u_long) -MS2BCLK((long)val) ;
		break ;
	case 7 :			/* TMIN */
		DB_MAIN("SET %s = %d\n",pt->pt_name,val) ;
		smc->mib.m[MAC0].fddiMACT_Min =
			(u_long) -MS2BCLK((long)val) ;
		break ;
	case 8 :			/* TREQ */
		DB_MAIN("SET %s = %d\n",pt->pt_name,val) ;
		smc->mib.a[PATH0].fddiPATHMaxT_Req =
			(u_long) -MS2BCLK((long)val) ;
		break ;
	case 9 :			/* TVX */
		DB_MAIN("SET %s = %d \n",pt->pt_name,val) ;
		smc->mib.a[PATH0].fddiPATHTVXLowerBound =
			(u_long) -US2BCLK((long)val) ;
		break ;
#ifdef	ESS
	case 10 :			/* SBAPAYLOAD */
		DB_MAIN("SET %s = %d\n",pt->pt_name,val) ;
		if (smc->mib.fddiESSPayload != val) {
			smc->ess.raf_act_timer_poll = TRUE ;
			smc->mib.fddiESSPayload = val ;
		}
		break ;
	case 11 :			/* SBAOVERHEAD */
		DB_MAIN("SET %s = %d\n",pt->pt_name,val) ;
		smc->mib.fddiESSOverhead = val ;
		break ;
	case 12 :			/* MAXTNEG */
		DB_MAIN("SET %s = %d\n",pt->pt_name,val) ;
		smc->mib.fddiESSMaxTNeg = (u_long) -MS2BCLK((long)val) ;
		break ;
	case 13 :			/* MINSEGMENTSIZE */
		DB_MAIN("SET %s = %d\n",pt->pt_name,val) ;
		smc->mib.fddiESSMinSegmentSize = val ;
		break ;
	case 14 :			/* SBACATEGORY */
		DB_MAIN("SET %s = %d\n",pt->pt_name,val) ;
		smc->mib.fddiESSCategory =
			(smc->mib.fddiESSCategory & 0xffff) |
			((u_long)(val << 16)) ;
		break ;
	case 15 :			/* SYNCHTXMODE */
		/* do not use memcmp(valbuf,"ALL",3) because DS != SS */
		if (valbuf[0] == 'A' && valbuf[1] == 'L' && valbuf[2] == 'L') {
			smc->mib.fddiESSSynchTxMode = TRUE ;
			DB_MAIN("SET %s = %s\n",pt->pt_name,valbuf) ;
		}
		/* if (!memcmp(valbuf,"SPLIT",5)) { */
		if (valbuf[0] == 'S' && valbuf[1] == 'P' && valbuf[2] == 'L' &&
			valbuf[3] == 'I' && valbuf[4] == 'T') {
			DB_MAIN("SET %s = %s\n",pt->pt_name,valbuf) ;
			smc->mib.fddiESSSynchTxMode = FALSE ;
		}
		break ;
#endif
#ifdef	SBA
	case 16 :			/* SBACOMMAND */
		/* if (!memcmp(valbuf,"START",5)) { */
		if (valbuf[0] == 'S' && valbuf[1] == 'T' && valbuf[2] == 'A' &&
			valbuf[3] == 'R' && valbuf[4] == 'T') {
			DB_MAIN("SET %s = %s\n",pt->pt_name,valbuf) ;
			smc->mib.fddiSBACommand = SB_START ;
		}
		/* if (!memcmp(valbuf,"STOP",4)) { */
		if (valbuf[0] == 'S' && valbuf[1] == 'T' && valbuf[2] == 'O' &&
			valbuf[3] == 'P') {
			DB_MAIN("SET %s = %s\n",pt->pt_name,valbuf) ;
			smc->mib.fddiSBACommand = SB_STOP ;
		}
		break ;
	case 17 :			/* SBAAVAILABLE */
		DB_MAIN("SET %s = %d\n",pt->pt_name,val) ;
		smc->mib.fddiSBAAvailable = (u_char) val ;
		break ;
#endif
	}
	return(0) ;
}