コード例 #1
0
ファイル: mpq.cpp プロジェクト: Dudelzack/blizzlikecore
/*
 *  This function reads a file and verify if it is a legit MPQ archive
 *  or not. Then it fills the mpq_header structure and reads the hash
 *  table.
 */
int libmpq_archive_open(mpq_archive *mpq_a, unsigned char *mpq_filename) {
	int fd = 0;
	int rb = 0;
	int ncnt = FALSE;
	struct stat fileinfo;

	/* allocate memory */
	mpq_a->mpq_l = (mpq_list *)malloc(sizeof(mpq_list));
	memset(mpq_a->mpq_l, 0, sizeof(mpq_list));
	mpq_a->header = (mpq_header *)malloc(sizeof(mpq_header));
	memset(mpq_a->header, 0, sizeof(mpq_header));

	/* Check if file exists and is readable */
	fd = _open((char *)mpq_filename, MPQ_FILE_OPEN_FLAGS);
	if (fd == LIBMPQ_EFILE) {
		return LIBMPQ_EFILE;
	}

	/* fill the structures with informations */
	strcpy((char *)mpq_a->filename, (char *)mpq_filename);
	libmpq_init_buffer(mpq_a);
	mpq_a->fd               = fd;
	mpq_a->header->id       = 0;
	mpq_a->maxblockindex    = 0;
	mpq_a->mpq_l->mpq_files = NULL;

    mpq_a->mpqpos = 0; //k

	while (!ncnt) {
		mpq_a->header->id = 0;

        libmpq_lseek(mpq_a, mpq_a->mpqpos);

        rb = _read(mpq_a->fd, mpq_a->header, sizeof(mpq_header));

		/* if different number of bytes read, break the loop */
		if (rb != sizeof(mpq_header)) {
			return LIBMPQ_EFILE_FORMAT;
		}

		/* special offset for protected MPQs */
		if (mpq_a->header->offset == LIBMPQ_HEADER_W3M) {
			mpq_a->flags |= LIBMPQ_FLAG_PROTECTED;
			mpq_a->header->offset = sizeof(mpq_header);
		}

		/* if valid signature has been found, break the loop */
        if (mpq_a->header->id == LIBMPQ_ID_MPQ) {
            ncnt = true;
        }
        /*if (mpq_a->header->id == LIBMPQ_ID_MPQ &&
		    mpq_a->header->offset == sizeof(mpq_header) &&
		    mpq_a->header->hashtablepos < mpq_a->header->archivesize &&
		    mpq_a->header->blocktablepos < mpq_a->header->archivesize) {
			ncnt = TRUE;
		}*/

		/* move to the next possible offset */
		if (!ncnt) {
			mpq_a->mpqpos += 0x200;
		}
	}

	/* get the right positions of the hash table and the block table. */
	mpq_a->blocksize = (0x200 << mpq_a->header->blocksize);
	fstat(mpq_a->fd, &fileinfo);

	/* Normal MPQs must have position of */
	/*if (mpq_a->header->hashtablepos + mpq_a->mpqpos < fileinfo.st_size &&
	    mpq_a->header->blocktablepos + mpq_a->mpqpos < fileinfo.st_size) {
		mpq_a->header->hashtablepos  += mpq_a->mpqpos;
		mpq_a->header->blocktablepos += mpq_a->mpqpos;
	} else {
		return LIBMPQ_EFILE_FORMAT;
	}*/

	/* Try to read and decrypt the hashtable */
	if (libmpq_read_hashtable(mpq_a) != 0) {
		return LIBMPQ_EHASHTABLE;
	}

	/* Try to read and decrypt the blocktable */
	if (libmpq_read_blocktable(mpq_a) != 0) {
		return LIBMPQ_EBLOCKTABLE;
	}

	return LIBMPQ_TOOLS_SUCCESS;
}
コード例 #2
0
ファイル: profile_db.cpp プロジェクト: hackshields/antivirus
profile_db *profile_db_open(const char *name, int flags, int mode)
{
    profile_db *pdb = (profile_db *)malloc(sizeof(profile_db));
    memset(pdb, 0, sizeof(profile_db));

    pdb->fd = _open(name, flags, mode);

    off_t size = 0;
    struct stat fd_stat;
    
    memset(&fd_stat, 0, sizeof(fd_stat));

    if(pdb->fd < 0)
	goto error;

    //stat(name, &fd_stat);

    size = _lseek(pdb->fd, 0, SEEK_END);
    //size = fd_stat.st_size;

    if(size > 0)
	{
	    /*
	     * Read profile data from database.
	     */

	    u_long profiles_count, profile_size;

	    char   *buf       = NULL;
	    size_t  buf_alloc = 0;

	    _lseek(pdb->fd, 0, SEEK_SET);

	    _read(pdb->fd, &profiles_count, sizeof(u_long));
	    pdb->profiles.alloc = ntohl(profiles_count);
	    pdb->profiles.array = (profile **)malloc(sizeof(profile *)*pdb->profiles.alloc);
	    memset(pdb->profiles.array, 0, sizeof(profile *)*pdb->profiles.alloc);

	    for(pdb->profiles.used = 0; pdb->profiles.used < pdb->profiles.alloc; pdb->profiles.used++)
		{
		    _read(pdb->fd, &profile_size, sizeof(u_long));
		    profile_size = ntohl(profile_size);

		    if(buf_alloc < profile_size)
			{
			    if(buf) free(buf);
			    buf = (char *)malloc(buf_alloc = profile_size);
			}

		    if(profile_size)
			{
			    _read(pdb->fd, buf, profile_size);
			    pdb->profiles.array[pdb->profiles.used] = profile_load(buf, profile_size);
			}
		}

	    if(buf)
		free(buf);
	}

    return pdb;

  error:
    
    if(pdb)
	profile_db_close(pdb);

    return NULL;
    
}
コード例 #3
0
ファイル: ViewerProxy.C プロジェクト: ahota/visit_intel
bool ViewerProxy::ConnectToExistingViewer(const std::string& host, const int& port, const std::string& password)
{

    //Step 1: Check and see if connection can be made..
    int testSocket = socket(AF_INET, SOCK_STREAM, 0);
    if( testSocket < 0 )
    {
        std::cerr << "Socket not created (ERROR)" << std::endl;
        return false;
    }

    std::cout << "connecting to host: " << host << " port " << port << std::endl;
    struct sockaddr_in sin;
    struct hostent *server = gethostbyname(host.c_str());
    memset(&sin, 0, sizeof(sin));
    memcpy(&(sin.sin_addr), server->h_addr, server->h_length);
    sin.sin_family = AF_INET;
    sin.sin_port = htons(port);

    if (connect(testSocket,(struct sockaddr*) &sin,sizeof(sin)) < 0)
    {
        std::cerr << "Unable to connect to Viewer" << std::endl;
        CloseSocket(testSocket);
        return false;
    }

    //Step 2: Send password to verify that you should be added
    std::ostringstream handshake;
    handshake << "{ \"password\" : \"" << password << "\" }";

#ifndef _WIN32
    int nwrite = write(testSocket,handshake.str().c_str(),handshake.str().length());
#else
    int nwrite = _write(testSocket,handshake.str().c_str(),(unsigned int)handshake.str().length());
#endif
    if(nwrite < 0)
    {
        std::cerr << "Error writing to Viewer" << std::endl;
        CloseSocket(testSocket);
        return false;
    }

    //Step 3: receive arguments to establish reverse connection

    char buffer[1024];

#ifndef _WIN32
    int bytes = read(testSocket,buffer,1024);
#else
    int bytes = _read(testSocket,buffer,1024);
#endif
    buffer[bytes] = '\0';
    //std::cout << "bytes read: " << bytes << " " << buffer << std::endl;

    CloseSocket(testSocket);
    //Step 4: reverse connect same as if it was originally intented..

    //parse message and create new reverse connect

    std::string message = buffer;

    JSONNode node;
    node.Parse(message);

    stringVector args;

    args.push_back("-v");
    args.push_back(node.GetJsonObject()["version"].GetString());

    args.push_back("-host");
    args.push_back(node.GetJsonObject()["host"].GetString());

    args.push_back("-port");
    args.push_back(node.GetJsonObject()["port"].GetString());

    args.push_back("-key");
    args.push_back(node.GetJsonObject()["securityKey"].GetString());

    args.push_back("-reverse_launch");

    int inputArgc = args.size();

    char** inputArgv = new char* [inputArgc+1];

    for(size_t i = 0; i < args.size(); ++i)
    {
        inputArgv[i] = new char [args[i].length()+1];
        strcpy(inputArgv[i],args[i].c_str());
        inputArgv[i][args[i].length()] = '\0';
    }

    inputArgv[inputArgc] = NULL;

    // Connect to the viewer process. Our command line arguments
    // should contain  The viewer is executed using
    // "visit -viewer".
    //

    viewerP = new ParentProcess;
    viewerP->Connect(1, 1, &inputArgc, &inputArgv, true);

    // Use viewerP's connections for xfer.
    xfer->SetInputConnection(viewerP->GetWriteConnection());
    xfer->SetOutputConnection(viewerP->GetReadConnection());
    return true;
}
コード例 #4
0
ファイル: iso_patch.cpp プロジェクト: Kilvas/lioneditor
//iso_offset 32bit整数。能表示的数字最大约0x80000000,这个足够表示iso的,iso9660一般最多0x2???????
//如果换成64bit大整数,vb调用起来就略麻烦了,也暂时没必要。
//函数返回patch的字节数。如果错误返回负数,为各种可能的常量。
int WINAPI iso_patch_file(int iso_type, char *iso_file, int need_ecc_edc, int iso_offset, char *patch_file)
{
	int fhISO, fhPatch;
	int sector_start;
	int sector_length;
	BYTE sector[2352];

	// check that the supplied ISO offset is sane
	if (iso_offset <= 0) 
	{
		return PATCH_ERR_OFFSET;
	}
	sector_start = iso_offset % 2352;
	if( sector_start < ISO9660_DATA_START[iso_type] ||
		sector_start >= ISO9660_DATA_START[iso_type] + ISO9660_DATA_SIZE[iso_type] ) 
	{
		return PATCH_ERR_OFFSET;
	}

	fhPatch = _open(patch_file, _O_BINARY | _O_RDONLY);
	if(fhPatch == -1)
	{ 
		return PATCH_ERR_FILE_PATCH;
	}

	fhISO = _open(iso_file, _O_BINARY | _O_RDWR);
	if(fhISO == -1)
	{ 
		_close(fhPatch); 
		return PATCH_ERR_FILE_ISO;
	}

	sector_length = ISO9660_DATA_SIZE[iso_type] +  ISO9660_DATA_START[iso_type] - sector_start;

	eccedc_init();

	int total_patched_bytes = 0;
	int size_read;
	int nTmp;
	// nTmp is start of sector
	nTmp = iso_offset - (iso_offset % 2352);

	// seek to start of sector
	_lseek(fhISO, nTmp, SEEK_SET);

	// Until done reading bytes...
	for (;_eof(fhPatch)==0;)
	{
		// Read the current sector
		_read(fhISO,sector,2352);

		// Read the data out of the input file and into the sector
		size_read = _read(fhPatch,
						&sector[sector_start],
						sector_length);
	
		if ((sector[0x12] & 8) == 0)
		{
			sector[0x12] = 8;
			sector[0x16] = 8;
		}

		if (need_ecc_edc != 0)
		{
			// Fixup ECC/EDC
			eccedc_generate(sector, iso_type);
		}
		
		_lseek(fhISO, -2352, SEEK_CUR); // Seek to beginning of sector
		_write(fhISO, sector, 2352); // Write the crap
		total_patched_bytes += size_read; // Update byte count
		sector_start = ISO9660_DATA_START[iso_type];
		sector_length = ISO9660_DATA_SIZE[iso_type];
	}

	_close(fhPatch);
	_close(fhISO);

	return total_patched_bytes;
}
コード例 #5
0
ファイル: ppputil.cpp プロジェクト: bhaggerty/wwiv
bool write_netlog(int sn, long sent, long recd, char *tmused)
{
	char s[101], s1[81], s2[81];
	//printf(" write_netlog: %d %ld %ld %s", sn, sent, recd, tmused );
	
	time_t some = time(NULL);
	struct tm *time_now = localtime(&some);
	strftime(s1, 35, "%m/%d/%y %H:%M:%S", time_now);
	
	if (sent || recd) 
	{
		if (recd && !sent)
		{
			sprintf(s2, "       , R:%4ldk,", recd);
		}
		else 
		{
			if (recd && sent)
			{
				sprintf(s2, "S:%4ldk, R:%4ldk,", sent, recd);
			}
			else
			{
				sprintf(s2, "S:%4ldk,         ", sent);
			}
		}
	} 
	else
	{
		strcpy(s2, "                 ");
	}

	if ( strlen( tmused ) > 10 )
	{
		printf(" Bad time pased to tmused\r\n" );
		tmused = "0.0";
	}
	sprintf(s, "%s To %5d, %s         %5s min  %s\r\n", s1, sn, s2, tmused, net_name);
	
	char* ss = (char *) malloc(MAX_LEN + 1024L);
	if (ss == NULL)
	{
		return false;
	}
	strcpy(ss, s);
	
	char szFileName[_MAX_PATH];
	sprintf(szFileName, "%sNET.LOG", syscfg.gfilesdir);
	int hFile = open_netlog(szFileName);
	_lseek(hFile, 0L, SEEK_SET);
	int nLength = _read(hFile, (void *) (&(ss[strlen(s)])), (int) MAX_LEN) + strlen(s);
	while (nLength > 0 && ss[nLength] != '\n')
	{
		--nLength;
	}
	_lseek(hFile, 0L, SEEK_SET);
	_write(hFile, ss, nLength + 1);
	_chsize(hFile, nLength + 1);
	if (ss) 
	{
		free(ss);
		ss = NULL;
	}
	_close(hFile);
	return true;
}
コード例 #6
0
 void read(AzFile *file) {
   reset(); 
   _read(file); 
 }
コード例 #7
0
ファイル: mm_io.cpp プロジェクト: Trottel/mkvtoolnix
uint32_t
mm_io_c::read(void *buffer,
              size_t size) {
  return _read(buffer, size);
}
コード例 #8
0
ファイル: xw.c プロジェクト: mohdazainol/cpcie
int __cdecl main(int argc, char *argv[]) {
	
	int rc=0;
	int sent = 0;
	int received = 0;
	int ijk;
	int total_loop=0;

	unsigned char *buf;
	int donebytes;

	//clock_t t;

	/*
	time_t start,end;
	double dif;
	*/
	
	
    DWORD dwStartTime;
    DWORD dwElapsed;
	
	xillybus_init();
	clear_flag();
	send_flag(ADDR00, FIN);
	matrix_UA = (argv[1]);
	total_loop = atoi(argv[2]);
	FilesizeA = hostpc_tx_sizeA(matrix_UA);
	buf = (char *) malloc(FilesizeA);
	//send_flag(ADDR03, FilesizeA);
	send_flag(ADDR03, 4096);
	send_flag(ADDR00, REQ);
	//t = clock();

	while (1) {
		rc = _read(fhA, buf, FilesizeA);
		rc += 4; // tupple of 4
		if ((rc < 0) && (errno == EINTR))
			continue;
		if (rc < 0) {
			perror("allread() failed to read");
			exit(1);
		}
		if (rc == 0) {
			fprintf(stderr, "Reached read EOF.\n");
			exit(0);
		}
		allwritex(fdw, buf, rc);
		break;
	}
	//t = clock() - t;
	//printf ("%d ticks (%f seconds).\n",t,((float)t)/CLOCKS_PER_SEC);
	send_flag(ADDR00, FIN);
	_close(fhA);
	free(buf);
	//xillybus_close();
	return 0;

	//char *to_pcie_file;

	// unreferenced local variables
	/*
	char *loopback_File;
	int FilesizeH;
	int FilesizeC;
	int FilesizeL;
	*/


	xillybus_init();
	
	// unreferenced local variable
	/*
	FilesizeH = 0;
	FilesizeC = 0;

	*/
	//printf("\nADDR00: %08X\n", read_flag(ADDR00));
	//printf("\nADDR01: %08X\n", read_flag(ADDR01));
	//printf("\nADDR02: %08X\n", read_flag(ADDR02));
	//printf("\nADDR03: %08X\n", read_flag(ADDR03));

	clear_flag();

	matrix_UA = (argv[1]);
	total_loop = atoi(argv[2]);
	
	//printf("\nSTART> total_loop: %d\n", total_loop);

	FilesizeA = hostpc_tx_sizeA(matrix_UA);
	buf = (char *) malloc(FilesizeA);
	donebytes = 0;

	send_flag(ADDR02, FilesizeA);
	send_flag(ADDR00, REQ);
	//wait_flag(ADDR01, RDY);

	//printf("\n1\n");

	while (1) {

		rc = _read(fhA, buf, FilesizeA);
		rc += 4; // tupple of 4
	  
		if ((rc < 0) && (errno == EINTR))
			continue;
		
		if (rc < 0) {
			perror("allread() failed to read");
			exit(1);
		}
		
		if (rc == 0) {
			fprintf(stderr, "Reached read EOF.\n");
			exit(0);
		}

		allwritex(fdw, buf, rc);
		break;

		//printf("\n2\n");
	}

	//printf("\n>>> (hostpc_tx_fileA) File %d Bytes transferred\n", FilesizeA);

	send_flag(ADDR00, FIN);
	//wait_flag(ADDR01, NCN);

	_close(fhA);
	free(buf);

	return 0;


	/*
	_close(fhA);
	xillybus_close();
	return 0;
	*/
	
	

	// Function of sending from SDRAM(FPGA) to HostPC
	/*
	wait_flag(ADDR01, REQ);
	FilesizeC = hostpc_rx_size();
	send_flag(ADDR00, RDY);
	wait_flag(ADDR01, FIN);
	hostpc_rx_file(FilesizeC);
	send_flag(ADDR00, ACK);
	wait_flag(ADDR01, NCN);
	clear_flag(); // All flag from HostPC must be cleared before exit
	xillybus_close();
	return 0;
	*/
	



	/*
	hostpc_tx_file_mat_mult(NULL);
	printf("\nC2");
	xillybus_close();
	clear_flag();
	return 0;
	*/









	/*
	wait_flag(ADDR01, REQ);
	printf("\nHWACC is ready to accept data.");
	send_flag(ADDR00, RDY);
	*/


	//Test_throughput_power();

	//Test_HostPC_to_SDRAM();			// OK
	//Test_HostPC_Loopback();			// OK
	//Test_SDRAM_to_HostPC();			// OK
	//Test_SDRAM_to_HwAcc_to_HostPC();	// OK
	//Test_HostPC_to_SDRAM_1_file();	// OK
	//HostPC_to_HwAcc_to_SDRAM_1_file();	// OK

	//Test_HostPC_to_SDRAM_to_HwAcc_to_HostPC(); // OK

	//HostPC_to_HwAcc_to_SDRAM();

	//Test_HostPC_decompress_to_SDRAM_1_file();


	return 0;

	//printf("\nA\n");
	
	send_flag(ADDR04, NCN);

	//printf("\nB\n");

	wait_flag(ADDR01, RDY);

	//printf("\nC\n");

	send_flag(ADDR00, RDY);

	//printf("\nD\n");

	//time (&start);
	dwStartTime = GetTickCount();
	for (ijk=total_loop-1; ijk>=0; --ijk) {
		send_flag(ADDR04, ijk);
		Test_HostPC_to_HwAcc_to_HostPC_1_file();
	}	
	//time (&end);
	dwElapsed = GetTickCount() - dwStartTime;

	//printf("\nE\n");

	//dif = difftime (end,start);
	//printf ("\nTime taken is: %.2lf\n", dif);
	printf("It took %d.%3d seconds to complete\n", dwElapsed/1000, dwElapsed - dwElapsed/1000);

	printf("\nFINISH\n");
	send_flag(ADDR04, NCN);

	wait_flag(ADDR01, NCN);
	clear_flag();

	xillybus_close();
	

	/*
	clear_flag();
	xillybus_close();
	*/

	return 0;

}
コード例 #9
0
ファイル: HERMESmain.cpp プロジェクト: okready/ArxFatalis
long	FileRead(long handle, void * adr, long size)
{
	return(_read(handle - 1, adr, size));
}
コード例 #10
0
ファイル: CMainDlg.cpp プロジェクト: DimeSPb/ecuExplorer
void CMainDlg::OnLoad()
{
	CString sFile;
	int fhLabel = 0;
	unsigned char cRead;
	unsigned char cStorage[255];
	LPSTRUCT_LABELITEM lpLabelItem = NULL;
	int iLoop;

	if(!BrowseForFile(&sFile))
		return;

	if((fhLabel = _open(sFile,_O_BINARY | _O_RDONLY,_S_IREAD)) == -1)
		return;

	_lseek(fhLabel,0,SEEK_SET);

	_read(fhLabel,&cRead,1);
	_read(fhLabel,&cStorage,cRead);
	strncpy(sVersion.GetBufferSetLength(cRead),(LPCTSTR)&cStorage[0],cRead);
	sVersion.ReleaseBuffer();
	_read(fhLabel,&cRead,1);

	while(!_eof(fhLabel))
	{
		if((lpLabelItem = new STRUCT_LABELITEM) == NULL)
			return;

		_read(fhLabel,&lpLabelItem->cLength_id,1);
		lpLabelItem->szID = (LPTSTR)malloc(lpLabelItem->cLength_id + 1);
		memset(lpLabelItem->szID,0,lpLabelItem->cLength_id);
		_read(fhLabel,&cStorage,lpLabelItem->cLength_id);
		cStorage[lpLabelItem->cLength_id] = '\0';
		strncpy(lpLabelItem->szID,(LPCTSTR)&cStorage[0],lpLabelItem->cLength_id + 1);

		_read(fhLabel,&lpLabelItem->cLength_label,1);
		lpLabelItem->szLabel = (LPTSTR)malloc(lpLabelItem->cLength_label + 1);
		memset(lpLabelItem->szLabel,0,lpLabelItem->cLength_label);
		_read(fhLabel,&cStorage,lpLabelItem->cLength_label);
		cStorage[lpLabelItem->cLength_label] = '\0';
		strncpy(lpLabelItem->szLabel,(LPCTSTR)&cStorage[0],lpLabelItem->cLength_label + 1);

//		_read(fhLabel,&lpLabelItem->cLength_type,1);
//		lpLabelItem->szType = (LPTSTR)malloc(lpLabelItem->cLength_type + 1);
//		memset(lpLabelItem->szType,0,lpLabelItem->cLength_type);
//		_read(fhLabel,&cStorage,lpLabelItem->cLength_type);
//		cStorage[lpLabelItem->cLength_type] = '\0';
//		strncpy(lpLabelItem->szType,(LPCTSTR)&cStorage[0],lpLabelItem->cLength_type + 1);

		_read(fhLabel,&lpLabelItem->cChecksum,1);

		listLabel.AddTail(lpLabelItem);
	}

	_close(fhLabel);

	pos = listLabel.GetHeadPosition();
	lpLabelItem = (LPSTRUCT_LABELITEM)listLabel.GetAt(pos);
	for(iLoop = 0;iLoop < lpLabelItem->cLength_id;iLoop++)
	{
		sFile.Format("%02X ",(unsigned char)lpLabelItem->szID[iLoop]);
		sID += sFile;
	}
	sLabel = lpLabelItem->szLabel;
//	sType = lpLabelItem->szType;
	sChecksum = lpLabelItem->cChecksum;
	UpdateData(FALSE);

	usIndex++;
	sFile.Format("ecuExplorer Label Editor - %i of %i",usIndex,listLabel.GetCount());
	SetWindowText(sFile);
}
コード例 #11
0
ファイル: osd_eeprom.cpp プロジェクト: Benbenbeni/ardupilot-1
void OSD_EEPROM::init(){

    for(uint16_t i=0;i<EEPROM_SIZE; i++){ // read out all to buffer
        data[i] = _read(i);
    }
}
コード例 #12
0
ファイル: gtstd.c プロジェクト: AugustoAbacus/core
static int hb_gt_std_ReadKey( PHB_GT pGT, int iEventMask )
{
   PHB_GTSTD pGTSTD;
   int ch = 0;

   HB_TRACE( HB_TR_DEBUG, ( "hb_gt_std_ReadKey(%p,%d)", pGT, iEventMask ) );

   HB_SYMBOL_UNUSED( iEventMask );

   pGTSTD = HB_GTSTD_GET( pGT );

#if defined( HB_HAS_TERMIOS )
   {
      struct timeval tv;
      fd_set rfds;
      tv.tv_sec = 0;
      tv.tv_usec = 0;
      FD_ZERO( &rfds );
      FD_SET( pGTSTD->hStdin, &rfds );
      if( select( pGTSTD->hStdin + 1, &rfds, NULL, NULL, &tv ) > 0 )
      {
         HB_BYTE bChar;
         if( hb_fsRead( pGTSTD->hStdin, &bChar, 1 ) == 1 )
            ch = bChar;
      }
   }
#elif defined( _MSC_VER ) && ! defined( HB_OS_WIN_CE )
   if( pGTSTD->fStdinConsole )
   {
      if( _kbhit() )
      {
         ch = _getch();
         if( ( ch == 0 || ch == 224 ) && _kbhit() )
         {
            /* It was a function key lead-in code, so read the actual
               function key and then offset it by 256 */
            ch = _getch() + 256;
         }
         ch = hb_gt_dos_keyCodeTranslate( ch );
      }
   }
   else if( ! _eof( ( int ) pGTSTD->hStdin ) )
   {
      HB_BYTE bChar;
      if( _read( ( int ) pGTSTD->hStdin, &bChar, 1 ) == 1 )
         ch = bChar;
   }
#elif defined( HB_OS_WIN )
   if( ! pGTSTD->fStdinConsole )
   {
      HB_BYTE bChar;
      if( hb_fsRead( pGTSTD->hStdin, &bChar, 1 ) == 1 )
         ch = bChar;
   }
   else if( WaitForSingleObject( ( HANDLE ) hb_fsGetOsHandle( pGTSTD->hStdin ), 0 ) == WAIT_OBJECT_0 )
   {
#if defined( HB_OS_WIN_CE )
      HB_BYTE bChar;
      if( hb_fsRead( pGTSTD->hStdin, &bChar, 1 ) == 1 )
         ch = bChar;
#else
      INPUT_RECORD  ir;
      DWORD         dwEvents;
      while( PeekConsoleInput( ( HANDLE ) hb_fsGetOsHandle( pGTSTD->hStdin ), &ir, 1, &dwEvents ) && dwEvents == 1 )
      {
         if( ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown )
         {
            HB_BYTE bChar;
            if( hb_fsRead( pGTSTD->hStdin, &bChar, 1 ) == 1 )
               ch = bChar;
         }
         else /* Remove from the input queue */
            ReadConsoleInput( ( HANDLE ) hb_fsGetOsHandle( pGTSTD->hStdin ), &ir, 1, &dwEvents );
      }
#endif
   }
#elif defined( __WATCOMC__ )
   if( pGTSTD->fStdinConsole )
   {
      if( kbhit() )
      {
         ch = getch();
         if( ( ch == 0 || ch == 224 ) && kbhit() )
         {
            /* It was a function key lead-in code, so read the actual
               function key and then offset it by 256 */
            ch = getch() + 256;
         }
         ch = hb_gt_dos_keyCodeTranslate( ch );
      }
   }
   else if( ! eof( pGTSTD->hStdin ) )
   {
      HB_BYTE bChar;
      if( read( pGTSTD->hStdin, &bChar, 1 ) == 1 )
         ch = bChar;
   }
#else
   {
      if( ! pGTSTD->fStdinConsole )
      {
         HB_BYTE bChar;
         if( hb_fsRead( pGTSTD->hStdin, &bChar, 1 ) == 1 )
            ch = bChar;
      }
      else
      {
         int iTODO; /* TODO: */
      }
   }
#endif

   if( ch )
   {
      int u = HB_GTSELF_KEYTRANS( pGT, ch );
      if( u )
         ch = HB_INKEY_NEW_UNICODE( u );
   }

   return ch;
}
コード例 #13
0
ファイル: qrad.c プロジェクト: jlecorre/hlinvasion
long
readtransfers(char *transferfile, long numpatches)
{
	int		handle;
	long	readpatches = 0, readtransfers = 0, totalbytes = 0;
	long	start, end;
	time(&start);
	if ( (handle = _open( transferfile, _O_RDONLY | _O_BINARY )) != -1 )
	{
		long			filepatches;
		unsigned long	bytesread;

		printf("%-20s Restoring [%-13s - ", "MakeAllScales:", transferfile );
		
		if ( (bytesread = _read(handle, &filepatches, sizeof(filepatches))) == sizeof(filepatches) )
		{
			if ( filepatches == numpatches )
			{

				patch_t			*patch;

				totalbytes += bytesread;

				for( patch = patches; readpatches < numpatches; patch++ )
				{
					if ( (bytesread = _read(handle, &patch->numtransfers, sizeof(patch->numtransfers)))
					  == sizeof(patch->numtransfers) )
					{
						if ( patch->transfers = calloc(patch->numtransfers, sizeof(patch->transfers[0])) )
						{
							totalbytes += bytesread;

							if ( patch->numtransfers )
							{
								if ( (bytesread = _read(handle, patch->transfers, patch->numtransfers*sizeof(transfer_t)))
								  == patch->numtransfers*sizeof(transfer_t) )
									{
										totalbytes += bytesread;
										readtransfers += patch->numtransfers;
									}
								else
								{
									printf("\nMissing transfer count!  Save file will now be rebuilt." );
									break;
								}
							}
							readpatches++;
						}
						else
						{
							printf("\nMemory allocation failure creating transfer lists(%d*%d)!\n",
								  patch->numtransfers, sizeof(transfer_t) );
							break;
						}
					}
					else
					{
						printf("\nMissing patch count!  Save file will now be rebuilt." );
						break;
					}
				}
			}
			else
				printf("\nIncorrect transfer patch count found!  Save file will now be rebuilt." );
		}
		_close( handle );
		time(&end);
		printf("%10.3fMB] (%d)\n",totalbytes/(1024.0*1024.0), end-start);
	}

	if (readpatches != numpatches )
		unlink(transferfile);
	else
		total_transfer = readtransfers;

	return readpatches;
}
コード例 #14
0
ファイル: GraspMMIlite.cpp プロジェクト: PsyPhy/GRASPonISS
int main( int argc, char *argv[] )
{

	BOOL new_hk;
	BOOL new_rt;

	int i;

	if ( argc < 2 ) printf( "Using default root path for cache files: %s\n", packetCacheFilenameRoot );
	else {
		packetCacheFilenameRoot = argv[1];
		printf( "Using command-line root path for cache files: %s\n", packetCacheFilenameRoot );
	}

	// Construct the paths to the cache files where we expect to read the incoming packets.
	CreateGripPacketCacheFilename( hkPacketCacheFilePath, sizeof( hkPacketCacheFilePath ), GRIP_HK_BULK_PACKET, packetCacheFilenameRoot );
	CreateGripPacketCacheFilename( rtPacketCacheFilePath, sizeof( rtPacketCacheFilePath ), GRIP_RT_SCIENCE_PACKET, packetCacheFilenameRoot );

	// Attempt to open the packet cache to read the accumulated packets.
	// If it is not immediately available, try for a few seconds then query the user.
	// The user can choose to continue to wait or cancel program execution.
	int retry_count;
	int return_code;
	int  fid;
	int packets_read = 0;
	char *filename = rtPacketCacheFilePath;
	int bytes_read;	do {
		for ( retry_count = 0; retry_count  < MAX_OPEN_CACHE_RETRIES; retry_count ++ ) {
			// If open succeeds, it will return zero. So if zero return, break from retry loop.
			return_code = _sopen_s( &fid, filename, _O_RDONLY | _O_BINARY, _SH_DENYNO, _S_IWRITE | _S_IREAD  );
			if ( return_code == 0 ) break;
			// Wait a second before trying again.
			Sleep( RETRY_PAUSE );
		}
		// If return_code is zero, file is open, so break out of loop and continue.
		if ( return_code == 0 ) break;
		// If return_code is non-zero, we are here because the retry count has been reached without opening the file.
		// Ask the user if they want to keep on trying or abort.
		else {
			int mb_answer = fMessageBox( MB_RETRYCANCEL, "GraspMMIlite", "Error opening %s for binary read.\nContinue trying?", filename );
			if ( mb_answer == IDCANCEL ) exit( ERROR_CACHE_NOT_FOUND ); // User chose to abort.
		}
	} while ( true ); // Keep trying until success or until user cancels.

	// Read in all of the data packets in the file.
	packets_read = 0;
	while ( rtPacketLengthInBytes == (bytes_read = _read( fid, &rtPacket, rtPacketLengthInBytes )) ) {
		packets_read++;
		if ( bytes_read < 0 ) {
			fMessageBox( MB_OK, "GraspMMIlite", "Error reading from %s.", filename );
			exit( -1 );
		}
		// Check that it is a valid GRIP packet. It would be strange if it was not.
		ExtractEPMTelemetryHeaderInfo( &epmHeader, &rtPacket );
		if ( epmHeader.epmSyncMarker != EPM_TELEMETRY_SYNC_VALUE || epmHeader.TMIdentifier != GRIP_RT_ID ) {
			fMessageBox( MB_OK, "GraspMMIlite", "Unrecognized packet from %s.", filename );
			exit( -1 );
		}
		// Show some of the realtime science data.
		ExtractGraspRealtimeDataInfo( rtInfo, rtPacket );
		for ( int i = 0; i < GRASP_RT_SLICES_PER_PACKET; i++ ) {
			if ( strcmp( (char *) rtInfo.dataSlice[i].clientData, "NULL" ) ) {
				printf( "\nFill Time: %8.3f Frame Time: %8.3f    Client Time: %8.3f Client Tag: %s", 
					rtInfo.dataSlice[i].fillTime,  
					rtInfo.dataSlice[i].codaFrame.time,
					rtInfo.dataSlice[i].clientTime,
					rtInfo.dataSlice[i].clientData );

				if ( !strcmp( "GRASP", (char *) rtInfo.dataSlice[i].clientData ) ) {
					Grasp::GraspClientData *grasp = (Grasp::GraspClientData *)  rtInfo.dataSlice[i].clientData;
					printf( "  %d %6s %08x", grasp->currentTrial, Grasp::GraspParadigmString[grasp->paradigm], grasp->currentState );
					Pose	pose;
					char	*object;
					int		visible;
				
//					vm.CopyPose( pose, grasp->headPose ); object = "Head"; visible = rtInfo.dataSlice[i].HMD.visible;
//					vm.CopyPose( pose, grasp->handPose ); object = "Hand"; visible = rtInfo.dataSlice[i].hand.visible;
					vm.CopyPose( pose, rtInfo.dataSlice[i].hand.pose ); object = "Hand"; visible = rtInfo.dataSlice[i].hand.visible;
//					vm.CopyPose( pose, grasp->chestPose ); object = "Chest"; visible = rtInfo.dataSlice[i].chest.visible;
					printf( "  %5s: %d %s %s", 
						object, visible, vm.vstr( pose.position ), vm.qstr( pose.orientation ) );
				}

				if ( !strcmp( "GRSPGUI", (char *) rtInfo.dataSlice[i].clientData ) ) {
					GraspGUI::GraspActionSlice *action = (GraspGUI::GraspActionSlice *) rtInfo.dataSlice[i].clientData;
					for (int j = 0; j < GUI_ITEMS_IN_SLICE; j++ ) {
						printf( "  %03d.%03d.%05d", action->record[j].task, action->record[j].step, action->record[j].code );
					}
				}
			
				if ( !strcmp( "ALIGN", (char *) rtInfo.dataSlice[i].clientData ) ) {
					AlignToRigidBodyGUI::AlignClientBuffer *align = (AlignToRigidBodyGUI::AlignClientBuffer *) rtInfo.dataSlice[i].clientData;
					printf( " %4s", ( align->prePost == PRE ? "PRE" : "POST" ) );
					for ( int unit = 0; unit < MAX_UNITS; unit++ ) {
						printf( "   Coda %d: %s %s", unit,
							vm.vstr( align->offsets[unit], "<%+6.1f %+6.1f %+6.1f>" ), 
							vm.mstr( align->rotations[unit], "[%+4.3f %+4.3f %+4.3f | %+4.3f %+4.3f %+4.3f | %+4.3f %+4.3f %+4.3f]" ) );
					}
				}
			}
		}

		if ( 0 == ( packets_read % 1000 ) ) {
			printf( "\nPress a key to continue ..." );
			fflush( stdout );
			int c = _getch();
			if ( ESCAPE == c ) exit( 0 );
		}
	}
	// Finished reading. Close the file and check for errors.
	return_code = _close( fid );

	if ( return_code ) {
		fMessageBox( MB_OK, "GraspMMIlite", "Error closing %s after binary read.\nError code: %s", filename, return_code );
		exit( return_code );
	}

	printf( "\n\nPress any key to exit ..." );
	fflush( stdout );
	_getch();

	return 0;
}
コード例 #15
0
ファイル: bytedistrpt.c プロジェクト: ErikCumps/spwproject
static int
process (int in, BIfunc func)
{
	BI		info;
	unsigned char	buffer[BUFSIZE];
	unsigned char	*bidxlist[(BUFSIZE/BLKSIZE)+1];
	int		bidx;
	ssize_t		bread;
	unsigned long	size;
	unsigned long	ccnt[cnt_LAST];
	double		cprc[cnt_LAST];
	FREQ		bcnt[256];
	double		bprc[256];
	int		i, c;

	memset (&info, 0, sizeof (info));
	memset (bidxlist, 0, sizeof (bidxlist));
	bidx = 0;
	while ((bidx * BLKSIZE) < BUFSIZE) {
		bidxlist[bidx] = &(buffer[bidx * BLKSIZE]);
		bidx++;
	}

	memset (ccnt, 0, sizeof (ccnt));
	memset (cprc, 0, sizeof (cprc));
	memset (bcnt, 0, sizeof (bcnt));
	memset (bprc, 0, sizeof (bprc));

	for (i=0; i<256; i++) bcnt[i].idx = i;

	size = 0;
	while (1) {
		memset (buffer, 0, sizeof (buffer));
		bread = _read (in, buffer, sizeof (buffer));
		if (bread <= 0) break;

		size += bread; bidx = 0;
		while (bread > 0)  {
			info.size = minsize (BLKSIZE, bread);
			info.buffer = bidxlist[bidx];
			func (&info, ccnt, bcnt);
			info.index++;
			info.offset += BLKSIZE;
			bidx++;
			bread -= BLKSIZE;
		}
	}
	if (bread == -1) {
		fprintf (stderr, "*** Error: error reading from file! (errno: %d)\n", errno);
		return (1);
	}

	printf ("# Character class distribution:\n");
	printf ("# %9s %9s %9s %9s %9s %9s\n", "alfa", "num", "punc", "space", "nul", "rest");

	cprc[cnt_alf] = ccnt[cnt_alf] * 100.0 / size;
	cprc[cnt_num] = ccnt[cnt_num] * 100.0 / size;
	cprc[cnt_pnc] = ccnt[cnt_pnc] * 100.0 / size;
	cprc[cnt_spc] = ccnt[cnt_spc] * 100.0 / size;
	cprc[cnt_nul] = ccnt[cnt_nul] * 100.0 / size;
	cprc[cnt_rst] = ccnt[cnt_rst] * 100.0 / size;
	
	printf ("  %9lu %9lu %9lu %9lu %9lu %9lu\n",
			ccnt[cnt_alf], ccnt[cnt_num], ccnt[cnt_pnc], ccnt[cnt_spc], ccnt[cnt_nul], ccnt[cnt_rst]);
	printf ("  %8.2f%% %8.2f%% %8.2f%% %8.2f%% %8.2f%% %8.2f%%\n",
			cprc[cnt_alf], cprc[cnt_num], cprc[cnt_pnc], cprc[cnt_spc], cprc[cnt_nul], cprc[cnt_rst]);
	printf ("\n");

	qsort (bcnt, 256, sizeof (FREQ), sort_freq);

	printf ("# Byte distribution, sorted on frequency:\n");
	printf ("# %4s %9s %6s\n", "char", "count", "dist");
	for (i=0; i<256; i++) {
		bprc[i] = bcnt[i].cnt * 100.0 / size;
		c = bcnt[i].idx & 0xff;
		if (isprint (c)) {
			printf ("  [ %c] %9lu %6.2f%%\n", c, bcnt[i].cnt, bprc[i]);
		} else {
			printf ("  [%2.2x] %9lu %6.2f%%\n", c, bcnt[i].cnt, bprc[i]);
		}
	}
	printf ("\n");

	qsort (bcnt, 256, sizeof (FREQ), sort_char);

	printf ("# Byte distribution, sorted on byte value:\n");
	printf ("# %4s %9s %6s\n", "char", "count", "dist");
	for (i=0; i<256; i++) {
		bprc[i] = bcnt[i].cnt * 100.0 / size;
		c = bcnt[i].idx & 0xff;
		if (isprint (c)) {
			printf ("  [ %c] %9lu %6.2f%%\n", c, bcnt[i].cnt, bprc[i]);
		} else {
			printf ("  [%2.2x] %9lu %6.2f%%\n", c, bcnt[i].cnt, bprc[i]);
		}
	}
	printf ("\n");

	return (0);
}
コード例 #16
0
ファイル: hash.c プロジェクト: edgar-pek/PerspicuOS
/* ARGSUSED */
DB *
__hash_open(const char *file, int flags, int mode,
    const HASHINFO *info,	/* Special directives for create */
    int dflags)
{
	HTAB *hashp;
	struct stat statbuf;
	DB *dbp;
	int bpages, hdrsize, new_table, nsegs, save_errno;

	if ((flags & O_ACCMODE) == O_WRONLY) {
		errno = EINVAL;
		return (NULL);
	}

	if (!(hashp = (HTAB *)calloc(1, sizeof(HTAB))))
		return (NULL);
	hashp->fp = -1;

	/*
	 * Even if user wants write only, we need to be able to read
	 * the actual file, so we need to open it read/write. But, the
	 * field in the hashp structure needs to be accurate so that
	 * we can check accesses.
	 */
	hashp->flags = flags;

	if (file) {
		if ((hashp->fp = _open(file, flags, mode)) == -1)
			RETURN_ERROR(errno, error0);
		(void)_fcntl(hashp->fp, F_SETFD, 1);
		new_table = _fstat(hashp->fp, &statbuf) == 0 &&
		    statbuf.st_size == 0 && (flags & O_ACCMODE) != O_RDONLY;
	} else
		new_table = 1;

	if (new_table) {
		if (!(hashp = init_hash(hashp, file, info)))
			RETURN_ERROR(errno, error1);
	} else {
		/* Table already exists */
		if (info && info->hash)
			hashp->hash = info->hash;
		else
			hashp->hash = __default_hash;

		hdrsize = _read(hashp->fp, &hashp->hdr, sizeof(HASHHDR));
#if BYTE_ORDER == LITTLE_ENDIAN
		swap_header(hashp);
#endif
		if (hdrsize == -1)
			RETURN_ERROR(errno, error1);
		if (hdrsize != sizeof(HASHHDR))
			RETURN_ERROR(EFTYPE, error1);
		/* Verify file type, versions and hash function */
		if (hashp->MAGIC != HASHMAGIC)
			RETURN_ERROR(EFTYPE, error1);
#define	OLDHASHVERSION	1
		if (hashp->VERSION != HASHVERSION &&
		    hashp->VERSION != OLDHASHVERSION)
			RETURN_ERROR(EFTYPE, error1);
		if ((int32_t)hashp->hash(CHARKEY, sizeof(CHARKEY)) != hashp->H_CHARKEY)
			RETURN_ERROR(EFTYPE, error1);
		/*
		 * Figure out how many segments we need.  Max_Bucket is the
		 * maximum bucket number, so the number of buckets is
		 * max_bucket + 1.
		 */
		nsegs = (hashp->MAX_BUCKET + 1 + hashp->SGSIZE - 1) /
			 hashp->SGSIZE;
		if (alloc_segs(hashp, nsegs))
			/*
			 * If alloc_segs fails, table will have been destroyed
			 * and errno will have been set.
			 */
			return (NULL);
		/* Read in bitmaps */
		bpages = (hashp->SPARES[hashp->OVFL_POINT] +
		    (hashp->BSIZE << BYTE_SHIFT) - 1) >>
		    (hashp->BSHIFT + BYTE_SHIFT);

		hashp->nmaps = bpages;
		(void)memset(&hashp->mapp[0], 0, bpages * sizeof(u_int32_t *));
	}

	/* Initialize Buffer Manager */
	if (info && info->cachesize)
		__buf_init(hashp, info->cachesize);
	else
		__buf_init(hashp, DEF_BUFSIZE);

	hashp->new_file = new_table;
	hashp->save_file = file && (hashp->flags & O_RDWR);
	hashp->cbucket = -1;
	if (!(dbp = (DB *)malloc(sizeof(DB)))) {
		save_errno = errno;
		hdestroy(hashp);
		errno = save_errno;
		return (NULL);
	}
	dbp->internal = hashp;
	dbp->close = hash_close;
	dbp->del = hash_delete;
	dbp->fd = hash_fd;
	dbp->get = hash_get;
	dbp->put = hash_put;
	dbp->seq = hash_seq;
	dbp->sync = hash_sync;
	dbp->type = DB_HASH;

#ifdef DEBUG
	(void)fprintf(stderr,
"%s\n%s%p\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%x\n%s%x\n%s%d\n%s%d\n",
	    "init_htab:",
	    "TABLE POINTER   ", hashp,
	    "BUCKET SIZE     ", hashp->BSIZE,
	    "BUCKET SHIFT    ", hashp->BSHIFT,
	    "DIRECTORY SIZE  ", hashp->DSIZE,
	    "SEGMENT SIZE    ", hashp->SGSIZE,
	    "SEGMENT SHIFT   ", hashp->SSHIFT,
	    "FILL FACTOR     ", hashp->FFACTOR,
	    "MAX BUCKET      ", hashp->MAX_BUCKET,
	    "OVFL POINT	     ", hashp->OVFL_POINT,
	    "LAST FREED      ", hashp->LAST_FREED,
	    "HIGH MASK       ", hashp->HIGH_MASK,
	    "LOW  MASK       ", hashp->LOW_MASK,
	    "NSEGS           ", hashp->nsegs,
	    "NKEYS           ", hashp->NKEYS);
#endif
#ifdef HASH_STATISTICS
	hash_overflows = hash_accesses = hash_collisions = hash_expansions = 0;
#endif
	return (dbp);

error1:
	if (hashp != NULL)
		(void)_close(hashp->fp);

error0:
	free(hashp);
	errno = save_errno;
	return (NULL);
}
コード例 #17
0
 AzIntPool(AzFile *file)
             : ent(NULL), ent_num(0), data(NULL), data_num(0), isCommitted(true) {
   _read(file); 
 }
コード例 #18
0
ファイル: vm.hpp プロジェクト: awesome-security/vera
 void *vread(vm_pagenum_t pagenum)        { return _read(pagenum, true); }
コード例 #19
0
static int win32_serial_port_read(int fd, char *read_buffer, size_t max_chars_to_read)
{
    int chars_read = _read(fd, read_buffer, max_chars_to_read);

    return chars_read;
}
コード例 #20
0
ファイル: vm.hpp プロジェクト: awesome-security/vera
 // Alloc buffer for NEW page
 void *valloc(vm_pagenum_t pagenum)       { return _read(pagenum, false); }
コード例 #21
0
ファイル: far.cpp プロジェクト: crom83/cromfarplugs
int MrRipper::GetFiles(struct PluginPanelItem *PanelItem, int ItemsNumber, int Move, char *DestPath, int OpMode)
{
    TSaveScreen SS;
    DWORD StartTime=GetTickCount();
    BOOL WaitMessage=FALSE;
    double Progress1, Progress2;
    long FullSize,CurSize, ProcessedBytes;
    int Owervrite = 0;
    char MyDestPath[MAX_PATH];
    char MyDestFile[MAX_PATH];

    if (!OpMode & OPM_SILENT){        
        if (!DestDirPrompt(DestPath)) return -2;        
    }

        if ((strlen(DestPath)==3)&&
                (DestPath[1]==':')&&
                (DestPath[2]=='\\')) DestPath[2] = 0;

    GetCurrentDirectory(MAX_PATH, MyDestPath);
    if (!SetCurrentDirectory(DestPath)) return FALSE;
    SetCurrentDirectory(MyDestPath);
    
    FormatFinder FF(PluginPath);        
    for (int i = 0; i<FF.GetFormatCount(); i++)             
        for (int j = 0; j<FF.GetnKnownFormats(i); j++)
            FF.SetActiveOpt(i, j, GetRegKey(HKEY_CURRENT_USER,"",FF.GetRegPath(i, j), 1));

    MakeCopyList(PanelItem, ItemsNumber);

    int f1, f2;
    int readed, pos, endpos, getret;
    
    if (!bPluginManager){
        FullSize = 0;
    
        for (int I = 0; I < copyfiles.size(); I++)
            FullSize += copyfiles[I].FileSize;
                        
        ProcessedBytes = 0;                                                     
    
        for (I = 0; I < copyfiles.size(); I++){
            if (copyfiles[I].FileName[strlen(copyfiles[I].FileName)-1]=='\\'){
                char *c = my_substr(copyfiles[I].FileName, 0, strlen(copyfiles[I].FileName)-1);
                FSF.sprintf(MyDestPath, "%s\\%s", DestPath, c);
                my_free(c);
                CreateDirectory(MyDestPath, NULL);            
            } else {    
                char *d = ExtractPath(copyfiles[I].FileName);
                if (strlen(d)>0) FSF.sprintf(MyDestPath, "%s\\%s", DestPath, d); 
                else strcpy(MyDestPath, DestPath);
                my_free(d);
            
                d = ExtractName(copyfiles[I].FileName);
                FSF.sprintf(MyDestFile, "%s", d);
                my_free(d);

                char c[MAX_PATH];
                FSF.sprintf(c, "%s\\%s", MyDestPath, MyDestFile);

                f2 = _open(c, _O_RDONLY|_O_BINARY);
                if (f2!=-1) {
                    _close(f2);
                    if (Owervrite==3) continue;
                    if (Owervrite == 0||Owervrite == 1)
                    if (!OpMode & OPM_SILENT) Owervrite = OverwritePrompt(MyDestFile);
                    if (Owervrite==-1) break;
                    if (Owervrite==3||Owervrite==1) continue;
                }   
    
                if (copyfiles[I].Fmt != FMT_DUMMY)
                    if (FF.GetCanGetFile(copyfiles[I].Fmt, copyfiles[I].Plugin)&&ConvView){
                        getret = FF.GetFile(copyfiles[I].Plugin, copyfiles[I].Fmt, RipFileName, MyDestFile, MyDestPath, copyfiles[I].StartOffset, copyfiles[I].FileSize, copyfiles[I].UnpSize, OpMode & OPM_SILENT, copyfiles[I].UserData.Data);
                        if (getret == 1){
                            ProcessedBytes += copyfiles[I].FileSize;
                            WaitMessage=FALSE;
                            if (!OpMode & OPM_SILENT){                                
                                if (GetTickCount()-StartTime>500){
                                    if (CheckForKey(VK_ESCAPE)) break;
                                    Progress1 = 100.0;
                                    Progress2 = ProcessedBytes; Progress2 *= 100; Progress2 /= FullSize;
                                    char FileMsg[100], ProgressMsg1[100], ProgressMsg2[100];
                                    FSF.sprintf(FileMsg,GetMsg(MExtracting), MyDestFile);
                                    FSF.sprintf(ProgressMsg1,GetMsg(MExtr1), Progress1);
                                    FSF.sprintf(ProgressMsg2,GetMsg(MExtr2), Progress2);                                                                                        
                                    const char *MsgItems[]={GetMsg(MExtraction),FileMsg, ProgressMsg1, ProgressMsg2};
                                    Info.Message(Info.ModuleNumber,WaitMessage ? FMSG_LEFTALIGN|FMSG_KEEPBACKGROUND:FMSG_LEFTALIGN,NULL,MsgItems,sizeof(MsgItems)/sizeof(MsgItems[0]),0);
                                    WaitMessage=TRUE;
                                }       
                            }
                            continue;
                        }
                        if (getret == 2){
                            if (CheckForKey(VK_ESCAPE)) break;
                            continue;
                        }
                    }
            
                FSF.sprintf(c, "%s\\%s", MyDestPath, MyDestFile);
    
                f1 = _open(RipFileName, _O_RDONLY|_O_BINARY);
                _lseek(f1,copyfiles[I].StartOffset,SEEK_SET);                                                     
            
                f2 = _open(c, _O_CREAT|_O_WRONLY|_O_BINARY);
                                
                endpos = copyfiles[I].StartOffset+copyfiles[I].FileSize;
                CurSize = copyfiles[I].FileSize;
                pos = _tell(f1);

                while (pos<endpos){                                       
                    if (!OpMode & OPM_SILENT){                    
                        if (GetTickCount()-StartTime>500){
                            if (CheckForKey(VK_ESCAPE)) break;
                            Progress1 = (pos-copyfiles[I].StartOffset); Progress1 *= 100; Progress1 /= copyfiles[I].FileSize;
                            Progress2 = ProcessedBytes; Progress2 *= 100; Progress2 /= FullSize;
                            char FileMsg[100], ProgressMsg1[100], ProgressMsg2[100];
                            FSF.sprintf(FileMsg,GetMsg(MExtracting), MyDestFile);
                            FSF.sprintf(ProgressMsg1,GetMsg(MExtr1), Progress1);
                            FSF.sprintf(ProgressMsg2,GetMsg(MExtr2), Progress2);                                                                                        
                            const char *MsgItems[]={GetMsg(MExtraction),FileMsg, ProgressMsg1, ProgressMsg2};
                            Info.Message(Info.ModuleNumber,WaitMessage ? FMSG_LEFTALIGN|FMSG_KEEPBACKGROUND:FMSG_LEFTALIGN,NULL,MsgItems,sizeof(MsgItems)/sizeof(MsgItems[0]),0);
                            WaitMessage=TRUE;
                        }       
                    }
                    readed = _read(f1, buf, BUF_SIZE);                                       
                    pos = _tell(f1);                                                                                
                    if (pos > endpos) readed = readed - (pos - endpos);
                    _write(f2, buf, readed);
                    ProcessedBytes += readed;
                    pos = _tell(f1);    
                    WaitMessage=FALSE;
                }            
                _close(f2);
                _close(f1);            
                SetFileAttributes(c, FILE_ATTRIBUTE_ARCHIVE);            
                if (!OpMode & OPM_SILENT) if (CheckForKey(VK_ESCAPE))  break;
            }
        }
        Free_copyfiles();
        return TRUE;
    } else { //For plugin manager    
        ADDPLUGININFO *PI;
        for (int I = 0; I < copyfiles.size(); I++){
            if (copyfiles[I].FileName[strlen(copyfiles[I].FileName)-1]=='\\'){
                char *c = my_substr(copyfiles[I].FileName, 0, strlen(copyfiles[I].FileName)-1);
                FSF.sprintf(MyDestPath, "%s\\%s", DestPath, c);
                my_free(c);
                CreateDirectory(MyDestPath, NULL);            
            } else {    
                char *d = ExtractPath(copyfiles[I].FileName);
                if (strlen(d)>0) FSF.sprintf(MyDestPath, "%s\\%s", DestPath, d); 
                else strcpy(MyDestPath, DestPath);
                my_free(d);
            
                d = ExtractName(copyfiles[I].FileName);
                FSF.sprintf(MyDestFile, "%s", d);
                my_free(d);

                char c[MAX_PATH];
                FSF.sprintf(c, "%s\\%s", MyDestPath, MyDestFile);

                f2 = _open(c, _O_RDONLY|_O_BINARY);
                if (f2!=-1) {
                    _close(f2);
                    if (Owervrite==3) continue;
                    if (Owervrite == 0||Owervrite == 1)
                    if (!OpMode & OPM_SILENT) Owervrite = OverwritePrompt(MyDestFile);
                    if (Owervrite==-1) break;
                    if (Owervrite==3||Owervrite==1) continue;
                }                   
            
                FSF.sprintf(c, "%s\\%s", MyDestPath, MyDestFile);                
            
                f2 = _open(c, _O_CREAT|_O_WRONLY|_O_BINARY);                                
                
                PI = (ADDPLUGININFO*)copyfiles[I].UserData.Data;

                FSF.sprintf((char*)buf, GetMsg(MInfoOptString), copyfiles[I].FileName);
                _write(f2, buf, lstrlen((char*)buf)+1);
                _write(f2, "\xD\xA\xD\xA", 4);

                FSF.sprintf((char*)buf, GetMsg(MInfoVer), copyfiles[I].Description);
                _write(f2, buf, lstrlen((char*)buf)+1);
                _write(f2, "\xD\xA", 2);
                
                char v[30];
                Ver2Char(PI->RipVer, v);

                FSF.sprintf((char*)buf, GetMsg(MInfoRipVer), v);
                _write(f2, buf, lstrlen((char*)buf)+1);                
                _write(f2, "\xD\xA\xD\xA", 4);

                FSF.sprintf((char*)buf, GetMsg(MInfoCopyright), PI->Copy);
                _write(f2, buf, lstrlen((char*)buf)+1);
                _write(f2, "\xD\xA", 2);

                FSF.sprintf((char*)buf, GetMsg(MInfoPath), PI->FilePath);
                _write(f2, buf, lstrlen((char*)buf)+1);
                _write(f2, "\xD\xA", 2);

                char *types[8] = {GetMsg(MInfoTypeGraph), 
                                  GetMsg(MInfoTypeVideo), 
                                  GetMsg(MInfoTypeSound),
                                  GetMsg(MInfoTypePack),
                                  GetMsg(MInfoTypeOther),
                                  GetMsg(MInfoTypeMusic),
                                  GetMsg(MInfoTypeText),
                                  GetMsg(MInfoTypeExe)};

                FSF.sprintf((char*)buf, GetMsg(MInfoType), types[PI->Type]);
                _write(f2, buf, lstrlen((char*)buf)+1);                

                _close(f2);
                
                SetFileAttributes(c, FILE_ATTRIBUTE_ARCHIVE);            
                if (!OpMode & OPM_SILENT) if (CheckForKey(VK_ESCAPE))  break;
            }
        }
        Free_copyfiles();

        //This for refuse reset selection
        if (!OpMode&OPM_SILENT) return -1;
        else return TRUE;
    }
    Free_copyfiles();
    return TRUE;
}
コード例 #22
0
ファイル: DDS.cpp プロジェクト: doodoonovitch/GameTech
//--------------------------------------------------------------------------------------
bool LoadDDSDataFromFile(const std::string & fileName,
                         std::unique_ptr<uint8_t[]>& ddsData,
                         DDS_HEADER** header,
                         uint8_t** bitData,
                         size_t* bitSize
                        )
{
    int file = -1;
    bool ret = false;

    errno_t err = _sopen_s(&file, fileName.c_str(), _O_BINARY | _O_RDONLY, _SH_DENYNO, _S_IREAD | _S_IWRITE);
    if (err != 0)
    {
        PRINT_ERROR("Loading '%s' failed : cannot open the file ! (errno = %i)\n", fileName.c_str(), err);
        return false;
    }

    __int64 fileSize = _filelength(file);

    // File is too big for 32-bit allocation, so reject read
    if (fileSize > ULONG_MAX)
    {
        PRINT_ERROR("Loading '%s' failed : the file is too big!\n", fileName.c_str());
        goto EXIT_PROC;
    }

    // Need at least enough data to fill the header and magic number to be a valid DDS
    if (fileSize < (sizeof(DDS_HEADER) + sizeof(DWORD)))
    {
        PRINT_ERROR("Loading '%s' failed : the file is too small!\n", fileName.c_str());
        goto EXIT_PROC;
    }

    // create enough space for the file data
    ddsData.reset(new uint8_t[fileSize]);
    if (!ddsData)
    {
        PRINT_ERROR("Loading '%s' failed : out of memory!\n", fileName.c_str());
        goto EXIT_PROC;
    }

    // read the data in
    uint32_t bytesread = 0;
    if ((bytesread = _read(file, ddsData.get(), (uint32_t)fileSize)) != fileSize)
    {
        PRINT_ERROR("Loading '%s' failed : read error (%li/%li byte(s) read)!\n", fileName.c_str(), bytesread, fileSize);
        goto EXIT_PROC;
    }

    // DDS files always start with the same magic number ("DDS ")
    uint32_t dwMagicNumber = *(const uint32_t*)(ddsData.get());
    if (dwMagicNumber != DDS_MAGIC)
    {
        PRINT_ERROR("Loading '%s' failed : the file does not contain the DDS signature!\n", fileName.c_str());
        goto EXIT_PROC;
    }

    DDS_HEADER* hdr = reinterpret_cast<DDS_HEADER*>(ddsData.get() + sizeof(uint32_t));

    // Verify header to validate DDS file
    if (hdr->dwSize != sizeof(DDS_HEADER)
            || hdr->ddspf.dwSize != sizeof(DDS_PIXELFORMAT))
    {
        PRINT_ERROR("Loading '%s' failed : wrong DDS header!\n", fileName.c_str());
        goto EXIT_PROC;
    }

    ptrdiff_t offset = sizeof(uint32_t) + sizeof(DDS_HEADER);

    if (hdr->ddspf.dwFlags & DDS_FOURCC)
    {
        // Check for DX10 extension
        if (MAKEFOURCC('D', 'X', '1', '0') == hdr->ddspf.dwFourCC)
        {
            // Must be long enough for both headers and magic value
            if (fileSize < (sizeof(DDS_HEADER) + sizeof(uint32_t) + sizeof(DDS_HEADER_DXT10)))
            {
                PRINT_ERROR("Loading '%s' failed : the file should have the DXT10 header!\n", fileName.c_str());
                goto EXIT_PROC;
            }

            offset += sizeof(DDS_HEADER_DXT10);
        }
    }

    // setup the pointers in the process request
    *header = hdr;
    *bitData = ddsData.get() + offset;
    *bitSize = fileSize - offset;

    ret = true;

EXIT_PROC:
    if (file != -1)
        _close(file);

    return ret;
}
コード例 #23
0
ファイル: ksdump.c プロジェクト: secure-endpoints/netidmgr
int main(int argc, char ** argv)
{
    keystore_t * ks = NULL;
    int fd = -1;
    long len;
    void * buffer = NULL;
    int read_len;
    khm_int32 rv;

    __try {
        if (argc != 2) {
            usage(argv[0]);
            return 0;
        }

        fprintf(stderr, "Trying to open file %s\n", argv[1]);

        _sopen_s(&fd, argv[1], _O_RDONLY | _O_BINARY | _O_SEQUENTIAL, _SH_DENYNO, _S_IREAD);

        if (fd == -1) {
            perror("_open");
            return 1;
        }

        len = _lseek(fd, 0, SEEK_END);
        if (len == -1) {
            perror("_lseek");
            return 1;
        }

        _lseek(fd, 0, SEEK_SET);

        buffer = malloc(len);

        read_len = _read(fd, buffer, len);

        if (read_len == -1) {
            perror("_read");
            return 1;
        }

        if (read_len != len) {
            fprintf(stderr, "Expected read len %ld.  Actual len %d\n", len, read_len);
            return 1;
        }

        if (KHM_FAILED(rv = ks_keystore_unserialize(buffer, len, &ks))) {
            fprintf(stderr, "ks_keystore_unserialize() == %d\n", rv);
            return 1;
        }

        dump_keystore(ks);

    } __finally {
        if (fd != -1)
            _close(fd);

        if (buffer != NULL)
            free(buffer);

        if (ks != NULL)
            ks_keystore_release(ks);
    }

    return 0;
}
コード例 #24
0
ファイル: editor.c プロジェクト: MatiasNAmendola/potatoes
void speed()
{
        int keyboard = _open("/dev/keyboard", 0, 0);
        int stdin = _open("/dev/stdin", 0, 0);
        char ch;
        int fd = _open(active_proc->name, 0, 0);
        int size = _seek(fd, 0, SEEK_END);
        size++; //terminating '\0'
        _seek(fd, 0, SEEK_SET);
        char* str = _malloc(size);
        bzero(str, size);
        _read(fd, str, size);
        line *startline = _malloc(sizeof(line));
        startline->num_chars=0;
        startline->offset=0;
        startline->next = NULL;
        startline->prev = NULL;
        line * actualline = startline;

        int pos = 0;
        while (str[pos]!='\0') {
                _printf("%c", str[pos]);
                if(str[pos] == '\n' || str[pos] == '\t') {
                        NEXT_LINE
                } else {
                        actualline->num_chars++;
                }
                pos++;
                if(pos == size - 1) { //terminating \0
                        size*=2;
                        str = resize_buf(size, str);
                }
        }
        _close(fd);

        //flush stdin
        while (_read(stdin, &ch, sizeof(ch)) != 0) ;

        while (!keydown(ESCAPE, keyboard)) {
                if(pos == size - 1) { //terminating \0
                        size *= 2;
                        str = resize_buf(size, str);
                }
                ch = _fgetch(stdin);
                switch(ch){
                case '\a':
                        break;
                case '\b':
                        if(actualline == startline && startline->num_chars == 0) { //nothing to erase
                                break;
                        }
                        if(str[pos - 1]=='\n' || str[pos - 1]=='\t') { //erase '\n' or '\t'
                                PREV_LINE
                        } else { //erase 1 character
                                actualline->num_chars--;
                                _printf("%c", ch);
                        }
                        str[--pos] = '\0';
                        if (pos == size / 4 - 1) {
                                size /= 2;
                                str = resize_buf(size, str);
                        }
                        break;
                default:
                        _printf("%c", ch);
                        str[pos] = ch;
                        if(ch == '\n' || ch == '\t') {
                                NEXT_LINE
                        } else {
                                actualline->num_chars++;
                        }
                        pos++;
                }
        }

        //flush stdin
        while (_read(stdin, &ch, sizeof(ch)) != 0) ;
        //DUMP_LINES
        _unlink(active_proc->name);
        //        fd = _open(active_proc->name, 0, 0);
        //        int fsize = _seek(fd, 0, SEEK_END);
        //        _close(fd);
        //        fd = _open(active_proc->name, 0, 0);
        //        char* nullstring = _malloc(fsize);
        //        bzero(nullstring, fsize);
        //        _free(nullstring);
        //        _write(fd, nullstring, fsize);
        //        _close(fd);

        fd = _open(active_proc->name, O_CREAT, 0);
        _write(fd, str, strlen(str));
        for(line *temp = startline; temp != NULL; temp = temp->next) {
                _free(temp);
        }
        _free(str);
        _close(keyboard);
        _close(stdin);
        _close(fd);
        _exit(0);
}
コード例 #25
0
ファイル: ppputil.cpp プロジェクト: bhaggerty/wwiv
int main(int argc, char *argv[])
{
	UNREFERENCED_PARAMETER( argc );

    char szConfigFileName[ _MAX_PATH ];
	strcpy(szConfigFileName, "CONFIG.DAT");
	int hConfigFile = _open(szConfigFileName, O_RDONLY | O_BINARY);
	if (hConfigFile < 0)
	{
		return 1;
	}
	_read(hConfigFile, &syscfg, sizeof(configrec));
	_close(hConfigFile);
	
	std::string arg = argv[1];
	std::transform( arg.begin(), arg.end(), arg.begin(),  (int(*)(int)) toupper );
	if ( arg == "NETLOG" )
	{
		strcpy(net_name, argv[6]);
		unsigned int sy = atoi(argv[2]);
		unsigned long sent = atol(argv[3]);
		unsigned long recd = atol(argv[4]);
		if (!write_netlog(sy, sent, recd, argv[5]))
		{
			return 1;
		}
	}
	
	if ( arg == "TRIM" )
	{
		strcpy(net_data, argv[2]);
		trim_log();
	}
	
	if ( arg == "PURGE" ) 
	{
		strcpy(net_data, argv[2]);
		int i = atoi(argv[3]);
		purge_sent( i );
	}
	
	if ( arg == "CHUNK" ) 
	{
		strcpy(net_data, argv[2]);
		std::string fileName = argv[3];
		std::stringstream ss;
		 ss << net_data << "INBOUND\\" << fileName; 
		 std::string fullPathName = ss.str();
		/* if (!chunk(fullPathName.c_str()))
		{
			_unlink(fullPathName.c_str());
		}  */

		 if (!chunk((char*)fullPathName.c_str()))
		 {
			 _unlink((char*)fullPathName.c_str());
		 }

	}
	
	return 0;
}
コード例 #26
0
ファイル: bt_open.c プロジェクト: edgar-pek/PerspicuOS
/*
 * __BT_OPEN -- Open a btree.
 *
 * Creates and fills a DB struct, and calls the routine that actually
 * opens the btree.
 *
 * Parameters:
 *	fname:	filename (NULL for in-memory trees)
 *	flags:	open flag bits
 *	mode:	open permission bits
 *	b:	BTREEINFO pointer
 *
 * Returns:
 *	NULL on failure, pointer to DB on success.
 *
 */
DB *
__bt_open(const char *fname, int flags, int mode, const BTREEINFO *openinfo, int dflags)
{
	struct stat sb;
	BTMETA m;
	BTREE *t;
	BTREEINFO b;
	DB *dbp;
	pgno_t ncache;
	ssize_t nr;
	int machine_lorder, saved_errno;

	t = NULL;

	/*
	 * Intention is to make sure all of the user's selections are okay
	 * here and then use them without checking.  Can't be complete, since
	 * we don't know the right page size, lorder or flags until the backing
	 * file is opened.  Also, the file's page size can cause the cachesize
	 * to change.
	 */
	machine_lorder = byteorder();
	if (openinfo) {
		b = *openinfo;

		/* Flags: R_DUP. */
		if (b.flags & ~(R_DUP))
			goto einval;

		/*
		 * Page size must be indx_t aligned and >= MINPSIZE.  Default
		 * page size is set farther on, based on the underlying file
		 * transfer size.
		 */
		if (b.psize &&
		    (b.psize < MINPSIZE || b.psize > MAX_PAGE_OFFSET + 1 ||
		    b.psize & (sizeof(indx_t) - 1) ))
			goto einval;

		/* Minimum number of keys per page; absolute minimum is 2. */
		if (b.minkeypage) {
			if (b.minkeypage < 2)
				goto einval;
		} else
			b.minkeypage = DEFMINKEYPAGE;

		/* If no comparison, use default comparison and prefix. */
		if (b.compare == NULL) {
			b.compare = __bt_defcmp;
			if (b.prefix == NULL)
				b.prefix = __bt_defpfx;
		}

		if (b.lorder == 0)
			b.lorder = machine_lorder;
	} else {
		b.compare = __bt_defcmp;
		b.cachesize = 0;
		b.flags = 0;
		b.lorder = machine_lorder;
		b.minkeypage = DEFMINKEYPAGE;
		b.prefix = __bt_defpfx;
		b.psize = 0;
	}

	/* Check for the ubiquitous PDP-11. */
	if (b.lorder != BIG_ENDIAN && b.lorder != LITTLE_ENDIAN)
		goto einval;

	/* Allocate and initialize DB and BTREE structures. */
	if ((t = (BTREE *)calloc(1, sizeof(BTREE))) == NULL)
		goto err;
	t->bt_fd = -1;			/* Don't close unopened fd on error. */
	t->bt_lorder = b.lorder;
	t->bt_order = NOT;
	t->bt_cmp = b.compare;
	t->bt_pfx = b.prefix;
	t->bt_rfd = -1;

	if ((t->bt_dbp = dbp = (DB *)calloc(1, sizeof(DB))) == NULL)
		goto err;
	if (t->bt_lorder != machine_lorder)
		F_SET(t, B_NEEDSWAP);

	dbp->type = DB_BTREE;
	dbp->internal = t;
	dbp->close = __bt_close;
	dbp->del = __bt_delete;
	dbp->fd = __bt_fd;
	dbp->get = __bt_get;
	dbp->put = __bt_put;
	dbp->seq = __bt_seq;
	dbp->sync = __bt_sync;

	/*
	 * If no file name was supplied, this is an in-memory btree and we
	 * open a backing temporary file.  Otherwise, it's a disk-based tree.
	 */
	if (fname) {
		switch (flags & O_ACCMODE) {
		case O_RDONLY:
			F_SET(t, B_RDONLY);
			break;
		case O_RDWR:
			break;
		case O_WRONLY:
		default:
			goto einval;
		}

		if ((t->bt_fd = _open(fname, flags, mode)) < 0)
			goto err;

	} else {
		if ((flags & O_ACCMODE) != O_RDWR)
			goto einval;
		if ((t->bt_fd = tmp()) == -1)
			goto err;
		F_SET(t, B_INMEM);
	}

	if (_fcntl(t->bt_fd, F_SETFD, 1) == -1)
		goto err;

	if (_fstat(t->bt_fd, &sb))
		goto err;
	if (sb.st_size) {
		if ((nr = _read(t->bt_fd, &m, sizeof(BTMETA))) < 0)
			goto err;
		if (nr != sizeof(BTMETA))
			goto eftype;

		/*
		 * Read in the meta-data.  This can change the notion of what
		 * the lorder, page size and flags are, and, when the page size
		 * changes, the cachesize value can change too.  If the user
		 * specified the wrong byte order for an existing database, we
		 * don't bother to return an error, we just clear the NEEDSWAP
		 * bit.
		 */
		if (m.magic == BTREEMAGIC)
			F_CLR(t, B_NEEDSWAP);
		else {
			F_SET(t, B_NEEDSWAP);
			M_32_SWAP(m.magic);
			M_32_SWAP(m.version);
			M_32_SWAP(m.psize);
			M_32_SWAP(m.free);
			M_32_SWAP(m.nrecs);
			M_32_SWAP(m.flags);
		}
		if (m.magic != BTREEMAGIC || m.version != BTREEVERSION)
			goto eftype;
		if (m.psize < MINPSIZE || m.psize > MAX_PAGE_OFFSET + 1 ||
		    m.psize & (sizeof(indx_t) - 1) )
			goto eftype;
		if (m.flags & ~SAVEMETA)
			goto eftype;
		b.psize = m.psize;
		F_SET(t, m.flags);
		t->bt_free = m.free;
		t->bt_nrecs = m.nrecs;
	} else {
		/*
		 * Set the page size to the best value for I/O to this file.
		 * Don't overflow the page offset type.
		 */
		if (b.psize == 0) {
			b.psize = sb.st_blksize;
			if (b.psize < MINPSIZE)
				b.psize = MINPSIZE;
			if (b.psize > MAX_PAGE_OFFSET + 1)
				b.psize = MAX_PAGE_OFFSET + 1;
		}

		/* Set flag if duplicates permitted. */
		if (!(b.flags & R_DUP))
			F_SET(t, B_NODUPS);

		t->bt_free = P_INVALID;
		t->bt_nrecs = 0;
		F_SET(t, B_METADIRTY);
	}

	t->bt_psize = b.psize;

	/* Set the cache size; must be a multiple of the page size. */
	if (b.cachesize && b.cachesize & (b.psize - 1) )
		b.cachesize += (~b.cachesize & (b.psize - 1) ) + 1;
	if (b.cachesize < b.psize * MINCACHE)
		b.cachesize = b.psize * MINCACHE;

	/* Calculate number of pages to cache. */
	ncache = (b.cachesize + t->bt_psize - 1) / t->bt_psize;

	/*
	 * The btree data structure requires that at least two keys can fit on
	 * a page, but other than that there's no fixed requirement.  The user
	 * specified a minimum number per page, and we translated that into the
	 * number of bytes a key/data pair can use before being placed on an
	 * overflow page.  This calculation includes the page header, the size
	 * of the index referencing the leaf item and the size of the leaf item
	 * structure.  Also, don't let the user specify a minkeypage such that
	 * a key/data pair won't fit even if both key and data are on overflow
	 * pages.
	 */
	t->bt_ovflsize = (t->bt_psize - BTDATAOFF) / b.minkeypage -
	    (sizeof(indx_t) + NBLEAFDBT(0, 0));
	if (t->bt_ovflsize < NBLEAFDBT(NOVFLSIZE, NOVFLSIZE) + sizeof(indx_t))
		t->bt_ovflsize =
		    NBLEAFDBT(NOVFLSIZE, NOVFLSIZE) + sizeof(indx_t);

	/* Initialize the buffer pool. */
	if ((t->bt_mp =
	    mpool_open(NULL, t->bt_fd, t->bt_psize, ncache)) == NULL)
		goto err;
	if (!F_ISSET(t, B_INMEM))
		mpool_filter(t->bt_mp, __bt_pgin, __bt_pgout, t);

	/* Create a root page if new tree. */
	if (nroot(t) == RET_ERROR)
		goto err;

	/* Global flags. */
	if (dflags & DB_LOCK)
		F_SET(t, B_DB_LOCK);
	if (dflags & DB_SHMEM)
		F_SET(t, B_DB_SHMEM);
	if (dflags & DB_TXN)
		F_SET(t, B_DB_TXN);

	return (dbp);

einval:	errno = EINVAL;
	goto err;

eftype:	errno = EFTYPE;
	goto err;

err:	saved_errno = errno;
	if (t) {
		if (t->bt_dbp)
			free(t->bt_dbp);
		if (t->bt_fd != -1)
			(void)_close(t->bt_fd);
		free(t);
	}
	errno = saved_errno;
	return (NULL);
}
コード例 #27
0
ファイル: defuse.cpp プロジェクト: nixz/covise
int defuse(const char *fileName)
{
    numtextures = 0;

    int fd;
    fd = _open(fileName, O_RDONLY | O_BINARY);
    if (fd <= 0)
    {
        fprintf(stderr, "could not open %s for reading\n", fileName);
        return -1;
    }
    //fprintf(stderr,"converting %s\n",argv[filenum]);
    struct stat statbuf;
    fstat(fd, &statbuf);
    size = statbuf.st_size;
    buf = new char[size + 1000];
    buf2 = new char[size + 100000];
    readpos = buf;
    writepos = buf2;
    memset(buf, 0, size + 1000);
    if ((buf2 == NULL) || (buf == NULL))
    {
        fprintf(stderr, "out of memory\n");
        return -1;
    }
    _read(fd, buf, size);
    int numref = 0;
    numtextures = 0;
    while (findTexture())
    {
        texture *currentTex = getTexture(currentTexturename, currentEnvironment, currentBlendMode);
        if (currentTex)
        {
            // already defined texture
            sprintf(writepos, " USE %s \n", currentTex->defName);
            writepos += strlen(writepos);
            numref++;
        }
        else
        {
            // new texture
            currentTex = new texture(currentTexturename, currentEnvironment, currentBlendMode);
            //fprintf(stderr,"currentEnvironment %d\n" , currentEnvironment);
            addTexture(currentTex);
            sprintf(writepos, " DEF %s ImageTexture{ url \"%s\"\n", currentTex->defName, currentTex->name);
            writepos += strlen(writepos);
            if (currentTex->env)
            {
                sprintf(writepos, " environment TRUE\n");
                writepos += strlen(writepos);
            }
            if (currentTex->blendMode > 0)
            {
                sprintf(writepos, " blendMode %d\n", currentTex->blendMode);
                writepos += strlen(writepos);
            }
            sprintf(writepos, "}\n");
            writepos += strlen(writepos);
        }
    }

    _close(fd);
    //fprintf(stderr,"found %d textures, %d references\n",numtextures, numref);
    if (numref == 0)
    {
        //fprintf(stderr,"%s unchanged\n",argv[filenum]);
    }
    else
    {

        fd = _open(fileName, O_WRONLY | O_CREAT | O_BINARY | O_TRUNC, 0777);
        if (fd <= 0)
        {
            fprintf(stderr, "could not open %s for writing\n", fileName);
            return -1;
        }
        _write(fd, buf2, (int)(writepos - buf2));
        _close(fd);
    }
    delete[] buf;
    delete[] buf2;
    return 0;
}
コード例 #28
0
ファイル: 71.c プロジェクト: FTCr/Siemens
int InitLGP(void)
{
	FSTATS fs;
	unsigned int err;
	char path[256];
	strcpy(path, dir_path);
	strcat(path, "\\");
	strcat(path, "71.txt");
	
	if (GetFileStats(path, &fs, &err) == -1) return 0;

	int fp = _open(path, A_ReadOnly + A_BIN, P_READ, &err);
	if (fp == -1) return 0;

	char *buffer = malloc(fs.size + 1);
	buffer[fs.size] = '\0';
	_read(fp, buffer, fs.size, &err);
	
	char tmp[128];
	char tmp_id[4];
	unsigned int tmp_id_len = 0;
	unsigned int wait_num = 1;
	
	unsigned int pos = 0, len = 0;
	while (pos <= fs.size)
	{
		if (buffer[pos] == '\n' || buffer[pos] == '\r' || buffer[pos] == '\0')
		{
			if (len)
			{
				_71_lgp = realloc(_71_lgp, sizeof(_71_LGP) * (_71_lgp_total + 1));
				_71_lgp[_71_lgp_total].str = malloc(len + 1);
				
				tmp[len] = '\0';
				strcpy(_71_lgp[_71_lgp_total].str, tmp);
				sscanf(tmp_id, "%d", &(_71_lgp[_71_lgp_total].id));
				len = 0;
				tmp_id_len = 0;
				wait_num = 1;
				
				_71_lgp_total++;
			}
		}
		else
		{
			if (wait_num)
			{
				if (buffer[pos] != ',')
					tmp_id[tmp_id_len++] = buffer[pos];
				else
				{
					tmp_id[tmp_id_len] = '\0';
					wait_num = 0;
				}
			}
			else
			{
				tmp[len++] = buffer[pos];
			}
		}
		pos++;
	}
	mfree(buffer);
	_close(fp, &err);
	return 1;
}
コード例 #29
0
ファイル: kernel.c プロジェクト: berysaidi/singpolyma-kernel
int main(void) {
	unsigned int stacks[TASK_LIMIT][STACK_SIZE];
	unsigned int *tasks[TASK_LIMIT];
	struct pipe_ringbuffer pipes[PIPE_LIMIT];
	size_t task_count = 0;
	size_t current_task = 0;
	size_t i;

	*(PIC + VIC_INTENABLE) = PIC_TIMER01;

	*TIMER0 = 10000;
	*(TIMER0 + TIMER_CONTROL) = TIMER_EN | TIMER_PERIODIC
	                            | TIMER_32BIT | TIMER_INTEN;

	tasks[task_count] = init_task(stacks[task_count], &first);
	task_count++;

	/* Initialize all pipes */
	for(i = 0; i < PIPE_LIMIT; i++) {
		pipes[i].start = pipes[i].end = 0;
	}

	while(1) {
		tasks[current_task] = activate(tasks[current_task]);
		tasks[current_task][-1] = TASK_READY;

		switch(tasks[current_task][2+7]) {
			case 0x1: /* fork */
				if(task_count == TASK_LIMIT) {
					/* Cannot create a new task, return error */
					tasks[current_task][2+0] = -1;
				} else {
					/* Compute how much of the stack is used */
					size_t used = stacks[current_task] + STACK_SIZE
					              - tasks[current_task];
					/* New stack is END - used */
					tasks[task_count] = stacks[task_count] + STACK_SIZE - used;
					/* Copy only the used part of the stack */
					memcpy(tasks[task_count], tasks[current_task],
					       used*sizeof(*tasks[current_task]));
					/* Set return values in each process */
					tasks[current_task][2+0] = task_count;
					tasks[task_count][2+0] = 0;
					/* There is now one more task */
					task_count++;
				}
				break;
			case 0x2: /* getpid */
				tasks[current_task][2+0] = current_task;
				break;
			case 0x3: /* write */
				_write(tasks[current_task], tasks, task_count, pipes);
				break;
			case 0x4: /* read */
				_read(tasks[current_task], tasks, task_count, pipes);
				break;
			case 0x5: /* interrupt_wait */
				/* Enable interrupt */
				*(PIC + VIC_INTENABLE) = tasks[current_task][2+0];
				/* Block task waiting for interrupt to happen */
				tasks[current_task][-1] = TASK_WAIT_INTR;
				break;
			default: /* Catch all interrupts */
				if((int)tasks[current_task][2+7] < 0) {
					unsigned int intr = (1 << -tasks[current_task][2+7]);

					if(intr == PIC_TIMER01) {
						/* Never disable timer. We need it for pre-emption */
						if(*(TIMER0 + TIMER_MIS)) { /* Timer0 went off */
							*(TIMER0 + TIMER_INTCLR) = 1; /* Clear interrupt */
						}
					} else {
						/* Disable interrupt, interrupt_wait re-enables */
						*(PIC + VIC_INTENCLEAR) = intr;
					}
					/* Unblock any waiting tasks
						XXX: nondeterministic unblock order
					*/
					for(i = 0; i < task_count; i++) {
						if(tasks[i][-1] == TASK_WAIT_INTR && tasks[i][2+0] == intr) {
							tasks[i][-1] = TASK_READY;
						}
					}
				}
		}

		/* Select next TASK_READY task */
		while(TASK_READY != tasks[current_task = (current_task + 1) % task_count][-1]);
	}

	return 0;
}
コード例 #30
0
//
// Load an ELF [binary] image 
//
//
// Note that in case of multicore and the core we wanna load the 
// image for is not in the same endianness that the core we run 
// redboot from, have to invert bytes on 16-bit boundary 
// (16-bit memory)
//
static unsigned long
load_elf_image(getc_t getc, unsigned long base, bool swap16bit)
{
#ifdef CYGSEM_REDBOOT_ELF
    Elf32_Ehdr ehdr;
#define MAX_PHDR 8
    Elf32_Phdr phdr[MAX_PHDR];
    unsigned long offset = 0;
    int phx, len, ch;
    unsigned char *addr, *addr_swap;
    unsigned long addr_offset = 0;
    unsigned long highest_address = 0;
    unsigned long lowest_address = 0xFFFFFFFF;
    unsigned char *SHORT_DATA = "Short data reading ELF file\n";

    // Read the header
    if (_read(getc, (unsigned char *)&ehdr, sizeof(ehdr)) != sizeof(ehdr)) {
        diag_printf("Can't read ELF header\n");
        redboot_getc_terminate(true);
        return 0;
    }
    offset += sizeof(ehdr);    
#if 0 // DEBUG
    diag_printf("Type: %d, Machine: %d, Version: %d, Entry: %p, PHoff: %p/%d/%d, SHoff: %p/%d/%d\n",
                ehdr.e_type, ehdr.e_machine, ehdr.e_version, ehdr.e_entry, 
                ehdr.e_phoff, ehdr.e_phentsize, ehdr.e_phnum,
                ehdr.e_shoff, ehdr.e_shentsize, ehdr.e_shnum);
#endif
    if (ehdr.e_type != ET_EXEC) {
        diag_printf("Only absolute ELF images supported\n");
        redboot_getc_terminate(true);
        return 0;
    }
    if (ehdr.e_phnum > MAX_PHDR) {
        diag_printf("Too many program headers\n");
        redboot_getc_terminate(true);
        return 0;
    }
    while (offset < ehdr.e_phoff) {
        if ((*getc)() < 0) {
            diag_printf(SHORT_DATA);
            redboot_getc_terminate(true);
            return 0;
        }
        offset++;
    }
    for (phx = 0;  phx < ehdr.e_phnum;  phx++) {
        if (_read(getc, (unsigned char *)&phdr[phx], sizeof(phdr[0])) != sizeof(phdr[0])) {
            diag_printf("Can't read ELF program header\n");
            redboot_getc_terminate(true);
            return 0;
        }
#if 0 // DEBUG
        diag_printf("Program header: type: %d, off: %p, va: %p, pa: %p, len: %d/%d, flags: %d\n",
                    phdr[phx].p_type, phdr[phx].p_offset, phdr[phx].p_vaddr, phdr[phx].p_paddr,
                    phdr[phx].p_filesz, phdr[phx].p_memsz, phdr[phx].p_flags);
#endif
        offset += sizeof(phdr[0]);
    }
    if (base) {
        // Set address offset based on lowest address in file.
        addr_offset = 0xFFFFFFFF;
        for (phx = 0;  phx < ehdr.e_phnum;  phx++) {
#ifdef CYGOPT_REDBOOT_ELF_VIRTUAL_ADDRESS     
            if ((phdr[phx].p_type == PT_LOAD) && (phdr[phx].p_vaddr < addr_offset)) {
                addr_offset = phdr[phx].p_vaddr;
#else
            if ((phdr[phx].p_type == PT_LOAD) && (phdr[phx].p_paddr < addr_offset)) {
                addr_offset = phdr[phx].p_paddr;
#endif
            }
        }
        addr_offset = (unsigned long)base - addr_offset;
    } else {
        addr_offset = 0;
    }
    for (phx = 0;  phx < ehdr.e_phnum;  phx++) {
        if (phdr[phx].p_type == PT_LOAD) {
            // Loadable segment
#ifdef CYGOPT_REDBOOT_ELF_VIRTUAL_ADDRESS
            addr = (unsigned char *)phdr[phx].p_vaddr;
#else     
            addr = (unsigned char *)phdr[phx].p_paddr;
#endif
            len = phdr[phx].p_filesz;
            if ((unsigned long)addr < lowest_address) {
                lowest_address = (unsigned long)addr;
            }
            addr += addr_offset;
            if (offset > phdr[phx].p_offset) {
                if ((phdr[phx].p_offset + len) < offset) {
                    diag_printf("Can't load ELF file - program headers out of order\n");
                    redboot_getc_terminate(true);
                    return 0;
                }
                addr += offset - phdr[phx].p_offset;
            } else {
                while (offset < phdr[phx].p_offset) {
                    if ((*getc)() < 0) {
                        diag_printf(SHORT_DATA);
                        redboot_getc_terminate(true);
                        return 0;
                    }
                    offset++;
                }
            }

            // Copy data into memory
            while (len-- > 0) {
#ifdef CYGSEM_REDBOOT_VALIDATE_USER_RAM_LOADS
                if (!valid_address(addr)) {
                    redboot_getc_terminate(true);
                    diag_printf("*** Abort! Attempt to load ELF data to address: %p which is not in RAM\n", (void*)addr);
                    return 0;
                }
#endif
                if ((ch = (*getc)()) < 0) {
                    diag_printf(SHORT_DATA);
                    redboot_getc_terminate(true);
                    return 0;
                }
     
                /* In case of multicore and the core we wanna load the image for is not in the same endianness
	    	that the core we run redboot from, have to invert bytes on 16-bit boundary (16-bit memory)*/
                if(swap16bit){
                    // addr is even, have to write char data to the last address
                    if(((unsigned long)addr)%2){
                        addr_swap=addr-1;
                        *addr_swap = ch;
                    }
                    // addr is odd, have to write char data to the next address
                    else{
                        addr_swap=addr+1;
                       *addr_swap = ch;
                    }
                    addr++;
                }
                else {
                    *addr++ = ch;
            	}
                offset++;
                if ((unsigned long)(addr-addr_offset) > highest_address) {
                    highest_address = (unsigned long)(addr - addr_offset);
                }
            }
        }
    }

    // Save load base/top and entry
    if (base) {
        load_address = base;
        load_address_end = base + (highest_address - lowest_address);
        entry_address = base + (ehdr.e_entry - lowest_address);
    } else {
        load_address = lowest_address;
        load_address_end = highest_address;
        entry_address = ehdr.e_entry;
    }

    // nak everything to stop the transfer, since redboot
    // usually doesn't read all the way to the end of the
    // elf files.
    redboot_getc_terminate(true);
    if (addr_offset) diag_printf("Address offset = %p\n", (void *)addr_offset);
    diag_printf("Entry point: %p, address range: %p-%p\n", 
                (void*)entry_address, (void *)load_address, (void *)load_address_end);
    return 1;
#else // CYGSEM_REDBOOT_ELF
    diag_printf("Loading ELF images not supported\n");
    return 0;
#endif // CYGSEM_REDBOOT_ELF
}