/* 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);

			continue;
		}

		if( !MAD_RECOVERABLE(mad->Stream.error) )
		{
			/* We've received an unrecoverable error. */
			SetError( mad_stream_errorstr(&mad->Stream) );
			return -1;
		}
	}
}
Exemple #2
0
void PopSession::ResetError()
{
	SetError(MailError::VALIDATED, "");
}
OMX_ERRORTYPE DecoderFileSink::ThreadRun(OMX_PTR pThreadData) {

    (void)pThreadData;
    OMX_ERRORTYPE result = OMX_ErrorNone;
    OMX_BUFFERHEADERTYPE *pHeader = NULL;
    BufferInfo *pBuffer = NULL;

    for (OMX_U32 i = 1; i <= m_nFrames && !m_bThreadStop; i++) {

        result = m_pBufferQueue->Pop(&pBuffer, sizeof(pBuffer), 0);
        VTEST_MSG_LOW("queue pop %u of %u (qsize %u)",
                (unsigned int)i, (unsigned int)m_nFrames, (unsigned int)m_pBufferQueue->GetSize());

        if ((pBuffer == NULL) || (result != OMX_ErrorNone)) {
            /* Can only happen if stop is called or someone else ran into an
             * error */
            VTEST_MSG_HIGH("Stopping thread");
            result = OMX_ErrorNone;
            continue;
        }

        pHeader = pBuffer->pHeaderIn;
        if (pHeader->nFlags & OMX_BUFFERFLAG_ENDOFFRAME) {
            VTEST_MSG_HIGH("frames written %u", (unsigned int)i);
        }

        if ((pHeader->nFlags & OMX_BUFFERFLAG_EOS) || (i >= m_nFrames)) {
            VTEST_MSG_HIGH("got EOS for frame : %u", (unsigned int)i);
            m_bThreadStop = OMX_TRUE;
        }

        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;
}
Exemple #4
0
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.
	if ( p-lastPos ) {
		data.append( lastPos, p-lastPos );
	}
	delete [] buf;
	buf = 0;

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

	if (  Error() )
        return false;
    else
		return true;
}
EXPORT_C void CPartContainerXml::Error(XML_Error Code, const XML_LChar * /*String*/, long /*ByteIndex*/)
{
	SetError(Code);
}
Exemple #6
0
	void SetError(ErrorCode errorCode, const char* errorString)
	{
		SetError(m_errorNode, errorCode, errorString);
	}
Exemple #7
0
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;
}
Exemple #8
0
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);
}
Exemple #9
0
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;
		}
	}
	return(!fail);
}
Exemple #10
0
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] =
				(r << nativeFormat.RShift) |
				(g << nativeFormat.GShift) |
				(b << nativeFormat.BShift) |
				nativeFormat.AMask;
				imageData += bpp;
			}
		} else {
			
			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;
				const unsigned int a = (color & TargaFormat.AMask) >> TargaFormat.AShift;
				m_pixels[i] =
				(r << nativeFormat.RShift) |
				(g << nativeFormat.GShift) |
				(b << nativeFormat.BShift) |
				(a << nativeFormat.AShift);
				imageData += bpp;
			}
		}

		delete [] image;

	} else if (header[IMAGE_TYPE] == COMPRESSED_TRUECOLOR_IMAGE) {
Exemple #11
0
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;
}
Exemple #12
0
/**
 * 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.");

      if (curtime - starttime > timeout){
        accept_timed_out = true;
        break;

      }else{

        continue;
      }
      
    }
    
    if (ret > 0) {
      accept_status = SSL_accept(ssl);
      curtime = time(NULL);
      expected = errorcode = SSL_get_error(ssl, accept_status);

      LOGM(VARP, logh, LEV_DEBUG, T_PRE, "Accept status: %d",accept_status);
      LOGM(VARP, logh, LEV_DEBUG, T_PRE, "Error code: %d",errorcode);
      LOGM(VARP, logh, LEV_DEBUG, T_PRE, "SSL_WANT_READ: %d, SSL_WANT_WRITE: %d",SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE);
    }

    if (ret < 0)
      // No more data from the select
      break;

    if (accept_status == 1)
      // SSL handshake completed
      break;

    if (timeout != -1 && (curtime - starttime > timeout)){
      // Timeout reached
      accept_timed_out = true;
      break;
    }

    if (accept_status <= 0 && ( errorcode != SSL_ERROR_WANT_READ && errorcode != SSL_ERROR_WANT_WRITE ))
      // SSL handshake error
      break;
    
  } while (true);
  
  // Error enstabilishing context
  if (accept_status != 1){

    LOGM(VARP, logh, LEV_INFO, T_PRE, "Error enstabilishing SSL context.");

    if (accept_timed_out){
      SetError("SSL Handshake failed due to server timeout!");
    }else{
      SetErrorOpenSSL("SSL Handshake error:");
    }

    goto err;
  }
  
  // Context enstabilished
  actual_cert = SSL_get_peer_certificate(ssl);
  peer_stack  = SSL_get_peer_cert_chain(ssl);

  char buffer[1000];

//  if (LogLevelMin(logh, LEV_DEBUG)) {
      LOGM(VARP, logh, LEV_DEBUG, T_PRE, "Certificate DN: %s",
           X509_NAME_oneline(X509_get_subject_name(actual_cert), buffer, 999));
      LOGM(VARP, logh, LEV_DEBUG, T_PRE, "Certificate CA: %s",
           X509_NAME_oneline(X509_get_issuer_name(actual_cert), buffer, 999));
      LOGM(VARP, logh, LEV_DEBUG, T_PRE, "Stack Size: %d", sk_X509_num(peer_stack));
//  }

  peer_cert = get_real_cert(actual_cert, peer_stack);

  if (peer_cert) {
    char *name = X509_NAME_oneline(X509_get_subject_name(peer_cert), NULL, 0);
    own_subject = std::string(name);
    OPENSSL_free(name);
  }

  if (LogLevelMin(logh, LEV_DEBUG)){
    for (int i = 0; i < sk_X509_num(peer_stack); i++) {
      X509 *cert = sk_X509_value(peer_stack, i);
      LOGM(VARP, logh, LEV_DEBUG, T_PRE, "Certificate DN: %s",
           X509_NAME_oneline(X509_get_subject_name(cert), buffer, 999));
      LOGM(VARP, logh, LEV_DEBUG, T_PRE, "Certificate CA: %s",
           X509_NAME_oneline(X509_get_issuer_name(cert), buffer, 999));
    }
  }

  name = X509_NAME_oneline(X509_get_subject_name(peer_cert), NULL, 0);
  if (name)
    peer_subject = std::string(name); 
  OPENSSL_free(name);

  name = X509_NAME_oneline(X509_get_issuer_name(peer_cert), NULL, 0);
  if (name)
    peer_ca = std::string(name);
  OPENSSL_free(name);

  serial = get_peer_serial(actual_cert);
  peer_serial = std::string(serial ? serial : "");
  OPENSSL_free(serial);

  return true;

err:
  destroy_SSL_proxy_handler(ssl);
  SSL_free(ssl);
  SSL_CTX_free(ctx);

  return false;
}
Exemple #13
0
//++ ------------------------------------------------------------------------------------
// 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;
}
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);
  }

  listener->OnChunkRead(aResult, this);

  return NS_OK;
}
Exemple #15
0
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;
}
Exemple #16
0
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);
}
Exemple #17
0
bool nglContext::Build(WindowRef Win, const nglContextInfo& rInfo, const nglContext* pShared, bool Fullscreen)
{
  mTargetAPI = rInfo.TargetAPI;
  if (mTargetAPI != eTargetAPI_OpenGL || mTargetAPI != eTargetAPI_OpenGL2)
    return false;
  
#ifndef __NOGLCONTEXT__
  mFullscreen = Fullscreen;

  std::vector<GLint> attribs;
  attribs.push_back(AGL_RGBA);
  if (rInfo.FrameCnt != 1)
    attribs.push_back(AGL_DOUBLEBUFFER);
  
  attribs.push_back(AGL_DEPTH_SIZE);
  attribs.push_back(rInfo.DepthBits);
  
  attribs.push_back(AGL_STENCIL_SIZE);
  attribs.push_back(rInfo.StencilBits);

  if (rInfo.AuxCnt)
  {
    attribs.push_back(AGL_AUX_BUFFERS);
    attribs.push_back(rInfo.AuxCnt);
  }
  
  if (rInfo.AABufferCnt)
  {
    attribs.push_back(AGL_SAMPLE_BUFFERS_ARB);
    attribs.push_back(rInfo.AABufferCnt);
    attribs.push_back(AGL_SAMPLES_ARB);
    attribs.push_back(rInfo.AASampleCnt);
  }

  attribs.push_back(AGL_RED_SIZE);
  attribs.push_back(rInfo.FrameBitsR);
  attribs.push_back(AGL_GREEN_SIZE);
  attribs.push_back(rInfo.FrameBitsG);
  attribs.push_back(AGL_BLUE_SIZE);
  attribs.push_back(rInfo.FrameBitsB);
  attribs.push_back(AGL_ALPHA_SIZE);
  attribs.push_back(rInfo.FrameBitsA);
  attribs.push_back(AGL_PIXEL_SIZE);
  attribs.push_back(rInfo.FrameBitsR + rInfo.FrameBitsG + rInfo.FrameBitsB + rInfo.FrameBitsA);

  if (rInfo.AccumBitsR || rInfo.AccumBitsG || rInfo.AccumBitsB || rInfo.AccumBitsA)
  {
    attribs.push_back(AGL_ACCUM_RED_SIZE);
    attribs.push_back(rInfo.AccumBitsR);
    attribs.push_back(AGL_ACCUM_GREEN_SIZE);
    attribs.push_back(rInfo.AccumBitsG);
    attribs.push_back(AGL_ACCUM_BLUE_SIZE);
    attribs.push_back(rInfo.AccumBitsB);
    attribs.push_back(AGL_ACCUM_ALPHA_SIZE);
    attribs.push_back(rInfo.AccumBitsA);
  }

  
  if (rInfo.Stereo) 
    attribs.push_back(AGL_STEREO);
  
  attribs.push_back(AGL_MINIMUM_POLICY);
  attribs.push_back(AGL_NO_RECOVERY);
  
  if (rInfo.CopyOnSwap)
    attribs.push_back(AGL_BACKING_STORE);
  
  attribs.push_back(AGL_NONE);
     
  /* Choose pixel format */
  AGLPixelFormat Format = aglChoosePixelFormat(NULL, 0, &attribs[0]);
  
  //NGL_OUT("Pixel Format: 0x%x\n", Format);
  
  if (!Format)
  {
    if (rInfo.CopyOnSwap)
    {
      attribs[attribs.size() - 2] = AGL_NONE;
      Format = aglChoosePixelFormat(NULL, 0, &attribs[0]);
    } 

    if (!Format)
    {
      SetError(_T("context"), NGL_CONTEXT_ENOMATCH);
      return false;
    }
  }

  //DumpFormat(Format);
  
  /* Create an AGL context */
  mCtx = aglCreateContext(Format, pShared?pShared->mCtx:NULL);
  long err = aglGetError();

  GLint value;
  aglDescribePixelFormat(Format, AGL_DOUBLEBUFFER, &value);
  mContextInfo.FrameCnt = value ? 2 : 1;     ///< Number of frame buffers (two means double-buffering)

  aglDescribePixelFormat(Format, AGL_RED_SIZE, (GLint*)&mContextInfo.FrameBitsR);   ///< Bits per red component (frame buffer)
  aglDescribePixelFormat(Format, AGL_GREEN_SIZE, (GLint*)&mContextInfo.FrameBitsG);   ///< Bits per green component (frame buffer)
  aglDescribePixelFormat(Format, AGL_BLUE_SIZE, (GLint*)&mContextInfo.FrameBitsB);   ///< Bits per blue component (frame buffer)
  aglDescribePixelFormat(Format, AGL_ALPHA_SIZE, (GLint*)&mContextInfo.FrameBitsA);   ///< Bits per alpha component (frame buffer)
  aglDescribePixelFormat(Format, AGL_DEPTH_SIZE, (GLint*)&mContextInfo.DepthBits);    ///< Depth buffer resolution (ie. Z buffer, 0 means no Z buffer)
  aglDescribePixelFormat(Format, AGL_STENCIL_SIZE, (GLint*)&mContextInfo.StencilBits);  ///< Stencil buffer resolution (0 means no stencil)
  aglDescribePixelFormat(Format, AGL_ACCUM_RED_SIZE, (GLint*)&mContextInfo.AccumBitsR);   ///< Bits per red component (accumulator buffer)
  aglDescribePixelFormat(Format, AGL_ACCUM_GREEN_SIZE, (GLint*)&mContextInfo.AccumBitsG);   ///< Bits per green component (accumulator buffer)
  aglDescribePixelFormat(Format, AGL_ACCUM_BLUE_SIZE, (GLint*)&mContextInfo.AccumBitsB);   ///< Bits per blue component (accumulator buffer)
  aglDescribePixelFormat(Format, AGL_ACCUM_ALPHA_SIZE, (GLint*)&mContextInfo.AccumBitsA);   ///< Bits per alpha component (accumulator buffer)
  aglDescribePixelFormat(Format, AGL_AUX_BUFFERS, (GLint*)&mContextInfo.AuxCnt);       ///< Number of auxiliary buffers
  aglDescribePixelFormat(Format, AGL_SAMPLE_BUFFERS_ARB, (GLint*)&mContextInfo.AABufferCnt);  ///< Number of anti-aliasing buffers
  aglDescribePixelFormat(Format, AGL_SAMPLES_ARB, (GLint*)&mContextInfo.AASampleCnt);  ///< Anti-alisaing oversampling count
  aglDescribePixelFormat(Format, AGL_STEREO, &value);       ///< Stereoscopic display

  mContextInfo.Stereo = value != 0;
  mContextInfo.Offscreen = false;       ///< This context can render in memory instead of to a window. (false by default).
  mContextInfo.RenderToTexture = false; ///< This context must be able to be bound as a texture. (false by default)
  aglDescribePixelFormat(Format, AGL_BACKING_STORE, &value);  ///< This context must be able to use copy the back buffer to the front buffer instead of swaping them. (false by default) 
  mContextInfo.CopyOnSwap = value != 0;
  if (rInfo.CopyOnSwap && !mContextInfo.CopyOnSwap)
    mValidBackBufferRequestedNotGranted = true;
  
  aglDestroyPixelFormat(Format);
  if (!mCtx)
  {
    SetError(_T("context"), NGL_CONTEXT_EGLCTX);
    /*
    switch (err)
    {
    case AGL_BAD_MATCH:
      NGL_OUT("AGL Error: Bad Context Match (shared context incompatible with requested pixel format).\n");
      break;
    case AGL_BAD_CONTEXT:
      NGL_OUT("AGL Error: Bad Shared Context.\n");
      break;
    case AGL_BAD_PIXELFMT:
      NGL_OUT("AGL Error: Bad Pixel Format.\n");
      break;
    default:
      NGL_OUT("AGL Error: Unknown error\n");
      break;
    }
    */
    return false;
  }

  /* Attach the context to the window */
  if (!aglSetDrawable(mCtx, GetWindowPort (Win)))
  {
    SetError(_T("context"), NGL_CONTEXT_EBIND);
    return false;
  }

  {
    CGLError err = kCGLNoError;
    CGLContextObj ctx = CGLGetCurrentContext();
    
    // Enable the multi-threading
    //err =  CGLEnable( ctx, kCGLCEMPEngine);
    
    if (err != kCGLNoError )
    {
      // Multi-threaded execution is possibly not available
      // Insert your code to take appropriate action
    }
  }
  
  GLint vsync = rInfo.VerticalSync ? 1 : 0;
  aglSetInteger(mCtx, AGL_SWAP_INTERVAL, &vsync);
  
  InitPainter();
  MakeCurrent(Win);
#endif
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  return true;
}
Exemple #18
0
static bool MoveFurther(char *thePattern,UINT32 patternIndex,char *pathBuffer,UINT32 pathIndex,GLOBDATA *theData)
// this attempts to add to pathBuffer by reading from thePattern at patternIndex
// pattern data is added to pathBuffer so that all data containing no meta characters is copied
// up to the first PATHSEP before data that does contain meta characters
// if there is a problem, SetError, and return false
{
	bool
		fail;
	bool
		done;
	UINT32
		lastPatternIndex,
		lastPathIndex;
	bool
		nextSpecial;
	bool
		hadMeta;					// tells if locally, we have seen any meta characters yet

	fail=done=nextSpecial=hadMeta=false;
	lastPatternIndex=patternIndex;
	lastPathIndex=pathIndex;
	while(!done&&pathIndex<MAXPATHLEN)
	{
		// copy all of thePattern that contains no meta characters until the next PATHSEP into pathBuffer
		pathBuffer[pathIndex]=thePattern[patternIndex];
		switch(thePattern[patternIndex])
		{
			case '\0':				// ran out of characters of the pattern, so this is not path information
				if((!hadMeta&&theData->dontGlobLast)||(!theData->hadMeta&&theData->passNoMeta))		// if no meta characters, then this IS the path (assuming we dont glob the last one)
				{
					pathBuffer[pathIndex]='\0';		// terminate the current path
					fail=!AddStringToList(pathBuffer,&theData->thePaths,&theData->numPaths);	// add this to the list
				}
				done=true;
				break;
			case '*':				// meta character (this means we stop here)
			case '?':
			case '[':
				if(nextSpecial)
				{
					patternIndex++;
					pathIndex++;
					nextSpecial=false;
				}
				else
				{
					hadMeta=true;				// remember locally that there were meta characters
					theData->hadMeta=true;		// remember it globally as well
					done=true;
				}
				break;
			case PATHSEP:
				patternIndex++;
				pathIndex++;
				lastPatternIndex=patternIndex;			// remember these
				lastPathIndex=pathIndex;
				nextSpecial=false;
				break;
			case '\\':
				if(nextSpecial)
				{
					patternIndex++;
					pathIndex++;
					nextSpecial=false;
				}
				else
				{
					nextSpecial=true;
					patternIndex++;						// skip the \, but do not move forward in path
				}
				break;
			default:
				patternIndex++;
				pathIndex++;
				nextSpecial=false;
				break;
		}
	}
	if(done)											// we got something
	{
		if(!((!hadMeta&&theData->dontGlobLast)||(!theData->hadMeta&&theData->passNoMeta)))	// if we aren't passing this verbatim, then glob against it
		{
			patternIndex=lastPatternIndex;				// move back
			pathIndex=lastPathIndex;
			pathBuffer[pathIndex]='\0';					// terminate the current path
			fail=!GlobAgainstDirectory(thePattern,patternIndex,pathBuffer,pathIndex,theData);	// expand the pattern at the end of the current path
		}
	}
	else											// path was about to overflow output
	{
		SetError(localErrorFamily,errorMembers[PATHTOOLONG],errorDescriptions[PATHTOOLONG]);
		fail=true;
	}
	return(!fail);

}
Exemple #19
0
void taskBackground(void* pvParameter)
{
static unsigned int val1;
static unsigned int val2;
time_t time_sec;

//	vTaskSetApplicationTaskTag( NULL, ( void * ) 'b' );	
alarm_st = 0;
#ifndef SIM_DEBUG
//sysinit
	wdi_ena = 0;
	Spi_init();
	if(get_time_rtc(&rtc_time)== FALSE)
	{
		SetError(RTC_ERR, HARWARE_ALRM_SCR);
		reset_rtc();
		while(clear_os_rtc() == FALSE);
		init_time_rtc(&rtc_time);
		
//		rtc_time.tm_sec = 0;
 //		rtc_time.tm_min = 0;
// 		rtc_time.tm_hour = 0;
//		rtc_time.tm_mday = 1;
//		rtc_time.tm_wday = 0;
//		rtc_time.tm_mon = 0;
//		rtc_time.tm_year = 100;
//		rtc_time.tm_yday = 0;
//		rtc_time.tm_isdst = 0;
		set_time_rtc(&rtc_time)/*set_date()*/;
	}
	else if(mktime(&rtc_time)==-1)
	{
		SetError(RTC_ERR, HARWARE_ALRM_SCR);
//		reset_rtc();
		init_time_rtc(&rtc_time);
		set_time_rtc(&rtc_time)/*set_date()*/;
	}
	
	time_sec  = mktime(&rtc_time); 
	set_clock(time_sec);

//	if(get_days(&calib_date) > 365)
//	if(time_sec - calib_time >= 31536000L /*365*24*60*60*/)
//	{
//			Beep(800);
//			lcd_clear();
//			beep(800,4);
//			RTclock.timer = 2000; //10sec timeout
//			draw_text( 15, LCD_TXTLINE1, (uchar*)"SEND THE PUMP", LCD_PIXEL_ON,0);
//			draw_text( 54, LCD_TXTLINE2, (uchar*)"TO", LCD_PIXEL_ON,0);
//			draw_text( 29, LCD_TXTLINE3, (uchar*)"CALIBRATE", LCD_PIXEL_ON,0);
//			while(RTclock.timer > 0);
//	}




	SST25ProtDisable();

	SST25ReadArray(PARAM_E2PIMG_BASE, &E2pImage, sizeof(E2pImage_t));
	if(crc16((unsigned char*)&E2pImage, sizeof(E2pImage_t)) != 0)
	{
		SetError(EEPROM_ERR, HARWARE_ALRM_SCR);
		set_defaults();
	}
	SST25ReadArray(CLBR_E2PIMG_BASE, &Clbr_E2pImage, sizeof(Clbr_E2pImage_t));
	if(crc16((unsigned char*)&Clbr_E2pImage, sizeof(Clbr_E2pImage_t)) != 0)
	{
		SetError(EEPROM_ERR, HARWARE_ALRM_SCR);
		set_fact_defaults();
	}
        if(GetError() != 0)
	{
		err_code = GetError();
		ClearError();
                ((unsigned int*)&E2pImage)[sizeof(E2pImage_t)/2 - 1] = crc16(&E2pImage, sizeof(E2pImage_t) - 2);
		SST25SectorErase(PARAM_E2PIMG_BASE);
		if(!SST25WriteArray(PARAM_E2PIMG_BASE, &E2pImage, sizeof(E2pImage_t)))
			/*CriticalError("eeprom err")*/;
	}

	MCP23S08Init();
	MCP4822Write(0, zero_press1 , 0);
	MCP4822Write(1, zero_press2 , 0);

	init_motor();
	init_airdet();
#endif
	init_keypad();
	init_clock();
	CheckParams();

	/* drop task priority */	 
	vTaskPrioritySet( hBACKGRNDTask, tskIDLE_PRIORITY + 1 );	
	while (1) 
	{
            vTaskDelay( 50 / portTICK_RATE_MS );   // Wait 50ms
		 
            if(val1 > 0x0fff)
                val1 = 0;
            else
                val1++;
            if(val2 > 0x0fff)
                val1 = 0;
            else
                val2++;

            if(!wdi_ena)
                toggleExpGPO(WDI_EXTIOBIT);
//	ClrWdt();
//	WD_PIN^= 1; 			 /*toggle external watch dog */
	}	
}
Exemple #20
0
static bool GlobAgainstDirectory(char *thePattern,UINT32 patternIndex,char *pathBuffer,UINT32 pathIndex,GLOBDATA *theData)
// try thePattern against all files at pathBuffer, adding each that matches completely, and calling
// move further on each one
// if there is some sort of problem, SetError, and return false
{
	DIR
		*theDirectory;
	struct dirent
		*theEntry;
	bool
		fail;
	char
		*thePath;
	UINT32
		theLength;
	UINT32
		newIndex;
	bool
		haveMatch;

	fail=false;
	if(pathBuffer[0])
	{
		thePath=pathBuffer;						// point at the passed path if one given
	}
	else
	{
		thePath="./";							// if passed path is empty, it means current directory
	}
	if((theDirectory=opendir(thePath)))			// if it does not open, assume it is because thePath did not point to something valid
	{
		while(!fail&&(theEntry=readdir(theDirectory)))
		{
			newIndex=patternIndex;
			if(theEntry->d_name[0]!='.'||thePattern[patternIndex]=='.')			// the first . must be matched exactly
			{
				if(MatchName(theEntry->d_name,thePattern,&newIndex,&haveMatch))
				{
					if(haveMatch)					// was there a match?
					{
						theLength=strlen(theEntry->d_name);
						if(pathIndex+theLength<MAXPATHLEN)	// append to path (if there's room)
						{
							strcpy(&(pathBuffer[pathIndex]),theEntry->d_name);
							if(thePattern[newIndex])		// see if there's more pattern left
							{
								fail=!MoveFurther(thePattern,newIndex,pathBuffer,pathIndex+theLength,theData);
							}
							else
							{
								fail=!AddStringToList(pathBuffer,&theData->thePaths,&theData->numPaths);
							}
						}
						else
						{
							SetError(localErrorFamily,errorMembers[PATHTOOLONG],errorDescriptions[PATHTOOLONG]);
							fail=true;
						}
					}
				}
				else
				{
					fail=true;
				}
			}
		}
		closedir(theDirectory);
	}
	return(!fail);
}
Exemple #21
0
DataMgmtProcType CScreensaver::DataManagementProc() {
    int             retval                      = 0;
    int             suspend_reason              = 0;
    RESULT*         theResult                   = NULL;
    RESULT*         graphics_app_result_ptr     = NULL;
    RESULT          previous_result;
    // previous_result_ptr = &previous_result when previous_result is valid, else NULL
    RESULT*         previous_result_ptr         = NULL;
    int             iResultCount                = 0;
    int             iIndex                      = 0;
    double          default_phase_start_time    = 0.0;
    double          science_phase_start_time    = 0.0;
    double          last_change_time            = 0.0;
    // If we run default screensaver during science phase because no science graphics 
    // are available, then shorten next default graphics phase by that much time.
    double          default_saver_start_time_in_science_phase    = 0.0;
    double          default_saver_duration_in_science_phase      = 0.0;

    SS_PHASE        ss_phase                    = DEFAULT_SS_PHASE;
    bool            switch_to_default_gfx       = false;
    bool            killing_default_gfx         = false;
    int             exit_status                 = 0;
    
    char*           default_ss_dir_path         = NULL;
    char            full_path[1024];

    BOINCTRACE(_T("CScreensaver::DataManagementProc - Display screen saver loading message\n"));
    SetError(TRUE, SCRAPPERR_BOINCSCREENSAVERLOADING);  // No GFX App is running: show moving BOINC logo
#ifdef _WIN32
    m_tThreadCreateTime = time(0);

    // Set the starting point for iterating through the results
    m_iLastResultShown = 0;
    m_tLastResultChangeTime = 0;
#endif

    m_bDefault_ss_exists = false;
    m_bScience_gfx_running = false;
    m_bDefault_gfx_running = false;
    m_bShow_default_ss_first = false;

#ifdef __APPLE__
    default_ss_dir_path = "/Library/Application Support/BOINC Data";
#else
    default_ss_dir_path = (char*)m_strBOINCInstallDirectory.c_str();
#endif

    strlcpy(full_path, default_ss_dir_path, sizeof(full_path));
    strlcat(full_path, PATH_SEPARATOR, sizeof(full_path));
    strlcat(full_path, THE_DEFAULT_SS_EXECUTABLE, sizeof(full_path));
        
    if (boinc_file_exists(full_path)) {
        m_bDefault_ss_exists = true;
    } else {
        SetError(TRUE, SCRAPPERR_CANTLAUNCHDEFAULTGFXAPP);  // No GFX App is running: show moving BOINC logo
    }
    
    if (m_bDefault_ss_exists && m_bShow_default_ss_first) {
        ss_phase = DEFAULT_SS_PHASE;
        default_phase_start_time = dtime();
        science_phase_start_time = 0;
        switch_to_default_gfx = true;
    } else {
        ss_phase = SCIENCE_SS_PHASE;
        default_phase_start_time = 0;
        science_phase_start_time = dtime();
    }

    while (true) {
        for (int i = 0; i < 4; i++) {
            // ***
            // *** Things that should be run frequently.
            // ***   4 times per second.
            // ***

            // Are we supposed to exit the screensaver?
            if (m_bQuitDataManagementProc) {     // If main thread has requested we exit
                BOINCTRACE(_T("CScreensaver::DataManagementProc - Thread told to stop\n"));
                if (m_hGraphicsApplication || graphics_app_result_ptr) {
                    if (m_bDefault_gfx_running) {
                        BOINCTRACE(_T("CScreensaver::DataManagementProc - Terminating default screensaver\n"));
                        terminate_default_screensaver(m_hGraphicsApplication);
                    } else {
                        BOINCTRACE(_T("CScreensaver::DataManagementProc - Terminating screensaver\n"));
                        terminate_screensaver(m_hGraphicsApplication, graphics_app_result_ptr);
                    }
                    graphics_app_result_ptr = NULL;
                    previous_result_ptr = NULL;
                    m_hGraphicsApplication = 0;
                }
                BOINCTRACE(_T("CScreensaver::DataManagementProc - Stopping...\n"));
                m_bDataManagementProcStopped = true; // Tell main thread that we exited
                return 0;                       // Exit the thread
            }
            boinc_sleep(0.25);
        }

        // ***
        // *** Things that should be run less frequently.
        // *** 1 time per second.
        // ***

        // Blank screen saver?
        if ((m_dwBlankScreen) && (time(0) > m_dwBlankTime) && (m_dwBlankTime > 0)) {
            BOINCTRACE(_T("CScreensaver::DataManagementProc - Time to blank\n"));
            SetError(FALSE, SCRAPPERR_SCREENSAVERBLANKED);    // Blanked - hide moving BOINC logo
            m_bQuitDataManagementProc = true;
            continue;       // Code above will exit the thread
        }

        BOINCTRACE(_T("CScreensaver::DataManagementProc - ErrorMode = '%d', ErrorCode = '%x'\n"), m_bErrorMode, m_hrError);

        if (!m_bConnected) {
            HandleRPCError();
        }
        
        if (m_bConnected) {
            // Do we need to get the core client state?
            if (m_bResetCoreState) {
                // Try and get the current state of the CC
                retval = rpc->get_state(state);
                if (retval) {
                    // CC may not yet be running
                    HandleRPCError();
                    continue;
                } else {
                    m_bResetCoreState = false;
                }
            }
    
            // Update our task list
            retval = rpc->get_screensaver_tasks(suspend_reason, results);
            if (retval) {
                // rpc call returned error
                HandleRPCError();
                m_bResetCoreState = true;
                continue;
            }
        } else {
            results.clear();
        }
        
        // Time to switch to default graphics phase?
        if (m_bDefault_ss_exists && (ss_phase == SCIENCE_SS_PHASE) && (m_fGFXDefaultPeriod > 0)) {
            if (science_phase_start_time && ((dtime() - science_phase_start_time) > m_fGFXSciencePeriod)) {
                if (!m_bDefault_gfx_running) {
                    switch_to_default_gfx = true;
                }
                ss_phase = DEFAULT_SS_PHASE;
                default_phase_start_time = dtime();
                science_phase_start_time = 0;
                if (m_bDefault_gfx_running && default_saver_start_time_in_science_phase) {
                    // Remember how long default graphics ran during science phase
                    default_saver_duration_in_science_phase += (dtime() - default_saver_start_time_in_science_phase); 
                }
                default_saver_start_time_in_science_phase = 0;
            }
        }
        
        // Time to switch to science graphics phase?
        if ((ss_phase == DEFAULT_SS_PHASE) && m_bConnected && (m_fGFXSciencePeriod > 0)) {
            if (default_phase_start_time && 
                    ((dtime() - default_phase_start_time + default_saver_duration_in_science_phase) 
                    > m_fGFXDefaultPeriod)) {
                // BOINCTRACE(_T("CScreensaver::Ending Default phase: now=%f, default_phase_start_time=%f, default_saver_duration_in_science_phase=%f\n"),
                // dtime(), default_phase_start_time, default_saver_duration_in_science_phase);
                ss_phase = SCIENCE_SS_PHASE;
                default_phase_start_time = 0;
                default_saver_duration_in_science_phase = 0;
                science_phase_start_time = dtime();
                if (m_bDefault_gfx_running) {
                    default_saver_start_time_in_science_phase = science_phase_start_time;
                }
                switch_to_default_gfx = false;
            }
        }

        // Core client suspended?
        if (suspend_reason && !(suspend_reason & (SUSPEND_REASON_CPU_THROTTLE | SUSPEND_REASON_CPU_USAGE))) {
            if (!m_bDefault_gfx_running) {
                SetError(TRUE, m_hrError);          // No GFX App is running: show moving BOINC logo
                if (m_bDefault_ss_exists) {
                    switch_to_default_gfx = true;
                }
            }
        }
        
        if (switch_to_default_gfx) {
            if (m_bScience_gfx_running) {
                if (m_hGraphicsApplication || previous_result_ptr) {
                    // use previous_result_ptr because graphics_app_result_ptr may no longer be valid
                    terminate_screensaver(m_hGraphicsApplication, previous_result_ptr);
                    if (m_hGraphicsApplication == 0) {
                        graphics_app_result_ptr = NULL;
                        m_bScience_gfx_running = false;
                    } else {
                        // HasProcessExited() test will clear m_hGraphicsApplication and graphics_app_result_ptr
                    }
                    previous_result_ptr = NULL;
                }
            } else {
                if (!m_bDefault_gfx_running) {
                    switch_to_default_gfx = false;
                    retval = launch_default_screensaver(default_ss_dir_path, m_hGraphicsApplication);
                    if (retval) {
                        m_hGraphicsApplication = 0;
                        previous_result_ptr = NULL;
                        graphics_app_result_ptr = NULL;
                        m_bDefault_gfx_running = false;
                        SetError(TRUE, SCRAPPERR_CANTLAUNCHDEFAULTGFXAPP);  // No GFX App is running: show moving BOINC logo
                   } else {
                        m_bDefault_gfx_running = true;
                        if (ss_phase == SCIENCE_SS_PHASE) {
                            default_saver_start_time_in_science_phase = dtime();
                        }
                        SetError(FALSE, SCRAPPERR_BOINCSCREENSAVERLOADING);    // A GFX App is running: hide moving BOINC logo
                    }
                }
            }
        }

        if ((ss_phase == SCIENCE_SS_PHASE) && !switch_to_default_gfx) {
        
#if SIMULATE_NO_GRAPHICS /* FOR TESTING */

            if (!m_bDefault_gfx_running) {
                SetError(TRUE, m_hrError);          // No GFX App is running: show moving BOINC logo
                if (m_bDefault_ss_exists) {
                    switch_to_default_gfx = true;
                }
            }

#else                   /* NORMAL OPERATION */

            if (m_bScience_gfx_running) {
                // Is the current graphics app's associated task still running?
                
                if ((m_hGraphicsApplication) || (graphics_app_result_ptr)) {
                    iResultCount = (int)results.results.size();
                    graphics_app_result_ptr = NULL;

                    // Find the current task in the new results vector (if it still exists)
                    for (iIndex = 0; iIndex < iResultCount; iIndex++) {
                        theResult = results.results.at(iIndex);

                        if (is_same_task(theResult, previous_result_ptr)) {
                            graphics_app_result_ptr = theResult;
                            previous_result = *theResult;
                            previous_result_ptr = &previous_result;
                            break;
                        }
                    }

                    // V6 graphics only: if worker application has stopped running, terminate_screensaver
                    if ((graphics_app_result_ptr == NULL) && (m_hGraphicsApplication != 0)) {
                        if (previous_result_ptr) {
                            BOINCTRACE(_T("CScreensaver::DataManagementProc - %s finished\n"), 
                                previous_result.graphics_exec_path
                            );
                        }
                        terminate_screensaver(m_hGraphicsApplication, previous_result_ptr);
                        previous_result_ptr = NULL;
                        if (m_hGraphicsApplication == 0) {
                            graphics_app_result_ptr = NULL;
                            m_bScience_gfx_running = false;
                            // Save previous_result and previous_result_ptr for get_random_graphics_app() call
                        } else {
                            // HasProcessExited() test will clear m_hGraphicsApplication and graphics_app_result_ptr
                        }
                    }

                     if (last_change_time && (m_fGFXChangePeriod > 0) && ((dtime() - last_change_time) > m_fGFXChangePeriod) ) {
                        if (count_active_graphic_apps(results, previous_result_ptr) > 0) {
                            if (previous_result_ptr) {
                                BOINCTRACE(_T("CScreensaver::DataManagementProc - time to change: %s / %s\n"), 
                                    previous_result.name, previous_result.graphics_exec_path
                                );
                            }
                            terminate_screensaver(m_hGraphicsApplication, graphics_app_result_ptr);
                            if (m_hGraphicsApplication == 0) {
                                graphics_app_result_ptr = NULL;
                                m_bScience_gfx_running = false;
                                // Save previous_result and previous_result_ptr for get_random_graphics_app() call
                            } else {
                                // HasProcessExited() test will clear m_hGraphicsApplication and graphics_app_result_ptr
                            }
                        }
                        last_change_time = dtime();
                    }
                }
            }       // End if (m_bScience_gfx_running)
        
            // If no current graphics app, pick an active task at random
            // and launch its graphics app
            //
            if ((m_bDefault_gfx_running || (m_hGraphicsApplication == 0)) && (graphics_app_result_ptr == NULL)) {
                graphics_app_result_ptr = get_random_graphics_app(results, previous_result_ptr);
                previous_result_ptr = NULL;
                
                if (graphics_app_result_ptr) {
                    if (m_bDefault_gfx_running) {
                        terminate_default_screensaver(m_hGraphicsApplication);
                        killing_default_gfx = true;
                        // Remember how long default graphics ran during science phase
                        if (default_saver_start_time_in_science_phase) {
                            default_saver_duration_in_science_phase += (dtime() - default_saver_start_time_in_science_phase); 
                            //BOINCTRACE(_T("CScreensaver::During Science phase: now=%f, default_saver_start_time=%f, default_saver_duration=%f\n"),
                            //    dtime(), default_saver_start_time_in_science_phase, default_saver_duration_in_science_phase);
                        }
                        default_saver_start_time_in_science_phase = 0;
                        // HasProcessExited() test will clear
                        // m_hGraphicsApplication and graphics_app_result_ptr
                     } else {
                        retval = launch_screensaver(graphics_app_result_ptr, m_hGraphicsApplication);
                        if (retval) {
                            m_hGraphicsApplication = 0;
                            previous_result_ptr = NULL;
                            graphics_app_result_ptr = NULL;
                            m_bScience_gfx_running = false;
                        } else {
                            // A GFX App is running: hide moving BOINC logo
                            //
                            SetError(FALSE, SCRAPPERR_BOINCSCREENSAVERLOADING);
                            last_change_time = dtime();
                            m_bScience_gfx_running = true;
                            // Make a local copy of current result, since original pointer 
                            // may have been freed by the time we perform later tests
                            previous_result = *graphics_app_result_ptr;
                            previous_result_ptr = &previous_result;
                            if (previous_result_ptr) {
                                BOINCTRACE(_T("CScreensaver::DataManagementProc - launching %s\n"), 
                                    previous_result.graphics_exec_path
                                );
                            }
                        }
                    }
                } else {
                    if (!m_bDefault_gfx_running) {
                        // We can't run a science graphics app, so run the default graphics if available
                        SetError(TRUE, m_hrError); 
                        if (m_bDefault_ss_exists) {
                            switch_to_default_gfx = true;
                        }
                    }

                }   // End if no science graphics available
            }      // End if no current science graphics app is running

#endif      // ! SIMULATE_NO_GRAPHICS

            if (switch_to_default_gfx) {
                switch_to_default_gfx = false;
                if (!m_bDefault_gfx_running) {
                    retval = launch_default_screensaver(default_ss_dir_path, m_hGraphicsApplication);
                    if (retval) {
                        m_hGraphicsApplication = 0;
                        previous_result_ptr = NULL;
                        graphics_app_result_ptr = NULL;
                        m_bDefault_gfx_running = false;
                        SetError(TRUE, SCRAPPERR_CANTLAUNCHDEFAULTGFXAPP);
                        // No GFX App is running: show BOINC logo
                    } else {
                        m_bDefault_gfx_running = true;
                        default_saver_start_time_in_science_phase = dtime();
                        SetError(FALSE, SCRAPPERR_BOINCSCREENSAVERLOADING);
                        // Default GFX App is running: hide moving BOINC logo
                    }
                }
            }
        }   // End if ((ss_phase == SCIENCE_SS_PHASE) && !switch_to_default_gfx)
        
        
        
        // Is the graphics app still running?
        if (m_hGraphicsApplication) {
            if (HasProcessExited(m_hGraphicsApplication, exit_status)) {
                // Something has happened to the previously selected screensaver
                //   application. Start a different one.
                BOINCTRACE(_T("CScreensaver::DataManagementProc - Graphics application isn't running, start a new one.\n"));
                if (m_bDefault_gfx_running) {
                    // If we were able to connect to core client
                    // but gfx app can't, don't use it. 
                    //
                    BOINCTRACE(_T("CScreensaver::DataManagementProc - Default graphics application exited with code %d.\n"), exit_status);
                    if (!killing_default_gfx) {     // If this is an unexpected exit
                        if (exit_status == DEFAULT_GFX_CANT_CONNECT) {
                            SetError(TRUE, SCRAPPERR_DEFAULTGFXAPPCANTCONNECT);
                            // No GFX App is running: show moving BOINC logo
                        } else {
                            SetError(TRUE, SCRAPPERR_DEFAULTGFXAPPCRASHED);
                            // No GFX App is running: show moving BOINC logo
                        }
                        m_bDefault_ss_exists = false;
                        ss_phase = SCIENCE_SS_PHASE;
                    }
                    killing_default_gfx = false;
                }
                SetError(TRUE, SCRAPPERR_BOINCNOGRAPHICSAPPSEXECUTING);
                // No GFX App is running: show moving BOINC logo
                m_hGraphicsApplication = 0;
                graphics_app_result_ptr = NULL;
                m_bDefault_gfx_running = false;
                m_bScience_gfx_running = false;
                continue;
            }
        }
    }   // end while(true)
}
Exemple #22
0
const char* TiXmlDocument::Parse
  ( const char* p, TiXmlParsingData* prevData, TiXmlEncoding encoding )
{
    ClearError();

    // Parse away, at the document level. Since a document
    // contains nothing but other tags, most of what happens
    // here is skipping white space.
    // sherm 100319: I changed this so that untagged top-level text is
    // parsed as a Text node rather than a parsing error. CDATA text was
    // already allowed at the top level so this seems more consistent.
    if ( !p || !*p )
    {
        SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
        return 0;
    }

    // Note that, for a document, this needs to come
    // before the while space skip, so that parsing
    // starts from the pointer we are given.
    location.Clear();
    if ( prevData )
    {
        location.row = prevData->cursor.row;
        location.col = prevData->cursor.col;
    }
    else
    {
        location.row = 0;
        location.col = 0;
    }
    TiXmlParsingData data( p, TabSize(), location.row, location.col );
    location = data.Cursor();

    if ( encoding == TIXML_ENCODING_UNKNOWN )
    {
        // Check for the Microsoft UTF-8 lead bytes.
        const unsigned char* pU = (const unsigned char*)p;
        if (    *(pU+0) && *(pU+0) == TIXML_UTF_LEAD_0
             && *(pU+1) && *(pU+1) == TIXML_UTF_LEAD_1
             && *(pU+2) && *(pU+2) == TIXML_UTF_LEAD_2 )
        {
            encoding = TIXML_ENCODING_UTF8;
            useMicrosoftBOM = true;
        }
    }

    // Remember the start of white space in case we end up reading a text
    // element in a "keep white space" mode.
    const char* pWithWhiteSpace = p;
    p = SkipWhiteSpace( p, encoding );
    if ( !p )
    {
        SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
        return 0;
    }

    // sherm 100319: ignore all but the first Declaration
    bool haveSeenDeclaration = false;
    while ( p && *p )
    {
        TiXmlNode* node = 0;
        if ( *p != '<' )
        {   // sherm 100319: I added this case by stealing the code from
            // Element parsing; see above comment.
            // Take what we have, make a text element.
            TiXmlText* textNode = new TiXmlText( "" );

            if ( !textNode )
            {
                SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, encoding );
                return 0;
            }

            if ( TiXmlBase::IsWhiteSpaceCondensed() )
            {
                p = textNode->Parse( p, &data, encoding );
            }
            else
            {
                // Special case: we want to keep the white space
                // so that leading spaces aren't removed.
                p = textNode->Parse( pWithWhiteSpace, &data, encoding );
            }

            if ( !textNode->Blank() ) {
                LinkEndChild( textNode );
                node = textNode;
            }
            else
                delete textNode;
        }
        else // We saw a '<', now identify what kind of tag it is.
        {
            TiXmlNode* node = Identify( p, encoding );
            if ( node )
            {
                p = node->Parse( p, &data, encoding );
                if (node->ToDeclaration()) {
                    if (haveSeenDeclaration) {
                        delete node; node=0; // ignore duplicate Declaration
                    } else
                        haveSeenDeclaration = true;
                }
                if (node)
                    LinkEndChild( node );
            }
            else
            {
                // If Identify fails then no further parsing is possible.
                break;
            }
        }

        // Did we get encoding info?
        if (    encoding == TIXML_ENCODING_UNKNOWN
             && node && node->ToDeclaration() )
        {
            TiXmlDeclaration* dec = node->ToDeclaration();
            const char* enc = dec->Encoding();
            assert( enc );

            if ( *enc == 0 )
                encoding = TIXML_ENCODING_UTF8;
            else if ( StringEqual( enc, "UTF-8", true, TIXML_ENCODING_UNKNOWN ) )
                encoding = TIXML_ENCODING_UTF8;
            else if ( StringEqual( enc, "UTF8", true, TIXML_ENCODING_UNKNOWN ) )
                encoding = TIXML_ENCODING_UTF8;    // incorrect, but be nice
            else
                encoding = TIXML_ENCODING_LEGACY;
        }

        pWithWhiteSpace = p;
        p = SkipWhiteSpace( p, encoding );
    }

    // Was this empty?
    if ( !firstChild ) {
        SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, encoding );
        return 0;
    }

    // All is well.
    return p;
}
Exemple #23
0
//++ ------------------------------------------------------------------------------------
// 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.
//			Synopsis: -target-select type parameters ...
//			Ref: http://sourceware.org/gdb/onlinedocs/gdb/GDB_002fMI-Target-Manipulation.html#GDB_002fMI-Target-Manipulation
// Type:	Overridden.
// Args:	None.
// Return:	MIstatus::success - Functional succeeded.
//			MIstatus::failure - Functional failed.
// Throws:	None.
//--
bool CMICmdCmdTargetSelect::Execute( void )
{
	CMICMDBASE_GETOPTION( pArgType, String, m_constStrArgNamedType );
	CMICMDBASE_GETOPTION( pArgParameters, String, m_constStrArgNamedParameters );

	CMICmnLLDBDebugSessionInfo & rSessionInfo( CMICmnLLDBDebugSessionInfo::Instance() );

	// Check we have a valid target
	// Note: target created via 'file-exec-and-symbols' command
	if( !rSessionInfo.m_lldbTarget.IsValid() )
	{
		SetError( CMIUtilString::Format( MIRSRC( IDS_CMD_ERR_INVALID_TARGET_CURRENT ), m_cmdData.strMiCmd.c_str() ) );
		return MIstatus::failure;
	}

	// Verify that we are executing remotely
	const CMIUtilString & rRemoteType( pArgType->GetValue() );
	if( rRemoteType != "remote" )
	{
		SetError( CMIUtilString::Format( MIRSRC( IDS_CMD_ERR_INVALID_TARGET_TYPE ), m_cmdData.strMiCmd.c_str(), rRemoteType.c_str() ) );
		return MIstatus::failure;
	}

	// Create a URL pointing to the remote gdb stub
	const CMIUtilString strUrl = CMIUtilString::Format( "connect://%s", pArgParameters->GetValue().c_str() );

	// Ask LLDB to collect to the target port
	const MIchar * pPlugin( "gdb-remote" );
	lldb::SBError error;
	lldb::SBProcess process = rSessionInfo.m_lldbTarget.ConnectRemote( rSessionInfo.m_rLlldbListener, strUrl.c_str(), pPlugin, error );

	// Verify that we have managed to connect successfully
	lldb::SBStream errMsg;
	if( !process.IsValid() )
	{
		SetError( CMIUtilString::Format( MIRSRC( IDS_CMD_ERR_INVALID_TARGET_PLUGIN ), m_cmdData.strMiCmd.c_str(), errMsg.GetData() ) );
		return MIstatus::failure;
	}
	if( error.Fail() )
	{
		SetError( CMIUtilString::Format( MIRSRC( IDS_CMD_ERR_CONNECT_TO_TARGET ), m_cmdData.strMiCmd.c_str(), errMsg.GetData() ) );
		return MIstatus::failure;
	}

	// Save the process in the session info
	// Note: Order is important here since this process handle may be used by CMICmnLLDBDebugHandleEvents
	//		 which can fire when interpreting via HandleCommand() below.
	rSessionInfo.m_lldbProcess = process;

	// Set the environment path if we were given one
	CMIUtilString strWkDir;
	if(	rSessionInfo.SharedDataRetrieve< CMIUtilString >( rSessionInfo.m_constStrSharedDataKeyWkDir, strWkDir ) )
	{
		lldb::SBDebugger & rDbgr = rSessionInfo.m_rLldbDebugger;
		if( !rDbgr.SetCurrentPlatformSDKRoot( strWkDir.c_str() ) )
		{
			SetError( CMIUtilString::Format( MIRSRC( IDS_CMD_ERR_FNFAILED ), m_cmdData.strMiCmd.c_str(), "target-select" ) );
			return MIstatus::failure;
		}
	}

	// Set the shared object path if we were given one
	CMIUtilString strSolibPath;
	if(	rSessionInfo.SharedDataRetrieve< CMIUtilString >( rSessionInfo.m_constStrSharedDataSolibPath, strSolibPath ) )
	{
		lldb::SBDebugger & rDbgr = rSessionInfo.m_rLldbDebugger;
		lldb::SBCommandInterpreter cmdIterpreter = rDbgr.GetCommandInterpreter();
		
		CMIUtilString strCmdString = CMIUtilString::Format( "target modules search-paths add . %s", strSolibPath.c_str() );

		lldb::SBCommandReturnObject retObj;
		cmdIterpreter.HandleCommand( strCmdString.c_str(), retObj, false );

		if( !retObj.Succeeded() )
		{
			SetError( CMIUtilString::Format( MIRSRC( IDS_CMD_ERR_FNFAILED ), m_cmdData.strMiCmd.c_str(), "target-select" ) );
			return MIstatus::failure;
		}
	}

	return MIstatus::success;
}
Exemple #24
0
/***
	PRIVATE
	Metodo LogicalOp
	Realiza batimentos entre duas listas de ocorrencias
        e gera uma terceira lista

	Parameters:
		- iOperation : operacao a ser realizada
		- iHandle1 : handle da primeira LO
		- iHandle2 : handle da segunda LO

	Return:
		- o handle da LO gerada ou um erro (valor negativo)

	Comments:
        	- a LO gerada NAO se torna a corrente
                  (ela nao eh habilitada)

***/
int
LBSC_Base::LogicalOp( int iOperation, int iHandle1, int iHandle2 )
{
	PRINTLOG( _clLBSLog, ("LBSC_Base::LogicalOp") );

	if( iHandle1 == iHandle2 ){	// nao podemos operar uma lista consigo mesma
		ERETURN( LBSE_ERROR );
	}

	// guarda a posicao da LO corrente
	int iCurr = pcOLList->GetCurrentIndex();
	// pega as listas correspondentes aos handles
	// pega a lista 1
	LBSC_Expr *pExprOrig1 = (*pcOLList)[ iHandle1 ];
	if( !pExprOrig1 || !pExprOrig1->szExpr ){
		ERETURN( LBSE_NOMEMORY );
	}
	// pega a lista 2
	LBSC_Expr *pExprOrig2 = (*pcOLList)[ iHandle2 ];
	if( !pExprOrig2 || !pExprOrig2->szExpr ){
		ERETURN( LBSE_NOMEMORY );
	}

	// temos que criar copias das listas e ordena-las em separado por registro
	// o algoritmo de refinamento depende da ordenacao por registro
	LTC_EXPR LTExpr1;
	LTC_EXPR LTExpr2;

	LTC_OCCURRENCELIST *pList1 = LTExpr1.LT_GetResultList();
	LTC_OCCURRENCELIST *pList2 = LTExpr2.LT_GetResultList();

	pExprOrig1->pOccList->CreateFullLTList( pList1 );
	pExprOrig2->pOccList->CreateFullLTList( pList2 );
	if ( !pList1 || !pList2 || pList1->LT_GetNumberOfOccurrence() == 0 ||
					pList2->LT_GetNumberOfOccurrence() == 0 ) {
		ERETURN( LBSE_NOMEMORY );
	}
	if ( !pList1->LT_ListSort() || !pList2->LT_ListSort() ) {
		ERETURN( LBSE_NOMEMORY );
	}

	// cria uma expressao LT vazia, que sera' usada para receber o
	// resultado do batimento
	LTC_EXPR LTExprResult;
	// faz o batimento
	int iRet;
	char *szNewExpr = new char [ strlen( pExprOrig1->szExpr ) +
				     strlen( pExprOrig2->szExpr ) +
				     max( strlen( GLT_Session->LT_GetSymbol( "AND" ) ),
				     max( strlen( GLT_Session->LT_GetSymbol( "OR" ) ),
				     max( strlen( GLT_Session->LT_GetSymbol( "XOR" ) ),
				     max( strlen( GLT_Session->LT_GetSymbol( "NOT" ) ), 0 )))) +
				     10 /* para os caracteres extras adicionados */ ];
	if( !szNewExpr ){
		ERETURN( LBSE_NOMEMORY );
	}
	switch( iOperation ){
	case OL_AND:
		sprintf( szNewExpr, "(%s) %s (%s)", (char*) pExprOrig1->szExpr, (char*) GLT_Session->LT_GetSymbol( "AND" ), (char*) pExprOrig2->szExpr );
		iRet = LTExprResult.LT_ExprAnd( szNewExpr, &LTExpr1, &LTExpr2 );
		break;

	case OL_OR:
		sprintf( szNewExpr, "(%s) %s (%s)", (char*) pExprOrig1->szExpr, (char*) GLT_Session->LT_GetSymbol( "OR" ), (char*) pExprOrig2->szExpr );
		iRet = LTExprResult.LT_ExprOr( szNewExpr, &LTExpr1, &LTExpr2 );
		break;

	case OL_XOR:
		sprintf( szNewExpr, "(%s) %s (%s)", (char*) pExprOrig1->szExpr, (char*) GLT_Session->LT_GetSymbol( "XOR" ), (char*) pExprOrig2->szExpr );
		iRet = LTExprResult.LT_ExprXor( szNewExpr, &LTExpr1, &LTExpr2 );
		break;

	case OL_NOT:
		sprintf( szNewExpr, "(%s) %s (%s)", (char*) pExprOrig1->szExpr, (char*) GLT_Session->LT_GetSymbol( "NOT" ), (char*) pExprOrig2->szExpr );
		iRet = LTExprResult.LT_ExprNot( szNewExpr, &LTExpr1, &LTExpr2 );
		break;

	}

	if( iRet != 0 ){
		// vamos retornar uma indicacao de que nao ha' ocorrencias
		// (a operacao de consulta resultou em uma LO vazia)
		ERETURN( LBSE_EMPTYLIST );
	}

	LBSC_Expr *pNewExpr = new LBSC_Expr;
	if ( !pNewExpr ) {
		ERETURN( LBSE_NOMEMORY );
	}
	pNewExpr->szExpr = szNewExpr;

	// gera a LO no formato registro/lista de ocorrencias (para navegacao corretamente)
	int iCreateOccRet = CreateLbsOccList( pNewExpr, &LTExprResult );
	if ( iCreateOccRet != LBS_OK ) {
		delete pNewExpr;
		ERETURN( iCreateOccRet );
	}
	// adiciona a nova LO na lista de LO's
	pcOLList->Add( pNewExpr, TAIL );
	// pega o handle da LO que foi adicionada na lista
	iRet = pcOLList->GetCurrentIndex();
	// Habilita a LO resultante
	if( EnableOcList( plbscsOwnerSession->plbsctTicket, iRet ) != LBS_OK ){
		if( (*pcOLList)[ iRet ] ){
			pcOLList->DeleteCurrObj();	// deleta somente o objeto, mas deixa o nodo.
		}
		ERETURN( LBSE_ENABLE );
	}

	// retorna o handle da LO resultante do batimento
	SetError( LBS_OK );
	return( iRet );
}
Exemple #25
0
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;
	}

	// 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;
	}

	// Process the buffer in place to normalize new lines. (See comment above.)
	// Copies from the 'p' to 'q' pointer, where p can advance faster if
	// a newline-carriage return is hit.
	//
	// Wikipedia:
	// Systems based on ASCII or a compatible character set use either LF  (Line feed, '\n', 0x0A, 10 in decimal) or
	// CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, 0x0D 0x0A)...
	//		* LF:    Multics, Unix and Unix-like systems (GNU/Linux, AIX, Xenix, Mac OS X, FreeBSD, etc.), BeOS, Amiga, RISC OS, and others
    //		* CR+LF: DEC RT-11 and most other early non-Unix, non-IBM OSes, CP/M, MP/M, DOS, OS/2, Microsoft Windows, Symbian OS
    //		* CR:    Commodore 8-bit machines, Apple II family, Mac OS up to version 9 and OS-9

	const char* p = buf;	// the read head
	char* q = buf;			// the write head
	const char CR = 0x0d;
	const char LF = 0x0a;

	buf[length] = 0;
	while( *p ) {
		assert( p < (buf+length) );
		assert( q <= (buf+length) );
		assert( q <= p );

		if ( *p == CR ) {
			*q++ = LF;
			p++;
			if ( *p == LF ) {		// check for CR+LF (and skip LF)
				p++;
			}
		}
		else {
			*q++ = *p++;
		}
	}
	assert( q <= (buf+length) );
	*q = 0;

	Parse( buf, 0, encoding );

	delete [] buf;
	return !Error();
}
FTendrModelData UTendrModelTetraGeneratorComponent::Build( const FTendrVertexArray& InputVertices, const FTendrIndexArray& InputIndices, bool bSilent )
{
	FTendrModelData OutputModelData;

	if(InputVertices.Num() > 0 && InputIndices.Num() > 0)
	{
		if(!bSilent)
		{
			GWarn->BeginSlowTask( FText::FromString( TEXT( "Building Tendr model" ) ), true );
		}

		// Generate model
		{
			// Debug statistics
			const uint32 NumSurfaceVerts = InputVertices.Num();

			// 1. Tetrahedralization
			bool ValidModel = false;
			tetgenio out;	// deinitialize (deallocator) is automatically called when these go out of scope
			{
				// Tetrahedral model generation
				{
					tetgenio in;	// deinitialize (deallocator) is automatically called when these go out of scope

					in.firstnumber = 0;
					in.numberofpoints = NumSurfaceVerts;

					in.pointlist = new REAL[ in.numberofpoints * 3 ];
					in.pointparamlist = new tetgenio::pointparam[ in.numberofpoints ];
					for(int i = 0; i < in.numberofpoints; ++i)
					{
						// Store vertices
						in.pointlist[ i * 3 + 0 ] = InputVertices[ i ].X;
						in.pointlist[ i * 3 + 1 ] = InputVertices[ i ].Y;
						in.pointlist[ i * 3 + 2 ] = InputVertices[ i ].Z;

						// Store UVs (currently not used)
						tetgenio::pointparam param;
						param.tag = 0;
						param.type = 0;
						for(uint32 t = 0; t < MAX_TEXCOORDS; ++t)
						{
							param.uv[ t * 2 + 0 ] = 1;
							param.uv[ t * 2 + 1 ] = 1;
						}

						// Store other per-vertex data (currently not used)
						param.uv[ 8 + 0 ] = 0;
						param.uv[ 8 + 1 ] = 0;
						param.uv[ 8 + 2 ] = 0;
						param.uv[ 8 + 3 ] = 0;
						param.uv[ 8 + 4 ] = 0;
						param.uv[ 8 + 5 ] = 0;

						in.pointparamlist[ i ] = param;

#ifdef TETRA_DEBUG
						UE_LOG( TendrModelTetraLog, Log, TEXT( "Vertex %u: %.3f, %.3f, %.3f" ), i, InputVertices[ i ].X, InputVertices[ i ].Y, InputVertices[ i ].Z );
#endif
					}

					in.numberoffacets = InputIndices.Num() / 3;
					in.facetlist = new tetgenio::facet[ in.numberoffacets ];
					in.facetmarkerlist = new int[ in.numberoffacets ];
					for(int i = 0; i < in.numberoffacets; ++i)
					{
						in.facetmarkerlist[ i ] = 1;

						tetgenio::facet& f = in.facetlist[ i ];
						f.holelist = NULL;
						f.numberofholes = 0;
						f.numberofpolygons = 1;
						f.polygonlist = new tetgenio::polygon[ f.numberofpolygons ];

						tetgenio::polygon& p = f.polygonlist[ 0 ];
						p.numberofvertices = 3;
						p.vertexlist = new int[ p.numberofvertices ];
						p.vertexlist[ 0 ] = InputIndices[ i * 3 + 0 ];
						p.vertexlist[ 1 ] = InputIndices[ i * 3 + 1 ];
						p.vertexlist[ 2 ] = InputIndices[ i * 3 + 2 ];
					}

					in.facetmarkerlist = NULL;

					UE_LOG( TendrModelTetraLog, Log, TEXT( "Tetrahedralizing mesh (input vertices: %u, triangles: %u)" ), in.numberofpoints, in.numberoffacets );

					tetgenbehavior b;
					{
						b.zeroindex = 1;
						b.docheck = 1;
						b.verbose = 1;
						b.diagnose = 0;
						b.facesout = 1;
						b.edgesout = 1;
						b.neighout = 1;
						b.object = tetgenbehavior::POLY;
						b.plc = 1;
						b.quality = 1;

						//b.weighted = 1;

						//b.no_sort = 1;
						//b.optscheme = 0;
						//b.optlevel = 0;

						// Disable removal of duplicate vertices and faces
						b.nomergefacet = 1;
						b.nomergevertex = 1;
						b.nojettison = 1;

						// Prevent insertion of vertices on boundary, only interior
						b.nobisect = 1;
						b.nobisect_nomerge = 1;
						//b.supsteiner_level = 0;

						// UV support
						b.psc = 1;

						// Constrain maximum volume of tetras
						//b.metric = 1;
						//b.minratio = 10;
						if(MaximumTetraVolume > 0)
						{
							b.maxvolume = MaximumTetraVolume;
							b.fixedvolume = 1;
						}
					}

					try
					{
						// Invoke tetgen
						{
							tetrahedralize( &b, &in, &out );

							UE_LOG( TendrModelTetraLog, Log, TEXT( "Output mesh done, points: %u, tetras: %u, triangles: %u, edges: %u" ),
									out.numberofpoints,
									out.numberoftetrahedra,
									out.numberoftrifaces,
									out.numberofedges
									);
						}

						// Conversion to compatible structures
						{
							//
							// Temporary coarse to sparse map
							//
							// Coarse: duplicated vertices, for use in UE4 graphics rendering
							// Sparse: non-duplicated vertices, for use in physics engine
							//
							// This distinction is necessary because UE4 graphics rendering requires the use of duplicated vertices
							// for vertex data blending, while our physics engine needs to be as sparse as possible for performnace reasons.
							//
							TMap<FVector, uint32> TempMapCoarseToSparse;

							// Iterate over generated points of model
							for(int i = 0; i < out.numberofpoints; ++i)
							{
								// Retrieve vertex
								FVector Vertex( out.pointlist[ i * 3 + 0 ], out.pointlist[ i * 3 + 1 ], out.pointlist[ i * 3 + 2 ] );

								// Store vertex
								OutputModelData.Vertices.Add( FVector4( Vertex, 0 ) );

								// Coarse to sparse mapping algorithm
								{
									uint32 IndexSparse = OutputModelData.VerticesPhysics.Num();

									// Check if duplicate vertex exists and insert if it doesn't
									uint32 * pKey = TempMapCoarseToSparse.Find( Vertex );
									if(pKey == NULL)
									{
										// No duplicate vertex exists

										// Add to map
										TempMapCoarseToSparse.Add( Vertex, IndexSparse );

										// Initialize dummy connectivity to InvalidIndex
										FTendrVertexConnectivityData Dummy;
										memset( Dummy.NeighbourIndices, 0xFF, sizeof( Dummy.NeighbourIndices ) );
										OutputModelData.Connectivity.Add( Dummy );

#ifdef TETRA_DEBUG
										UE_LOG( TendrModelTetraLog, Log, TEXT( "Vertex %u (%.3f, %.3f, %.3f) ++ physics vertex %u" ),
												i,
												Vertex.X,
												Vertex.Y,
												Vertex.Z,
												IndexSparse
												);
#endif
										// Add vertex to sparse data structure
										OutputModelData.VerticesPhysics.Add( FVector4( Vertex, 0 ) );

									}
									else
									{
#ifdef TETRA_DEBUG
										UE_LOG( TendrModelTetraLog, Log, TEXT( "Vertex %u (%.3f, %.3f, %.3f) == physics vertex %u" ),
												i,
												Vertex.X,
												Vertex.Y,
												Vertex.Z,
												*pKey
												);
#endif
									}

									// In any case, add mapping
									OutputModelData.MappingCoarseToSparse.Add( ( pKey == NULL ) ? IndexSparse : (*pKey) );
								}
							}

							// Iterate over generated triangles of model
							for(int i = 0; i < out.numberoftrifaces; ++i)
							{
								int A = out.trifacelist[ i * 3 + 0 ];
								int B = out.trifacelist[ i * 3 + 1 ];
								int C = out.trifacelist[ i * 3 + 2 ];
								OutputModelData.Indices.Add( A );
								OutputModelData.Indices.Add( B );
								OutputModelData.Indices.Add( C );
#ifdef TETRA_DEBUG
								UE_LOG( TendrModelTetraLog, Log, TEXT( "Index %u: %u %u %u" ), i, A, B, C );
#endif
							}

							// Output some statistics
							UE_LOG( TendrModelTetraLog, Log, TEXT( "Input  = Indices [%u], Vertices [%u]" ), InputIndices.Num(), NumSurfaceVerts );
							UE_LOG( TendrModelTetraLog, Log, TEXT( "Output = Indices [%u], Vertices [%u surface, %u internal, %u physics]" ), OutputModelData.Indices.Num(), NumSurfaceVerts, OutputModelData.Vertices.Num(), OutputModelData.VerticesPhysics.Num() );

							// Add connectivity based on edges
							uint32 MaxNeighbours = 0;
							for(int i = 0; i < out.numberofedges; ++i)
							{
								int a, b;
								{
									// Retrieve edge indices (coarse)
									int coarseA = out.edgelist[ i * 2 + 0 ];
									int coarseB = out.edgelist[ i * 2 + 1 ];

									// Get corresponding sparse index
									a = OutputModelData.MappingCoarseToSparse[ coarseA ];
									b = OutputModelData.MappingCoarseToSparse[ coarseB ];

									// Check for consistency
									check( a != InvalidIndex );
									check( b != InvalidIndex );

									// Add to sparse connectivity data structure
									ConnectivityAddNeighbour( OutputModelData, a, b, MaxNeighbours );
									ConnectivityAddNeighbour( OutputModelData, b, a, MaxNeighbours );
								}
							}

							UE_LOG( TendrModelTetraLog, Log, TEXT( "Maximum neighbours in model: %u" ), MaxNeighbours );

							// Mark as valid
							OutputModelData.Valid = true;
						}
					}
					catch(int error)
					{
						switch(error)
						{
						case 1:
							SetError( TEXT( "Not enough memory available or model excessively large" ) );
							break;
						case 3:
							SetError( TEXT( "Input contains self-intersecting triangles" ) );
							break;
						case 4:
						case 5:
							SetError( TEXT( "Input contains triangles that are too small" ) );
							break;
						default:
							SetError( FString::Printf( TEXT( "Input could not be processed (tetgen error %u)" ), error ) );
							break;
						}
					}
				}
			}
		}

		if(!bSilent)
		{
			GWarn->EndSlowTask();
		}
	}

	return OutputModelData;
}
const char* TiXmlDocument::Parse( const char* p, TiXmlParsingData* prevData, TiXmlEncoding encoding )
{
	ClearError();

	// Parse away, at the document level. Since a document
	// contains nothing but other tags, most of what happens
	// here is skipping white space.
	if ( !p || !*p )
	{
		SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
		return 0;
	}

	// Note that, for a document, this needs to come
	// before the while space skip, so that parsing
	// starts from the pointer we are given.
	location.Clear();
	if ( prevData )
	{
		location.row = prevData->cursor.row;
		location.col = prevData->cursor.col;
	}
	else
	{
		location.row = 0;
		location.col = 0;
	}
	TiXmlParsingData data( p, TabSize(), location.row, location.col );
	location = data.Cursor();

	if ( encoding == TIXML_ENCODING_UNKNOWN )
	{
		// Check for the Microsoft UTF-8 lead bytes.
		const unsigned char* pU = (const unsigned char*)p;
		if (	*(pU+0) && *(pU+0) == TIXML_UTF_LEAD_0
			 && *(pU+1) && *(pU+1) == TIXML_UTF_LEAD_1
			 && *(pU+2) && *(pU+2) == TIXML_UTF_LEAD_2 )
		{
			encoding = TIXML_ENCODING_UTF8;
			useMicrosoftBOM = true;
		}
	}

    p = SkipWhiteSpace( p, encoding );
	if ( !p )
	{
		SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
		return 0;
	}

	while ( p && *p )
	{
		TiXmlNode* node = Identify( p, encoding );
		if ( node )
		{
			p = node->Parse( p, &data, encoding );
			LinkEndChild( node );
		}
		else
		{
			break;
		}

		// Did we get encoding info?
		if (    encoding == TIXML_ENCODING_UNKNOWN
			 && node->ToDeclaration() )
		{
			TiXmlDeclaration* dec = node->ToDeclaration();
			const char* enc = dec->Encoding();
			assert( enc );

			if ( *enc == 0 )
				encoding = TIXML_ENCODING_UTF8;
			else if ( StringEqual( enc, "UTF-8", true, TIXML_ENCODING_UNKNOWN ) )
				encoding = TIXML_ENCODING_UTF8;
			else if ( StringEqual( enc, "UTF8", true, TIXML_ENCODING_UNKNOWN ) )
				encoding = TIXML_ENCODING_UTF8;	// incorrect, but be nice
			else 
				encoding = TIXML_ENCODING_LEGACY;
		}

		p = SkipWhiteSpace( p, encoding );
	}

	// Was this empty?
	if ( !firstChild ) {
		SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, encoding );
		return 0;
	}

	// All is well.
	return p;
}
Exemple #28
0
//++ ------------------------------------------------------------------------------------
// 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
CMICmdCmdBreakInsert::Execute()
{
    CMICMDBASE_GETOPTION(pArgTempBrkPt, OptionShort, m_constStrArgNamedTempBrkPt);
    CMICMDBASE_GETOPTION(pArgThreadGroup, OptionLong, m_constStrArgNamedThreadGroup);
    CMICMDBASE_GETOPTION(pArgLocation, String, m_constStrArgNamedLocation);
    CMICMDBASE_GETOPTION(pArgIgnoreCnt, OptionShort, m_constStrArgNamedInoreCnt);
    CMICMDBASE_GETOPTION(pArgPendingBrkPt, OptionShort, m_constStrArgNamedPendinfBrkPt);
    CMICMDBASE_GETOPTION(pArgDisableBrkPt, OptionShort, m_constStrArgNamedDisableBrkPt);
    CMICMDBASE_GETOPTION(pArgConditionalBrkPt, OptionShort, m_constStrArgNamedConditionalBrkPt);
    CMICMDBASE_GETOPTION(pArgRestrictBrkPtToThreadId, OptionShort, m_constStrArgNamedRestrictBrkPtToThreadId);

    m_bBrkPtEnabled = !pArgDisableBrkPt->GetFound();
    m_bBrkPtIsTemp = pArgTempBrkPt->GetFound();
    m_bHaveArgOptionThreadGrp = pArgThreadGroup->GetFound();
    if (m_bHaveArgOptionThreadGrp)
    {
        MIuint nThreadGrp = 0;
        pArgThreadGroup->GetExpectedOption<CMICmdArgValThreadGrp, MIuint>(nThreadGrp);
        m_strArgOptionThreadGrp = CMIUtilString::Format("i%d", nThreadGrp);
    }
    m_bBrkPtIsPending = pArgPendingBrkPt->GetFound();
    if (pArgLocation->GetFound())
        m_brkName = pArgLocation->GetValue();
    else if (m_bBrkPtIsPending)
    {
        pArgPendingBrkPt->GetExpectedOption<CMICmdArgValString, CMIUtilString>(m_brkName);
    }
    if (pArgIgnoreCnt->GetFound())
    {
        pArgIgnoreCnt->GetExpectedOption<CMICmdArgValNumber, MIuint>(m_nBrkPtIgnoreCount);
    }
    m_bBrkPtCondition = pArgConditionalBrkPt->GetFound();
    if (m_bBrkPtCondition)
    {
        pArgConditionalBrkPt->GetExpectedOption<CMICmdArgValString, CMIUtilString>(m_brkPtCondition);
    }
    m_bBrkPtThreadId = pArgRestrictBrkPtToThreadId->GetFound();
    if (m_bBrkPtCondition)
    {
        pArgRestrictBrkPtToThreadId->GetExpectedOption<CMICmdArgValNumber, MIuint>(m_nBrkPtThreadId);
    }

    // Determine if break on a file line or at a function
    BreakPoint_e eBrkPtType = eBreakPoint_NotDefineYet;
    CMIUtilString fileName;
    MIuint nFileLine = 0;
    CMIUtilString strFileFn;
    CMIUtilString rStrLineOrFn;
    // Is the string in the form 'file:func' or 'file:line'?
    // If so, find the position of the ':' separator.
    const size_t nPosColon = findFileSeparatorPos(m_brkName);
    if (nPosColon != std::string::npos)
    {
        // Extract file name and line number from it
        fileName = m_brkName.substr(0, nPosColon);
        rStrLineOrFn = m_brkName.substr(nPosColon + 1, m_brkName.size() - nPosColon - 1);

        if (rStrLineOrFn.empty())
            eBrkPtType = eBreakPoint_ByName;
        else
        {
            MIint64 nValue = 0;
            if (rStrLineOrFn.ExtractNumber(nValue))
            {
                nFileLine = static_cast<MIuint>(nValue);
                eBrkPtType = eBreakPoint_ByFileLine;
            }
            else
            {
                strFileFn = rStrLineOrFn;
                eBrkPtType = eBreakPoint_ByFileFn;
            }
        }
    }

    // Determine if break defined as an address
    lldb::addr_t nAddress = 0;
    if (eBrkPtType == eBreakPoint_NotDefineYet)
    {
        MIint64 nValue = 0;
        if (m_brkName.ExtractNumber(nValue))
        {
            nAddress = static_cast<lldb::addr_t>(nValue);
            eBrkPtType = eBreakPoint_ByAddress;
        }
    }

    // Break defined as an function
    if (eBrkPtType == eBreakPoint_NotDefineYet)
    {
        eBrkPtType = eBreakPoint_ByName;
    }

    // Ask LLDB to create a breakpoint
    bool bOk = MIstatus::success;
    CMICmnLLDBDebugSessionInfo &rSessionInfo(CMICmnLLDBDebugSessionInfo::Instance());
    lldb::SBTarget sbTarget = rSessionInfo.GetTarget();
    switch (eBrkPtType)
    {
        case eBreakPoint_ByAddress:
            m_brkPt = sbTarget.BreakpointCreateByAddress(nAddress);
            break;
        case eBreakPoint_ByFileFn:
        {
            lldb::SBFileSpecList module;    // search in all modules
            lldb::SBFileSpecList compUnit;
            compUnit.Append (lldb::SBFileSpec(fileName.c_str()));
            m_brkPt = sbTarget.BreakpointCreateByName(strFileFn.c_str(), module, compUnit);
            break;
        }
        case eBreakPoint_ByFileLine:
            m_brkPt = sbTarget.BreakpointCreateByLocation(fileName.c_str(), nFileLine);
            break;
        case eBreakPoint_ByName:
            m_brkPt = sbTarget.BreakpointCreateByName(m_brkName.c_str(), nullptr);
            break;
        case eBreakPoint_count:
        case eBreakPoint_NotDefineYet:
        case eBreakPoint_Invalid:
            bOk = MIstatus::failure;
            break;
    }

    if (bOk)
    {
        if (!m_bBrkPtIsPending && (m_brkPt.GetNumLocations() == 0))
        {
            sbTarget.BreakpointDelete(m_brkPt.GetID());
            SetError(CMIUtilString::Format(MIRSRC(IDS_CMD_ERR_BRKPT_LOCATION_NOT_FOUND), m_cmdData.strMiCmd.c_str(), m_brkName.c_str()));
            return MIstatus::failure;
        }

        m_brkPt.SetEnabled(m_bBrkPtEnabled);
        m_brkPt.SetIgnoreCount(m_nBrkPtIgnoreCount);
        if (m_bBrkPtCondition)
            m_brkPt.SetCondition(m_brkPtCondition.c_str());
        if (m_bBrkPtThreadId)
            m_brkPt.SetThreadID(m_nBrkPtThreadId);
    }

    // CODETAG_LLDB_BREAKPOINT_CREATION
    // This is in the main thread
    // Record break point information to be by LLDB event handler function
    CMICmnLLDBDebugSessionInfo::SBrkPtInfo sBrkPtInfo;
    if (!rSessionInfo.GetBrkPtInfo(m_brkPt, sBrkPtInfo))
        return MIstatus::failure;
    sBrkPtInfo.m_id = m_brkPt.GetID();
    sBrkPtInfo.m_bDisp = m_bBrkPtIsTemp;
    sBrkPtInfo.m_bEnabled = m_bBrkPtEnabled;
    sBrkPtInfo.m_bHaveArgOptionThreadGrp = m_bHaveArgOptionThreadGrp;
    sBrkPtInfo.m_strOptThrdGrp = m_strArgOptionThreadGrp;
    sBrkPtInfo.m_nTimes = m_brkPt.GetHitCount();
    sBrkPtInfo.m_strOrigLoc = m_brkName;
    sBrkPtInfo.m_nIgnore = m_nBrkPtIgnoreCount;
    sBrkPtInfo.m_bPending = m_bBrkPtIsPending;
    sBrkPtInfo.m_bCondition = m_bBrkPtCondition;
    sBrkPtInfo.m_strCondition = m_brkPtCondition;
    sBrkPtInfo.m_bBrkPtThreadId = m_bBrkPtThreadId;
    sBrkPtInfo.m_nBrkPtThreadId = m_nBrkPtThreadId;

    bOk = bOk && rSessionInfo.RecordBrkPtInfo(m_brkPt.GetID(), sBrkPtInfo);
    if (!bOk)
    {
        SetError(CMIUtilString::Format(MIRSRC(IDS_CMD_ERR_BRKPT_INVALID), m_cmdData.strMiCmd.c_str(), m_brkName.c_str()));
        return MIstatus::failure;
    }

    // CODETAG_LLDB_BRKPT_ID_MAX
    if (m_brkPt.GetID() > (lldb::break_id_t)rSessionInfo.m_nBrkPointCntMax)
    {
        SetError(CMIUtilString::Format(MIRSRC(IDS_CMD_ERR_BRKPT_CNT_EXCEEDED), m_cmdData.strMiCmd.c_str(), rSessionInfo.m_nBrkPointCntMax,
                                       m_brkName.c_str()));
        return MIstatus::failure;
    }

    return MIstatus::success;
}
Exemple #29
0
// TODO: Refactor this with some of the timer changes
// TODO: Write unit tests
BootloaderState BootloaderFSM(BootloaderState state)
{
	BootloaderState next_state; // Leave like this for static analysis to catch or set to set state?
	char comByte;

	switch(state)
	{
	case Check:
		// Check that the program has been programmed correctly. If so, go to Boot. Otherwise, go to Not Loaded.

		if(*header == HEADER_CONSTANT)
		{
			// We want to read from the header, so let's set a pointer to it that we can advance
			uint32_t* read_header = header;
			// We should be pointing to start now
			read_header++;

			// Read start address, length, version, and footer address
			start = (uint32_t*)*read_header++;
			length = *read_header++;
			version = *read_header++;
			footer = (uint32_t*)*read_header++;

			crc = *(footer + 1);

			// TODO: Validate data

			if(*footer == FOOTER_CONSTANT)
			{
				uint32_t crc = DoCRC(start, length);

				if(crc == crc)
				{
					next_state = Booting;
				}
				else
				{
					SetError(error, "CrcFaild");
					next_state = NotLoaded;
				}
			}
			else
			{
				SetError(error, "BadFootr");
				next_state = NotLoaded;
			}
		}
		else
		{
			SetError(error, "BadHeadr");
			next_state = NotLoaded;
		}
		break;
	case NotLoaded:
		// Wait for 5 seconds. If no communication during that time, then power down

		if(power_down_time == 0)
		{
			power_down_time = *timer + FIVE_SECONDS;
			next_state = NotLoaded;
		}

		// Check for a message to push us into communicate
		comByte = Rs232GetByte();
		if(IsBootCommand(comByte))
		{
			next_state = Communicate;
		}
		else
		{
			// Otherwise, check if we need to power down
			if(*timer > power_down_time)
			{
				// 5 seconds have passed, power the device down
				next_state = PowerDown;
			}
			else
			{
				// Keep waiting.
				// TODO: Wait here?
				next_state = NotLoaded;
			}
		}

		break;
	case Booting:
		// Wait for 0.5 ms. If no communication during that time, boot our program.
		if(boot_time == 0)
		{
			boot_time = *timer + FIVE_HUNDRED_MS;
		}

		// Check if a service tool wants to communicate
		comByte = Rs232GetByte();
		if(IsBootCommand(comByte))
		{
			// Move to communicate state if so
			next_state = Communicate;
		}
		else
		{
			// Otherwise, check if it's time to boot
			if(boot_time > *timer)
			{
				// Point of No Return
				// Boot();
			}
			else
			{
				// Keep waiting
				// TODO: Wait here?
				next_state = Booting;
			}
		}

		break;
	case PowerDown:
		// PowerDown();

		// Once we come out of sleep, then go to check
		next_state = Check;

		break;
	case Communicate:
		DoProtocol();
		next_state = Check;

		break;
	}

	return next_state;
}
void
GetFileOrDirectoryTask::Work()
{
  MOZ_ASSERT(FileSystemUtils::IsParentProcess(),
             "Only call from parent process!");
  MOZ_ASSERT(!NS_IsMainThread(), "Only call on worker thread!");

  nsRefPtr<FileSystemBase> filesystem = do_QueryReferent(mFileSystem);
  if (!filesystem) {
    return;
  }

  // Whether we want to get the root directory.
  bool getRoot = mTargetRealPath.IsEmpty();

  nsCOMPtr<nsIFile> file = filesystem->GetLocalFile(mTargetRealPath);
  if (!file) {
    SetError(NS_ERROR_DOM_FILESYSTEM_INVALID_PATH_ERR);
    return;
  }

  bool ret;
  nsresult rv = file->Exists(&ret);
  if (NS_FAILED(rv)) {
    SetError(rv);
    return;
  }

  if (!ret) {
    if (!getRoot) {
      SetError(NS_ERROR_DOM_FILE_NOT_FOUND_ERR);
      return;
    }

    // If the root directory doesn't exit, create it.
    rv = file->Create(nsIFile::DIRECTORY_TYPE, 0777);
    if (NS_FAILED(rv)) {
      SetError(rv);
      return;
    }
  }

  // Get isDirectory.
  rv = file->IsDirectory(&mIsDirectory);
  if (NS_FAILED(rv)) {
    SetError(rv);
    return;
  }

  if (!mIsDirectory) {
    // Check if the root is a directory.
    if (getRoot) {
      SetError(NS_ERROR_DOM_FILESYSTEM_TYPE_MISMATCH_ERR);
      return;
    }

    // Get isFile
    rv = file->IsFile(&ret);
    if (NS_FAILED(rv)) {
      SetError(rv);
      return;
    }
    if (!ret) {
      // Neither directory or file.
      SetError(NS_ERROR_DOM_FILESYSTEM_TYPE_MISMATCH_ERR);
      return;
    }

    if (!filesystem->IsSafeFile(file)) {
      SetError(NS_ERROR_DOM_SECURITY_ERR);
      return;
    }

    mTargetFile = new nsDOMFileFile(file);
  }
}