/**
 * \brief The Hard Fault Handler
 *
 */
void Hard_Fault_Handler(uint32_t stack[])
{
	static char msg[80];
	printErrorMsg("Hard Fault!!!\n");
	sprintf(msg, "SCB->HFSR = 0x%08x\n", SCB->HFSR);
	printErrorMsg(msg);

	if ((SCB->HFSR & (1 << 30)) != 0) {
		printErrorMsg("Forced Hard Fault\n");
		sprintf(msg, "SCB->CFSR = 0x%08x\n", SCB->CFSR);
		printErrorMsg(msg);

		if ((SCB->CFSR & 0xFFFF0000) != 0) {
			printUsageErrorMsg(SCB->CFSR);
		}

		if ((SCB->CFSR & 0xFF00) != 0) {
			printBusFaultErrorMsg(SCB->CFSR);
		}

		if ((SCB->CFSR & 0xFF) != 0) {
			printMemoryManagementErrorMsg(SCB->CFSR);
		}
	}

	DumpStack(stack);
	HardFaultHandlerUser(stack);

#if defined(__ICCARM__)
	__asm volatile("BKPT #01");
#endif

	while (1) {};
}
static int bleedSocket(SOCKET p_socket){
	DWORD l_err =0;
	DWORD l_count =0;
	DWORD l_err2;
	do {
		l_err = recv(p_socket,recBuffer+l_count,SIZE_REC_BUFFER-l_count,0);
		l_err2 = WSAGetLastError();
		if (l_err == 0){
			break;
		}
		if (l_err == SOCKET_ERROR || l_err2 == WSAEWOULDBLOCK){
			break;//finished
		}
		l_count +=l_err;
	} while (1);
	if (l_err ==0 ){//
		printErrorMsg(_T("recv(), client abruptly closed socket"), l_err2,1,0);
		closesocket(p_socket);
		return 0;
	}
	if (l_err2 != WSAEWOULDBLOCK){
		printErrorMsg(_T("recv(), error"), l_err2,1,1);
		closesocket(p_socket);
		return SOCKET_ERROR;
	}
	return l_count;
}
/**
 * \brief Dump Stack, printing all registers ARM core pushes on stack on hard fault exception
 */
static void DumpStack(uint32_t stack[])
{
	static char msg[80];
	int code_address_error=0;
	sprintf(msg, "\nr0  = 0x%08x\n", stack[r0]);
	printErrorMsg(msg);
	sprintf(msg, "r1  = 0x%08x\n", stack[r1]);
	printErrorMsg(msg);
	sprintf(msg, "r2  = 0x%08x\n", stack[r2]);
	printErrorMsg(msg);
	sprintf(msg, "r3  = 0x%08x\n", stack[r3]);
	printErrorMsg(msg);
	sprintf(msg, "r12 = 0x%08x\n", stack[r12]);
	printErrorMsg(msg);
	sprintf(msg, "lr  = 0x%08x\n", stack[lr]);
	printErrorMsg(msg);
	sprintf(msg, "pc  = 0x%08x\n", stack[pc]);
	printErrorMsg(msg);
	sprintf(msg, "psr = 0x%08x\n", stack[psr]);
	printErrorMsg(msg);

	if (stack[pc] == 0) {
		code_address_error = stack[lr];
	} else {
		code_address_error = stack[pc];
	}

	sprintf(msg, "\n--\t--\t--\nHard fault occurred at address 0x%08x.\nFind high-level ", code_address_error);
	printErrorMsg(msg);
	sprintf(msg, "function with\nDisassembly window or Map file\n--\t--\t--\n");
	printErrorMsg(msg);
}
void checkParameterPassing(Parameter* formalParameter, AST_NODE* actualParameter)
{
  while (formalParameter && actualParameter) {
    if (actualParameter->nodeType == EXPR_NODE) {
      processExprNode(actualParameter);
      if (formalParameter->type->kind == ARRAY_TYPE_DESCRIPTOR) {
        printErrorMsg(actualParameter, PASS_SCALAR_TO_ARRAY);
      }
    } else if (actualParameter->nodeType == CONST_VALUE_NODE) {
    } else if (actualParameter->nodeType == STMT_NODE) {
      checkFunctionCall(actualParameter);
      SymbolTableEntry *entry = retrieveSymbol(actualParameter->semantic_value.identifierSemanticValue.identifierName);
      if (entry != NULL) {
        if (formalParameter->type->kind == ARRAY_TYPE_DESCRIPTOR ) {
          printErrorMsg(actualParameter, PASS_SCALAR_TO_ARRAY);
        } else {
          if (getDataType(formalParameter->type) != getDataType(entry->attribute->attr.typeDescriptor)) {
            printErrorMsgSpecial(actualParameter, formalParameter->parameterName, PARAMETER_TYPE_UNMATCH);
          }
        }
      }
    } else if (actualParameter->nodeType == IDENTIFIER_NODE) {
      checkParameterIdentifier(formalParameter, actualParameter);
    }

    formalParameter = formalParameter->next;
    actualParameter = actualParameter->rightSibling;
  }
}
void declareIdList(AST_NODE* declarationNode, SymbolAttributeKind isVariableOrTypeAttribute, int ignoreArrayFirstDimSize)
{
  AST_NODE *idNode = declarationNode->rightSibling;
  while (idNode) {
    if (detectSymbol(idNode->semantic_value.identifierSemanticValue.identifierName)) {
      //symbol name redefine
      printErrorMsg(idNode, SYMBOL_REDECLARE);
    } else {
      SymbolAttribute* varAttr = (SymbolAttribute*)malloc(sizeof(SymbolAttribute));
      TypeDescriptor* typeDesc = (TypeDescriptor*)malloc(sizeof(TypeDescriptor));
      varAttr->attributeKind = VARIABLE_ATTRIBUTE;
      varAttr->attr.typeDescriptor = typeDesc;
      typeDesc->properties.dataType 
        = retrieveType(declarationNode->semantic_value.identifierSemanticValue.identifierName);

      if (typeDesc->properties.dataType == VOID_TYPE) {
        printErrorMsg(idNode, VOID_VARIABLE);
      } else {
        //printf("get variable %s\n", idNode->semantic_value.identifierSemanticValue.identifierName);
        //printf("type %d\n", retrieveType(declarationNode->semantic_value.identifierSemanticValue.identifierName));

        processDeclDimList(idNode, typeDesc, False);

        enterSymbol(idNode->semantic_value.identifierSemanticValue.identifierName, varAttr);
      }
    }

    idNode = idNode->rightSibling;
  }
}
Exemple #6
0
void printUsageErrorMsg(uint32_t CFSRValue)
{
   printErrorMsg("Usage fault: ");
   CFSRValue >>= 16;                  // right shift to lsb
   if((CFSRValue & (1 << 9)) != 0) {
      printErrorMsg("Divide by zero\n");
   }
}
/* This function was made in respect to, if I want to receive a file,
 * either from the server or client I can use this function */
void receiveFile(char *buff, int descriptor, char *filename) {
  // Determine size of the incoming file
  uint32_t fileSize;
  int totalNumBytes = sizeof(uint32_t);
  int numBytesRcvd = 0;

  while (numBytesRcvd < totalNumBytes) {
    int result = recv(descriptor, &fileSize, totalNumBytes - numBytesRcvd, 0);
    if (result < 0) {
      printErrorMsg("recv() failed for determining file size");
    }

    numBytesRcvd += result;
  }

  if (fileSize == 0) {
    printf("File `%s` was not found.\n", filename);
    return;
  }
  else {
    printf("Incoming file with a size of %u bytes.\n", fileSize);
  }

  FILE *file = fopen(filename, "ab");
  if (file == NULL) {
    printErrorMsg("fopen() failed in receiveFile function");
  }
  printf("Created new file `%s` successfully.\n", filename);

  totalNumBytes = fileSize;
  numBytesRcvd = 0;
  bzero(buff, MAX_BUFF_LEN);

  while (numBytesRcvd < totalNumBytes) {
    int recvResult = recv(descriptor, buff, MAX_BUFF_LEN, 0);
    if (recvResult < 0) {
      printErrorMsg("recv() failed");
    }

    int writeResult = fwrite(buff, sizeof(char), recvResult, file);
    if (writeResult < recvResult) {
      printErrorMsg("fwrite() failed to write the bytes to disk");
    }

    bzero(buff, MAX_BUFF_LEN);
    numBytesRcvd += writeResult;
    printf("%d out of %d bytes written to disk.\n", numBytesRcvd, totalNumBytes);
  }

  fclose(file);

  if (totalNumBytes == numBytesRcvd) {
    printf("Finished downloading %s!\n", filename);
  }
  else {
    printf("It seems like something went wrong while downloading %s.\n", filename);
  }
}
Exemple #8
0
// Try to gracefully shut down a connection using a given socket
void shutdownConnection(struct socketDescriptor * sd) {

   sd->connected = FALSE;
   
   if (sd->socket==INVALID_SOCKET)
      return;
      
   SOCKET socket = sd->socket;
   sd->socket=INVALID_SOCKET;
   
   SOCKADDR sa;
   int salen=sizeof(sa);
   if (getpeername(socket, &sa, &salen) == SOCKET_ERROR) {   
      // calling to shutdown an unconnected socket is normal
      if (WSAGetLastError() != WSAENOTCONN)
         printErrorMsg("shutdownConnection getpeername");
   }         

   printq("Shutdown connection host %s socket %d\n", sd->host, socket);
   
   // Disallow any further data sends.  This will tell the other side
   // that we want to go away now.  If we skip this step, we don't
   // shut the connection down nicely.
   if (shutdown(socket, SD_SEND) == SOCKET_ERROR) {
      printErrorMsg("shutdownConnection shutdown");
   }

   // Receive any extra data still sitting on the socket.  After all
   // data is received, this call will block until the remote host
   // acknowledges the TCP control packet sent by the shutdown above.
   // Then we'll get a 0 back from recv, signalling that the remote
   // host has closed its side of the connection.
   char acReadBuffer[KBUFFERSIZE];
   while (1) {
      int afterBytes = recv(socket, acReadBuffer, KBUFFERSIZE, 0);
      if (afterBytes == SOCKET_ERROR) {
         if (WSAGetLastError() != WSAECONNRESET) {
          // ignore a recv error if the remote host forcibly closed the connection
            printErrorMsg("shutdownConnection recv");  
         }
         closesocket(socket);   
         return;
      }
      else if (afterBytes);
         // read and ignore extraneous data
      else
         break;
   }

   // Close the socket.
   if (closesocket(socket) == SOCKET_ERROR)
      printErrorMsg("shutdownConnection close socket");

   return;
}
static int prepareListenSocket(){
	sockaddr_in service;
	u_short port = 27015;
	char* ip;
	DWORD l_err;

	gsockListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (gsockListen == INVALID_SOCKET) {  
		printErrorMsg(_T("socket() failed with:"), WSAGetLastError(),1,1);
		
		return FALSE;
	}


	service.sin_family = AF_INET;
	service.sin_port = htons(port);
	hostent* thisHost;
	thisHost = gethostbyname("");
	if (thisHost == NULL){
		printErrorMsg(_T("gethostbyname() failed with:"), WSAGetLastError(),1,1);
		
		return FALSE;
	}
	ip = inet_ntoa (*(struct in_addr *)*thisHost->h_addr_list);
	service.sin_addr.s_addr = inet_addr(ip);



	l_err = bind(gsockListen, (SOCKADDR *) &service, sizeof(SOCKADDR));
	if (l_err == SOCKET_ERROR) {  
		printErrorMsg(_T("bind() failed with:"), WSAGetLastError(),1,1);
		
		return 0;
	}
	//enable non-blocking mode
	u_long l_arg =1;
	ioctlsocket(gsockListen, FIONBIO, &l_arg);

	l_err = listen(gsockListen, 1);

	if (l_err == SOCKET_ERROR) {  
		printf("listen() failed with error: %d\n", WSAGetLastError() );
		destroyNetwork();
		return FALSE;
	}

	l_err = WSAEventSelect(gsockListen,events[0],FD_ACCEPT);
	if (l_err == SOCKET_ERROR) {  
		printf("WSAEventSelect() ,FD_ACCEPT, failed with error: %d\n", WSAGetLastError() );
		destroyNetwork();
		return FALSE;
	}
	return TRUE;

}
void BuildScriptSymbols::caseArrayDecl(ASTArrayDecl &host, void *param)
{
    pair<Scope *, SymbolTable *> *p = (pair<Scope *, SymbolTable *> *)param;
    string name = host.getName();
    int type;
    ExtractType temp;
    host.getType()->execute(temp, &type);
    
    if(type == ScriptParser::TYPE_VOID)
    {
        failure = true;
        printErrorMsg(&host, VOIDARR, name);
    }
    
    if(type == ScriptParser::TYPE_FFC || type == ScriptParser::TYPE_ITEM
            || type == ScriptParser::TYPE_ITEMCLASS || type == ScriptParser::TYPE_NPC
            || type == ScriptParser::TYPE_LWPN || type == ScriptParser::TYPE_EWPN)
    {
        failure = true;
        printErrorMsg(&host, REFARR, name);
    }
    
    //var is always visible
    int id = p->first->getVarSymbols().addVariable(name, type);
    
    if(id == -1)
    {
        failure = true;
        printErrorMsg(&host, ARRREDEF, name);
        return;
    }
    
    p->second->putAST(&host, id);
    p->second->putVar(id, type);
    
    if(this->deprecateGlobals)
    {
        printErrorMsg(&host, DEPRECATEDGLOBAL, name);
    }
    
    if(host.isRegister())
        ((ASTExpr *) host.getSize())->execute(*this, param);
        
    if(host.getList() != NULL)
    {
        for(list<ASTExpr *>::iterator it = host.getList()->getList().begin(); it != host.getList()->getList().end(); it++)
        {
            (*it)->execute(*this,param);
        }
    }
}
/**
 * \brief Print Bus Fault Errors
 */
static void printBusFaultErrorMsg(uint32_t CFSRValue)
{
	char str[200];
	printErrorMsg("Bus fault: ");
	CFSRValue = (CFSRValue & 0x0000FF00);
	sprintf(str, "%.2X\n", CFSRValue);
	printErrorMsg(str);

	if ((CFSRValue & SCB_CFSR_IBUSERR) != 0) {
		printErrorMsg("Instruction bus error\n");
	}

	if ((CFSRValue & SCB_CFSR_PRECISERR) != 0) {
		printErrorMsg("Precise data bus error\n");
	}

	if ((CFSRValue & SCB_CFSR_IMPRECISERR) != 0) {
		printErrorMsg("Imprecise data bus error\n");
	}

	if ((CFSRValue & SCB_CFSR_UNSTKERR) != 0) {
		printErrorMsg("Unstacking error\n");
	}

	if ((CFSRValue & SCB_CFSR_STKERR) != 0) {
		printErrorMsg("Stacking error\n");
	}

	if ((CFSRValue & SCB_CFSR_BFARVALID) != 0) {
		sprintf(str, "Bus Fault Address Register address valid flag\nBFAR value = 0x%.8X\n", SCB->BFAR);
		printErrorMsg(str);
	}
}
void processVariableLValue(AST_NODE* idNode)
{
  SymbolTableEntry *entry = retrieveSymbol(idNode->semantic_value.identifierSemanticValue.identifierName);
  DATA_TYPE type = retrieveType(idNode->semantic_value.identifierSemanticValue.identifierName);
  if (entry == NULL) {
    printErrorMsg(idNode, SYMBOL_UNDECLARED);
  } else if (entry->attribute->attributeKind == FUNCTION_SIGNATURE) {
    printErrorMsg(idNode, IS_FUNCTION_NOT_VARIABLE);
  } else if (entry->attribute->attributeKind == TYPE_ATTRIBUTE) {
    printErrorMsg(idNode, IS_TYPE_NOT_VARIABLE);
  } else if (type == VOID_TYPE) {
    printErrorMsg(idNode, NOT_ASSIGNABLE);
  }
}
void reOpenFiles(){
	DWORD l_pos;//first we check if HANDLE is valid
	DWORD l_err;
	l_pos = SetFilePointer(logFileHandle,0,0,FILE_CURRENT);
	if (l_pos ==INVALID_SET_FILE_POINTER) {
		//--attempt reopen faileL 
		closeLogFile();
		logFileHandle = CreateFile(
			logFile/*lpFileName*/,
			FILE_APPEND_DATA/*dwDesiredAccess*/,
			FILE_SHARE_READ/*dwShareMode*/,
			NULL /*lpSecurityAttributes*/,
			OPEN_ALWAYS/*dwCreationDisposition*/,
			FILE_ATTRIBUTE_NORMAL|FILE_FLAG_SEQUENTIAL_SCAN/*dwFlagsAndAttributes*/,
			NULL/*hTemplateFile*/);
		if (logFileHandle == INVALID_HANDLE_VALUE){
			printErrorMsg(_T("Could not open or create logfile, reason"),GetLastError(),0,1);
			destroyConfig();
			exit(1);
		}
	}
	//we have a valid handle here for logfile
	trace("");
	trace("Logfile opened");
	l_pos = SetFilePointer(configFileHandle,0,0,FILE_CURRENT);
	if (l_pos ==INVALID_SET_FILE_POINTER) {
		//--attempt reopen faileL 
		closeConfigFile();//do this anyway
		configFileHandle = CreateFile(
			configFile/*lpFileName*/,
			GENERIC_WRITE|GENERIC_READ/*dwDesiredAccess*/,
			FILE_SHARE_READ/*dwShareMode*/,
			NULL /*lpSecurityAttributes*/,
			OPEN_ALWAYS/*dwCreationDisposition*/,
			FILE_ATTRIBUTE_NORMAL/*dwFlagsAndAttributes*/,
			NULL/*hTemplateFile*/);

		if (configFileHandle == INVALID_HANDLE_VALUE){
			trace("ERR:creating or opening the configuration file refused");
			traceErrorMsg(configFile,_tcslen(configFile)*sizeof(TCHAR));
			trace("ERR:...Check disk space or directory/file permissions");
			printErrorMsg(_T("Could not open or create configfile, system error"),GetLastError(),1,1);
			destroyConfig();
			exit(1);
		}
	}
	trace("Configuration file opened.");
	traceErrorMsg(configFile,_tcslen(configFile)*sizeof(TCHAR));
}
Exemple #14
0
CFDateRef GetDateFieldFromCertificate(SecCertificateRef certificate, CFTypeRef oid)
{
  const void *keys[] = { oid };
  CFDictionaryRef dict = NULL;
  CFErrorRef error;
  CFDateRef date = NULL;

  CFArrayRef keySelection = CFArrayCreate(NULL, keys , sizeof(keys)/sizeof(keys[0]), &kCFTypeArrayCallBacks);
  dict = SecCertificateCopyValues(certificate, keySelection, &error);
  if (dict == NULL)
    {
      printErrorMsg("GetDateFieldFromCertificate: SecCertificateCopyValues", error);
      goto release_ks;
    }
  CFDictionaryRef vals = dict ? CFDictionaryGetValue(dict, oid) : NULL;
  CFNumberRef vals2 = vals ? CFDictionaryGetValue(vals, kSecPropertyKeyValue) : NULL;
  if (vals2 == NULL)
    goto release_dict;

  CFAbsoluteTime validityNotBefore;
  if (CFNumberGetValue(vals2, kCFNumberDoubleType, &validityNotBefore))
    date = CFDateCreate(kCFAllocatorDefault,validityNotBefore);

release_dict:
  CFRelease(dict);
release_ks:
  CFRelease(keySelection);
  return date;
}
/* if a theres an incoming connection accept the incoming connection */
void acceptIncomingConnection(int *listen_socket, int *accept_socket) {
  struct sockaddr address;
  socklen_t address_len = (socklen_t) sizeof(address);
  if ((*accept_socket = accept(*listen_socket, &address, &address_len)) < 0) {
    printErrorMsg("Error accepting connection\n");
  }
}
/* We can as well recieve message from the server or the client back and forth 
 * this function was basically made to handle commands like "ls", "mkdir" etc */
int receiveMessage(char *buff, int descriptor) {
  bzero(buff, MAX_BUFF_LEN);
  int numBytesRcvd = 0;
  while (1) {
    int result = recv(descriptor, buff, MAX_BUFF_LEN - numBytesRcvd, 0);
    if (result == 0 || (result < 0 && errno == ECONNRESET)) {
      printf("Connection terminated by client.\n");
      return -1;
    }
    else if (result < 0) {
      printErrorMsg("recv() failed\n");
    }

    printf("We just recevied %d bytes", result);
    numBytesRcvd += result;
    if (strchr(buff, '\0') != NULL) { // The null terminator has been read
      break;
    }
  }

  #if NETWORKING_DEBUG
  printf("Received a %d-bytes message: %s\n", numBytesRcvd, buff);
  #endif

  return numBytesRcvd;
}
void checkIDNode(AST_NODE *idNode){
  SymbolTableEntry *entry = retrieveSymbol(idNode->semantic_value.identifierSemanticValue.identifierName);
  idNode->dataType = retrieveType(idNode->semantic_value.identifierSemanticValue.identifierName);
  if (entry == NULL) {
    printErrorMsg(idNode, SYMBOL_UNDECLARED);
  } else if (entry->attribute->attributeKind == FUNCTION_SIGNATURE) {
    printErrorMsg(idNode, IS_FUNCTION_NOT_VARIABLE);
  } else if (entry->attribute->attributeKind == TYPE_ATTRIBUTE) {
    printErrorMsg(idNode, IS_TYPE_NOT_VARIABLE);
  } else if (idNode->semantic_value.identifierSemanticValue.kind == ARRAY_ID
      && entry->attribute->attr.typeDescriptor->kind == SCALAR_TYPE_DESCRIPTOR) {
    printErrorMsg(idNode, NOT_ARRAY);
  } else if (idNode->semantic_value.identifierSemanticValue.kind == ARRAY_ID) {
    checkSubscript(idNode);
  }
}
void BuildFunctionSymbols::caseExprArray(ASTExprArray &host, void *param)
{
    BFSParam *p = (BFSParam *)param;
    string name = host.getName();
    string nspace = host.getNamespace();
    int id = p->scope->getVarInScope(nspace, name);
    
    if(id == -1 && !(nspace == "" && p->table->isConstant(name)))
    {
        string fullname;
        
        if(nspace == "")
            fullname=name;
        else
            fullname = nspace + "." + name;
            
        printErrorMsg(&host, VARUNDECLARED, fullname);
        failure = true;
        return;
    }
    
    p->table->putAST(&host, id);
    
    if(host.getIndex())
        host.getIndex()->execute(*this,param);
}
Exemple #19
0
// Given a dotted-quad IP address, perform a reverse DNS lookup to return
// the associated hostname.  If we fail, return the given ip string 
char * lookupName(const char * ip, char * sz, int szSize) {
   struct sockaddr_in sa;
   char * dotLan;
   char hostname[NI_MAXHOST];
   char servInfo[NI_MAXSERV];

   sa.sin_family = AF_INET;
   sa.sin_addr.s_addr = inet_addr(ip);
   sa.sin_port = htons(2000);

   int retval = getnameinfo((struct sockaddr *) &sa,                         
                            sizeof (struct sockaddr),                           
                            hostname, NI_MAXHOST, 
                            servInfo, NI_MAXSERV, 
                            NI_NUMERICSERV);

   if (retval) {
      printErrorMsg("lookupName");
      strncpy(sz, ip, szSize);
   } else {   
      if (dotLan=strstr(hostname, ".lan"))
         *dotLan = '\0';   // drop .lan on locally resolved hostnames 
      strncpy(sz, hostname, szSize);
   }
      
   return sz;
}
void BuildFunctionSymbols::caseArrayDecl(ASTArrayDecl &host, void *param)
{
    BFSParam *p = (BFSParam *)param;
    string name = host.getName();
    int type;
    ExtractType temp;
    host.getType()->execute(temp, &type);
    int id = p->scope->getVarSymbols().addVariable(name, type);
    
    if(id == -1)
    {
        printErrorMsg(&host, ARRREDEF, name);
        failure = true;
        return;
    }
    
    p->table->putAST(&host, id);
    p->table->putVar(id, type);
    
    if(host.isRegister())
        ((ASTExpr *) host.getSize())->execute(*this, param);
        
    if(host.getList() != NULL)
    {
        for(list<ASTExpr *>::iterator it = host.getList()->getList().begin(); it != host.getList()->getList().end(); it++)
        {
            (*it)->execute(*this,param);
        }
    }
}
void cacheConfigFile(){
	DWORD l_pos; //first we check if HANDLE is valid
	DWORD l_err;
	BOOL l_rc;
	DWORD l_actual_read;
	char* cText;
	//
	char* key;
	char *value, *value2;
	char* line;
	char _line[1024];
	//
	propCache.count=0;
	comPortList.count=0;
	int i;

	for (i=0;i<CACHE_lIST_SIZE;i++){
		memset(propCache.hash[i].key,0,HASH_KEY_SIZE);
		memset(propCache.hash[i].value,0,HASH_VALUE_SIZE);

	}
	for (i=0;i<COM_LIST_SIZE;i++){
		memset((comPortList.list+i),0,sizeof(COMELEMENT));
	}
	trace("Function cacheConfigFile");
	l_pos = SetFilePointer(configFileHandle, 0, 0, FILE_END);
	LPVOID l_file= LocalAlloc(LPTR, l_pos+1);
	cText = (char *)LocalAlloc(LPTR, l_pos+1);
	SetFilePointer(configFileHandle, 0, 0, FILE_BEGIN);
	l_rc = ReadFile(configFileHandle, l_file, l_pos, &l_actual_read, NULL);
	if (l_rc ==0){
		l_err = GetLastError();
		printErrorMsg(_T("Could not read the config file, reason"),l_err,1,1);
		destroyConfig();
		exit(1);
	}
	*((char*)l_file+l_pos)=0;
	//whe are done, close file
	closeConfigFile();
	convertToANSI((TCHAR *)l_file,l_pos+1,cText,l_pos+1);
	LocalFree(l_file);
	//we have converted everything to ansi so!
	line=0;
	while ((line = fetchNextLine(cText,line,l_pos+1)) != NULL){
		//copy line
		strcpy(_line,line);
		if (isCommentOrEmptyLine(_line)){
			continue;
		}
		splitKeyValue(_line,'=',&key,&value);
		if (stricmp(key,PROP_PORTNAME)==0){
			trace("property PROP_PORTNAME found");
			insertOrReplacePropertyByKey(key, value);
			strcpy(_line,line);
			trace(trim(strupr(_line)));
			continue;
		}

	}
}
static void Ltrace(char* p_msg, int p_force){
	BOOL bRc;
	DWORD l_err;
	char cLine[4096];
	DWORD dwBytesWritten;
	struct _SYSTEMTIME l_systemTime;
	//get datetime
	GetLocalTime(&l_systemTime);
	sprintf(cLine,
		"[%02d/%02d/%04d %02d:%02d:%02d] %s\r\n",
		l_systemTime.wDay,
		l_systemTime.wMonth,
		l_systemTime.wYear,
		l_systemTime.wHour,
		l_systemTime.wMinute,
		l_systemTime.wSecond,
		p_msg);

	bRc =WriteFile(logFileHandle,cLine,strlen(cLine),&dwBytesWritten,NULL);

	if  (bRc == false && p_force ==1){
		l_err = GetLastError();
		printErrorMsg(_T("Writing to logfile failed, reason"),l_err,0,1);
		destroyConfig();
		exit(1);
	}
	FlushFileBuffers(logFileHandle);
}
/* Function to initialize my client attributes */
void createClientAddrStruct(struct sockaddr_in *address, char *ip_address, int port) {
  bzero(address, sizeof(*address));
  address->sin_port = htons(port);
  address->sin_family = AF_INET;
  if (inet_pton(address->sin_family, ip_address, &(address->sin_addr.s_addr)) != 1) {
    printErrorMsg("Can't parse IP address or system error occurred\n");
  }
}
/* After accepting incoming connection connect the client to the server */
void connectToServer(char *ip_address, int port, int *descriptor) {
  struct sockaddr_in address;
  createClientAddrStruct(&address, ip_address, port);
  createSocket(descriptor);
  if (connect(*descriptor, (struct sockaddr *) &address, sizeof(address)) < 0) {
    printErrorMsg("Can't initiate connection on socket\n");
  }
}
void checkWriteFunction(AST_NODE* functionCallNode)
{
  AST_NODE* exprNode = functionCallNode->child->rightSibling;
  AST_NODE* paramNode = NULL;
  if (exprNode->nodeType == NUL_NODE) {
    printErrorMsg(functionCallNode->child, TOO_FEW_ARGUMENTS);
  } else {
    paramNode = exprNode->child;
    if (paramNode->rightSibling) {
      printErrorMsg(functionCallNode->child, TOO_MANY_ARGUMENTS);
    } else if (paramNode->nodeType == CONST_VALUE_NODE) {
      if (paramNode->semantic_value.const1->const_type != STRINGC) {
        printErrorMsg(functionCallNode->child, PARAMETER_TYPE_UNMATCH);
      }
    }
  }
}
Exemple #26
0
// receive and process agent/server notifications
DWORD rxClientThread(LPVOID arg) {  
   char buffer[1024], msg[2048], * delim;
   int nBytes;
   struct socketDescriptor * sd = (struct socketDescriptor *) arg;
   SOCKET socket=sd->socket;
   msg[0]='\0';
   
   addSocketDescriptorToClientList(sd);
   
   while(!sd->exit) {
      if (!sd->connected) {
         if (establishConnection(sd))
            socket=sd->socket;
         else 
            Sleep(10000);
      } else {  
      
         nBytes=recv(sd->socket, buffer, sizeof(buffer-1), 0);
         
         if (nBytes==0) {
            // graceful close
            shutdownConnection(sd);
         }   
         else if(nBytes==SOCKET_ERROR) {
            // forceful close
            if (WSAGetLastError()!=WSAECONNABORTED) {
               // an aborted connection error is normal on a half closed connection
               printErrorMsg("rxClientThread");
            }   
            shutdownConnection(sd);
         } 
         else {
            // concatenate packets into a single carriage return terminated message
            // or process multiple carriage return terminated messages individually

            if (strlen(msg) + nBytes > sizeof(msg)) {
               // prevent an overrun
               msg[0]='\0';
            }

            buffer[nBytes]='\0';
            strcat(msg, buffer);

            while (delim=strstr(msg, "\r")) {
               *delim='\0';
               processServerMsg(msg, sd);
               strcpy(msg, delim+1);
            }   
         }
      }
   }
   
   CloseHandle(sd->hThread);
   sd->hThread=NULL;
   printq("rxClientThread exit host %s socket %d\n", sd->host, socket);
   ExitThread(0);
   
}
/**
 * \brief Print Memory Management Errors
 */
static void printMemoryManagementErrorMsg(uint32_t CFSRValue)
{
	char str[200];
	printErrorMsg("Memory Management (MPU) fault: ");
	CFSRValue &= 0x000000FF; /* mask mem faults only */
	sprintf(str, "%.2X\n", CFSRValue);
	printErrorMsg(str);

	if ((CFSRValue & SCB_CFSR_IACCVIOL) != 0) {
		printErrorMsg("Instruction access violation\n");
	}

	if ((CFSRValue & SCB_CFSR_DACCVIOL) != 0) {
		printErrorMsg("Data access violation\n");
	}

	if ((CFSRValue & SCB_CFSR_MUNSTKERR) != 0) {
		printErrorMsg("Unstacking error\n");
	}

	if ((CFSRValue & SCB_CFSR_MSTKERR) != 0) {
		printErrorMsg("Stacking error\n");
	}

	if ((CFSRValue & SCB_CFSR_MMARVALID) != 0) {
		sprintf(str,"Memory Manage Address Register address valid flag\nMMFAR value = 0x%.8X\n", SCB->MMFAR);
		printErrorMsg(str);
	}
}
/**
 * \brief Print Usage Errors
 */
static void printUsageErrorMsg(uint32_t CFSRValue)
{
	printErrorMsg("Usage fault: ");

	if ((CFSRValue & SCB_CFSR_DIVBYZERO) != 0) {
		printErrorMsg("Divide by zero\n");
	}

	if ((CFSRValue & SCB_CFSR_INVSTATE) != 0) {
		printErrorMsg("Invalid combination of EPSR and instruction,\nsuch as calling a null pointer function\n");
	}

	if ((CFSRValue & SCB_CFSR_UNDEFINSTR) != 0) {
		printErrorMsg("The processor attempted to excecute an undefined instruction\n");
	}

	if ((CFSRValue & SCB_CFSR_INVPC) != 0) {
		printErrorMsg("Attempt to load EXC_RETURN into pc illegally\n");
	}

	if ((CFSRValue & SCB_CFSR_NOCP) != 0) {
		printErrorMsg("Attempt to use a coprocessor instruction\n");
	}

	if ((CFSRValue & SCB_CFSR_UNALIGNED) != 0) { /* if enabled it is for all instruction, otherwise only for some of them */
		printErrorMsg("Attempt to make an unaligned memory access\n");
	}
}
Exemple #29
0
void sendKeepAlivePacket(int sock, struct addrinfo * p) {
    struct request_keep_alive packet;
	memset(&packet, '\0', sizeof(packet));
    packet.req_type = htonl(REQ_KEEP_ALIVE);
    int status = sendto(sock, &packet, sizeof(struct request_keep_alive), 0, p->ai_addr, p->ai_addrlen);
    if(status == -1) {
		printErrorMsg("unable to send keep-alive packet");
    }
}
int DLS::setOutputFilter (int nsamples, int nspikes, int nerrors)
{
    // Request Current Config
    char write_data[] = "s0fi\r\n";
    serialWrite(write_data, sizeof(write_data)/sizeof(write_data[0]));

    // Read Current Config
    char read_data[] = "g0fi+aa+bb+cc\r\n";
    serialRead(read_data);
    //
    // Check for error indicator (@) and parse error value.
    if (read_data[2]=='@') {
        char errcode_str [] = "000";
        sprintf (errcode_str, "%*s", 3, read_data+4);
        return(-1 * atoi (errcode_str));
    }

    char aa_str [] = "aa";
    aa_str[0] = read_data [5];
    aa_str[1] = read_data [6];
    char bb_str [] = "bb";
    bb_str[0] = read_data [8];
    bb_str[1] = read_data [9];
    char cc_str [] = "cc";
    cc_str[0] = read_data [11];
    cc_str[1] = read_data [12];

    if ((nsamples < 0) || (nsamples > 32))
        nsamples = atoi (aa_str);
    if (nspikes < 0)
        nspikes = atoi (bb_str);
    if (nerrors < 0)
        nerrors = atoi (cc_str);

    debug_print("samples %i\n", nsamples);
    debug_print("spikes %i\n", nspikes);
    debug_print("errors %i\n", nerrors);

    if (2*nspikes+nerrors > 0.4 * nsamples) {
        fprintf(stderr, "ERROR: Make sure that (2*nspikes + nerrors) <= nsamples\n");
        nspikes = atoi (bb_str);
        nerrors = atoi (cc_str);
        nsamples = atoi (aa_str);
    }

    char write_data2[] = "s0fi+aa+bb+cc\r\n";
    sprintf(write_data2, "s0fi+%02i+%02i+%02i\r\n",nsamples,nspikes,nerrors);

    serialWrite(write_data2, sizeof(write_data2)/sizeof(write_data[0]));

    int status = rxData();
    if (status < 0)
        printErrorMsg(status);

    return(status);
}