当前位置: 首页>>代码示例>>C++>>正文


C++ SetError函数代码示例

本文整理汇总了C++中SetError函数的典型用法代码示例。如果您正苦于以下问题:C++ SetError函数的具体用法?C++ SetError怎么用?C++ SetError使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了SetError函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: while

/* Handle first-stage decoding: extracting the MP3 frame data. */
int RageSoundReader_MP3::do_mad_frame_decode( bool headers_only )
{
	int bytes_read = 0;

	while(1)
	{
		int ret;

		/* Always actually decode the first packet, so we cleanly parse Xing tags. */
		if( headers_only && !mad->first_frame )
			ret=mad_header_decode( &mad->Frame.header,&mad->Stream );
		else
			ret=mad_frame_decode( &mad->Frame,&mad->Stream );

		if( ret == -1 && (mad->Stream.error == MAD_ERROR_BUFLEN || mad->Stream.error == MAD_ERROR_BUFPTR) )
		{
			if( bytes_read > 25000 )
			{
				/* We've read this much without actually getting a frame; error. */
				SetError( "Can't find data" );
				return -1;
			}

			ret = fill_buffer();
			if( ret <= 0 )
				return ret;
			bytes_read += ret;

			continue;
		}

		if( ret == -1 && mad->Stream.error == MAD_ERROR_LOSTSYNC )
		{
			/* This might be an ID3V2 tag. */
			const int tagsize = id3_tag_query(mad->Stream.this_frame,
				mad->Stream.bufend - mad->Stream.this_frame);

			if( tagsize )
			{
				mad_stream_skip(&mad->Stream, tagsize);

				/* Don't count the tagsize against the max-read-per-call figure. */
				bytes_read -= tagsize;

				continue;
			}
		}

		if( ret == -1 && mad->Stream.error == MAD_ERROR_BADDATAPTR )
		{
			/*
			 * Something's corrupt.  One cause of this is cutting an MP3 in the middle
			 * without reencoding; the first two frames will reference data from previous
			 * frames that have been removed.  The frame is valid--we can get a header from
			 * it, we just can't synth useful data.
			 *
			 * BASS pretends the bad frames are silent.  Emulate that, for compatibility.
			 */
			ret = 0; /* pretend success */
		}

		if( !ret )
		{
			/* OK. */
			if( mad->first_frame )
			{
				/* We're at the beginning.  Is this a Xing tag? */
				if(handle_first_frame())
				{
					/* The first frame contained a header. Continue searching. */
					continue;
				}

				/* We've decoded the first frame of data. 
				 *
				 * We want mad->Timer to represent the timestamp of the first sample of the
				 * currently decoded frame.  Don't increment mad->Timer on the first frame,
				 * or it'll be the time of the *next* frame.  (All frames have the same
				 * duration.) */
				mad->first_frame = false;
				mad->Timer = mad_timer_zero;
				mad->header_bytes = get_this_frame_byte(mad);
			}
			else
			{
				mad_timer_add( &mad->Timer,mad->Frame.header.duration );
			}

			fill_frame_index_cache( mad );

			return 1;
		}

		if( mad->Stream.error == MAD_ERROR_BADCRC )
		{
			/* XXX untested */
			mad_frame_mute(&mad->Frame);
			mad_synth_mute(&mad->Synth);

//.........这里部分代码省略.........
开发者ID:SamDecrock,项目名称:stepmania5-http-post-scores,代码行数:101,代码来源:RageSoundReader_MP3.cpp

示例2: SetError

void PopSession::ResetError()
{
	SetError(MailError::VALIDATED, "");
}
开发者ID:Garfonso,项目名称:app-services,代码行数:4,代码来源:PopSession.cpp

示例3: sizeof


//.........这里部分代码省略.........

        if (m_pFile != NULL) {

            if (pHeader->nFilledLen > 0) {
                VTEST_MSG_MEDIUM("writing frame %u with %u bytes...",
                        (unsigned int)i, (unsigned int)pHeader->nFilledLen);
                /*
                   unsigned int stride = VENUS_Y_STRIDE(COLOR_FMT_NV12, m_nFrameWidth);
                   unsigned int scanlines = VENUS_Y_SCANLINES(COLOR_FMT_NV12, m_nFrameHeight);
                   char *temp = (char *) pBuffer->pBuffer;
                   int i = 0;

                   temp += (stride * (int)crop_rect.nTop) +  (int)crop_rect.nLeft;
                   for (i = 0; i < crop_rect.nHeight; i++) {
                   bytes_written = fwrite(temp, crop_rect.nWidth, 1, outputBufferFile);
                   temp += stride;
                   }

                   temp = (char *)pBuffer->pBuffer + stride * scanlines;
                   temp += (stride * (int)crop_rect.nTop) +  (int)crop_rect.nLeft;
                   for (i = 0; i < crop_rect.nHeight/2; i++) {
                   bytes_written += fwrite(temp, crop_rect.nWidth, 1, outputBufferFile);
                   temp += stride;
                   }
                */

                OMX_S32 nBytes;
                OMX_U8 *data = pHeader->pBuffer;

                if (m_bSecureSession) {

                    /* This non-sense is done for secure decoder down scalar
                     * feature where beyond a certain threshold, buffer can be
                     * taken out of CPZ by venus */
                    OMX_U8 *data = (OMX_U8 *)mmap(NULL, pHeader->nFilledLen,
                            PROT_READ | PROT_WRITE, MAP_SHARED, (unsigned long)pHeader->pBuffer, 0);
                    if (data == MAP_FAILED) {
                        data = NULL;
                        VTEST_MSG_HIGH("Mapping failed - Assume secure buffer!");
                        if (m_pCrypto != NULL) {
                            data = new OMX_U8[pHeader->nAllocLen];
                            result = m_pCrypto->Copy(SAMPLECLIENT_COPY_SECURE_TO_NONSECURE,
                                    data, (unsigned long)pHeader->pBuffer, pHeader->nFilledLen);
                        } else {
                            VTEST_MSG_ERROR("Crypto object null");
                            result = OMX_ErrorBadParameter;
                        }

                        if (result != OMX_ErrorNone) {
                            VTEST_MSG_ERROR("OEMCrypto_Copy failed, result is %d", result);
                        } else {
                            result = m_pFile->Write(data, pHeader->nFilledLen, &nBytes);
                        }

                        if (data) {
                            delete[] data;
                            data = NULL;
                        }
                    } else {
                        VTEST_MSG_HIGH("Mapping passed! - Assume buffer out of CPZ");
                        result = m_pFile->Write(data, pHeader->nFilledLen, &nBytes);
                        if (munmap(data, pHeader->nFilledLen)) {
                            VTEST_MSG_ERROR("munmap failed for data : %p", data);
                        }
                        data = NULL;
                    }
                } else {
                    result = m_pFile->Write(data, pHeader->nFilledLen, &nBytes);
                }

                if (result != OMX_ErrorNone) {
                    VTEST_MSG_ERROR("Error writing to file...");
                    SetError();
                } else if ((OMX_U32)nBytes != pHeader->nFilledLen) {
                    VTEST_MSG_ERROR(
                            "Error mismatched number of bytes %d vs expected : %d in file write",
                            nBytes, (OMX_S32)pHeader->nFilledLen);
                    SetError();
                    result = OMX_ErrorUndefined;
                }
            } else {
                VTEST_MSG_HIGH("skipping frame %u, 0 length...", (unsigned int)i);
            }
        } else {
            VTEST_MSG_MEDIUM("received frame %u... but did not write as no file present", (unsigned int)i);
        }

        m_pSource->SetBuffer(pBuffer, this);
    }

    //clean up
    while(m_pBufferQueue->GetSize() > 0) {
        VTEST_MSG_LOW("cleanup: q-wait (qsize %u)", (unsigned int)m_pBufferQueue->GetSize());
        m_pBufferQueue->Pop(&pBuffer, sizeof(BufferInfo **), 0);
        m_pSource->SetBuffer(pBuffer, this);
    }

    VTEST_MSG_HIGH("thread exiting...");
    return result;
}
开发者ID:xingrz,项目名称:android_tools_leeco_msm8996,代码行数:101,代码来源:vtest_DecoderFileSink.cpp

示例4: SetError

bool TiXmlDocument::LoadFile( FILE* file, TiXmlEncoding encoding )
{
	if ( !file )
	{
		SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );
		return false;
	}

	// Delete the existing data:
	Clear();
	location.Clear();

	// Get the file size, so we can pre-allocate the string. HUGE speed impact.
	long length = 0;
	fseek( file, 0, SEEK_END );
	length = ftell( file );
	fseek( file, 0, SEEK_SET );

	// Strange case, but good to handle up front.
	if ( length <= 0 )
	{
		SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
		return false;
	}

	// If we have a file, assume it is all one big XML file, and read it in.
	// The document parser may decide the document ends sooner than the entire file, however.
	TIXML_STRING data;
	data.reserve( length );

	// Subtle bug here. TinyXml did use fgets. But from the XML spec:
	// 2.11 End-of-Line Handling
	// <snip>
	// <quote>
	// ...the XML processor MUST behave as if it normalized all line breaks in external
	// parsed entities (including the document entity) on input, before parsing, by translating
	// both the two-character sequence #xD #xA and any #xD that is not followed by #xA to
	// a single #xA character.
	// </quote>
	//
	// It is not clear fgets does that, and certainly isn't clear it works cross platform.
	// Generally, you expect fgets to translate from the convention of the OS to the c/unix
	// convention, and not work generally.

	/*
	while( fgets( buf, sizeof(buf), file ) )
	{
		data += buf;
	}
	*/

	char* buf = new char[ length+1 ];
	buf[0] = 0;

	if ( fread( buf, length, 1, file ) != 1 ) {
		delete [] buf;
		SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );
		return false;
	}

	const char* lastPos = buf;
	const char* p = buf;

	buf[length] = 0;
	while( *p ) {
		assert( p < (buf+length) );
		if ( *p == 0xa ) {
			// Newline character. No special rules for this. Append all the characters
			// since the last string, and include the newline.
			data.append( lastPos, (p-lastPos+1) );	// append, include the newline
			++p;									// move past the newline
			lastPos = p;							// and point to the new buffer (may be 0)
			assert( p <= (buf+length) );
		}
		else if ( *p == 0xd ) {
			// Carriage return. Append what we have so far, then
			// handle moving forward in the buffer.
			if ( (p-lastPos) > 0 ) {
				data.append( lastPos, p-lastPos );	// do not add the CR
			}
			data += (char)0xa;						// a proper newline

			if ( *(p+1) == 0xa ) {
				// Carriage return - new line sequence
				p += 2;
				lastPos = p;
				assert( p <= (buf+length) );
			}
			else {
				// it was followed by something else...that is presumably characters again.
				++p;
				lastPos = p;
				assert( p <= (buf+length) );
			}
		}
		else {
			++p;
		}
	}
	// Handle any left over characters.
//.........这里部分代码省略.........
开发者ID:4ian,项目名称:GD,代码行数:101,代码来源:tinyxml.cpp

示例5: SetError

EXPORT_C void CPartContainerXml::Error(XML_Error Code, const XML_LChar * /*String*/, long /*ByteIndex*/)
{
	SetError(Code);
}
开发者ID:flaithbheartaigh,项目名称:jaikuengine-mobile-client,代码行数:4,代码来源:bbxml.cpp

示例6: Clear

bool TiXmlDocument::LoadFile( const char* filename, TiXmlEncoding encoding )
{
	// Delete the existing data:
	Clear();
	location.Clear();

	// There was a really terrifying little bug here. The code:
	//		value = filename
	// in the STL case, cause the assignment method of the std::string to
	// be called. What is strange, is that the std::string had the same
	// address as it's c_str() method, and so bad things happen. Looks
	// like a bug in the Microsoft STL implementation.
	// See STL_STRING_BUG above.
	// Fixed with the StringToBuffer class.
	value = filename;

	//SECURITY-UPDATE:2/3/07
	//FILE* file = fopen( value.c_str (), "r" );
	//if ( file )
	//{

	FILE *file=NULL;
	errno_t err=0;

	err=fopen_s(&file,value.c_str (), "r");

	if(file && err==0)
	{
		// Get the file size, so we can pre-allocate the string. HUGE speed impact.
		long length = 0;
		fseek( file, 0, SEEK_END );
		length = ftell( file );
		fseek( file, 0, SEEK_SET );

		// Strange case, but good to handle up front.
		if ( length == 0 )
		{
			fclose( file );
			return false;
		}

		// If we have a file, assume it is all one big XML file, and read it in.
		// The document parser may decide the document ends sooner than the entire file, however.
		TIXML_STRING data;
		data.reserve( length );

		const int BUF_SIZE = 2048;
		char buf[BUF_SIZE];

		while( fgets( buf, BUF_SIZE, file ) )
		{
			data += buf;
		}
		fclose( file );

		Parse( data.c_str(), 0, encoding );

		if (  Error() )
            return false;
        else
			return true;
	}
	SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );
	return false;
}
开发者ID:carussell,项目名称:nvvg,代码行数:65,代码来源:tinyxml.cpp

示例7: ExpandTildes

static bool ExpandTildes(char *thePattern,char *newPattern,UINT32 newPatternLength)
// expand tilde sequences in thePattern, write output into newPattern
// if there is a problem, SetError, and return false
{
	bool
		done,
		fail;
	char
		theChar;
	UINT32
		inIndex,
		outIndex;
	char
		*theHome;
	struct passwd
		*passwordEntry;
	UINT32
		theLength;

	fail=false;
	if(thePattern[0]=='~')	// see if a tilde exists at the start of thePattern
	{
		inIndex=1;			// skip the tilde
		outIndex=0;
		done=false;
		while(!done&&!fail&&(theChar=thePattern[inIndex])&&outIndex<(newPatternLength-1))
		{
			switch(theChar)
			{
				case PATHSEP:
					inIndex++;
					done=true;
					break;
				case '\\':
					inIndex++;
					if(!(newPattern[outIndex++]=thePattern[inIndex]))
					{
						SetError(localErrorFamily,errorMembers[DANGLINGQUOTE],errorDescriptions[DANGLINGQUOTE]);
						fail=true;
					}
					break;
				default:
					newPattern[outIndex++]=theChar;
					inIndex++;
					break;
			}
		}
		if(!fail)
		{
			newPattern[outIndex]='\0';		// terminate the user name string
			theHome=NULL;					// no home found yet
			if(outIndex)					// name was specified
			{
				if((passwordEntry=getpwnam(newPattern)))
				{
					theHome=passwordEntry->pw_dir;
				}
			}
			else
			{
				if(!(theHome=getenv("HOME")))	// try to find environment variable
				{
					if((passwordEntry=getpwuid(getuid())))	// if no environment, try to get from password database
					{
						theHome=passwordEntry->pw_dir;
					}
				}
			}
			if(theHome)
			{
				strncpy(newPattern,theHome,newPatternLength-1);
				newPattern[newPatternLength-1]='\0';
				theLength=strlen(newPattern);
				if(theLength&&theLength<newPatternLength-1)
				{
					if(newPattern[theLength-1]!=PATHSEP)	// add path separator if needed
					{
						newPattern[theLength++]=PATHSEP;
						newPattern[theLength]='\0';
					}
				}
				strncat(newPattern,&thePattern[inIndex],newPatternLength-theLength);
			}
			else
			{
				SetError(localErrorFamily,errorMembers[NOUSER],errorDescriptions[NOUSER]);	// user not there
				fail=true;
			}
		}
	}
	else
	{
		strncpy(newPattern,thePattern,newPatternLength-1);
		newPattern[newPatternLength-1]='\0';
	}
	return(!fail);
}
开发者ID:JamesLinus,项目名称:e93,代码行数:97,代码来源:glob.c

示例8: MatchRange

static bool MatchRange(char theChar,char *thePattern,UINT32 *patternIndex,bool *haveMatch)
// a range is starting in thePattern, so attempt to match theChar
// against it
{
	bool
		fail,
		done,
		isNot;
	char
		testChar,
		lastChar;

	isNot=done=fail=false;
	if(thePattern[*patternIndex]=='^')				// check for not flag
	{
		isNot=true;
		(*patternIndex)++;
	}
	lastChar='\0';									// start with bottom of range at 0
	*haveMatch=false;
	while(!done&&!fail&&(testChar=thePattern[(*patternIndex)++]))
	{
		switch(testChar)
		{
			case '\\':
				if((testChar=thePattern[(*patternIndex)++]))	// get next character to test
				{
					if(theChar==testChar)					// test it literally
					{
						*haveMatch=true;
					}
				}
				else
				{
					SetError(localErrorFamily,errorMembers[DANGLINGQUOTE],errorDescriptions[DANGLINGQUOTE]);
					fail=true;						// got \ at the end of the pattern
				}
				break;
			case '-':
				if((testChar=thePattern[(*patternIndex)++]))		// get the next character for the range (if there is one)
				{
					switch(testChar)
					{
						case '\\':
							if((testChar=thePattern[(*patternIndex)++]))
							{
								if(theChar>=lastChar&&theChar<=testChar)
								{
									*haveMatch=true;
								}
							}
							else
							{
								SetError(localErrorFamily,errorMembers[DANGLINGQUOTE],errorDescriptions[DANGLINGQUOTE]);
								fail=true;						// got \ at the end of the pattern
							}
							break;
						case ']':
							if(theChar>=lastChar)				// empty range at end, so take as infinite end
							{
								*haveMatch=true;
							}
							done=true;
							break;
						default:
							if(theChar>=lastChar&&theChar<=testChar)
							{
								*haveMatch=true;
							}
							break;
					}
				}
				else
				{
					SetError(localErrorFamily,errorMembers[UNBALANCEDSQUAREBRACKET],errorDescriptions[UNBALANCEDSQUAREBRACKET]);
					fail=true;
				}
				break;
			case ']':
				done=true;							// scanning is done (empty lists are allowed)
				break;
			default:								// otherwise it is normal, and just gets tested
				if(theChar==testChar)
				{
					*haveMatch=true;
				}
				break;
		}
		lastChar=testChar;							// remember this for next time around the loop
	}
	if(!done&&!fail)								// ran out of things to scan
	{
		SetError(localErrorFamily,errorMembers[UNBALANCEDSQUAREBRACKET],errorDescriptions[UNBALANCEDSQUAREBRACKET]);
		fail=true;
	}
	if(!fail)
	{
		if(isNot)
		{
			*haveMatch=!*haveMatch;
//.........这里部分代码省略.........
开发者ID:JamesLinus,项目名称:e93,代码行数:101,代码来源:glob.c

示例9: fin

bool mglTexture::LoadTGA(const mtlDirectory &p_filename)
{
	std::ifstream fin(p_filename.GetDirectory().GetChars(), std::ios::binary);
	if (!fin.is_open()) {
		SetError("File unreadable");
		return false;
	}
	enum RelevantHeaderField
	{
		COLOR_MAP_TYPE	= 1,
		IMAGE_TYPE		= 2,
		IMAGE_WIDTH		= 12,
		IMAGE_HEIGHT	= 14,
		PIXEL_DEPTH		= 16,
		HEADER_SIZE		= 18
	};
	enum SupportedColorMapType
	{
		NO_COLOR_MAP
	};
	enum SupportedTextureType
	{
		UNCOMPRESSED_TRUECOLOR_IMAGE	= 2,
		UNCOMPRESSED_GRAYSCALE_IMAGE	= 3,
		COMPRESSED_TRUECOLOR_IMAGE		= 10,
		COMPRESSED_GRAYSCALE_IMAGE		= 11
	};
	enum SupportedPixelDepth
	{
		GRAY8		= 8,
		BGRA5551	= 16,
		BGR888		= 24,
		BGRA8888	= 32
	};

	unsigned char header[HEADER_SIZE];
	fin.read((char*)header, HEADER_SIZE);
	if (fin.fail()) {
		SetError("Reading TGA header failed");
		return false;
	}
	if (header[COLOR_MAP_TYPE] != NO_COLOR_MAP) {
		SetError("TGA contains color map");
		return false;
	}
	
	int bpp = header[PIXEL_DEPTH] == BGRA8888 ? 4 : (header[PIXEL_DEPTH] == BGR888 ? 3 : -1);
	if (header[IMAGE_TYPE] == UNCOMPRESSED_TRUECOLOR_IMAGE || header[IMAGE_TYPE] == COMPRESSED_TRUECOLOR_IMAGE) {
		if (header[PIXEL_DEPTH] == BGRA8888) {
			bpp = 4;
		} else if (header[PIXEL_DEPTH] == BGR888) {
			bpp = 3;
		} else {
			bpp = -1;
		}
	} else if (header[IMAGE_TYPE] == UNCOMPRESSED_GRAYSCALE_IMAGE || header[IMAGE_TYPE] == COMPRESSED_GRAYSCALE_IMAGE) {
		if (header[PIXEL_DEPTH] == GRAY8) {
			bpp = 1;
		} else {
			bpp = -1;
		}
	}
	
	if (bpp == -1) {
		SetError("Unsupported pixel depth");
		return false;
	}
	
	int w = (int)(*(unsigned short*)(header+IMAGE_WIDTH));
	int h = (int)(*(unsigned short*)(header+IMAGE_HEIGHT));
	if (w != h) {
		SetError("Dimensions are not equal");
		return false;
	}
	if (!Create(w)) {
		return false;
	}

	if (header[IMAGE_TYPE] == UNCOMPRESSED_TRUECOLOR_IMAGE) {
		
		const int SIZE = GetArea();
		// allocate one byte extra, since we will need to read one garbage byte when
		// converting a pointer to 3 bytes to a pointer 4 (unsigned int)
		unsigned char *image = new unsigned char[SIZE*bpp + 1];

		if (fin.read((char*)image, SIZE*bpp).bad()) {
			SetError("Reading pixel data failed");
			delete [] image;
			return false;
		}
		
		unsigned char *imageData = image;
		if (bpp == 3) {
			
			for (int i = 0; i < SIZE; ++i) {
				const unsigned int color = (*(unsigned int*)(imageData));
				const unsigned int b = (color & TargaFormat.BMask) >> TargaFormat.BShift;
				const unsigned int g = (color & TargaFormat.GMask) >> TargaFormat.GShift;
				const unsigned int r = (color & TargaFormat.RMask) >> TargaFormat.RShift;
				m_pixels[i] =
//.........这里部分代码省略.........
开发者ID:shujunqiao,项目名称:MiniLib,代码行数:101,代码来源:mglTexture.cpp

示例10: WriteTrace

bool CN64Disk::AllocateAndLoadDiskImage(const char * FileLoc)
{
    WriteTrace(TraceN64System, TraceDebug, "Trying to open %s", FileLoc);
    if (!m_DiskFile.Open(FileLoc, CFileBase::modeRead))
    {
        WriteTrace(TraceN64System, TraceError, "Failed to open %s", FileLoc);
        return false;
    }

    //Read the first 4 bytes and make sure it is a valid disk image
    uint8_t Test[4];
    m_DiskFile.SeekToBegin();
    if (m_DiskFile.Read(Test, sizeof(Test)) != sizeof(Test))
    {
        m_DiskFile.Close();
        WriteTrace(TraceN64System, TraceError, "Failed to read ident bytes");
        return false;
    }
    if (!IsValidDiskImage(Test))
    {
        m_DiskFile.Close();
        WriteTrace(TraceN64System, TraceError, "invalid image file %X %X %X %X", Test[0], Test[1], Test[2], Test[3]);
        return false;
    }
    uint32_t DiskFileSize = m_DiskFile.GetLength();
    WriteTrace(TraceN64System, TraceDebug, "Successfully Opened, size: 0x%X", DiskFileSize);

    //Check Disk File Format
    if (DiskFileSize == MameFormatSize)
    {
        //If Disk is MAME Format (size is constant, it should be the same for every file), then continue
        WriteTrace(TraceN64System, TraceDebug, "Disk File is MAME Format");

        if (!AllocateDiskImage(DiskFileSize))
        {
            m_DiskFile.Close();
            return false;
        }

        //Load the n64 disk to the allocated memory
        g_Notify->DisplayMessage(5, MSG_LOADING);
        m_DiskFile.SeekToBegin();

        uint32_t count, TotalRead = 0;
        for (count = 0; count < (int)DiskFileSize; count += ReadFromRomSection)
        {
            uint32_t dwToRead = DiskFileSize - count;
            if (dwToRead > ReadFromRomSection) { dwToRead = ReadFromRomSection; }

            if (m_DiskFile.Read(&m_DiskImage[count], dwToRead) != dwToRead)
            {
                m_DiskFile.Close();
                SetError(MSG_FAIL_IMAGE);
                WriteTrace(TraceN64System, TraceError, "Failed to read file (TotalRead: 0x%X)", TotalRead);
                return false;
            }
            TotalRead += dwToRead;

            //Show Message of how much % wise of the rom has been loaded
            g_Notify->DisplayMessage(0, stdstr_f("%s: %.2f%c", GS(MSG_LOADED), ((float)TotalRead / (float)DiskFileSize) * 100.0f, '%').c_str());
        }

        if (DiskFileSize != TotalRead)
        {
            m_DiskFile.Close();
            SetError(MSG_FAIL_IMAGE);
            WriteTrace(TraceN64System, TraceError, "Expected to read: 0x%X, read: 0x%X", TotalRead, DiskFileSize);
            return false;
        }
    }
    else if (DiskFileSize == SDKFormatSize)
    {
        //If Disk is SDK format (made with SDK based dumpers like LuigiBlood's, or Nintendo's, size is also constant)
        //We need to convert it.
        g_Notify->DisplayMessage(5, MSG_LOADING);

        //Allocate supported size
        if (!AllocateDiskImage(MameFormatSize))
        {
            m_DiskFile.Close();
            return false;
        }

        ConvertDiskFormat();
    }
    else
    {
        //Else the disk file is invalid
        m_DiskFile.Close();
        WriteTrace(TraceN64System, TraceError, "Disk File is invalid, unexpected size");
        return false;
    }

    g_Notify->DisplayMessage(5, MSG_BYTESWAP);
    ByteSwapDisk();

    ProtectMemory(m_DiskImage, m_DiskFileSize, MEM_READWRITE);
    return true;
}
开发者ID:guimmp,项目名称:project64,代码行数:99,代码来源:N64DiskClass.cpp

示例11: free

/**
 * Accept the GSI Authentication.
 * @param sock the socket for communication.
 * @param ctx the authorization context.
 * @return the context identifier. 
 */
bool
GSISocketServer::AcceptGSIAuthentication()
{
  char *name = NULL;
  long  errorcode = 0;
  int   flags;

  time_t curtime, starttime;
  int ret, accept_status;
  bool accept_timed_out = false;
  int expected = 0;
  BIO *bio = NULL;
  char *cert_file, *user_cert, *user_key, *user_proxy;
  char *serial=NULL;

  cert_file = user_cert = user_key = user_proxy = NULL;

  if (proxy_get_filenames(0, &cert_file, &cacertdir, &user_proxy, &user_cert, &user_key) == 0) {
    (void)load_credentials(user_cert, user_key, &ucert, &own_stack, &upkey, NULL);
  }

  free(cert_file);
  free(user_cert);
  free(user_key);
  free(user_proxy);

  own_cert = ucert;
  own_key = upkey;
  ctx = SSL_CTX_new(SSLv23_method());
  SSL_CTX_load_verify_locations(ctx, NULL, cacertdir);
  SSL_CTX_use_certificate(ctx, ucert);
  SSL_CTX_use_PrivateKey(ctx,upkey);
  SSL_CTX_set_cipher_list(ctx, "ALL:!LOW:!EXP:!MD5:!MD2");    
  SSL_CTX_set_purpose(ctx, X509_PURPOSE_ANY);
  SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
  SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, proxy_verify_callback);
  SSL_CTX_set_verify_depth(ctx, 100);
  SSL_CTX_set_cert_verify_callback(ctx, proxy_app_verify_callback, 0);

  if (own_stack) {
    /*
     * Certificate was a proxy with a cert. chain.
     * Add the certificates one by one to the chain.
     */
    X509_STORE_add_cert(ctx->cert_store, ucert);
    for (int i = 0; i <sk_X509_num(own_stack); ++i) {
      X509 *cert = (sk_X509_value(own_stack,i));

      if (!X509_STORE_add_cert(ctx->cert_store, cert)) {
        if (ERR_GET_REASON(ERR_peek_error()) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
          ERR_clear_error();
          continue;
        }
        else {
          SetErrorOpenSSL("Cannot add certificate to the SSL context's certificate store");
          goto err;
        }
      }
    }
  }

  flags = fcntl(newsock, F_GETFL, 0);
  (void)fcntl(newsock, F_SETFL, flags | O_NONBLOCK);

  bio = BIO_new_socket(newsock, BIO_NOCLOSE);
  (void)BIO_set_nbio(bio, 1);

  ssl = SSL_new(ctx);
  setup_SSL_proxy_handler(ssl, cacertdir);

  writeb = bio->method->bwrite;
  readb  = bio->method->bread;
  bio->method->bwrite = globusf_write;
  bio->method->bread  = globusf_read;

  SSL_set_bio(ssl, bio, bio);

  curtime = starttime = time(NULL);

  ret = accept_status = -1;
  expected = 0;

  do {

    ret = do_select(newsock, starttime, timeout, expected);
    LOGM(VARP, logh, LEV_DEBUG, T_PRE, "Select status: %d",ret);

    curtime = time(NULL);


    if (ret == 0){

      LOGM(VARP, logh, LEV_DEBUG, T_PRE, "Select timed out.");

//.........这里部分代码省略.........
开发者ID:andreaceccanti,项目名称:voms,代码行数:101,代码来源:Server.cpp

示例12: CMICMDBASE_GETOPTION

//++ ------------------------------------------------------------------------------------
// Details: The invoker requires this function. The command does work in this function.
//          The command is likely to communicate with the LLDB SBDebugger in here.
// Type:    Overridden.
// Args:    None.
// Return:  MIstatus::success - Functional succeeded.
//          MIstatus::failure - Functional failed.
// Throws:  None.
//--
bool
CMICmdCmdStackListArguments::Execute()
{
    CMICMDBASE_GETOPTION(pArgThread, OptionLong, m_constStrArgThread);
    CMICMDBASE_GETOPTION(pArgPrintValues, PrintValues, m_constStrArgPrintValues);
    CMICMDBASE_GETOPTION(pArgFrameLow, Number, m_constStrArgFrameLow);
    CMICMDBASE_GETOPTION(pArgFrameHigh, Number, m_constStrArgFrameHigh);

    // Retrieve the --thread option's thread ID (only 1)
    MIuint64 nThreadId = UINT64_MAX;
    if (pArgThread->GetFound())
    {
        if (!pArgThread->GetExpectedOption<CMICmdArgValNumber, MIuint64>(nThreadId))
        {
            SetError(CMIUtilString::Format(MIRSRC(IDS_CMD_ERR_OPTION_NOT_FOUND), m_cmdData.strMiCmd.c_str(), m_constStrArgThread.c_str()));
            return MIstatus::failure;
        }
    }

    const CMICmnLLDBDebugSessionInfo::VariableInfoFormat_e eVarInfoFormat = static_cast<CMICmnLLDBDebugSessionInfo::VariableInfoFormat_e>(pArgPrintValues->GetValue());

    MIuint nFrameLow = 0;
    MIuint nFrameHigh = UINT32_MAX;
    if (pArgFrameLow->GetFound() && pArgFrameHigh->GetFound())
    {
        nFrameLow = pArgFrameLow->GetValue();
        nFrameHigh = pArgFrameHigh->GetValue() + 1;
    }
    else if (pArgFrameLow->GetFound() || pArgFrameHigh->GetFound())
    {
        // Only low-frame or high-frame was specified but both are required
        SetError(CMIUtilString::Format(MIRSRC(IDS_CMD_ERR_THREAD_FRAME_RANGE_INVALID), m_cmdData.strMiCmd.c_str()));
        return MIstatus::failure;
    }

    CMICmnLLDBDebugSessionInfo &rSessionInfo(CMICmnLLDBDebugSessionInfo::Instance());
    lldb::SBProcess sbProcess = rSessionInfo.GetProcess();
    lldb::SBThread thread = (nThreadId != UINT64_MAX) ? sbProcess.GetThreadByIndexID(nThreadId) : sbProcess.GetSelectedThread();
    m_bThreadInvalid = !thread.IsValid();
    if (m_bThreadInvalid)
        return MIstatus::success;

    const lldb::StopReason eStopReason = thread.GetStopReason();
    if ((eStopReason == lldb::eStopReasonNone) || (eStopReason == lldb::eStopReasonInvalid))
    {
        m_bThreadInvalid = true;
        return MIstatus::success;
    }

    const MIuint nFrames = thread.GetNumFrames();
    if (nFrameLow >= nFrames)
    {
        // The low-frame is larger than the actual number of frames
        SetError(CMIUtilString::Format(MIRSRC(IDS_CMD_ERR_THREAD_FRAME_RANGE_INVALID), m_cmdData.strMiCmd.c_str()));
        return MIstatus::failure;
    }

    nFrameHigh = std::min(nFrameHigh, nFrames);
    for (MIuint i = nFrameLow; i < nFrameHigh; i++)
    {
        lldb::SBFrame frame = thread.GetFrameAtIndex(i);
        CMICmnMIValueList miValueList(true);
        const MIuint maskVarTypes = CMICmnLLDBDebugSessionInfo::eVariableType_Arguments;
        if (!rSessionInfo.MIResponseFormVariableInfo(frame, maskVarTypes, eVarInfoFormat, miValueList))
            return MIstatus::failure;
        const CMICmnMIValueConst miValueConst(CMIUtilString::Format("%d", i));
        const CMICmnMIValueResult miValueResult("level", miValueConst);
        CMICmnMIValueTuple miValueTuple(miValueResult);
        const CMICmnMIValueResult miValueResult2("args", miValueList);
        miValueTuple.Add(miValueResult2);
        const CMICmnMIValueResult miValueResult3("frame", miValueTuple);
        m_miValueList.Add(miValueResult3);
    }

    return MIstatus::success;
}
开发者ID:JuliaLang,项目名称:lldb,代码行数:85,代码来源:MICmdCmdStack.cpp

示例13: LOG

nsresult
CacheFileChunk::OnDataRead(CacheFileHandle *aHandle, char *aBuf,
                           nsresult aResult)
{
  LOG(("CacheFileChunk::OnDataRead() [this=%p, handle=%p, result=0x%08x]",
       this, aHandle, aResult));

  nsCOMPtr<CacheFileChunkListener> listener;

  {
    CacheFileAutoLock lock(mFile);

    MOZ_ASSERT(mState == READING);
    MOZ_ASSERT(mListener);

    if (NS_SUCCEEDED(aResult)) {
      CacheHash::Hash16_t hash = CacheHash::Hash16(mRWBuf, mRWBufSize);
      if (hash != mReadHash) {
        LOG(("CacheFileChunk::OnDataRead() - Hash mismatch! Hash of the data is"
             " %hx, hash in metadata is %hx. [this=%p, idx=%d]",
             hash, mReadHash, this, mIndex));
        aResult = NS_ERROR_FILE_CORRUPTED;
      }
      else {
        if (!mBuf) {
          // Just swap the buffers if we don't have mBuf yet
          MOZ_ASSERT(mDataSize == mRWBufSize);
          mBuf = mRWBuf;
          mBufSize = mRWBufSize;
          mRWBuf = nullptr;
          mRWBufSize = 0;
        } else {
          LOG(("CacheFileChunk::OnDataRead() - Merging buffers. [this=%p]",
               this));

          // Merge data with write buffer
          if (mRWBufSize >= mBufSize) {
            // The new data will fit into the buffer that contains data read
            // from the disk. Simply copy the valid pieces.
            mValidityMap.Log();
            for (uint32_t i = 0; i < mValidityMap.Length(); i++) {
              if (mValidityMap[i].Offset() + mValidityMap[i].Len() > mBufSize) {
                MOZ_CRASH("Unexpected error in validity map!");
              }
              memcpy(mRWBuf + mValidityMap[i].Offset(),
                     mBuf + mValidityMap[i].Offset(), mValidityMap[i].Len());
            }
            mValidityMap.Clear();

            free(mBuf);
            mBuf = mRWBuf;
            mBufSize = mRWBufSize;
            mRWBuf = nullptr;
            mRWBufSize = 0;
            ChunkAllocationChanged();
          } else {
            // Buffer holding the new data is larger. Use it as the destination
            // buffer to avoid reallocating mRWBuf. We need to copy those pieces
            // from mRWBuf which are not valid in mBuf.
            uint32_t invalidOffset = 0;
            uint32_t invalidLength;
            mValidityMap.Log();
            for (uint32_t i = 0; i < mValidityMap.Length(); i++) {
              MOZ_ASSERT(invalidOffset <= mValidityMap[i].Offset());
              invalidLength = mValidityMap[i].Offset() - invalidOffset;
              if (invalidLength > 0) {
                if (invalidOffset + invalidLength > mRWBufSize) {
                  MOZ_CRASH("Unexpected error in validity map!");
                }
                memcpy(mBuf + invalidOffset, mRWBuf + invalidOffset,
                       invalidLength);
              }
              invalidOffset = mValidityMap[i].Offset() + mValidityMap[i].Len();
            }
            if (invalidOffset < mRWBufSize) {
              invalidLength = mRWBufSize - invalidOffset;
              memcpy(mBuf + invalidOffset, mRWBuf + invalidOffset,
                     invalidLength);
            }
            mValidityMap.Clear();

            free(mRWBuf);
            mRWBuf = nullptr;
            mRWBufSize = 0;
            ChunkAllocationChanged();
          }

          DoMemoryReport(MemorySize());
        }
      }
    }

    if (NS_FAILED(aResult)) {
      aResult = mIndex ? NS_ERROR_FILE_CORRUPTED : NS_ERROR_FILE_NOT_FOUND;
      SetError(aResult);
      mDataSize = 0;
    }

    mState = READY;
    mListener.swap(listener);
//.........这里部分代码省略.........
开发者ID:logicoftekk,项目名称:cyberfox,代码行数:101,代码来源:CacheFileChunk.cpp

示例14: SetErrors

BOOL CDib::Open(HWND hWnd, const char *pFileName, BOOL bOpenFromFile)
{
	/*
	UINT fuLoad;

	if(bOpenFromFile==TRUE)
		fuLoad = LR_CREATEDIBSECTION|LR_LOADFROMFILE|LR_DEFAULTSIZE;
	else
		fuLoad = (bOpenFromFile?LR_CREATEDIBSECTION:0)|LR_LOADFROMFILE|LR_DEFAULTSIZE;
	*/
	m_hBitmap=(HBITMAP)::LoadImage(
		(HINSTANCE)GetWindowLong(hWnd,GWL_HINSTANCE),
		pFileName,
		IMAGE_BITMAP,
		0,0,
		//fuLoad);
		LR_CREATEDIBSECTION|(bOpenFromFile?LR_LOADFROMFILE:0)|LR_DEFAULTSIZE);
	if(m_hBitmap==NULL){
		SetErrors(CMERR_CANT_OPEN_FILE,pFileName);
		return FALSE;
	}

	BITMAP bm;
	BITMAPINFOHEADER bi;
	LPBITMAPINFOHEADER lpbi;	// 24bit라서 팔레트 정보가 없을 것이므로 필요없으나... 확장을 위해

	GetObject(m_hBitmap,sizeof(BITMAP),&bm);

	if(bm.bmHeight>=0)m_bTopDown=FALSE;
	else m_bTopDown=TRUE;

    bi.biSize				= sizeof(BITMAPINFOHEADER);
    bi.biWidth				= bm.bmWidth;
    bi.biHeight				= bm.bmHeight;
    bi.biPlanes				= 1;
    //bi.biBitCount           = bm.bmPlanes * bm.bmBitsPixel;
	bi.biBitCount			= 24;			// 8bit 도 24bit로 읽어낸다. 따라서 Pal 정보가 없다.
    bi.biCompression		= BI_RGB;
    bi.biSizeImage			= 0;
    bi.biXPelsPerMeter		= 0;
    bi.biYPelsPerMeter		= 0;
    bi.biClrUsed			= 0;
    bi.biClrImportant		= 0;

// 팔레트 개수
#define DibNumColors(lpbi)	((lpbi)->biClrUsed == 0 && (lpbi)->biBitCount <= 8 \
								? (WORD)(1 << (int)(lpbi)->biBitCount) \
								: (WORD)(lpbi)->biClrUsed)

	// BITMAPINFO( BITMAPINFOHEADER+PAL ) 의 크기
	DWORD nLen  = bi.biSize + DibNumColors(&bi) * sizeof(RGBQUAD);

	lpbi=(LPBITMAPINFOHEADER)new char[nLen];

	*lpbi=bi;

	HDC hDC=GetDC(hWnd);
	GetDIBits(hDC,m_hBitmap,0,bi.biHeight,NULL,(LPBITMAPINFO)lpbi,DIB_RGB_COLORS);
	ReleaseDC(hWnd,hDC);

	bi=*lpbi;

	// 드라이버가 biSizeImage를 채우지 않는 경우
	if(bi.biSizeImage==0){
		bi.biSizeImage=(DWORD)WIDTHBYTES(bm.bmWidth*bi.biBitCount)*bm.bmHeight;
		if(bi.biCompression!=BI_RGB)
			bi.biSizeImage=(bi.biSizeImage*3)/2;
	}

	delete[] lpbi;

	nLen=bi.biSize+DibNumColors(&bi)*sizeof(RGBQUAD)+bi.biSizeImage;

	//lpbi=(LPBITMAPINFOHEADER)new char[nLen];
	m_pBitmapData=new BYTE[nLen];

	if(m_pBitmapData==NULL){
		//_RPT0(_CRT_WARN,"Memory Allocation Error");
		SetError(CMERR_OUT_OF_MEMORY);
		return FALSE;
	}

	*(LPBITMAPINFOHEADER)m_pBitmapData=bi;

	hDC=GetDC(hWnd);
	GetDIBits(hDC,m_hBitmap,0,bi.biHeight,DibPtr((LPBITMAPINFOHEADER)m_pBitmapData),(LPBITMAPINFO)m_pBitmapData,DIB_RGB_COLORS);
	ReleaseDC(hWnd,hDC);
	
	return TRUE;
}
开发者ID:MagistrAVSH,项目名称:node3d,代码行数:90,代码来源:Dib.cpp

示例15: MatchName

static bool MatchName(char *theName,char *thePattern,UINT32 *patternIndex,bool *haveMatch)
// match theName against thePattern
// thePattern points to the start of a pattern terminated with a '\0', or a PATHSEP
// update patternIndex to point to the character that stopped the match
// if a match occurs, return true if have match
// if there is a problem SetError, and return false
{
	UINT32
		nameIndex;
	UINT32
		startPatternIndex;
	bool
		fail,
		done,
		matching;
	char
		theChar;

	fail=*haveMatch=done=false;
	matching=true;
	nameIndex=0;
	while(!done&&matching)
	{
		switch(thePattern[*patternIndex])
		{
			case '\0':				// ran out of characters of the pattern
			case PATHSEP:
				matching=(theName[nameIndex]=='\0');
				done=true;
				break;
			case '*':
				(*patternIndex)++;	// move past the *
				matching=false;
				do
				{
					startPatternIndex=*patternIndex;
					fail=!MatchName(&theName[nameIndex],thePattern,&startPatternIndex,&matching);
				}
				while(theName[nameIndex++]&&!fail&&!matching);			// recurse trying to make a match
				if(matching)
				{
					*patternIndex=startPatternIndex;
					done=true;
				}
				break;
			case '?':
				(*patternIndex)++;
				matching=(theName[nameIndex++]!='\0');
				break;
			case '[':
				(*patternIndex)++;
				if((theChar=theName[nameIndex++]))
				{
					fail=!MatchRange(theChar,thePattern,patternIndex,&matching);
				}
				else
				{
					matching=false;
				}
				break;
			case '\\':
				(*patternIndex)++;
				if((theChar=thePattern[(*patternIndex)++]))
				{
					matching=(theName[nameIndex++]==theChar);
				}
				else
				{
					SetError(localErrorFamily,errorMembers[DANGLINGQUOTE],errorDescriptions[DANGLINGQUOTE]);
					fail=true;
				}
				break;
			default:
				matching=(theName[nameIndex++]==thePattern[(*patternIndex)++]);
				break;
		}
	}
	if(!fail)
	{
		*haveMatch=matching;
	}
	return(!fail);
}
开发者ID:JamesLinus,项目名称:e93,代码行数:83,代码来源:glob.c


注:本文中的SetError函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。