Ejemplo n.º 1
0
int main (int argc, char *argv[])
   {
      stat   *a,*b;
      hit     h;
      int     p[FIELDS];
      char    str[256], str_last[256];
      char   *s;

      int     i, j, w, c, len = 0;
      idtype     id, threshold, sizelog = SIZELOG;
      

      a = (stat *) malloc ( sizeof (stat) * 1 << sizelog );
      b = (stat *) malloc ( sizeof (stat) * 1 << sizelog );

      threshold = atol ( argv[1] );

      while ( gets (str) )
	 {
	    s = rindex (str, ' ') + 1;
	    
	    str [ s - str - 1 ] = '\0';

	    readhit (str, &h);
	    c = atol (s);

	    if ( c < threshold ) lcheck (&h);

	    id = getid ( &h );

	    if ( !len ) 
	       { 
		  a[0].n = id; 
		  a[0].c = c; 

		  len++; 
	       }
	    else 
	       {
		  w = bfind (a, id, len);

		  if ( w == len )
		    {
		      a[w].n = id;
		      a[w].c = c;

		      len++;
		    }
		  else if ( a[w].n == id ) a[w].c+=c;
		  else 
		    {
		      memcpy ((char *)b, (char *)a + w * sizeof(stat), (len - w) * sizeof(stat));
		      a[w].n = id;
		      a[w].c = c;

		      memcpy ((char *)a + (w + 1) * sizeof(stat), (char *)b, (len - w) * sizeof(stat)); 

		      len++;
		      /*fprintf (stderr, "%d\n", len);*/
/*
		      if ( len == 2 << sizelog )
			{
			  sizelog++;
			  a = (stat *) realloc ( a, sizeof (stat) * 1 << sizelog );
			  b = (stat *) realloc ( b, sizeof (stat) * 1 << sizelog );
			}
 */
		    }
		}
	  }


      for ( i = 0; i < len; i++ )
	 {
	    unpackid (a[i].n, &h);

	    printf ("%d", h.i[0]);

	    for ( j = 1; j < FIELDS; j++ )
	       printf ("_%d", h.i[j]);

	    printf (" %d\n", a[i].c);
	 }

      return 0;

   }
void
newsyntax(rtems_shell_hexdump_globals* globals, int argc, char ***argvp)
{
	int ch;
	char *p, **argv;

  struct getopt_data getopt_reent;
  memset(&getopt_reent, 0, sizeof(getopt_data));

	argv = *argvp;
	if ((p = rindex(argv[0], 'h')) != NULL &&
	    strcmp(p, "hd") == 0) {
		/* "Canonical" format, implies -C. */
		add(globals, "\"%08.8_Ax\n\"");
		add(globals, "\"%08.8_ax  \" 8/1 \"%02x \" \"  \" 8/1 \"%02x \" ");
		add(globals, "\"  |\" 16/1 \"%_p\" \"|\\n\"");
	}
	while ((ch = getopt_r(argc, argv, "bcCde:f:n:os:vx", &getopt_reent)) != -1)
		switch (ch) {
		case 'b':
			add(globals, "\"%07.7_Ax\n\"");
			add(globals, "\"%07.7_ax \" 16/1 \"%03o \" \"\\n\"");
			break;
		case 'c':
			add(globals, "\"%07.7_Ax\n\"");
			add(globals, "\"%07.7_ax \" 16/1 \"%3_c \" \"\\n\"");
			break;
		case 'C':
			add(globals, "\"%08.8_Ax\n\"");
			add(globals, "\"%08.8_ax  \" 8/1 \"%02x \" \"  \" 8/1 \"%02x \" ");
			add(globals, "\"  |\" 16/1 \"%_p\" \"|\\n\"");
			break;
		case 'd':
			add(globals, "\"%07.7_Ax\n\"");
			add(globals, "\"%07.7_ax \" 8/2 \"  %05u \" \"\\n\"");
			break;
		case 'e':
			add(globals, getopt_reent.optarg);
			break;
		case 'f':
			addfile(globals, getopt_reent.optarg);
			break;
		case 'n':
			if ((length = atoi(getopt_reent.optarg)) < 0)
				errx(exit_jump, 1, "%s: bad length value", getopt_reent.optarg);
			break;
		case 'o':
			add(globals, "\"%07.7_Ax\n\"");
			add(globals, "\"%07.7_ax \" 8/2 \" %06o \" \"\\n\"");
			break;
		case 's':
			if ((skip = strtoll(getopt_reent.optarg, &p, 0)) < 0)
				errx(exit_jump, 1, "%s: bad skip value", getopt_reent.optarg);
			switch(*p) {
			case 'b':
				skip *= 512;
				break;
			case 'k':
				skip *= 1024;
				break;
			case 'm':
				skip *= 1048576;
				break;
			}
			break;
		case 'v':
			vflag = ALL;
			break;
		case 'x':
			add(globals, "\"%07.7_Ax\n\"");
			add(globals, "\"%07.7_ax \" 8/2 \"   %04x \" \"\\n\"");
			break;
		case '?':
			usage(globals);
		}

	if (!fshead) {
		add(globals, "\"%07.7_Ax\n\"");
		add(globals, "\"%07.7_ax \" 8/2 \"%04x \" \"\\n\"");
	}

	*argvp += getopt_reent.optind;
}
Ejemplo n.º 3
0
void registerService()
{
    DBusMessage* msg;
    DBusMessageIter args;
    DBusConnection* conn;
    DBusError err;
    DBusPendingCall* pending;
    dbus_uint32_t level;
    int fd;

    char path[PATH_MAX];
    const char *ret_string = 0;

    // initialiset the errors
    dbus_error_init(&err);
    conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
    if (dbus_error_is_set(&err)) {
       fprintf(stderr, "Connection Error (%s)\n", err.message);
       dbus_error_free(&err);
       return;
    }

    // create a new method call and check for errors
    msg = dbus_message_new_method_call("org.bluez",         // target for the method call
                                       "/",                 // object to call on
                                       "org.bluez.Manager", // interface to call on
                                       "DefaultAdapter");   // method name

    if (!dbus_connection_send_with_reply (conn, msg, &pending, -1)) {
       fprintf(stderr, "dbus-send failed: Out Of Memory!\n");
       return;
    }

    dbus_connection_flush(conn);

    dbus_message_unref(msg);
    dbus_pending_call_block(pending);
    msg = dbus_pending_call_steal_reply(pending);
    dbus_pending_call_unref(pending);

    if (!dbus_message_iter_init(msg, &args))
       fprintf(stderr, "Message has no arguments!\n");
    else if (DBUS_TYPE_OBJECT_PATH != dbus_message_iter_get_arg_type(&args))
       fprintf(stderr, "Argument is not an object path!\n");
    else
       dbus_message_iter_get_basic(&args, &ret_string);

    if(!ret_string){
        fprintf(stderr, "Failed to get bluez path\n");
        return;
    }

    strcpy(path, ret_string);
    // change path to use any
    strcpy(rindex(path, '/'), "/any");

    printf("Using path: %s\n", path);   

    dbus_message_unref(msg);

    // create a new method call and check for errors
    msg = dbus_message_new_method_call("org.bluez",         // target for the method call
                                       path,                // object to call on
                                       "org.bluez.Service", // interface to call on
                                       "AddRecord");        // method name

    if(!dbus_message_append_args(msg, DBUS_TYPE_STRING, &xmldefn, DBUS_TYPE_INVALID)){
        fprintf(stderr, "Failed to append args\n");
        return;
    }

    // send message and get a handle for a reply
    if (!dbus_connection_send_with_reply (conn, msg, &pending, -1)) { // -1 is default timeout
       fprintf(stderr, "Out Of Memory!\n");
       exit(1);
    }
    dbus_connection_flush(conn);

    // free message
    dbus_message_unref(msg);

    // block until we receive a reply
    dbus_pending_call_block(pending);

    // get the reply message
    msg = dbus_pending_call_steal_reply(pending);
    if (NULL == msg) {
       fprintf(stderr, "Reply Null\n");
       return;
    }
    // free the pending message handle
    dbus_pending_call_unref(pending);

    // read the parameters
    if (!dbus_message_iter_init(msg, &args))
       fprintf(stderr, "Message has no arguments!\n");
    else if (DBUS_TYPE_UINT32 != dbus_message_iter_get_arg_type(&args))
       fprintf(stderr, "Argument is not int!\n");
    else
       dbus_message_iter_get_basic(&args, &level);

    printf("Got handle: 0x%x\n", level);

    // free reply
    dbus_message_unref(msg);

    dbus_connection_get_socket(conn, &fd);
    addfd(head, fd, POLLHUP|POLLNVAL, dbus_error, 0x0);
}
Ejemplo n.º 4
0
/* when cgroups are configured with cpuset, at least
 * cpuset.cpus and cpuset.mems must be set or the cgroup
 * will not be available at all.
 * we duplicate the ancestor configuration in the init step */
static int _xcgroup_cpuset_init(xcgroup_t* cg)
{
	int fstatus,i;

	char* cpuset_metafiles[] = {
		"cpus",
		"mems"
	};
	char cpuset_meta[PATH_MAX];
	char* cpuset_conf;
	size_t csize;

	xcgroup_t acg;
	char* acg_name;
	char* p;

	fstatus = XCGROUP_ERROR;

	/* load ancestor cg */
	acg_name = (char*) xstrdup(cg->name);
	p = rindex(acg_name,'/');
	if (p == NULL) {
		debug2("task/cgroup: unable to get ancestor path for "
		       "cpuset cg '%s' : %m",cg->path);
		return fstatus;
	} else
		*p = '\0';
	if (xcgroup_load(cg->ns,&acg, acg_name) != XCGROUP_SUCCESS) {
		debug2("task/cgroup: unable to load ancestor for "
		       "cpuset cg '%s' : %m",cg->path);
		return fstatus;
	}

	/* inherits ancestor params */
	for (i = 0 ; i < 2 ; i++) {
	again:
		snprintf(cpuset_meta, sizeof(cpuset_meta), "%s%s",
			 cpuset_prefix, cpuset_metafiles[i]);
		if (xcgroup_get_param(&acg,cpuset_meta,
				      &cpuset_conf,&csize)
		    != XCGROUP_SUCCESS) {
			if (!cpuset_prefix_set) {
				cpuset_prefix_set = 1;
				cpuset_prefix = "cpuset.";
				goto again;
			}

			debug("task/cgroup: assuming no cpuset cg "
			       "support for '%s'",acg.path);
			xcgroup_destroy(&acg);
			return fstatus;
		}
		if (csize > 0)
			cpuset_conf[csize-1]='\0';
		if (xcgroup_set_param(cg,cpuset_meta,cpuset_conf)
		    != XCGROUP_SUCCESS) {
			debug("task/cgroup: unable to write %s configuration "
			       "(%s) for cpuset cg '%s'",cpuset_meta,
			       cpuset_conf,cg->path);
			xcgroup_destroy(&acg);
			xfree(cpuset_conf);
			return fstatus;
		}
		xfree(cpuset_conf);
	}

	xcgroup_destroy(&acg);
	return XCGROUP_SUCCESS;
}
Ejemplo n.º 5
0
/* If 'fullpath' points to the original OpenCL library, redirect it to 'm2s-opencl.so'
 * in the same path. */
void si_emu_libopencl_redirect(struct x86_ctx_t *ctx, char *full_path, int size)
{
	char fullpath_original[MAX_PATH_SIZE];
	char buf[MAX_PATH_SIZE];
	char *relpath, *filename;
	int length;
	FILE *f;

	/* Get path length */
	snprintf(fullpath_original, sizeof fullpath_original, "%s", full_path);
	length = strlen(full_path);
	relpath = rindex(full_path, '/');
	assert(relpath && *relpath == '/');
	filename = relpath + 1;

	/* Detect an attempt to open 'libm2s-opencl' and record it */
	if (!strcmp(filename, "libm2s-opencl.so"))
	{
		/* Attempt to open original location */
		f = fopen(full_path, "r");
		if (f)
		{
			fclose(f);
			ctx->libopencl_open_attempt = 0;
		}
		else
		{
			/* Attempt to open 'libm2s-openc.so' in current directory */
			if (!getcwd(buf, MAX_PATH_SIZE))
				fatal("%s: cannot get current directory", __FUNCTION__);
			sprintf(full_path, "%s/libm2s-opencl.so", buf);
			f = fopen(full_path, "r");
			if (f)
			{
				fclose(f);
				warning("path '%s' has been redirected to '%s'\n"
					"\tYour application is trying to access the Multi2Sim OpenCL library. A copy of\n"
					"\tthis library has been found in the current working directory, and this copy\n"
					"\twill be used in the linker. To avoid this message, please link your program\n"
					"\tstatically. See the Multi2Sim Guide for further details (www.multi2sim.org).\n",
					fullpath_original, full_path);
				ctx->libopencl_open_attempt = 0;
			}
			else
			{
				/* Attemps failed, record this. */
				ctx->libopencl_open_attempt = 1;
			}
		}
	}

	/* Translate libOpenCL -> libm2s-opencl */
	if (!strcmp(filename, "libOpenCL.so") || !strncmp(filename, "libOpenCL.so.", 13))
	{
		/* Translate name in same path */
		full_path[length - 13] = '\0';
		snprintf(buf, MAX_STRING_SIZE, "%s/libm2s-opencl.so", full_path);
		strncpy(full_path, buf, size);
		f = fopen(full_path, "r");

		/* If attempt failed, translate name into current working directory */
		if (!f)
		{
			if (!getcwd(buf, MAX_PATH_SIZE))
				fatal("%s: cannot get current directory", __FUNCTION__);
			sprintf(full_path, "%s/libm2s-opencl.so", buf);
			f = fopen(full_path, "r");
		}

		/* End of attempts */
		if (f)
		{
			fclose(f);
			warning("path '%s' has been redirected to '%s'\n"
				"\tYour application is trying to access the default OpenCL library, which is being\n"
				"\tredirected by Multi2Sim to its own provided library. Though this should work,\n"
				"\tthe safest way to simulate an OpenCL program is by linking it initially with\n"
				"\t'libm2s-opencl.so'. See the Multi2Sim Guide for further details (www.multi2sim.org).\n",
				fullpath_original, full_path);
			ctx->libopencl_open_attempt = 0;
		}
		else
		{
			ctx->libopencl_open_attempt = 1;
		}
	}
}
Ejemplo n.º 6
0
/*******************************************
 * API - create a new service mailbox
 * A mailbox is created in SRV_INIT state
 *
 * IN:
 *  name - tag name of the mailbox
 *  size - size of the mailbox
 *******************************************/
mb_id_t
mb_create(const char* tag,
          size_t size)
{
    mb_handle_t* mbhdl;
    mb_hdr_t*    mbhdr;
    char         mbname[MAXPATHLEN];
    char*        ptag;
    const char   c = 0;

    /*
     * bad tag name length 
    */
    if (strlen(tag) >= MAILBOX_TAG_MAXLEN) {
        return (MB_INVALID_ID);
    }

    /*
     * Try to allocate the mailbox handle
     */
    mbhdl = (mb_handle_t*) malloc(sizeof(mb_handle_t));
    if (mbhdl == NULL) {
        return (MB_INVALID_ID);
    }

    /*
     * Create the corresponding tmpfs file
     */
 
    /* Create the mailbox file */
    
    snprintf(mbname, sizeof(mbname), "%s/%s",
             MAILBOX_PATH, tag);
    mbhdl->fd = open(mbname, O_RDWR | O_CREAT | O_TRUNC, MAILBOX_MODE);
    if (mbhdl->fd == -1) {
        free(mbhdl);
        return(MB_INVALID_ID);
    }
    size += sizeof(mb_hdr_t);
    lseek(mbhdl->fd, size - 1, SEEK_SET);
    write(mbhdl->fd, &c, 1);

    /*
     * Map the mailbox in caller address space
     */
    mbhdl->maddr = mmap(NULL,
                        size,
                        PROT_READ | PROT_WRITE,
                        MAP_SHARED,
                        mbhdl->fd,
                        0);

    if (mbhdl->maddr == MAP_FAILED) {
        close(mbhdl->fd);
        free(mbhdl);
        (void) unlink(mbname);
        return (MB_INVALID_ID);
    }

    /*
     * Initialize mailbox header
     */
    mbhdr = (mb_hdr_t*) mbhdl->maddr;
    mbhdl->valid     = MB_VALID;
    mbhdl->flags     = MB_CREATOR;
    mbhdr->version   = MAILBOX_VER;
    mbhdr->ttSize    = size;
    mbhdr->usrClbk   = NULL;
    mbhdr->curState  = SRV_INIT;
    mbhdr->rqstState = SRV_INVALID;

    ptag = rindex(mbname, '/');
    if (ptag == NULL) {
        ptag = mbname;
    }
    strncpy(mbhdr->mboxTag, ptag, sizeof(mbhdr->mboxTag));

    /* multicast this mailbox */
    _mb_net_send(mbhdr);

    return (mb_id_t) (mbhdl);
}
Ejemplo n.º 7
0
int 
main (int argc, char *argv[]) {
  char *filename;
  char *divstring = NULL, *lasttypestring, *ptr;
  Univcoord_T univ_coordstart, univ_coordend;
  Chrpos_T coordstart, coordend, lastcoord = 0U;
  char Buffer[BUFLEN], nocomment[BUFLEN], query[BUFLEN], typestring[BUFLEN];
  int typeint, *types, c;
  int nargs, ntypes, ndivs;
  int *value_matches = NULL, *matches = NULL;
  int n_value_matches = 0, nmatches = 0, i;
  int *leftflanks, *rightflanks, nleftflanks = 0, nrightflanks = 0;
  long int total;
  int n;
  IIT_T iit = NULL;
  Univ_IIT_T chromosome_iit = NULL;
  bool skipp, universalp;
  
  int opt;
  extern int optind;
  extern char *optarg;
  const char *long_name;
  int long_option_index = 0;

  while ((opt = getopt_long(argc,argv,"a:b:f:LCASUu:c:HRTZN",long_options,&long_option_index)) != -1) {
    switch (opt) {
    case 0:
      long_name = long_options[long_option_index].name;
      if (!strcmp(long_name,"version")) {
	print_program_version();
	exit(0);
      } else if (!strcmp(long_name,"help")) {
	print_program_usage();
	exit(0);
      } else if (!strcmp(long_name,"exact")) {
	exactp = true;
      } else {
	/* Shouldn't reach here */
	fprintf(stderr,"Don't recognize option %s.  For usage, run 'gsnap --help'",long_name);
	exit(9);
      }
      break;

    case 'a': lowval = atof(optarg); user_lowvalue_p = true; value_matches_p = true; break;
    case 'b': highval = atof(optarg); user_highvalue_p = true; value_matches_p = true; break;

    case 'f': fieldstring = optarg; break;
    case 'L': force_label_p = true; break;
    case 'C': force_coords_p = true; break;
    case 'A': annotationonlyp = true; break;
    case 'S': sortp = true; break;
    case 'U': signedp = false; break;
    case 'u': nflanking = atoi(optarg); break;

    case 'c': centerp = true; centerlength = atoi(optarg); break;
    case 'H': centeruc = true; break;
    case 'R': runlengthp = true; break;
    case 'T': tallyp = true; break;
    case 'Z': zeroesp = true; break;
    case 'N': statsp = true; break;

    case 'V': print_program_version(); exit(0);
    case '?': print_program_usage(); exit(0);
    default: exit(9);
    }
  }

  argc -= (optind - 1);
  argv += (optind - 1);

  if (argc <= 1) {
    fprintf(stderr,"Need to specify an iit file.  Type \"iit_get --help\" for help.\n");
    exit(9);
  } else {
    filename = argv[1];
  }

  if (value_matches_p == true) {
    if ((iit = IIT_read(filename,/*name*/NULL,true,/*divread*/READ_ALL,/*divstring*/NULL,
			/*add_iit_p*/true,/*labels_read_p*/true)) == NULL) {
      if (Access_file_exists_p(filename) == false) {
	fprintf(stderr,"Cannot read file %s\n",filename);
      } else {
	fprintf(stderr,"File %s appears to be an invalid IIT file\n",filename);
      }
      exit(9);

    } else if (fieldstring != NULL) {
      if ((fieldint = IIT_fieldint(iit,fieldstring)) < 0) {
	fprintf(stderr,"No field %s defined in iit file.\n",fieldstring);
	exit(9);
      }
    }

    if (IIT_valuep(iit) == false) {
      fprintf(stderr,"Error: This IIT file does not have values stored\n");
      exit(9);
    }

    if (user_lowvalue_p == true && user_highvalue_p == true) {
      if (lowval > highval) {
	fprintf(stderr,"Cannot have lowval %f > highval %f\n",lowval,highval);
	exit(9);
      } else {
	value_matches = IIT_get_values_between(&n_value_matches,iit,lowval,highval,/*sortp*/false);
      }
    } else if (user_lowvalue_p == true) {
      value_matches = IIT_get_values_above(&n_value_matches,iit,lowval,/*sortp*/false);
      
    } else { /* user_highvalue_p == true */
      value_matches = IIT_get_values_below(&n_value_matches,iit,highval,/*sortp*/false);
    }
  }

  if (0 && statsp == true && argc == 2) {
    /* Want total over entire IIT */
    if ((iit = IIT_read(filename,NULL,true,/*divread*/READ_ALL,/*divstring*/NULL,/*add_iit_p*/true,
			/*labels_read_p*/false)) == NULL) {
      if (Access_file_exists_p(filename) == false) {
	fprintf(stderr,"Cannot read file %s\n",filename);
      } else {
	fprintf(stderr,"File %s appears to be an invalid IIT file\n",filename);
      }
      exit(9);

    } else if (fieldstring != NULL) {
      if ((fieldint = IIT_fieldint(iit,fieldstring)) < 0) {
	fprintf(stderr,"No field %s defined in iit file.\n",fieldstring);
	exit(9);
      }
    } 

    total = 0;
    n = 0;
    for (i = 0; i < IIT_total_nintervals(iit); i++) {
      debug(printf("index = %d\n",matches[i]));
      compute_totals_tally(&total,&n,/*coordstart*/0,/*coordend*/-1U,i,iit);
    }
    printf("counts:%ld non-zero-positions:%u mean-over-nonzero:%.3f\n",total,n,(double) total/(double) n);
      
    IIT_free(&iit);
    return 0;

  } else if ((universalp = IIT_universalp(filename,/*add_iit_p*/true)) == true) {
    chromosome_iit = Univ_IIT_read(filename,/*readonlyp*/true,/*add_iit_p*/true);
    if (argc != 3) {
      fprintf(stderr,"For chromosome IIT file, need to specify a query on the command line\n");
      exit(9);
    } else {
      /* Try as 0:<iitfile> 1:<query> */
      matches = get_matches_univ(&nmatches,&divstring,&univ_coordstart,&univ_coordend,
				 &leftflanks,&nleftflanks,&rightflanks,&nrightflanks,
				 argv[2],/*typestring*/NULL,&chromosome_iit,filename);

      for (i = 0; i < nmatches; i++) {
	debug(printf("\nindex = %d\n",matches[i]));
	print_interval_univ(univ_coordstart,univ_coordend,matches[i],chromosome_iit);
      }
    }

    if (divstring != NULL) {
      FREE(divstring);
    }
    Univ_IIT_free(&chromosome_iit);
    return 0;

  } else if (argc == 2 && value_matches_p == true) {
    /* Note: Could potentially handle input from stdin, but currently just deal with value_matches */

    ndivs = IIT_ndivs(iit);
    for (i = 0; i < n_value_matches; i++) {
      debug(printf("\nindex = %d\n",matches[i]));
      print_interval(&lastcoord,/*total*/0,/*divstring*/NULL,/*coordstart*/0,/*coordend*/0,
		     value_matches[i],iit,ndivs,fieldint);
    }
    
    FREE(value_matches);
    IIT_free(&iit);
    return 0;

  } else if (argc == 2) {
    debug(printf("Running under argc 2\n"));
    /* Expecting input from stdin */
      
    if ((iit = IIT_read(filename,NULL,true,/*divread*/READ_ALL,/*divstring*/NULL,/*add_iit_p*/true,
			/*labels_read_p*/true)) == NULL) {
      if (Access_file_exists_p(filename) == false) {
	fprintf(stderr,"Cannot read file %s\n",filename);
      } else {
	fprintf(stderr,"File %s appears to be an invalid IIT file\n",filename);
      }
      exit(9);
    } else if (fieldstring != NULL) {
      if ((fieldint = IIT_fieldint(iit,fieldstring)) < 0) {
	fprintf(stderr,"No field %s defined in iit file.\n",fieldstring);
	exit(9);
      }
    }
	
    while (fgets(Buffer,BUFLEN,stdin) != NULL) {
      if ((ptr = rindex(Buffer,'\n')) != NULL) {
	*ptr = '\0';
      }
      strcpy(nocomment,Buffer);
      if ((ptr = rindex(nocomment,'#')) != NULL) {
	*ptr = '\0';
      }

      skipp = false;

      if ((nargs = sscanf(nocomment,"%s %s",query,typestring)) == 2) {
	debug(printf("typestring is %s\n",typestring));
	matches = get_matches(&nmatches,&divstring,&univ_coordstart,&univ_coordend,
			      &leftflanks,&nleftflanks,&rightflanks,&nrightflanks,
			      query,typestring,&iit,filename);
	coordstart = (Chrpos_T) univ_coordstart;
	coordend = (Chrpos_T) univ_coordend;

      } else if (nargs == 1) {
	debug(printf("typestring is NULL\n"));
	matches = get_matches(&nmatches,&divstring,&univ_coordstart,&univ_coordend,
			      &leftflanks,&nleftflanks,&rightflanks,&nrightflanks,
			      query,/*typestring*/NULL,&iit,filename);
	coordstart = (Chrpos_T) univ_coordstart;
	coordend = (Chrpos_T) univ_coordend;

      } else {
	fprintf(stderr,"Can't parse line %s.  Ignoring.\n",nocomment);
	skipp = true;
      }
	
      total = 0;
      if (skipp == false) {
	fprintf(stdout,"# Query: %s\n",Buffer);
	ndivs = IIT_ndivs(iit);
	if (nflanking > 0) {
	  for (i = nleftflanks-1; i >= 0; i--) {
	    debug(printf("\nleft index = %d\n",leftflanks[i]));
	    print_interval(&lastcoord,/*total*/0,divstring,coordstart,coordend,leftflanks[i],iit,ndivs,fieldint);
	  }
	  printf("====================\n");
	  FREE(leftflanks);
	}

	lastcoord = coordstart;
	for (i = 0; i < nmatches; i++) {
	  debug(printf("\nindex = %d\n",matches[i]));
	  total = print_interval(&lastcoord,total,divstring,coordstart,coordend,matches[i],iit,ndivs,fieldint);
	}

	if (nflanking > 0) {
	  printf("====================\n");
	  for (i = 0; i < nrightflanks; i++) {
	    debug(printf("\nright index = %d\n",rightflanks[i]));
	    print_interval(&lastcoord,/*total*/0,divstring,coordstart,coordend,rightflanks[i],iit,ndivs,fieldint);
	  }
	  FREE(rightflanks);
	}

	if (zeroesp == true) {
	  while (lastcoord <= coordend) {
	    printf("%s\t%u\t%d\n",divstring,lastcoord,0);
	    lastcoord++;
	  }
	}
      }

      if (divstring != NULL) {
	FREE(divstring);
      }
      FREE(matches);
      printf("%ld\n",total);
      fprintf(stdout,"# End\n");
      fflush(stdout);
    }

    IIT_free(&iit);
    return 0;

  } else {
    /* Get coordinates/type from command line */
    if (argc == 3) {
      /* Try as 0:<iitfile> 1:<query> */
      matches = get_matches(&nmatches,&divstring,&univ_coordstart,&univ_coordend,
			    &leftflanks,&nleftflanks,&rightflanks,&nrightflanks,
			    argv[2],/*typestring*/NULL,&iit,filename);
      coordstart = (Chrpos_T) univ_coordstart;
      coordend = (Chrpos_T) univ_coordend;
    
    } else if (argc == 4) {
      /* Try as 0:<iitfile> 1:<query> 2:<type> */
      debug(printf("Running under argc 4\n"));
      matches = get_matches(&nmatches,&divstring,&univ_coordstart,&univ_coordend,
			    &leftflanks,&nleftflanks,&rightflanks,&nrightflanks,
			    argv[2],argv[3],&iit,filename);
      coordstart = (Chrpos_T) univ_coordstart;
      coordend = (Chrpos_T) univ_coordend;

    } else {
      types = (int *) CALLOC(argc-3,sizeof(int));
      for (c = 3, ntypes = 0; c < argc; c++) {
	if ((typeint = IIT_typeint(iit,argv[c])) < 0) {
	  fprintf(stderr,"No such type as %s.  Ignoring the type.\n",argv[c]);
	} else {
	  types[ntypes++] = typeint;
	  lasttypestring = argv[c];
	}
      }
      if (ntypes == 0) {
	matches = get_matches(&nmatches,&divstring,&univ_coordstart,&univ_coordend,
			      &leftflanks,&nleftflanks,&rightflanks,&nrightflanks,
			      argv[2],/*typestring*/NULL,&iit,filename);
	coordstart = (Chrpos_T) univ_coordstart;
	coordend = (Chrpos_T) univ_coordend;

      } else if (ntypes == 1) {
	matches = get_matches(&nmatches,&divstring,&univ_coordstart,&univ_coordend,
			      &leftflanks,&nleftflanks,&rightflanks,&nrightflanks,
			      argv[2],lasttypestring,&iit,filename);
	coordstart = (Chrpos_T) univ_coordstart;
	coordend = (Chrpos_T) univ_coordend;

      } else {
	matches = get_matches_multiple_typed(&nmatches,&divstring,&univ_coordstart,&univ_coordend,
					     &leftflanks,&nleftflanks,&rightflanks,&nrightflanks,
					     argv[2],types,ntypes,&iit,filename);
	coordstart = (Chrpos_T) univ_coordstart;
	coordend = (Chrpos_T) univ_coordend;
      }
    }

    if (value_matches_p == true) {
      matches = match_intersection(&nmatches,/*matches1*/matches,/*nmatches1*/nmatches,
				   /*matches2*/value_matches,/*nmatches2*/n_value_matches);
      FREE(value_matches);
    }

#if 0
    if (centerp == true) {
      print_spaces(centerlength);
      printf("*");
      print_spaces(centerlength-1);
      printf("\n");
    }
#endif

    if (statsp == true) {
      total = 0;
      n = 0;
      for (i = 0; i < nmatches; i++) {
	debug(printf("index = %d\n",matches[i]));
	compute_totals_tally(&total,&n,coordstart,coordend,matches[i],iit);
      }
      n = coordend - coordstart + 1;
      printf("counts:%ld width:%u mean:%.3f\n",total,n,(double)total/(double) n);

#if 0
    } else if (geomeanp == true) {
      logtotal = 0.0;
      total = 0;
      n = 0;
      for (i = 0; i < nmatches; i++) {
	debug(printf("index = %d\n",matches[i]));
	logtotal = compute_logtotal_tally(&total,&n,coordstart,coordend,matches[i],iit);
      }
      printf("geomean:%f totalcounts:%ld posrange:%d\n",
	     exp(logtotal/(double) (coordend - coordstart + 1)) - 1.0,total,n);
#endif

    } else {
      ndivs = IIT_ndivs(iit);
      if (nflanking > 0) {
	for (i = nleftflanks-1; i >= 0; i--) {
	  debug(printf("\nleft index = %d\n",leftflanks[i]));
	  print_interval(&lastcoord,/*total*/0,divstring,coordstart,coordend,leftflanks[i],iit,ndivs,fieldint);
	}
	printf("====================\n");
	FREE(leftflanks);
      }

      lastcoord = coordstart;
      for (i = 0; i < nmatches; i++) {
	debug(printf("\nindex = %d\n",matches[i]));
	print_interval(&lastcoord,/*total*/0,divstring,coordstart,coordend,matches[i],iit,ndivs,fieldint);
      }
      
      if (nflanking > 0) {
	printf("====================\n");
	for (i = 0; i < nrightflanks; i++) {
	  debug(printf("\nright index = %d\n",rightflanks[i]));
	  print_interval(&lastcoord,/*total*/0,divstring,coordstart,coordend,rightflanks[i],iit,ndivs,fieldint);
	}
	FREE(rightflanks);
      }
    }

    if (divstring != NULL) {
      FREE(divstring);
    }
    FREE(matches);
    IIT_free(&iit);
    return 0;
  }
}
Ejemplo n.º 8
0
//
// Save()
//
// Save values from cache to file
//
void
CPreferenceFile::Save()
{
#ifdef DEBUG
   printf("CPreferenceFile::Save() %s\n", fModified?"Modified":"Not Modified");
   dumpList(m_list);
#endif

   if (fModified)
   {
      FILE *in;
      FILE *out;
      char msg[MAXLEN];
      char *p;
      int count = 0;
      bool bQuoted = FALSE;
      bool bSaved = FALSE;
 
      // Open source and destination files
      char *outfilename = NULL;
      const char *infilename = fFileName;

      outfilename = (char *) malloc(strlen(infilename) + 64);
      sprintf(outfilename, "%s%s", fFileName, ".new");
      in = fopen (infilename, "r");
      out = fopen (outfilename, "w+");
      if (in == 0)
      {
         fprintf (stderr, "Couldn't open current config file. '%s' - %s\n",
           infilename, strerror(errno));
      }
      if (out == 0)
      {
         fprintf (stderr, "Couldn't open new config file. '%s' - %s\n",
           outfilename, strerror(errno));
      }
      else
      {
         char *sType = NULL;

         // build a copy of all the args we want to save
         CPreferenceList *pTempList = new QList<CPrefItem>;
         CPrefItem *pref;
         for( pref = m_list->first(); pref != 0; pref=m_list->next() )
         {
            if (pref->Persistent())
              pTempList->append(pref);
         }
#ifdef DEBUGSAVE
printf("CPreferenceFile::Save() Saving list:\n");
dumpList(pTempList);
#endif

         if (in)
         {
           // Parse source file
           while (fgets (msg, sizeof(msg), in) != NULL)
           {
              // terminate on CF or LF 
              p = index (msg, '\n');
              if (p)
                *p = 0;
              p = index (msg, '\r');
              if (p)
                *p = 0;
                                       
              // end of section - dump all items left in list that belong here
              if (sType && !msg[0])
              {
                bool bRemoved;
                do
                {
                  bRemoved = FALSE;
                  // done copying filters that existed in file already
                  // dump whatever is left in list
                  for( pref = pTempList->first(); pref != 0; pref = pTempList->next() )
                  {
                     char *tempStr = strdup(pref->Identifier());
//                     p = index(tempStr, '_');
                     p = rindex(tempStr, '_');
                     if (p)
                       *p++ = 0;
                     if (!strcasecmp(sType, tempStr))
                     {
                        struct timeval tv;
                        if (!gettimeofday(&tv, NULL))
                           fprintf(out, "%s\t%s\t# Added %s", p, pref->Text(), 
                               ctime(&tv.tv_sec));
                        else
                           fprintf(out, "%s\t%s\t# Added\n", p,pref->Text());
#ifdef DEBUGSAVE
  fprintf(stdout, "CPreferenceFile::Save(): '%s\t%s' - added\n", 
         pref->Identifier(), pref->Text());
#endif
                        count++;
                        pTempList->remove(pref);
                        bRemoved = TRUE;
                        break; // repeat search for more to remove
                     } // if this belongs in this section
                  } // end for all prefs in unsaved list
                } while (bRemoved);

                free(sType);
                sType = 0;

              } // end if end of section

              // Check for section name
              if (msg[0] == '[')
              {
                p = index(msg, ']');
                if (p)
                  *p = 0;
                p = index(msg, '\r');
                if (p)
                  *p = 0;
                if (sType)
                  free(sType);
                sType = strdup(msg + 1);
                fprintf(out, "[%s]", sType);  // cr will get tacked on later
#ifdef DEBUGSAVE
  fprintf(stdout, "CPreferenceFile::Save(): '[%s]' - sectionname\n", sType);
#endif
                msg[0] = 0;  // skip this line
              } // end if section name

              // treat lines beginning with # or ; as comments
              if ( (msg[0] == '#') || (msg[0] == ';'))
              {
#ifdef DEBUGSAVE
  fprintf(stdout, "CPreferenceFile::Save(): '%s' - comment\n", msg);
#endif
                 fprintf(out, "%s", msg);
                 msg[0] = 0;
              } // end if comment

              if (msg[0])
              {
                 char *tempstr = strdup(msg);
                 char *valueend = 0;
                 char *name = 0;
                 char *value = 0;
                 char *ioLine = tempstr;

                 // strip leading whitespace from line
                 while(*ioLine && isspace(*ioLine)) ioLine++;
                 name = ioLine;

                 // advance to whitespace
                 while(*ioLine && !isspace(*ioLine)) ioLine++;
                 if(*ioLine)
                   *ioLine++ = 0;

                 // strip whitespace in front of value 
                 while(*ioLine && isspace(*ioLine)) ioLine++;
                 value = ioLine;

                 // if value is quoted, parse to end of it 
                 bQuoted = FALSE;
                 if (value[0] == '"')
                 {
                    bQuoted = TRUE;
                    value++;
                    char *endquote = index(value, '\"');
                    if (endquote) 
                    {
                      *endquote = 0;
                      ioLine = endquote;
                    }
                 }

                 // advance to whitespace and terminate
                 while(*ioLine && !isspace(*ioLine)) ioLine++;
                 if(*ioLine)
                   *ioLine = 0;

                // look for a match, if found put it in the file 
                //  and remove it from the list
                char *tempstr1;
                if (sType)
                {
                   tempstr1 = (char *) malloc(strlen(sType)+strlen(name)+2);
                   sprintf(tempstr1, "%s_%s", sType, name);
                }
                else
                   tempstr1 = strdup(name);
                bSaved = FALSE;
                for(pref = pTempList->first();pref != 0;pref=pTempList->next())
                {
                  // if this is the same identifier as the one in the file 
                  if (!strcmp(pref->Identifier(), tempstr1))
                  {
                     char *ioLine1 = msg;
                     char *restofline = 0;   // everything after value
                     char *whitespace = 0;   // start of whitespace after name

                     // advance to text (name)
                     while(*ioLine1 && isspace(*ioLine1)) ioLine1++; 
                     // advance to whitespace
                     while(*ioLine1 && !isspace(*ioLine1)) ioLine1++; 
                     whitespace = ioLine1;

                     // advance to text (value)
                     while(*ioLine1 && isspace(*ioLine1)) ioLine1++; 
                     bQuoted = (ioLine1[0] == '"');
                     *ioLine1++ = 0;  // terminate it

                     if (bQuoted)
                     {
                        char *endquote = index(ioLine1, '\"');
                        if (endquote) 
                        {
                          ioLine1 = endquote;
                          ioLine1++;
                        }
                     }

                     // advance to whitespace
                     while(*ioLine1 && !isspace(*ioLine1)) ioLine1++; 
                     restofline = ioLine1;
                     if (!bQuoted)
                     {
                       fprintf(out, "%s%s%s%s\n", name, 
                                 whitespace, pref->Text(), restofline);
#ifdef DEBUGSAVE
  fprintf(stdout, "CPreferenceFile::Save(): '%s%s%s%s\n' - updated\n", 
         name, whitespace, pref->Text(), restofline);  
#endif
                     }
                     else
                     {
                       fprintf(out, "%s%s\"%s\"%s\n", name, 
                                 whitespace, pref->Text(), restofline);
#ifdef DEBUGSAVE
  fprintf(stdout, "CPreferenceFile::Save(): '%s%s%s%s\n' - updated\n", 
         name, whitespace, pref->Text(), restofline);  
#endif
                     }
                     bSaved = TRUE;
                     count++;
                     pTempList->remove(pref);
                     break;  // match found, done looking
                  } // end if match

                } // end for all entries in temp list

                // if we didn't find a match, save whatever the line was
                if (!bSaved)
                {
#ifdef DEBUGSAVE
  fprintf(stdout, "CPreferenceFile::Save(): '%s\n' - saved non update\n", 
         msg);  
#endif
                  fprintf(out, "%s\n", msg);
                }
                free(tempstr);
                free(tempstr1);

              } // end if pref 
              else
              {
                fprintf(out, "\n");
              }
            }  // end while lines in source file          
#ifdef DEBUGSAVE
  printf("\nCPreferenceFile::Save() - done parsing file-saving leftovers\n\n");
  dumpList(pTempList);
#endif
          // done copying filters that existed in file already
          // dump whatever is left in list
          if (pTempList->count() > 0)
          {
             struct timeval tv;
             if (!gettimeofday(&tv, NULL))
                fprintf(out, "\n# Added Items %s", ctime(&tv.tv_sec));
             else
                fprintf(out, "\n# Added Items\n");
             for( pref = pTempList->first(); pref != 0; pref = pTempList->next() )
             {
                fprintf(out, "%s\t%s\n", pref->Identifier(), pref->Text());
#ifdef DEBUGSAVE
  fprintf(stdout, "CPreferenceFile::Save(): '%s\t%s\n", 
         pref->Identifier(), pref->Text());
#endif
             } // end for all items in remaining list
          } // if items to be added
          if (fflush (out))
            fprintf (stderr, "Couldn't flush file. '%s' - %s\n",
              outfilename, strerror(errno));
          if (fclose (out))
            fprintf (stderr, "Couldn't flush file. '%s' - %s\n",
              outfilename, strerror(errno));                  if (in)
            fclose (in);

//          printf ("file saved '%s'\n", outfilename);

#if 1
          // rename files
          char *tempstr = (char*) malloc( (strlen(infilename) * 2) 
                              + strlen(outfilename) + 25); // should be enough
          sprintf(tempstr, "cp %s %s.bak", infilename, infilename);
#ifdef DEBUG
  printf("%s\n", tempstr);
#endif
          if (-1 == system(tempstr))
          {
            fprintf(stderr, "'%s' - failed\n", tempstr);
          }
          sprintf(tempstr, "mv -f %s %s", outfilename, infilename);
#ifdef DEBUG
   printf("%s\n", tempstr);
#endif
          if (-1 == system(tempstr))
          {
            fprintf(stderr, "'%s' - failed\n", tempstr);
          }
#endif
          free(tempstr);
          if (sType)
            free(sType);
        }
        if (outfilename)
          free(outfilename);
      } // end else file handles good

      fModified = FALSE;

   } // end if modified

} // end Save()
Ejemplo n.º 9
0
int 
main (int argc, char **argv, char **envp)
{
	char  *cp,
			 *sp;

	 fprintf (stderr, "%s\n", rosyversion);

	sysout[0] = sysdef[0] = systbl[0] = systub[0] = NULL;
	for (argc--, argv++; argc > 0; argc--, argv++) {
		cp = *argv;

		if (strcmp (cp, "-pepsy") == 0) {
			Pepsyflag++;
			continue;
		}
		if (strcmp (cp, "-defs") == 0) {
			Defsflag++;
			continue;
		}
		if (strcmp (cp, "-d") == 0) {
			dflag++;
			continue;
		}
		if (strcmp (cp, "-m") == 0) {
			mflag++;
			continue;
		}
		if (strcmp (cp, "-o") == 0) {
			if (sysout[0]) {
				 fprintf (stderr, "too many output files\n");
				exit (1);
			}
			argc--, argv++;
			if ((cp = *argv) == NULL || (*cp == '-' && cp[1] != NULL))
				goto usage;
			 strcpy (sysout, cp);

			continue;
		}
		if (strcmp (cp, "-b") == 0) {
			if (bflag) {
				 fprintf (stderr, "too many prefixes\n");
				exit (1);
			}
			argc--, argv++;
			if ((bflag = *argv) == NULL || *bflag == '-')
				goto usage;
			continue;
		}
		if (strcmp (cp, "-s") == 0) {
			sflag++;
			continue;
		}
		if (strcmp (cp, "-T") == 0) {
			if (mymodulename) {
				 fprintf (stderr, "too many table names\n");
				exit (1);
			}
			argc --;
			argv ++;
			if ((mymodulename = *argv) == NULL || *mymodulename == '-')
				goto usage;
			continue;
		}
		if (strcmp (cp, "-O") == 0) {
			argc --;
			argv ++;
			if ((cp = *argv) == NULL || (*cp == '-'))
				goto usage;
			if (oplistorig[0])
				 strcat (oplistorig, cp);
			else
				 strcpy (oplistorig, cp);
			continue;
		}

		if (sysin) {
usage:
			;
			 fprintf (stderr,
							"usage: rosy [-pepsy] [-d] [-o module.py] [-s] module.ry\n");
			exit (1);
		}

		if (*cp == '-') {
			if (*++cp != NULL)
				goto usage;
			sysin = "";
		}
		sysin = cp;

		if (sysout[0])
			continue;
		if (sp = rindex (cp, '/'))
			sp++;
		if (sp == NULL || *sp == NULL)
			sp = cp;
		sp += strlen (cp = sp) - 3;
		if (sp > cp && strcmp (sp, ".ry") == 0)
			 sprintf (sysout, "%.*s.py", sp - cp, cp);
		else
			 sprintf (sysout, "%s.py", cp);
	}

	switch (rosydebug = (cp = getenv ("ROSYTEST")) && *cp ? atoi (cp) : 0) {
	case 2:
		yydebug++;		/* fall */
	case 1:
		sflag++;		/*   .. */
	case 0:
		break;
	}

	if (sysin == NULLCP)
		sysin = "";

	if (*sysin && freopen (sysin, "r", stdin) == NULL) {
		 fprintf (stderr, "unable to read "), perror (sysin);
		exit (1);
	}

	if (strcmp (sysout, "-") == 0)
		sysout[0] = NULL;
	if (*sysout && freopen (sysout, "w", stdout) == NULL) {
		 fprintf (stderr, "unable to write "), perror (sysout);
		exit (1);
	}

	if (cp = index (rosyversion, ')'))
		for (cp++; *cp != ' '; cp++)
			if (*cp == NULL) {
				cp = NULL;
				break;
			}
	if (cp == NULL)
		cp = rosyversion + strlen (rosyversion);
	 sprintf (autogen, "%*.*s",
					cp - rosyversion, cp - rosyversion, rosyversion);
	 printf ("-- automatically generated by %s, do not edit!\n\n", autogen);

	initoidtbl ();

	exit (yyparse ());		/* NOTREACHED */
}
Ejemplo n.º 10
0
/*
 * is_llvm_bitcode_from_memory() is passed a pointer and size of a memory
 * buffer, a pointer to an arch_flag struct and an pointer to return the lto
 * module if not NULL.  If it the memory is an llvm bit code it returns 1 and
 * sets the fields in the arch flag.  If pmod is not NULL it stores the lto
 * module in their, if not it frees the lto module.  If the memory buffer is
 * not an llvm bit code it returns 0.
 */
__private_extern__ int is_llvm_bitcode_from_memory(
char *addr,
uint32_t size,
struct arch_flag *arch_flag,
void **pmod) /* maybe NULL */
{

   uint32_t bufsize;
   char *p, *prefix, *lto_path, buf[MAXPATHLEN], resolved_name[PATH_MAX];
   int i;
   void *mod;

	/*
	 * The libLTO API's can't handle empty files.  So return 0 to indicate
	 * this is not a bitcode file if it has a zero size.
	 */
	if(size == 0)
	    return(0);

	if(tried_to_load_lto == 0){
	    tried_to_load_lto = 1;
	    /*
	     * Construct the prefix to this executable assuming it is in a bin
	     * directory relative to a lib directory of the matching lto library
	     * and first try to load that.  If not then fall back to trying
	     * "/Applications/Xcode.app/Contents/Developer/Toolchains/
	     * XcodeDefault.xctoolchain/usr/lib/libLTO.dylib".
	     */
	    bufsize = MAXPATHLEN;
	    p = buf;
	    i = _NSGetExecutablePath(p, &bufsize);
	    if(i == -1){
		p = allocate(bufsize);
		_NSGetExecutablePath(p, &bufsize);
	    }
	    prefix = realpath(p, resolved_name);
	    p = rindex(prefix, '/');
	    if(p != NULL)
		p[1] = '\0';
	    lto_path = makestr(prefix, "../lib/libLTO.dylib", NULL);

	    lto_handle = dlopen(lto_path, RTLD_NOW);
	    if(lto_handle == NULL){
		free(lto_path);
		lto_path = NULL;
		lto_handle = dlopen("/Applications/Xcode.app/Contents/"
				    "Developer/Toolchains/XcodeDefault."
				    "xctoolchain/usr/lib/libLTO.dylib",
				    RTLD_NOW);
	    }
	    if(lto_handle == NULL)
		return(0);

	    lto_is_object = dlsym(lto_handle,
				  "lto_module_is_object_file_in_memory");
	    lto_create = dlsym(lto_handle, "lto_module_create_from_memory");
	    lto_create_local = dlsym(lto_handle,
				     "lto_module_create_in_local_context");
	    lto_dispose = dlsym(lto_handle, "lto_module_dispose");
	    lto_get_target = dlsym(lto_handle, "lto_module_get_target_triple");
	    lto_get_num_symbols = dlsym(lto_handle,
					"lto_module_get_num_symbols");
	    lto_get_sym_attr = dlsym(lto_handle,
				     "lto_module_get_symbol_attribute");
	    lto_get_sym_name = dlsym(lto_handle, "lto_module_get_symbol_name");

	    if(lto_is_object == NULL ||
	       lto_create == NULL ||
	       lto_dispose == NULL ||
	       lto_get_target == NULL ||
	       lto_get_num_symbols == NULL ||
	       lto_get_sym_attr == NULL ||
	       lto_get_sym_name == NULL){
		dlclose(lto_handle);
		if(lto_path != NULL)
		    free(lto_path);
		return(0);
	    }
	}
	if(lto_handle == NULL)
	    return(0);
	    
	if(!lto_is_object(addr, size))
	    return(0);
	
	if(lto_create_local)
	    mod = lto_create_local(addr, size, "is_llvm_bitcode_from_memory");
	else
	    mod = lto_create(addr, size);
	if(mod == NULL)
	    return(0);

	/*
	 * It is possible for new targets to be added to lto that are not yet
	 * known to this code.  So we will try to get lucky and let them pass
	 * through with the cputype set to 0. This should work for things
	 * like libtool(1) as long as we don't get two different unknown
	 * targets.  But we'll hope that just doesn't happen.
	 */
	arch_flag->cputype = 0;
	arch_flag->cpusubtype = 0;
	arch_flag->name = NULL;
	(void)get_lto_cputype(arch_flag, lto_get_target(mod));

	if(pmod != NULL)
	    *pmod = mod;
	else
	    lto_free(mod);

	return(1);
}
Ejemplo n.º 11
0
Archivo: ux_init.c Proyecto: ZoeB/frotz
void os_process_arguments (int argc, char *argv[])
{
    int c, i;

    char *p = NULL;
    char *blorb_ext = NULL;

    char *home;
    char configfile[FILENAME_MAX + 1];

#ifndef WIN32
    if ((getuid() == 0) || (geteuid() == 0)) {
        printf("I won't run as root!\n");
        exit(1);
    }
#endif

#ifdef WIN32
#define HOMEDIR "USERPROFILE"
#else
#define HOMEDIR "HOME"
#endif

    if ((home = getenv(HOMEDIR)) == NULL) {
        printf("Hard drive on fire!\n");
        exit(1);
    }

/*
 * It doesn't look like Frotz can reliably be resized given its current
 * screen-handling code.  While playing with Nitfol, I noticed that it
 * resized itself fairly reliably, even though the terminal looked rather
 * ugly to begin with.  Since Nitfol uses the Glk library for screen I/O,
 * I think there might be something in Glk that can make resizing easier.
 * Something to think about for later.
 *
 */

/*
    if (signal(SIGWINCH, SIG_IGN) != SIG_IGN)
	signal(SIGWINCH, sigwinch_handler);
*/

    if (signal(SIGINT, SIG_IGN) != SIG_IGN)
	signal(SIGINT, sigint_handler);

    /* First check for a "$HOME/.frotzrc". */
    /* If not found, look for CONFIG_DIR/frotz.conf */
    /* $HOME/.frotzrc overrides CONFIG_DIR/frotz.conf */

    strncpy(configfile, home, FILENAME_MAX);
    strncat(configfile, "/", 1);

    strncat(configfile, USER_CONFIG, strlen(USER_CONFIG));
    if (!getconfig(configfile)) {
	strncpy(configfile, CONFIG_DIR, FILENAME_MAX);
	strncat(configfile, "/", 1);	/* added by DJP */
	strncat(configfile, MASTER_CONFIG, FILENAME_MAX-10);
	getconfig(configfile);  /* we're not concerned if this fails */
    }

    /* Parse the options */

    do {
	c = getopt(argc, argv, "aAb:c:def:Fh:il:oOpPqr:s:S:tu:w:xZ:");
	switch(c) {
	  case 'a': f_setup.attribute_assignment = 1; break;
	  case 'A': f_setup.attribute_testing = 1; break;

	  case 'b': u_setup.background_color = getcolor(optarg);
		u_setup.force_color = 1;
		u_setup.disable_color = 0;
		if ((u_setup.background_color < 2) ||
		    (u_setup.background_color > 9))
		  u_setup.background_color = -1;
		break;
	  case 'c': f_setup.context_lines = atoi(optarg); break;
	  case 'd': u_setup.disable_color = 1; break;
	  case 'e': f_setup.sound = 1; break;
	  case 'f': u_setup.foreground_color = getcolor(optarg);
		    u_setup.force_color = 1;
		    u_setup.disable_color = 0;
	            if ((u_setup.foreground_color < 2) ||
			(u_setup.foreground_color > 9))
			u_setup.foreground_color = -1;
		    break;
	  case 'F': u_setup.force_color = 1;
		    u_setup.disable_color = 0;
		    break;
          case 'h': u_setup.screen_height = atoi(optarg); break;
	  case 'i': f_setup.ignore_errors = 1; break;
	  case 'l': f_setup.left_margin = atoi(optarg); break;
	  case 'o': f_setup.object_movement = 1; break;
	  case 'O': f_setup.object_locating = 1; break;
	  case 'p': u_setup.plain_ascii = 1; break;
	  case 'P': f_setup.piracy = 1; break;
	  case 'q': f_setup.sound = 0; break;
	  case 'r': f_setup.right_margin = atoi(optarg); break;
	  case 's': u_setup.random_seed = atoi(optarg); break;
	  case 'S': f_setup.script_cols = atoi(optarg); break;
	  case 't': u_setup.tandy_bit = 1; break;
	  case 'u': f_setup.undo_slots = atoi(optarg); break;
	  case 'w': u_setup.screen_width = atoi(optarg); break;
	  case 'x': f_setup.expand_abbreviations = 1; break;
	  case 'Z': f_setup.err_report_mode = atoi(optarg);
		    if ((f_setup.err_report_mode < ERR_REPORT_NEVER) ||
			(f_setup.err_report_mode > ERR_REPORT_FATAL))
		      f_setup.err_report_mode = ERR_DEFAULT_REPORT_MODE;
		    break;
	}

    } while (c != EOF);

    if (optind != argc - 1) {
	printf("FROTZ V%s\t", VERSION);
#ifdef OSS_SOUND
	printf("oss sound driver, ");
#endif

#ifdef USE_NCURSES
	printf("ncurses interface.");
#else
	printf("curses interface.");
#endif
	putchar('\n');

	puts (INFORMATION);
	printf ("\t-Z # error checking mode (default = %d)\n"
	    "\t     %d = don't report errors   %d = report first error\n"
	    "\t     %d = report all errors     %d = exit after any error\n\n",
	    ERR_DEFAULT_REPORT_MODE, ERR_REPORT_NEVER,
	    ERR_REPORT_ONCE, ERR_REPORT_ALWAYS,
	    ERR_REPORT_FATAL);
	exit (1);
    }

    /* This section is exceedingly messy and really can't be fixed
       without major changes all over the place.
     */

    /* Save the story file name */

    f_setup.story_file = strdup(argv[optind]);
    f_setup.story_name = strdup(basename(argv[optind]));

    /* Now strip off the extension. */
    p = rindex(f_setup.story_name, '.');
    if ((p != NULL) &&
        ((strcmp(p,EXT_BLORB2) == 0) ||
         (strcmp(p,EXT_BLORB3) == 0) ||
         (strcmp(p,EXT_BLORB4) == 0) ) )
    {
        blorb_ext = strdup(p);
    }
    else
    {
        blorb_ext = strdup(EXT_BLORB);
    }

    /* Get rid of extensions with 1 to 6 character extensions. */
    /* This will take care of an extension like ".zblorb". */
    /* More than that, there might be something weird going on */
    /* which is not our concern. */
    if (p != NULL) {
        if (strlen(p) >= 2 && strlen(p) <= 7) {
                *p = '\0';      /* extension removed */
        }
    }

    f_setup.story_path = strdup(dirname(argv[optind]));

    /* Create nice default file names */

    u_setup.blorb_name = malloc(FILENAME_MAX * sizeof(char));
    strncpy(u_setup.blorb_name, f_setup.story_name,
	strlen(f_setup.story_name) +1);
    strncat(u_setup.blorb_name, blorb_ext, strlen(blorb_ext));

    u_setup.blorb_file = malloc(strlen(f_setup.story_path) *
                sizeof(char) + strlen(u_setup.blorb_name) * sizeof(char) + 4);
    strncpy(u_setup.blorb_file, f_setup.story_path,
	strlen(f_setup.story_path));
    strncat(u_setup.blorb_file, "/", 1);
    strncat(u_setup.blorb_file, u_setup.blorb_name,
	strlen(u_setup.blorb_name) + 1);

    f_setup.script_name = malloc(strlen(f_setup.story_name) * sizeof(char) + 5);
    strncpy(f_setup.script_name, f_setup.story_name, strlen(f_setup.story_name));
    strncat(f_setup.script_name, EXT_SCRIPT, strlen(EXT_SCRIPT));

    f_setup.command_name = malloc(strlen(f_setup.story_name) * sizeof(char) + 5);
    strncpy(f_setup.command_name, f_setup.story_name, strlen(f_setup.story_name));
    strncat(f_setup.command_name, EXT_COMMAND, strlen(EXT_COMMAND));

    f_setup.save_name = malloc(strlen(f_setup.story_name) * sizeof(char) + 5);
    strncpy(f_setup.save_name, f_setup.story_name, strlen(f_setup.story_name));
    strncat(f_setup.save_name, EXT_SAVE, strlen(EXT_SAVE));

    f_setup.aux_name = malloc(strlen(f_setup.story_name) * sizeof(char) + 5);
    strncpy(f_setup.aux_name, f_setup.story_name, strlen(f_setup.story_name));
    strncat(f_setup.aux_name, EXT_AUX, strlen(EXT_AUX));

    switch (ux_init_blorb()) {
        case bb_err_Format:
	  printf("Blorb file loaded, but unable to build map.\n\n");
	  break;
	case bb_err_NotFound:
	  printf("Blorb file loaded, but lacks executable chunk.\n\n");
	  break;
    }

  printf("u_setup.blorb_file %s\n", u_setup.blorb_file);
  printf("u_setup.blorb_name %s\n", u_setup.blorb_name);

}/* os_process_arguments */
Ejemplo n.º 12
0
int main(void)
{
	int lfd, cfd, i, n;
	struct sockaddr_in serv_addr;

	lfd = socket(AF_INET, SOCK_STREAM, 0);

	memset(&serv_addr, 0, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(SERV_PORT);
	inet_pton(AF_INET, SERV_IP, &serv_addr.sin_addr.s_addr);

	bind(lfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
	if(n == -1)
		sys_err("bind error");
	listen(lfd, 20);

	while(1){
		cfd = accept(lfd, NULL, NULL);
		if(cfd ==-1)
			sys_err("accept error");
		char buf[1024], path[1024],tmp[1024];
		int fd;
		char *p,*q;
		char *filename;

		n = read(cfd, buf, 1024);
		buf[n] = '\0';
		strcpy(tmp,buf);
#if 1
		p = strstr(buf,":");
		if(p != NULL)
		{      /*download file from server*/
			filename = p+2;
#endif
			sprintf(path, "/%s",filename);

			fd = open(path, O_RDONLY);
			if(fd == -1)
				exit(1);
			while(n = read(fd, buf, 1024))
				write(cfd, buf, n);
			close(cfd);
		}
		else
		{      /*upload file to server*/
			write(cfd,"ok",3);
			q = rindex(tmp,'/');

			n = read(cfd,buf,1024);
			buf[n] = '\0';
			sprintf(path,"%s%s",buf,q);
		//	printf("path:%s\n",path);

			write(cfd,"ok",3);

			fd = open(path,O_WRONLY | O_CREAT | O_TRUNC ,0644);
			if(fd == -1)
			{
				sys_err("open error");
			}
			while(n = read(cfd,buf,1024))
				write(fd,buf,n);

			close(cfd);
			close(fd);
		}
	}
	return 0;
}
Ejemplo n.º 13
0
int do_get(const char *src, const char *dst, int sock_fd)
{
	char *dst_file; 
	char *p;
	struct stat statbuf; 
	int n, fd;
	char buf[MAX_LINE]; 
	int len;
	int res = -1; 
	
	if(src == NULL || dst == NULL){ 
		printf("wrong command\n"); 
		return -1;
	}
	
	if(src[strlen(src)-1]=='/'){
		printf("source file should be a regular file\n");
		return -1;
	}
	
   	if( (dst_file = (char *)malloc(strlen(dst) + strlen(src))) == NULL){ 
		perror("fail to malloc");
		return -1; 
	}
    
	strcpy(dst_file, dst); 
	if(dst_file[strlen(dst_file) - 1] != '/')
		strcat(dst_file, "/");
	p = rindex(src, '/'); 
    	strcat(dst_file, p + 1);  
	    	
	if((fd = open(dst_file, O_WRONLY | O_CREAT | O_TRUNC, 0644)) == -1){
	  	perror("fail to open dst-file");
	  	goto end2;
    	}
 
    	if(fstat(fd, &statbuf) == -1){ /* 取目标文件的文件状态 */
		perror("fail to stat dst-file");
	  	goto end1;
	}
	
	if(!S_ISREG(statbuf.st_mode)){
	  	printf("dst-file should be a regular file");
	  	goto end1;
	}

    	sprintf(buf, "GET %s", src); 
    	
	if(my_write(sock_fd, buf, strlen(buf)+1) == -1) 
		goto end1;
    	
	if( (n = my_read(sock_fd, buf, MAX_LINE)) <= 0){ 
		goto end1;
    	}
    	
	if(buf[0] == 'E'){ 
		write(STDOUT_FILENO, buf, n); 
	  	res = 0;
		goto end1;
    	}
    
    	len = atoi(&buf[3]);

	if(my_write(sock_fd, "RDY", 3) == -1)
		goto end1;
   
	while(1){
	 	n = my_read(sock_fd, buf, MAX_LINE);
	  	
		if(n > 0){
	    		write(fd, buf, n);
	       	len -= n;
	  	}else if(len == 0){
			printf("OK\n"); 
	       		break;
	  	}else 
			goto end1;
	}

	res = 0; 
end1:
    	free(dst_file); 
end2:       
	close(fd); 

	return res;
}
Ejemplo n.º 14
0
int do_put(const char *src, const char *dst, int sock_fd)
{
	char *dst_file; 
	struct stat statbuf;
    	int n, fd; 
	int res = -1; 
	char buf[MAX_LINE];
	char *p;

	if(src == NULL || dst == NULL){ 
		printf("wrong command\n");
		return -1;
	}

	if(src[strlen(src)-1]=='/'){ 
	  	printf("source file should be a regular file\n");
	  	return -1;
    	}
     
	if((dst_file = malloc(strlen(dst)+strlen(src)+2)) == NULL){
		perror("fail to malloc");
		return -1;
	}
	
	strcpy(dst_file, dst);
    	if(dst_file[strlen(dst_file)-1] != '/')
		strcat(dst_file, "/");
	p = rindex(src, '/');
    	strcat(dst_file, p + 1);

	if((fd = open(src, O_RDONLY)) == -1){
	  	perror("fail to open src-file");
	  	goto end1;
    	}

 	if(fstat(fd, &statbuf) == -1){
	  	perror("fail to stat src-file");
	  	goto end2;
    	}
    
	if(!S_ISREG(statbuf.st_mode)){ 
		fputs("src-file should be a regular file\n", stderr);
	  	goto end2;
    	}
    
	sprintf(buf, "PUT %d %s", statbuf.st_size, dst_file);
	if(my_write(sock_fd, buf, strlen(buf)+1) == -1) 
		goto end2;
    
	if((my_read(sock_fd, buf, MAX_LINE)) <= 0) 
	  	goto end2;
     
     	if(buf[0]=='E'){ 
	  	write(STDOUT_FILENO, buf, n);
	 	goto end2;
     	}
     
     	while(1){ 
	  	n = read(fd, buf, MAX_LINE);
	  	
		if(n > 0)
	       		if(my_write(sock_fd, buf, n) == -1)
				goto end2;
	  	else if(n == 0){
	       		printf("OK\n");
	      		break;
	  	}else{ 
	       		perror("fail to read\n");
	       		goto end2;
	  	}
	}
    
	res = 0; 
end1:
	close(fd); 
end2:
	free(dst_file); 

	return res; 
}
Ejemplo n.º 15
0
void
pf_init (global_t *gp, char *file, char *prog)
{
  FILE *pf;                     /* personal file */
  char buf[100];
  char buf2[100];
  char buf3[100];
  char *p;
  int v;

  gp->ext[0] = (pf_global_t *) malloc (sizeof (pf_global_t));
  bzero (gp->ext[0], sizeof (pf_global_t));

  pf = 0;
  if (p = getenv ("NETMAJ_LIB"))
    {
      strcpy (personal_file, p);
      strcat (personal_file, "/");
      strcat (personal_file, file);
      strcat (personal_file, ".pf");
      pf = fopen (personal_file, "r");
    }
  if (!pf)
    {
      strcpy (personal_file, NETMAJ_LIB);
      strcat (personal_file, "/");
      strcat (personal_file, file);
      strcat (personal_file, ".pf");
      pf = fopen (personal_file, "r");
    }
  if (!pf)
    {
      strcpy (personal_file, prog);
      if (p = rindex (personal_file, '/'))
        {
          p[1] = 0;
        }
      else
        {
          personal_file[0] = 0;
        }
      strcat (personal_file, file);
      strcat (personal_file, ".pf");
      pf = fopen (personal_file, "r");
    }
  if (!pf)
    {
      personal_file[0] = 0;
    }
  else
    {
      for (;;)
        {
          if (fgets (buf, 100, pf))
            {
              if (!strcmp (buf, PF_PREIDENT))
                continue;
              if (!strcmp (buf, PF_IDENT))
                break;
            }
          fclose (pf);
          personal_file[0] = 0;
          return;
        }

      while (fgets (buf, 100, pf))
        {
          if (buf[0] < 'a' || buf[0] > 'z')
            continue;
          if (sscanf (buf, PF_PARAM, buf2, buf3) == 2)
            {
              v = 0;
              sscanf (buf3, "%d", &v);
              pf_add_param (gp, buf2, v, buf3);
            }
        }
      fclose (pf);
    }
}
Ejemplo n.º 16
0
int main(int argc, char *argv[])
{
  char *data_filename, *deref_filename;
  double train_pct, prune_pct, test_pct;
  double train_accuracy, test_accuracy;
  DTNODE *tree;
  uchar *test_members, *train_members, *prune_members;
  int multiple_input_files;
  char *train_filename, *prune_filename, *test_filename;
  int num_test, num_train, num_prune, num_features, num_data;
  int depth, count, prev_count;
  int num_negatives, num_false_negatives;
  int num_positives, num_false_positives;
  void **data;
  struct timeval tv;
  unsigned int random_seed;
  SSVINFO ssvinfo;

  ssvinfo.batch = 0;

  progname = (char *) rindex(argv[0], '/');
  argv[0] = progname = (progname != NULL) ? (progname + 1) : argv[0];

  multiple_input_files = 0;
  if (argc>2){
    if (!strcmp(argv[1],"-tpt") && (argc==5)){
      train_filename = argv[2];
      prune_filename = argv[3];
      test_filename = argv[4];
      data = ReadTPT(train_filename, prune_filename, test_filename,
                     &train_members, &prune_members, &test_members,
                     &num_train, &num_prune, &num_test,
                     &num_data, &num_features, &ssvinfo);
      multiple_input_files = 1;
    } else if (!strcmp(argv[1],"-tp") && (argc==4)){
      train_filename = argv[2];
      prune_filename = argv[3];
      data = ReadTwo(train_filename, prune_filename,
		     &train_members, &prune_members,
                     &num_train, &num_prune,
                     &num_data, &num_features, &ssvinfo);
      num_test = 0;
      test_members = CREATE_BITARRAY(num_data);
      ZERO_BITARRAY(test_members,num_data);
      multiple_input_files = 1;
    } else if (!strcmp(argv[1],"-tt")&& (argc==4)){
      train_filename = argv[2];
      test_filename = argv[3];
      data = ReadTwo(train_filename, test_filename,
		     &train_members, &test_members,
                     &num_train, &num_test,
                     &num_data, &num_features, &ssvinfo);
      num_prune = 0;
      prune_members = CREATE_BITARRAY(num_data);
      ZERO_BITARRAY(prune_members,num_data);
      multiple_input_files = 1;
    }
  }

  if (!multiple_input_files){
    if (argc != 5 && argc != 7) {
      fprintf(stderr, USAGE, progname);
      exit(1);
    }
    switch (argc) {
    case 5:
      if (gettimeofday(&tv, NULL) == -1)
	SYS_ERROR1("gettimeofday(%s)", "");
      random_seed = (unsigned int) tv.tv_usec;
      train_pct = atof(argv[1]);
      prune_pct = atof(argv[2]);
      test_pct = atof(argv[3]);
      data_filename = argv[4];
      break;
    case 7:
      if ((argv[1][1] == 's') || (argv[1][1] == 'S')) {
	random_seed = atoi(argv[2]);
      } else if ((argv[1][1] == 'b') || (argv[1][1] == 'B')) {
	if (gettimeofday(&tv, NULL) == -1)
	  SYS_ERROR1("gettimeofday(%s)", "");
	random_seed = (unsigned int) tv.tv_usec;
	ssvinfo.batch = atoi(argv[2]);
      } else {
	fprintf(stderr, USAGE, progname);
	exit(1);
      }
      train_pct = atof(argv[3]);
      prune_pct = atof(argv[4]);
      test_pct = atof(argv[5]);
      data_filename = argv[6];
      break;
    default:
      fprintf(stderr, USAGE, progname);
      exit(1);
    }
    if ((random_seed < 0) ||
	(train_pct <= 0.0) || (train_pct > 1.0) ||
	(prune_pct < 0.0) || (prune_pct > 1.0) ||
	(test_pct < 0.0) || (test_pct > 1.0) ||
	(train_pct + prune_pct + test_pct > 1.00000001)) {
      fprintf(stderr, USAGE, progname);
      exit(1);
    }

    /* Memory-map the examples file. */
    data = ReadSSVFile(data_filename, &num_data, &num_features, &ssvinfo);
    
    /* Initialize random number generator. */
    srandom(random_seed);

    if (ssvinfo.batch>0) {
      BatchMain(data, num_data, num_features, train_pct, prune_pct, test_pct, &ssvinfo);
      exit(0);
    } 

    /* Partition examples in train, test and prune sets. */
    PartitionExamples(data, &num_data, num_features,
		      &train_members, &num_train,
		      &test_members, &num_test,
		      &prune_members, &num_prune,
		      train_pct, prune_pct, test_pct,
		      &ssvinfo);

    /* Print the program arguments */
    PrintSection("Program arguments");

    printf("Random seed:    %u\n", random_seed);
    printf("Training:       %.0f%% (%d examples)\n", train_pct * 100.0, num_train);
    printf("Pruning:        %.0f%% (%d examples)\n", prune_pct * 100.0, num_prune);
    printf("Testing:        %.0f%% (%d examples)\n", test_pct * 100.0, num_test);
    printf("Data filename:  %s\n", data_filename);
  }

  if (num_train == 0) {
    fprintf(stderr, "%s: no examples to train on!\n", progname);
    exit(1);
  }
  
  /* Create a decision tree and print it */
  PrintSection("Growing decision tree");

  tree = CreateDecisionTree(data, num_data, num_features, prune_pct, test_pct,
			    train_members, num_train, &ssvinfo);


  PrintSection("Printing decision tree");
  PrintDecisionTreeStructure(tree, &ssvinfo);

  PrintSection("Computing decision tree statistics");
  PrintStats(tree, data, num_data, train_members, num_train, test_members, num_test, &ssvinfo);

  /* Post-prune the decision tree. */
  if (num_prune > 0) {

    PrintSection("Pruning decision tree");

    prev_count = CountNodes(tree);

    PruneDecisionTree(tree, tree, data, num_data,
			     prune_members, num_prune, &ssvinfo);

    count = CountNodes(tree);
    
    /* If the node count decreased, something must have been pruned */

    if (count < prev_count) {
      
      printf("\nPruning reduced the tree size from %d to %d nodes\n",prev_count,count);

      PrintSection("Printing PRUNED decision tree");
      PrintDecisionTreeStructure(tree, &ssvinfo);

    } else {
      
      printf("\nPruning did not remove any nodes\n");
    
    }

    /* Print the statistics again, for comparison */

    PrintSection("Computing decision tree statistics after pruning");  
    PrintStats(tree, data, num_data, train_members, num_train, test_members, num_test, &ssvinfo);

  }

  free(train_members);
  free(test_members);
  free(prune_members);
  exit(0);
}
Ejemplo n.º 17
0
int 
f_put (char **vec)
{
	int     append;
#ifdef	BRIDGE
	int     result;
	char  *dst;
#else
	int	    sglobbed;
	char  *bp,
			 *dst,
			 **gp,
			 **src;
	char   *freedst = NULL,
			buffer[BUFSIZ];
#endif

	append = strcmp (*vec, "append") == 0;

	if (*++vec == NULL) {
#ifdef	BRIDGE
		return NOTOK;
#else
		if (getftamline ("source: ", buffer) == NOTOK || str2vec (buffer, vec) < 1)
			return OK;
		dst = NULL;
#endif
	} else {
#ifdef	BRIDGE
		dst = *vec;
#else
		char **ap;

		for (ap = vec; *ap; ap++)
			continue;
		if (--ap != vec)
			dst = *ap, *ap = NULL;
		else
			dst = NULL;
#endif
	}
#ifndef	BRIDGE
	if (!(src = xglob (vec, 0)))
		return OK;
	sglobbed = xglobbed;

	if (dst == NULL) {
		if (getftamline ("destination: ", buffer) == NOTOK) {
			blkfree (src);
			return OK;
		}
		switch (str2vec (buffer, vec)) {
		case 0:
			break;

		case 1:
			dst = *vec;
			break;

		default:
			advise (NULLCP, "too many destinations");
			goto out;
		}
	}
	if (dst && !(dst = freedst = xglob1val (dst, 0)))
		goto out;

	if (src[1] == NULL) {
		if (interrupted)
			goto out;

		if (dst == NULL) {
			switch (realstore) {
			case RFS_UNIX:
				if (dst = rindex (*src, '/'))
					dst++;
				if (dst == NULL || *dst == NULL)
					dst = *src;
				break;

			default:
				dst = *src;
				break;
			}
			dst = str2file (dst);

ask_it:
			;
			if (query)
				switch (ask ("%s %s %s", append ? "append" : "put", *src,
							 dst)) {
				case NOTOK:
					goto out;

				case OK:
				default:
					break;

				case DONE:
					goto out;
				}
		} else
			switch (realstore) {
			case RFS_UNIX:
				if (isdir (dst, NULLCP, 1) == NOTOK)
					break;
#ifdef apollo
				if (*dst == '/')
					 sprintf (bp = buffer, "%s", dst);
				else
#endif
					 sprintf (bp = buffer, "%s/", dst);
				bp += strlen (bp);
				if (dst = rindex (*src, '/'))
					dst++;
				if (dst == NULL || *dst == NULL)
					dst = *src;
				 strcpy (bp, dst);
				dst = buffer;
				goto ask_it;

			default:
				break;
			}

		dst = str2file (dst);
		 put (*src, dst, append);
		goto out;
	}

	switch (realstore) {
	case RFS_UNKNOWN:
		advise (NULLCP, "%s", rs_unknown);
		goto out;

	case RFS_UNIX:
		if (dst)
#ifdef apollo
			if (*(bp = str2file (dst)) == '/') {
				 strcpy (buffer, bp);
				bp = buffer;
			} else
#endif
				 sprintf (bp = buffer, "%s/", str2file (dst));
		else if (rcwd)
			 sprintf (bp = buffer, "%s", str2file (""));
		else
			 strcpy (bp = buffer, "./");
		bp += strlen (bp);
		break;

	default:
		advise (NULLCP, "%s", rs_support);
		goto out;
	}

	if (isdir (str2file (buffer), NULLCP, 0) == NOTOK)
		goto out;

	for (gp = src; *gp && !interrupted; gp++) {
		switch (realstore) {
		case RFS_UNIX:
			if (dst = rindex (*gp, '/'))
				dst++;
			if (dst == NULL || *dst == NULL)
				dst = *gp;
			break;

		default:
			dst = *gp;
			break;
		}
		 strcpy (bp, dst);
		dst = str2file (buffer);

		if (sglobbed) {
			if (query)
				switch (ask ("%s %s %s", append ? "append" : "put", *gp, dst)) {
				case NOTOK:
					continue;

				case OK:
				default:
					break;

				case DONE:
					goto out;
				}
			else
				advise (NULLCP, "%s %s %s", append ? "append" : "put", *gp,
						dst);
		}

		 put (*gp, dst, append);

		if (ftamfd == NOTOK)
			break;
	}

out:
	;
	blkfree (src);
	if (freedst)
		free (freedst);

	return OK;
#else
	result = put (dst, append);
	return result;
#endif
}
Ejemplo n.º 18
0
void Points::Rotate(char axis, int point_count, std::string title)
{
    int g=point_count;

    std::vector<int> index(g*g);
    std::vector<int> rindex(g*g);
    std::vector<int> It(g);
    std::vector<double> theta(g);
    std::vector<double> phi(g);
    std::vector<double> theta_rotated(g);
    std::vector<double> phi_rotated(g);



    std::vector<double> theta_index(g*g);
    std::vector<double> phi_index(g*g);
    Points::kernel_map.resize(g);
    Points::weight_map.resize(g);
    Points::fkernel_map.resize(g);
    Points::theta_prime.resize(g*g);
    Points:: phi_prime.resize(g*g);

    std::vector<std::vector<double> > kern(g);
    std::vector<std::vector<double> > fkern(g);
    std::vector<std::vector<double> > weight(g);
    std::vector<std::vector<double> > rkern(g);
    std::vector<std::vector<double> > rkern2(g);
    std::vector<std::vector<double> > rotated_kern(g);
    std::vector<double> r_weight(g*g);
    std::vector<std::vector<double> > rfkernel_value(g);

    std::vector<Vex> Original(g);
    std::vector<Vex> Rotated(g);
    Points::TtoZ.resize(g);

    theta=Points::Theta;
    phi=Points::Phi;






    if(axis=='X')
    {
        theta_rotated=Points::theta_rotatedX;
        phi_rotated=Points::phi_rotatedX;

    }
    else if(axis=='Y')
    {

        theta_rotated=Points::theta_rotatedY;
        phi_rotated=Points::phi_rotatedY;

    }
    else if(axis=='Z')
    {

        theta_rotated=Points::theta_rotatedZ;
        phi_rotated=Points::phi_rotatedZ;

    }
    else
    {

    }


    std::vector<int> i_it(g*g);
    std::vector<int> j_it(g*g);


      for(int i=0; i<g; i++)
    {

        Original[i].SphericaltoXYZ(theta[i],phi[i],1.0);
        Rotated[i].SphericaltoXYZ(theta_rotated[i], phi_rotated[i], 1.0);

       // std::cout <<"x, y, z =" << Original[i].GetX() << ", " << Original[i].GetY() << ", "<< Original[i].GetZ() << ", "<< std::endl;
    }


    for(int i=0; i<g; i++)
    {
        kern[i].resize(g);
        fkern[i].resize(g);
        weight[i].resize(g);

        rkern[i].resize(g);
        rkern2[i].resize(g);

        //std::cout << "original xyz = ("  << Original[i].GetX() << ", " << Original[i].GetY() << ", " << Original[i].GetZ() << ")" << std::endl;


    }



//------------ load unroated kernel matrix from file ------------------//


    std::cout <<axis+title << std::endl;
    std::ifstream kernel_read(title);
    kernel_read.precision(15);
    kernel_read.clear();                 // clear fail and eof bits
    kernel_read.seekg(0, std::ios::beg); // back to the start!

    int u=0;

    for(int i=0; i<g; i++)
    {
        kernel_map[i].resize(g);
        fkernel_map[i].resize(g);
        weight_map[i].resize(g);

        for(int j=0; j<g; j++)
        {
            //kernel_read >> theta_index[u] >> phi_index[u] >> kern[i][j] >> fkern[i][j] >> weight[i][j];
            kernel_read >> kern[i][j] >> fkern[i][j] >> weight[i][j];
            u++;
        }

    }

    kernel_read.close();


//--------------find index that matches rotation -----------------------//


    for(int i=0; i<g; i++)
    {
        for(int j=0; j<g; j++)
        {
            if(Original[i]==Rotated[j])
            {
                Points::TtoZ[i] = Rotated[j];
                It[i]=j;
            }
        }
    }





//-------------------use rotated index to map kernel ------------------------//

    for(int i=0; i<g; i++)
    {
        Points::theta_prime[i]=theta[ It[i] ];
        Points::phi_prime[i]=phi[ It[i] ];

        for(int j=0; j<g; j++)
        {
            Points::kernel_map[i][j]=kern[ It[i] ][ It[j] ];
            Points::fkernel_map[i][j]=fkern[ It[i] ][ It[j] ];
            Points::weight_map[i][j]=weight[ It[i] ][ It[j] ];

        }

    }




    std::cout << std::endl;
    std::cout << "Rotation Passed! " <<  std::endl;
    std::cout << std::endl;

}
Ejemplo n.º 19
0
int pvfs_connect(char *fs_spec)
{
    int ret = 0;
    struct PVFS_sys_mntent *me = &pvfs_mntent;
    char *cp;
    int cur_server;

    /* the following is copied from PVFS_util_init_defaults()
       in fuse/lib/pvfs2-util.c */

    /* initialize pvfs system interface */
    ret = PVFS_sys_initialize(GOSSIP_NO_DEBUG);
    if (ret < 0)
    {
        return(ret);
    }

    /* the following is copied from PVFS_util_parse_pvfstab()
       in fuse/lib/pvfs2-util.c */
    memset( me, 0, sizeof(pvfs_mntent) );

    /* Enable integrity checks by default */
    me->integrity_check = 1;
    /* comma-separated list of ways to contact a config server */
    me->num_pvfs_config_servers = 1;

    for (cp=fs_spec; *cp; cp++)
        if (*cp == ',')
            ++me->num_pvfs_config_servers;

    /* allocate room for our copies of the strings */
    me->pvfs_config_servers =
        malloc(me->num_pvfs_config_servers *
               sizeof(*me->pvfs_config_servers));
    if (!me->pvfs_config_servers)
        exit(-1);
    memset(me->pvfs_config_servers, 0,
           me->num_pvfs_config_servers * sizeof(*me->pvfs_config_servers));

    me->mnt_dir = NULL;
    me->mnt_opts = NULL;

    cp = fs_spec;
    cur_server = 0;
    for (;;) {
        char *tok;
        int slashcount;
        char *slash;
        char *last_slash;

        tok = strsep(&cp, ",");
        if (!tok) break;

        slash = tok;
        slashcount = 0;
        while ((slash = index(slash, '/')))
        {
            slash++;
            slashcount++;
        }
        if (slashcount != 3)
        {
            fprintf(stderr,"Error: invalid FS spec: %s\n",
                    fs_spec);
            exit(-1);
        }

        /* find a reference point in the string */
        last_slash = rindex(tok, '/');
        *last_slash = '\0';

        /* config server and fs name are a special case, take one 
         * string and split it in half on "/" delimiter
         */
        me->pvfs_config_servers[cur_server] = strdup(tok);
        if (!me->pvfs_config_servers[cur_server])
            exit(-1);

        ++last_slash;

        if (cur_server == 0) {
            me->pvfs_fs_name = strdup(last_slash);
            if (!me->pvfs_fs_name)
                exit(-1);
        } else {
            if (strcmp(last_slash, me->pvfs_fs_name) != 0) {
                fprintf(stderr,
                        "Error: different fs names in server addresses: %s\n",
                        fs_spec);
                exit(-1);
            }
        }
        ++cur_server;
    }

    /* FIXME flowproto should be an option */
    me->flowproto = FLOWPROTO_DEFAULT;

    /* FIXME encoding should be an option */
    me->encoding = PVFS2_ENCODING_DEFAULT;

    /* FIXME default_num_dfiles should be an option */

    ret = PVFS_sys_fs_add(me);
    if( ret < 0 )
    {
        PVFS_perror("Could not add mnt entry", ret);
        return(-1);
    }
    pvfs_fsid = me->fs_id;

    ret = pvfs_generate_serverlist();

    /* XXX: Turn off attribute caches, they screw with us.  In the future, we
     * might want to investigate invalidating them only when needed. */
    PVFS_sys_set_info(PVFS_SYS_NCACHE_TIMEOUT_MSECS, 0);
    PVFS_sys_set_info(PVFS_SYS_ACACHE_TIMEOUT_MSECS, 0);

    return ret;
}
Ejemplo n.º 20
0
static int array_request_parse_token(char *str, int *start, int *end)
  {
  int num_ids;
  long start_l;
  long end_l;
  char *idx;
  char *ridx;


  idx = index(str, '-');
  ridx = rindex(str, '-');

  /* token is not a range, parse it as a single task id */
  if (idx == NULL)
    {
    /* make sure it is a number...*/
    if (!is_num(str))
      {
      start_l = -1;
      end_l = -1;
      }
    else
      {
      /* token is a number, set start_l and end_l to the value */ 
      start_l = strtol(str, NULL, 10);
      end_l = start_l;
      }
    }
  /* index and rindex found the same '-' character, this is a range */
  else if (idx == ridx)
    {
    *idx = '\0';
    idx++;

    /* check for an invalid range */
    if (!is_num(str) || !is_num(idx))
      {
      start_l = -1;
      end_l = -1;
      }
    else
      {
      /* both sides of the range were numbers so we set start_l and end_l
         we will check later to make sure that the range is "good" */
      start_l = strtol(str, NULL, 10);
      end_l = strtol(idx, NULL, 10);
      }
    }
  /* index/rindex found different '-' characters, this can't be a good range */
  else
    {
    start_l = -1;
    end_l = -1;
    }

  /* restore the string so this function is non-destructive to the token */
  if (idx != NULL && idx == ridx)
    {
    idx--;
    *idx = '-';
    }
    

  /* make sure the start or end of the range is not out of the range for 
     job array task IDs, and make sure that end_l is not less than start_l 
     (it is OK for end_l to == start_l)*/
  if (start_l < 0 || start_l >= INT_MAX || end_l < 0 || end_l >= INT_MAX
      || start_l > PBS_MAXJOBARRAY || end_l > PBS_MAXJOBARRAY || end_l < start_l)
    {
    *start = -1;
    *end = -1;
    num_ids = 0;
    }
  else
    {
    /* calculate the number of task IDs in the range, and cast the start_l and
       end_l to ints when setting start and end (we already confirmed that 
       start_l and end_l are > 0 and <= INT_MAX, so we will not under/overflow)
      */
    num_ids = end_l - start_l + 1;
    *start = (int)start_l;
    *end   = (int)end_l;
    }

  return num_ids;
  }
Ejemplo n.º 21
0
Archivo: util.c Proyecto: AEliu/calibre
EXPORT
int
run(const char **ENV_VARS, const char **ENV_VAR_VALS, char *PROGRAM,
        const char *MODULE, const char *FUNCTION, const char *PYVER,
        int IS_GUI, int argc, const char **argv, const char **envp) {
    char *pathPtr = NULL, *t = NULL;
    char buf[3*PATH_MAX];
    int ret = 0, i;
    PyObject *site, *mainf, *res;
    uint32_t buf_size = PATH_MAX+1;
    char *ebuf = calloc(buf_size, sizeof(char));

    ret = _NSGetExecutablePath(ebuf, &buf_size);
    if (ret == -1) {
        free(ebuf);
        ebuf = calloc(buf_size, sizeof(char));
        if (_NSGetExecutablePath(ebuf, &buf_size) != 0)
            return report_error("Failed to find real path of executable.");
    }
    pathPtr = realpath(ebuf, buf);
    if (pathPtr == NULL) {
        return report_error(strerror(errno));
    }
    for (i = 0; i < 3; i++) {
        t = rindex(pathPtr, '/');
        if (t == NULL) return report_error("Failed to determine bundle path.");
        *t = '\0';
    }
    if (strstr(pathPtr, "/calibre.app/Contents/") != NULL) {
        // We are one of the duplicate executables created to workaround codesign's limitations
        for (i = 0; i < 2; i++) {
            t = rindex(pathPtr, '/');
            if (t == NULL) return report_error("Failed to resolve bundle path in dummy executable");
            *t = '\0';
        }
    }

    char rpath[PATH_MAX+1], exe_path[PATH_MAX+1];
    snprintf(exe_path, PATH_MAX+1, "%s/Contents", pathPtr);
    snprintf(rpath, PATH_MAX+1, "%s/Resources", exe_path);
    initialize_interpreter(ENV_VARS, ENV_VAR_VALS, PROGRAM, MODULE, FUNCTION, PYVER, IS_GUI,
            exe_path, rpath, argc, argv);

    site = PyImport_ImportModule("site");

    if (site == NULL)
        ret = calibre_show_python_error("Failed to import site module",  -1);
    else {
        Py_XINCREF(site);

        mainf = PyObject_GetAttrString(site, "main");
        if (mainf == NULL || !PyCallable_Check(mainf)) 
            ret = calibre_show_python_error("site module has no main function", -1);
        else {
            Py_XINCREF(mainf);
            res = PyObject_CallObject(mainf, NULL);

            if (res == NULL) 
                ret = calibre_show_python_error("Python function terminated unexpectedly", -1);
            else {
            }
        }
    }
    PyErr_Clear();
    Py_Finalize();

    //printf("11111 Returning: %d\r\n", ret);
    return ret;
}
Ejemplo n.º 22
0
/******************************************************************************
 * parseArgs
 ******************************************************************************/
 void parseArgs(Int argc, Char *argv[], Args *argsp)
{
   // const Char shortOptions[] = "a:s:v:y:O:kt:lfoh";
   const Char shortOptions[] = "v:y:O:kt:lfoh";
    const struct option longOptions[] = {
        {"videofile",        required_argument, NULL, 'v'},
        {"display_standard", required_argument, NULL, 'y'},
        {"display_output",   required_argument, NULL, 'O'},
        {"keyboard",         no_argument,       NULL, 'k'},
        {"time",             required_argument, NULL, 't'},
        {"loop",             no_argument,       NULL, 'l'},
        {"osd",              no_argument,       NULL, 'o'},
        {"help",             no_argument,       NULL, 'h'},
        {"exit",             no_argument,       NULL, 'e'},            
        {0, 0, 0, 0}
    };

    Int   index;
    Int   c;
    Char *extension;

    for (;;) {
        c = getopt_long(argc, argv, shortOptions, longOptions, &index);

        if (c == -1) {
            break;
        }

        switch (c) {
            case 0:
                break;

            case 'v':
                extension = rindex(optarg, '.');
                if (extension == NULL) {
                    fprintf(stderr, "Video file without extension: %s\n",
                            optarg);
                    exit(EXIT_FAILURE);
                }

                argsp->videoDecoder =
                    getCodec(extension, engine->videoDecoders);

                if (!argsp->videoDecoder) {
                    fprintf(stderr, "Unknown video file extension: %s\n",
                            extension);
                    exit(EXIT_FAILURE);
                }
                argsp->videoFile = optarg;

                break;

            case 'y':
                switch (atoi(optarg)) {
                    case 1:
                        argsp->videoStd = VideoStd_D1_NTSC;
                        argsp->videoStdString = "D1 NTSC";
                        break;
                    case 2:
                        argsp->videoStd = VideoStd_D1_PAL;
                        argsp->videoStdString = "D1 PAL";
                        break;
                    case 3:
                        argsp->videoStd = VideoStd_720P_60;
                        argsp->videoStdString = "720P 60Hz";
                        break;
                    case 5:
                        argsp->videoStd = VideoStd_1080I_30;
                        argsp->videoStdString = "1080I 30Hz";
                        break;
                    default:
                        fprintf(stderr, "Unknown display resolution\n");
                        usage();
                        exit(EXIT_FAILURE);
                }
                break;

            case 'O':
                if (strcmp(optarg, "component") == 0) {
                    argsp->displayOutput = Display_Output_COMPONENT;
                } else if (strcmp(optarg, "composite") == 0) {
                    argsp->displayOutput = Display_Output_COMPOSITE;
                } else {
                    fprintf(stderr, "Unknown video output: %s\n", optarg);
                    usage();
                    exit(EXIT_FAILURE);
                }
                break;

            case 'k':
                argsp->keyboard = TRUE;
                break;

            case 't':
                argsp->time = atoi(optarg);
                break;

            case 'l':
                argsp->loop = TRUE;
                break;

            case 'o':
                argsp->osd = TRUE;
                break;

            case 'h':
                usage();
                exit(EXIT_SUCCESS);

            default:
                usage();
                exit(EXIT_FAILURE);
        }
    }

    if (argsp->displayOutput == Display_Output_COUNT) {
        if ((argsp->videoStd == VideoStd_D1_NTSC) || 
            (argsp->videoStd == VideoStd_D1_PAL)) {
            argsp->displayOutput = Display_Output_COMPOSITE;
        } else {
            argsp->displayOutput = Display_Output_COMPONENT;
        }
    }
}
Ejemplo n.º 23
0
BSM* bs_recv_message(int fd, int expect_data) {
    char *token, *data;
    size_t bytes, data_size, status_size, status_max = 512, expect_data_bytes = 0;
    ssize_t ret;
    BSM *message = (BSM*)calloc(1, sizeof(BSM));
    if (!message) return 0;

    message->status = (char*)calloc(1, status_max);
    if (!message->status) {
        bs_free_message(message);
        return 0;
    }

    // poll until ready to read
    if (bs_poll) bs_poll(1, fd);
    ret = recv(fd, message->status, status_max - 1, 0);
    if (ret < 0) {
        bs_free_message(message);
        return 0;
    } else {
      bytes = (size_t) ret;
    }

    token = strstr(message->status, "\r\n");
    if (!token) {
        bs_free_message(message);
        return 0;
    }

    *token        = 0;
    status_size   = (size_t) (token - message->status);

    if (expect_data) {
        token  = rindex(message->status, ' ');
        expect_data_bytes = token ? strtoul(token + 1, NULL, 10) : 0;
    }

    if (!expect_data || expect_data_bytes == 0)
        return message;

    message->size = bytes - status_size - 2;
    data_size     = message->size > BS_READ_CHUNK_SIZE ? message->size + BS_READ_CHUNK_SIZE : BS_READ_CHUNK_SIZE;

    message->data = (char*)malloc(data_size);
    if (!message->data) {
        bs_free_message(message);
        return 0;
    }

    memcpy(message->data, message->status + status_size + 2, message->size);
    data = message->data + message->size;

    // already read the body along with status, all good.
    if ((expect_data_bytes + 2) <= message->size) {
        message->size = expect_data_bytes;
        return message;
    }

    while (1) {
        // poll until ready to read.
        if (bs_poll) bs_poll(1, fd);
        ret = recv(fd, data, data_size - message->size, 0);
        if (ret < 0) {
            if (bs_poll && DATA_PENDING)
                continue;
            else {
                bs_free_message(message);
                return 0;
            }
        } else {
          bytes = (size_t) ret;
        }

        // doneski, we have read enough bytes + \r\n
        if (message->size + bytes >= expect_data_bytes + 2) {
            message->size = expect_data_bytes;
            break;
        }

        data_size      += BS_READ_CHUNK_SIZE;
        message->size  += bytes;
        message->data   = (char*)realloc(message->data, data_size);
        if (!message->data) {
            bs_free_message(message);
            return 0;
        }

        // move ahead pointer for reading more.
        data = message->data + message->size;
    }

    return message;
}
static void load_porting_library() {
#if ! defined(EGL_X11_FB_CONTAINER)

    jboolean (*lens_platform_init)(LensNativePort*) = 0;
    const char* liblens_porting = "liblens_porting.so";

#ifdef ANDROID_NDK    
    //Get the data path. All .so are installed in lib.
    const char *path = android_getDataDir();
    char *libpath = (char *) calloc(strlen(path) + strlen(liblens_porting) + 
                                    + strlen("/lib/") + 1, 1);
    strcpy(libpath, path);
    strcat(libpath, "/lib/");
    strcat(libpath, liblens_porting);
    
    void *dlhand = dlopen(libpath, RTLD_LAZY | RTLD_GLOBAL);
    if (!dlhand) {
        LOGE("GLASS", "dlopen failed. %s", dlerror());
        exit(-1);
    } else {
        lens_platform_init = dlsym(dlhand, "lens_platform_initialize");
        if (!lens_platform_init) {
            LOGE("GLASS", "lens_platform_initialize missing. %s", dlerror());
            exit(-1);
        }    
    }
    free(path);
    free(libpath);
#else    
    Dl_info dlinfo;
    if (dladdr(&lens_wm_initialize, &dlinfo)) {

        size_t rslash = (size_t)rindex(dlinfo.dli_fname,'/');
        if (rslash) {
            char *b = (char *) alloca(strlen(dlinfo.dli_fname)+20);
            rslash = rslash + 1 - (size_t)dlinfo.dli_fname;
            strncpy(b, dlinfo.dli_fname,rslash);
            strcpy(b + rslash, liblens_porting);

            void *dlhand = dlopen(b,RTLD_NOW); 
            if (dlhand) {
                lens_platform_init = dlsym(dlhand, "lens_platform_initialize");
                if (!lens_platform_init) {
                    fprintf(stderr,"lens_platform_initialize missing in liblens_porting.so\n");
                    exit(-1);
                }
            } else {
                fprintf(stderr,"LENS FAILED TO OPEN %s\n",b);
                fprintf(stderr,"dlopen reports %s\n",dlerror());
                exit(-1);
            }
        }
    } else {
        fprintf(stderr,"Did not get DLINFO\n");
        exit(-1);
    }
#endif
    lensPort.version = NATIVE_LENS_PORT_VERSION;
    (*lens_platform_init)(&lensPort);

    // set the current logging information
    lensPort.setLogger(&glass_logf, glass_log_level);
#endif
}
Ejemplo n.º 25
0
struct obj *readobjnam(char *bp)
{
    char *p;
    int i;
    int cnt;
    int spe;
    int spesgn;
    int typ;
    int heavy;
    char let;
    char *un;
    char *dn;
    char *an;
    /* int the = 0; */
    /* char *oname = 0; */

    heavy = 0;
    typ = heavy;
    spesgn = typ;
    spe = spesgn;
    cnt = spe;
    let = 0;
    un = 0;
    dn = un;
    an = dn;

    for(p = bp; *p != 0; ++p) {
        if(('A' <= *p) && (*p <= 'Z')) {
            *p += ('a' - 'A');
        }
    }

    if(strncmp(bp, "the ", 4) == 0) {
        /* the = 1; */
        bp += 4;
    }
    else if(strncmp(bp, "an ", 3) == 0) {
        cnt = 1;
        bp += 3;
    }
    else if(strncmp(bp, "a ", 2) == 0) {
        cnt = 1;
        bp += 2;
    }

    if((cnt == 0) && (digit(*bp) != 0)) {
        cnt = atoi(bp);

        while(digit(*bp) != 0) {
            ++bp;
        }

        while(*bp == ' ') {
            ++bp;
        }
    }

    if(cnt == 0) {
        /* %% What with "gems" etc.? */
        cnt = 1;
    }

    if((*bp == '+') || (*bp == '-')) {
        if(*bp == '+') {
            spesgn = 1;
        }
        else {
            spesgn = 01;
        }
        
        ++bp;

        spe = atoi(bp);

        while(digit(*bp) != 0) {
            ++bp;
        }

        while(*bp == ' ') {
            ++bp;
        }
    }
    else {
        p = rindex(bp, '(');

        if(p != 0) {
            if((p > bp) && (p[-1] == ' ')) {
                p[-1] = 0;
            }
            else {
                *p = 0;
            }

            ++p;

            spe = atoi(p);

            while(digit(*p) != 0) {
                ++p;
            }

            if(strcmp(p, ")") != 0) {
                spe = 0;
            }
            else {
                spesgn = 1;
            }
        }
    }

    /*
     * Now we have the actual name, as delivered by xname, say:
     * green positions called whisky
     * scrolls labeled "QWERTY"
     * egg
     * dead zruties
     * fortune cookies
     * very heavy iron ball named hoei
     * wand of wishing
     * elven cloak
     */
    for(p = bp; *p != 0; ++p) {
        if(strncmp(p, " named ", 7) == 0) {
            *p = 0;
            /* oname = p + 7; */
        }
    }

    for(p = bp; *p != 0; ++p) {
        if(strncmp(p, " called ", 8) == 0) {
            *p = 0;
            un = p + 8;
        }
    }

    for(p = bp; *p != 0; ++p) {
        if(strncmp(p, " labeled ", 9) == 0) {
            *p = 0;
            dn = p + 9;
        }
    }

    int flag = 0;
    /* First change to singular if necessary */
    if(cnt != 1) {
        /* Find "cloves of garlic", "worthless pieces of blue glass" */
        for(p = bp; *p != 0; ++p) {
            if(strncmp(p, "s of ", 5) == 0) {
                *p = p[1];
                while(*p != 0) {
                    ++p;
                    *p = p[1];
                }

                flag = 1;
                break;
            }
        }

        if(flag == 0) {
            /* Remove -s or -es (boxes) or -ies (rubies, zruties) */
            p = eos(bp);
            if(p[-1] == 's') {
                if(p[-2] == 'e') {
                    if(p[-3] == 'i') {
                        if(strcmp(p - 7, "cookies") == 0) {
                            p[-1] = 0;
                
                            flag = 1;
                        }
                        
                        if(flag == 0) {
                            strcpy(p - 3, "y");
                            flag = 1;
                        }
                    }
                    
                    if(flag == 0) {
                        /* Note: cloves / knives from clove / knife */
                        if(strcmp(p - 6, "knives") == 0) {
                            strcpy(p - 3, "fe");
                        
                            flag = 1;
                        
                        }
                    }
                    
                    if(flag == 0) {
                        /* Note: nurses, axes but boxes */
                        if(strcmp(p - 5, "boxes") == 0) {
                            p[-2] = 0;
                        
                            flag = 1;
                        }
                    }
                }

                if(flag == 0) {
                    p[-1] = 0;
                }
            }
            else {
                if(strcmp(p - 9, "homunculi") == 0) {
                    /* !! Makes string longer */
                    strcpy(p - 1, "us");
                 
                    flag = 1;
                }

                if(flag == 0) {
                    if(strcmp(p - 5, "teeth") == 0) {
                        strcpy(p - 5, "tooth");
                    
                        flag = 1;
                    }
                }

                /* Here we cannot find the plural suffix */
            }
        }
    }
 
    flag = 0;
    if(strcmp(bp, "amulet of yendor") == 0) {
        typ = AMULET_OF_YENDOR;

        flag = 2;
    }

    if(flag != 2) {
        p = eos(bp);
        
        /* Note: ring mail is not a ring! */
        if(strcmp(p - 5, " mail") == 0) {
            let = ARMOR_SYM;
            an = bp;

            flag = 1;
        }

        if(flag != 1) {
            for(i = 0; i < sizeof(wrpsym); ++i) {
                int j = strlen(wrp[i]);
                
                if(strncmp(bp, wrp[i], j) == 0) {
                    let = wrpsym[i];
                    bp += j;
                    
                    if(strncmp(bp, " of ", 4) == 0) {
                        an += 4;
                    }
                    
                    flag = 1;
                    break;
                }
                
                if(strcmp(p - j, wrp[i]) == 0) {
                    let = wrpsym[i];
                    p -= j;
                    *p = 0;
                    if(p[-1] == ' ') {
                        p[-1] = 0;
                    }
                    
                    dn = bp;
                    
                    flag = 1;
                    break;
                }
            }
        }

        if(flag != 1) {
            if(strcmp(p - 6, " stone") == 0) {
                p[-6] = 0;
                let = GEM_SYM;
                an = bp;
                
                flag = 1;
            }
        }

        if(flag != 1) {
            if(strcmp(bp, "very heavy iron ball") == 0) {
                heavy = 1;
                typ = HEAVY_IRON_BALL;
                
                flag = 2;
            }
        }
        
        if(flag != 2) {
            if(flag != 1) {
                an = bp;
            }

            if((an == 0) && (dn == 0) && (un == 0)) {
                if(let == 0) {
                    let = wrpsym[rn2(sizeof(wrpsym))];
                }
                
                typ = probtype(let);
                
                flag = 2;
            }
            
            if(flag != 2) {
                i = 1;
                
                if(let != 0) {
                    i = bases[letindex(let)];
                }
                
                while((i <= NROFOBJECTS) && ((let == 0) || (objects[i].oc_olet == let))) {
                    if((an != 0) && (strcmp(an, objects[i].oc_name) != 0)) {
                        ++i;
                        continue;
                    }
                    
                    if((dn != 0) && (strcmp(an, objects[i].oc_descr) != 0)) {
                        ++i;
                        continue;
                    }
                    
                    if((un != 0) && (strcmp(un, objects[i].oc_uname) != 0)) {
                        ++i;
                        continue;
                    }
                    
                    typ = i;
                    
                    flag = 2;
                    break;
                }
                
                if(flag != 2) {
                    if(let == 0) {
                        let = wrpsym[rn2(sizeof(wrpsym))];
                    }
                    
                    typ = probtype(let);
                }
            }
        }
    }

    struct obj *otmp;
    
    let = objects[typ].oc_olet;
    
    if((let == FOOD_SYM) && (typ >= CORPSE)) {
        if(typ > ((CORPSE + 'Z') - '@')) {
            let = ((typ - CORPSE) + '@') + (('a' - 'Z') - 1);
        }
        else {
            let = ((typ - CORPSE) + '@') + (0);
        }
    }
    
    otmp = mksobj(let, typ);
    
    if(heavy != 0) {
        otmp->owt = 15;
    }
    
    if((cnt > 0)
       && (index("%?!*)", let) != 0)
       && ((cnt < 4) 
           || ((let == WEAPON_SYM) && (typ <= ROCK) && (cnt < 20)))) {
        otmp->quan = cnt;
    }
    
    if(spesgn == -1) {
        otmp->cursed = 1;
    }
    
    if((spe > 3) && (spe > otmp->spe)) {
        spe = 0;
    }
    else if(let == WAND_SYM) {
        spe = otmp->spe;
    }
    
    if((spe == 3) && (u.uluck < 0)) {
        spesgn = -1;
    }
    
    if((let != WAND_SYM) && (spesgn == -1)) {
        spe = -spe;
    }
    
    if(let == BALL_SYM) {
        spe = 0;
    }
    else if(let == AMULET_SYM) {
        spe = -1;
    }
    else if((typ == WAN_WISHING) && (rn2(10) != 0)) {
        spe = 0;
    }
    else if(let == ARMOR_SYM) {
        spe += (10 - objects[typ].a_ac);
        
        if((spe > 5) && (rn2(spe - 5) != 0)) {
            otmp->cursed = 1;
        }
    }
    
    otmp->spe = spe;
    
    return otmp;
}
Ejemplo n.º 26
0
/** \brief turn StatsTable into a json object
 *  \param flags JSON_STATS_* flags for controlling output
 */
json_t *StatsToJSON(const StatsTable *st, uint8_t flags)
{
    const char delta_suffix[] = "_delta";
    struct timeval tval;
    gettimeofday(&tval, NULL);

    json_t *js_stats = json_object();
    if (unlikely(js_stats == NULL)) {
        return NULL;
    }

    /* Uptime, in seconds. */
    json_object_set_new(js_stats, "uptime",
        json_integer((int)difftime(tval.tv_sec, st->start_time)));

    uint32_t u = 0;
    if (flags & JSON_STATS_TOTALS) {
        for (u = 0; u < st->nstats; u++) {
            if (st->stats[u].name == NULL)
                continue;
            const char *name = st->stats[u].name;
            const char *shortname = name;
            if (rindex(name, '.') != NULL) {
                shortname = &name[rindex(name, '.') - name + 1];
            }
            json_t *js_type = OutputStats2Json(js_stats, name);
            if (js_type != NULL) {
                json_object_set_new(js_type, shortname,
                    json_integer(st->stats[u].value));

                if (flags & JSON_STATS_DELTAS) {
                    char deltaname[strlen(shortname) + strlen(delta_suffix) + 1];
                    snprintf(deltaname, sizeof(deltaname), "%s%s", shortname,
                        delta_suffix);
                    json_object_set_new(js_type, deltaname,
                        json_integer(st->stats[u].value - st->stats[u].pvalue));
                }
            }
        }
    }

    /* per thread stats - stored in a "threads" object. */
    if (st->tstats != NULL && (flags & JSON_STATS_THREADS)) {
        /* for each thread (store) */
        json_t *threads = json_object();
        if (unlikely(threads == NULL)) {
            json_decref(js_stats);
            return NULL;
        }
        uint32_t x;
        for (x = 0; x < st->ntstats; x++) {
            uint32_t offset = x * st->nstats;

            /* for each counter */
            for (u = offset; u < (offset + st->nstats); u++) {
                if (st->tstats[u].name == NULL)
                    continue;

                char str[256];
                snprintf(str, sizeof(str), "%s.%s", st->tstats[u].tm_name, st->tstats[u].name);
                char *shortname = &str[rindex(str, '.') - str + 1];
                json_t *js_type = OutputStats2Json(threads, str);

                if (js_type != NULL) {
                    json_object_set_new(js_type, shortname, json_integer(st->tstats[u].value));

                    if (flags & JSON_STATS_DELTAS) {
                        char deltaname[strlen(shortname) + strlen(delta_suffix) + 1];
                        snprintf(deltaname, sizeof(deltaname), "%s%s",
                            shortname, delta_suffix);
                        json_object_set_new(js_type, deltaname,
                            json_integer(st->tstats[u].value - st->tstats[u].pvalue));
                    }
                }
            }
        }
        json_object_set_new(js_stats, "threads", threads);
    }
    return js_stats;
}
Ejemplo n.º 27
0
static GtkWidget *script_info_add(const char *path, const char *fname)
{
    char *fullname;
    ScriptInfo *si;
    FILE *script;
    int i;
    char line[1024];
    const char *str;
    char *dot;
    char *underscore;
    GtkWidget *menuitem = NULL;

    fullname = g_malloc(strlen(path)+strlen(fname)+2);
    sprintf(fullname,"%s/%s",path,fname);

    script = fopen(fullname,"r");
    if (script)
    {
        si = (ScriptInfo *)g_malloc0(sizeof(ScriptInfo));
        si->script_file = strdup(fname);

        //rtrim(line); uninitialized yet

        for (i=0; i<30; i++)
        {
            if (fgets(line,1024,script)==NULL) break;

            rtrim(line);

            if ((str=locate_after_prefix("@name",line))!=NULL)
            {
                si->script_name = g_strdup(str);
            }
            else if ((str=locate_after_prefix("@description",line))!=NULL)
            {
                si->script_description = g_strdup(str);
            }
            else if ((str=locate_after_prefix("@targets",line))!=NULL)
            {
                si->script_targeted_version = g_strdup(str);
            }
        }

        fclose(script);

        if (si->script_name==NULL)
        {
            si->script_name = g_strdup(fname);

            dot = rindex(si->script_name,'.');
            if (dot) *dot=0;

            for (underscore=si->script_name; *underscore!=0; underscore++)
            {
                if (*underscore=='_') *underscore=' ';
            }
        }

        si->prev = SCRIPTS;
        SCRIPTS = si;

        menuitem = gtk_menu_item_new_with_label(si->script_name);
        if (si->script_description) gtk_widget_set_tooltip_text(menuitem,si->script_description);
        g_signal_connect(GTK_WIDGET(menuitem),"activate",G_CALLBACK(menu_run_script_cb),si);
        gtk_widget_show(menuitem);
    }
    else
    {
        log_printf(LOG_ERROR,"Failed to open %s for reading",fullname);
    }
    g_free(fullname);
    return menuitem;
}
Ejemplo n.º 28
0
void main(int argc, char **argv)
{
	char *stop;
	int	opts;
	char *debugstr;
	int	debuglvl;
	int	i;
	int	modemstate;
	int	modeminits;

	breaklist_init();

	progbasename = argv[0];

	if ((stop = rindex(argv[0], '/'))) progbasename = ++stop;

		/* Die Argumente des Programms einlesen und den Debuglevel	*/
		/* setzen.																	*/

	debugstr		= NULL;
	isdnttyname	= NULL;

	while ((opts = getopt_long(argc, argv, "vhx:d:", arguments, (int *)0)) != EOF)
	{
		switch (opts)
		{
			case 'x':
				debugstr = optarg;
				break;

			case 'd':
				isdnttyname = optarg;
				break;

			case 'v':
				show_usage(200, 0);
				break;

			case 'h':
			default:
				show_usage(200, 1);
				break;
		}
	}

	if (debugstr)
	{
		if (strcasecmp(debugstr, "FULL") != 0)
		{
			debuglvl = LOG_E;

			for (i = 0; i < strlen(debugstr); i++)
			{
				switch (debugstr[i])
				{
					case 'W':
					case 'w':
						debuglvl |= LOG_W;
						break;
					
					case 'I':
						debuglvl |= LOG_I;
						break;
					
					case 'A':
						debuglvl |= LOG_A;
						break;
					
					case 'D':
						debuglvl |= LOG_D;
						break;
				}
			}
		}
		else debuglvl = LOG_X;

		log_set_debuglevel(debuglvl);
	}

	umask(xstrtoo(VBOX_ROOT_UMASK, 0));

		/* Pfadangaben vom Devicenamen abschneiden und überprüfen ob	*/
		/* das Device vom Benutzer gelesen und beschrieben werden		*/
		/* kann (eigentlich nicht nötig, da nur unter Rootrechten ge-	*/
		/* startet werden kann.														*/

	if (isdnttyname)
	{
		if ((stop = rindex(isdnttyname, '/'))) isdnttyname = ++stop;

		printstring(savettydname, "%s"     , isdnttyname);
		printstring(temppathname, "/dev/%s", isdnttyname);
		
		if (access(temppathname, F_OK|R_OK|W_OK) != 0)
		{
			fprintf(stderr, "\n%s: error: \"%s\" doesn't exist or is not accessible!\n\n", progbasename, temppathname);

			quit_program(100);
		}
	}
	else
	{
		fprintf(stderr, "\n%s: error: isdn tty name is required!\n", progbasename);

		show_usage(100, 1);
	}

		/* Prüfen ob das Programm unter Rootrechten gestartet wurde. Die	*/
		/* Rechte werden später auf die des jeweiligen Benutzers geän-		*/
		/* dert, zum Start sind aber Rootrechte nötig.							*/

	if (getuid() != 0)
	{
		fprintf(stderr, "\n%s: error: need root privilegs to start!\n\n", progbasename);

		quit_program(100);
	}

		/* Jetzt wird der Log geöffnet. Der Name des aktuellen Devices	*/
		/* wird an das Ende angehängt.											*/

	printstring(temppathname, "%s/vboxgetty-%s.log", LOGDIR, isdnttyname);

	log_open(temppathname);

		/* Tcl-Interpreter starten. Für die momentanen Funktionen wird	*/
		/* Version 8 oder höher benötigt.										*/

	if (scr_create_interpreter() == -1)
	{
		log_line(LOG_E, "Can't create/initialize the tcl interpreter!\n");
		
		quit_program(100);
	}

	log_line(LOG_I, "Running vbox version %s (with tcl version %s).\n", VERSION, scr_tcl_version());

		/* Konfiguration des getty's abarbeiten. Zuerst wird die globale,	*/
		/* dann die des jeweiligen tty's eingelesen.								*/

	if (vboxgettyrc_parse(isdnttyname) == -1)
	{
		log_line(LOG_E, "Unable to read/parse configuration!\n");
	
		quit_program(100);
	}

		/* Modem Device öffnen und die interne Initialisierung	*/
		/* ausführen (nicht der normale Modeminit).					*/

	printstring(temppathname, "/dev/%s", isdnttyname);

	log_line(LOG_D, "Opening modem device \"%s\" (38400, CTS/RTS)...\n", temppathname);

	if (vboxmodem_open(&vboxmodem, temppathname) == -1)
	{
		log_line(LOG_E, "Can't open/setup modem device (%s).\n", vboxmodem_error());

		quit_program(100);
	}

		/* Lock- und PID-Datei für den getty und das entsprechende	*/
		/* Device erzeugen.														*/

	printstring(temppathname, "%s/LCK..%s", LOCKDIR, isdnttyname);
	
	if (lock_create(temppathname) == -1) quit_program(100);

	printstring(temppathname, "%s/vboxgetty-%s.pid", PIDDIR, isdnttyname);

	pid_create(temppathname);

		/* Signalhändler installieren. Alle möglichen Signale werden	*/
		/* auf quit_program() umgelenkt.											*/

	signal(SIGINT , quit_program);
	signal(SIGTERM, quit_program);
	signal(SIGHUP , quit_program);

		/* Hauptloop: Der Loop wird nur verlassen, wenn während der	*/
		/* Abarbeitung ein Fehler aufgetreten ist. Das Programm be-	*/
		/* endet sich danach!													*/
	
	modemstate = VBOXMODEM_STAT_INIT;
	modeminits = 0;
	
	while (modemstate != VBOXMODEM_STAT_EXIT)
	{
		switch (modemstate)
		{
			case VBOXMODEM_STAT_INIT:

				if (run_modem_init() == -1)
				{
					if ((i = (int)xstrtol(rc_get_entry(rc_getty_c, "badinitsexit"), 10)) > 0)
					{
						modeminits++;
						
						if (modeminits >= i)
						{
							modemstate = VBOXMODEM_STAT_EXIT;
							modeminits = 0;
							
							log_line(LOG_E, "Exit program while bad init limit are reached.\n");
						}
						else log_line(LOG_W, "Bad initialization - Program will exist on %d trys!\n", (i - modeminits));
					}
				}
				else
				{
					modemstate = VBOXMODEM_STAT_WAIT;
					modeminits = 0;
				}
				break;

			case VBOXMODEM_STAT_WAIT:
				
				modem_flush(&vboxmodem, 0);

				if (modem_wait(&vboxmodem) == 0)
				{
					modemstate = VBOXMODEM_STAT_RING;
					modeminits = 0;
				}
				else modemstate = VBOXMODEM_STAT_TEST;
				
				break;

			case VBOXMODEM_STAT_TEST:
			
				log_line(LOG_D, "Checking if modem is still alive...\n");
				
				if (modem_command(&vboxmodem, "AT", "OK") > 0)
				{
					modemstate = VBOXMODEM_STAT_WAIT;
					modeminits = 0;
				}
				else modemstate = VBOXMODEM_STAT_INIT;
				
				break;
				
			case VBOXMODEM_STAT_RING:
			
				modem_set_nocarrier(&vboxmodem, 0);
				process_incoming_call();
				modem_hangup(&vboxmodem);

				if (set_process_permissions(0, 0, xstrtoo(VBOX_ROOT_UMASK, 0)) != 0)
					modemstate = VBOXMODEM_STAT_EXIT;
				else
 					modemstate = VBOXMODEM_STAT_INIT;
				
				break;

			default:

				log_line(LOG_E, "Unknown modem status %d!\n", modemstate);
				
				modemstate = VBOXMODEM_STAT_INIT;
				
				break;
		}
	}

	quit_program(0);
}
Ejemplo n.º 29
0
void StringRindex(struct ParseState *Parser, struct Value *ReturnValue, struct Value **Param, int NumArgs)
{
    ReturnValue->Val->Pointer = rindex(Param[0]->Val->Pointer, Param[1]->Val->Integer);
}
Ejemplo n.º 30
0
/* ------------- */
void load_cfg(void)
{
FILE *cfg_h;
register int i, j;
register char *xx, *xf;
char string[80];

cfg_h = fopen("M_TEXT.CFG", "r");
if (cfg_h)
	{
	for (i = 0; i < M_POINTS; i++)	
		{
		do
			{
			fgets(string, 79, cfg_h);
			}while( !strchr(string, '='));

			if (strchr(string, '\n'))
				*strchr(string, '\n') = 0;

			if ( strchr(string, '=') )
				{
				xx = strchr(string, '=') + 2;
				if (!strncmp(xx, "..", 2))
					xx = "  ";

				if (*xx == '~')
					*xx = 0x7;

				strncpy(rindex(menu_adr[menu_id[i]].ob_spec.free_string, 'x') - 1, xx, 2);

				if (*xx == 0x7)
					{
					xx++;

					for (j = 0; j < ALT_NUM; j++)
						if (alt_tab[j] == *((unsigned char *)xx) )
							alt_tab[j] = menu_id[i] | 0x8000;
					}
				else
					if (*xx == '^')
						{
						xx++;

						for (j = 0; j < CNTRL_NUM; j++)
							if (cntrl_tab[j] == *((unsigned char *)xx) )
								cntrl_tab[j] = menu_id[i] | 0x8000;
						}
					else
						if (*xx == 'F')
							{
							alt_tab[0x3B + *(xx + 1) - '1'] = menu_id[i] | 0x8000;
	
							if (*(xx + 1) == '0')
								{
								j = strlen(menu_adr[menu_id[i]].ob_spec.free_string);
								menu_adr[menu_id[i]].ob_spec.free_string[j - 2] = '1';
								menu_adr[menu_id[i]].ob_spec.free_string[j - 1] = '0';
								}

							xf = strchr(xx, ':');
							if (xf)
								{
								do
									{
									xf++;
									}while(*xf == ' ' || *xf == '\t');

								strcpy(f_text[*(xx + 1) - '0'], xf);
								}
							}
				}
		}

	fclose(cfg_h);
	}
}