Пример #1
0
/**
 * Runs the DNS-SD sequence to discover the sFlow server settings,
 * collector addresses and ports and sampling rates and polling interval
 * settings.
 * The DNS query is scoped to query for entries in the domain (zone)
 * configured as the domain override in the registry (if set), or the
 * primary domain name configured on the system if there is no domain
 * override.
 * Note that the DNS query could fail or return no results if we are
 * unable to discover the primary domain of the system.
 * HSP *sp used to update the min TTL for DNS entries so that the
 * next DNS request can be scheduled.
 * HSPSFlowSettings *settings in which sFlow collector addresses and ports
 * and sampling and polling settings will be populated.
 * Returns the number of sFlow collectors discovered or -1 on failure.
 */
int dnsSD(HSP *sp, HSPSFlowSettings *settings)
{
    char request[HSP_MAX_DNS_LEN];
	if (sp->DNSSD_domain) {
		sprintf_s(request, HSP_MAX_DNS_LEN, "%s%s", SFLOW_DNS_SD, sp->DNSSD_domain);
	} else {
		char domain[MAX_HOSTNAME_LEN];
		memset(domain, 0, MAX_HOSTNAME_LEN);
		DWORD len = MAX_HOSTNAME_LEN;
		char *dot = "";
		if (GetComputerNameEx(ComputerNameDnsDomain, domain, &len) == 0) {
			DWORD err = GetLastError();
			logErr(LOG_ERR, err, "dnsSD: cannot determined DNS domain for this computer error=%u", err);
		} else if (len == 0) {
			myLog(LOG_ERR, "dnsSD: DNS domain for this computer not set");
		} else {
			dot = ".";
		}
		sprintf_s(request, HSP_MAX_DNS_LEN, "%s%s%s", SFLOW_DNS_SD, dot, domain);
	}
	myLog(LOG_INFO, "dnsSD: request=%s", request);
    int num_servers = dnsSD_Request(sp, settings, request, DNS_TYPE_SRV);
    dnsSD_Request(sp, settings, request, DNS_TYPE_TEXT);
    // it's ok even if only the SRV request succeeded
    return num_servers; //  -1 on error
}
Пример #2
0
Mesh* MeshManager::getMesh(string name){
	std::map<string, Mesh*>::iterator it;
	it = meshMap.find(name);
	if(it != meshMap.end()){//mesh previament carregat LEAK!
		Mesh* result = new Mesh(it->second, getNewId());
		result->generateVBO();
		return result;
	}

	if(FileSystem::getInstance()->openFile(name) == -1){
		logErr("Error TextureManager::getTexture opening %s: ", name.c_str());
		return 0;
	}
	std::size_t foundMD5 = name.find(".md5");
	std::size_t foundOBJ = name.find(".obj");
	if (foundOBJ!=std::string::npos){
		meshMap[name] = parseOBJ(name, FileSystem::getInstance()->getFileData(name), FileSystem::getInstance()->getFileSize(name));
	}
	else if (foundMD5!=std::string::npos){
		meshMap[name] = parseMD5(name, FileSystem::getInstance()->getFileData(name), FileSystem::getInstance()->getFileSize(name));
	}
	else{
		FileSystem::getInstance()->destroyFileData(name);
		return 0;
	}
	FileSystem::getInstance()->destroyFileData(name);

//	printMeshData(meshMap[name]);
	meshMap[name]->generateVBO();
	return meshMap[name];
}
Пример #3
0
int makeSocketNoBlocking(int fd){
	int flags, s;
	flags = fcntl(fd, F_GETFL, 0);
	if(flags == -1){
		logErr("fcntl");
		return -1;
	}
	flags |= O_NONBLOCK;
	s = fcntl(fd, F_SETFL, flags);
	if(s == -1){
		logErr("fcntl");
		return -1;
	}

	return 0;
}
Пример #4
0
bool NDLocalXmlString::parseLines( vector<string>& vecLines )
{
	if (vecLines.size() < 2) return false;
	m_kMapData.clear();

	bool bOK = true;
	int index = 0;
	while (index < vecLines.size() - 1)
	{
		const string& keyLine = vecLines[ index ];
		const string& valLine = vecLines[ index + 1 ];

		if (isKey(keyLine.c_str()) && isVal(valLine.c_str()))
		{
			index += 2;

			bOK &= addKeyValue( keyLine, valLine );
		}
		else
		{
			index++;

			//bad line!
			logErr( keyLine, valLine );
			bOK = false;
		}
	}

	return bOK;
}
Пример #5
0
void savepoint::getSavepointName()
{
  logMsg("savepoint::getSavepointName() - MySQL_Savepoint::getSavepointName()");
  try
  {
    con->setAutoCommit(false);
    std::auto_ptr< sql::Savepoint > sp(con->setSavepoint("mysavepoint"));
    ASSERT_EQUALS("mysavepoint", sp->getSavepointName());
    con->releaseSavepoint(sp.get());
  }
  catch (sql::SQLException &e)
  {
    logErr(e.what());
    logErr("SQLState: " + std::string(e.getSQLState()));
    fail(e.what(), __FILE__, __LINE__);
  }
}
Пример #6
0
/**
 * Issues the DNS request to discover the sFlow service settings
 * (collector addresses and ports, sampling rates and polling intervals).
 * The DNS request is configured to bypass the DNS cache and go straight
 * to the wire to avoid using stale entries.
 * If the request succeeds, updates the min TTL in HSP *sp, parses the response,
 * and returns the number of records returned, populating HSPSFlowSettings *settings
 * with the parsed result.
 * If the request fails, returns -1.
 * char *dname contains the DNS query (fully qualified)
 * WORD dtype the DNS query type (SRV for collectors or TEXT for sampling rates
 * and polling intervals)
 * Note that we are using the DnsQuery function to make the DNS request.
 * This function does not take into account the system DNS search path, so the
 * DNS query must be fully qualified (ie include the domain to search).
 */
static int dnsSD_Request(HSP *sp, HSPSFlowSettings *settings,
						 char *dname, WORD rtype)
{
	PDNS_RECORD pDnsRecord;
	DNS_FREE_TYPE dnsFreeType;
	dnsFreeType = DnsFreeRecordListDeep;
	DNS_STATUS status = DnsQuery(dname, rtype, DNS_QUERY_WIRE_ONLY, NULL, &pDnsRecord, NULL);
	if (status) {
		//fail
		logErr(LOG_ERR, status, "dnsSD_Request: DNSQuery(%s, %u) failed error=%u", dname, rtype, status);
		return -1;
	} else {
		 //process results and free
		int answerCount = 0;
		PDNS_RECORD nextRecord = pDnsRecord;
		while (nextRecord != NULL) {
			//update the minimum ttl
			DWORD ttl = nextRecord->dwTtl;
			if (sp->DNSSD_ttl == 0 || ttl < sp->DNSSD_ttl) {
				sp->DNSSD_ttl = ttl;
			}
			switch(rtype) {
			case DNS_TYPE_TEXT:
				if (nextRecord->wType == DNS_TYPE_TEXT) {
					answerCount++;
					DWORD stringCount = nextRecord->Data.TXT.dwStringCount;
					for (DWORD i = 0; i < stringCount; i++) {
						if (LOG_INFO <= debug) {
							myLog(LOG_INFO, "dnsDS_Request: DNS_TYPE_TEXT %s",
								nextRecord->Data.TXT.pStringArray[i]);
						}
						dnsSD_parseTxt(settings,
									   nextRecord->Data.TXT.pStringArray[i]);
					}
				}
				break;
			case DNS_TYPE_SRV:
				if (nextRecord->wType == DNS_TYPE_SRV) {
					answerCount++;
					if (LOG_INFO <= debug) {
						myLog(LOG_INFO, "dnsDS_Request: DNS_TYPE_SRV %s %u",
							nextRecord->Data.SRV.pNameTarget, nextRecord->Data.SRV.wPort);
					}
					insertCollector(settings, nextRecord->Data.SRV.pNameTarget, 
						nextRecord->Data.SRV.wPort);
				}
				break;
			default:
				DnsRecordListFree(pDnsRecord, dnsFreeType);
				myLog(LOG_ERR, "dnsDS_Request: unsupported query type %u", rtype);
				return -1;
			}
			nextRecord = nextRecord->pNext;
		}
		DnsRecordListFree(pDnsRecord, dnsFreeType);
		return answerCount;
	}
}
Пример #7
0
char* FileSystem::getFileData(string filePath){
	std::map<string, FileStruct* >::iterator it;
	it = fileMap.find(filePath);
	if(it == fileMap.end()){//the file isn't found
		logErr("the file %s isn't at fileMap", filePath.c_str());
		return 0;
	}
	return (it->second)->data;
}
void CameraPreviewPlaneShader::loadVars(){
	logInf("CameraPreviewPlaneShader::loadVars");
	const char* attributeName = "coord3d";
	attributeCoord = glGetAttribLocation(program, attributeName);
	if (attributeCoord == -1) {
		logErr("Could not bind attribute %s\n", attributeName);
		return;
	}
	attributeName = "texcoord";
	attributeTexture = glGetAttribLocation(program, attributeName);
	if (attributeTexture == -1) {
		logErr("Could not bind attribute %s\n", attributeName);
		attributeTexture = 0;
	}
    
    const char* uniformName;
#ifdef IOS_PLATFORM
    uniformName = "SamplerY";
	uniformLuminanceTexture = glGetUniformLocation(program, uniformName);
	if (uniformLuminanceTexture == -1) {
		logErr("Could not bind uniform %s\n", uniformName);
		return;
	}
    glUniform1i(uniformLuminanceTexture, 0);


#else
	uniformName = "texture";
	uniformTexture = glGetUniformLocation(program, uniformName);
	if (uniformTexture == -1) {
		logErr("Could not bind uniform %s\n", uniformName);
		return;
	}
    
#endif
	uniformName = "mvp";
	uniformMVP = glGetUniformLocation(program, uniformName);
	if (uniformMVP == -1) {
		logErr("Could not bind uniform %s\n", uniformName);
		return;
	}
}
/* throws Exception */
void ResultSetMetadataTest::testGetScale()
{
  logMsg("Calling getScale on ResultSetMetaData");
  int scaleSize=rsmd->getScale(2);
  if (scaleSize >= 0) {
    TestsListener::messagesLog()
            << "getScale method returns: " << scaleSize << std::endl;
  } else {
    logErr(" getScale method returns a negative value");
  }
}
/* throws Exception */
void ResultSetMetadataTest::testGetPrecision()
{
  logMsg("Calling getPrecision on ResultSetMetaData");
  int precisionSize=rsmd->getPrecision(1);
  if (precisionSize >= 0) {
    TestsListener::messagesLog()
            << "getPrecision method returns: " << precisionSize << std::endl;
  } else {
    logErr(" getPrecision method returns a negative value");
  }
}
/* throws Exception */
void ResultSetMetadataTest::testGetColumnCount()
{
  logMsg("Calling getColumnCount on ResultSetMetaData");
  int coloumnCount=rsmd->getColumnCount();
  if (coloumnCount >= 0) {
    TestsListener::messagesLog()
            << "getColumnCount method returns: " << coloumnCount << std::endl;
  } else {
    logErr(" getColumnCount method returns a negative value");
  }
}
Пример #12
0
void ColorShader::loadVars(){
	const char* attributeName = "coord3d";
	attributeCoord = glGetAttribLocation(program, attributeName);
	if (attributeCoord == -1) {
		logErr("Could not bind attribute %s\n", attributeName);
		return;
	}
	const char* uniformName;
	uniformName = "mvp";
	uniformMVP = glGetUniformLocation(program, uniformName);
	if (uniformMVP == -1) {
		logErr("Could not bind uniform %s\n", uniformName);
		return;
	}
	uniformName = "color";
	uniformColor = glGetUniformLocation(program, uniformName);
	if (uniformColor == -1) {
		logErr("Could not bind uniform %s\n", uniformName);
		return;
	}
}
Пример #13
0
void statement::selectZero()
{
  logMsg("statement::selectZero() - MySQL_Statement::*");

  stmt.reset(con->createStatement());
  try
  {
    res.reset(stmt->executeQuery("SELECT 1, -1, 0"));
    ASSERT(res->next());
    ASSERT_EQUALS("1", res->getString(1));
    ASSERT_EQUALS("-1", res->getString(2));
    ASSERT_EQUALS("0", res->getString(3));
  }
  catch (sql::SQLException &e)
  {
    logErr(e.what());
    logErr("SQLState: " + std::string(e.getSQLState()));
    fail(e.what(), __FILE__, __LINE__);
  }

}
Пример #14
0
void destroyActivity(Activity *activity) {
	pthread_cancel(activity->thread);
	pthread_join(activity->thread, NULL);

	if (activity->polling != NULL_FILE_DESCRIPTOR) {
		close(activity->polling);
		activity->polling = NULL_FILE_DESCRIPTOR;
	}

	char *messageQueueId = createMessageQueueId(activity->descriptor->name);
	if (mq_close(activity->messageQueue) < 0) {
		logErr("[%s] Error closing activity's message queue for incoming messages: %s", activity->descriptor->name, strerror(errno));
	}
	if (mq_unlink(messageQueueId) < 0) {
		logErr("[%s] Error destroying activity's message queue %s for incoming messages: %d: %s", activity->descriptor->name, messageQueueId, errno, strerror(errno));
	}
	free(messageQueueId);

	free(activity->descriptor);
	free(activity);
}
Пример #15
0
/**
 * Display compilation errors from the OpenGL shader compiler
 */
void Shader::printShaderLog(GLuint object){
	GLint log_length = 0;
	if (glIsShader(object))
		glGetShaderiv(object, GL_INFO_LOG_LENGTH, &log_length);
	else if (glIsProgram(object))
		glGetProgramiv(object, GL_INFO_LOG_LENGTH, &log_length);
	else {
		logErr("printlog: Not a shader or a program\n");
		return;
	}

	char* log = (char*)malloc(log_length);

	if (glIsShader(object))
		glGetShaderInfoLog(object, log_length, NULL, log);
	else if (glIsProgram(object))
		glGetProgramInfoLog(object, log_length, NULL, log);

	logErr("%s", log);
	free(log);
}
Пример #16
0
CallResult libhardware_dl()
{
	if(hw_get_moduleSym)
		return OK;
	void *libhardware = dlopen("libhardware.so", RTLD_LAZY);
	if(!libhardware)
	{
		logErr("libhardware not found");
		return INVALID_PARAMETER;
	}
	hw_get_moduleSym = (hw_get_moduleProto)dlsym(libhardware, "hw_get_module");
	if(!hw_get_moduleSym)
	{
		logErr("missing libhardware functions");
		dlclose(libhardware);
		hw_get_moduleSym = 0;
		return INVALID_PARAMETER;
	}
	logMsg("libhardware symbols loaded");
	return OK;
}
Пример #17
0
int Texture::getNextPowerOf2(int value)
{
	int result = 1;
	for (int i = 1; i < 13; ++i)
	{
		result = result << 1;
		if (result >= value)
			return result;
	}
	logErr("getNextPowerOf2 value is too large, value %i max %i", value, result);
	return result;
}
Пример #18
0
bool libhardware_dl()
{
	if(hw_get_moduleSym)
		return true;
	void *libhardware = dlopen("libhardware.so", RTLD_LAZY);
	if(!libhardware)
	{
		logErr("libhardware not found");
		return false;
	}
	hw_get_moduleSym = (hw_get_moduleProto)dlsym(libhardware, "hw_get_module");
	if(!hw_get_moduleSym)
	{
		logErr("missing libhardware functions");
		dlclose(libhardware);
		hw_get_moduleSym = 0;
		return false;
	}
	logMsg("libhardware symbols loaded");
	return true;
}
Пример #19
0
void template_bug456_class::template_bug456_method()
{
  logMsg("Regression test for #[TODO - add bug numer]");
  try
  {
    /*
     By default the framework will establish a connection in setUp() and connect
     to the configured MySQL Server and select the configured schema.
     No other members will be initialized, however, there are several
     auto-ptr members which you can make use of: this->stmt, this->pstmt, this->res.
     The good thing about the auto-ptr members is that you don't need to care much
     about them. tearDown() will reset them and auto-ptr will ensure proper
     memory management.
     */
    stmt.reset(con->createStatement());

    /* Running a SELECT and storing the returned result set in this->res */
    res.reset(stmt->executeQuery("SELECT 'Hello world!'"));

    /* Move result set cursor to first rowm, fetch result, write result to log  */
    res->next();
    logMsg(res->getString(1));

  }
  catch (sql::SQLException &e)
  {
    /* If anything goes wrong, write some info to the log... */
    logErr(e.what());
    logErr("SQLState: " + std::string(e.getSQLState()));

    /*
     ... and let the test fail. FAIL() is a macro.
     FAIL calls fail(const char* reason, const char* file, int line)
     */
    fail(e.what(), __FILE__, __LINE__);
  }
  /* If all goes fine, there is no need to call PASS() or something.	 */
}
/* throws Exception */
void ResultSetMetadataTest::testIsNullable()
{
  logMsg("Calling isNullable on ResultSetMetaData");
  int coloumnCount=rsmd->isNullable(2);

  if ((coloumnCount == sql::ResultSetMetaData::columnNoNulls)
      || (coloumnCount == sql::ResultSetMetaData::columnNullable)
      || (coloumnCount == sql::ResultSetMetaData::columnNullableUnknown)) {
    TestsListener::messagesLog()
            << "isNullable method returns: " << coloumnCount << std::endl;
  } else {
    logErr(" isNullable method returns a negative value");
  }
}
Пример #21
0
void statement::anonymousSelect()
{
  logMsg("statement::anonymousSelect() - MySQL_Statement::*, MYSQL_Resultset::*");

  stmt.reset(con->createStatement());
  try
  {
    res.reset(stmt->executeQuery("SELECT ' ', NULL"));
    ASSERT(res->next());
    ASSERT_EQUALS(" ", res->getString(1));

    std::string mynull(res->getString(2));
    ASSERT(res->isNull(2));
    ASSERT(res->wasNull());

  }
  catch (sql::SQLException &e)
  {
    logErr(e.what());
    logErr("SQLState: " + std::string(e.getSQLState()));
    fail(e.what(), __FILE__, __LINE__);
  }
}
Пример #22
0
static char *createMessageQueueId(char *activityName) {
	if (!activityName) {
		logErr("["__FILE__"] null pointer at createMessageQueueId(activityName)!");

		return 0;
	}

	size_t idLength = strlen(activityName) + 2;
	char *id = (char *) malloc(idLength);
	memset(id, 0, idLength);
	id[0] = '/';
	strcat(id, activityName);

	return id;
}
Пример #23
0
bool NDLocalXmlString::addKeyValue( const string& keyLine, const string& valLine )
{
	string strKey, strValue;
	if (getMidString( keyLine, "<key>", "</key>", strKey )
		&& getMidString( valLine, "<string>", "</string>", strValue ))
	{
		m_kMapData[ strKey ] = strValue;
		return true;
	}
	else
	{
		logErr( keyLine, valLine );
	}
	return false;
}
Пример #24
0
int IOSFileSystem::openFile(string filePath){
    if(getFileSize(filePath) != -1){
		return 1;//the file exist and is loaded
	}
    
    std::string filename = GlobalData::getInstance()->iOSPath+"/assets/"+filePath;
    FILE* fp;
    fp = fopen(filename.c_str(), "r");
    if(fp == 0){
        logErr("unable to open asset %s", filename.c_str());
        fclose(fp);
        return -1;
    }
    fseek(fp, 0, SEEK_END);
    unsigned long fileSize = ftell(fp);
    rewind(fp);
    
    char* buffer = (char*) malloc(fileSize+1);
    unsigned long readResult = fread(buffer, sizeof(char), fileSize, fp);
    
    if(readResult != fileSize){
        logErr("something bad happens, read result != file size");
        return -1;
    }
    buffer[fileSize] = '\0';
    
    FileStruct* fileStruct = new FileStruct((int)fileSize+1);
	
    memcpy(fileStruct->data, buffer, fileSize+1);
    fileMap.emplace(filePath, fileStruct);
    
    free(buffer);
    fclose(fp);

    return 0;
}
Пример #25
0
static mqd_t createMessageQueue(char *activityName, MessageQueueMode messageQueueMode) {
	char *id = createMessageQueueId(activityName);

	if (mq_unlink(id) < 0) {
		// Ignore any errors
	}

	struct mq_attr attributes = {
			.mq_maxmsg = 10,
			.mq_msgsize = MAX_MESSAGE_LENGTH
	};

	mqd_t queue;
	if (messageQueueMode == messageQueue_nonBlocking) {
		queue = mq_open(id, O_CREAT | O_RDONLY | O_NONBLOCK, S_IRWXU | S_IRWXG, &attributes);
	} else {
		queue = mq_open(id, O_CREAT | O_RDONLY, S_IRWXU | S_IRWXG, &attributes);
	}

	free(id);

	if (queue < 0) {
		logErr("[%s] Error creating message queue %s: %s", activityName, id, strerror(errno));
	}

	return queue;
}

static void * runThread(void *argument) {
	Activity *activity = (Activity *)argument;

	logInfo("[%s] Launching...", activity->descriptor->name);

	activity->descriptor->setUp(activity);
	pthread_cleanup_push(activity->descriptor->tearDown, NULL);

	activity->descriptor->run(activity);

	logInfo("[%s] Terminated.", activity->descriptor->name);

	pthread_cleanup_pop(1);

	return NULL;
}
Пример #26
0
int readConf(char *filename, yg_conf_t *cf, char *buf, int len){
	FILE *fp = fopen(filename, "r");
	if(!fp){
		logErr("cannot open config file: %s", filename);
		return YG_CONF_ERROR;
	}

	int pos = 0;
	char *delim_pos;
	int line_len;
	char *cur_pos = buf+pos;

	while(fgets(cur_pos, len-pos, fp)){
		delim_pos = strstr(cur_pos, DELIM);
		line_len = strlen(cur_pos);

		if(!delim_pos)
			return YG_CONF_ERROR;

		if(cur_pos[strlen(cur_pos) - 1] == '\n'){
			cur_pos[strlen(cur_pos) - 1] = '\0';
		}

		if(strncmp("root", cur_pos, 4) == 0){
			cf->root = delim_pos + 1;
		}

		if(strncmp("port", cur_pos, 4) == 0){
			cf->port = atoi(delim_pos + 1);
		}

		if(strncmp("threadnum", cur_pos, 9) == 0){
			cf->thread_num = atoi(delim_pos + 1);
		}

		cur_pos += line_len;
	}
	fclose(fp);
	return YG_CONF_OK;
}
/* throws Exception */
void ResultSetMetadataTest::testGetColumnDisplaySize()
{
  /*try
  {*/
  logMsg("Calling getColumnDisplaySize on ResultSetMetaData");

  int colDispSize=rsmd->getColumnDisplaySize(2);

  if (colDispSize >= 0) {
    TestsListener::messagesLog()
            << "getColumnDisplaySize method returns: " << colDispSize << std::endl;
  } else {
    logErr(" getColumnDisplaySize method returns a negative value");
  }
  /*}
  catch (sql::DbcException & sqle) {

      FAIL("Call to getColumnDisplaySize is Failed!");
  }*/
  /*catch (std::exception & e) {
      logErr(String( "Unexpected exception " ) + e.what());
      FAIL("Call to getColumnDisplaySize is Failed!");
  }*/
}
Пример #28
0
int waitForEvent2(Activity *activity, ActivityDescriptor *senderDescriptor, void *buffer, unsigned long length, unsigned int timeout) {
	//logInfo("[%s] Going to wait for an event...", activity->descriptor->name);

	//int polling;
	if (activity->polling == NULL_FILE_DESCRIPTOR) {
		if ((/* polling */ activity->polling = epoll_create(1)) < 0) {
			logErr("[%s] Error setting up event waiting: %s", activity->descriptor->name, strerror(errno));

			close(activity->polling);
			activity->polling = NULL_FILE_DESCRIPTOR;

			return -EFAULT;
		}

		struct epoll_event messageQueueEventDescriptor = {
				.events = EPOLLIN,
				.data.fd = activity->messageQueue
		};
		if (epoll_ctl(/* polling */ activity->polling, EPOLL_CTL_ADD, messageQueueEventDescriptor.data.fd, &messageQueueEventDescriptor) < 0) {
			logErr("[%s] Error registering message queue event source: %s", activity->descriptor->name, strerror(errno));

			//close(polling);
			close(activity->polling);
			activity->polling = NULL_FILE_DESCRIPTOR;

			return -EFAULT;
		}
	}
	int polling = activity->polling;

	struct epoll_event firedEvents[1];
	int numberOfFiredEvents;
	numberOfFiredEvents = epoll_wait(polling, firedEvents, 1, timeout);

	//close(polling);

	if (numberOfFiredEvents < 0) {
		logErr("[%s] Error waiting for event: %s", activity->descriptor->name, strerror(errno));

		return -EFAULT;
	} else if (numberOfFiredEvents == 1) {
		//logInfo("[%s] Message received!", activity->descriptor->name);

		unsigned long incomingMessageLength = receiveMessage2(activity, senderDescriptor, buffer, length);

		return incomingMessageLength;
	} else {
		//logInfo("[%s] Timeout occured!", activity->descriptor->name);

		return 0;
	}
}

#ifdef __XENO__
#define mq_receive __real_mq_receive
#endif

int receiveMessage(void *_receiver, char *buffer, unsigned long length) {
	return receiveMessage2(_receiver, NULL, buffer, length);
}

//int receiveMessage2(void *_receiver, char *senderName, char *buffer, unsigned long length) {
int receiveMessage2(void *_receiver, ActivityDescriptor *senderDescriptor, void *buffer, unsigned long length) {
	if (!_receiver) {
		logErr("["__FILE__"] null pointer at receiveMessage(_receiver, ...)!");

		return -EFAULT;
	}

	int result = 0;

	Activity *receiver = (Activity *)_receiver;

	//logInfo("[%s] Going to receive message...", receiver->descriptor->name);

	//char receiveBuffer[MAX_MESSAGE_LENGTH + 1];
	void *receiveBuffer = NULL;
	if (!(receiveBuffer = malloc(MAX_MESSAGE_LENGTH + 1))) {
		logErr("[%s] Error allocating receiver buffer: %s", receiver->descriptor->name, strerror(errno));

		return -EFAULT;
	}

	ssize_t receiveLength;
	if ((receiveLength = mq_receive(receiver->messageQueue, receiveBuffer, /* sizeof(receiveBuffer) */ MAX_MESSAGE_LENGTH + 1, NULL)) < 0) {
		if (receiver->messageQueueMode != messageQueue_nonBlocking) {
			logErr("[%s] Error receiving message: %s", receiver->descriptor->name, strerror(errno));

			result = -EFAULT;

			goto receiveMessage2_out;
		}
	}

	// Copy message length
	unsigned long messageLength;
	memcpy(&messageLength, receiveBuffer, sizeof(unsigned long));

	// Check length of the receive message
	if (messageLength > length) {
		logErr("[%s] Error receiving message: Message longer than expected!", receiver->descriptor->name);

		result = -EFAULT;

		goto receiveMessage2_out;
	}

	// Copy message
	memcpy(buffer, receiveBuffer + sizeof(unsigned long), messageLength);
	result = messageLength;

	//char *_senderName = NULL;
	ActivityDescriptor *_senderDescriptor = NULL;
	if (receiveLength > sizeof(unsigned long) + messageLength) {
		//_senderName = receiveBuffer + length;
		_senderDescriptor = receiveBuffer + sizeof(unsigned long) + messageLength;
	}

	//if (senderName) {
	if (senderDescriptor) {
		// Copy sender name
		//if (_senderName) {
		if (_senderDescriptor) {
			//memcpy(senderName, _senderName, MAX_ACTIVITY_NAME_LENGTH);
			memcpy(senderDescriptor, _senderDescriptor, sizeof(ActivityDescriptor));
		} else {
			//senderName[0] = '\0';
			//memcpy(senderName, UNKNOWN_SENDER_NAME, strlen(UNKNOWN_SENDER_NAME) + 1);
			memcpy(senderDescriptor, UNKNOWN_SENDER_DESCRIPTOR, sizeof(ActivityDescriptor));
		}
	}

	//if (_senderName) {
	if (_senderDescriptor) {
		//logInfo("[%s] Message received from %s (message length: %u)...", receiver->descriptor->name, _senderName, length);
		//logInfo("[%s] Message received from %s (message length: %u)...", receiver->descriptor->name, _senderDescriptor->name, length);
	} else {
		//logInfo("[%s] Message received (message length: %u)...", receiver->descriptor->name, messageLength);
	}

receiveMessage2_out:
	free(receiveBuffer);

	return result;
}

int sendMessage(ActivityDescriptor receiverDescriptor, char *buffer, unsigned long length, MessagePriority priority) {
	return sendMessage2(NULL, receiverDescriptor, length, buffer, priority);
}

int sendMessage2(void *_sender, ActivityDescriptor receiverDescriptor, unsigned long length, void *buffer, MessagePriority priority) {
//	if (!_sender) {
//		logErr("["__FILE__"] null pointer at senderMessage(_sender, ...)!");
//
//		return -EFAULT;
//	}

	if (strcmp(receiverDescriptor.name, "<Null activity>") == 0) {
		return 0;
	}

	int result = 0;

	Activity *sender = (Activity *)_sender;

	unsigned long sendLength;

	if (sender) {
		sendLength = sizeof(ActivityDescriptor) + sizeof(length) + length;
	} else {
		sendLength = sizeof(length) + length;
	}

	if (sendLength > MAX_MESSAGE_LENGTH) {
		logErr("[%s] Error sending message: Message too long!", "<Sender>");

		return -EFAULT;
	}

	char *receiverMessageQueueId = createMessageQueueId(receiverDescriptor.name);

	mqd_t receiverQueue = mq_open(receiverMessageQueueId, O_WRONLY);
	free(receiverMessageQueueId);
	if (receiverQueue < 0) {
		// If there is no corresponding message queue, the receiver is probably not running
		if (errno == ENOENT) {
			logWarn("[%s] %s is not running?!", sender->descriptor->name, receiverDescriptor.name);
		} else {
			if (sender) {
				logErr("[%s] Error opening message queue %s for sending: %s", sender->descriptor->name, receiverDescriptor.name, strerror(errno));
			} else {
				logErr("[%s] Error opening message queue %s for sending: %s", "<Sender>", receiverDescriptor.name, strerror(errno));
			}
		}

		return -EFAULT;
	}

	if (sender) {
		//logInfo("[%s] Sending message to %s (message length: %u)...", sender->descriptor->name, receiverDescriptor.name, length);
	} else {
		//logInfo("[%s] Sending message to %s (message length: %u)...", "<Sender>", receiverDescriptor.name, length);
	}

	void *sendBuffer = 0;
	//if (!(sendBuffer = malloc(MAX_ACTIVITY_NAME_LENGTH + length))) {
	if (!(sendBuffer = malloc(sendLength))) {
		logErr("[%s] Error allocating send buffer: %s", sender->descriptor->name, strerror(errno));

		result = -EFAULT;

		goto sendMessage2_out;
	}

	// Copy message length
	memcpy(sendBuffer, &length, sizeof(length));
	// Copy message
	memcpy(sendBuffer + sizeof(length), buffer, length);

	if (sender) {
		// Copy sender name
		//memcpy(sendBuffer + length, sender->descriptor->name, MAX_ACTIVITY_NAME_LENGTH);
		// copy sender descriptor
		memcpy(sendBuffer + sizeof(length) + length, sender->descriptor, sizeof(ActivityDescriptor));
		//if (mq_send(receiverQueue, sendBuffer, MAX_ACTIVITY_NAME_LENGTH + length, priority) < 0) {
		if (mq_send(receiverQueue, sendBuffer, sendLength, priority) < 0) {
			logErr("[%s] Error sending message: %s", sender->descriptor->name, strerror(errno));

			result = -EFAULT;

			goto sendMessage2_out;
		}
	} else {
		if (mq_send(receiverQueue, sendBuffer, sendLength, priority) < 0) {
			logErr("[%s] Error sending message: %s", "<Sender>", strerror(errno));

			result = -EFAULT;

			goto sendMessage2_out;
		}
	}

sendMessage2_out:
	free(sendBuffer);

	mq_close(receiverQueue);

	return result;
}
Пример #29
0
void
virgo__lua_debug_stackdump(lua_State *L, const char *msg)
{
  int i;
  int top = lua_gettop(L);
  virgo_t* v = virgo__lua_context(L);

  logErr(v, "Lua Stack Dump: %s starting at %d", msg, top);

  for (i = 1; i <= top; i++) {
    int t = lua_type(L, i);
    switch (t) {
      case LUA_TSTRING:{
        logErr(v, "%d:  '%s'", i, lua_tostring(L, i));
        break;
      }
      case LUA_TUSERDATA:{
        logErr(v, "%d:  <userdata %p>", i, lua_topointer(L, i));
        break;
      }
      case LUA_TLIGHTUSERDATA:{
        logErr(v, "%d:  <lightuserdata %p>", i, lua_topointer(L, i));
        break;
      }
      case LUA_TNIL:{
        logErr(v, "%d:  NIL", i);
        break;
      }
      case LUA_TNONE:{
        logErr(v, "%d:  None", i);
        break;
      }
      case LUA_TBOOLEAN:{
        logErr(v, "%d:  %s", i, lua_toboolean(L, i) ? "true" : "false");
        break;
      }
      case LUA_TNUMBER:{
        logErr(v, "%d:  %g", i, lua_tonumber(L, i));
        break;
      }
      case LUA_TTABLE:{
        logErr(v, "%d:  <table %p>", i, lua_topointer(L, i));
        break;
      }
      case LUA_TTHREAD:{
        logErr(v, "%d:  <thread %p>", i, lua_topointer(L, i));
        break;
      }
      case LUA_TFUNCTION:{
        logErr(v, "%d:  <function %p>", i, lua_topointer(L, i));
        break;
      }
      default:{
        logErr(v, "%d:  unknown: [%s]", i, lua_typename(L, i));
        break;
      }
    }
  }
}
void DirectionalLightNormalMapShader::loadVars(){
	const char* attributeName = "Vertex";
	attributeCoord = glGetAttribLocation(program, attributeName);
	if (attributeCoord == -1) {
		logErr("Could not bind attribute %s\n", attributeName);
		return;
	}
	attributeName = "Normal";
	attributeNormal = glGetAttribLocation(program, attributeName);
	if (attributeNormal == -1) {
		logErr("Could not bind attribute %s\n", attributeName);
		return;
	}
	attributeName = "Tangent";
	attributeTangent = glGetAttribLocation(program, attributeName);
	if (attributeTangent == -1) {
		logErr("Could not bind attribute %s\n", attributeName);
		return;
	}
	attributeName = "Bitangent";
	attributeBitangent = glGetAttribLocation(program, attributeName);
	if (attributeBitangent == -1) {
		logErr("Could not bind attribute %s\n", attributeName);
		return;
	}
	attributeName = "Texcoord";
	attributeTexture = glGetAttribLocation(program, attributeName);
	if (attributeTexture == -1) {
		logErr("Could not bind attribute %s\n", attributeName);
		return;
	}

	const char* uniformName;
	uniformName = "ProjectionMatrix";
	uniformProjectionMatrix = glGetUniformLocation(program, uniformName);
	if (uniformProjectionMatrix == -1) {
		logErr("Could not bind uniform %s\n", uniformName);
		return;
	}
	uniformName = "ViewMatrix";
	uniformViewMatrix = glGetUniformLocation(program, uniformName);
	if (uniformViewMatrix == -1) {
		logErr("Could not bind uniform %s\n", uniformName);
	}

	uniformName = "ModelMatrix";
	uniformModelMatrix = glGetUniformLocation(program, uniformName);
	if (uniformModelMatrix == -1) {
		logErr("Could not bind uniform %s\n", uniformName);
	}

	uniformName = "LightPosition";
	uniformLightPosition = glGetUniformLocation(program, uniformName);
	if (uniformLightPosition == -1) {
		logErr("Could not bind uniform %s\n", uniformName);
	}
/*	uniformName = "LightColor";
	uniformLightAmbient = glGetUniformLocation(program, uniformName);
	if (uniformLightAmbient == -1){
		logErr("Could not bind uniform %s\n", uniformName);
	}*/
	uniformName = "texture";
	uniformTexture = glGetUniformLocation(program, uniformName);
	if (uniformTexture == -1) {
		logErr("Could not bind uniform %s\n", uniformName);
	}
/*	uniformName = "normalMapTexture";
	uniformNormalTexture = glGetUniformLocation(program, uniformName);
	if (uniformNormalTexture == -1) {
		logErr("Could not bind uniform %s\n", uniformName);
	}*/
}