int test_qtostr(testspec_t *t, FILE *ofp)
{
  mp_rat    in[2];
  long      radix;
  mp_result res, len;

  if(!parse_rat_values(t, in, NULL, NULL))
    return imath_errno = MP_BADARG, 0;

  trim_line(t->input[1]);
  if(!read_long(&radix, t->input[1]))
    return imath_errno = MP_BADARG, 0;

  if(radix < MP_MIN_RADIX || radix > MP_MAX_RADIX) {
    fprintf(stderr, "Line %d: Radix %ld out of range\n", 
	    t->line, radix);
    return imath_errno = MP_RANGE, 0;
  }

  trim_line(t->output[0]);
  len = mp_rat_string_len(in[0], radix);

  if((res = mp_rat_to_string(in[0], radix, g_output, len)) != MP_OK)
    return imath_errno = res, 0;

  if(strcmp(t->output[0], g_output) != 0)
    return imath_errno = OTHER_ERROR, 0;

  return 1;
}
int test_to_uns(testspec_t *t, FILE *ofp)
{
  mp_int in[1];
  int    test_len, out_len;
  mp_result res;

  if(!parse_int_values(t, in, NULL, NULL))
    return imath_errno = MP_BADARG, 0;

  trim_line(t->output[0]);
  if((out_len = parse_binary(t->output[0], g_bin1, sizeof(g_bin1))) < 0)
    return imath_errno = MP_BADARG, 0;
  
  if((test_len = mp_int_unsigned_len(in[0])) != out_len) {
    sprintf(g_output, "Output lengths do not match (want %d, got %d)",
	    test_len, out_len);
    return imath_errno = OTHER_ERROR, 0;
  }

  if((res = mp_int_to_unsigned(in[0], g_bin2, sizeof(g_bin2))) != MP_OK)
    return imath_errno = res, 0;

  if(memcmp(g_bin1, g_bin2, test_len) != 0) {
    int pos = 0, i;

    for(i = 0; i < test_len - 1; ++i)
      pos += sprintf(g_output + pos, "%d.", g_bin2[i]);

    sprintf(g_output + pos, "%d", g_bin2[i]);
    return imath_errno = OTHER_ERROR, 0;
  }

  return 1;
}
Beispiel #3
0
int load_config(const char *config_file)
{
    int ret = 0;
    FILE *fp = NULL;
    char *name, *value;

    if(config_file == NULL)
    {
        fprintf(stderr, "config file is null.\n");
        return -1;
    }
    fp = fopen(config_file, "r");
    if(NULL == fp)
    {
        fprintf(stderr, "open config file failed!\n");
        return -1;
    }

    while(read_line(fp, line, LINE_LEN) > 0)
    {
        //printf("%s\n", line);
        if(trim_line(line, &name, &value) == 0)
        {
           // printf("name:%s\t\tvalue:%s\n", name, value);
            if(parse(name, value) !=0)
                fprintf(stderr, "unmach config:%s =  %s\n", name, value);
        }
    }
    fclose(fp);

    return 0;
}
Beispiel #4
0
int	read_tag_line(
    FILE	*fp,
    char	**tagp, 
    char        **valp
)
{
    char	*lp, *lp2;

    while (fgets(lp = tag_linebuf, BUFSIZ, fp)) {
	tag_line_num++;
	skip_white(lp);		/* lp = trim_line(lp); */
	if (!*lp || *lp == '\n' || is_comment_char(*lp))
	    continue;
	if (!(lp2 = strchr(lp, TAG_END_CHAR))) {
	    continue;
	}
	*lp2++ = 0;
	lp2 = trim_line(lp2);

	*tagp = lp;
	*valp = *lp2 ? lp2 : 0;
	return tag_line_num;
    }
    *tagp = *valp = 0;

    return (ferror(fp)) ? -1 : 0;
}
int test_tostr(testspec_t *t, FILE *ofp)
{
  mp_int    in[2];
  int       radix;
  mp_result res, len;

  if(!parse_int_values(t, in, NULL, NULL))
    return imath_errno = MP_BADARG, 0;

  if((res = mp_int_to_int(in[1], &radix)) != MP_OK)
    return imath_errno = MP_BADARG, 0;

  if(radix < MP_MIN_RADIX || radix > MP_MAX_RADIX)
    return imath_errno = MP_RANGE, 0;

  trim_line(t->output[0]);

  len = mp_int_string_len(in[0], radix);

  if((res = mp_int_to_string(in[0], radix, g_output, len)) != MP_OK)
    return imath_errno = res, 0;

  if(strcmp(t->output[0], g_output) != 0) 
    return imath_errno = OTHER_ERROR, 0;

  return 1;
}
Beispiel #6
0
/** match_stdin
 * Reads up to the maximum number of lines from standard input
 * 
 * Return Value:
 *     int - the number of matches found or the number of lines without matches 
 * 	     if the -r flag was used
 *     struct Globals *gl - the "global" variables for this search
 */
int 
match_stdin(struct counters *counter, struct Globals *gl){
	char *input_line;
	int count = 0;
	int status;
	int matches = 0;
	
	unsigned int my_flags;
	unsigned int num_chars;
	int max_lines;
	my_flags = gl->my_flags;
	num_chars = gl->num_chars;
	max_lines = gl->max_lines;
	
	input_line = calloc(sizeof(char), num_chars);

	counter->files_read++;
	
	while(matches != max_lines && fgets(input_line, num_chars, stdin) != NULL){
		count++;
		trim_line(input_line);
		status = match_line(input_line, &counter, gl);
		if(status == MATCH && (my_flags&REVERSE_SELECTION) != REVERSE_SELECTION){
			/* Increments the match counter if a match was found and
			   the reverse flag was not chosen */
			if((my_flags&SUMMARY) != SUMMARY){
				/* Prints out the line if the summary flag was not chosen */
				pthread_mutex_lock(&mu);
				/* Since the server does not read from standard in, no check 
				   needs to be done here. */ 
				fprintf(stdout, "%d: %s\n", count, input_line);
				pthread_mutex_unlock(&mu);
			}
			matches++;
		}else if(status == NO_MATCH 
			    && (my_flags&REVERSE_SELECTION) == REVERSE_SELECTION){
			/* Increments the match counter if a match was not found
			   and the reverse flag was chosen */
			if((my_flags&SUMMARY) != SUMMARY){
				/* Prints out the line if the summary flag was not chosen */
				pthread_mutex_lock(&mu);
				/* Since the server does not read from standard in, no check 
				   needs to be done here. */ 
				fprintf(stdout, "%d: %s\n", count, input_line);
				pthread_mutex_unlock(&mu);
			}
			matches++;
		}
	}
	
	counter->lines_read += count;
	counter->lines_matched += matches;
	counter->bytes_read += ftell(stdin); 
	
	return matches;
	/*match_stdin*/
}
// Assemble the command
void assemble (char *line, char * cmd, op_id opcode, parse_func parser, FILE *outfile)
{
    // NOP
    char *args = trim_line (line + strlen(cmd));

    // calc opcode
    int op = (opcode << 9) | parser(args);
    fwrite(&op, sizeof(int), 1, outfile);
}
int test_qtodec(testspec_t *t, FILE *ofp)
{
  mp_rat in[4];
  long   radix, prec;
  mp_round_mode rmode;
  mp_result res, expect = MP_OK, len;

  if(!parse_rat_values(t, in, NULL, NULL))
    return imath_errno = MP_BADARG, 0;

  if(t->output[0][0] == '$' && !parse_result_code(t->output[0], &expect)) {
    fprintf(stderr, "Line %d: Invalid result code [%s]\n", 
	    t->line, t->output[0]);
    return 0;
  }
  
  trim_line(t->input[1]);
  trim_line(t->input[2]);
  trim_line(t->input[3]);
  if(!read_long(&radix, t->input[1]))
    return imath_errno = MP_BADARG, 0;
  if(!read_long(&prec, t->input[2]))
    return imath_errno = MP_BADARG, 0;
  if(!read_long((long *)&rmode, t->input[3]))
    return imath_errno = MP_BADARG, 0;

  if(prec < 0) {
    fprintf(stderr, "Line %d: Precision %ld out of range\n", 
	    t->line, prec);
    return imath_errno = MP_RANGE, 0;
  }
  
  trim_line(t->output[0]);
  len = mp_rat_decimal_len(in[0], radix, prec);

  if((res = mp_rat_to_decimal(in[0], radix, prec, 
                              rmode, g_output, len)) != expect)
    return imath_errno = res, 0;
  
  if(res == MP_OK && strcmp(t->output[0], g_output) != 0)
    return imath_errno = OTHER_ERROR, 0;
  
  return 1;
}
static int output_img_with_config(FILE *img_fp, FILE *cfg_fp) {
  int entry_count = parse_config_entry_count(cfg_fp);
  struct dt_image_writer *writer = dt_image_writer_start(img_fp, entry_count);

  fseek(cfg_fp, 0, SEEK_SET); /* Reset the file pos to head */

  int is_entry = 0;
  char line[1024];
  while (fgets(line, sizeof(line), cfg_fp) != NULL) {
    char *trimmed = trim_line(line);
    if (trimmed[0] == '\0') {
      /* empty line, pass */
      continue;
    }

    if (trimmed == line) {
      /* This line is a file name,
        because it start from the first char of the line */
      if (dt_image_writer_add_entry(writer, trimmed) != 0) {
        return -1;
      }
      is_entry = 1;
      continue;
    }

    char *option, *value;
    if (parse_option(&option, &value, trimmed) != 0) {
      fprintf(stderr, "Wrong syntax: %s\n", trimmed);
      return -1;
    }

    int ret = is_entry ?
      set_entry_options(writer, option, value) :
      set_global_options(writer, option, value);
    if (ret != 0) {
      fprintf(stderr, "Unknown option: %s\n", option);
      return -1;
    }
  }

  if (dt_image_writer_end(writer) != 0) {
    return -1;
  }

  return 0;
}
Beispiel #10
0
Datei: token.c Projekt: rioru/42
void			trim_figure(t_data *d)
{
	int			i;

	i = 0;
	trim_line(d);
	trim_col(d);
	d->tfline = d->fnbline;
	d->eatline = 0;
	d->tfcol = d->fnbcol - d->eatcol;
	d->tf = (char **)malloc(sizeof(*(d->tf)) * (d->tfline + 1));
	d->tf[d->tfline] = NULL;
	while (i < d->tfline)
	{
		d->tf[i] = ft_strsub(d->fig[i + d->eatline], d->eatcol, d->tfcol);
		++i;
	}
}
Beispiel #11
0
void skip_to_end_of_section(FILE *fp)
{
	char buffer[1024];

	while (!feof(fp))
	{
		buffer[0]='\0';

		fgets(buffer, sizeof(buffer)-1, fp);

		trim_line(buffer);

		char *b=&buffer[0];
		if (lex(b)==LEX_END_SEC)
		{
			break;
		}
	}
}
Beispiel #12
0
void process_key(char *data)
{
	size_t size=0;

	char *a=data;

	while (*a != ' ' && *a != '\t' && *a != '\0')
	{
		a++;
		size++;
	}

	if (size==0)
	{
		return;
	}
	int set=0;
	for (int i=0; i< HAM_LAST_ENTRY_DONT_USE_ME_LOL; i++)
	{
		if (strncmp(data, hooklist[i].name, size)==0)
		{
			data+=size+1;

			trim_line(data);
			int value=read_number(data);

			hooklist[i].isset=1;
			hooklist[i].vtid=value;


			set=1;
			break;

		}
	}

	if (set==0)
	{
		printf("stray key in process_key: %s\n", data);
	}

}
Beispiel #13
0
int lex(char*& buffer)
{
	trim_line(buffer);

	size_t len;

	for (int i=0; i<LEX_END; i++)
	{
		if (tokens[i]!=NULL && *(tokens[i])!='\0')
		{
			len=strlen(tokens[i]);
			if (strncmp(buffer,tokens[i],len)==0)
			{
				buffer+=len+1;
				return i;
			}
		}
	}
	return LEX_UNKNOWN;
}
static int       parse_binary(char *str, unsigned char *buf, int limit)
{
  int    pos = 0;
  char  *tok;

  trim_line(str);

  for(tok = strtok(str, ".");
      tok != NULL && pos < limit;
      tok = strtok(NULL, ".")) {
    long v;

    if(!read_long(&v, tok) || v > UCHAR_MAX || v < 0)
      return -1;
      
    buf[pos++] = (unsigned char)v;
  }

  return pos;
}
Beispiel #15
0
int read_start_section(char *data)
{
	if (strncasecmp(data, CurrentModName, strlen(CurrentModName))==0)
	{
		data+=strlen(CurrentModName)+1;
		trim_line(data);

#ifdef _WIN32
		if (strcmp(data, "windows")==0)
#elif defined(__linux__)
		if (strcmp(data, "linux")==0)
#elif defined(__APPLE__)
		if (strcmp(data, "mac")==0)
#endif
		{
			return 1;
		}
	}
	return 0;
}
int  read_line(FILE *ifp, char *line, int limit)
{
  static FILE *current_fp = NULL;
  static int   current_line = 0;
  
  if(ifp != current_fp) {
    current_fp = ifp;
    current_line = 0;
  }

  do {
    if(fgets(line, limit, ifp) == NULL)
      return 0;

    ++current_line;
  } while(is_blank(line));

  trim_line(line);

  return current_line;
}
int test_read_uns(testspec_t *t, FILE *ofp)
{
  mp_int out[1], in = g_zreg + 1;
  int in_len;
  mp_result res, expect;

  if(!parse_int_values(t, NULL, out, &expect))
    return imath_errno = MP_BADARG, 0;

  trim_line(t->input[0]);
  if((in_len = parse_binary(t->input[0], g_bin1, sizeof(g_bin1))) < 0)
    return imath_errno = MP_BADARG, 0;

  if((res = mp_int_read_unsigned(in, g_bin1, in_len)) != expect)
    return imath_errno = res, 0;

  if(expect == MP_OK && mp_int_compare(in, out[0]) != 0) {
    mp_int_to_string(in, 10, g_output, OUTPUT_LIMIT);
    return imath_errno = OTHER_ERROR, 0;
  }

  return 1;
}
Beispiel #18
0
void archive_go_upper(struct_panel *panel) /* Переходим на уровень выше внутри архива */
{
  if (panel->archive_cwd[0] == '\0') /* Если на верхнем уровне архива - то покидаем его*/
    leave_archive(panel);
  else /* А если нет - */
  {
    char *slash=NULL, *path, *iter;
    trim_line(panel->archive_cwd); /* Удяляем последний символ (слэш) из текущего имени */
    archive_cwd_prev=xconcat(basename(panel->archive_cwd),"/");
    slash=strrchr(panel->archive_cwd, '/'); /* Ищем последний слэш в пути */
    if (slash==NULL) /* Если значение пути вырождается в NULL (слэша больше не оказалось) то делаем archive_cwd нулевой строкой*/
      panel->archive_cwd[0]='\0';
    else /* А иначе просто обрезаем путь в архиве на один уровень */
      *(slash+1)='\0';

    if (panel == &top_panel)
    {
      write_config_string("top_panel.archive_cwd", panel->archive_cwd);
      top_panel.last_name[0]='\0';
      write_config_string("top_panel.last_name", top_panel.last_name);
    }
    else
    {
      write_config_string("bottom_panel.archive_cwd", panel->archive_cwd);
      bottom_panel.last_name[0]='\0';
      write_config_string("bottom_panel.last_name", bottom_panel.last_name);
    }
    update(panel); /* Перерисовываем список */
    iter=iter_from_filename (archive_cwd_prev, panel);
    move_selection(iter, panel); /* И выделяем предыдущий каталог в архиве */
    free(iter);
    path=xconcat_path_file(panel->archive_stack[panel->archive_depth],panel->archive_cwd);
    gtk_label_set_text (GTK_LABEL(panel->path_label), path); /* Пишем имя архива с путём в поле снизу */
    free(path);
  }
}
int test_qrdec(testspec_t *t, FILE *ofp)
{
  mp_rat out[1], reg = g_qreg + 1;
  long   radix;
  mp_result res, expect;

  if(!parse_rat_values(t, NULL, out, &expect)) 
    return imath_errno = MP_BADARG, 0;
  
  trim_line(t->input[1]);
  if(!read_long(&radix, t->input[1]))
    return imath_errno = MP_BADARG, 0;

  if((res = mp_rat_read_decimal(reg, radix, t->input[0])) != expect)
    return imath_errno = res, 0;

  if(expect == MP_OK &&
     mp_rat_compare(reg, out[0]) != 0) {
    mp_rat_to_string(reg, 10, g_output, OUTPUT_LIMIT);
    return imath_errno = OTHER_ERROR, 0;
  }

  return 1;
}
static int       parse_rat_values(testspec_t *t, mp_rat *in, mp_rat *out,
				  mp_result *rval)
{
  int i, pos = 0;
  char *str;

  if(rval != NULL)
    *rval = MP_OK;  /* default */

  if(in != NULL) {
    for(i = 0; i < t->num_inputs; ++i) {
      str = t->input[i];

      trim_line(str);

      if(*str == '=') {
	int k = abs(atoi(str + 1)) - 1;
	
	if(k < 0 || k >= i) {
	  fprintf(stderr, "Line %d: Invalid input back-reference [%s]\n",
		  t->line, str);
	  return 0;
	}
      
	in[i] = in[k];
      } else {
	mp_rat reg = g_qreg + pos++; /* grab next free register */
	
	if(read_rat_value(reg, str) != MP_OK) {
	  fprintf(stderr, "Line %d: Invalid input value [%s]\n",
		  t->line, str);
	  return 0;
	}
	
	in[i] = reg;
      }
    }
  }

  for(i = 0; i < t->num_outputs; ++i) {
    mp_rat reg = g_qreg + pos++;

    str = t->output[i];
    
    trim_line(str);

    if(strcmp(str, "?") == 0)
      mp_rat_zero(reg);
    else if(*str == '$') {
      mp_result code;

      if(!parse_result_code(str, &code)) {
	fprintf(stderr, "Line %d: Invalid result code [%s]\n", 
		t->line, str);
	return 0;
      }
      else if(rval == NULL) {
	fprintf(stderr, "Line %d: Result code not permitted here [%s]\n",
		t->line, str);
	return 0;
      }
      else
	*rval = code;

      /* Provide a dummy value for the corresponding output */
      mp_rat_zero(reg);
    }
    else if(out != NULL && read_rat_value(reg, str) != MP_OK) {
      fprintf(stderr, "Line %d: Invalid output value [%s]\n",
	      t->line, str);
      return 0;
    }

    if(out != NULL)
      out[i] = reg;
  }

  return 1;
}
Beispiel #21
0
/** match_file
 * Reads up to the maximum number of lines from standard input
 * 
 * Parameters:
 *     FILE *fptr - the file pointer 
 *     struct Filename *file - the names associated with the file
 *     struct Globals *gl - the "global" variables for this search
 * Return Value:
 *     int - the number of matches found or the number of lines without matches 
 * 	     if the -r flag was used
 */
int match_file(FILE *fptr, struct Filename *file, struct Globals *gl){
	char *input_line;
	int count = 0;
	int status;
	int matches = 0;
	
	unsigned int my_flags;
	unsigned int num_chars;
	int max_lines;
	my_flags = gl->my_flags;
	num_chars = gl->num_chars;
	max_lines = gl->max_lines;
	
	input_line = calloc(sizeof(char), num_chars);
	
	file->counters->files_read++;
	
	while(matches != max_lines && fgets(input_line, num_chars, fptr) != NULL){
		count++;
		trim_line(input_line);
		status = match_line(input_line, &(file->counters), gl);
		if(status == MATCH && (my_flags&REVERSE_SELECTION) != REVERSE_SELECTION){
			/* Increments the match counter if a match was found and
			   the reverse flag was not chosen */
			if((my_flags&SUMMARY) != SUMMARY){
				/* Prints out the line if the summary flag was not chosen */
				pthread_mutex_lock(&mu);
				if(gl->is_network){
					char *output;
					
					output = calloc(sizeof(char), gl->path_max);
					sprintf(output, "%s,%d: %s\n", file->realptr, count, input_line);
					write_output_line(output, gl);
					free(output);
				}
				else{
					fprintf(stdout, "%s,%d: %s\n", file->realptr, count, input_line);
				}
				pthread_mutex_unlock(&mu);
			}
			matches++;
		}else if(status == NO_MATCH 
					&& (my_flags&REVERSE_SELECTION) == REVERSE_SELECTION){
			/* Increments the match counter if a match was not found
			   and the reverse flag was chosen */
			if((my_flags&SUMMARY) != SUMMARY){
				/* Prints out the line if the summary flag was not chosen */
				pthread_mutex_lock(&mu);
				if(gl->is_network){
					char *output;
					
					output = calloc(sizeof(char), gl->path_max);
					sprintf(output, "%s,%d: %s\n", file->realptr, count, input_line);
					write_output_line(output, gl);
					free(output);
				}
				else{
					fprintf(stdout, "%s,%d: %s\n", file->realptr, count, input_line);
				}
				pthread_mutex_unlock(&mu);
			}
			matches++;
		}
	}
	
	file->counters->lines_read += count;
	file->counters->lines_matched += matches;
	file->counters->bytes_read += ftell(fptr); 
	
	return matches;
	/*match_file*/
}
Beispiel #22
0
int find_next_archive_directory(struct_panel *panel)
{
  char **directories_list;
  int i=0;
  char *slash=NULL, *up_dir;
  up_dir=strdup(panel->archive_cwd);
  trim_line(up_dir); /* Удяляем последний символ (слэш) из текущего имени */
  slash=strrchr(up_dir, '/'); /* Ищем последний слэш в пути */
  if (slash==NULL) /* Если значение пути вырождается в NULL (слэша больше не оказалось) */
    up_dir[0]='\0'; /* То делаем archive_cwd нулевой строкой */
    else /* А иначе просто обрезаем путь в архиве на один уровень */
      *(slash+1)='\0';
    directories_list=archive_get_directories_list(panel, up_dir);
  while (TRUE)
  {
    if (directories_list[i]==NULL)
    {
      free(directories_list);
      return FALSE; /* Если достигли конца списка */
    }
    else
    {
      #ifdef debug_printf
      printf ("Checking '%s', need '%s'\n", directories_list[i], panel->archive_cwd);
      #endif
    }
    if (strcmp (directories_list[i], panel->archive_cwd) == 0) /* Сравниваем строку с текущим каталогом */
    {
      if (directories_list[i+1][0] == '\0') /* Если следующая строка пустая - */
      {
        #ifdef debug_printf
        printf ("Matched dirname '%s', stay here\n", directories_list[i]);
        #endif
        free(directories_list[i]);
        free(directories_list[i+1]);
        free(directories_list);
        return FALSE;  /* То возвращаем что переход не удался */
      }
      else
      {
        free(panel->archive_cwd);
        panel->archive_cwd=strdup(directories_list[i+1]);
        if ( panel == &top_panel )
          write_config_string("top_panel.archive_cwd", panel->archive_cwd);
        else
          write_config_string("bottom_panel.archive_cwd", panel->archive_cwd);
        #ifdef debug_printf
        printf("JUMPING TO %s\n", panel->archive_cwd);
        #endif

        /*Очищаем оставшийся список каталогов*/
        do free(directories_list[i++]);
        while (directories_list[i] != NULL);
        free(directories_list);

        return TRUE;  /* Иначе возвращаем успех */
      }
    }
    #ifdef debug_printf
    printf ("NOT matched dirname '%s', need '%s'\n", directories_list[i], panel->archive_cwd);
    #endif
    free(directories_list[i]);
    i++;
  }
  #ifdef debug_printf
  printf ("Dirname not matched!\n");
  #endif

  /*Очищаем оставшийся список каталогов*/
  do free(directories_list[i++]);
  while (directories_list[i] != NULL);
  free(directories_list);

  return FALSE; /* И возвращаем значение текущего каталога */
}
Beispiel #23
0
boost::tribool request_parser::parse_line(http_request &request, const std::string &line)
{
	if (line.empty() || line[line.size() - 1] != '\r')
		return false;

	const bool is_empty_line = line.compare(0, line.size(), "\r", 1) == 0;

	switch (m_state_new) {
		case request_line: {
			if (is_empty_line) {
				// Ignore CRLF characters between requests in Keep-Alive connection
				return boost::indeterminate;
			}

			const auto first_space = line.find(' ');
			if (first_space == std::string::npos)
				return false;

			request.set_method(line.substr(0, first_space));

			const auto second_space = line.find(' ', first_space + 1);
			if (second_space == std::string::npos)
				return false;

			request.set_url(line.substr(first_space + 1, second_space - first_space - 1));

			if (line.compare(second_space + 1, 5, "HTTP/", 5) != 0)
				return false;

			const auto version_major_start = second_space + 1 + 5;
			const auto dot = line.find('.', version_major_start);
			if (dot == std::string::npos)
				return false;

			const auto version_minor_end = line.find('\r', dot);

			if (version_minor_end == std::string::npos)
				return false;

			boost::tribool result = boost::indeterminate;
			const auto major_version = parse_int(line.data() + version_major_start, line.data() + dot, result);
			const auto minor_version = parse_int(line.data() + dot + 1, line.data() + version_minor_end, result);
			request.set_http_version(major_version, minor_version);

			m_state_new = header_line;
			return result;
		}
		case header_line: {
			if (!m_header.first.empty() && (line[0] == ' ' || line[0] == '\t')) {
				// any number of LWS is allowed after field, rfc 2068
				auto begin = line.begin() + 1;
				auto end = line.end();
				trim_line(begin, end);

				m_header.second += ' ';
				m_header.second.append(begin, end);

				return boost::indeterminate;
			}

			if (!m_header.first.empty()) {
				request.headers().add(m_header);
				m_header.first.resize(0);
				m_header.second.resize(0);
			}

			if (is_empty_line) {
				return true;
			}

			const auto colon = line.find(':');
			if (colon == std::string::npos)
				return false;

			auto name_begin = line.begin();
			auto name_end = line.begin() + colon;
			trim_line(name_begin, name_end);
			m_header.first.assign(name_begin, name_end);

			auto value_begin = line.begin() + colon + 1;
			auto value_end = line.end();
			trim_line(value_begin, value_end);
			m_header.second.assign(value_begin, value_end);

			return boost::indeterminate;
		}
	}

	return false;
}
Beispiel #24
0
/*
 *	assemble a file and load into memory
 */
Assembly* parse_file(FILE* file) {
	Assembly* assembly;					/* assembly structure */
	int labelid;								/* new label id */
	Segment* current_segment;		/* holds current segment */
	char line[MAX_LINE];				/* holds one line */
	char* items[MAX_ARGS];			/* split line into items (split on ' ' and '\t') */
	int segment;								/* holds current segment id */
	int count, i, size;					/* loop variables */
	long long params[MAX_ARGS];	/* parsed items array */
	char sbuffer[1024];					/* 1K string buffer */
	char* sourcefile;						/* current source file */
	Label* label;
	
	/* initialize variables */
	assembly = new_assembly();
	labelid = 0;
	
	linenr = 0;
	segment = UNKNOWN;
	sourcefile = NULL;
	
	/* read a line lines (returns nr of characters read, -1 if eof) */
	while(read_line(file, line, MAX_LINE) >= 0) {
		linenr++;
		/* get rid of spaces/tabs in front of the line */
		trim_line(line);

		/* split the line on spaces/tabs */
		count = split_line(line, items);
		/* note: line == items[0] */
		
		/* check if the line was not empty */
		if (strlen(line) > 0) {
			if (strcmp(line, "code") == 0) {
				/* code segment */
				segment = CODE;
				current_segment = assembly->code;
			} else if (strcmp(line, "bss") == 0) {
				/* bss segment */
				segment = BSS;
				/* bss has no segment structure */
				/* (no point in saving uninitialized data */
				current_segment = 0;
			} else if (strcmp(line, "lit") == 0) {
				/* lit segment */
				segment = LIT;
				current_segment = assembly->lit;
			} else if (strcmp(line, "data") == 0) {
				/* data segment */
				segment = DATA;
				current_segment = assembly->data;
			} else if (strcmp(line, "export") == 0) {
				/* mark label as public */
				if (count != 2) error(linenr, "invalid number of parameters");
				label = get_label(assembly, items[1]);
				/* any exported function should be included */
				label->accessed = 1;
				label->exported = TRUE;
			} else if (strcmp(line, "import") == 0) {
				/* mark label as imported */
				if (count != 2) error(linenr, "invalid number of parameters");
				get_label(assembly, items[1])->imported = TRUE;
			} else if (segment == UNKNOWN) {
				/* all other things must be in segments */
				error(linenr, "code outside segment");
			} else if (strcmp(line, "align") == 0) {
				/* align a segment */
				if (count != 2) error(linenr, "invalid number of parameters");
				params[0] = parse_numeric(items[1]);
				if (segment == BSS) {
					/* align bss just by size */
					while(assembly->bss_size % params[0]) assembly->bss_size++;
				} else {
					align_segment(current_segment, params[0]);
				}
			}	else if (strcmp(line, "byte") == 0) {
				/* one byte of data */
				if (count != 3) error(linenr, "invalid number of parameters");
				if (segment == BSS) {
					error(linenr, "can't put initialized data in bss, use data segment instead");
				} else {
					/* parse */
					params[0] = parse_numeric(items[1]);
					params[1] = parse_numeric(items[2]);
					/* write to segment */
					MS_WriteBE(current_segment->data, params[1], (int)params[0]);
					for (i = 0; i < (int)params[0]; i++) MS_WriteBit(current_segment->mask, FALSE);
				}
			}	else if (strcmp(line, "skip") == 0) {
				/* some empty space */
				if (count != 2) error(linenr, "invalid number of parameters");
				/* parse */
				params[0] = parse_numeric(items[1]);
				if (segment == BSS) {
					/* for bss: just update the size */
					assembly->bss_size += params[0];
				} else {
					/* for other segment: write zeros */
					MS_Write(current_segment->data, 0, (int)params[0]);
					for (i = 0; i < (int)params[0]; i++) MS_WriteBit(current_segment->mask, FALSE);
				}
			} else if (strcmp(line, "address") == 0) {
				/* insert address to label here */

				/* some empty space */
				if (count != 2) error(linenr, "invalid number of parameters");
				/* write the id to the current segment */
				MS_WriteBE(current_segment->data, get_label(assembly, items[1])->id, PTR_SIZE);
				/* needs to be resolved */
				for (i = 0; i < PTR_SIZE; i++) MS_WriteBit(current_segment->mask, TRUE);
			} else if (strcmp(line, "line") == 0) {
				if (count < 2) error(linenr, "invalid number of parameters");
				if (sourcefile == NULL) error(linenr, "file directive must precede line directive");

				size = sprintf(sbuffer, "$%s:", sourcefile);
				for (i = 1; i < count; i++) {
					size += sprintf(sbuffer+size, "%s", items[i]);
					if (i == count-1) {
						sbuffer[size++] = 0;
					} else {
						sbuffer[size++] = ' ';
					}
				}
				
				/* register debug label */
				label = get_label(assembly, sbuffer);
				if (label->segment == UNKNOWN) {
					if (segment == BSS) {
						label->location = assembly->bss_size;
					} else {
						label->location = current_segment->data->size;
					}
					label->segment = segment;
				}
				/* mark as debug function, set accessed to 1 to include it in the assembly */
				label->accessed = 1;
				label->debuginfo = LABEL_DEBUG_LINE;
			} else if (strcmp(line, "file") == 0) {
				if (count < 2) error(linenr, "invalid number of parameters");

				size = sprintf(sbuffer, "$");
				for (i = 1; i < count; i++) {
					size += sprintf(sbuffer+size, "%s", items[i]);
					if (i == count-1) {
						sbuffer[size++] = 0;
					} else {
						sbuffer[size++] = ' ';
					}
				}

				if (sourcefile != NULL) free(sourcefile);
				sourcefile = malloc(size-1);
				strcpy(sourcefile, sbuffer+1);
				
				/* register debug label */
				label = get_label(assembly, sbuffer);
				if (segment == BSS) {
					label->location = assembly->bss_size;
				} else {
					label->location = current_segment->data->size;
				}
				label->segment = segment;
				/* mark as debug function, set accessed to 1 to include it in the assembly */
				label->accessed = 1;
				label->debuginfo = LABEL_DEBUG_FILE;
			} else if (strcmp(line, "local") == 0) {
				if (count < 3) error(linenr, "invalid number of parameters");

				size = sprintf(sbuffer, "$");
				for (i = 1; i < count; i++) {
					if (i != 2) {
						size += sprintf(sbuffer+size, "%s", items[i]);
						if (i == count-1) {
							sbuffer[size++] = 0;
						} else {
							sbuffer[size++] = ' ';
						}
					}
				}
				
				/* register debug label */
				label = get_label(assembly, sbuffer);
				label->location = parse_numeric(items[2]);				

				label->segment = UNKNOWN;
				/* mark as debug function, set accessed to 1 to include it in the assembly */
				label->accessed = 1;
				label->debuginfo = LABEL_DEBUG_LOCAL;
			} else if (strcmp(line, "param") == 0) {
				if (count < 3) error(linenr, "invalid number of parameters");

				size = sprintf(sbuffer, "$");
				for (i = 1; i < count; i++) {
					if (i != 2) {
						size += sprintf(sbuffer+size, "%s", items[i]);
						if (i == count-1) {
							sbuffer[size++] = 0;
						} else {
							sbuffer[size++] = ' ';
						}
					}
				}
				
				/* register debug label */
				label = get_label(assembly, sbuffer);
				label->location = parse_numeric(items[2]);
				label->segment = UNKNOWN;
				/* mark as debug function, set accessed to 1 to include it in the assembly */
				label->accessed = 1;
				label->debuginfo = LABEL_DEBUG_PARAM;
			} else if (strcmp(line, "global") == 0) {
				if (count < 2) error(linenr, "invalid number of parameters");

				size = sprintf(sbuffer, "$");
				for (i = 1; i < count; i++) {
					size += sprintf(sbuffer+size, "%s", items[i]);
					if (i == count-1) {
						sbuffer[size++] = 0;
					} else {
						sbuffer[size++] = ' ';
					}
				}
				
				/* register debug label */
				label = get_label(assembly, sbuffer);
				label->ref = get_label(assembly, items[1]);
				/* mark as debug function, set accessed to 1 to include it in the assembly */
				label->accessed = 1;
				label->debuginfo = LABEL_DEBUG_GLOBAL;
			} else if (strcmp(line, "function") == 0) {
				if (count < 2) error(linenr, "invalid number of parameters");

				size = sprintf(sbuffer, "$");
				for (i = 1; i < count; i++) {
					size += sprintf(sbuffer+size, "%s", items[i]);
					if (i == count-1) {
						sbuffer[size++] = 0;
					} else {
						sbuffer[size++] = ' ';
					}
				}
				
				/* register debug label */
				label = get_label(assembly, sbuffer);
				label->ref = get_label(assembly, items[1]);
				/* mark as debug function, set accessed to 1 to include it in the assembly */
				label->accessed = 1;
				label->debuginfo = LABEL_DEBUG_FUNCTION;
			} else if (strcmp(line, "label") == 0) {
				/* a label; register */
				if (count != 2) error(linenr, "invalid number of parameters");

				if (segment == BSS) {
					register_label(assembly, items[1], segment, assembly->bss_size);
				} else {
					register_label(assembly, items[1], segment, current_segment->data->size);
				}
			} else if (strcmp(line, "typedef") == 0) {
				if (count < 2) error(linenr, "invalid number of parameters");

				size = sprintf(sbuffer, "$");
				for (i = 1; i < count; i++) {
					size += sprintf(sbuffer+size, "%s", items[i]);
					if (i == count-1) {
						sbuffer[size++] = 0;
					} else {
						sbuffer[size++] = ' ';
					}
				}

				/* register debug label */
				label = get_label(assembly, sbuffer);
				/* mark as debug function, set accessed to 1 to include it in the assembly */
				label->accessed = 1;
				label->debuginfo = LABEL_DEBUG_TYPEDEF;
			} else if (strcmp(line, "field") == 0) {
				if (count < 2) error(linenr, "invalid number of parameters");

				size = sprintf(sbuffer, "$");
				for (i = 1; i < count; i++) {
					if (i != 2) {
						size += sprintf(sbuffer+size, "%s", items[i]);
						if (i == count-1) {
							sbuffer[size++] = 0;
						} else {
							sbuffer[size++] = ' ';
						}
					}
				}

				/* register debug label */
				label = get_label(assembly, sbuffer);
				label->location = parse_numeric(items[2]);				

				label->segment = UNKNOWN;
				/* mark as debug function, set accessed to 1 to include it in the assembly */
				label->accessed = 1;
				label->debuginfo = LABEL_DEBUG_FIELD;
			} else {
				/* not identified; should be an instruction */
				write_instruction(assembly, items, count, current_segment);
			}
		}
	}	
	
	if (sourcefile != NULL) free(sourcefile);

	/* return the structure */
	return assembly;
}
int main (int argc, char **argv)
{
    FILE *fr = NULL;
    FILE *fw = NULL;
    char *line = NULL;

    // check the input
    if (argc != 3)
    {
	printf ("Usage: %s infile outfile\n", argv[0]);
	exit (-1);
    }

    char *infile = argv[1];
    char *outfile = argv[2];


    // open the files
    if ((fr = fopen (infile, "rt")) == NULL)
    {
	printf ("Cannot open infile. infile: %s\n", infile);
	exit (-2);
    }

    if ((fw = fopen(outfile, "w+")) == NULL)
    {
	printf ("Cannot open infile. outfile: %s\n", outfile);
	exit (-2);
    }


    int i = 0;
    int len = sizeof(dictionary) / sizeof(dictionary[0]);

    // loop through the input
    while (fgets (g_line, MAXLINE, fr) != NULL)
    {
	// check the line
	g_line_no++;
	check_line();

	// skip empty lines
	line = trim_line(g_line);
	if (!(*line)) 
	    continue;

	// loop through the dictionary to find the command
	for (i = 0; i < len; i++)
	{
	    if (strncmp (line, dictionary[i].cmd, strlen (dictionary[i].cmd)) == 0)
	    {
		assemble (line, dictionary[i].cmd, dictionary[i].opcode, dictionary[i].parser, fw);
		break;
	    }
	}

	if (i == len)
	{
	    printf ("Line: %d\n", g_line_no);
	    printf ("%s\n", g_line);
	    printf ("UNKNOWN command.\n");
	    exit (-6);
	}
    }
    fclose(fr);
    fclose(fw);
}
Beispiel #26
0
void process_base(char *data)
{
	trim_line(data);
	Offsets.SetBase(read_number(data));
}
Beispiel #27
0
void process_pev(char *data)
{
	trim_line(data);
	Offsets.SetPev(read_number(data));
}
Beispiel #28
0
int main(int argc,char **argv)
{
  int curr_arg;
  bool bDropDelim;
  bool bNoTrim;
  char delimiter;
  FILE *fptr;
  int linelen;

  if ((argc < 3) || (argc > 5)) {
    printf(usage);
    return 1;
  }

  if ((line = (char *)malloc(MAX_LINE_LEN)) == NULL) {
    printf("couldn't allocate memory for line\n");
    return 2;
  }

  if ((buf = (char *)malloc(MAX_LINE_LEN)) == NULL) {
    printf("couldn't allocate memory for buf\n");
    free(line);
    return 3;
  }

  bDropDelim = false;
  bNoTrim = false;

  for (curr_arg = 1; curr_arg < argc; curr_arg++) {
    if (!strcmp(argv[curr_arg],"-drop_delim"))
      bDropDelim = true;
    else if (!strcmp(argv[curr_arg],"-no_trim"))
      bNoTrim = true;
    else
      break;
  }

  if (argc - curr_arg != 2) {
    printf(usage);
    free(buf);
    free(line);
    return 4;
  }

  if (!strcmp(argv[curr_arg],"TAB"))
    delimiter = TAB;
  else if (!strcmp(argv[curr_arg],"BACKSLASH"))
    delimiter = BACKSLASH;
  else
    delimiter = argv[curr_arg][0];

  if ((fptr = fopen(argv[curr_arg+1],"r")) == NULL) {
    printf(couldnt_open,argv[curr_arg+1]);
    free(buf);
    free(line);
    return 5;
  }

  for ( ; ; ) {
    GetLine(fptr,line,&linelen,MAX_LINE_LEN);

    if (feof(fptr))
      break;

    if (bDropDelim && !bNoTrim)
      trim_line(line,&linelen,delimiter);

    chop(line,delimiter,bDropDelim);
  }

  fclose(fptr);

  free(buf);
  free(line);

  return 0;
}