Пример #1
0
ino get_first_free_block(void) {
    char freeBlockBitmap[BLOCK_SIZE];
    ReadBlock(FREE_BLOCK_BITMAP, freeBlockBitmap);

    int freeBlockNumber = 0;
    int index;
    for (index = 6; index < N_BLOCK_ON_DISK; ++index) {
        if (freeBlockBitmap[index]) {
            printf("GLOFS: Saisie bloc %i\n", index);
            freeBlockNumber = index;
            freeBlockBitmap[index] = 0;
            break;
        }
    }

    WriteBlock(FREE_BLOCK_BITMAP, freeBlockBitmap);

    return freeBlockNumber;
}
Пример #2
0
extern "C" BOOL	LoadPlugin (char *plugin)
{
	int w;
	char filename[MAX_PATH];
	FILE *PLUGIN;
	char *filedata;
	BOOL status;
	
	strcpy(filename,Path_PLUG);
	strcat(filename,plugin);
	
	if ((PLUGIN = fopen(filename,"rb")) == NULL)
	{
		MessageBox(topHWnd,"Failed to open plugin file!","LoadPlugin",MB_OK | MB_ICONERROR);
		return FALSE;
	}
	if (!WriteCommand(0x4B,0x00,0x04,0x04,0xB4))	// write to CPU space
	{	// failed to load plugin
		fclose(PLUGIN);
		return FALSE;
	}
	fseek(PLUGIN,128,SEEK_SET);
	filedata = (char*)malloc(1024);
	fread((void*)filedata, 1024, 1, PLUGIN);
	
	status = WriteBlock((BYTE*)filedata, 1024);
	free(filedata);
  
  if (!status)
  {
		fclose(PLUGIN);
		return FALSE;
  }

	for (w = 0; !feof(PLUGIN); w++)
		fread(&ROMstring[w],1,1,PLUGIN);
	ROMstring[w] = 0;
	fclose(PLUGIN);
	StatusPercent(0);
	Sleep(SLEEP_SHORT);
	return TRUE;
}
Пример #3
0
//================================================================
// Write noBytes from buffer into the file represented by fHandle
// Returns no of bytes written
//================================================================
long WriteFile(struct FCB *fcb, char *buffer, long noBytes)
{
	int i;

	// If noBytes == 0 there is nothing to do
	if (!noBytes)
		return 0;
	// Deal with the case of an initial empty file
	if (!fcb->inode->i_block[0])
		AddFirstBlockToFile(fcb);
	for (i = 0; i < noBytes; i++)
	{
		// If the bufCursor is at the end of the block we need to load the next block
		if (fcb->bufCursor == block_size)
		{
			// If the current buffer is dirty write the block to disk
			if (fcb->bufferIsDirty)
			{
				WriteBlock(fcb->currentBlock, fcb->buffer);
				fcb->bufferIsDirty = 0;
			}
			// If the file cursor is at the end of the file allocate a new block
			if (fcb->fileCursor >= (int)(fcb->inode->i_size - 1))
				AddBlockToFile(fcb);
			else
				// Load the block and set fcb->bufCursor
				SetBufferFromCursor(fcb);
		}
		// Increment the bufCursor and copy the byte to the file buffer
		fcb->buffer[fcb->bufCursor++] = buffer[i];
		// Mark the current buffer as dirty and increment the fileCursor
		fcb->bufferIsDirty = 1;
		fcb->fileCursor++;
		// If at the end of the file increment the file size in the inode and mark the inode as dirty
		if (fcb->fileCursor > (int)(fcb->inode->i_size))
		{
			fcb->inode->i_size++;
			fcb->inodeIsDirty = 1;
		}
	}
	return noBytes;
}
Пример #4
0
static int AddINodeToINode(const char* filename, const iNodeEntry *pSrcInode, iNodeEntry *pDstInode) {
  if (!(pDstInode->iNodeStat.st_mode & G_IFDIR))
    return -1;

  char dataBlock[BLOCK_SIZE];
  if (ReadBlock(pDstInode->Block[0], dataBlock) == -1)
    return -1;

  DirEntry *pDirEntry = (DirEntry*)dataBlock;
  if (pDirEntry == NULL)
    return -1;

  const size_t nDir = NumberofDirEntry(pDstInode->iNodeStat.st_size);
  pDirEntry[nDir].iNode = pSrcInode->iNodeStat.st_ino;
  strcpy(pDirEntry[nDir].Filename, filename);
  if (WriteBlock(pDstInode->Block[0], dataBlock) == -1)
    return -1;
  pDstInode->iNodeStat.st_size += sizeof(DirEntry);
  return WriteINodeToDisk(pDstInode);
}
Пример #5
0
void create_file(ino directoryiNode, const char *filename) {
    char directoryDataBlock[BLOCK_SIZE];
    ReadBlock(6 + directoryiNode - 1, directoryDataBlock);
    DirEntry *directory = (DirEntry *)directoryDataBlock;

    int directorySize = numberOfFilesInDirectory(directory);
    ino fileiNode = get_first_free_inode();

    // Create new file at the end of the directory
    strcpy(directory[directorySize].Filename, filename);
    directory[directorySize].iNode = fileiNode;

    // Create the new inode associated with the file
    create_new_file_inode(fileiNode);

    // Adds the file size to the directory size
    add_size_to_inode_size(sizeof(directory[directorySize]), directoryiNode);

    WriteBlock(6 + directoryiNode - 1, directoryDataBlock);
}
off_t CreateNewLeaf_int(BPlusTree tree, leaf_t_int *leaf, off_t offset, leaf_t_int *newLeaf)
{
    off_t newLeafOffset;
    leaf_t_int *newLeafNext;
    newLeafOffset = AllocLeaf_int(tree, newLeaf);
    newLeaf->parent = leaf->parent;
    newLeaf->next = leaf->next;
    leaf->next = newLeafOffset;
    newLeaf->prev = offset;
    if (newLeaf->next)
    {
        newLeafNext = (leaf_t_int *)ReadBlock(tree->path, newLeaf->next, sizeof(leaf_t_int));
        newLeafNext->prev = newLeafOffset;
        WriteBlock(tree->path, newLeafNext, newLeaf->next, sizeof(leaf_t_int));
#ifdef NOBUFFER
        free(newLeafNext);
#endif
    }
    return newLeafOffset;
}
off_t CreateNewInternal_int(BPlusTree tree, internal_t_int *internal, off_t offset, internal_t_int *newInternal)
{
    off_t newInternalOffset;
    internal_t_int *newInternalNext;
    newInternalOffset = AllocInternal_int(tree, newInternal);
    newInternal->parent = internal->parent;
    newInternal->next = internal->next;
    internal->next = newInternalOffset;
    newInternal->prev = offset;
    if (newInternal->next)
    {
        newInternalNext = (internal_t_int *)ReadBlock(tree->path, newInternal->next, sizeof(internal_t_int));
        newInternalNext->prev = newInternalOffset;
        WriteBlock(tree->path, newInternalNext, newInternal->next, sizeof(internal_t_int));
#ifdef NOBUFFER
        free(newInternalNext);
#endif
    }
    return newInternalOffset;
}
Пример #8
0
uint64 WriteFrame(IMkvWriter* writer, const Frame* const frame,
                  Cluster* cluster) {
  if (!writer || !frame || !frame->IsValid() || !cluster ||
      !cluster->timecode_scale())
    return 0;

  //  Technically the timecode for a block can be less than the
  //  timecode for the cluster itself (remember that block timecode
  //  is a signed, 16-bit integer).  However, as a simplification we
  //  only permit non-negative cluster-relative timecodes for blocks.
  const int64 relative_timecode = cluster->GetRelativeTimecode(
      frame->timestamp() / cluster->timecode_scale());
  if (relative_timecode < 0 || relative_timecode > kMaxBlockTimecode)
    return 0;

  return frame->CanBeSimpleBlock() ?
             WriteSimpleBlock(writer, frame, relative_timecode) :
             WriteBlock(writer, frame, relative_timecode,
                        cluster->timecode_scale());
}
Пример #9
0
void DataFlash_Block::EraseAll()
{
    log_write_started = false;
    for (uint16_t j = 1; j <= (df_NumPages+1)/8; j++) {
        BlockErase(j);
        if (j%6 == 0) {
            hal.scheduler->delay(6);
        }
    }
    // write the logging format in the last page
    hal.scheduler->delay(100);
    StartWrite(df_NumPages+1);
    uint32_t version = DF_LOGGING_FORMAT;
    log_write_started = true;
    _writes_enabled = true;
    WriteBlock(&version, sizeof(version));
    log_write_started = false;
    FinishWrite();
    hal.scheduler->delay(100);
}
Пример #10
0
int WriteInode(int dev, int ino, struct INode *inode)
{
    if (inode==NULL)
        return -1;// error

    int ino_in_single_blk= BLKSIZE/sizeof(struct INode);
    int blkno= (ino-1)/ino_in_single_blk;
    int offset = (ino-1)- blkno*ino_in_single_blk;

    char buf[BLKSIZE];

    ReadBlock(dev,INODE_BLK_STARTS_AT+blkno,buf);

    struct INode* ptr= (struct INode*) buf;

    my_memcpy(ptr+offset,inode,sizeof(struct INode));

    WriteBlock(dev,INODE_BLK_STARTS_AT+blkno,buf);

    return 0;
}
Пример #11
0
size_t BlockWriteStream::WriteData(const MemoryByteData& data, DataReadingMode mode /*= DataReadingMode::AlwaysCopy*/)
{
	RETURN_ZERO_IF_FALSE(CanWrite());

	size_t dataPos = 0;
	size_t dataSize = data.Size();

	if (mBuffer.Position() > 0)
	{
		size_t bufferLeftLength = mBuffer.LeftLength();
		size_t writeSize = Math::Min(bufferLeftLength, dataSize);
		MemoryByteData tempData = MemoryByteData::FromStatic(data.Data(), writeSize);
		writeSize = mBuffer.WriteData(tempData, mode);
		dataPos += writeSize;
		dataSize -= writeSize;

		if (mBuffer.IsEnd())
		{
			WriteCurrentBlock();
			++mBlockIndex;
		}
		else
		{
			//all data write to buffer
			return dataPos;
		}
	}

	//directly write data block per block
	size_t blockSize = mBuffer.Length();
	size_t blockCount = dataSize / blockSize;
	FOR_EACH_SIZE(i, blockCount)
	{
		MemoryByteData tempData = MemoryByteData::FromStatic(data.Data() + dataPos, blockSize);
		size_t writeSize = WriteBlock(mBlockIndex, tempData);
		++mBlockIndex;

		dataPos += writeSize;
		dataSize -= writeSize;
	}
Пример #12
0
/*!
* \brief	audio mute or unmute
*		When mute audio, Audio source should keep sending MCLK, BCLK, WS signal. Just stop SD data.
*		If change MCLK, BCLK,WS, or change video mode, should call active to umMute.
* \retval  None
*/ 
void sil902x_mute_audio(int enable)
{
	char reg;
	
	if( enable ){
		reg = ReadByte(0x26);
		WriteByte(0x26,reg | 0x10);
	}
	else {
		char audioInfoFrame[]={0xc2,0x84,0x01,0x0A,0x71,0,0,0,0,0,0,0,0,0,0};
	
		reg = ReadByte(0x26);	
		WriteByte(0x26, reg & 0xEF ) ;	
		// For non-A version, always need to re-set layout = 0 after unMute audio
		// For A version , don't need following 4 instructions
		WriteByte(0xBC,0x02);				// internal page 2
		WriteByte(0xBD,0x2F);				// index reg 0x2F
		reg = ReadByte(0xBE);
		WriteByte(0xBE,reg & 0xFD);			// Layout=2 channel
		WriteBlock(0xBF, audioInfoFrame, 15);// enable & send audio infoframe every frame , 
	}
} /* End of sil902x_mute_audio */
void UpdateIndexChild_int(BPlusTree tree, off_t parentOffset, my_key_t_int oldKey, my_key_t_int newKey)
{
    internal_t_int *parent;
    int i;
    parent = (internal_t_int *)ReadBlock(tree->path, parentOffset, sizeof(internal_t_int));
    for (i = (int)parent->n - 1; i >= 0; i--)
    {
        if (KeyCmp_int(parent->children[i].key, oldKey) <= 0 || 0 == i)  // found old key
        {
            parent->children[i].key = newKey;
            break;
        }
    }
    WriteBlock(tree->path, parent, parentOffset, sizeof(internal_t_int));
    if (0 == i && 0 != parent->parent)  // recursively update child
    {
        UpdateIndexChild_int(tree, parent->parent, oldKey, newKey);
    }
#ifdef NOBUFFER
    free(parent);
#endif
}
Пример #14
0
static inline int CheckBufferSpace(nffile_t *nffile, size_t required) {

#ifdef DEVEL
//	printf("Buffer Size %u\n", nffile->block_header->size);
#endif
	// flush current buffer to disc
	if ( (nffile->block_header->size + required )  > WRITE_BUFFSIZE ) {

		// this should never happen, but catch it anyway
		if ( required > WRITE_BUFFSIZE ) {
			LogError("Required buffer size %zu too big for output buffer!" , required);
			return 0;
		}

		if ( WriteBlock(nffile) <= 0 ) {
			LogError("Failed to write output buffer to disk: '%s'" , strerror(errno));
			return 0;
		} 
	}

	return 1;
} // End of CheckBufferSpace
Пример #15
0
int Delete_from_dir(int d_inode,int inode_num)
{	
		
	int i,k,p,res;
	int blk_num,total_blks;
	struct dir_entry * dir;
	struct inode dir_inode;
	dir=(struct dir_entry * )malloc(BLOCKSIZE);
	
	res=GetInode(d_inode,&dir_inode);
	
	total_blks=(dir_inode.size+BLOCKSIZE-1)/BLOCKSIZE;
	
	for(i=0;i<total_blks;i++)
	{
		if(i<NUM_DIRECT)
			blk_num=dir_inode.direct[i];
		else
			blk_num=GetIndirectBlk(dir_inode.indirect,i-NUM_DIRECT);
		res=GetBlock(blk_num,(char *)dir);
		if(res==ERROR)	
			return ERROR;
			
		for(k=0;k<(BLOCKSIZE/DIRECTORYSIZE);k++)
			{	
				if(dir[k].inum==inode_num)
				{	dir[k].inum=0;						
					WriteBlock(blk_num,dir);
					Add_free_inode(inode_num);
					free(dir);
					
					return 0 ;
				}
			}
	}
	
	free(dir);
	return 0;
 }
Пример #16
0
bool FirewirePort::WriteAllBoards(void)
{
    if ((Protocol_ == FirewirePort::PROTOCOL_SEQ_R_BC_W) || (Protocol_ == FirewirePort::PROTOCOL_BC_QRW)) {
        return WriteAllBoardsBroadcast();
    }

    if (!handle) {
        outStr << "WriteAllBoards: handle for port " << PortNum << " is NULL" << std::endl;
        return false;
    }
    bool allOK = true;
    bool noneWritten = true;
    for (int board = 0; board < max_board; board++) {
        if (BoardList[board]) {
            quadlet_t *buf = BoardList[board]->GetWriteBuffer();
            unsigned int numBytes = BoardList[board]->GetWriteNumBytes();
            unsigned int numQuads = numBytes/4;
            // Currently (Rev 1 firmware), the last quadlet (Status/Control register)
            // is done as a separate quadlet write.
            bool ret = WriteBlock(board, 0, buf, numBytes-4);
            if (ret) noneWritten = false;
            else allOK = false;
            quadlet_t ctrl = buf[numQuads-1];  // Get last quadlet
            bool ret2 = true;
            if (ctrl) {    // if anything non-zero, write it
                ret2 = WriteQuadlet(board, 0, ctrl);
                if (ret2) noneWritten = false;
                else allOK = false;
            }
            // SetWriteValid clears the buffer if the write was valid
            BoardList[board]->SetWriteValid(ret&&ret2);
        }
    }
    if (noneWritten)
        PollEvents();
    return allOK;
}
Пример #17
0
int write_from_buffer(const iNodeEntry iNode, const char *buffer, int offset,
                      int numbytes) {

    int bytesWritten = 0;
    char dataBlock[BLOCK_SIZE];
    ReadBlock(iNode.Block[0], dataBlock);

    int fileSize = iNode.iNodeStat.st_size;
    int fileiNode = iNode.iNodeStat.st_ino;
    int endingByte = offset + numbytes;

    if (endingByte >= BLOCK_SIZE) {
        bytesWritten = BLOCK_SIZE - offset;
        int i;
        for (i = offset; i < BLOCK_SIZE; ++i) {
            dataBlock[i] = buffer[i - offset];
        }
    } else {
        bytesWritten = numbytes;
        int i;
        for (i = offset; i < endingByte; ++i) {
            dataBlock[i] = buffer[i - offset];
        }
    }

    if ((endingByte > fileSize) && (endingByte < BLOCK_SIZE)) {
        if (offset < fileSize) {
            add_to_inode_size(fileiNode, endingByte - fileSize);
        } else {
            add_to_inode_size(fileiNode, bytesWritten);
        }
    }

    WriteBlock(iNode.Block[0], dataBlock);

    return bytesWritten;
}
Пример #18
0
void BaseIndex::BlockConnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex,
                               const std::vector<CTransactionRef>& txn_conflicted)
{
    if (!m_synced) {
        return;
    }

    const CBlockIndex* best_block_index = m_best_block_index.load();
    if (!best_block_index) {
        if (pindex->nHeight != 0) {
            FatalError("%s: First block connected is not the genesis block (height=%d)",
                       __func__, pindex->nHeight);
            return;
        }
    } else {
        // Ensure block connects to an ancestor of the current best block. This should be the case
        // most of the time, but may not be immediately after the sync thread catches up and sets
        // m_synced. Consider the case where there is a reorg and the blocks on the stale branch are
        // in the ValidationInterface queue backlog even after the sync thread has caught up to the
        // new chain tip. In this unlikely event, log a warning and let the queue clear.
        if (best_block_index->GetAncestor(pindex->nHeight - 1) != pindex->pprev) {
            LogPrintf("%s: WARNING: Block %s does not connect to an ancestor of " /* Continued */
                      "known best chain (tip=%s); not updating index\n",
                      __func__, pindex->GetBlockHash().ToString(),
                      best_block_index->GetBlockHash().ToString());
            return;
        }
    }

    if (WriteBlock(*block, pindex)) {
        m_best_block_index = pindex;
    } else {
        FatalError("%s: Failed to write block %s to index",
                   __func__, pindex->GetBlockHash().ToString());
        return;
    }
}
Пример #19
0
Файл: HDD.cpp Проект: ss23/rpcs3
void vfsHDD::RemoveBlocksDir(u64 start_block)
{
	std::string name;
	u64 block = start_block;
	vfsHDD_Entry entry;

	while (block)
	{
		ReadEntry(block, entry, name);
		WriteBlock(block, g_null_block);

		if (entry.type == vfsHDD_Entry_Dir && name != "." && name != "..")
		{
			LOG_WARNING(HLE, "Removing sub folder '%s'", name.c_str());
			RemoveBlocksDir(entry.data_block);
		}
		else if (entry.type == vfsHDD_Entry_File)
		{
			RemoveBlocksFile(entry.data_block);
		}

		block = entry.next_block;
	}
}
Пример #20
0
/*
============================
idFile_SaveGamePipelined::FlushCompressedBlock

Called when a compressed block fills up, and also to flush the final partial block.
Flushes everything from [compressedConsumedBytes -> compressedProducedBytes)

Reads:
	compressed
	compressedProducedBytes

Modifies:
	dataZlib
	bytesZlib
	compressedConsumedBytes
============================
*/
void idFile_SaveGamePipelined::FlushCompressedBlock()
{
	// block until the background thread is done with the last block
	if( writeThread != NULL )
	{
		writeThread->WaitForThread();
	}
	if( nativeFile == NULL )
	{
		if( !nativeFileEndHit )
		{
			blockRequested.Wait();
		}
	}
	
	// prepare the next block to be written out
	dataIO = &compressed[ compressedConsumedBytes & ( COMPRESSED_BUFFER_SIZE - 1 ) ];
	bytesIO = compressedProducedBytes - compressedConsumedBytes;
	compressedConsumedBytes = compressedProducedBytes;
	
	if( writeThread != NULL )
	{
		// signal a new block is available to be written out
		writeThread->SignalWork();
	}
	else if( nativeFile != NULL )
	{
		// write syncronously
		WriteBlock();
	}
	else
	{
		// signal a new block is available to be written out
		blockAvailable.Raise();
	}
}
Пример #21
0
int Server_Write(int inode,int len,int offset,char *buff)
{
	int size,blk_num,sec_num,i,k,j;
	int len_write=0,res;
	int total_blk,num_blk;
	int blk_offset;
	char str[BLOCKSIZE];
	struct inode curr_inode;
	int final_size,final_total_blk;
	printf("\nWrite:Reached 1");

	if(inode<1||inode>max_inode_num||buff==NULL)
		return ERROR;

	
	printf("\nWrite:Reached 1 with inode=%d",inode);
	
	res=GetInode(inode,&curr_inode);
	
	if(res==ERROR)
		return ERROR;
	
	printf("\nWrite :Reached 2 with inode type as %d",curr_inode.type);
	
	if(curr_inode.type!=INODE_REGULAR)			
		return ERROR;
	
	printf("\nWrite :Reached 3");
	
	size=curr_inode.size;
	printf("\nWrite :Reached 3");

	if(offset>size+1)
		return ERROR;
	print_inode(inode,&curr_inode);
	
	
	printf("\nWrite :Reached 4 size=%d",size);
	
	
	
	total_blk=(size+BLOCKSIZE-1)/BLOCKSIZE;
	
	final_size=size+len;
	final_total_blk=(final_size+BLOCKSIZE-1)/BLOCKSIZE;
	printf("\nWrite :Reached 5 final block =%d and total blk =%d",final_total_blk,total_blk);
	/*res=Has_N_Free_Blocks(final_total_blk-total_blk);
	if(res==0)
		return ERROR;*/
	for(i=total_blk;i<final_total_blk;i++)
	{
		blk_num=Get_free_blknum();
		if(i<NUM_DIRECT)
			curr_inode.direct[i]=blk_num;
		else
			PutIndirectBlk(curr_inode.indirect,i-NUM_DIRECT,blk_num);

	}
	printf("\nWrite :Reached 5 ");
	num_blk=offset/BLOCKSIZE;
	for(k=num_blk;k<final_total_blk;k++)
	{	
		if(k<NUM_DIRECT)
				blk_num=curr_inode.direct[k];
			else
				blk_num=GetIndirectBlk(curr_inode.indirect,k-NUM_DIRECT);
		
		if(k==num_blk)
		{	blk_offset=offset%BLOCKSIZE;
			res=GetBlock(blk_num,&str);
			if(res==ERROR)
				return ERROR;
		}
		else
			blk_offset=0;
		
		for(i=blk_offset;i<BLOCKSIZE/sizeof(char);i++)
			if(len_write<len)
			{	str[i]=buff[len_write++];
				curr_inode.size++;
				printf("\nCopied %c",buff[len_write-1]);	
			}
			else 
			{	WriteBlock(blk_num,&str);
				write_inode(inode,&curr_inode);
				printf("\nReturning from Write()");
				return len_write;
			}
		WriteBlock(blk_num,&str);

	}
	write_inode(inode,&curr_inode);
	return len_write;
}
Пример #22
0
int Server_SymLink(int inode_num,char *oldname,char *newname)
{
	int i,blk_num;
	int last_slash=-1;
	int num;
	int res;
	int resF;
	int len=strlen(newname);
	char dir_path[MAXPATHNAMELEN+1];
	struct inode curr_inode;
	char block[BLOCKSIZE];
	
	if(inode_num<1||inode_num>max_inode_num||newname==NULL)
		return ERROR;

	for(i=0;i<len;i++)
		if(newname[i]=='/')
			last_slash=i;
	
	
	printf("\nReached in SymLink 1");
	if(last_slash==0)
		res=ROOTINODE;
	else
		res=inode_num;
	if(last_slash>0)
	{	
		printf("\nSymLink: Reached in Link_file 2");
		
		strncpy(dir_path,newname,last_slash);
		
		dir_path[last_slash]='\0';
		
		res=LookUp(dir_path,inode_num,0);
		
		if((res==ERROR)||(res==0))
		{
			printf("\nERROR: Path %s does not exist ",dir_path);
			free(dir_path);
			return ERROR;
		}
	}	
		
	strncpy(dir_path,&newname[last_slash+1],len-last_slash-1);
	
	dir_path[len-last_slash-1]='\0';
	
	printf("\nSymLink : Value of dir_path is %s",dir_path);
	
	resF=LookUp(dir_path,res,0);
	
	printf("\nSymLink :Reached in Link_file 4 with resF as %d",resF);
	
	if(resF==ERROR)
	{
		printf("\nSymLink ERROR: Path %s does not exist ",dir_path);
		return ERROR;
	}
	if(resF!=0)
	{
		printf("\nSymLink ERROR: Pathname %s already exists ",newname);
		return ERROR;
	}
	resF=Get_free_inode();
	if(resF==0)
		return ERROR;
	
	//GetInode(resF,&curr_inode);
	curr_inode.type=INODE_SYMLINK;
	curr_inode.nlink=1;
	curr_inode.size=strlen(oldname);
	blk_num=Get_free_blknum();
	if(blk_num==0)
	{
		printf("\nSymLink ERROR: Not enough memory available!");
		Add_free_inode(resF);
		return ERROR;
	}

	curr_inode.direct[0]=blk_num;
	GetBlock(blk_num,&block);
	strncpy(&block,oldname,strlen(oldname)+1);
	
	WriteBlock(blk_num,&block);
	
	PutInDir(res,resF,dir_path);
	write_inode(resF,&curr_inode);
	curr_inode.size=0;
	GetInode(resF,&curr_inode);
	print_inode(resF,&curr_inode);
	printf("\nReturning from SymLink");
	return 0;



}
Пример #23
0
int PutInDir(int d_inode,int inode_num,char *name)
{	
	
	int i,k,p,res;
	int blk_num,total_blks;
	struct dir_entry * dir;
	struct inode *dir_inode=(struct inode *)malloc(INODESIZE);

	printf("\nInside PutInDir : Reached 0");
	
	if(dir_inode==NULL)
	{	
		printf("\nPutInDir ERROR : Not enough memory %p",dir_inode);
		return ERROR;
	}
	
	printf("\nInside PutInDir : Reached 0.5");
	res=GetInode(d_inode,dir_inode);
	
	if(res==ERROR||dir_inode->type!=INODE_DIRECTORY)
	{	
		printf("\nERROR: Coud not get node");
		free(dir_inode);
		return ERROR;
	}
	printf("\nInside PutInDir : Reached 1 with size as %d",dir_inode->size);
	dir=(struct dir_entry *)malloc(BLOCKSIZE);
	
	total_blks=(dir_inode->size+BLOCKSIZE-1/BLOCKSIZE);
	
	for(i=0;i<total_blks;i++)
	{
		if(i<NUM_DIRECT)
			blk_num=dir_inode->direct[i];
		else
			blk_num=GetIndirectBlk(dir_inode->indirect,i-NUM_DIRECT);
		res=GetBlock(blk_num,(char *)dir);
		if(res==ERROR)
			return res;
		for(k=0;k<(BLOCKSIZE/DIRECTORYSIZE);k++)
			{	
				if(dir[k].inum==0)
				{		
					dir[k].inum=inode_num;
					for(p=0;p<DIRNAMELEN;p++)
						if(name[p]=='\0')
							break;
						else
							dir[k].name[p]=name[p];		
					if(p<DIRNAMELEN)
						dir[k].name[p]='\0';
					

					printf("\nInside PutInDir : putting (%s)%d in %d  ",name,inode_num,d_inode);
					
					dir_inode->size+=DIRECTORYSIZE;
					printf("\nInside PutInDir : Reached inside loop with size as %d",dir_inode->size);
					write_inode(d_inode,dir_inode);
					WriteBlock(blk_num,(char *)dir);
					free(dir);
					free(dir_inode);
					return 0;

				}
			}
			
	}
	
	blk_num=Get_free_blknum();
	
	for(k=0;k<(BLOCKSIZE/DIRECTORYSIZE);k++)
		dir[k].inum=0;


	dir[0].inum=inode_num;
	for(p=0;p<DIRNAMELEN;p++)
		if(name[p]=='\0')
			break;
		else
			dir[k].name[p]=name[p];		
	if(p<DIRNAMELEN)
		dir[k].name[p]='\0';

	WriteBlock(blk_num,(char *)dir);
	
	dir_inode->direct[total_blks]=blk_num;
	dir_inode->size+=DIRECTORYSIZE;
	write_inode(d_inode,dir_inode);
	
	printf("\nInside PutInDir : Reached outside loop with size as %d",dir_inode->size);
	printf("\nInside PutInDir : Reached 5");
	free(dir);
	free(dir_inode);
	return 0;
 }
Пример #24
0
void SaveMEM(SAVESTATE_t* save, memc* mem) {
	int i;
	if (!mem) return;
	CHUNK_t *chunk = NewChunk(save, MEM_tag);

	WriteInt(chunk, mem->flash_size);
	WriteInt(chunk, mem->flash_pages);
	WriteInt(chunk, mem->ram_size);
	WriteInt(chunk, mem->ram_pages);
	WriteInt(chunk, mem->step);
	WriteChar(chunk, mem->cmd);
	
	WriteInt(chunk, mem->boot_mapped);
	WriteInt(chunk, mem->flash_locked);
	WriteInt(chunk, mem->flash_version);	

	for(i = 0; i < 5; i++) {
		WriteInt(chunk, mem->normal_banks[i].page);
		WriteInt(chunk, mem->normal_banks[i].read_only);
		WriteInt(chunk, mem->normal_banks[i].ram);
		WriteInt(chunk, mem->normal_banks[i].no_exec);
	}
	
	WriteInt(chunk, mem->read_OP_flash_tstates);
	WriteInt(chunk, mem->read_NOP_flash_tstates);
	WriteInt(chunk, mem->write_flash_tstates);
	WriteInt(chunk, mem->read_OP_ram_tstates);
	WriteInt(chunk, mem->read_NOP_ram_tstates);
	WriteInt(chunk, mem->write_ram_tstates);
	
	WriteInt(chunk, mem->flash_upper);
	WriteInt(chunk, mem->flash_lower);

	chunk = NewChunk(save, ROM_tag);
	WriteBlock(chunk, mem->flash, mem->flash_size);

	chunk = NewChunk(save, RAM_tag);
	WriteBlock(chunk, mem->ram, mem->ram_size);
	
	chunk = NewChunk(save, REMAP_tag);
	WriteInt(chunk, mem->port27_remap_count);
	WriteInt(chunk, mem->port28_remap_count);

	chunk = NewChunk(save, RAM_LIMIT_tag);
	WriteInt(chunk, mem->ram_upper);
	WriteInt(chunk, mem->ram_lower);

	int count = 0;
	chunk = NewChunk(save, FLASH_BREAKS_tag);
	for (int i = 0; i < mem->flash_size; i++)
	{
		if (mem->flash_break[i])
		{
			count++;
			WriteInt(chunk, i);
			WriteInt(chunk, mem->flash_break[i]);
		}
	}
	chunk = NewChunk(save, NUM_FLASH_BREAKS_tag);
	WriteInt(chunk, count);

	count = 0;
	chunk = NewChunk(save, RAM_BREAKS_tag);
	for (int i = 0; i < mem->ram_size; i++)
	{
		if (mem->ram_break[i])
		{
			count++;
			WriteInt(chunk, i);
			WriteInt(chunk, mem->ram_break[i]);
		}
	}
	chunk = NewChunk(save, NUM_RAM_BREAKS_tag);
	WriteInt(chunk, count);
}
Пример #25
0
bool MPEG_File::save(int tags, bool stripOthers)
{
	if(tags == MPEG_NoTags && stripOthers)
		return strip(MPEG_AllTags);

	if( !m_id3v2Tag && !m_id3v1Tag && !m_apeTag )
	{
		if( (m_hasId3v1 || m_hasId3v2 || m_hasApe) && stripOthers)
			return strip(MPEG_AllTags);

		return true;
	}

	if( ReadOnly() )
	{
		wxLogDebug(wxT("MPEG::File::save() -- File is read only."));
		return false;
	}

	// Create the tags if we've been asked to.  Copy the values from the tag that
	// does exist into the new tag.

	if( (tags & MPEG_ID3v2) && m_id3v1Tag )
	{
		Tagger_Tag::duplicate(m_id3v1Tag, ID3v2Tag(true), false);
	}

	if( (tags & MPEG_ID3v1) && m_id3v2Tag )
	{
		Tagger_Tag::duplicate(m_id3v2Tag, ID3v1Tag(true), false);
	}

	bool success = true;

	if(MPEG_ID3v2 & tags)
	{
		if (m_id3v2Tag && !m_id3v2Tag->isEmpty() )
		{
			if(!m_hasId3v2)
			{
				m_id3v2Location = 0;
			}

			success = Insert(m_id3v2Tag->render(), m_id3v2Location, m_id3v2OriginalSize) && success;
		}
		else if(stripOthers)
		{
			success = strip(MPEG_ID3v2, false) && success;
		}
	}
	else if(m_hasId3v2 && stripOthers)
	{
		success = strip(MPEG_ID3v2) && success;
	}

	if(MPEG_ID3v1 & tags)
	{
		if(m_id3v1Tag && !m_id3v1Tag->isEmpty())
		{
			int offset = m_hasId3v1 ? -128 : 0;
			Seek(offset, SJ_SEEK_END);
			success = WriteBlock(m_id3v1Tag->render()) && success;
		}
		else if(stripOthers)
		{
			success = strip(MPEG_ID3v1) && success;
		}
	}
	else if(m_hasId3v1 && stripOthers)
	{
		success = strip(MPEG_ID3v1, false) && success;
	}

	// Dont save an APE-tag unless one has been created

	if((MPEG_APE & tags) && m_apeTag)
	{
		if(m_hasApe)
		{
			success = Insert(m_apeTag->render(), m_apeLocation, m_apeOriginalSize) && success;
		}
		else
		{
			if(m_hasId3v1)
			{
				success = Insert(m_apeTag->render(), m_id3v1Location, 0) && success;
				m_apeOriginalSize = m_apeTag->footer()->completeTagSize();
				m_hasApe = true;
				m_apeLocation = m_id3v1Location;
				m_id3v1Location += m_apeOriginalSize;
			}
			else
			{
				Seek(0, SJ_SEEK_END);
				m_apeLocation = Tell();
				success = WriteBlock(m_apeTag->render()) && success;
				m_apeOriginalSize = m_apeTag->footer()->completeTagSize();
				m_hasApe = true;
			}
		}
	}
	else if(m_hasApe && stripOthers)
	{
		success = strip(MPEG_APE, false) && success;
	}

	return success;
}
Пример #26
0
Файл: HDD.cpp Проект: ss23/rpcs3
bool vfsHDD::Create(vfsHDD_EntryType type, const std::string& name)
{
	if (HasEntry(name))
	{
		return false;
	}

	u64 new_block = FindFreeBlock();
	if (!new_block)
	{
		return false;
	}

	LOG_NOTICE(HLE, "CREATING ENTRY AT 0x%llx", new_block);
	WriteBlock(new_block, g_used_block);

	{
		vfsHDD_Entry new_entry;
		vfsHDDManager::CreateEntry(new_entry);
		new_entry.next_block = 0;
		new_entry.type = type;

		if (type == vfsHDD_Entry_Dir)
		{
			u64 block_cur = FindFreeBlock();

			if (!block_cur)
			{
				return false;
			}

			WriteBlock(block_cur, g_used_block);

			u64 block_last = FindFreeBlock();

			if (!block_last)
			{
				return false;
			}

			WriteBlock(block_last, g_used_block);

			vfsHDD_Entry entry_cur, entry_last;
			vfsHDDManager::CreateEntry(entry_cur);
			vfsHDDManager::CreateEntry(entry_last);

			entry_cur.type = vfsHDD_Entry_Dir;
			entry_cur.data_block = block_cur;
			entry_cur.next_block = block_last;

			entry_last.type = vfsHDD_Entry_Dir;
			entry_last.data_block = m_cur_dir_block;
			entry_last.next_block = 0;

			new_entry.data_block = block_cur;

			WriteEntry(block_cur, entry_cur, ".");
			WriteEntry(block_last, entry_last, "..");
		}

		WriteEntry(new_block, new_entry, name);
	}

	{
		u64 block = m_cur_dir_block;

		vfsHDD_Block tmp;
		while (block)
		{
			ReadBlock(block, tmp);

			if (!tmp.next_block)
				break;

			block = tmp.next_block;
		}

		tmp.next_block = new_block;
		WriteBlock(block, tmp);
	}

	return true;
}
Пример #27
0
Файл: HDD.cpp Проект: ss23/rpcs3
u64 vfsHDDFile::Write(const void* src, u64 size)
{
	if (!size)
		return 0;

	//vfsDeviceLocker lock(m_hdd);

	const u32 block_size = m_hdd_info.block_size - sizeof(vfsHDD_Block);

	if (!m_cur_block)
	{
		if (!m_info.data_block)
		{
			u64 new_block = FindFreeBlock();

			if (!new_block)
			{
				return 0;
			}

			WriteBlock(new_block, g_used_block);
			m_info.data_block = new_block;
			m_info.size = 0;
			SaveInfo();
		}

		m_cur_block = m_info.data_block;
		m_position = 0;
	}

	u64 wsize = std::min<u64>(block_size - m_position, size);

	vfsHDD_Block block_info;
	ReadBlock(m_cur_block, block_info);

	if (wsize)
	{
		CHECK_ASSERTION(m_hdd.Seek(m_cur_block * m_hdd_info.block_size + sizeof(vfsHDD_Block) + m_position) != -1);

		m_hdd.Write(src, wsize);
		size -= wsize;
		m_info.size += wsize;
		m_position += wsize;
		SaveInfo();

		if (!size)
			return wsize;
	}

	u64 last_block = m_cur_block;
	block_info.is_used = true;
	u64 offset = wsize;

	for (; size; size -= wsize, offset += wsize, m_info.size += wsize)
	{
		u64 new_block = FindFreeBlock();

		if (!new_block)
		{
			m_position = 0;
			SaveInfo();
			return offset;
		}

		m_cur_block = new_block;
		wsize = std::min<u64>(block_size, size);

		block_info.next_block = m_cur_block;
		
		CHECK_ASSERTION(m_hdd.Seek(last_block * m_hdd_info.block_size) != -1);

		if (m_hdd.Write(&block_info, sizeof(vfsHDD_Block)) != sizeof(vfsHDD_Block))
		{
			m_position = 0;
			SaveInfo();
			return offset;
		}

		block_info.next_block = 0;

		CHECK_ASSERTION(m_hdd.Seek(m_cur_block * m_hdd_info.block_size) != -1);

		if (m_hdd.Write(&block_info, sizeof(vfsHDD_Block)) != sizeof(vfsHDD_Block))
		{
			m_position = 0;
			SaveInfo();
			return offset;
		}

		if ((m_position = m_hdd.Write((u8*)src + offset, wsize)) != wsize)
		{
			m_info.size += wsize;
			SaveInfo();
			return offset;
		}

		last_block = m_cur_block;
	}

	SaveInfo();
	m_position = wsize;
	return offset;
}
Пример #28
0
stat_record_t process_data(char *wfile, int element_stat, int flow_stat, int sort_flows,
	printer_t print_header, printer_t print_record, time_t twin_start, time_t twin_end, 
	uint64_t limitflows, int tag, int compress, int do_xstat) {
common_record_t 	*flow_record;
master_record_t		*master_record;
nffile_t			*nffile_w, *nffile_r;
xstat_t				*xstat;
stat_record_t 		stat_record;
int 				done, write_file;

#ifdef COMPAT15
int	v1_map_done = 0;
#endif
	
	// time window of all matched flows
	memset((void *)&stat_record, 0, sizeof(stat_record_t));
	stat_record.first_seen = 0x7fffffff;
	stat_record.msec_first = 999;

	// Do the logic first

	// do not print flows when doing any stats are sorting
	if ( sort_flows || flow_stat || element_stat ) {
		print_record = NULL;
	}

	// do not write flows to file, when doing any stats
	// -w may apply for flow_stats later
	write_file = !(sort_flows || flow_stat || element_stat) && wfile;
	nffile_r = NULL;
	nffile_w = NULL;
	xstat  	 = NULL;

	// Get the first file handle
	nffile_r = GetNextFile(NULL, twin_start, twin_end);
	if ( !nffile_r ) {
		LogError("GetNextFile() error in %s line %d: %s\n", __FILE__, __LINE__, strerror(errno) );
		return stat_record;
	}
	if ( nffile_r == EMPTY_LIST ) {
		LogError("Empty file list. No files to process\n");
		return stat_record;
	}

	// preset time window of all processed flows to the stat record in first flow file
	t_first_flow = nffile_r->stat_record->first_seen;
	t_last_flow  = nffile_r->stat_record->last_seen;

	// store infos away for later use
	// although multiple files may be processed, it is assumed that all 
	// have the same settings
	is_anonymized = IP_ANONYMIZED(nffile_r);
	strncpy(Ident, nffile_r->file_header->ident, IDENTLEN);
	Ident[IDENTLEN-1] = '\0';

	// prepare output file if requested
	if ( write_file ) {
		nffile_w = OpenNewFile(wfile, NULL, compress, IP_ANONYMIZED(nffile_r), NULL );
		if ( !nffile_w ) {
			if ( nffile_r ) {
				CloseFile(nffile_r);
				DisposeFile(nffile_r);
			}
			return stat_record;
		}
		if ( do_xstat ) {
			xstat = InitXStat(nffile_w);
			if ( !xstat ) {
				if ( nffile_r ) {
					CloseFile(nffile_r);
					DisposeFile(nffile_r);
				}
				return stat_record;
			}
		}
	}

	// setup Filter Engine to point to master_record, as any record read from file
	// is expanded into this record
	// Engine->nfrecord = (uint64_t *)master_record;

	done = 0;
	while ( !done ) {
	int i, ret;

		// get next data block from file
		ret = ReadBlock(nffile_r);

		switch (ret) {
			case NF_CORRUPT:
			case NF_ERROR:
				if ( ret == NF_CORRUPT ) 
					LogError("Skip corrupt data file '%s'\n",GetCurrentFilename());
				else 
					LogError("Read error in file '%s': %s\n",GetCurrentFilename(), strerror(errno) );
				// fall through - get next file in chain
			case NF_EOF: {
				nffile_t *next = GetNextFile(nffile_r, twin_start, twin_end);
				if ( next == EMPTY_LIST ) {
					done = 1;
				} else if ( next == NULL ) {
					done = 1;
					LogError("Unexpected end of file list\n");
				} else {
					// Update global time span window
					if ( next->stat_record->first_seen < t_first_flow )
						t_first_flow = next->stat_record->first_seen;
					if ( next->stat_record->last_seen > t_last_flow ) 
						t_last_flow = next->stat_record->last_seen;
					// continue with next file
				}
				continue;

				} break; // not really needed
			default:
				// successfully read block
				total_bytes += ret;
		}


#ifdef COMPAT15
		if ( nffile_r->block_header->id == DATA_BLOCK_TYPE_1 ) {
			common_record_v1_t *v1_record = (common_record_v1_t *)nffile_r->buff_ptr;
			// create an extension map for v1 blocks
			if ( v1_map_done == 0 ) {
				extension_map_t *map = malloc(sizeof(extension_map_t) + 2 * sizeof(uint16_t) );
				if ( ! map ) {
					LogError("malloc() allocation error in %s line %d: %s\n", __FILE__, __LINE__, strerror(errno) );
					exit(255);
				}
				map->type 	= ExtensionMapType;
				map->size 	= sizeof(extension_map_t) + 2 * sizeof(uint16_t);
				if (( map->size & 0x3 ) != 0 ) {
					map->size += 4 - ( map->size & 0x3 );
				}

				map->map_id = INIT_ID;

				map->ex_id[0]  = EX_IO_SNMP_2;
				map->ex_id[1]  = EX_AS_2;
				map->ex_id[2]  = 0;
				
				map->extension_size  = 0;
				map->extension_size += extension_descriptor[EX_IO_SNMP_2].size;
				map->extension_size += extension_descriptor[EX_AS_2].size;

				if ( Insert_Extension_Map(extension_map_list,map) && write_file ) {
					// flush new map
					AppendToBuffer(nffile_w, (void *)map, map->size);
				} // else map already known and flushed

				v1_map_done = 1;
			}

			// convert the records to v2
			for ( i=0; i < nffile_r->block_header->NumRecords; i++ ) {
				common_record_t *v2_record = (common_record_t *)v1_record;
				Convert_v1_to_v2((void *)v1_record);
				// now we have a v2 record -> use size of v2_record->size
				v1_record = (common_record_v1_t *)((pointer_addr_t)v1_record + v2_record->size);
			}
			nffile_r->block_header->id = DATA_BLOCK_TYPE_2;
		}
#endif

		if ( nffile_r->block_header->id == Large_BLOCK_Type ) {
			// skip
			printf("Xstat block skipped ...\n");
			continue;
		}

		if ( nffile_r->block_header->id != DATA_BLOCK_TYPE_2 ) {
			if ( nffile_r->block_header->id == DATA_BLOCK_TYPE_1 ) {
				LogError("Can't process nfdump 1.5.x block type 1. Add --enable-compat15 to compile compatibility code. Skip block.\n");
			} else {
				LogError("Can't process block type %u. Skip block.\n", nffile_r->block_header->id);
			}
			skipped_blocks++;
			continue;
		}

		flow_record = nffile_r->buff_ptr;
		for ( i=0; i < nffile_r->block_header->NumRecords; i++ ) {

			switch ( flow_record->type ) {
				case CommonRecordV0Type:
				case CommonRecordType:  {
					int match;
					uint32_t map_id = flow_record->ext_map;
					generic_exporter_t *exp_info = exporter_list[flow_record->exporter_sysid];
					if ( map_id >= MAX_EXTENSION_MAPS ) {
						LogError("Corrupt data file. Extension map id %u too big.\n", flow_record->ext_map);
						exit(255);
					}
					if ( extension_map_list->slot[map_id] == NULL ) {
						LogError("Corrupt data file. Missing extension map %u. Skip record.\n", flow_record->ext_map);
						flow_record = (common_record_t *)((pointer_addr_t)flow_record + flow_record->size);	
						continue;
					} 

					total_flows++;
					master_record = &(extension_map_list->slot[map_id]->master_record);
					Engine->nfrecord = (uint64_t *)master_record;
					ExpandRecord_v2( flow_record, extension_map_list->slot[map_id], 
						exp_info ? &(exp_info->info) : NULL, master_record);

					// Time based filter
					// if no time filter is given, the result is always true
					match  = twin_start && (master_record->first < twin_start || master_record->last > twin_end) ? 0 : 1;
					match &= limitflows ? stat_record.numflows < limitflows : 1;

					// filter netflow record with user supplied filter
					if ( match ) 
						match = (*Engine->FilterEngine)(Engine);
	
					if ( match == 0 ) { // record failed to pass all filters
						// increment pointer by number of bytes for netflow record
						flow_record = (common_record_t *)((pointer_addr_t)flow_record + flow_record->size);	
						// go to next record
						continue;
					}

					// Records passed filter -> continue record processing
					// Update statistics
					UpdateStat(&stat_record, master_record);

					// update number of flows matching a given map
					extension_map_list->slot[map_id]->ref_count++;
	
					if ( flow_stat ) {
						AddFlow(flow_record, master_record, extension_map_list->slot[map_id]);
						if ( element_stat ) {
							AddStat(flow_record, master_record);
						} 
					} else if ( element_stat ) {
						AddStat(flow_record, master_record);
					} else if ( sort_flows ) {
						InsertFlow(flow_record, master_record, extension_map_list->slot[map_id]);
					} else {
						if ( write_file ) {
							AppendToBuffer(nffile_w, (void *)flow_record, flow_record->size);
							if ( xstat ) 
								UpdateXStat(xstat, master_record);
						} else if ( print_record ) {
							char *string;
							// if we need to print out this record
							print_record(master_record, &string, tag);
							if ( string ) {
								if ( limitflows ) {
									if ( (stat_record.numflows <= limitflows) )
										printf("%s\n", string);
								} else 
									printf("%s\n", string);
							}
						} else { 
							// mutually exclusive conditions should prevent executing this code
							// this is buggy!
							printf("Bug! - this code should never get executed in file %s line %d\n", __FILE__, __LINE__);
						}
					} // sort_flows - else
					} break; 
				case ExtensionMapType: {
					extension_map_t *map = (extension_map_t *)flow_record;
	
					if ( Insert_Extension_Map(extension_map_list, map) && write_file ) {
						// flush new map
						AppendToBuffer(nffile_w, (void *)map, map->size);
					} // else map already known and flushed
					} break;
				case ExporterRecordType:
				case SamplerRecordype:
						// Silently skip exporter records
					break;
				case ExporterInfoRecordType: {
					int ret = AddExporterInfo((exporter_info_record_t *)flow_record);
					if ( ret != 0 ) {
						if ( write_file && ret == 1 ) 
							AppendToBuffer(nffile_w, (void *)flow_record, flow_record->size);
					} else {
						LogError("Failed to add Exporter Record\n");
					}
					} break;
				case ExporterStatRecordType:
					AddExporterStat((exporter_stats_record_t *)flow_record);
					break;
				case SamplerInfoRecordype: {
					int ret = AddSamplerInfo((sampler_info_record_t *)flow_record);
					if ( ret != 0 ) {
						if ( write_file && ret == 1 ) 
							AppendToBuffer(nffile_w, (void *)flow_record, flow_record->size);
					} else {
						LogError("Failed to add Sampler Record\n");
					}
					} break;
				default: {
					LogError("Skip unknown record type %i\n", flow_record->type);
				}
			}

		// Advance pointer by number of bytes for netflow record
		flow_record = (common_record_t *)((pointer_addr_t)flow_record + flow_record->size);	


		} // for all records

		// check if we are done, due to -c option 
		if ( limitflows ) 
			done = stat_record.numflows >= limitflows;

	} // while

	CloseFile(nffile_r);

	// flush output file
	if ( write_file ) {
		// flush current buffer to disc
		if ( nffile_w->block_header->NumRecords ) {
			if ( WriteBlock(nffile_w) <= 0 ) {
				LogError("Failed to write output buffer to disk: '%s'" , strerror(errno));
			} 
		}

		if ( xstat ) {
			if ( WriteExtraBlock(nffile_w, xstat->block_header ) <= 0 ) {
				LogError("Failed to write xstat buffer to disk: '%s'" , strerror(errno));
			} 
		}

		/* Stat info */
		if ( write_file ) {
			/* Copy stat info and close file */
			memcpy((void *)nffile_w->stat_record, (void *)&stat_record, sizeof(stat_record_t));
			CloseUpdateFile(nffile_w, nffile_r->file_header->ident );
			nffile_w = DisposeFile(nffile_w);
		} // else stdout
	}	 

	PackExtensionMapList(extension_map_list);

	DisposeFile(nffile_r);
	return stat_record;

} // End of process_data
Пример #29
0
/*
  write a structure format to the log
 */
void DataFlash_Class::Log_Write_Format(const struct LogStructure *s)
{
    struct log_Format pkt;
    Log_Fill_Format(s, pkt);
    WriteBlock(&pkt, sizeof(pkt));
}
Пример #30
0
void
decode_start(int* out_data_image_width, int* out_data_image_height, int* out_data_comp_vpos, int* out_data_comp_hpos)
{
    int i;
    int CurrentMCU = 0;
    int HuffBuff[NUM_COMPONENT][DCTSIZE2];
    int IDCTBuff[6][DCTSIZE2];
    
    /* Read buffer */
    CurHuffReadBuf = p_jinfo_jpeg_data; 
    
    /*
     * Initial value of DC element is 0
     */
    for(i = 0; i < NUM_COMPONENT; i++){
        HuffBuff[i][0] = 0;
    }
    
    /*
     * Set the size of image to output buffer
     */
    *out_data_image_width = p_jinfo_image_width;
    *out_data_image_height = p_jinfo_image_height;

    /*
     * Initialize output buffer
     */
    for(i = 0; i < RGB_NUM; i++){
        out_data_comp_vpos[i] =  0;
        out_data_comp_hpos[i] =  0;
    }
    
    
    if(p_jinfo_smp_fact == SF1_1_1){
        // printf("Decode 1:1:1 NumMCU = %d\n",p_jinfo_NumMCU);
        
        /*
         * 1_1_1
         */
        while(CurrentMCU < p_jinfo_NumMCU){
            
            for(i = 0; i < NUM_COMPONENT; i++){
                decode_block(i, IDCTBuff[i], HuffBuff[i]);
            }

            
            YuvToRgb(0,IDCTBuff[0],IDCTBuff[1],IDCTBuff[2]);
            /*
             * Write
             */
            for(i = 0; i < RGB_NUM; i++){
                WriteBlock(&rgb_buf[0][i][0],
                           &out_data_comp_vpos[i],
                           &out_data_comp_hpos[i],
                           &OutData_comp_buf[i][0]);
            }
            CurrentMCU++;
        }
        
    }else{
        // printf("Decode 4:1:1 NumMCU = %d\n",p_jinfo_NumMCU);
        /*
         * 4_1_1
         */
        while(CurrentMCU < p_jinfo_NumMCU){
            /*
             * Decode Y element
	         * Decoding Y, U and V elements should be sequentially conducted for the use of Huffman table
             */

            for(i = 0; i < 4; i++){
                decode_block(0, IDCTBuff[i], HuffBuff[0]);
            }
            
            /* Decode U */
            decode_block(1, IDCTBuff[4], HuffBuff[1]);
            
            /* Decode V */
            decode_block(2, IDCTBuff[5], HuffBuff[2]);

            
            /* Transform from Yuv into RGB */

            for(i = 0; i < 4; i++){
                YuvToRgb(i,IDCTBuff[i],IDCTBuff[4],IDCTBuff[5]);
            }


            for(i = 0; i < RGB_NUM; i++){
                Write4Blocks(&rgb_buf[0][i][0],
                            &rgb_buf[1][i][0],
                            &rgb_buf[2][i][0],
                            &rgb_buf[3][i][0],
                            &out_data_comp_vpos[i],
                            &out_data_comp_hpos[i],
                            &OutData_comp_buf[i][0]);
            }
            
            
            CurrentMCU += 4;
        }
    }
}