int main()
{
	srand(time(0));
	do_string("abracadebra");
	do_string("grrrrrr");
	do_string("elk");
	do_string("seesaw");
	do_string("");
	return 0;
}
Exemple #2
0
static bool do_trnheader(int fp,bool bRead,t_trnheader *sh, bool *bOK)
{
  const int magic=GROMACS_MAGIC;
  const char *version = "GMX_trn_file";
  static bool bFirst=TRUE;
  char buf[256];
  
  *bOK=TRUE;

  gmx_fio_select(fp);
  if (!do_int(magic))
    return FALSE;
  
  if (bRead) {
    *bOK = *bOK && do_string(buf);
    if (bFirst)
      fprintf(stderr,"trn version: %s ",buf);
  }
  else
    *bOK = *bOK && do_string(version);
  *bOK = *bOK && do_int(sh->ir_size);
  *bOK = *bOK && do_int(sh->e_size);
  *bOK = *bOK && do_int(sh->box_size);
  *bOK = *bOK && do_int(sh->vir_size);
  *bOK = *bOK && do_int(sh->pres_size);
  *bOK = *bOK && do_int(sh->top_size); 
  *bOK = *bOK && do_int(sh->sym_size); 
  *bOK = *bOK && do_int(sh->x_size); 
  *bOK = *bOK && do_int(sh->v_size); 
  *bOK = *bOK && do_int(sh->f_size); 
  *bOK = *bOK && do_int(sh->natoms);

  if (!*bOK) return *bOK; 
  sh->bDouble = (nFloatSize(sh) == sizeof(double));
  gmx_fio_setprecision(fp,sh->bDouble);

  if (bRead && bFirst) {
    fprintf(stderr,"(%s precision)\n",sh->bDouble ? "double" : "single");
    bFirst = FALSE;
  }
  
  *bOK = *bOK && do_int(sh->step); 
  *bOK = *bOK && do_int(sh->nre); 
  *bOK = *bOK && do_real(sh->t); 
  *bOK = *bOK && do_real(sh->lambda); 
  
  return *bOK;
}
Exemple #3
0
/** Add a Lua C package directory.
 * The directory is added to the search path for lua C packages. Files
 * with a .so suffix will be considered as Lua modules.
 * @param path path to add
 * @param prefix if true, insert path at the beginning of the search path,
 * append to end otherwise
 */
void
LuaContext::add_cpackage_dir(const char *path, bool prefix)
{
  MutexLocker lock(__lua_mutex);

  if (prefix) {
    do_string(__L, "package.cpath = \"%s/?.so;\" .. package.cpath", path);

    __cpackage_dirs.push_front(path);
  } else {
    do_string(__L, "package.cpath = package.cpath .. \";%s/?.so\"", path);

    __cpackage_dirs.push_back(path);
  }
  if ( __fam )  __fam->watch_dir(path);
}
Exemple #4
0
void do_value()
{
	skip_whitespace();
	int ch;
	switch(ch = getc(stdin))
	{
	case '[':
		putc('{', stdout);
		do_array();
		break;
	case '{':
		putc('{', stdout);
		do_object();
		break;
	case '"':
		do_string();
		break;
	case 'f': expect("alse");
		printf("false");
		break;
	case 't': expect("rue");
		printf("true");
		break;
	case 'n': expect("ull");
		printf("nil");
		break;
	default:
		unexpected(ch);
		break;
	}
}
Exemple #5
0
/** Add a Lua C package directory.
 * The directory is added to the search path for lua C packages. Files
 * with a .so suffix will be considered as Lua modules.
 * @param path path to add
 */
void
LuaContext::add_cpackage_dir(const char *path)
{
  MutexLocker lock(__lua_mutex);

  do_string(__L, "package.cpath = package.cpath .. \";%s/?.so\"", path);

  __cpackage_dirs.push_back(path);
  if ( __fam )  __fam->watch_dir(path);
}
Exemple #6
0
/** Add a default package.
 * Packages that are added this way are automatically loaded now and
 * on restart().
 * @param package package to add
 */
void
LuaContext::add_package(const char *package)
{
  MutexLocker lock(__lua_mutex);
  if (find(__packages.begin(), __packages.end(), package) == __packages.end()) {
    do_string(__L, "require(\"%s\")", package);

    __packages.push_back(package);
  }
}
Exemple #7
0
int newbackside( float line )
{
    extern int dev_lmts();  /* in geom/limits.c */
    char *instr;
    int ie;
    float min_x;
    float max_x;
    float min_y;
    float max_y;
    float offset = 1.0;

    instr = malloc(80*sizeof(char));
    instr = "structure outf=suprem4temp.str";
    do_string(instr, NULL, 0);

/*    hack up grid here */
    dev_lmts(&min_x, &max_x, &min_y, &max_y);
    min_x *= 1.0e4;
    max_x *= 1.0e4;
    min_y *= 1.0e4;
    max_y *= 1.0e4;
    if (line < max_y)  {
	sprintf(instr, "etch silicon start x=%g y=%g", min_x - offset, line);
        do_string(instr, "/dev/null", 0);
	sprintf(instr, "etch silicon continue x=%g y=%g", max_x + offset, line);
        do_string(instr, "/dev/null", 0);
	sprintf(instr, "etch silicon continue x=%g y=%g", max_x + offset,
		max_y + offset);
        do_string(instr, "/dev/null", 0);
	sprintf(instr, "etch silicon done x=%g y=%g", min_x - offset,
		max_y + offset);
        do_string(instr, "/dev/null", 0);
	instr = "structure outf=etch.str";
	do_string(instr, "/dev/null", 0);

	/* now that we have the final structure, recompute the backside
	 *  boundary condition
	 */

	/* for now lets just walk through all the triangle.  it's inefficient
	 *	but should work
	 */
	for (ie = 0; ie < ne; ie++)  {
	    if (WITHIN(pt[nd[tri[ie]->nd[0]]->pt]->cord[1], line*1.0e-4))  {
	        if (WITHIN(pt[nd[tri[ie]->nd[1]]->pt]->cord[1], line*1.0e-4))
		    tri[ie]->nb[2] = BC_OFFSET + 1;
	        else
		  if (WITHIN(pt[nd[tri[ie]->nd[2]]->pt]->cord[1], line*1.0e-4))
		    tri[ie]->nb[1] = BC_OFFSET + 1;
	    }
	    else {
		if (WITHIN(pt[nd[tri[ie]->nd[1]]->pt]->cord[1], line*1.0e-4))
	          if (WITHIN(pt[nd[tri[ie]->nd[2]]->pt]->cord[1], line*1.0e-4))
		        tri[ie]->nb[0] = BC_OFFSET + 1;
	    }
	}
        free(instr);
    }
    return(0);
}
Exemple #8
0
/** Set start script.
 * The script will be executed once immediately in this method, make
 * sure you call this after all other init-relevant routines like
 * add_* if you need to access these in the start script!
 * @param start_script script to execute now and on restart(). If the
 * string is the path and name of an accessible file it is loaded via
 * do_file(), otherwise it is considered to be the name of a module and
 * loaded via Lua's require(). Note however, that if you use a module,
 * special care has to be taken to correctly modify the global
 * environment!
 */
void
LuaContext::set_start_script(const char *start_script)
{
  if ( __start_script )  free(__start_script);
  if ( start_script ) {
    __start_script = strdup(start_script);
    if (access(__start_script, R_OK) == 0) {
      // it's a file and we can access it, execute it!
      do_file(__start_script);
    } else {
      do_string("require(\"%s\")", __start_script);
    }
  } else {
    __start_script = NULL;
  }
}
Exemple #9
0
static void do_type(const char *varname)
{
	int	ret;
	unsigned int	i, numq, numa;
	char	**answer;
	const char	*query[4];

	query[0] = "TYPE";
	query[1] = upsname;
	query[2] = varname;
	numq = 3;

	ret = upscli_get(ups, numq, query, &numa, &answer);

	if ((ret < 0) || (numa < numq)) {
		printf("Unknown type\n");	
		return;
	}

	/* TYPE <upsname> <varname> <type>... */
	for (i = 3; i < numa; i++) {

		if (!strcasecmp(answer[i], "ENUM")) {
			do_enum(varname);
			return;
		}

		if (!strcasecmp(answer[i], "RANGE")) {
			do_range(varname);
			return;
		}

		if (!strncasecmp(answer[i], "STRING:", 7)) {
			do_string(varname);
			return;
		}

		/* ignore this one */
		if (!strcasecmp(answer[i], "RW")) {
			continue;
		}

		printf("Type: %s (unrecognized)\n", answer[i]);
	}
}
Exemple #10
0
/* Pop the terminal.
 * Called anytime by user command "set term pop".
 */
void
pop_terminal()
{
    if (push_term_name != NULL) {
	char *s;
	int i = strlen(push_term_name) + 11;
	if (push_term_opts) {
	    /* do_string() does not like backslashes -- thus remove them */
	    for (s=push_term_opts; *s; s++)
		if (*s=='\\' || *s=='\n') *s=' ';
	    i += strlen(push_term_opts);
	}
	s = gp_alloc(i, "pop");
	i = interactive;
	interactive = 0;
	sprintf(s,"set term %s %s", push_term_name, (push_term_opts ? push_term_opts : ""));
	do_string(s, TRUE);
	interactive = i;
	if (interactive)
	    fprintf(stderr,"   restored terminal is %s %s\n", term->name, ((*term_options) ? term_options : ""));
    } else
	fprintf(stderr,"No terminal has been pushed yet\n");
}
/* updates title_text, sb_text and tt strings */
gboolean update_info(gpointer data) {

    char *state_string;
    int current_time, song_time;
    int play_state;

    if(mpd_info.msi.connected) { // connected
		play_state = mpd_play_state();
		current_time = mpd_get_current_play_time();
		song_time = mpd_get_current_song_time();
		if(!mpd_info.mps.update) {
			switch(play_state) {
			/* playing */
			case 1:
				state_string = "playing";
				do_string(FMT_TITLE, state_string, current_time, song_time);
				do_string(FMT_STATUSBAR, state_string, current_time, song_time);
#ifdef APPLET
				do_string(FMT_TOOLTIP, state_string, current_time, song_time);
				if(musicus_applet.show_text)
				do_string(FMT_APPLET, state_string, current_time, song_time);
				else
				snprintf(ap_text, 255, "[MPD]");
#endif
				break;
			case 2:
				state_string = "paused";
				do_string(FMT_TITLE, state_string, current_time, song_time);
				do_string(FMT_STATUSBAR, state_string, current_time, song_time);
#ifdef APPLET
				do_string(FMT_TOOLTIP, state_string, current_time, song_time);
				if(musicus_applet.show_text)
				do_string(FMT_APPLET, state_string, current_time, song_time);
				else
				snprintf(ap_text, 255, "[MPD]");
#endif
				break;
			default:
				snprintf(title_text, 255, "MPD [stopped]");
				snprintf(sb_text, 255, "[stopped]");
#ifdef APPLET
				snprintf(tt_text, 255, "MPD [stopped]");
				snprintf(ap_text, 255, "MPD");
#endif
			}
		}

		/* update MpdObj status */
		if(!mpd_check_connected(mpd_info.obj)) {
			if(mpd_connect(mpd_info.obj)!=MPD_OK) {
			    msi_clear(&mpd_info);
			    mpd_info.msi.connected = FALSE;
			    return FALSE;   
			}
			msi_fill(&mpd_info);
			mpd_info.msi.connected = TRUE;
		}
		mpd_status_update(mpd_info.obj);
		return ((mpd_info.update_interval != *(int*)data) ? FALSE : TRUE);
    }
#ifdef APPLET
    snprintf(ap_text, 255, "MPD");
#endif
    return FALSE;
}
Exemple #12
0
void
gmx_mtxio_write(char *                   filename,
                int                      nrow,
                int                      ncol,
                real *                   full_matrix,
                gmx_sparsematrix_t *     sparse_matrix)
{
    int     fd;
    XDR *   xd;
    int     i,j,prec;
    bool    bDum = TRUE;
    bool    bRead = FALSE;
    size_t  sz;

    if(full_matrix!=NULL && sparse_matrix!=NULL)
    {
        gmx_fatal(FARGS,"Both full AND sparse matrix specified to gmx_mtxio_write().\n");
    }

    fd = gmx_fio_open(filename,"w");
    gmx_fio_select(fd);
    xd = gmx_fio_getxdr(fd);

    /* Write magic number */
    i = GMX_MTXIO_MAGIC_NUMBER;
    do_int(i);

    /* Write generating Gromacs version */
    do_string(GromacsVersion());

    /* Write 1 for double, 0 for single precision */
    if(sizeof(real)==sizeof(double))
        prec = 1;
    else
        prec = 0;
    do_int(prec);

    do_int(nrow);
    do_int(ncol);

    if(full_matrix!=NULL)
    {
        /* Full matrix storage format */
        i = GMX_MTXIO_FULL_MATRIX;
        do_int(i);
        sz = nrow*ncol;
        ndo_real(full_matrix,sz,bDum);
    }
    else
    {
        /* Sparse storage */
        i = GMX_MTXIO_SPARSE_MATRIX;
        do_int(i);

        do_int(sparse_matrix->compressed_symmetric);
        do_int(sparse_matrix->nrow);
        if(sparse_matrix->nrow != nrow)
        {
            gmx_fatal(FARGS,"Internal inconsistency in sparse matrix.\n");
        }
        ndo_int(sparse_matrix->ndata,sparse_matrix->nrow,bDum);
        for(i=0; i<sparse_matrix->nrow; i++)
        {
            for(j=0; j<sparse_matrix->ndata[i]; j++)
            {
                do_int(sparse_matrix->data[i][j].col);
                do_real(sparse_matrix->data[i][j].value);
            }
        }
    }
    gmx_fio_close(fd);
}
Exemple #13
0
void
gmx_mtxio_read (char *                  filename,
                int *                   nrow,
                int *                   ncol,
                real **                 full_matrix,
                gmx_sparsematrix_t **   sparse_matrix)
{
    int     fd;
    XDR *   xd;
    int     i,j,prec;
    bool    bDum = TRUE;
    bool    bRead = TRUE;
    char    gmxver[256];
    size_t  sz;

    fd = gmx_fio_open(filename,"r");
    gmx_fio_select(fd);
    xd = gmx_fio_getxdr(fd);

    /* Read and check magic number */
    i = GMX_MTXIO_MAGIC_NUMBER;
    do_int(i);

    if(i!=GMX_MTXIO_MAGIC_NUMBER)
    {
        gmx_fatal(FARGS,
                  "No matrix data found in file. Note that the Hessian matrix format changed\n"
                  "in Gromacs 3.3 to enable portable files and sparse matrix storage.\n");
    }

    /* Read generating Gromacs version */
    do_string(gmxver);

    /* Write 1 for double, 0 for single precision */
    if(sizeof(real)==sizeof(double))
        prec = 1;
    else
        prec = 0;
    do_int(prec);

    fprintf(stderr,"Reading %s precision matrix generated by Gromacs %s\n",
            (prec == 1) ? "double" : "single",gmxver);

    do_int(i);
    *nrow=i;
    do_int(i);
    *ncol=i;

    do_int(i);

    if(i==GMX_MTXIO_FULL_MATRIX)
    {
        printf("Full matrix storage format, nrow=%d, ncols=%d\n",*nrow,*ncol);

        sz = (*nrow) * (*ncol);
        snew((*full_matrix),sz);
        ndo_real((*full_matrix),sz,bDum);
    }
    else
    {
        /* Sparse storage */
        printf("Sparse matrix storage format, nrow=%d, ncols=%d\n",*nrow,*ncol);

        snew((*sparse_matrix),1);
        do_int((*sparse_matrix)->compressed_symmetric);
        do_int((*sparse_matrix)->nrow);
        if((*sparse_matrix)->nrow != *nrow)
        {
            gmx_fatal(FARGS,"Internal inconsistency in sparse matrix.\n");
        }
        snew((*sparse_matrix)->ndata,(*sparse_matrix)->nrow);
        snew((*sparse_matrix)->nalloc,(*sparse_matrix)->nrow);
        snew((*sparse_matrix)->data,(*sparse_matrix)->nrow);
        ndo_int((*sparse_matrix)->ndata,(*sparse_matrix)->nrow,bDum);

        for(i=0; i<(*sparse_matrix)->nrow; i++)
        {
            (*sparse_matrix)->nalloc[i] = (*sparse_matrix)->ndata[i] + 10;
            snew(((*sparse_matrix)->data[i]),(*sparse_matrix)->nalloc[i]);

            for(j=0; j<(*sparse_matrix)->ndata[i]; j++)
            {
                do_int((*sparse_matrix)->data[i][j].col);
                do_real((*sparse_matrix)->data[i][j].value);
            }
        }
    }
    gmx_fio_close(fd);
}
Exemple #14
0
/*
 * XXX this SUCKS! popen() should not be used at all because its shell
 * processing will trash command line arguments :-(
 * ./nwcc -DFOO='"bar"' file.c
 * ... the "" quotes are trashed here, thus cpp receives -DFOO=bar
 * Use fork()/pipe()/exec*() manually
 */
FILE *
exec_cmd(int use_popen, char *prog, char *format, ...) {
	va_list		v;
	char		buf[4096] = { 0 };
	char		*p;
	int		err = 0;
	size_t		len = 0;
	char		*arguments[4096];
#define N_ARGS (sizeof arguments / sizeof arguments[0])
	int		args_used = 0;
	
	va_start(v, format);

	if (!use_popen) {
		arguments[args_used++] = prog;
	}

	strncpy(buf, prog, sizeof buf);
	buf[sizeof(buf) - 1] = 0;
	len = strlen(buf);
	while (*format) {
		switch (*format) {
		case '%':
			switch (*++format) {
			case 's':
				p = va_arg(v, char *);
				if (use_popen) {
					if (do_string(buf, p, sizeof buf, &len, 0)
						!= 0) {
						err = 1;
					}	
				} else {
					if ((unsigned)args_used >= N_ARGS - 1) {
						(void) fprintf(stderr,
							"exec_cmd: Too many "
							"arguments\n");
						exit(EXIT_FAILURE);
					}
					while (isspace((unsigned char)*p)) {
						++p;
					}
					if (*p != 0) {
						arguments[args_used++] = p;
					}
				}
				break;
			case '[':
				if (*++format == ']') {
					char	**sv;
					int	i;

					sv = va_arg(v, char **);
					for (i = 0; sv[i] != NULL; ++i) {
						if (use_popen) {
							if (do_string(buf, sv[i],
								sizeof buf, &len, 1) != 0) {
								err = 1;
								break;
							}	
						} else {
							char	*p;

							if ((unsigned)args_used >= N_ARGS - 1) {
								(void) fprintf(stderr,
									"exec_cmd: Too many "
									"arguments\n");
								exit(EXIT_FAILURE);
							}
							p = sv[i];

							while (isspace((unsigned char)*p)) {
								++p;
							}
							if (*p != 0) {
								arguments[args_used++] = p;
							}
						}
					}	
					break;
				}
				/* FALLTHRU */
			default:
				(void) fprintf(stderr,
				"Unknown escape sequence - ignoring.\n");
				if (*format == 0) {
					err = 1;
				}
			}
			break;
		default:
			if (use_popen) {
				if (len < 4095) {
					buf[len] = *format;
					++len;
					buf[len] = 0;
				} else {
					fprintf(stderr, "Arguments too long.\n");
					err = 1;
					break;
				}
			} else {
				/*
				 * 03/01/09: For now we only support %s and %[]
				 * when using execv() instead of popen()
				 */
				if (!isspace((unsigned char)*format)) {
					fprintf(stderr, "exec_cmd: Bad format string\n");
					exit(EXIT_FAILURE);
				}
			}
		}
		if (err == 1) {
			return NULL;
		}
		if (*++format == 0) {
			break;
		}
	}
Exemple #15
0
void vterm_push_bytes(VTerm *vt, const char *bytes, size_t len)
{
  size_t pos = 0;
  const char *string_start;

  switch(vt->parser_state) {
  case NORMAL:
    string_start = NULL;
    break;
  case ESC:
  case ESC_IN_OSC:
  case ESC_IN_DCS:
  case CSI:
  case OSC:
  case DCS:
    string_start = bytes;
    break;
  }

#define ENTER_STRING_STATE(st) do { vt->parser_state = st; string_start = bytes + pos + 1; } while(0)
#define ENTER_NORMAL_STATE()   do { vt->parser_state = NORMAL; string_start = NULL; } while(0)

  for( ; pos < len; pos++) {
    unsigned char c = bytes[pos];

    if(c == 0x00 || c == 0x7f) { // NUL, DEL
      if(vt->parser_state != NORMAL) {
        append_strbuffer(vt, string_start, bytes + pos - string_start);
        string_start = bytes + pos + 1;
      }
      continue;
    }
    if(c == 0x18 || c == 0x1a) { // CAN, SUB
      ENTER_NORMAL_STATE();
      continue;
    }
    else if(c == 0x1b) { // ESC
      if(vt->parser_state == OSC)
        vt->parser_state = ESC_IN_OSC;
      else if(vt->parser_state == DCS)
        vt->parser_state = ESC_IN_DCS;
      else
        ENTER_STRING_STATE(ESC);
      continue;
    }
    else if(c == 0x07 &&  // BEL, can stand for ST in OSC or DCS state
            (vt->parser_state == OSC || vt->parser_state == DCS)) {
      // fallthrough
    }
    else if(c < 0x20) { // other C0
      if(vt->parser_state != NORMAL)
        append_strbuffer(vt, string_start, bytes + pos - string_start);
      do_control(vt, c);
      if(vt->parser_state != NORMAL)
        string_start = bytes + pos + 1;
      continue;
    }
    // else fallthrough

    switch(vt->parser_state) {
    case ESC_IN_OSC:
    case ESC_IN_DCS:
      if(c == 0x5c) { // ST
        switch(vt->parser_state) {
          case ESC_IN_OSC: vt->parser_state = OSC; break;
          case ESC_IN_DCS: vt->parser_state = DCS; break;
          default: break;
        }
        do_string(vt, string_start, bytes + pos - string_start - 1);
        ENTER_NORMAL_STATE();
        break;
      }
      vt->parser_state = ESC;
      string_start = bytes + pos;
      // else fallthrough

    case ESC:
      switch(c) {
      case 0x50: // DCS
        ENTER_STRING_STATE(DCS);
        break;
      case 0x5b: // CSI
        ENTER_STRING_STATE(CSI);
        break;
      case 0x5d: // OSC
        ENTER_STRING_STATE(OSC);
        break;
      default:
        if(c >= 0x30 && c < 0x7f) {
          /* +1 to pos because we want to include this command byte as well */
          do_string(vt, string_start, bytes + pos - string_start + 1);
          ENTER_NORMAL_STATE();
        }
        else if(c >= 0x20 && c < 0x30) {
          /* intermediate byte */
        }
        else {
          fprintf(stderr, "TODO: Unhandled byte %02x in Escape\n", c);
        }
      }
      break;

    case CSI:
      if(c >= 0x40 && c <= 0x7f) {
        /* +1 to pos because we want to include this command byte as well */

        do_string(vt, string_start, bytes + pos - string_start + 1);
        ENTER_NORMAL_STATE();
      }
      break;

    case OSC:
    case DCS:
      if(c == 0x07 || (c == 0x9c && !vt->is_utf8)) {
        do_string(vt, string_start, bytes + pos - string_start);
        ENTER_NORMAL_STATE();
      }
      break;

    case NORMAL:
      if(c >= 0x80 && c < 0xa0 && !vt->is_utf8) {
        switch(c) {
        case 0x90: // DCS
          ENTER_STRING_STATE(DCS);
          break;
        case 0x9b: // CSI
          ENTER_STRING_STATE(CSI);
          break;
        case 0x9d: // OSC
          ENTER_STRING_STATE(OSC);
          break;
        default:
          do_control(vt, c);
          break;
        }
      }
      else {
        size_t text_eaten = do_string(vt, bytes + pos, len - pos);

        if(text_eaten == 0) {
          string_start = bytes + pos;
          goto pause;
        }

        pos += (text_eaten - 1); // we'll ++ it again in a moment
      }
      break;
    }
  }

pause:
  if(string_start && string_start < len + bytes) {
    size_t remaining = len - (string_start - bytes);
    append_strbuffer(vt, string_start, remaining);
  }
}
Exemple #16
0
int extract_or_test_files()    /* return PK-type error code */
{
    uch *cd_inptr;
    int cd_incnt, error, error_in_archive=PK_COOL;
    int i, j, renamed, query, len, filnum=(-1), blknum=0;
    int *fn_matched=NULL, *xn_matched=NULL;
    ush members_remaining, num_skipped=0, num_bad_pwd=0;
    long cd_bufstart, bufstart, inbuf_offset, request;
    LONGINT old_extra_bytes=0L;
    static min_info info[DIR_BLKSIZ];


/*---------------------------------------------------------------------------
    The basic idea of this function is as follows.  Since the central di-
    rectory lies at the end of the zipfile and the member files lie at the
    beginning or middle or wherever, it is not very desirable to simply
    read a central directory entry, jump to the member and extract it, and
    then jump back to the central directory.  In the case of a large zipfile
    this would lead to a whole lot of disk-grinding, especially if each mem-
    ber file is small.  Instead, we read from the central directory the per-
    tinent information for a block of files, then go extract/test the whole
    block.  Thus this routine contains two small(er) loops within a very
    large outer loop:  the first of the small ones reads a block of files
    from the central directory; the second extracts or tests each file; and
    the outer one loops over blocks.  There's some file-pointer positioning
    stuff in between, but that's about it.  Btw, it's because of this jump-
    ing around that we can afford to be lenient if an error occurs in one of
    the member files:  we should still be able to go find the other members,
    since we know the offset of each from the beginning of the zipfile.
  ---------------------------------------------------------------------------*/

    pInfo = info;
    members_remaining = ecrec.total_entries_central_dir;
#if (defined(CRYPT) || !defined(NO_ZIPINFO))
    newzip = TRUE;
#endif

    /* malloc space for CRC table and generate it */
    if ((crc_32_tab = (ulg *)malloc(256*sizeof(ulg))) == (ulg *)NULL)
        return PK_MEM2;
    makecrc();

    /* malloc space for check on unmatched filespecs (OK if one or both NULL) */
    if (filespecs > 0  &&
        (fn_matched=(int *)malloc(filespecs*sizeof(int))) != (int *)NULL)
        for (i = 0;  i < filespecs;  ++i)
            fn_matched[i] = FALSE;
    if (xfilespecs > 0  &&
        (xn_matched=(int *)malloc(xfilespecs*sizeof(int))) != (int *)NULL)
        for (i = 0;  i < xfilespecs;  ++i)
            xn_matched[i] = FALSE;

/*---------------------------------------------------------------------------
    Begin main loop over blocks of member files.  We know the entire central
    directory is on this disk:  we would not have any of this information un-
    less the end-of-central-directory record was on this disk, and we would
    not have gotten to this routine unless this is also the disk on which
    the central directory starts.  In practice, this had better be the ONLY
    disk in the archive, but maybe someday we'll add multi-disk support.
  ---------------------------------------------------------------------------*/

    while (members_remaining) {
        j = 0;

        /*
         * Loop through files in central directory, storing offsets, file
         * attributes, case-conversion and text-conversion flags until block
         * size is reached.
         */

        while (members_remaining && (j < DIR_BLKSIZ)) {
            --members_remaining;
            pInfo = &info[j];

            if (readbuf(sig, 4) == 0) {
                error_in_archive = PK_EOF;
                members_remaining = 0;  /* ...so no more left to do */
                break;
            }
            if (strncmp(sig, central_hdr_sig, 4)) {  /* just to make sure */
                FPRINTF(stderr, LoadFarString(CentSigMsg), j);  /* sig not found */
                FPRINTF(stderr, LoadFarString(ReportMsg));   /* check binary transfers */
                error_in_archive = PK_BADERR;
                members_remaining = 0;  /* ...so no more left to do */
                break;
            }
            /* process_cdir_file_hdr() sets pInfo->hostnum, pInfo->lcflag */
            if ((error = process_cdir_file_hdr()) != PK_COOL) {
                error_in_archive = error;   /* only PK_EOF defined */
                members_remaining = 0;  /* ...so no more left to do */
                break;
            }
            if ((error = do_string(crec.filename_length,FILENAME)) != PK_COOL) {
                if (error > error_in_archive)
                    error_in_archive = error;
                if (error > PK_WARN) {  /* fatal:  no more left to do */
                    FPRINTF(stderr, LoadFarString(FilNamMsg), filename, "central");
                    members_remaining = 0;
                    break;
                }
            }
            if ((error = do_string(crec.extra_field_length, EXTRA_FIELD)) != 0)
            {
                if (error > error_in_archive)
                    error_in_archive = error;
                if (error > PK_WARN) {  /* fatal */
                    FPRINTF(stderr, LoadFarString(ExtFieldMsg), filename, "central");
                    members_remaining = 0;
                    break;
                }
            }
            if ((error = do_string(crec.file_comment_length,SKIP)) != PK_COOL) {
                if (error > error_in_archive)
                    error_in_archive = error;
                if (error > PK_WARN) {  /* fatal */
                    FPRINTF(stderr, LoadFarString(BadFileCommLength),
                            filename);
                    members_remaining = 0;
                    break;
                }
            }
            if (process_all_files) {
                if (store_info())
                    ++j;  /* file is OK; info[] stored; continue with next */
                else
                    ++num_skipped;
            } else {
                int   do_this_file = FALSE;
                char  **pfn = pfnames-1;

                while (*++pfn)
                    if (match(filename, *pfn, C_flag)) {
                        do_this_file = TRUE;   /* ^-- ignore case or not? */
                        if (fn_matched)
                            fn_matched[pfn-pfnames] = TRUE;
                        break;       /* found match, so stop looping */
                    }
                if (do_this_file) {  /* check if this is an excluded file */
                    char  **pxn = pxnames-1;

                    while (*++pxn)
                        if (match(filename, *pxn, C_flag)) {
                            do_this_file = FALSE;  /* ^-- ignore case or not? */
                            if (xn_matched)
                                xn_matched[pxn-pxnames] = TRUE;
                            break;
                        }
                }
                if (do_this_file)
                    if (store_info())
                        ++j;            /* file is OK */
                    else
                        ++num_skipped;  /* unsupp. compression or encryption */
            } /* end if (process_all_files) */


        } /* end while-loop (adding files to current block) */

        /* save position in central directory so can come back later */
        cd_bufstart = cur_zipfile_bufstart;
        cd_inptr = inptr;
        cd_incnt = incnt;

    /*-----------------------------------------------------------------------
        Second loop:  process files in current block, extracting or testing
        each one.
      -----------------------------------------------------------------------*/

        for (i = 0; i < j; ++i) {
            filnum = i + blknum*DIR_BLKSIZ;
            pInfo = &info[i];

            /* if the target position is not within the current input buffer
             * (either haven't yet read far enough, or (maybe) skipping back-
             * ward), skip to the target position and reset readbuf(). */

            /* LSEEK(pInfo->offset):  */
            request = pInfo->offset + extra_bytes;
            inbuf_offset = request % INBUFSIZ;
            bufstart = request - inbuf_offset;

            Trace((stderr, "\ndebug: request = %ld, inbuf_offset = %ld\n",
              request, inbuf_offset));
            Trace((stderr,
              "debug: bufstart = %ld, cur_zipfile_bufstart = %ld\n",
              bufstart, cur_zipfile_bufstart));
            if (request < 0) {
                FPRINTF(stderr, LoadFarStringSmall(SeekMsg), zipfn,
                  LoadFarString(ReportMsg));
                error_in_archive = PK_ERR;
                if (filnum == 0 && extra_bytes != 0L) {
                    FPRINTF(stderr, LoadFarString(AttemptRecompensate));
                    old_extra_bytes = extra_bytes;
                    extra_bytes = 0L;
                    request = pInfo->offset; /* could also check if this != 0 */
                    inbuf_offset = request % INBUFSIZ;
                    bufstart = request - inbuf_offset;
                    Trace((stderr, "debug: request = %ld, inbuf_offset = %ld\n",
                      request, inbuf_offset));
                    Trace((stderr,
                      "debug: bufstart = %ld, cur_zipfile_bufstart = %ld\n",
                      bufstart, cur_zipfile_bufstart));
                } else {
                    error_in_archive = PK_BADERR;
                    continue;  /* this one hosed; try next */
                }
            }
            /* try again */
            if (request < 0) {
                Trace((stderr, "debug: recompensated request still < 0\n"));
                FPRINTF(stderr, LoadFarStringSmall(SeekMsg), zipfn,
                  LoadFarString(ReportMsg));
                error_in_archive = PK_BADERR;
                continue;
            } else if (bufstart != cur_zipfile_bufstart) {
                Trace((stderr, "debug: bufstart != cur_zipfile_bufstart\n"));
                cur_zipfile_bufstart = lseek(zipfd,(LONGINT)bufstart,SEEK_SET);
                if ((incnt = read(zipfd,(char *)inbuf,INBUFSIZ)) <= 0) {
                    FPRINTF(stderr, LoadFarString(OffsetMsg), filnum, "lseek",
                      bufstart);
                    error_in_archive = PK_BADERR;
                    continue;   /* can still do next file */
                }
                inptr = inbuf + (int)inbuf_offset;
                incnt -= (int)inbuf_offset;
            } else {
                incnt += (inptr-inbuf) - (int)inbuf_offset;
                inptr = inbuf + (int)inbuf_offset;
            }

            /* should be in proper position now, so check for sig */
            if (readbuf(sig, 4) == 0) {  /* bad offset */
                FPRINTF(stderr, LoadFarString(OffsetMsg), filnum, "EOF",
                  request);
                error_in_archive = PK_BADERR;
                continue;   /* but can still try next one */
            }
            if (strncmp(sig, local_hdr_sig, 4)) {
                FPRINTF(stderr, LoadFarString(OffsetMsg), filnum,
                  LoadFarStringSmall(LocalHdrSig), request);
                error_in_archive = PK_ERR;
                if ((filnum == 0 && extra_bytes != 0L) ||
                    (extra_bytes == 0L && old_extra_bytes != 0L)) {
                    FPRINTF(stderr, LoadFarString(AttemptRecompensate));
                    if (extra_bytes) {
                        old_extra_bytes = extra_bytes;
                        extra_bytes = 0L;
                    } else
                        extra_bytes = old_extra_bytes;  /* third attempt */
                    LSEEK(pInfo->offset)
                    if (readbuf(sig, 4) == 0) {  /* bad offset */
                        FPRINTF(stderr, LoadFarString(OffsetMsg), filnum, "EOF",
                          request);
                        error_in_archive = PK_BADERR;
                        continue;   /* but can still try next one */
                    }
                    if (strncmp(sig, local_hdr_sig, 4)) {
                        FPRINTF(stderr, LoadFarString(OffsetMsg), filnum,
                          LoadFarStringSmall(LocalHdrSig), request);
                        error_in_archive = PK_BADERR;
                        continue;
                    }
                } else
                    continue;  /* this one hosed; try next */
            }
Exemple #17
0
int
main(int argc_orig, char **argv)
#endif
{
    int i;

    /* We want the current value of argc to persist across a LONGJMP from int_error().
     * Without this the compiler may put it on the stack, which LONGJMP clobbers.
     * Here we try make it a volatile variable that optimization will not affect.
     * Why do we not have to do the same for argv?   I don't know.
     * But the test cases that broke with generic argc seem fine with generic argv.
     */
    static volatile int argc;
    argc = argc_orig;

#ifdef LINUXVGA
    LINUX_setup();		/* setup VGA before dropping privilege DBT 4/5/99 */
    drop_privilege();
#endif
/* make sure that we really have revoked root access, this might happen if
   gnuplot is compiled without vga support but is installed suid by mistake */
#ifdef __linux__
    if (setuid(getuid()) != 0) {
	fprintf(stderr,"gnuplot: refusing to run at elevated privilege\n");
	exit(EXIT_FAILURE);
    }
#endif

/* HBB: Seems this isn't needed any more for DJGPP V2? */
/* HBB: disable all floating point exceptions, just keep running... */
#if defined(DJGPP) && (DJGPP!=2)
    _control87(MCW_EM, MCW_EM);
#endif

#if defined(OS2)
    {
	int rc;
#ifdef OS2_IPC
	char semInputReadyName[40];

	sprintf(semInputReadyName, "\\SEM32\\GP%i_Input_Ready", getpid());
	rc = DosCreateEventSem(semInputReadyName, &semInputReady, 0, 0);
	if (rc != 0)
	    fputs("DosCreateEventSem error\n", stderr);
#endif
	rc = RexxRegisterSubcomExe("GNUPLOT", (PFN) RexxInterface, NULL);
    }
#endif

/* malloc large blocks, otherwise problems with fragmented mem */
#ifdef MALLOCDEBUG
    malloc_debug(7);
#endif


/* init progpath and get helpfile from executable directory */
#if defined(MSDOS) || defined(OS2)
    {
	char *s;

#ifdef __EMX__
	_execname(progpath, sizeof(progpath));
#else
	safe_strncpy(progpath, argv[0], sizeof(progpath));
#endif
	/* convert '/' to '\\' */
	for (s = progpath; *s != NUL; s++)
	    if (*s == DIRSEP2)
		*s = DIRSEP1;
	/* cut program name */
	s = strrchr(progpath, DIRSEP1);
	if (s != NULL)
	    s++;
	else
	    s = progpath;
	*s = NUL;
	/* init HelpFile */
	strcpy(HelpFile, progpath);
	strcat(HelpFile, "gnuplot.gih");
	/* remove trailing "bin/" from progpath */
	if ((s != NULL) && (s - progpath >= 4)) {
	    s -= 4;
	    if (strncasecmp(s, "bin", 3) == 0)
		*s = NUL;
	}
    }
#endif /* DJGPP */

#if (defined(PIPE_IPC) || defined(_WIN32)) && (defined(HAVE_LIBREADLINE) || (defined(HAVE_LIBEDITLINE) && defined(X11)))
    /* Editline needs this to be set before the very first call to readline(). */
    /* Support for rl_getc_function is broken for utf-8 in editline. Since it is only
       really required for X11, disable this section when building without X11. */
    rl_getc_function = getc_wrapper;
#endif

#if defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)
    /* T.Walter 1999-06-24: 'rl_readline_name' must be this fix name.
     * It is used to parse a 'gnuplot' specific section in '~/.inputrc'
     * or gnuplot specific commands in '.editrc' (when using editline
     * instead of readline) */
    rl_readline_name = "Gnuplot";
    rl_terminal_name = getenv("TERM");
#if defined(HAVE_LIBREADLINE)
    using_history();
#else
    history_init();
#endif
#endif
#if defined(HAVE_LIBREADLINE) && !defined(MISSING_RL_TILDE_EXPANSION)
    rl_complete_with_tilde_expansion = 1;
#endif

    for (i = 1; i < argc; i++) {
	if (!argv[i])
	    continue;

	if (!strcmp(argv[i], "-V") || !strcmp(argv[i], "--version")) {
	    printf("gnuplot %s patchlevel %s\n",
		    gnuplot_version, gnuplot_patchlevel);
	    return 0;

	} else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
	    printf( "Usage: gnuplot [OPTION] ... [FILE]\n"
#ifdef X11
		    "for X11 options see 'help X11->command-line-options'\n"
#endif
		    "  -V, --version\n"
		    "  -h, --help\n"
		    "  -p  --persist\n"
		    "  -s  --slow\n"
		    "  -d  --default-settings\n"
		    "  -c  scriptfile ARG1 ARG2 ... \n"
		    "  -e  \"command1; command2; ...\"\n"
		    "gnuplot %s patchlevel %s\n",
		    gnuplot_version, gnuplot_patchlevel);
#ifdef DEVELOPMENT_VERSION
	    printf(
#ifdef DIST_CONTACT
		    "Report bugs to "DIST_CONTACT"\n"
		    "            or %s\n",
#else
		    "Report bugs to %s\n",
#endif
		    bug_email);
#endif
	    return 0;

	} else if (!strncmp(argv[i], "-persist", 2) || !strcmp(argv[i], "--persist")
#ifdef _WIN32
		|| !stricmp(argv[i], "-noend") || !stricmp(argv[i], "/noend")
#endif
		) {
	    persist_cl = TRUE;
	} else if (!strncmp(argv[i], "-slow", 2) || !strcmp(argv[i], "--slow")) {
	    slow_font_startup = TRUE;
	} else if (!strncmp(argv[i], "-d", 2) || !strcmp(argv[i], "--default-settings")) {
	    /* Skip local customization read from ~/.gnuplot */
	    skip_gnuplotrc = TRUE;
	}
    }

#ifdef X11
    /* the X11 terminal removes tokens that it recognizes from argv. */
    {
	int n = X11_args(argc, argv);
	argv += n;
	argc -= n;
    }
#endif

    setbuf(stderr, (char *) NULL);

#ifdef HAVE_SETVBUF
    /* This was once setlinebuf(). Docs say this is
     * identical to setvbuf(,NULL,_IOLBF,0), but MS C
     * faults this (size out of range), so we try with
     * size of 1024 instead. [SAS/C does that, too. -lh]
     */
    if (setvbuf(stdout, (char *) NULL, _IOLBF, (size_t) 1024) != 0)
	(void) fputs("Could not linebuffer stdout\n", stderr);

    /* Switching to unbuffered mode causes all characters in the input
     * buffer to be lost. So the only safe time to do it is on program entry.
     * Do any non-X platforms suffer from this problem?
     * EAM - Jan 2013 YES.
     */
    setvbuf(stdin, (char *) NULL, _IONBF, 0);
#endif

    gpoutfile = stdout;

    /* Initialize pre-loaded user variables */
    /* "pi" is hard-wired as the first variable */
    (void) add_udv_by_name("GNUTERM");
    (void) add_udv_by_name("NaN");
    init_constants();
    udv_user_head = &(udv_NaN->next_udv);

    init_memory();

    interactive = FALSE;

    /* April 2017:  We used to call init_terminal() here, but now   */
    /* We defer initialization until error handling has been set up. */

# if defined(_WIN32) && !defined(WGP_CONSOLE)
    interactive = TRUE;
# else
    interactive = isatty(fileno(stdin));
# endif

    /* Note: we want to know whether this is an interactive session so that we can
     * decide whether or not to write status information to stderr.  The old test
     * for this was to see if (argc > 1) but the addition of optional command line
     * switches broke this.  What we really wanted to know was whether any of the
     * command line arguments are file names or an explicit in-line "-e command".
     */
    for (i = 1; i < argc; i++) {
# ifdef _WIN32
	if (!stricmp(argv[i], "/noend"))
	    continue;
# endif
	if ((argv[i][0] != '-') || (argv[i][1] == 'e') || (argv[i][1] == 'c') ) {
	    interactive = FALSE;
	    break;
	}
    }

    /* Need this before show_version is called for the first time */

    if (interactive)
	show_version(stderr);
    else
	show_version(NULL); /* Only load GPVAL_COMPILE_OPTIONS */

    update_gpval_variables(3);  /* update GPVAL_ variables available to user */

#ifdef VMS
    /* initialise screen management routines for command recall */
    {
    unsigned int ierror;
    if (ierror = smg$create_virtual_keyboard(&vms_vkid) != SS$_NORMAL)
	done(ierror);
    if (ierror = smg$create_key_table(&vms_ktid) != SS$_NORMAL)
	done(ierror);
    }
#endif /* VMS */

    if (!SETJMP(command_line_env, 1)) {
	/* first time */
	interrupt_setup();
	get_user_env();
	init_loadpath();
	init_locale();

	memset(&sm_palette, 0, sizeof(sm_palette));
	init_fit();		/* Initialization of fitting module */
#ifdef READLINE
	/* When using the built-in readline, we set the initial
	   encoding according to the locale as this is required
	   to properly handle keyboard input. */
	init_encoding();
#endif
	init_gadgets();

	/* April 2017: Now that error handling is in place, it is safe parse
	 * GNUTERM during terminal initialization.
	 * atexit processing is done in reverse order. We want
	 * the generic terminal shutdown in term_reset to be executed before
	 * any terminal specific cleanup requested by individual terminals.
	 */
	init_terminal();
	push_terminal(0);	/* remember the initial terminal */
	gp_atexit(term_reset);

	/* Execute commands in ~/.gnuplot */
	init_session();

	if (interactive && term != 0) {		/* not unknown */
#ifdef GNUPLOT_HISTORY
#if (defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)) && !defined(_WIN32)
	    expanded_history_filename = tilde_expand(GNUPLOT_HISTORY_FILE);
#else
	    expanded_history_filename = gp_strdup(GNUPLOT_HISTORY_FILE);
	    gp_expand_tilde(&expanded_history_filename);
#endif
	    read_history(expanded_history_filename);

	    /*
	     * It is safe to ignore the return values of 'atexit()' and
	     * 'on_exit()'. In the worst case, there is no history of your
	     * currrent session and you have to type all again in your next
	     * session.
	     */
	    gp_atexit(wrapper_for_write_history);
#endif /* GNUPLOT_HISTORY */

#if defined(READLINE) && defined(WGP_CONSOLE)
	    fprintf(stderr, "Encoding set to '%s'.\n", encoding_names[encoding]);
#endif
	}			/* if (interactive && term != 0) */
    } else {
	/* come back here from int_error() */
	if (!successful_initialization) {
	    /* Only print the warning once */
	    successful_initialization = TRUE;
	    fprintf(stderr,"WARNING: Error during initialization\n\n");
	}
	if (interactive == FALSE)
	    exit_status = EXIT_FAILURE;
#ifdef HAVE_READLINE_RESET
	else {
	    /* reset properly readline after a SIGINT+longjmp */
	    rl_reset_after_signal ();
	}
#endif

	load_file_error();	/* if we were in load_file(), cleanup */
	SET_CURSOR_ARROW;

#ifdef VMS
	/* after catching interrupt */
	/* VAX stuffs up stdout on SIGINT while writing to stdout,
	   so reopen stdout. */
	if (gpoutfile == stdout) {
	    if ((stdout = freopen("SYS$OUTPUT", "w", stdout)) == NULL) {
		/* couldn't reopen it so try opening it instead */
		if ((stdout = fopen("SYS$OUTPUT", "w")) == NULL) {
		    /* don't use int_error here - causes infinite loop! */
		    fputs("Error opening SYS$OUTPUT as stdout\n", stderr);
		}
	    }
	    gpoutfile = stdout;
	}
#endif /* VMS */

	/* Why a goto?  Because we exited the loop below via int_error */
	/* using LONGJMP.  The compiler was not expecting this, and    */
	/* "optimized" the handling of argc and argv such that simply  */
	/* entering the loop again from the top finds them messed up.  */
	/* If we reenter the loop via a goto then there is some hope   */
	/* that code reordering does not hurt us.                      */
	if (reading_from_dash && interactive)
	    goto RECOVER_FROM_ERROR_IN_DASH;
	reading_from_dash = FALSE;

	if (!interactive && !noinputfiles) {
	    term_reset();
	    gp_exit(EXIT_FAILURE);	/* exit on non-interactive error */
	}
    }

    /* load filenames given as arguments */
    while (--argc > 0) {
	    ++argv;
	    c_token = 0;
	    if (!strncmp(*argv, "-persist", 2) || !strcmp(*argv, "--persist")
#ifdef _WIN32
		|| !stricmp(*argv, "-noend") || !stricmp(*argv, "/noend")
#endif
	    ) {
		FPRINTF((stderr,"'persist' command line option recognized\n"));
	    } else if (strcmp(*argv, "-") == 0) {
#if defined(_WIN32) && !defined(WGP_CONSOLE)
		TextShow(&textwin);
		interactive = TRUE;
#else
		interactive = isatty(fileno(stdin));
#endif

RECOVER_FROM_ERROR_IN_DASH:
		reading_from_dash = TRUE;
		while (!com_line());
		reading_from_dash = FALSE;
		interactive = FALSE;
		noinputfiles = FALSE;

	    } else if (strcmp(*argv, "-e") == 0) {
		int save_state = interactive;
		--argc; ++argv;
		if (argc <= 0) {
		    fprintf(stderr, "syntax:  gnuplot -e \"commands\"\n");
		    return 0;
		}
		interactive = FALSE;
		noinputfiles = FALSE;
		do_string(*argv);
		interactive = save_state;

	    } else if (!strncmp(*argv, "-slow", 2) || !strcmp(*argv, "--slow")) {
		slow_font_startup = TRUE;

	    } else if (!strncmp(*argv, "-d", 2) || !strcmp(*argv, "--default-settings")) {
		/* Ignore this; it already had its effect */
		FPRINTF((stderr, "ignoring -d\n"));

	    } else if (strcmp(*argv, "-c") == 0) {
		/* Pass command line arguments to the gnuplot script in the next
		 * argument. This consumes the remainder of the command line
		 */
		interactive = FALSE;
		noinputfiles = FALSE;
		--argc; ++argv;
		if (argc <= 0) {
		    fprintf(stderr, "syntax:  gnuplot -c scriptname args\n");
		    gp_exit(EXIT_FAILURE);
		}
		call_argc = GPMIN(9, argc - 1);
		for (i=0; i<=call_argc; i++) {
		    /* Need to stash argv[i] somewhere visible to load_file() */
		    call_args[i] = gp_strdup(argv[i+1]);
		}

		load_file(loadpath_fopen(*argv, "r"), gp_strdup(*argv), 5);
		gp_exit(EXIT_SUCCESS);

	    } else if (*argv[0] == '-') {
		fprintf(stderr, "unrecognized option %s\n", *argv);
	    } else {
		interactive = FALSE;
		noinputfiles = FALSE;
		load_file(loadpath_fopen(*argv, "r"), gp_strdup(*argv), 4);
	    }
    }

    /* take commands from stdin */
    if (noinputfiles) {
	while (!com_line())
	    ctrlc_flag = FALSE; /* reset asynchronous Ctrl-C flag */
    }

#ifdef _WIN32
    /* On Windows, handle 'persist' by keeping the main input loop running (windows/wxt), */
    /* but only if there are any windows open. Note that qt handles this properly. */
    if (persist_cl) {
	if (WinAnyWindowOpen()) {
#ifdef WGP_CONSOLE
	    if (!interactive) {
		/* no further input from pipe */
		while (WinAnyWindowOpen())
		win_sleep(100);
	    } else
#endif
	    {
		interactive = TRUE;
		while (!com_line())
		    ctrlc_flag = FALSE; /* reset asynchronous Ctrl-C flag */
		interactive = FALSE;
	    }
	}
    }
#endif

#if (defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)) && defined(GNUPLOT_HISTORY)
#if !defined(HAVE_ATEXIT) && !defined(HAVE_ON_EXIT)
    /* You should be here if you neither have 'atexit()' nor 'on_exit()' */
    wrapper_for_write_history();
#endif /* !HAVE_ATEXIT && !HAVE_ON_EXIT */
#endif /* (HAVE_LIBREADLINE || HAVE_LIBEDITLINE) && GNUPLOT_HISTORY */

#ifdef OS2
    RexxDeregisterSubcom("GNUPLOT", NULL);
#endif

    /* HBB 20040223: Not all compilers like exit() to end main() */
    /* exit(exit_status); */
#if ! defined(_WIN32)
    /* Windows does the cleanup later */
    gp_exit_cleanup();
#endif
    return exit_status;
}
Exemple #18
0
int
main(int argc, char **argv)
#endif
{
    int i;

#ifdef LINUXVGA
    LINUX_setup();		/* setup VGA before dropping privilege DBT 4/5/99 */
    drop_privilege();
#endif
/* make sure that we really have revoked root access, this might happen if
   gnuplot is compiled without vga support but is installed suid by mistake */
#ifdef __linux__
    setuid(getuid());
#endif

#if defined(MSDOS) && !defined(_Windows) && !defined(__GNUC__)
    PC_setup();
#endif /* MSDOS !Windows */

/* HBB: Seems this isn't needed any more for DJGPP V2? */
/* HBB: disable all floating point exceptions, just keep running... */
#if defined(DJGPP) && (DJGPP!=2)
    _control87(MCW_EM, MCW_EM);
#endif

#if defined(OS2)
    int rc;
#ifdef OS2_IPC
    char semInputReadyName[40];
    sprintf( semInputReadyName, "\\SEM32\\GP%i_Input_Ready", getpid() );
    rc = DosCreateEventSem(semInputReadyName,&semInputReady,0,0);
    if (rc != 0)
      fputs("DosCreateEventSem error\n",stderr);
#endif
    rc = RexxRegisterSubcomExe("GNUPLOT", (PFN) RexxInterface, NULL);
#endif

/* malloc large blocks, otherwise problems with fragmented mem */
#ifdef MALLOCDEBUG
    malloc_debug(7);
#endif

/* get helpfile from home directory */
#ifdef __DJGPP__
    {
	char *s;
	strcpy(HelpFile, argv[0]);
	for (s = HelpFile; *s; s++)
	    if (*s == DIRSEP1)
		*s = DIRSEP2;	/* '\\' to '/' */
	strcpy(strrchr(HelpFile, DIRSEP2), "/gnuplot.gih");
    }			/* Add also some "paranoid" tests for '\\':  AP */
#endif /* DJGPP */

#ifdef VMS
    unsigned int status[2] = { 1, 0 };
#endif

#if defined(HAVE_LIBEDITLINE)
    rl_getc_function = getc_wrapper;
#endif

#if defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)
    /* T.Walter 1999-06-24: 'rl_readline_name' must be this fix name.
     * It is used to parse a 'gnuplot' specific section in '~/.inputrc' 
     * or gnuplot specific commands in '.editrc' (when using editline
     * instead of readline) */
    rl_readline_name = "Gnuplot";
    rl_terminal_name = getenv("TERM");
    using_history();
#endif
#if defined(HAVE_LIBREADLINE) && !defined(MISSING_RL_TILDE_EXPANSION)
    rl_complete_with_tilde_expansion = 1;
#endif

    for (i = 1; i < argc; i++) {
	if (!argv[i])
	    continue;

	if (!strcmp(argv[i], "-V") || !strcmp(argv[i], "--version")) {
	    printf("gnuplot %s patchlevel %s\n",
		    gnuplot_version, gnuplot_patchlevel);
	    return 0;

	} else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
	    printf( "Usage: gnuplot [OPTION]... [FILE]\n"
#ifdef X11
		    "for X11 options see 'help X11->command-line-options'\n"
#endif
		    "  -V, --version\n"
		    "  -h, --help\n"
		    "  -p  --persist\n"
		    "  -e  \"command1; command2; ...\"\n"
		    "gnuplot %s patchlevel %s\n"
#ifdef DIST_CONTACT
		    "Report bugs to "DIST_CONTACT"\n"
		    "            or %s\n",
#else
		    "Report bugs to %s\n",
#endif
		    gnuplot_version, gnuplot_patchlevel, bug_email);
	    return 0;

	} else if (!strncmp(argv[i], "-persist", 2) || !strcmp(argv[i], "--persist")) {
	    persist_cl = TRUE;
	}
    }

#ifdef X11
    /* the X11 terminal removes tokens that it recognizes from argv. */
    {
	int n = X11_args(argc, argv);
	argv += n;
	argc -= n;
    }
#endif

    setbuf(stderr, (char *) NULL);

#ifdef HAVE_SETVBUF
    /* this was once setlinebuf(). Docs say this is
     * identical to setvbuf(,NULL,_IOLBF,0), but MS C
     * faults this (size out of range), so we try with
     * size of 1024 instead. [SAS/C does that, too. -lh]
     * Failing this, I propose we just make the call and
     * ignore the return : its probably not a big deal
     */
    if (setvbuf(stdout, (char *) NULL, _IOLBF, (size_t) 1024) != 0)
	(void) fputs("Could not linebuffer stdout\n", stderr);

#ifdef X11
    /* This call used to be in x11.trm, with the following comment:
     *   Multi-character inputs like escape sequences but also mouse-pasted
     *   text got buffered and therefore didn't trigger the select() function
     *   in X11_waitforinput(). Switching to unbuffered input solved this.
     *   23 Jan 2002 (joze)
     * But switching to unbuffered mode causes all characters in the input
     * buffer to be lost. So the only safe time to do it is on program entry.
     * The #ifdef X11 is probably unnecessary, but makes the change minimal.
     * Do any non-X platforms suffer from the same problem?
     * EAM - Jan 2004.
     */
    setvbuf(stdin, (char *) NULL, _IONBF, 0);
#endif

#endif

    gpoutfile = stdout;

    /* Initialize pre-loaded user variables */
    (void) Gcomplex(&udv_pi.udv_value, M_PI, 0.0);
    udv_NaN = add_udv_by_name("NaN");
    (void) Gcomplex(&(udv_NaN->udv_value), not_a_number(), 0.0);
    udv_NaN->udv_undef = FALSE;

    init_memory();

    interactive = FALSE;
    init_terminal();		/* can set term type if it likes */
    push_terminal(0);		/* remember the default terminal */

    /* reset the terminal when exiting */
    /* this is done through gp_atexit so that other terminal functions
     * can be registered to be executed before the terminal is reset. */
    GP_ATEXIT(term_reset);

# if defined(_Windows) && ! defined(WGP_CONSOLE)
    interactive = TRUE;
# else
    interactive = isatty(fileno(stdin));
# endif

    if (argc > 1)
	interactive = noinputfiles = FALSE;
    else
	noinputfiles = TRUE;

    /* Need this before show_version is called for the first time */

#ifdef HAVE_SYS_UTSNAME_H
    {
	struct utsname uts;

	/* something is fundamentally wrong if this fails ... */
	if (uname(&uts) > -1) {
# ifdef _AIX
	    strcpy(os_name, uts.sysname);
	    sprintf(os_name, "%s.%s", uts.version, uts.release);
# elif defined(SCO)
	    strcpy(os_name, "SCO");
	    strcpy(os_rel, uts.release);
# elif defined(DJGPP)
	    if (!strncmp(uts.sysname, "??Un", 4)) /* don't print ??Unknow" */
		strcpy(os_name, "Unknown");
	    else {
		strcpy(os_name, uts.sysname);
		strcpy(os_rel, uts.release);
	    }
# else
	    strcpy(os_name, uts.sysname);
	    strcpy(os_rel, uts.release);
# ifdef OS2
	    if (!strchr(os_rel,'.'))
		/* write either "2.40" or "4.0", or empty -- don't print "OS/2 1" */
		strcpy(os_rel, "");
# endif

# endif
	}
    }
#else /* ! HAVE_SYS_UTSNAME_H */

    strcpy(os_name, OS);
    strcpy(os_rel, "");

#endif /* HAVE_SYS_UTSNAME_H */

    if (interactive)
	show_version(stderr);
    else
	show_version(NULL); /* Only load GPVAL_COMPILE_OPTIONS */

#ifdef WGP_CONSOLE
#ifdef CONSOLE_SWITCH_CP
    if (cp_changed && interactive) {
	fprintf(stderr,
	    "\ngnuplot changed the codepage of this console from %i to %i to\n" \
	    "match the graph window. Some characters might only display correctly\n" \
	    "if you change the font to a non-raster type.\n", 
	    cp_input, GetConsoleCP());
    }
#else
    if ((GetConsoleCP() != GetACP()) && interactive) {
	fprintf(stderr,
	    "\nWarning: The codepage of the graph window (%i) and that of the\n" \
	    "console (%i) differ. Use `set encoding` or `!chcp` if extended\n" \
	    "characters don't display correctly.\n", 
	    GetACP(), GetConsoleCP());
    }
#endif
#endif

    update_gpval_variables(3);  /* update GPVAL_ variables available to user */

#ifdef VMS
    /* initialise screen management routines for command recall */
    if (status[1] = smg$create_virtual_keyboard(&vms_vkid) != SS$_NORMAL)
	done(status[1]);
    if (status[1] = smg$create_key_table(&vms_ktid) != SS$_NORMAL)
	done(status[1]);
#endif /* VMS */

    if (!SETJMP(command_line_env, 1)) {
	/* first time */
	interrupt_setup();
	/* should move this stuff another initialisation routine,
	 * something like init_set() maybe */
	get_user_env();
	init_loadpath();
	init_locale();
	/* HBB: make sure all variables start in the same mode 'reset'
	 * would set them to. Since the axis variables aren't in
	 * initialized arrays any more, this is now necessary... */
	reset_command();
	init_color();  /*  Initialization of color  */
	load_rcfile();
	init_fit();		/* Initialization of fitting module */

	if (interactive && term != 0) {		/* not unknown */
#ifdef GNUPLOT_HISTORY
	    FPRINTF((stderr, "Before read_history\n"));
#if defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)
	    expanded_history_filename = tilde_expand(GNUPLOT_HISTORY_FILE);
#else
	    expanded_history_filename = gp_strdup(GNUPLOT_HISTORY_FILE);
	    gp_expand_tilde(&expanded_history_filename);
#endif
	    FPRINTF((stderr, "expanded_history_filename = %s\n", expanded_history_filename));
	    read_history(expanded_history_filename);
	    {
		/* BEGIN: Go local to get environment variable */
		const char *temp_env = getenv ("GNUPLOT_HISTORY_SIZE");
		if (temp_env)
		    gnuplot_history_size = strtol (temp_env, (char **) NULL, 10);
	    } /* END: Go local to get environment variable */

	    /*
	     * It is safe to ignore the return values of 'atexit()' and
	     * 'on_exit()'. In the worst case, there is no history of your
	     * currrent session and you have to type all again in your next
	     * session.
	     * This is the default behaviour (traditional reasons), too.
	     * In case you don't have one of these functions, or you don't
	     * want to use them, 'write_history()' is called directly.
	     */
	    GP_ATEXIT(wrapper_for_write_history);
#endif /* GNUPLOT_HISTORY */

	    fprintf(stderr, "\nTerminal type set to '%s'\n", term->name);
	}			/* if (interactive && term != 0) */
    } else {
	/* come back here from int_error() */
	if (interactive == FALSE)
	    exit_status = EXIT_FAILURE;
#ifdef HAVE_READLINE_RESET
	else
	{
	    /* reset properly readline after a SIGINT+longjmp */
	    rl_reset_after_signal ();
	}
#endif

	load_file_error();	/* if we were in load_file(), cleanup */
	SET_CURSOR_ARROW;

#ifdef VMS
	/* after catching interrupt */
	/* VAX stuffs up stdout on SIGINT while writing to stdout,
	   so reopen stdout. */
	if (gpoutfile == stdout) {
	    if ((stdout = freopen("SYS$OUTPUT", "w", stdout)) == NULL) {
		/* couldn't reopen it so try opening it instead */
		if ((stdout = fopen("SYS$OUTPUT", "w")) == NULL) {
		    /* don't use int_error here - causes infinite loop! */
		    fputs("Error opening SYS$OUTPUT as stdout\n", stderr);
		}
	    }
	    gpoutfile = stdout;
	}
#endif /* VMS */
	if (!interactive && !noinputfiles) {
	    term_reset();
	    exit(EXIT_FAILURE);	/* exit on non-interactive error */
	}
    }

    if (argc > 1) {
#ifdef _Windows
	TBOOLEAN noend = persist_cl;
#endif

	/* load filenames given as arguments */
	while (--argc > 0) {
	    ++argv;
	    c_token = 0;
#ifdef _Windows
	    if (stricmp(*argv, "-noend") == 0 || stricmp(*argv, "/noend") == 0
	       	|| stricmp(*argv, "-persist") == 0)
		noend = TRUE;
	    else
#endif
	    if (!strncmp(*argv, "-persist", 2) || !strcmp(*argv, "--persist")) {
		FPRINTF((stderr,"'persist' command line option recognized\n"));

	    } else if (strcmp(*argv, "-") == 0) {
		interactive = TRUE;
		while (!com_line());
		interactive = FALSE;

	    } else if (strcmp(*argv, "-e") == 0) {
		--argc; ++argv;
		if (argc <= 0) {
		    fprintf(stderr, "syntax:  gnuplot -e \"commands\"\n");
		    return 0;
		}
		do_string(*argv);

	    } else {
		load_file(loadpath_fopen(*argv, "r"), gp_strdup(*argv), FALSE);
	    }
	}
#ifdef _Windows
	if (noend) {
	    interactive = TRUE;
	    while (!com_line());
	}
#endif
    } else {
	/* take commands from stdin */
	while (!com_line());
    }

#if (defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)) && defined(GNUPLOT_HISTORY)
#if !defined(HAVE_ATEXIT) && !defined(HAVE_ON_EXIT)
    /* You should be here if you neither have 'atexit()' nor 'on_exit()' */
    wrapper_for_write_history();
#endif /* !HAVE_ATEXIT && !HAVE_ON_EXIT */
#endif /* (HAVE_LIBREADLINE || HAVE_LIBEDITLINE) && GNUPLOT_HISTORY */

#ifdef OS2
    RexxDeregisterSubcom("GNUPLOT", NULL);
#endif

    /* HBB 20040223: Not all compilers like exit() to end main() */
    /* exit(exit_status); */
    return exit_status;
}
Exemple #19
0
/// Convenience function to evaluate a Lua expression.
///
/// \param s The Lua state.
/// \param expression The textual expression to evaluate.
/// \param nresults The number of results to leave on the stack.  Must be
///     positive.
///
/// \throw api_error If there is a problem evaluating the expression.
void
lutok::eval(state& s, const std::string& expression, const int nresults)
{
    assert(nresults > 0);
    do_string(s, "return " + expression, nresults);
}
Exemple #20
0
/** Initialize Lua state.
 * Initializes the state and makes all necessary initializations.
 * @return fresh initialized Lua state
 */
lua_State *
LuaContext::init_state()
{
  lua_State *L = luaL_newstate();
  luaL_openlibs(L);

  if (__enable_tracebacks) {
    lua_getglobal(L, "debug");
    lua_getfield(L, -1, "traceback");
    lua_remove(L, -2);
  }

  // Add package paths
  for (__slit = __package_dirs.begin(); __slit != __package_dirs.end(); ++__slit) {
    do_string(L, "package.path = package.path .. \";%s/?.lua;%s/?/init.lua\"", __slit->c_str(), __slit->c_str());
  }

  for (__slit = __cpackage_dirs.begin(); __slit != __cpackage_dirs.end(); ++__slit) {
    do_string(L, "package.cpath = package.cpath .. \";%s/?.so\"", __slit->c_str());
  }

  // load base packages
  for (__slit = __packages.begin(); __slit != __packages.end(); ++__slit) {
    do_string(L, "require(\"%s\")", __slit->c_str());
  }

  for ( __utit = __usertypes.begin(); __utit != __usertypes.end(); ++__utit) {
    tolua_pushusertype(L, __utit->second.first, __utit->second.second.c_str());
    lua_setglobal(L, __utit->first.c_str());
  }

  for ( __strings_it = __strings.begin(); __strings_it != __strings.end(); ++__strings_it) {
    lua_pushstring(L, __strings_it->second.c_str());
    lua_setglobal(L, __strings_it->first.c_str());
  }

  for ( __booleans_it = __booleans.begin(); __booleans_it != __booleans.end(); ++__booleans_it) {
    lua_pushboolean(L, __booleans_it->second);
    lua_setglobal(L, __booleans_it->first.c_str());
  }

  for ( __numbers_it = __numbers.begin(); __numbers_it != __numbers.end(); ++__numbers_it) {
    lua_pushnumber(L, __numbers_it->second);
    lua_setglobal(L, __numbers_it->first.c_str());
  }

  for ( __integers_it = __integers.begin(); __integers_it != __integers.end(); ++__integers_it) {
    lua_pushinteger(L, __integers_it->second);
    lua_setglobal(L, __integers_it->first.c_str());
  }

  LuaContext *tmpctx = new LuaContext(L);
  MutexLocker(__watchers.mutex());
  LockList<LuaContextWatcher *>::iterator i;
  for (i = __watchers.begin(); i != __watchers.end(); ++i) {
    try {
      (*i)->lua_restarted(tmpctx);
    } catch (...) {
      delete tmpctx;
      lua_close(L);
      throw;
    }
  }
  delete tmpctx;

  if ( __start_script ) {
    if (access(__start_script, R_OK) == 0) {
      // it's a file and we can access it, execute it!
      do_file(L, __start_script);
    } else {
      do_string(L, "require(\"%s\")", __start_script);
    }
  }

  return L;
}