Example #1
0
void Elf32_Ehdr::Load(vfsStream& f)
{
	e_magic = Read32(f);
	e_class = Read8(f);
	e_data = Read8(f);
	e_curver = Read8(f);
	e_os_abi = Read8(f);

	if (IsLittleEndian())
	{
		e_abi_ver = Read64LE(f);
		e_type = Read16LE(f);
		e_machine = Read16LE(f);
		e_version = Read32LE(f);
		e_entry = Read32LE(f);
		e_phoff = Read32LE(f);
		e_shoff = Read32LE(f);
		e_flags = Read32LE(f);
		e_ehsize = Read16LE(f);
		e_phentsize = Read16LE(f);
		e_phnum = Read16LE(f);
		e_shentsize = Read16LE(f);
		e_shnum = Read16LE(f);
		e_shstrndx = Read16LE(f);
	}
	else
	{
		e_abi_ver = Read64(f);
		e_type = Read16(f);
		e_machine = Read16(f);
		e_version = Read32(f);
		e_entry = Read32(f);
		e_phoff = Read32(f);
		e_shoff = Read32(f);
		e_flags = Read32(f);
		e_ehsize = Read16(f);
		e_phentsize = Read16(f);
		e_phnum = Read16(f);
		e_shentsize = Read16(f);
		e_shnum = Read16(f);
		e_shstrndx = Read16(f);
	}
}
void CFileSystemGCWii::InitFileSystem()
{
	m_Initialized = true;

	// read the whole FST
	u64 FSTOffset = (u64)Read32(0x424) << m_OffsetShift;
	// u32 FSTSize     = Read32(0x428);
	// u32 FSTMaxSize  = Read32(0x42C);


	// read all fileinfos
	SFileInfo Root;
	Root.m_NameOffset = Read32(FSTOffset + 0x0);
	Root.m_Offset     = (u64)Read32(FSTOffset + 0x4) << m_OffsetShift;
	Root.m_FileSize   = Read32(FSTOffset + 0x8);

	if (Root.IsDirectory())
	{
		if (m_FileInfoVector.size())
			PanicAlert("Wtf?");
		u64 NameTableOffset = FSTOffset;

		m_FileInfoVector.reserve((unsigned int)Root.m_FileSize);
		for (u32 i = 0; i < Root.m_FileSize; i++)
		{
			SFileInfo sfi;
			u64 Offset = FSTOffset + (i * 0xC);
			sfi.m_NameOffset = Read32(Offset + 0x0);
			sfi.m_Offset     = (u64)Read32(Offset + 0x4) << m_OffsetShift;
			sfi.m_FileSize   = Read32(Offset + 0x8);

			m_FileInfoVector.push_back(sfi);
			NameTableOffset += 0xC;
		}

		BuildFilenames(1, m_FileInfoVector.size(), NULL, NameTableOffset);
	}
}
Example #3
0
void SelfSection::Load(const fs::file& f)
{
	*data = Read32(f);
	size = Read64(f);
	offset = Read64(f);
}
Example #4
0
int SidFile::Parse(string file)
{
	FILE *f = fopen(file.c_str(), "rb");
	
	if(f == NULL)
	{
		return SIDFILE_ERROR_FILENOTFOUND;
	}
	
	uint8_t header[PSID_MAX_HEADER_LENGTH];
	memset(header, 0, PSID_MAX_HEADER_LENGTH);
	
	size_t read = fread(header, 1, PSID_MAX_HEADER_LENGTH, f);
	
	if(read < PSID_MIN_HEADER_LENGTH || !IsPSIDHeader(header))
	{
		fclose(f);
		return SIDFILE_ERROR_MALFORMED;
	}

	numOfSongs = Read16(header, SIDFILE_PSID_NUMBER);
	
	if(numOfSongs == 0)
	{
		numOfSongs = 1;
	}
	
	firstSong = Read16(header, SIDFILE_PSID_DEFSONG);
	if(firstSong)
	{
		firstSong--;
	}
	if (firstSong >= numOfSongs)
	{
		firstSong = 0;
	}

	initAddr = Read16(header, SIDFILE_PSID_INIT);
	playAddr = Read16(header, SIDFILE_PSID_MAIN);
	speedFlags = Read32(header, SIDFILE_PSID_SPEED);

	moduleName = (char *)(header + SIDFILE_PSID_NAME);
	
	authorName = (char *)(header + SIDFILE_PSID_AUTHOR);
	
	string copyrightInfo = (char *)(header + SIDFILE_PSID_COPYRIGHT);

	// Seek to start of module data
	fseek(f, Read16(header, SIDFILE_PSID_LENGTH), SEEK_SET);

	// Find load address
	loadAddr = Read16(header, SIDFILE_PSID_START);
	if(loadAddr == 0)
	{
		uint8_t lo = fgetc(f);
		uint8_t hi = fgetc(f);
		loadAddr = (hi << 8) | lo;
	}
	
	if(initAddr == 0)
	{
		initAddr = loadAddr;
	}

	// Load module data
	dataLength = fread(dataBuffer, 1, 0x10000, f);
	
	fclose(f);

	return SIDFILE_OK;
}
Example #5
0
bool PNGFormat::ReadMolecule(OBBase* pOb, OBConversion* pConv)
{
  istream& ifs = *pConv->GetInStream();
  if(pConv->IsFirstInput())
  {
    _count=0;
    _hasInputPngFile=true;
  }
  const char pngheader[] = {-119,80,78,71,13,10,26,10,0};
  char readbytes[9];
  ifs.read(readbytes, 8);

  if(!equal(pngheader, pngheader+8, readbytes))
  {
    obErrorLog.ThrowError("PNG Format","Not a PNG file", obError);
     return false;
  }

  //Loop through all the chunks
  while(ifs)
  {
    unsigned int len = Read32(ifs);
    ifs.read(readbytes,4);
    string chunkid(readbytes, readbytes+4);
    if(chunkid=="IEND")
    {
      bytesToIEND = ifs.tellg();
      bytesToIEND -= 8;
      break;
    }
    streampos pos = ifs.tellg();

    const char* altid = pConv->IsOption("y",OBConversion::INOPTIONS);
    if(chunkid=="tEXt" || chunkid=="zTXt" || (altid && chunkid==altid))
    {
      string keyword;
      getline(ifs, keyword, '\0');
      unsigned int datalength = len - keyword.size()-1;

      //remove "file" from end of keyword
      transform(keyword.begin(),keyword.end(),keyword.begin(),::tolower);
      string::size_type pos = keyword.find("file");
      if(pos!=string::npos)
        keyword.erase(pos);

      OBFormat* pFormat = OBConversion::FindFormat(keyword.c_str());
      if(pFormat)
      {
        //We have found embedded text that we need to extract
        stringstream ss;
        if(chunkid[0]!='z')
        {
          //Copy it to a stringstream
          istreambuf_iterator<char> initer(ifs);
          ostreambuf_iterator<char> outiter(ss);
          for (unsigned int i = 0; i < datalength; ++i)
            *outiter++ = *initer++;
        }

        else
        {
          //Needs to be uncompressed first
          Bytef* pCompTxt = new Bytef[datalength];
          ifs.read((char*)pCompTxt, datalength);
          --datalength; //for compression method byte
          uLongf uncompLen;
          Bytef* pUncTxt = new Bytef[datalength*6];//guess uncompressed length. NASTY!
          if(*pCompTxt!=0 /*compression method*/
            || uncompress(pUncTxt, &uncompLen, pCompTxt+1, datalength)!=Z_OK)
          {
            obErrorLog.ThrowError("PNG Format","Errors in decompression", obError);
            delete[] pUncTxt;
            delete[] pCompTxt;
            return false;
          }
          pUncTxt[uncompLen] = '\0';
          ss.str((char*)pUncTxt);
          delete[] pUncTxt;
          delete[] pCompTxt;
        }

        //Use a new OBConversion object to convert embedded text
        OBConversion conv2(&ss, pConv->GetOutStream());
        conv2.CopyOptions(pConv);
        conv2.SetInAndOutFormats(pFormat, pConv->GetOutFormat());
        _count += conv2.Convert();

        ifs.ignore(4);//CRC
        continue; //already at the end of the chunk
      }
    }
    //Move to end of chunk
    ifs.seekg(pos);
    ifs.ignore(len+4); //data + CRC
  }


  //if we will be writing a png file, read and save the whole input file.
  CopyOfInput.clear();
  if(pConv->GetOutFormat()==this)
  {
    ifs.seekg(0);
    copy(istreambuf_iterator<char>(ifs), istreambuf_iterator<char>(),back_inserter(CopyOfInput));
  }

  if(pConv->IsLastFile() && _count>0)
  {
    pConv->ReportNumberConverted(_count); //report the number of chemical objects
    pConv->SetOutFormat(this); //so that number of files is reported as "PNG_files"
  }

  return true;
}
Example #6
0
int ExecuteLevelScript()
{
	dmsg(" - Level layout script: 0x%06X to 0x%06X (0x%X bytes)\n - Entry point at 0x%06X\n\n", LvlScript_Start, LvlScript_End, LvlScript_Length, LvlScript_Entry);

	unsigned int ObjGeoOffset[256];
	memset(ObjGeoOffset, 0x00, sizeof(ObjGeoOffset));

	bool EndOfScript = false;
	ColVtxBuffer = (unsigned char *) malloc (sizeof(char) * 0x8000);
	ColTriBuffer = (unsigned char *) malloc (sizeof(char) * 0x10000);
	ZWaterBuffer = (unsigned char *) malloc (sizeof(char) * 0x400);	/* Room for 64 water boxes */
	memset(ColTriBuffer, 0x10000, 0x0);
	memset(ZWaterBuffer, 0x400, 0x0);
	ZWaterOffset = 0;
	#ifdef DEBUG
	int i;
	#endif

	while (!(EndOfScript) && (TempScriptPos < ROMFilesize)) {
		CurrentCmd = Read16(RAMSegment[TempScriptSegment].Data, TempScriptPos);
		CurrentCmdLength = RAMSegment[TempScriptSegment].Data[TempScriptPos + 1];
		JumpInScript = false;

		if(CurrentCmdLength == 0x00) EndOfScript = true;

		switch(CurrentCmd)
		{
			case 0x0204:
			case 0x1E04:
				// end
				EndOfScript = true;
				break;

			case 0x0608: {
				// jump
				unsigned int TargetSeg = RAMSegment[TempScriptSegment].Data[TempScriptPos + 4];

				if(RAMSegment[TargetSeg].IsSet) {
					TempScriptPos_Backup = TempScriptPos;
					TempScriptSegment_Backup = TempScriptSegment;
					TempScriptPos = Read24(RAMSegment[TempScriptSegment].Data, TempScriptPos + 5);
					TempScriptSegment = TargetSeg;
					JumpInScript = true;
				}
				break; }

			case 0x0704:
				// return
				TempScriptPos = (TempScriptPos_Backup + 4);
				TempScriptSegment = TempScriptSegment_Backup;
				break;

			case 0x170C: {
				// setup ram segment
				unsigned int TempSeg = RAMSegment[TempScriptSegment].Data[TempScriptPos + 3];
				dmsg("- Segment loader: 0x%02X\n", TempSeg);

				unsigned int ROMData_Start = Read32(RAMSegment[TempScriptSegment].Data, TempScriptPos + 4);
				unsigned int ROMData_End = Read32(RAMSegment[TempScriptSegment].Data, TempScriptPos + 8);
				unsigned int ROMData_Length = ROMData_End - ROMData_Start;

				RAMSegment[TempSeg].Data = (unsigned char *) malloc (sizeof(char) * ROMData_Length);
				memcpy(RAMSegment[TempSeg].Data, &ROMBuffer[ROMData_Start], ROMData_Length);
				RAMSegment[TempSeg].IsSet = true;
				RAMSegment[TempSeg].Length = ROMData_Length;

				dmsg("[ROM] RAM segment 0x%02X: 0x%08X to 0x%08X (0x%X bytes)\n", TempSeg, ROMData_Start, ROMData_End, ROMData_Length);
				break; }

			case 0x1A0C: {
				// textures
				unsigned int TempSeg = RAMSegment[TempScriptSegment].Data[TempScriptPos + 3];
				dmsg("- Texture loader: 0x%02X\n", TempSeg);
				if(TempSeg == 0x09) {
					unsigned int TexData_Start = Read32(RAMSegment[TempScriptSegment].Data, TempScriptPos + 4);
					unsigned int TexData_End = Read32(RAMSegment[TempScriptSegment].Data, TempScriptPos + 8);
					TexData_Start += Read32(ROMBuffer, TexData_Start + 8);
					TexData_Start += 2;
					unsigned int TexData_Length = TexData_End - TexData_Start;

					RAMSegment[TempSeg].Data = (unsigned char *) malloc (sizeof(char) * TexData_Length);
					memcpy(RAMSegment[TempSeg].Data, &ROMBuffer[TexData_Start], TexData_Length);
					RAMSegment[TempSeg].IsSet = true;
					RAMSegment[TempSeg].Length = TexData_Length;

					dmsg("[ROM] External texture data: 0x%08X to 0x%08X (0x%X bytes)\n", TexData_Start, TexData_End, TexData_Length);
				}
				break; }

			case 0x1D04: {
				// end of segment loading sequence
				// generate initial zmap data

				// only generate when segment 0x07 is already set, if it's not we're still executing segment 0x15
				if(RAMSegment[0x07].IsSet == false) break;

				msg(3, " - Generating initial Zelda map data...\n");

				ZMapFilesize = RAMSegment[0x07].Length + ZMAP_HEADERGAP;
				int PadSize = GetPaddingSize(ZMapFilesize, 0x08);
				TextureSize = RAMSegment[0x09].Length;

				dmsg("  - Size of main data:\t\t\t\t\t0x%06X\n", ZMapFilesize);
				dmsg("  - Size of padding:\t\t\t\t\t0x%04X\n", PadSize);
				dmsg("  - Size of external texture data:\t\t0x%06X\n", TextureSize);

				ZMapFilesize += PadSize;
				ZMapFilesize += TextureSize;

				dmsg("  - Total data size:\t\t\t\t\t0x%06X\n", ZMapFilesize);
				msg(3, " - Allocating and clearing map buffer...\n");
				ZMapBuffer = (unsigned char*) malloc (sizeof(char) * ZMapFilesize);
				memset(ZMapBuffer, 0x00, ZMapFilesize);

				msg(3, " - Copying main data and external texture data...\n");

				memcpy(&ZMapBuffer[ZMAP_HEADERGAP], RAMSegment[0x07].Data, RAMSegment[0x07].Length);
				memcpy(&ZMapBuffer[ZMapFilesize - TextureSize], RAMSegment[0x09].Data, TextureSize);

				msg(3, " - Done, resuming conversion.\n");
				break; }

			case 0x1F08: {
				// execute geometry script
				TempGeoScriptSegment = RAMSegment[TempScriptSegment].Data[TempScriptPos + 4];
				TempGeoScriptPos = Read24(RAMSegment[TempScriptSegment].Data, TempScriptPos + 5);
				TempGeoScriptSegment_Backup = 0x00, TempGeoScriptPos_Backup = 0x00;

				CurrentLevelArea = RAMSegment[TempScriptSegment].Data[TempScriptPos + 2];

				dmsg("\nCurrent level area set to 0x%02X (wanted 0x%02X)\n", CurrentLevelArea, LevelArea);

				if(LevelArea != CurrentLevelArea) break;

				ExecuteGeoScript(false);

				break; }

			case 0x2E08: // execute collision script
			{
				if(LevelArea != CurrentLevelArea) break;

				unsigned int ColScriptSeg = RAMSegment[TempScriptSegment].Data[TempScriptPos + 4];
				unsigned int ColScriptPos = Read24(RAMSegment[TempScriptSegment].Data, TempScriptPos + 5);

				if (RAMSegment[ColScriptSeg].IsSet == true)
					ExecuteCollisionScript(ColScriptSeg, ColScriptPos);

				break;
			}
			case 0x2208: {
				// load object w/ geo layout
				unsigned char ObjID = RAMSegment[TempScriptSegment].Data[TempScriptPos + 3];
				if(RAMSegment[TempScriptSegment].Data[TempScriptPos + 4] == 0x0E) {
					unsigned int GeoOffset = Read32(RAMSegment[TempScriptSegment].Data, TempScriptPos + 4);
					ObjGeoOffset[ObjID] = GeoOffset;
					InsertSpecialObjects(ObjID, GeoOffset);
				}
				break; }
			case 0x2418: {
				if(TempScriptSegment == 0x0E)
					SM64_Behavior_To_OoT(TempScriptSegment, TempScriptPos, 0);
				break; }
			case 0x3908: {
				dmsg("\nAdding macro objects for level area 0x%02X...\n", LevelArea);

				unsigned int MacroSeg = RAMSegment[TempScriptSegment].Data[TempScriptPos + 4];
				unsigned int MacroPos = Read24(RAMSegment[TempScriptSegment].Data, TempScriptPos + 5);

				bool EndOfObjects = false;
				while(!EndOfObjects) {
					unsigned int Preset = Read16(RAMSegment[MacroSeg].Data, MacroPos);
					Preset &= 0x01FF;
					unsigned int Behav = Read32(ROMBuffer, MacroPreset_Offset + ((Preset - 0x01F) << 3));

					if((Preset == 0x01E) || (Preset == 0x000)) {
						EndOfObjects = true;
					} else {
						SM64_Behavior_To_OoT(MacroSeg, MacroPos, Behav);
						MacroPos += 0x0A;
					}
				}

				break; }

			default:
				#ifdef DEBUG
				printf("Unknown: %04X:", CurrentCmd);
				for (i=TempScriptPos+2;i<TempScriptPos+CurrentCmdLength; i++)
					printf("%02X",RAMSegment[TempScriptSegment].Data[i]);
				printf("\n");
				#endif
				break;
		}

		if(!JumpInScript) TempScriptPos += CurrentCmdLength;
	}

	return 0;
}
Example #7
0
void DumpObjDbgSyms (FILE* F, unsigned long Offset)
/* Dump the debug symbols from an object file */
{
    ObjHeader   H;
    Collection  StrPool = AUTO_COLLECTION_INITIALIZER;
    unsigned    Count;
    unsigned    I;

    /* Seek to the header position and read the header */
    FileSetPos (F, Offset);
    ReadObjHeader (F, &H);

    /* Seek to the start of the string pool and read it */
    FileSetPos (F, Offset + H.StrPoolOffs);
    ReadStrPool (F, &StrPool);

    /* Seek to the start of the debug syms */
    FileSetPos (F, Offset + H.DbgSymOffs);

    /* Output a header */
    printf ("  Debug symbols:\n");

    /* Check if the object file was compiled with debug info */
    if ((H.Flags & OBJ_FLAGS_DBGINFO) == 0) {
	/* Print that there no debug symbols and bail out */
	printf ("    Count:%27u\n", 0);
	return;
    }

    /* Read the number of exports and print it */
    Count = ReadVar (F);
    printf ("    Count:%27u\n", Count);

    /* Read and print all debug symbols */
    for (I = 0; I < Count; ++I) {

    	unsigned long 	Value = 0;
        unsigned long   Size = 0;
        unsigned        ImportId = 0;
        unsigned        ExportId = 0;

       	/* Read the data for one symbol */
       	unsigned Type          = ReadVar (F);
        unsigned char AddrSize = Read8 (F);
        unsigned long Owner    = ReadVar (F);
       	const char*   Name     = GetString (&StrPool, ReadVar (F));
	unsigned      Len      = strlen (Name);
	if (SYM_IS_CONST (Type)) {
	    Value = Read32 (F);
	} else {
	    SkipExpr (F);
	}
        if (SYM_HAS_SIZE (Type)) {
            Size = ReadVar (F);
        }
        if (SYM_IS_IMPORT (Type)) {
            ImportId = ReadVar (F);
        }
        if (SYM_IS_EXPORT (Type)) {
            ExportId = ReadVar (F);
        }

        /* Skip both line info lists */
        SkipLineInfoList (F);
        SkipLineInfoList (F);

	/* Print the header */
	printf ("    Index:%27u\n", I);

	/* Print the data */
       	printf ("      Type:%22s0x%02X  (%s)\n", "", Type, GetExportFlags (Type, 0));
	printf ("      Address size:%14s0x%02X  (%s)\n", "", AddrSize,
                AddrSizeToStr (AddrSize));
       	printf ("      Owner:%25lu\n", Owner);
	printf ("      Name:%*s\"%s\"\n", (int)(24-Len), "", Name);
	if (SYM_IS_CONST (Type)) {
	    printf ("      Value:%15s0x%08lX  (%lu)\n", "", Value, Value);
	}
       	if (SYM_HAS_SIZE (Type)) {
	    printf ("      Size:%20s0x%04lX  (%lu)\n", "", Size, Size);
	}
       	if (SYM_IS_IMPORT (Type)) {
	    printf ("      Import:%24u\n", ImportId);
	}
       	if (SYM_IS_EXPORT (Type)) {
	    printf ("      Export:%24u\n", ExportId);
	}
    }

    /* Destroy the string pool */
    DestroyStrPool (&StrPool);
}
Example #8
0
bool PSFLoader::LoadValuesTable()
{
	psf_f.Seek(psfhdr.psf_offset_values_table);
	m_info.Reset();

	for(uint i=0;i<m_table.GetCount(); i++)
	{
		if(!m_table[i].Cmp("TITLE_ID"))
		{
			m_info.serial = PsfHelper::ReadString(psf_f);
			m_table[i].Append(wxString::Format(": %s", m_info.serial.mb_str()));
			PsfHelper::GoToNN(psf_f);
		}
		else if(!m_table[i](0, 5).Cmp("TITLE"))
		{
			m_info.name = PsfHelper::FixName(PsfHelper::ReadString(psf_f));
			m_table[i].Append(wxString::Format(": %s", m_info.name.mb_str()));
			PsfHelper::GoToNN(psf_f);
		}
		else if(!m_table[i].Cmp("APP_VER"))
		{
			m_info.app_ver = PsfHelper::ReadString(psf_f, sizeof(u64));
			m_table[i].Append(wxString::Format(": %s", m_info.app_ver.mb_str()));
		}
		else if(!m_table[i].Cmp("ATTRIBUTE"))
		{
			psf_f.Read(&m_info.attr, sizeof(m_info.attr));
			m_table[i].Append(wxString::Format(": 0x%x", m_info.attr));
		}
		else if(!m_table[i].Cmp("CATEGORY"))
		{
			m_info.category = PsfHelper::ReadString(psf_f, sizeof(u32));
			m_table[i].Append(wxString::Format(": %s", m_info.category.mb_str()));
		}
		else if(!m_table[i].Cmp("BOOTABLE"))
		{
			psf_f.Read(&m_info.bootable, sizeof(m_info.bootable));
			m_table[i].Append(wxString::Format(": %d", m_info.bootable));
		}
		else if(!m_table[i].Cmp("LICENSE"))
		{
			m_table[i].Append(wxString::Format(": %s", PsfHelper::ReadString(psf_f).mb_str()));
			psf_f.Seek(psf_f.Tell() + (sizeof(u64) * 7 * 2) - 1);
		}
		else if(!m_table[i](0, 14).Cmp("PARENTAL_LEVEL"))
		{
			u32 buf;
			psf_f.Read(&buf, sizeof(buf));
			if(!m_table[i].Cmp("PARENTAL_LEVEL"))
			{
				m_info.parental_lvl = buf;
			}
			m_table[i].Append(wxString::Format(": %d", buf));
		}
		else if(!m_table[i].Cmp("PS3_SYSTEM_VER"))
		{
			m_info.fw =  PsfHelper::ReadString(psf_f, sizeof(u64));
			m_table[i].Append(wxString::Format(": %s", m_info.fw.mb_str()));
		}
		else if(!m_table[i].Cmp("SOUND_FORMAT"))
		{
			m_info.sound_format = Read32(psf_f);
			m_table[i].Append(wxString::Format(": 0x%x", m_info.sound_format));
		}
		else if(!m_table[i].Cmp("RESOLUTION"))
		{
			m_info.resolution = Read32(psf_f);
			m_table[i].Append(wxString::Format(": 0x%x", m_info.resolution));
		}
		else
		{
			m_table[i].Append(wxString::Format(": %s", PsfHelper::ReadString(psf_f).mb_str()));
			PsfHelper::GoToNN(psf_f);
		}
	}

	if(m_info.serial.Length() == 9)
	{
		m_info.serial = m_info.serial(0, 4) + "-" + m_info.serial(4, 5);
	}

	return true;
}
tTJSVariant* tTJSBinarySerializer::ReadBasicType( const tjs_uint8* buff, const tjs_uint size, tjs_uint& index ) {
	if( index > size ) return NULL;
	tjs_uint8 type = buff[index];
	index++;
	switch( type  ) {
	case TYPE_NIL:
		return new tTJSVariant((iTJSDispatch2*)NULL);
	case TYPE_VOID:
		return new tTJSVariant();
	case TYPE_TRUE:
		return new tTJSVariant((tjs_int)1);
	case TYPE_FALSE:
		return new tTJSVariant((tjs_int)0);
	case TYPE_STRING8: {
		if( (index+sizeof(tjs_uint8)) > size ) TJS_eTJSError( TJSReadError );
		tjs_uint8 len = buff[index]; index++;
		if( (index+(len*sizeof(tjs_char))) > size ) TJS_eTJSError( TJSReadError );
		return ReadStringVarint( buff, len, index );
	}
	case TYPE_STRING16: {
		if( (index+sizeof(tjs_uint16)) > size ) TJS_eTJSError( TJSReadError );
		tjs_uint16 len = Read16( buff, index );
		if( (index+(len*sizeof(tjs_char))) > size ) TJS_eTJSError( TJSReadError );
		return ReadStringVarint( buff, len, index );
	}
	case TYPE_STRING32: {
		if( (index+sizeof(tjs_uint32)) > size ) TJS_eTJSError( TJSReadError );
		tjs_uint32 len = Read32( buff, index );
		if( (index+(len*sizeof(tjs_char))) > size ) TJS_eTJSError( TJSReadError );
		return ReadStringVarint( buff, len, index );
	}
	case TYPE_FLOAT: {
			if( (index+sizeof(float)) > size ) TJS_eTJSError( TJSReadError );
			tjs_uint32 t = Read32( buff, index );
			return new tTJSVariant(*(float*)&t);
		}
	case TYPE_DOUBLE: {
			if( (index+sizeof(double)) > size ) TJS_eTJSError( TJSReadError );
			tjs_uint64 t = Read64( buff, index );
			return new tTJSVariant(*(double*)&t);
		}
	case TYPE_UINT8: {
			if( (index+sizeof(tjs_uint8)) > size ) TJS_eTJSError( TJSReadError );
			tjs_uint8 t = buff[index]; index++;
			return new tTJSVariant( t );
		}
	case TYPE_UINT16: {
			if( (index+sizeof(tjs_uint16)) > size ) TJS_eTJSError( TJSReadError );
			tjs_uint16 t = Read16( buff, index );
			return new tTJSVariant( t );
		}
	case TYPE_UINT32: {
			if( (index+sizeof(tjs_uint32)) > size ) TJS_eTJSError( TJSReadError );
			tjs_uint32 t = Read32( buff, index );
			return new tTJSVariant( (tjs_int64)t );
		}
	case TYPE_UINT64: {
			if( (index+sizeof(tjs_uint64)) > size ) TJS_eTJSError( TJSReadError );
			tjs_uint64 t = Read64( buff, index );
			return new tTJSVariant( (tjs_int64)t );
		}
	case TYPE_INT8: {
			if( (index+sizeof(tjs_uint8)) > size ) TJS_eTJSError( TJSReadError );
			tjs_uint8 t = buff[index]; index++;
			return new tTJSVariant( (tjs_int8)t );
		}
	case TYPE_INT16: {
			if( (index+sizeof(tjs_uint16)) > size ) TJS_eTJSError( TJSReadError );
			tjs_uint16 t = Read16( buff, index );
			return new tTJSVariant( (tjs_int16)t );
		}
	case TYPE_INT32: {
			if( (index+sizeof(tjs_uint32)) > size ) TJS_eTJSError( TJSReadError );
			tjs_uint32 t = Read32( buff, index );
			return new tTJSVariant( (tjs_int32)t );
		}
	case TYPE_INT64: {
			if( (index+sizeof(tjs_uint64)) > size ) TJS_eTJSError( TJSReadError );
			tjs_uint64 t = Read64( buff, index );
			return new tTJSVariant( (tjs_int64)t );
		}
	case TYPE_RAW16: {
		if( (index+sizeof(tjs_uint16)) > size ) TJS_eTJSError( TJSReadError );
		tjs_uint16 len = Read16( buff, index );
		if( (index+len) > size ) TJS_eTJSError( TJSReadError );
		return ReadOctetVarint( buff, len, index );
	}
	case TYPE_RAW32: {
		if( (index+sizeof(tjs_uint32)) > size ) TJS_eTJSError( TJSReadError );
		tjs_uint32 len = Read32( buff, index );
		if( (index+len) > size ) TJS_eTJSError( TJSReadError );
		return ReadOctetVarint( buff, len, index );
	}
	case TYPE_ARRAY16: {
		if( (index+sizeof(tjs_uint16)) > size ) TJS_eTJSError( TJSReadError );
		tjs_uint16 count = Read16( buff, index );
		return ReadArray( buff, size, count, index );
	}
	case TYPE_ARRAY32: {
		if( (index+sizeof(tjs_uint32)) > size ) TJS_eTJSError( TJSReadError );
		tjs_uint32 count = Read32( buff, index );
		return ReadArray( buff, size, count, index );
	}
	case TYPE_MAP16: {
		if( (index+sizeof(tjs_uint16)) > size ) TJS_eTJSError( TJSReadError );
		tjs_uint16 count = Read16( buff, index );
		return ReadDictionary( buff, size, count, index );
	}
	case TYPE_MAP32: {
		if( (index+sizeof(tjs_uint32)) > size ) TJS_eTJSError( TJSReadError );
		tjs_uint32 count = Read32( buff, index );
		return ReadDictionary( buff, size, count, index );
	}
	default: {
		if( type >= TYPE_POSITIVE_FIX_NUM_MIN && type <= TYPE_POSITIVE_FIX_NUM_MAX ) {
			tjs_int value = type;
			return new tTJSVariant(value);
		} else if( type >= TYPE_NEGATIVE_FIX_NUM_MIN && type <= TYPE_NEGATIVE_FIX_NUM_MAX ) {
			tjs_int value = type;
			return new tTJSVariant(value);
		} else if( type >= TYPE_FIX_RAW_MIN && type <= TYPE_FIX_RAW_MAX ) { // octet
			tjs_int len = type - TYPE_FIX_RAW_MIN;
			if( (len*sizeof(tjs_uint8)+index) > size ) TJS_eTJSError( TJSReadError );
			return ReadOctetVarint( buff, len, index );
		} else if( type >= TYPE_FIX_STRING_MIN && type <= TYPE_FIX_STRING_MAX ) {
			tjs_int len = type - TYPE_FIX_STRING_MIN;
			if( (len*sizeof(tjs_char)+index) > size ) TJS_eTJSError( TJSReadError );
			return ReadStringVarint( buff, len, index );
		} else if( type >= TYPE_FIX_ARRAY_MIN && type <= TYPE_FIX_ARRAY_MAX ) {
			tjs_int count = type - TYPE_FIX_ARRAY_MIN;
			return ReadArray( buff, size, count, index );
		} else if( type >= TYPE_FIX_MAP_MIN && type <= TYPE_FIX_MAP_MAX ) {
			tjs_int count = type - TYPE_FIX_MAP_MIN;
			return ReadDictionary( buff, size, count, index );
		} else {
			TJS_eTJSError( TJSReadError );
			return NULL;
		}
	}
	}
}
Example #10
0
static void LinkFile (const char* Name, FILETYPE Type)
/* Handle one file */
{
    char*         PathName;
    FILE*         F;
    unsigned long Magic;


    /* If we don't know the file type, determine it from the extension */
    if (Type == FILETYPE_UNKNOWN) {
        Type = GetFileType (Name);
    }

    /* For known file types, search the file in the directory list */
    switch (Type) {

        case FILETYPE_LIB:
            PathName = SearchFile (LibSearchPath, Name);
            if (PathName == 0) {
                PathName = SearchFile (LibDefaultPath, Name);
            }
            break;

        case FILETYPE_OBJ:
            PathName = SearchFile (ObjSearchPath, Name);
            if (PathName == 0) {
                PathName = SearchFile (ObjDefaultPath, Name);
            }
            break;

        default:
            PathName = xstrdup (Name);   /* Use the name as is */
            break;
    }

    /* We must have a valid name now */
    if (PathName == 0) {
        Error ("Input file `%s' not found", Name);
    }

    /* Try to open the file */
    F = fopen (PathName, "rb");
    if (F == 0) {
        Error ("Cannot open `%s': %s", PathName, strerror (errno));
    }

    /* Read the magic word */
    Magic = Read32 (F);

    /* Check the magic for known file types. The handling is somewhat weird
    ** since we may have given a file with a ".lib" extension, which was
    ** searched and found in a directory for library files, but we now find
    ** out (by looking at the magic) that it's indeed an object file. We just
    ** ignore the problem and hope no one will notice...
    */
    switch (Magic) {

        case OBJ_MAGIC:
            ObjAdd (F, PathName);
            ++ObjFiles;
            break;

        case LIB_MAGIC:
            LibAdd (F, PathName);
            ++LibFiles;
            break;

        default:
            fclose (F);
            Error ("File `%s' has unknown type", PathName);

    }

    /* Free allocated memory. */
    xfree (PathName);
}
Example #11
0
float kexBinFile::ReadFloat(void) {
    fint_t fi;
    fi.i = Read32();
    return fi.f;
}
Example #12
0
ReplayInfo *ReplayInfo::ReplayInfoFromFile(FILE *in)
{
  char        temp[256+1];
  ReplayInfo *info = new ReplayInfo(0, 0);
  uint32_t    marker;

  info->last_error = _("Unspecified error or end of file");
  info->valid = false;

  // Header magic
  marker = Read32(in);                      // Header marker
  if (marker != HEADER_MAGIC) {
    info->last_error =
      Format(_("Bad header 0x%08X instead of 0x%08X"), marker, HEADER_MAGIC);
    return info;
  }

  // Version
  if (!fscanf(in, "%256[^\n]\n", temp)) return info;
  info->version = temp;
  if (ferror(in)) return info;
  
  // Time
  info->duration_ms = Read32(in);           // Duration
  info->date        = Read32(in);           // Return of time(NULL)
  if (ferror(in)) return info;

  // Comment
  if (!fscanf(in, "%256[^\n]\n", temp) || ferror(in)) return info;
  info->comment = temp;

  // map ID
  if (!fscanf(in, "%256[^\n]\n", temp) || ferror(in)) return info;
  info->map_id = temp;

  // Teams
  uint32_t num_teams = Read32(in);          // Number of teams
  if (num_teams > 8) {
    info->last_error = Format(_("Suspicious number of teams 0x%08X"), num_teams);
    return info;
  }
  while (num_teams) {
    ConfigTeam team_cfg;

    // Team No.i name
    if (!fscanf(in, "%256[^\n]\n", temp) || ferror(in))
      goto team_error;
    team_cfg.id = std::string(temp);

    // Player name for team No.i 
    if (!fscanf(in, "%256[^\n]\n", temp) || ferror(in))
      goto team_error;
    team_cfg.player_name = std::string(temp);

    team_cfg.nb_characters = Read32(in);
    if (ferror(in))
      goto team_error;

    // Nb characters for team ID No.i
    if (!fscanf(in, "%256[^\n]\n", temp) || ferror(in))
      goto team_error;
    team_cfg.ai = std::string(temp);

    info->teams.push_back(team_cfg);
    num_teams--;
    continue;

team_error:
    info->last_error = _("End of file while parsing teams");
    return info;
  }

  // Game mode
  info->mode_info.allow_character_selection = Read32(in);
  info->mode_info.turn_duration = Read32(in);
  info->mode_info.duration_before_death_mode = Read32(in);
  info->mode_info.damage_per_turn_during_death_mode = Read32(in);
  info->mode_info.init_energy = Read32(in);
  info->mode_info.max_energy = Read32(in);
  info->mode_info.gravity = Read32(in);

  if (Read32(in) != DATA_MAGIC) {           // Data magic
    info->last_error = Format(_("Bad data marker 0x%08X instead of 0x%08X"), marker, DATA_MAGIC);
    return info;
  }

  info->valid = true;
  return info;
}
Example #13
0
void SelfSection::Load(vfsStream& f)
{
	*data = Read32(f);
	size = Read64(f);
	offset = Read64(f);
}
Example #14
0
void ControlInfo::Load(vfsStream& f)
{
	type = Read32(f);
	size = Read32(f);
	next = Read64(f);

	if (type == 1)
	{
		control_flags.ctrl_flag1 = Read32(f);
		control_flags.unknown1 = Read32(f);
		control_flags.unknown2 = Read32(f);
		control_flags.unknown3 = Read32(f);
		control_flags.unknown4 = Read32(f);
		control_flags.unknown5 = Read32(f);
		control_flags.unknown6 = Read32(f);
		control_flags.unknown7 = Read32(f);
	}
	else if (type == 2)
	{
		if (size == 0x30)
		{
			f.Read(file_digest_30.digest, 20);
			file_digest_30.unknown = Read64(f);
		}
		else if (size == 0x40)
		{
			f.Read(file_digest_40.digest1, 20);
			f.Read(file_digest_40.digest2, 20);
			file_digest_40.unknown = Read64(f);
		}
	}
	else if (type == 3)
	{
		npdrm.magic = Read32(f);
		npdrm.unknown1 = Read32(f);
		npdrm.license = Read32(f);
		npdrm.type = Read32(f);
		f.Read(npdrm.content_id, 48);
		f.Read(npdrm.digest, 16);
		f.Read(npdrm.invdigest, 16);
		f.Read(npdrm.xordigest, 16);
		npdrm.unknown2 = Read64(f);
		npdrm.unknown3 = Read64(f);
	}
}
Example #15
0
u64 TestEnvironment::TestMemory::Read64(VAddr addr) {
    return Read32(addr) | static_cast<u64>(Read32(addr + 4)) << 32;
}
Example #16
0
void ReadObjHeader (FILE* F, ObjHeader* H)
/* Read an object file header from the file */
{
    /* Read all fields */
    H->Magic        = Read32 (F);
    H->Version      = Read16 (F);
    H->Flags        = Read16 (F);
    H->OptionOffs   = Read32 (F);
    H->OptionSize   = Read32 (F);
    H->FileOffs     = Read32 (F);
    H->FileSize     = Read32 (F);
    H->SegOffs      = Read32 (F);
    H->SegSize      = Read32 (F);
    H->ImportOffs   = Read32 (F);
    H->ImportSize   = Read32 (F);
    H->ExportOffs   = Read32 (F);
    H->ExportSize   = Read32 (F);
    H->DbgSymOffs   = Read32 (F);
    H->DbgSymSize   = Read32 (F);
    H->LineInfoOffs = Read32 (F);
    H->LineInfoSize = Read32 (F);
    H->StrPoolOffs  = Read32 (F);
    H->StrPoolSize  = Read32 (F);
    H->AssertOffs   = Read32 (F);
    H->AssertSize   = Read32 (F);
    H->ScopeOffs    = Read32 (F);
    H->ScopeSize    = Read32 (F);
    H->SpanOffs     = Read32 (F);
    H->SpanSize     = Read32 (F);
}
Example #17
0
bool Replay::LoadReplay(const std::string& name)
{
#define TEMP_SIZE 256
  char           temp[TEMP_SIZE];
  bool           status     = false;
  std::streampos pos;
  ReplayInfo     *info      = NULL;
  GameMode       *game_mode = GameMode::GetInstance();
  int            map_id, val;

  ASSERT(!is_recorder);
  old_time = 0;

  FILE *in = fopen(name.c_str(), "rb");
  if (!in) {
    Error(Format(_("Couldn't open %s\n"), name.c_str()));
    goto done;
  }

  info = ReplayInfo::ReplayInfoFromFile(in);
  if (!info->IsValid())
    goto done;

  if (info->GetVersion() != Constants::WARMUX_VERSION) {
    Error(Format(_("Bad version: %s != %s"),
                 info->GetVersion().c_str(),
                 Constants::WARMUX_VERSION.c_str()));
    goto done;
  }
  goto ok;

err:
  Error(Format(_("Warning, malformed replay with data of size %u"), bufsize));

done:
  fclose(in);
  if (info) delete info;
  return status;

ok:
  // duration
  old_time = info->GetMillisecondsDuration();

  // map ID
  map_id = MapsList::GetInstance()->FindMapById(info->GetMapId());
  if (map_id == -1) {
    Error(Format(_("Couldn't find map %s"), temp));
    return false;
  }
  MapsList::GetInstance()->SelectMapByIndex(map_id);

  // Backup playing list
  TeamsList& teams_list = GetTeamsList();
  backup_list = teams_list.playing_list;
  teams_list.playing_list.clear();

  // Teams
  for (uint i = 0; i<info->GetTeams().size(); i++) {
    ConfigTeam team_cfg;
    teams_list.AddTeam(info->GetTeams()[i], true);
  }

  // Game mode
  memcpy(&mode_info, info->GetGameModeInfo(), sizeof(GameModeInfo));

  // Set GameMode
  val = mode_info.allow_character_selection;
  mode_info.allow_character_selection = game_mode->allow_character_selection;
  game_mode->allow_character_selection = (GameMode::manual_change_character_t)val;
#define SWAP(a, b) val = a; a = b; b = val
  SWAP(mode_info.turn_duration, game_mode->duration_turn);
  SWAP(mode_info.duration_before_death_mode, game_mode->duration_before_death_mode);
  SWAP(mode_info.damage_per_turn_during_death_mode, game_mode->damage_per_turn_during_death_mode);
  SWAP(mode_info.init_energy, game_mode->character.init_energy);
  SWAP(mode_info.max_energy, game_mode->character.max_energy);
  SWAP(mode_info.gravity, game_mode->gravity);

  MSG_DEBUG("replay", "Game mode: turn=%us move_player=%u max_energy=%u init_energy=%u\n",
            game_mode->duration_turn, game_mode->duration_move_player,
            game_mode->character.max_energy, game_mode->character.init_energy);

  // All of the above could be avoided through a GameMode::Load
  config_loaded = true;

  seed = Read32(in);

  // Get remaining data
  pos = ftell(in);
  fseek(in, 0, SEEK_END);
  uint size = ftell(in)-pos;
  fseek(in, pos, SEEK_SET);
  MSG_DEBUG("replay", "Actions found at %u on %uB, seed=%08X\n", (uint)pos, size, seed);

  // Explicit buffer change to avoid garbage
  if (buf)
    free(buf);
  buf = (uint8_t*)malloc(size);
  ptr = buf;
  bufsize = size;

  if (fread(buf, size, 1, in)!=1 || ferror(in))
    goto err;

  size = SDLNet_Read16(ptr); ptr += 2;
  std::string mode_name((char*)ptr, size); ptr += size;

  size = SDLNet_Read16(ptr); ptr += 2;
  std::string mode((char*)ptr, size); ptr += size;

  size = SDLNet_Read16(ptr); ptr += 2;
  std::string mode_objects((char*)ptr, size); ptr += size;

  game_mode->LoadFromString(mode_name, mode, mode_objects);
  status = true;

  goto done;
}
Example #18
0
wxUint16 wxTextInputStream::Read16(int base)
{
    return (wxUint16)Read32(base);
}
Example #19
0
status_t
radeon_set_display_mode(display_mode* mode)
{
	radeon_shared_info &info = *gInfo->shared_info;

	// Set mode on each display
	for (uint8 id = 0; id < MAX_DISPLAY; id++) {
		if (gDisplay[id]->attached == false)
			continue;

		uint32 connectorIndex = gDisplay[id]->connectorIndex;
		dp_info *dpInfo = &gConnector[connectorIndex]->dpInfo;

		// Determine DP lanes if DP
		if (connector_is_dp(connectorIndex))
			dpInfo->laneCount = dp_get_lane_count(dpInfo, mode);

		// *** crtc and encoder prep
		encoder_output_lock(true);
		encoder_dpms_set(id, B_DPMS_OFF);
		display_crtc_lock(id, ATOM_ENABLE);
		display_crtc_dpms(id, B_DPMS_OFF);

		// *** Set up encoder -> crtc routing
		encoder_assign_crtc(id);

		// *** CRT controler mode set
		// TODO: program SS
		pll_set(ATOM_PPLL1, mode->timing.pixel_clock, id);
			// TODO: check if ATOM_PPLL1 is used and use ATOM_PPLL2 if so
		display_crtc_set_dtd(id, mode);

		display_crtc_fb_set(id, mode);
		// atombios_overscan_setup
		display_crtc_scale(id, mode);

		// *** encoder mode set
		encoder_mode_set(id);

		// *** CRT controler commit
		display_crtc_dpms(id, B_DPMS_ON);
		display_crtc_lock(id, ATOM_DISABLE);

		// *** encoder commit

		// handle DisplayPort link training
		if (connector_is_dp(connectorIndex)) {
			if (info.dceMajor >= 4)
				encoder_dig_setup(connectorIndex,
					ATOM_ENCODER_CMD_DP_VIDEO_OFF, 0);

			dp_link_train(id, mode);

			if (info.dceMajor >= 4)
				encoder_dig_setup(connectorIndex,
					ATOM_ENCODER_CMD_DP_VIDEO_ON, 0);
		}

		encoder_dpms_set(id, B_DPMS_ON);
		encoder_output_lock(false);
	}

	// for debugging
	TRACE("D1CRTC_STATUS        Value: 0x%X\n",
		Read32(CRT, AVIVO_D1CRTC_STATUS));
	TRACE("D2CRTC_STATUS        Value: 0x%X\n",
		Read32(CRT, AVIVO_D2CRTC_STATUS));
	TRACE("D1CRTC_CONTROL       Value: 0x%X\n",
		Read32(CRT, AVIVO_D1CRTC_CONTROL));
	TRACE("D2CRTC_CONTROL       Value: 0x%X\n",
		Read32(CRT, AVIVO_D2CRTC_CONTROL));
	TRACE("D1GRPH_ENABLE        Value: 0x%X\n",
		Read32(CRT, AVIVO_D1GRPH_ENABLE));
	TRACE("D2GRPH_ENABLE        Value: 0x%X\n",
		Read32(CRT, AVIVO_D2GRPH_ENABLE));
	TRACE("D1SCL_ENABLE         Value: 0x%X\n",
		Read32(CRT, AVIVO_D1SCL_SCALER_ENABLE));
	TRACE("D2SCL_ENABLE         Value: 0x%X\n",
		Read32(CRT, AVIVO_D2SCL_SCALER_ENABLE));
	TRACE("D1CRTC_BLANK_CONTROL Value: 0x%X\n",
		Read32(CRT, AVIVO_D1CRTC_BLANK_CONTROL));
	TRACE("D2CRTC_BLANK_CONTROL Value: 0x%X\n",
		Read32(CRT, AVIVO_D1CRTC_BLANK_CONTROL));

	return B_OK;
}
Example #20
0
wxUint8 wxTextInputStream::Read8(int base)
{
    return (wxUint8)Read32(base);
}
Example #21
0
void DumpObjExports (FILE* F, unsigned long Offset)
/* Dump the exports in the object file */
{
    ObjHeader 	H;
    Collection  StrPool = AUTO_COLLECTION_INITIALIZER;
    unsigned   	Count;
    unsigned   	I;

    /* Seek to the header position and read the header */
    FileSetPos (F, Offset);
    ReadObjHeader (F, &H);

    /* Seek to the start of the string pool and read it */
    FileSetPos (F, Offset + H.StrPoolOffs);
    ReadStrPool (F, &StrPool);

    /* Seek to the start of the exports */
    FileSetPos (F, Offset + H.ExportOffs);

    /* Output a header */
    printf ("  Exports:\n");

    /* Read the number of exports and print it */
    Count = ReadVar (F);
    printf ("    Count:%27u\n", Count);

    /* Read and print all exports */
    for (I = 0; I < Count; ++I) {

	unsigned long 	Value = 0;
        unsigned long   Size = 0;
       	unsigned char  	ConDes[CD_TYPE_COUNT];
       	const char*    	Name;
	unsigned	Len;


       	/* Read the data for one export */
       	unsigned Type          = ReadVar (F);
        unsigned char AddrSize = Read8 (F);
	ReadData (F, ConDes, SYM_GET_CONDES_COUNT (Type));
       	Name  = GetString (&StrPool, ReadVar (F));
	Len   = strlen (Name);
       	if (SYM_IS_CONST (Type)) {
	    Value = Read32 (F);
	} else {
       	    SkipExpr (F);
	}
        if (SYM_HAS_SIZE (Type)) {
            Size = ReadVar (F);
        }

        /* Skip both line infos lists */
        SkipLineInfoList (F);
        SkipLineInfoList (F);

	/* Print the header */
	printf ("    Index:%27u\n", I);

	/* Print the data */
       	printf ("      Type:%22s0x%02X  (%s)\n", "", Type, GetExportFlags (Type, ConDes));
	printf ("      Address size:%14s0x%02X  (%s)\n", "", AddrSize,
                AddrSizeToStr (AddrSize));
	printf ("      Name:%*s\"%s\"\n", (int)(24-Len), "", Name);
	if (SYM_IS_CONST (Type)) {
    	    printf ("      Value:%15s0x%08lX  (%lu)\n", "", Value, Value);
    	}
       	if (SYM_HAS_SIZE (Type)) {
	    printf ("      Size:%16s0x%04lX  (%lu)\n", "", Size, Size);
	}
    }

    /* Destroy the string pool */
    DestroyStrPool (&StrPool);
}
Example #22
0
Export* ReadExport (FILE* F, ObjData* O)
/* Read an export from a file */
{
    unsigned    ConDesCount;
    unsigned    I;
    Export*     E;

    /* Read the type */
    unsigned Type = ReadVar (F);

    /* Read the address size */
    unsigned char AddrSize = Read8 (F);

    /* Create a new export without a name */
    E = NewExport (Type, AddrSize, INVALID_STRING_ID, O);

    /* Read the constructor/destructor decls if we have any */
    ConDesCount = SYM_GET_CONDES_COUNT (Type);
    if (ConDesCount > 0) {

        unsigned char ConDes[CD_TYPE_COUNT];

        /* Read the data into temp storage */
        ReadData (F, ConDes, ConDesCount);

        /* Re-order the data. In the file, each decl is encoded into a byte
        ** which contains the type and the priority. In memory, we will use
        ** an array of types which contain the priority.
        */
        for (I = 0; I < ConDesCount; ++I) {
            E->ConDes[CD_GET_TYPE (ConDes[I])] = CD_GET_PRIO (ConDes[I]);
        }
    }

    /* Read the name */
    E->Name = MakeGlobalStringId (O, ReadVar (F));

    /* Read the value */
    if (SYM_IS_EXPR (Type)) {
        E->Expr = ReadExpr (F, O);
    } else {
        E->Expr = LiteralExpr (Read32 (F), O);
    }

    /* Read the size */
    if (SYM_HAS_SIZE (Type)) {
        E->Size = ReadVar (F);
    }

    /* Last are the locations */
    ReadLineInfoList (F, O, &E->DefLines);
    ReadLineInfoList (F, O, &E->RefLines);

    /* If this symbol is exported as a condes, and the condes type declares a
    ** forced import, add this import to the object module.
    */
    for (I = 0; I < CD_TYPE_COUNT; ++I) {
        const ConDesImport* CDI;

        if (E->ConDes[I] != CD_PRIO_NONE && (CDI = ConDesGetImport (I)) != 0) {
            unsigned J;

            /* Generate a new import, and add it to the module's import list. */
            Import* Imp = GenImport (CDI->Name, CDI->AddrSize);

            Imp->Obj = O;
            CollAppend (&O->Imports, Imp);

            /* Add line info for the export that is actually the condes that
            ** forces the import.  Then, add line info for the config. file.
            ** The export's info is added first because the import pretends
            ** that it came from the object module instead of the config. file.
            */
            for (J = 0; J < CollCount (&E->DefLines); ++J) {
                CollAppend (&Imp->RefLines, DupLineInfo (CollAt (&E->DefLines, J)));
            }
            CollAppend (&Imp->RefLines, GenLineInfo (&CDI->Pos));
        }
    }

    /* Return the new export */
    return E;
}
Example #23
0
STATICforIDL CDFstatus ValidateCDF (struct CDFstruct *CDF, vFILE *CDFfp, 
                                    Int32 offset, Int32 fileSize,
                                    Logical debug)
{
  Int32 recordSize;
  Int32 recordType;
  CDFstatus status;

  status = CDF_OK;
  /****************************************************************************
  * Read internal records from the beginning of the file until EOF (or illegal
  * record) reached.
  ****************************************************************************/
  if (!SEEKv(CDFfp,offset,vSEEK_SET)) return CRE;
  for (;;) {
     /*************************************************************************
     * Read record size.
     *************************************************************************/
     offset = V_tell (CDFfp);
     if (!CDF->badEOF && offset >= fileSize) break;
     if (!Read32(CDFfp,&recordSize)) {
       if (!CDF->badEOF) return CRE;
       else break;
     }
     if (recordSize < 1 || (!CDF->badEOF && recordSize > fileSize)) 
       return QuitCDF ("CDF: an invalid internal record size ",
                       4, 1, &recordSize, 0, debug);
     /*************************************************************************
     * Read record type.
     *************************************************************************/
     if (!Read32(CDFfp,&recordType)) return CRE;
     /*************************************************************************
     * Based on the record type...
     *************************************************************************/
     switch ((int)recordType) {
        /**********************************************************************
        * Compressed CDF Record (CCR).
        **********************************************************************/
        case CCR_: {
/*
          status = ValidateCCR (CDFfp, offset, debug);
          if (status != CDF_OK) return status;
*/
          offset = offset + recordSize;
          if (!SEEKv(CDFfp,offset,vSEEK_SET)) return CRE;
	  break;
        }
        /**********************************************************************
        * CDF Descriptor Record (CDR).
        **********************************************************************/
        case CDR_: {
          numAttrs = rVars = zVars = 0;
          status = ValidateCDR (CDFfp, offset, debug);
          if (status != CDF_OK) return status;
	  status = ValidateGDR (CDFfp, CDR.GDRoffset, debug);
	  if (status != CDF_OK) return status;
          offset = offset + recordSize;
          if (!SEEKv(CDFfp,offset,vSEEK_SET)) return CRE;
	  break;
        }
        /**********************************************************************
        * Global Descriptor Record (GDR).
        **********************************************************************/
        case GDR_: {
          offset = offset + recordSize;
          if (!SEEKv(CDFfp,offset,vSEEK_SET)) return CRE;
	  break;
        }
        /**********************************************************************
        * Attribute Descriptor Record (ADR).
        **********************************************************************/
        case ADR_: {
          ++numAttrs;
          offset = offset + recordSize;
          if (!SEEKv(CDFfp,offset,vSEEK_SET)) return CRE;
	  break;
        }
        /**********************************************************************
        * Attribute Entry Descriptor Record (AgrEDR or AzEDR).
        **********************************************************************/
        case AgrEDR_:
        case AzEDR_: {
          offset = offset + recordSize;
          if (!SEEKv(CDFfp,offset,vSEEK_SET)) return CRE;
	  break;
        }
        /**********************************************************************
        * Variable Descriptor Record (rVDR or zVDR).
        **********************************************************************/
        case rVDR_:
        case zVDR_: {
          Logical zVar = (recordType == zVDR_);
          if (zVar)
            ++zVars;
          else
            ++rVars;
          offset = offset + recordSize;
          if (!SEEKv(CDFfp,offset,vSEEK_SET)) return CRE;
	  break;
        }
        /**********************************************************************
        * Variable indeX Record (VXR).
        **********************************************************************/
        case VXR_: {
          offset = offset + recordSize;
          if (!SEEKv(CDFfp,offset,vSEEK_SET)) return CRE;
	  break;
        }
        /**********************************************************************
        * Variable Values Record (VVR).
        **********************************************************************/
        case VVR_: {
          status = ValidateVVR (CDFfp, offset, debug);
          if (recordSize < VVR_BASE_SIZE) 
            return QuitCDF ("CDF: record size is invalid ",
                            4, 1, &recordSize, 0, debug);
          offset = offset + recordSize;
          if (!SEEKv(CDFfp,offset,vSEEK_SET)) return CRE;
	  break;
        }
        /**********************************************************************
        * Compressed Variable Values Record (CVVR).
        **********************************************************************/
        case CVVR_: {
          status = ValidateCVVR (CDFfp, offset, debug);
          if (status != CDF_OK) return status;
          offset = offset + recordSize;
          if (!SEEKv(CDFfp,offset,vSEEK_SET)) return CRE;
	  break;
        }
        /**********************************************************************
        * Compressed Parameters Record (CPR).
        **********************************************************************/
        case CPR_: {
          offset = offset + recordSize;
          if (!SEEKv(CDFfp,offset,vSEEK_SET)) return CRE;
	  break;
        }
        /**********************************************************************
        * Sparseness Parameters Record (SPR).
        **********************************************************************/
        case SPR_: {
/*
          status = ValidateSPR (CDFfp, offset, debug);
          if (status != CDF_OK) return status;
*/
          offset = offset + recordSize;
          if (!SEEKv(CDFfp,offset,vSEEK_SET)) return CRE;
	  break;
        }
        /**********************************************************************
        * Unused internal record
        **********************************************************************/
        case UIR_: {
          offset = offset + recordSize;
          if (!SEEKv(CDFfp,offset,vSEEK_SET)) return CRE;
	  break;
        }
        /**********************************************************************
        * Illegal record type.
        **********************************************************************/
        default: {
	    return QuitCDF ("CDF: an invalid internal record type",
                            4, 1, &recordType, 0, debug);
        }
     }
  }
  /****************************************************************************
  * Check attribute links and their attribute entries.
  ****************************************************************************/
  if (GDR.NumAttr != numAttrs)
    return QuitCDF ("CDF: number of attributes does not match: ",
                    4, 2, &GDR.NumAttr, &numAttrs, debug);
  if (numAttrs > 0) {
    status = ValidateAttributeLinks(CDF, CDFfp, debug);
    if (status != CDF_OK) return status;
  }
  /****************************************************************************
  * Check rVariable links and their data.
  ****************************************************************************/
  if (GDR.NrVars != rVars)
    return QuitCDF ("CDF: number of rVariables does not match: ",
                    4, 2, &GDR.NrVars, &rVars, debug);
  if (rVars > 0) {
    status = ValidateVariableLinks(CDF, CDFfp, FALSE, debug);
    if (status != CDF_OK) return status;
  }
  /****************************************************************************
  * Check zVariable links and their data.
  ****************************************************************************/
  if (GDR.NzVars != zVars)
    return QuitCDF ("CDF: number of zVariables does not match: ",
                    4, 2, &GDR.NzVars, &zVars, debug);
  if (zVars > 0) {
    status = ValidateVariableLinks(CDF, CDFfp, TRUE, debug);
    if (status != CDF_OK) return status;
  }
  return CDF_OK;
}
Example #24
0
/**
 *	Reads and returns a 32-bit value from the stream without advancing the stream's position
 */
UInt32 IDataStream::Peek32(void)
{
	IDataStream_PositionSaver	saver(this);

	return Read32();
}
Example #25
0
bool CFileSystemGCWii::GetBootDOL(u8* &buffer, u32 DolSize) const
{
	u32 DolOffset = Read32(0x420) << m_OffsetShift;
	return m_rVolume->Read(DolOffset, DolSize, buffer);
}
Example #26
0
/**
 *	Reads and returns a 32-bit floating point value from the stream
 */
float IDataStream::ReadFloat(void)
{
	UInt32	out = Read32();

	return *((float *)&out);
}
Example #27
0
bool SidFile::IsPSIDHeader(const uint8_t *p)
{
	uint32_t id = Read32(p, SIDFILE_PSID_ID);
	uint16_t version = Read16(p, SIDFILE_PSID_VERSION);
	return id == 0x50534944 && (version == 1 || version == 2);
}
Example #28
0
void Read16(u16& _uReturnValue, const u32 _iAddress)
{
	u32 word;
	Read32(word, _iAddress & ~3);
	_uReturnValue = word >> (_iAddress & 3) ? 16 : 0;
}
Example #29
0
static int read_movie_header(FILE* fd, SMovie* movie)
{
	uint8 header[SMV_HEADER_SIZE];
	if(fread(header, 1, SMV_HEADER_SIZE, fd) != SMV_HEADER_SIZE)
		return WRONG_FORMAT;

	const uint8* ptr=header;
	uint32 magic=Read32(ptr);
	if(magic!=SMV_MAGIC)
		return WRONG_FORMAT;

	uint32 version=Read32(ptr);
	if(version>SMV_VERSION)
		return WRONG_VERSION;

	// we can still get this basic info from v1 movies
	movie->MovieId=Read32(ptr);
	movie->RerecordCount=Read32(ptr);
	movie->MaxFrame=Read32(ptr);
	movie->Version=version;

	int i, p, j;
	for(j = 0; j < 2; j++)
	{
		if((j == 0 && version != 3) || (j == 1 && version == 3))
		{
			movie->ControllersMask=Read8(ptr);
			movie->Opts=Read8(ptr);
			Read8(ptr); // reserved byte
			movie->SyncFlags=Read8(ptr);

			movie->SaveStateOffset=Read32(ptr);
			movie->ControllerDataOffset=Read32(ptr);
		}

		// not part of original v1 SMV format:

		if((j == 1 && version > 3) || (j == 0 && version == 3))
		{
			movie->MaxSample=Read32(ptr);
			movie->PortType[0]=Read8(ptr);
			movie->PortType[1]=Read8(ptr);

			for(p=0;p<2;p++)
				for(i=0;i<4;i++)
					movie->PortIDs[p][i]=Read8(ptr);
		}
	}

	if(version<3)
		return WRONG_VERSION;

	// needs to be at least 1 sample per frame. So, assume that to make hex editing easier, at least for non-peripheral-using movies.
	if(movie->MaxSample < movie->MaxFrame)
		movie->MaxSample = movie->MaxFrame;


	ptr += 18; // reserved bytes

	assert(ptr-header==SMV_HEADER_SIZE);

	return SUCCESS;
}
Example #30
0
status_t
radeon_set_display_mode(display_mode *mode)
{
	radeon_shared_info &info = *gInfo->shared_info;

	// Set mode on each display
	for (uint8 id = 0; id < MAX_DISPLAY; id++) {
		if (gDisplay[id]->active == false)
			continue;

		uint16 connectorIndex = gDisplay[id]->connectorIndex;

		// *** encoder prep
		encoder_output_lock(true);
		encoder_dpms_set(id, gConnector[connectorIndex]->encoder.objectID,
			B_DPMS_OFF);
		encoder_assign_crtc(id);

		// *** CRT controler prep
		display_crtc_lock(id, ATOM_ENABLE);
		display_crtc_blank(id, ATOM_BLANKING);
		if (info.dceMajor >= 3)
			display_crtc_memreq(id, ATOM_DISABLE);
		display_crtc_power(id, ATOM_DISABLE);

		// *** CRT controler mode set
		// TODO: program SS
		pll_set(ATOM_PPLL1, mode->timing.pixel_clock, id);
			// TODO: check if ATOM_PPLL1 is used and use ATOM_PPLL2 if so
		display_crtc_set_dtd(id, mode);

		display_crtc_fb_set(id, mode);
		// atombios_overscan_setup
		display_crtc_scale(id, mode);

		// *** encoder mode set
		encoder_mode_set(id, mode->timing.pixel_clock);

		// *** CRT controler commit
		display_crtc_power(id, ATOM_ENABLE);
		if (info.dceMajor >= 3)
			display_crtc_memreq(id, ATOM_ENABLE);
		display_crtc_blank(id, ATOM_BLANKING_OFF);
		display_crtc_lock(id, ATOM_DISABLE);

		// *** encoder commit
		encoder_dpms_set(id, gConnector[connectorIndex]->encoder.objectID,
			B_DPMS_ON);
		encoder_output_lock(false);
	}

	// for debugging
	TRACE("D1CRTC_STATUS        Value: 0x%X\n", Read32(CRT, D1CRTC_STATUS));
	TRACE("D2CRTC_STATUS        Value: 0x%X\n", Read32(CRT, D2CRTC_STATUS));
	TRACE("D1CRTC_CONTROL       Value: 0x%X\n", Read32(CRT, D1CRTC_CONTROL));
	TRACE("D2CRTC_CONTROL       Value: 0x%X\n", Read32(CRT, D2CRTC_CONTROL));
	TRACE("D1GRPH_ENABLE        Value: 0x%X\n",
		Read32(CRT, AVIVO_D1GRPH_ENABLE));
	TRACE("D2GRPH_ENABLE        Value: 0x%X\n",
		Read32(CRT, AVIVO_D2GRPH_ENABLE));
	TRACE("D1SCL_ENABLE         Value: 0x%X\n",
		Read32(CRT, AVIVO_D1SCL_SCALER_ENABLE));
	TRACE("D2SCL_ENABLE         Value: 0x%X\n",
		Read32(CRT, AVIVO_D2SCL_SCALER_ENABLE));
	TRACE("D1CRTC_BLANK_CONTROL Value: 0x%X\n",
		Read32(CRT, AVIVO_D1CRTC_BLANK_CONTROL));
	TRACE("D2CRTC_BLANK_CONTROL Value: 0x%X\n",
		Read32(CRT, AVIVO_D1CRTC_BLANK_CONTROL));

	return B_OK;
}