Ejemplo n.º 1
0
/*!
    Returns TRUE if the property shall be stored for object \a o;
    otherwise returns FALSE.

    If no object \a o is given, the function returns a static
    approximation.
 */
bool QMetaProperty::stored( QObject* o ) const
{
    if ( !isValid() || !writable() )
	return FALSE;
    if ( o ) {
	int idx = _id >= 0 ? _id : (*meta)->indexOfProperty( this, TRUE );
	return idx >= 0 && o->qt_property( idx, 5, 0 );
    }
    if ( testFlags( StoredOverride ) ) {
	const QMetaObject* mo = (*meta);
	const QMetaProperty* parent = mo->resolveProperty( this );
	return parent ? parent->stored() : FALSE;
    }
    return !testFlags( NotStored );
}
Ejemplo n.º 2
0
std::vector<flock> getSharedFiles(const std::wstring& path){
    FILE_INFO_3* pFiles = NULL;
    DWORD nRead = 0, nTotal = 0;

    std::vector<flock> ret;
    std::vector<long> ids;

    int res = ERROR_MORE_DATA;

    std::vector<wchar_t> writable(path.begin(), path.end());
    writable.push_back('\0');

    int totalDone = 0;

    while(res==ERROR_MORE_DATA){

        try{
        res = NetFileEnum(
          NULL, // servername, NULL means localhost
          &writable[0], // basepath, directory where VB6 program is
          NULL, // username, searches for all users
          3, // level, we just need resource ID
          (BYTE**)&pFiles, // bufptr,
          MAX_PREFERRED_LENGTH, // prefmaxlen, collect as much as possible
          &nRead, // entriesread, number of entries stored in pFiles
          &nTotal, // totalentries, ignore this
          NULL //resume_handle, ignore this
        );

        }
        catch(int exx){
            printf("%i",exx);
            break;
        }

        for (unsigned int i=0; i < nRead; ++i){
            //int nret = NetFileClose(NULL, pFiles[i].fi2_id);
            flock tmp(pFiles[i]);
            ret.push_back(tmp);

        }

        NetApiBufferFree(pFiles);
    }

    return ret;
}
Ejemplo n.º 3
0
int VpiSignalObjHdl::set_signal_value(std::string &value)
{
    FENTER
    s_vpi_value value_s;

    std::vector<char> writable(value.begin(), value.end());
    writable.push_back('\0');

    value_s.value.str = &writable[0];
    value_s.format = vpiBinStrVal;

    vpi_put_value(GpiObjHdl::get_handle<vpiHandle>(), &value_s, NULL, vpiNoDelay);
    check_vpi_error();

    FEXIT
    return 0;
}
Ejemplo n.º 4
0
void load_tga_image(std::string nome, GLuint texture, bool transparency)
{
	std::string impathfile = "textures/" + nome + ".tga";

	std::vector<char> writable(impathfile.begin(), impathfile.end());
	writable.push_back('\0');

	// Carrega a imagem de textura
	im = tgaLoad(&writable[0]);
	//printf("IMAGE INFO: %s\nstatus: %d\ntype: %d\npixelDepth: %d\nsize%d x %d\n", impathfile, im->status, im->type, im->pixelDepth, im->width, im->height);

	// Seleciona a textura atual
	glBindTexture(GL_TEXTURE_2D, texture);

	// set up quadric object and turn on FILL draw style for it
	mysolid = gluNewQuadric();
	gluQuadricDrawStyle(mysolid, GLU_FILL);

	// turn on texture coordinate generator for the quadric
	gluQuadricTexture(mysolid, GL_TRUE);

	// select modulate to mix texture with color for shading
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); // MIPMAP
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	// build our texture mipmaps
	if (!transparency){
		gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, im->width, im->height, GL_RGB, GL_UNSIGNED_BYTE, im->imageData); // MIPMAP
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, im->width, im->height, 0, GL_RGB, GL_UNSIGNED_BYTE, im->imageData);
	}
	else{
		//Textura com transparência (anéis de saturno)
		gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, im->width, im->height, GL_RGB, GL_UNSIGNED_BYTE, im->imageData); // MIPMAP
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, im->width, im->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, im->imageData);
	}


	// Destroi a imagem
	tgaDestroy(im);
}
Ejemplo n.º 5
0
bool Repo::initSchema(int repoId, bool& isWritable) {
  if (!schemaExists(repoId)) {
    if (createSchema(repoId)) {
      // Check whether this failure is due to losing the schema
      // initialization race with another process.
      if (!schemaExists(repoId)) {
        return true;
      }
    } else {
      // createSchema() successfully wrote to the database, so no further
      // verification is necessary.
      return false;
    }
  }
  if (isWritable) {
    isWritable = writable(repoId);
  }
  return false;
}
Ejemplo n.º 6
0
static void write_string(struct oport *p, prt_level level, struct string *print)
{
  uvalue l = string_len(print);

  if (level == prt_display)
    pswrite(p, print, 0, l);
  else
    {
      unsigned char *str = (unsigned char *)alloca(l + 1);
      unsigned char *endstr;

      memcpy((char *)str, print->str, l + 1);
      GCPRO1(p);
      /* The NULL byte at the end doesn't count */
      endstr = str + l;

      pputc('"', p);
      while (str < endstr)
	{
	  unsigned char *pos = str;

	  while (pos < endstr && writable(*pos)) pos++;
	  opwrite(p, (char *)str, pos - str);
	  if (pos < endstr)	/* We stopped for a \ */
	    {
	      pputc('\\', p);
	      switch (*pos)
		{
		case '\\': case '"': pputc(*pos, p); break;
		case '\n': pputc('n', p); break;
		case '\r': pputc('r', p); break;
		case '\t': pputc('t', p); break;
		case '\f': pputc('f', p); break;
		default: pprintf(p, "%o", *pos); break;
		}
	      str = pos + 1;
	    }
	  else str = pos;
	}
      pputc('"', p);
      GCPOP(1);
    }
}
Ejemplo n.º 7
0
GpiObjHdl* VpiImpl::native_check_create(std::string &name, GpiObjHdl *parent)
{
    int32_t type;
    vpiHandle new_hdl;
    GpiObjHdl *new_obj = NULL; 
    std::vector<char> writable(name.begin(), name.end());
    writable.push_back('\0');

    new_hdl = vpi_handle_by_name(&writable[0], NULL);

    if (!new_hdl)
        return NULL;

    if (vpiUnknown == (type = vpi_get(vpiType, new_hdl))) {
        vpi_free_object(new_hdl);
        return new_obj;
    }

    /* What sort of isntance is this ?*/
    switch (type) {
        case vpiNet:
        case vpiReg:
        case vpiParameter:
            new_obj = new VpiSignalObjHdl(this, new_hdl);
            break;
        case vpiStructVar:
        case vpiModule:
        case vpiInterface:
        case vpiModport:
            new_obj = new GpiObjHdl(this, new_hdl);
            break;
        default:
            LOG_INFO("Not sure what to do with type %d for entity (%s)", type, name.c_str());
            return NULL;
    }

    new_obj->initialise(name);

    return new_obj;
}
Ejemplo n.º 8
0
static int write_to_file(char* logfile, char* buf, int size){
    int ret = 0;
    struct file * f = NULL;
    BEGIN_KMEM;
    f = filp_open(logfile, O_CREAT|O_APPEND, 00600);
    if(IS_ERR(f)){
        printk(KERN_INFO "Error %ld opening %s\n", -PTR_ERR(f), logfile);
        ret = -1;
    } else{
        if(writable(f))
            write(f, buf, size);
        else{
            printk(KERN_INFO "%s does not have a write method\n", logfile);
            ret = -1;
        }
        if((ret = filp_close(f,NULL)))
            printk("Error %d closing %s\n", -ret, logfile);
    }
    END_KMEM;

    return ret;
}
Ejemplo n.º 9
0
int
main(int argc, char *argv [])
{
    // make a copy as we don't want to modify argv[0], copy it to a vector to
    // guarantee that memory is correctly managed/exception safe
    std::string programName {argv[0]};
    std::vector<char> writable(programName.size() + 1);
    std::copy(programName.begin(), programName.end(), writable.begin());

    ring::fileutils::set_program_dir(writable.data());

#ifdef TOP_BUILDDIR
    if (!getenv("CODECS_PATH"))
        setenv("CODECS_PATH", TOP_BUILDDIR "/src/media/audio/codecs", 1);
#endif

    print_title();

    bool persistent = false;
    if (parse_args(argc, argv, persistent))
        return 0;

    // initialize client/library
    try {
        dbusClient.reset(new DBusClient {ringFlags, persistent});
    } catch (const std::exception& ex) {
        std::cerr << "One does not simply initialize the DBus client: " << ex.what() << std::endl;
        return 1;
    }

    // TODO: Block signals for all threads but the main thread, decide how/if we should
    // handle other signals
    signal(SIGINT, signal_handler);
    signal(SIGHUP, signal_handler);
    signal(SIGTERM, signal_handler);

    return run();
}
Ejemplo n.º 10
0
static void delnet(struct line line) {
	struct {
		int netid;
	} __attribute__((__packed__)) args;
	sscan(line, "-i", &args);

	struct sockifo* ifo = find(args.netid);

	if (!ifo)
		die("Cannot find network %d in delnet", args.netid);
	ifo->state.mplex_dropped = 1;
	if (ifo->fd >= 0)
		qprintf(&sockets->net[0].sendq, "D %d Drop Requested\n", ifo->netid);

#if SSL_ENABLED
	if (ifo->state.ssl)
		ssl_drop(ifo);
	else
#endif
	{
		ifo->state.poll = POLL_FORCE_WOK;
		writable(ifo);
	}
}
Ejemplo n.º 11
0
/*
 * Let's do it.  We end up doing a lot of file opening and closing,
 * but what do we care?  This application isn't run constantly.
 */
int main(int argc, char *argv[])
{
    FILE *ftemp = NULL;
    FILE *fpw = NULL;
    char user[MAX_STRING_LEN];
    char password[MAX_STRING_LEN];
    char record[MAX_STRING_LEN];
    char line[MAX_STRING_LEN];
    char pwfilename[MAX_STRING_LEN];
    char *arg;
    int found = 0;
    int alg = ALG_CRYPT;
    int newfile = 0;
    int nofile = 0;
    int noninteractive = 0;
    int i;
    int args_left = 2;

    tempfilename = NULL;
    signal(SIGINT, (void (*)(int)) interrupted);

    /*
     * Preliminary check to make sure they provided at least
     * three arguments, we'll do better argument checking as 
     * we parse the command line.
     */
    if (argc < 3) {
	return usage();
    }

    /*
     * Go through the argument list and pick out any options.  They
     * have to precede any other arguments.
     */
    for (i = 1; i < argc; i++) {
	arg = argv[i];
	if (*arg != '-') {
	    break;
	}
	while (*++arg != '\0') {
	    if (*arg == 'c') {
		newfile++;
	    }
	    else if (*arg == 'n') {
		nofile++;
		args_left--;
	    }
	    else if (*arg == 'm') {
		alg = ALG_APMD5;
	    }
	    else if (*arg == 's') {
		alg = ALG_APSHA;
	    }
	    else if (*arg == 'p') {
		alg = ALG_PLAIN;
	    }
	    else if (*arg == 'd') {
		alg = ALG_CRYPT;
	    }
	    else if (*arg == 'b') {
		noninteractive++;
		args_left++;
	    }
	    else {
		return usage();
	    }
	}
    }

    /*
     * Make sure we still have exactly the right number of arguments left
     * (the filename, the username, and possibly the password if -b was
     * specified).
     */
    if ((argc - i) != args_left) {
	return usage();
    }
    if (newfile && nofile) {
	fprintf(stderr, "%s: -c and -n options conflict\n", argv[0]);
	return ERR_SYNTAX;
    }
    if (nofile) {
	i--;
    }
    else {
	if (strlen(argv[i]) > (sizeof(pwfilename) - 1)) {
	    fprintf(stderr, "%s: filename too long\n", argv[0]);
	    return ERR_OVERFLOW;
	}
	strcpy(pwfilename, argv[i]);
	if (strlen(argv[i + 1]) > (sizeof(user) - 1)) {
	    fprintf(stderr, "%s: username too long (>%lu)\n", argv[0],
		    (unsigned long)(sizeof(user) - 1));
	    return ERR_OVERFLOW;
	}
    }
    strcpy(user, argv[i + 1]);
    if ((arg = strchr(user, ':')) != NULL) {
	fprintf(stderr, "%s: username contains illegal character '%c'\n",
		argv[0], *arg);
	return ERR_BADUSER;
    }
    if (noninteractive) {
	if (strlen(argv[i + 2]) > (sizeof(password) - 1)) {
	    fprintf(stderr, "%s: password too long (>%lu)\n", argv[0],
		    (unsigned long)(sizeof(password) - 1));
	    return ERR_OVERFLOW;
	}
	strcpy(password, argv[i + 2]);
    }

#if (!(defined(WIN32) || defined(TPF) || defined(NETWARE)))
    if (alg == ALG_PLAIN) {
	fprintf(stderr,"Warning: storing passwords as plain text might "
		"just not work on this platform.\n");
    }
#endif
    if (! nofile) {
	/*
	 * Only do the file checks if we're supposed to frob it.
	 *
	 * Verify that the file exists if -c was omitted.  We give a special
	 * message if it doesn't.
	 */
	if ((! newfile) && (! exists(pwfilename))) {
	    fprintf(stderr,
		    "%s: cannot modify file %s; use '-c' to create it\n",
		    argv[0], pwfilename);
	    perror("fopen");
	    exit(ERR_FILEPERM);
	}
	/*
	 * Verify that we can read the existing file in the case of an update
	 * to it (rather than creation of a new one).
	 */
	if ((! newfile) && (! readable(pwfilename))) {
	    fprintf(stderr, "%s: cannot open file %s for read access\n",
		    argv[0], pwfilename);
	    perror("fopen");
	    exit(ERR_FILEPERM);
	}
	/*
	 * Now check to see if we can preserve an existing file in case
	 * of password verification errors on a -c operation.
	 */
	if (newfile && exists(pwfilename) && (! readable(pwfilename))) {
	    fprintf(stderr, "%s: cannot open file %s for read access\n"
		    "%s: existing auth data would be lost on "
		    "password mismatch",
		    argv[0], pwfilename, argv[0]);
	    perror("fopen");
	    exit(ERR_FILEPERM);
	}
	/*
	 * Now verify that the file is writable!
	 */
	if (! writable(pwfilename)) {
	    fprintf(stderr, "%s: cannot open file %s for write access\n",
		    argv[0], pwfilename);
	    perror("fopen");
	    exit(ERR_FILEPERM);
	}
    }

    /*
     * All the file access checks (if any) have been made.  Time to go to work;
     * try to create the record for the username in question.  If that
     * fails, there's no need to waste any time on file manipulations.
     * Any error message text is returned in the record buffer, since
     * the mkrecord() routine doesn't have access to argv[].
     */
    i = mkrecord(user, record, sizeof(record) - 1,
		 noninteractive ? password : NULL,
		 alg);
    if (i != 0) {
	fprintf(stderr, "%s: %s\n", argv[0], record);
	exit(i);
    }
    if (nofile) {
	printf("%s\n", record);
	exit(0);
    }

    /*
     * We can access the files the right way, and we have a record
     * to add or update.  Let's do it..
     */
    errno = 0;
    tempfilename = tmpnam(tname_buf);
    if ((tempfilename == NULL) || (*tempfilename == '\0')) {
	fprintf(stderr, "%s: unable to generate temporary filename\n",
		argv[0]);
	if (errno == 0) {
	    errno = ENOENT;
	}
	perror("tmpnam");
	exit(ERR_FILEPERM);
    }
    ftemp = fopen(tempfilename, "w+");
    if (ftemp == NULL) {
	fprintf(stderr, "%s: unable to create temporary file '%s'\n", argv[0],
		tempfilename);
	perror("fopen");
	exit(ERR_FILEPERM);
    }
    /*
     * If we're not creating a new file, copy records from the existing
     * one to the temporary file until we find the specified user.
     */
    if (! newfile) {
	char scratch[MAX_STRING_LEN];

	fpw = fopen(pwfilename, "r");
	while (! (mygetline(line, sizeof(line), fpw))) {
	    char *colon;

	    if ((line[0] == '#') || (line[0] == '\0')) {
		putline(ftemp, line);
		continue;
	    }
	    strcpy(scratch, line);
	    /*
	     * See if this is our user.
	     */
	    colon = strchr(scratch, ':');
	    if (colon != NULL) {
		*colon = '\0';
	    }
	    if (strcmp(user, scratch) != 0) {
		putline(ftemp, line);
		continue;
	    }
	    found++;
	    break;
	}
    }
    if (found) {
	fprintf(stderr, "Updating ");
    }
    else {
	fprintf(stderr, "Adding ");
    }
    fprintf(stderr, "password for user %s\n", user);
    /*
     * Now add the user record we created.
     */
    putline(ftemp, record);
    /*
     * If we're updating an existing file, there may be additional
     * records beyond the one we're updating, so copy them.
     */
    if (! newfile) {
	copy_file(ftemp, fpw);
	fclose(fpw);
    }
    /*
     * The temporary file now contains the information that should be
     * in the actual password file.  Close the open files, re-open them
     * in the appropriate mode, and copy them file to the real one.
     */
    fclose(ftemp);
    fpw = fopen(pwfilename, "w+");
    ftemp = fopen(tempfilename, "r");
    copy_file(fpw, ftemp);
    fclose(fpw);
    fclose(ftemp);
    unlink(tempfilename);
    return 0;
}
Ejemplo n.º 12
0
bool PlatformRegion::accessible() const {
	return readable() || writable() || executable();
}
Ejemplo n.º 13
0
void TypedData< TimePeriod >::load( LoadContextPtr context )
{
	Data::load( context );

	unsigned int v = 0;

	ConstIndexedIOPtr container = context->container( staticTypeName(), v );

	std::string beginStr;
	container->read( g_beginEntry, beginStr );
	boost::posix_time::ptime begin;
	try
	{
		begin = boost::posix_time::from_iso_string( beginStr );
	}
	catch ( boost::bad_lexical_cast )
	{
		/// Do these checks here instead of first as they're likely to be the least-used cases.
		if ( beginStr == "not-a-date-time" )
		{
			begin = boost::posix_time::not_a_date_time;
		}
		else if ( beginStr == "+infinity" )
		{
			begin = boost::posix_time::pos_infin;
		}
		else if ( beginStr == "-infinity" )
		{
			begin = boost::posix_time::neg_infin;
		}
		else
		{
			throw;
		}
	}

	std::string endStr;
	container->read( g_endEntry, endStr );
	boost::posix_time::ptime end;
	try
	{
		end = boost::posix_time::from_iso_string( endStr );
	}
	catch ( boost::bad_lexical_cast )
	{
		/// Do these checks here instead of first as they're likely to be the least-used cases.
		if ( endStr == "not-a-date-time" )
		{
			end = boost::posix_time::not_a_date_time;
		}
		else if ( endStr == "+infinity" )
		{
			end = boost::posix_time::pos_infin;
		}
		else if ( endStr == "-infinity" )
		{
			end = boost::posix_time::neg_infin;
		}
		else
		{
			throw;
		}
	}

	writable() = boost::posix_time::time_period( begin, end );
}
Ejemplo n.º 14
0
u32int FSNode::removeSC() {
	if (!writable()) return 0;
	return (VFS::remove(this) ? 1 : 0);
}
Ejemplo n.º 15
0
void PlyReader::parseFile()
{
	SURGSIM_ASSERT(isValid()) << "'" << m_filename << "' is an invalid .ply file";

	if (m_startParseFileCallback != nullptr)
	{
		m_startParseFileCallback();
	}

	char* currentElementName;
	for (int elementIndex = 0; elementIndex < m_data->elementCount; ++elementIndex)
	{
		currentElementName = m_data->elementNames[elementIndex];

		int numberOfElements;
		int propertyCount;

		// Free this after we are done with it
		PlyProperty** properties =
			ply_get_element_description(m_data->plyFile, currentElementName, &numberOfElements, &propertyCount);

		std::vector<int> listOffsets;
		// Check if the user wanted this element, if yes process
		if (m_requestedElements.find(currentElementName) != m_requestedElements.end())
		{
			ElementInfo& elementInfo = m_requestedElements[currentElementName];

			// Build the propertyinfo structure
			for (size_t propertyIndex = 0; propertyIndex < elementInfo.requestedProperties.size(); ++propertyIndex)
			{
				PropertyInfo& propertyInfo = elementInfo.requestedProperties[propertyIndex];
				PlyProperty requestedProperty = {nullptr, 0, 0, 0, 0, 0, 0, 0};

				// Create temp char*
				std::vector<char> writable(propertyInfo.propertyName.size() + 1);
				std::copy(propertyInfo.propertyName.begin(), propertyInfo.propertyName.end(), writable.begin());
				requestedProperty.name = &writable[0];
				requestedProperty.internal_type = propertyInfo.dataType;
				requestedProperty.offset = propertyInfo.dataOffset;
				requestedProperty.count_internal = propertyInfo.countType;
				requestedProperty.count_offset = propertyInfo.countOffset;
				requestedProperty.is_list = (propertyInfo.countType != 0) ? PLY_LIST : PLY_SCALAR;

				if (requestedProperty.is_list == PLY_LIST)
				{
					listOffsets.push_back(propertyInfo.dataOffset);
				}

				// Tell ply that we want this property to be read and put into the readbuffer
				ply_get_property(m_data->plyFile, currentElementName, &requestedProperty);
			}

			void* readBuffer = elementInfo.startElementCallback(currentElementName, numberOfElements);

			for (int element = 0; element < numberOfElements; ++element)
			{
				ply_get_element(m_data->plyFile, readBuffer);
				if (elementInfo.processElementCallback != nullptr)
				{
					try
					{
						elementInfo.processElementCallback(currentElementName);
					}
					catch (const std::exception&)
					{
						for (size_t i = 0; i<listOffsets.size(); ++i)
						{
							void** item = (void **)((char *)readBuffer + listOffsets[i]); // NOLINT
							free(item[0]);
						}
						for (int i = 0; i < propertyCount; ++i)
						{
							free(properties[i]->name);
							free(properties[i]);
						}
						free(properties);
						throw;
					}
				}

				// Free the lists that where allocated by plyreader
				// This gains access to the buffer, where ply.c put the address of
				// the memory that was allocated to carry the information for the list property
				// it does that for all properties that where marked as lists
				for (size_t i = 0; i<listOffsets.size(); ++i)
				{
					void** item = (void **)((char *)readBuffer + listOffsets[i]); // NOLINT
					free(item[0]);
				}

			}

			if (elementInfo.endElementCallback != nullptr)
			{
				elementInfo.endElementCallback(currentElementName);
			}
		}
		else
		{
			// Inefficient way to skip an element, but there does not seem to be an
			// easy way to ignore an element
			// The data for other is stored internally in the plyFile data structure
			// and should not be freed
			ply_get_other_element(m_data->plyFile, currentElementName, numberOfElements);

		}

		// Free the data allocated in the ply_get_element_description call
		for (int i = 0; i < propertyCount; ++i)
		{
			free(properties[i]->name);
			free(properties[i]);
		}
		free(properties);
	}

	if (m_endParseFileCallback != nullptr)
	{
		m_endParseFileCallback();
	}
}
Ejemplo n.º 16
0
/**
 * @name    Native Check Create
 * @brief   Determine whether a simulation object is native to FLI and create
 *          a handle if it is
 */
GpiObjHdl*  FliImpl::native_check_create(std::string &name, GpiObjHdl *parent)
{
    bool search_rgn       = false;
    bool search_sig       = false;
    bool search_var       = false;

    std::string   fq_name  = parent->get_fullname();
    gpi_objtype_t obj_type = parent->get_type();

    if (fq_name == "/") {
        fq_name += name;
        search_rgn = true;
        search_sig = true;
        search_var = true;
    } else if (obj_type == GPI_MODULE) {
        fq_name += "/" + name;
        search_rgn = true;
        search_sig = true;
        search_var = true;
    } else if (obj_type == GPI_STRUCTURE) {
        FliValueObjHdl *fli_obj = reinterpret_cast<FliValueObjHdl *>(parent);

        fq_name += "." + name;
        search_rgn = false;
        search_var = fli_obj->is_var();
        search_sig = !search_var;
    } else {
        LOG_ERROR("FLI: Parent of type %d must be of type GPI_MODULE or GPI_STRUCTURE to have a child.", obj_type);
        return NULL;
    }

    LOG_DEBUG("Looking for child %s from %s", name.c_str(), parent->get_name_str());

    std::vector<char> writable(fq_name.begin(), fq_name.end());
    writable.push_back('\0');

    HANDLE hdl = NULL;
    PLI_INT32 accType;
    PLI_INT32 accFullType;

    if (search_rgn && (hdl = mti_FindRegion(&writable[0])) != NULL) {
        accType     = acc_fetch_type(hdl);
        accFullType = acc_fetch_fulltype(hdl);
        LOG_DEBUG("Found region %s -> %p", fq_name.c_str(), hdl);
        LOG_DEBUG("        Type: %d", accType);
        LOG_DEBUG("   Full Type: %d", accFullType);
    } else if (search_sig && (hdl = mti_FindSignal(&writable[0])) != NULL) {
        accType     = acc_fetch_type(hdl);
        accFullType = acc_fetch_fulltype(hdl);
        LOG_DEBUG("Found a signal %s -> %p", fq_name.c_str(), hdl);
        LOG_DEBUG("        Type: %d", accType);
        LOG_DEBUG("   Full Type: %d", accFullType);
    } else if (search_var && (hdl = mti_FindVar(&writable[0])) != NULL) {
        accFullType = accType = mti_GetVarKind(static_cast<mtiVariableIdT>(hdl));
        LOG_DEBUG("Found a variable %s -> %p", fq_name.c_str(), hdl);
        LOG_DEBUG("        Type: %d", accType);
        LOG_DEBUG("   Full Type: %d", accFullType);
    } else if (search_rgn){
        mtiRegionIdT rgn;

        /* If not found, check to see if the name of a generate loop and create a pseudo-region */
        for (rgn = mti_FirstLowerRegion(parent->get_handle<mtiRegionIdT>()); rgn != NULL; rgn = mti_NextRegion(rgn)) {
            if (acc_fetch_fulltype(rgn) == accForGenerate) {
                std::string rgn_name = mti_GetRegionName(static_cast<mtiRegionIdT>(rgn));
                if (rgn_name.compare(0,name.length(),name) == 0) {
                    FliObj *fli_obj = dynamic_cast<FliObj *>(parent);
                    return create_gpi_obj_from_handle(parent->get_handle<HANDLE>(), name, fq_name, fli_obj->get_acc_type(), fli_obj->get_acc_full_type());
                }
            }
        }
    }

    if (NULL == hdl) {
        LOG_DEBUG("Didn't find anything named %s", &writable[0]);
        return NULL;
    }

    /* Generate Loops have inconsistent behavior across fli.  A "name"
     * without an index, i.e. dut.loop vs dut.loop(0), will attempt to map
     * to index 0, if index 0 exists.  If it doesn't then it won't find anything.
     *
     * If this unique case is hit, we need to create the Pseudo-region, with the handle
     * being equivalent to the parent handle.
     */
    if (accFullType == accForGenerate) {
        FliObj *fli_obj = dynamic_cast<FliObj *>(parent);
        return create_gpi_obj_from_handle(parent->get_handle<HANDLE>(), name, fq_name, fli_obj->get_acc_type(), fli_obj->get_acc_full_type());
    }

    return create_gpi_obj_from_handle(hdl, name, fq_name, accType, accFullType);
}
Ejemplo n.º 17
0
/**
 * @name    Native Check Create
 * @brief   Determine whether a simulation object is native to FLI and create
 *          a handle if it is
 */
GpiObjHdl*  FliImpl::native_check_create(int32_t index, GpiObjHdl *parent)
{
    gpi_objtype_t obj_type = parent->get_type();

    HANDLE hdl;
    PLI_INT32 accType;
    PLI_INT32 accFullType;
    char buff[14];

    if (obj_type == GPI_GENARRAY) {
        LOG_DEBUG("Looking for index %d from %s", index, parent->get_name_str());

        snprintf(buff, 14, "(%d)", index);

        std::string idx = buff;
        std::string name = parent->get_name() + idx;
        std::string fq_name = parent->get_fullname() + idx;

        std::vector<char> writable(fq_name.begin(), fq_name.end());
        writable.push_back('\0');

        if ((hdl = mti_FindRegion(&writable[0])) != NULL) {
            accType     = acc_fetch_type(hdl);
            accFullType = acc_fetch_fulltype(hdl);
            LOG_DEBUG("Found region %s -> %p", fq_name.c_str(), hdl);
            LOG_DEBUG("        Type: %d", accType);
            LOG_DEBUG("   Full Type: %d", accFullType);
        } else {
            LOG_DEBUG("Didn't find anything named %s", &writable[0]);
            return NULL;
        }

        return create_gpi_obj_from_handle(hdl, name, fq_name, accType, accFullType);
    } else if (obj_type == GPI_REGISTER || obj_type == GPI_ARRAY || obj_type == GPI_STRING) {
        FliValueObjHdl *fli_obj = reinterpret_cast<FliValueObjHdl *>(parent);

        LOG_DEBUG("Looking for index %u from %s", index, parent->get_name_str());

        if ((hdl = fli_obj->get_sub_hdl(index)) == NULL) {
            LOG_DEBUG("Didn't find the index %d", index);
            return NULL;
        }

        snprintf(buff, 14, "(%d)", index);

        std::string idx = buff;
        std::string name = parent->get_name() + idx;
        std::string fq_name = parent->get_fullname() + idx;

        if (!(fli_obj->is_var())) {
            accType     = acc_fetch_type(hdl);
            accFullType = acc_fetch_fulltype(hdl);
            LOG_DEBUG("Found a signal %s -> %p", fq_name.c_str(), hdl);
            LOG_DEBUG("        Type: %d", accType);
            LOG_DEBUG("   Full Type: %d", accFullType);
        } else {
            accFullType = accType = mti_GetVarKind(static_cast<mtiVariableIdT>(hdl));
            LOG_DEBUG("Found a variable %s -> %p", fq_name.c_str(), hdl);
            LOG_DEBUG("        Type: %d", accType);
            LOG_DEBUG("   Full Type: %d", accFullType);
        }
        return create_gpi_obj_from_handle(hdl, name, fq_name, accType, accFullType);
    } else {
        LOG_ERROR("FLI: Parent of type %d must be of type GPI_GENARRAY, GPI_REGISTER, GPI_ARRAY, or GPI_STRING to have an index.", obj_type);
        return NULL;
    }
}
Ejemplo n.º 18
0
void
PeridigmNS::InterfaceData::WriteExodusOutput(int timeStep, const float & timeValue, Teuchos::RCP<Epetra_Vector> x, Teuchos::RCP<Epetra_Vector> y){

  int error_int = 0;

  int CPU_word_size = 0;
  int IO_word_size = 0;
  float version = 0;
  std::string outputFileNameStr = filename.str();
  std::vector<char> writable(outputFileNameStr.size() + 1);
  std::copy(outputFileNameStr.begin(), outputFileNameStr.end(), writable.begin());

  exoid = ex_open(&writable[0], EX_WRITE, &CPU_word_size, &IO_word_size, &version);

  error_int = ex_put_time(exoid, timeStep, &timeValue);
  TEUCHOS_TEST_FOR_EXCEPTION(error_int,std::logic_error, "ex_put_time(): Failure");

  float * quadValues = new float[numQuads];
  float * triValues = new float[numTris];

  // populate the quad values
  int quadIndex = 0;
  int triIndex = 0;
  for(int i=0;i<numOwnedPoints;++i){
    if(interfaceNodesMap->ElementSize(i)==4){
      quadValues[quadIndex] = (*interfaceAperture)[i];
      quadIndex++;
    }
    else if(interfaceNodesMap->ElementSize(i)==3){
      triValues[triIndex] = (*interfaceAperture)[i];
      triIndex++;
    }
    else{
      TEUCHOS_TEST_FOR_EXCEPTION(true,std::invalid_argument,"size of this element is not recognized: " << interfaceNodesMap->ElementSize(i));
    }
  }

  int blockIndex = 0;
  const int varIndex = 1;
  blockIndex++;
  if(numQuads > 0){
    error_int = ex_put_elem_var(exoid, timeStep, varIndex, blockIndex, numQuads, &quadValues[0]);
    TEUCHOS_TEST_FOR_EXCEPTION(error_int,std::logic_error,"Failure ex_put_elem_var(): ");
  }
  blockIndex++;
  if(numTris > 0){
    error_int = ex_put_elem_var(exoid, timeStep, varIndex, blockIndex, numTris, &triValues[0]);
    TEUCHOS_TEST_FOR_EXCEPTION(error_int,std::logic_error,"Failure ex_put_elem_var(): ");
  }

  delete [] quadValues;
  delete [] triValues;

  // update the apertures...
  // import the mothership vectors x and y to the overlap epetra vectors
  Teuchos::RCP<const Epetra_Import> importer = Teuchos::rcp(new Epetra_Import(*elemOverlapMap, x->Map()));

  Teuchos::RCP<Epetra_Vector> xOverlap = Teuchos::rcp(new Epetra_Vector(*elemOverlapMap,true));
  xOverlap->Import(*x,*importer,Insert);
  Teuchos::RCP<Epetra_Vector> yOverlap = Teuchos::rcp(new Epetra_Vector(*elemOverlapMap,true));
  yOverlap->Import(*y,*importer,Insert);

  double *xValues;
  xOverlap->ExtractView( &xValues );
  double *yValues;
  yOverlap->ExtractView( &yValues );

  double xLeft=0,yLeft=0,zLeft=0,xRight=0,yRight=0,zRight=0;
  double XLeft=0,YLeft=0,ZLeft=0,XRight=0,YRight=0,ZRight=0;
  double X=0,Y=0;
  double dx=0,dy=0,dz=0,dX=0,dY=0,dZ=0;
  int elemIndexLeft=-1,elemIndexRight=-1,GIDLeft=-1,GIDRight=-1;

  for(int i=0;i<numOwnedPoints;++i){
    GIDLeft = elementLeft[i];
    GIDRight = elementRight[i];

    elemIndexLeft = xOverlap->Map().FirstPointInElement(elemOverlapMap->LID(GIDLeft));
    elemIndexRight = xOverlap->Map().FirstPointInElement(elemOverlapMap->LID(GIDRight));

    xLeft = xValues[elemIndexLeft+0];
    yLeft = xValues[elemIndexLeft+1];
    zLeft = xValues[elemIndexLeft+2];
    xRight = xValues[elemIndexRight+0];
    yRight = xValues[elemIndexRight+1];
    zRight = xValues[elemIndexRight+2];

    XLeft = yValues[elemIndexLeft+0];
    YLeft = yValues[elemIndexLeft+1];
    ZLeft = yValues[elemIndexLeft+2];
    XRight = yValues[elemIndexRight+0];
    YRight = yValues[elemIndexRight+1];
    ZRight = yValues[elemIndexRight+2];

    dx = xRight - xLeft;
    dy = yRight - yLeft;
    dz = zRight - zLeft;

    dX = XRight - XLeft;
    dY = YRight - YLeft;
    dZ = ZRight - ZLeft;

    X = std::sqrt(dx*dx + dy*dy + dz*dz);
    Y = std::sqrt(dX*dX + dY*dY + dZ*dZ);

    interfaceAperture->ReplaceMyValue(i,0,Y-X);
  }
  error_int = ex_update(exoid);
  TEUCHOS_TEST_FOR_EXCEPTION(error_int,std::logic_error,"Exodus file close failed.");
  error_int = ex_close(exoid);
  TEUCHOS_TEST_FOR_EXCEPTION(error_int,std::logic_error,"Exodus file close failed.");

}
Ejemplo n.º 19
0
void
PeridigmNS::InterfaceData::InitializeExodusOutput(Teuchos::RCP<Epetra_Vector> exodusMeshElementConnectivity, Teuchos::RCP<Epetra_Vector> exodusMeshNodePositions){

  if(comm->NumProc()>1){
    filename << "Interfaces.e." << comm->NumProc() << "." << comm->MyPID();
  }
  else{
    filename << "Interfaces.e";
  }
  std::string outputFileNameStr = filename.str();
  std::vector<char> writable(outputFileNameStr.size() + 1);
  std::copy(outputFileNameStr.begin(), outputFileNameStr.end(), writable.begin());

  int spaDim = 3; // force three dimensional output
  const int numShells = numOwnedPoints;
  const int numNodes = exodusMeshNodePositions->Map().NumMyElements();
  int error_int;
  int CPU_word_size = 0;
  int IO_word_size = 0;
  /* create EXODUS II file */
  const int output_exoid = ex_create (&writable[0],EX_CLOBBER,&CPU_word_size, &IO_word_size);
  exoid = output_exoid;

  // scan the connectivity to see if there are quads and tets:
  numQuads = 0;
  numTris = 0;
  for(int i=0;i<numOwnedPoints;++i){
    if(interfaceNodesMap->ElementSize(i)==4) numQuads++;
    if(interfaceNodesMap->ElementSize(i)==3) numTris++;
  }
  TEUCHOS_TEST_FOR_EXCEPTION(numQuads+numTris!=numShells,std::logic_error,"numQuads " << numQuads << "  + numTris " << numTris << " should sum up to numShells " << numShells);


  const int numBlocks = 2;

  error_int = ex_put_init(exoid, &writable[0], spaDim, numNodes, numShells, numBlocks, 0, 0);
  TEUCHOS_TEST_FOR_EXCEPTION(error_int,std::logic_error,"ex_put_init(): Failure");

  //  write initial coordinates and node/element maps
  float * x = new float[numNodes];
  float * y = new float[numNodes];
  float * z = new float[numNodes];

  int * shellMap = new int[numShells];
  int * nodeMap = new int[numNodes];

  for(int i=0;i<numNodes;++i){
    int nodeIndex = exodusMeshNodePositions->Map().FirstPointInElement(i);
    x[i] = (*exodusMeshNodePositions)[nodeIndex+0];
    y[i] = (*exodusMeshNodePositions)[nodeIndex+1];
    z[i] = (*exodusMeshNodePositions)[nodeIndex+2];
    nodeMap[i] = exodusMeshNodePositions->Map().GID(i) + 1; // numbering is one based in exodus
  }
  for(int i=0;i<numShells;++i){
    shellMap[i] = interfaceNodesMap->GID(i) +1; // numbering is one based in exodus
  }

  error_int = ex_put_coord(exoid, x, y, z);
  char * coord_names[3];
  coord_names[0] = (char*) "coordinates_x";
  coord_names[1] = (char*) "coordinates_y";
  coord_names[2] = (char*) "coordinates_x";
  error_int = ex_put_coord_names(exoid, coord_names);
  TEUCHOS_TEST_FOR_EXCEPTION(error_int,std::logic_error,"ex_put_coord_names(): Failure");
  error_int = ex_put_elem_num_map(exoid, shellMap);
  TEUCHOS_TEST_FOR_EXCEPTION(error_int,std::logic_error,"ex_put_elem_num_map(): Failure");
  error_int = ex_put_node_num_map(exoid, nodeMap);
  TEUCHOS_TEST_FOR_EXCEPTION(error_int,std::logic_error,"ex_put_node_num_map(): Failure");
  delete[] shellMap;
  delete[] nodeMap;
  delete[] x; delete[] y; delete[] z;

  // write quad blocks:
  int blockIndex = 0;
  blockIndex ++;
  int num_nodes_per_elem_q4 = 4;
  const std::string elem_type_str_q4 = numQuads > 0 ? "QUAD4" : "NULL";
  char * elem_type_q4 = const_cast<char *>(elem_type_str_q4.c_str());
  const int numElemInBlock_q4 = numQuads;
  error_int = ex_put_elem_block(exoid, blockIndex, elem_type_q4, numElemInBlock_q4, num_nodes_per_elem_q4, 0); // no attributes put in output file
  TEUCHOS_TEST_FOR_EXCEPTION(error_int,std::logic_error,"ex_put_elem_block(): Failure");
  blockIndex ++;
  int num_nodes_per_elem_t3 = 3;
  const std::string elem_type_str_t3 = numTris > 0 ? "TRI3": "NULL";
  char * elem_type_t3 = const_cast<char *>(elem_type_str_t3.c_str());
  const int numElemInBlock_t3 = numTris;
  error_int = ex_put_elem_block(exoid, blockIndex, elem_type_t3, numElemInBlock_t3, num_nodes_per_elem_t3, 0); // no attributes put in output file
  TEUCHOS_TEST_FOR_EXCEPTION(error_int,std::logic_error,"ex_put_elem_block(): Failure");

  //  write elem connectivities
  //  HEADS UP: the connectivities will not write to file until ex_close is called
  //  also note that the nodes must be the local node ids

  const int connLength = interfaceNodes->Map().NumMyElements();

  blockIndex = 0;
  blockIndex ++;
  int conn_index = 0;
  int * block_connect_q4 = new int[numQuads*num_nodes_per_elem_q4];
  for(int it=0;it<connLength;++it)
  {
    if(interfaceNodes->Map().ElementSize(it)!=4) continue;
    int elemIndex = interfaceNodes->Map().FirstPointInElement(it);
    for(int nn=0;nn<4;++nn){
      int node = static_cast<int>( (*interfaceNodes)[elemIndex+nn] );
      block_connect_q4[conn_index*num_nodes_per_elem_q4+nn] = exodusMeshNodePositions->Map().LID(node) + 1;// nodes are 1 based in exodus
    }
    conn_index++;
  }
  error_int = ex_put_elem_conn(exoid, blockIndex, block_connect_q4);
  delete[] block_connect_q4;
  blockIndex ++;
  conn_index = 0;
  int * block_connect_t3 = new int[numTris*num_nodes_per_elem_t3];
  for(int it=0;it<connLength;++it)
  {
    if(interfaceNodes->Map().ElementSize(it)!=3) continue;
    int elemIndex = interfaceNodes->Map().FirstPointInElement(it);
    for(int nn=0;nn<3;++nn){
      int node = static_cast<int>( (*interfaceNodes)[elemIndex+nn] );
      block_connect_t3[conn_index*num_nodes_per_elem_t3+nn] = exodusMeshNodePositions->Map().LID(node) + 1;// nodes are 1 based in exodus
    }
    conn_index++;
  }
  error_int = ex_put_elem_conn(exoid, blockIndex, block_connect_t3);
  delete[] block_connect_t3;

  int numVariables = 1; // TODO careful with this, if more fields are added to the interface data this must be updated
  char** eleVarNames = new char*[numVariables];
  std::vector<std::string> strNames;
  strNames.push_back("interface_aperture");
  for (int i=0;i<numVariables;++i)
    eleVarNames[i] = (char*) (strNames[i].c_str());
  error_int = ex_put_var_param(exoid, (char*) "e", numVariables);
  error_int = ex_put_var_names(exoid, (char*) "e", numVariables, &eleVarNames[0]);

  delete [] eleVarNames;

  // write the truth table
  int * truth_tab = new int[numVariables*numBlocks];
  for(int i=0;i<numVariables*numBlocks;++i)
    truth_tab[i] = 1;
  error_int = ex_put_elem_var_tab (exoid, numBlocks, numVariables, truth_tab);
  delete [] truth_tab;

  error_int = ex_update(exoid);
  TEUCHOS_TEST_FOR_EXCEPTION(error_int,std::logic_error,"Exodus file close failed.");
  error_int = ex_close(exoid);
  TEUCHOS_TEST_FOR_EXCEPTION(error_int,std::logic_error,"Exodus file close failed.");

}
Ejemplo n.º 20
0
	/**
	 * parse the domain file
	 */
	void DomainParser::parseDomain(const std::string domainPath) {
		
		// only parse domain once
		if(domain_parsed) return;
		domain_parsed = true;

		std::string domainFileName = (domainPath);
		ROS_INFO("KCL: (KB) Parsing domain: %s.", domainFileName.c_str());

		// save filename for VAL
		std::vector<char> writable(domainFileName.begin(), domainFileName.end());
		writable.push_back('\0');
		current_filename = &writable[0];

		// parse domain
		VAL::current_analysis = &VAL::an_analysis;
		std::ifstream domainFile;
		domainFile.open(domainFileName.c_str());
		yydebug = 0;

		VAL::yfl = new yyFlexLexer;

		if (domainFile.bad()) {
			ROS_ERROR("KCL: (KB) Failed to open domain file.");
			line_no = 0;
			VAL::log_error(VAL::E_FATAL,"Failed to open file");
		} else {
			line_no = 1;
			VAL::yfl->switch_streams(&domainFile, &std::cout);
			yyparse();

			// domain name
			VAL::domain* domain = VAL::current_analysis->the_domain;
			domain_name = domain->name;

			// types
			VAL::pddl_type_list* types = domain->types;
			for (VAL::pddl_type_list::const_iterator ci = types->begin(); ci != types->end(); ci++) {
				const VAL::pddl_type* type = *ci;
				domain_types.push_back(type->getName());
			}

			// predicates
			VAL::pred_decl_list* predicates = domain->predicates;
			if(predicates) {
				for (VAL::pred_decl_list::const_iterator ci = predicates->begin(); ci != predicates->end(); ci++) {
					const VAL::pred_decl* predicate = *ci;

					// predicate name
					PDDLAtomicFormula pred;
					pred.name = predicate->getPred()->symbol::getName();
					domain_predicates[pred.name] = pred;

					// predicate variables
					for (VAL::var_symbol_list::const_iterator vi = predicate->getArgs()->begin(); vi != predicate->getArgs()->end(); vi++) {

						const VAL::var_symbol* var = *vi;
						PDDLTypedSymbol sym;
						sym.type = var->type->getName();
						sym.name = var->pddl_typed_symbol::getName();
						domain_predicates[pred.name].vars.push_back(sym);
					}
				}
			}

			// functions
			VAL::func_decl_list* functions = domain->functions;
			if(functions) {
				for (VAL::func_decl_list::const_iterator ci = functions->begin(); ci != functions->end(); ci++) {
					const VAL::func_decl* function = *ci;
					// function name
					PDDLAtomicFormula func;
					func.name = function->getFunction()->symbol::getName();
					domain_functions[func.name] = func;

					// parameters
					for (VAL::var_symbol_list::const_iterator vi = function->getArgs()->begin(); vi != function->getArgs()->end(); vi++) {
						const VAL::var_symbol* var = *vi;
						PDDLTypedSymbol sym;
						sym.type = var->type->getName();
						sym.name = var->pddl_typed_symbol::getName();
						domain_functions[func.name].vars.push_back(sym);
					}
				}
			}

			// operators
			VAL::operator_list* operators = domain->ops;
			for (VAL::operator_list::const_iterator ci = operators->begin(); ci != operators->end(); ci++) {			
				const VAL::operator_* op = *ci;

				// name
				std::string name = op->name->symbol::getName();

				// condition
				const VAL::goal* precondition = op->precondition;
				PDDLGoalDescription c = parseCondition(precondition);

				// duration
				PDDLFunctionNumber n(0);
				PDDLDuration d(n, EQ);
				const VAL::durative_action* da = dynamic_cast<const VAL::durative_action*>(op);
				if (da) {
					// TODO get the real duration from VAL
					PDDLFunctionNumber n(1);
					d = PDDLDuration(n, EQ);
				}

				// operator
				PDDLOperator oper(d, c);
				oper.name = name;

				// parameters
				for (VAL::var_symbol_list::const_iterator vi = op->parameters->begin(); vi != op->parameters->end(); vi++) {
					const VAL::var_symbol* var = *vi;
					PDDLTypedSymbol sym;
					sym.type = var->type->getName();
					sym.name = var->pddl_typed_symbol::getName();
					oper.parameters.push_back(sym);
				}

				domain_operators.insert( std::pair<std::string,PDDLOperator>(name, oper) );
			}
		}
		domainFile.close();
		delete VAL::yfl;
	}
Ejemplo n.º 21
0
static void mplex() {
	struct timeval timeout = {
		.tv_sec = 1,
		.tv_usec = 0,
	};
	int i;
	int maxfd = 0;
	fd_set rok, wok, xok;
	FD_ZERO(&rok);
	FD_ZERO(&wok);
	FD_ZERO(&xok);
	if (io_stop == 1) {
		io_stop = 2;
		q_puts(&sockets->net[0].sendq, "X\n");
	}
	for(i=0; i < sockets->count; i++) {
		struct sockifo* ifo = &sockets->net[i];
		if (ifo->death_time && ifo->death_time < now) {
			esock(ifo, "Ping Timeout");
		}
		if (ifo->fd < 0) {
			if (ifo->state.mplex_dropped) {
				delnet_real(ifo);
				i--;
			}
			continue;
		}
		if (ifo->fd > maxfd)
			maxfd = ifo->fd;

		int need_read, need_write;
		switch (ifo->state.poll) {
		case POLL_NORMAL:
			writable(ifo);
			need_read = 1;
			need_write = (ifo->sendq.start != ifo->sendq.end);
			break;
		case POLL_FORCE_ROK:
			writable(ifo);
			need_read = 1;
			need_write = 0;
			break;
		case POLL_FORCE_WOK:
			need_read = 0;
			need_write = 1;
			break;
		case POLL_HANG:
		default:
			need_read = 0;
			need_write = 0;
		}
		if (ifo->fd < 0)
			continue;
		if (need_read)
			FD_SET(ifo->fd, &rok);
		if (need_write)
			FD_SET(ifo->fd, &wok);
		FD_SET(ifo->fd, &xok);
		if (io_stop == 2)
			break;
	}
	int ready = select(maxfd + 1, &rok, &wok, &xok, &timeout);
	time_t new_ts = time(NULL);
	if (now != new_ts && io_stop != 2) {
		now = new_ts;
		qprintf(&sockets->net[0].sendq, "T %d\n", now);
	}
	if (ready <= 0)
		return;
	for(i=0; i < sockets->count; i++) {
		struct sockifo* ifo = &sockets->net[i];
		if (ifo->fd < 0)
			continue;
		if (FD_ISSET(ifo->fd, &xok)) {
			esock(ifo, "Exception on socket");
			continue;
		}
		if (FD_ISSET(ifo->fd, &wok)) {
			writable(ifo);
			if (ifo->fd < 0)
				continue;
		}
		if (FD_ISSET(ifo->fd, &rok)) {
			readable(ifo);
		}
		if (io_stop == 2)
			return;
	}
	if (ready > 1 || !FD_ISSET(sockets->net[0].fd, &rok))
		q_puts(&sockets->net[0].sendq, "Q\n");
}

static void sig2child(int sig) {
	kill(worker_pid, sig);
}
Ejemplo n.º 22
0
int copy(const char *src, const char *dst, struct stat *srcst,
			struct stat *dstst)
/* Copy one file to another and copy (some of) the attributes. */
{
    char buf[CHUNK];
    int srcfd, dstfd;
    ssize_t n;

    assert(srcst->st_ino != 0);

    if (dstst->st_ino == 0) {
	/* The file doesn't exist yet. */

	if (!S_ISREG(srcst->st_mode)) {
	    /* Making a new mode 666 regular file. */
	    srcst->st_mode= (S_IFREG | 0666) & fc_mask;
	} else
	if (!pflag && conforming) {
	    /* Making a new file copying mode with umask applied. */
	    srcst->st_mode &= fc_mask;
	}
    } else {
	/* File exists, ask if ok to overwrite if '-i'. */

	if (iflag || (action == MOVE && !fflag && !writable(dstst))) {
	    fprintf(stderr, "Overwrite %s? (mode = %03o) ",
			dst, dstst->st_mode & 07777);
	    if (!affirmative()) return 0;
	}

	if (action == MOVE) {
	    /* Don't overwrite, remove first. */
	    if (unlink(dst) < 0 && errno != ENOENT) {
		report(dst);
		return 0;
	    }
	} else {
	    /* Overwrite. */
	    if (!pflag) {
		/* Keep the existing mode and ownership. */
		srcst->st_mode= dstst->st_mode;
		srcst->st_uid= dstst->st_uid;
		srcst->st_gid= dstst->st_gid;
	    }
	}
    }

    /* Keep the link structure if possible. */
    if (trylink(src, dst, srcst, dstst)) return 1;

    if ((srcfd= open(src, O_RDONLY)) < 0) {
	report(src);
	return 0;
    }

    dstfd= open(dst, O_WRONLY|O_CREAT|O_TRUNC, srcst->st_mode & 0777);
    if (dstfd < 0 && fflag && errno == EACCES) {
	/* Retry adding a "w" bit. */
	(void) chmod(dst, dstst->st_mode | S_IWUSR);
	dstfd= open(dst, O_WRONLY|O_CREAT|O_TRUNC, 0);
    }
    if (dstfd < 0 && fflag && errno == EACCES) {
	/* Retry after trying to delete. */
	(void) unlink(dst);
	dstfd= open(dst, O_WRONLY|O_CREAT|O_TRUNC, 0);
    }
    if (dstfd < 0) {
	report(dst);
	close(srcfd);
	return 0;
    }

    /* Get current parameters. */
    if (fstat(dstfd, dstst) < 0) {
	report(dst);
	close(srcfd);
	close(dstfd);
	return 0;
    }

    /* Copy the little bytes themselves. */
    while ((n= read(srcfd, buf, sizeof(buf))) > 0) {
	char *bp = buf;
	ssize_t r;

	while (n > 0 && (r= write(dstfd, bp, n)) > 0) {
	    bp += r;
	    n -= r;
	}
	if (r <= 0) {
	    if (r == 0) {
		fprintf(stderr,
		    "%s: Warning: EOF writing to %s\n",
		    prog_name, dst);
		break;
	    }
	    fatal(dst);
	}
    }

    if (n < 0) {
	report(src);
	close(srcfd);
	close(dstfd);
	return 0;
    }

    close(srcfd);
    close(dstfd);

    /* Copy the ownership. */
    if ((pflag || !conforming)
	&& S_ISREG(dstst->st_mode)
	&& (dstst->st_uid != srcst->st_uid
		|| dstst->st_gid != srcst->st_gid)
    ) {
	if (chmod(dst, 0) == 0) dstst->st_mode&= ~07777;
	if (chown(dst, srcst->st_uid, srcst->st_gid) < 0) {
	    if (errno != EPERM) {
		report(dst);
		return 0;
	    }
	} else {
	    dstst->st_uid= srcst->st_uid;
	    dstst->st_gid= srcst->st_gid;
	}
    }

    if (conforming && S_ISREG(dstst->st_mode)
	&& (dstst->st_uid != srcst->st_uid
		|| dstst->st_gid != srcst->st_gid)
    ) {
	/* Suid bits must be cleared in the holy name of
	 * security (and the assumed user stupidity).
	 */
	srcst->st_mode&= ~06000;
    }

    /* Copy the mode. */
    if (S_ISREG(dstst->st_mode) && dstst->st_mode != srcst->st_mode) {
	if (chmod(dst, srcst->st_mode) < 0) {
	    if (errno != EPERM) {
		report(dst);
		return 0;
	    }
	    fprintf(stderr, "%s: Can't change the mode of %s\n",
		prog_name, dst);
	}
    }

    /* Copy the file modification time. */
    if ((pflag || !conforming) && S_ISREG(dstst->st_mode)) {
	struct utimbuf ut;

	ut.actime= action == MOVE ? srcst->st_atime : time(nil);
	ut.modtime= srcst->st_mtime;
	if (utime(dst, &ut) < 0) {
	    if (errno != EPERM) {
		report(dst);
		return 0;
	    }
	    if (pflag) {
		fprintf(stderr,
		    "%s: Can't set the time of %s\n",
		    prog_name, dst);
	    }
	}
    }
    if (vflag) {
	printf(action == COPY ? "cp %s ..\n" : "mv %s ..\n", src);
    }
    return 1;
}
Ejemplo n.º 23
0
bool RenderThinker::start()
{
        int halfWidth = resultSize.width() / 2;
        int halfHeight = resultSize.height() / 2;
        QImage image(resultSize, QImage::Format_RGB32);

        const int NumPasses = 8;
        int pass = 0;
        while (pass < NumPasses) {
            const int MaxIterations = (1 << (2 * pass + 6)) + 32;
            const int Limit = 4;
            bool allBlack = true;

            for (int y = -halfHeight; y < halfHeight; ++y) {
               if (wasPauseRequested())
                    return;

                uint *scanLine =
                        reinterpret_cast<uint *>(image.scanLine(y + halfHeight));
                double ay = centerY + (y * scaleFactor);

                for (int x = -halfWidth; x < halfWidth; ++x) {
                    double ax = centerX + (x * scaleFactor);
                    double a1 = ax;
                    double b1 = ay;
                    int numIterations = 0;

                    do {
                        ++numIterations;
                        double a2 = (a1 * a1) - (b1 * b1) + ax;
                        double b2 = (2 * a1 * b1) + ay;
                        if ((a2 * a2) + (b2 * b2) > Limit)
                            break;

                        ++numIterations;
                        a1 = (a2 * a2) - (b2 * b2) + ax;
                        b1 = (2 * a2 * b2) + ay;
                        if ((a1 * a1) + (b1 * b1) > Limit)
                            break;
                    } while (numIterations < MaxIterations);

                    if (numIterations < MaxIterations) {
                        *scanLine++ = colormap[numIterations % ColormapSize];
                        allBlack = false;
                    } else {
                        *scanLine++ = qRgb(0, 0, 0);
                    }
                }
            }

            if (allBlack && pass == 0) {
                pass = 4;
            } else {
                lockForWrite();
                writable().image = image;
                writable().scaleFactor = scaleFactor;
                unlock();
                ++pass;
            }
        }
        return true;
}
Ejemplo n.º 24
0
int VhpiSignalObjHdl::set_signal_value(std::string &value)
{
    switch (m_value.format) {
        case vhpiEnumVal:
        case vhpiLogicVal: {
            m_value.value.enumv = chr2vhpi(value.c_str()[0]);
            break;
        }

        case vhpiEnumVecVal:
        case vhpiLogicVecVal: {

            int len = value.length();

            // Since we may not get the numElems correctly from the sim and have to infer it
            // we also need to set it here as well each time.

            m_value.numElems = len;

            if (len > m_num_elems) {
                LOG_DEBUG("VHPI: Attempt to write string longer than (%s) signal %d > %d",
                          m_name.c_str(), len, m_num_elems);
                m_value.numElems = m_num_elems;
            }

            std::string::iterator iter;

            int i = 0;
            for (iter = value.begin();
                 (iter != value.end()) && (i < m_num_elems);
                 iter++, i++) {
                m_value.value.enumvs[i] = chr2vhpi(*iter);
            }

            // Fill bits at the end of the value to 0's
            for (i = len; i < m_num_elems; i++) {
                m_value.value.enumvs[i] = vhpi0;
            }

            break;
        }

        case vhpiStrVal: {
            std::vector<char> writable(value.begin(), value.end());
            writable.push_back('\0');
            strncpy(m_value.value.str, &writable[0], m_value.numElems);
            m_value.value.str[m_value.numElems] = '\0';
            break;
        }

        default: {
            LOG_ERROR("VHPI: Unable to handle this format type %s",
                      ((VhpiImpl*)GpiObjHdl::m_impl)->format_to_string(m_value.format));
            return -1;
        }
    }

    if (vhpi_put_value(GpiObjHdl::get_handle<vhpiHandleT>(), &m_value, vhpiDepositPropagate)) {
        check_vhpi_error();
        return -1;
    }

    return 0;
}
Ejemplo n.º 25
0
void copy1(const char *src, const char *dst, struct stat *srcst,
			    struct stat *dstst)
/* Inspect the source file and then copy it.  Treatment of symlinks and
 * special files is a bit complicated.  The filetype and link-structure are
 * ignored if (expand && !rflag), symlinks and link-structure are ignored
 * if (expand && rflag), everything is copied precisely if !expand.
 */
{
    int r, linked;

    assert(srcst->st_ino != 0);

    if (srcst->st_ino == dstst->st_ino && srcst->st_dev == dstst->st_dev) {
	fprintf(stderr, "%s: can't copy %s onto itself\n",
	    prog_name, src);
	ex_code= 1;
	return;
    }

    /* You can forget it if the destination is a directory. */
    if (dstst->st_ino != 0 && S_ISDIR(dstst->st_mode)) {
	errno= EISDIR;
	report(dst);
	return;
    }

    if (S_ISREG(srcst->st_mode) || (expand && !rflag)) {
	if (!copy(src, dst, srcst, dstst)) return;

	if (action == MOVE && unlink(src) < 0) {
	    report(src);
	    return;
	}
	return;
    }

    if (dstst->st_ino != 0) {
	if (iflag || (action == MOVE && !fflag && !writable(dstst))) {
	    fprintf(stderr, "Replace %s? (mode = %03o) ",
		dst, dstst->st_mode & 07777);
	    if (!affirmative()) return;
	}
	if (unlink(dst) < 0) {
	    report(dst);
	    return;
	}
	dstst->st_ino= 0;
    }

    /* Apply the file creation mask if so required. */
    if (!pflag && conforming) srcst->st_mode &= fc_mask;

    linked= 0;

    if (S_ISLNK(srcst->st_mode)) {
	char buf[1024+1];

	if ((r= readlink(src, buf, sizeof(buf)-1)) < 0) {
	    report(src);
	    return;
	}
	buf[r]= 0;
	r= symlink(buf, dst);
	if (vflag && r == 0)
	    printf("ln -s %s %s\n", buf, dst);
    } else
    if (trylink(src, dst, srcst, dstst)) {
	linked= 1;
	r= 0;
    } else
    if (S_ISFIFO(srcst->st_mode)) {
	r= mkfifo(dst, srcst->st_mode);
	if (vflag && r == 0)
	    printf("mkfifo %s\n", dst);
    } else
    if (S_ISBLK(srcst->st_mode) || S_ISCHR(srcst->st_mode)) {
	r= mknod(dst, srcst->st_mode, srcst->st_rdev);
	if (vflag && r == 0) {
	    printf("mknod %s %c %d %d\n",
		dst,
		S_ISBLK(srcst->st_mode) ? 'b' : 'c',
		(srcst->st_rdev >> 8) & 0xFF,
		(srcst->st_rdev >> 0) & 0xFF);
	}
Ejemplo n.º 26
0
std::vector<char> str2char_star (std::string str) {
  std::vector<char> writable(str.begin(), str.end());
  writable.push_back('\0');
  return writable;
  // get the char* using &writable[0] or &*writable.begin()
}