PUBLIC tBOOL GetProfileStrOut(tCHAR *szProfileName, tCHAR *szSectionName, ProfileOutput lpProfileOutput, tINT nOpt) { FILE *fp; tBOOL bRetVal = FALSE; tCHAR szBuf[1024], szStr[1024], *pChar; tCHAR szName[1024]; if ((fp = fopen(szProfileName, "rt")) == NULL) { return bRetVal; } while (fgets(szBuf, 1023, fp)) { if (szBuf[0] == '/') continue; if (szBuf[0] == '[') { szStr[0] = '\0'; GetSectionName(szBuf, szStr); if (szStr[0] && strcmp(szStr, szSectionName) == 0) { bRetVal = TRUE; break; } } } if (bRetVal == FALSE) { fclose(fp); return bRetVal; } bRetVal = FALSE; while (fgets(szBuf, 1023, fp)) { if (szBuf[0] == '/') continue; if (szBuf[0] == '[') { break; } pChar = szBuf; if ((pChar = strchr(pChar, '=')) == NULL) continue; *pChar = '\0'; if (sscanf(szBuf, "%s", szName) == 1) { pChar ++; if (nOpt) { if (sscanf(pChar, "%s", szStr) != 1) { continue; } } else { strcpy(szStr, pChar); AdjustStr(szStr); } lpProfileOutput(szName, szStr); bRetVal = TRUE; } } fclose(fp); return bRetVal; }
// print error message if error in object data-file --------------------------- // void AodInput::ParseError( int section ) { //NOTE: // GetSectionName() is overloaded and not virtual, therefore // SingleInput's ParseError() cannot be used! sprintf( line, "%sin section %s (line %d)", parser_err_str, GetSectionName( section ), m_parser_lineno ); ErrorMessage( line ); HandleCriticalError(); }
void FSystemSettings::SaveToIni() { // don't write changes in the editor if (bIsEditor) { UE_LOG(LogSystemSettings, Log, TEXT("Can't save system settings to ini in an editor mode")); return; } FSystemSettingsData::SaveToIni(GetSectionName(bIsEditor)); }
SectionID ElfReader::GetSectionByName(const char *name, int firstSection) const { for (int i = firstSection; i < header->e_shnum; i++) { const char *secname = GetSectionName(i); if (secname != NULL && strcmp(name, secname) == 0) return i; } return -1; }
/** * Overriden function that selects the proper ini section to write to */ void FSystemSettings::LoadFromIni() { FSystemSettingsData::LoadFromIni(GetSectionName(bIsEditor)); if (FParse::Param(FCommandLine::Get(), TEXT("FeatureLevelES2")) || !FPlatformProperties::SupportsHighQualityLightmaps()) { // Hack: disable high quality lightmaps with feature level ES2 //@todo-mobile - replace this with a system where feature levels can clamp misc features static auto CVarAllowHighQualityLightMaps = IConsoleManager::Get().FindConsoleVariable(TEXT("r.HighQualityLightMaps")); CVarAllowHighQualityLightMaps->Set(0); } }
UINT CPrinterInfo::GetProfileInt(LPCSTR pEntry, UINT wDefault) { CString csSection; if (m_csIniName.IsEmpty() || !GetSectionName(csSection)) { return wDefault; } else { return ::GetPrivateProfileInt(csSection, pEntry, wDefault, m_csIniName); } }
BOOL CPrinterInfo::WriteProfileString(LPCSTR pEntry, LPCSTR pString) { CString csSection; if (m_csIniName.IsEmpty() || !GetSectionName(csSection)) { return FALSE; } else { return ::WritePrivateProfileString(csSection, pEntry, pString, m_csIniName); } }
CFixed CPrinterInfo::GetProfileFixed(LPCSTR pEntry, CFixed cfDefault) { CString csSection; if (!m_csIniName.IsEmpty() && GetSectionName(csSection)) { char szBuffer[40]; if (::GetPrivateProfileString(csSection, pEntry, "", szBuffer, sizeof(szBuffer)-1, m_csIniName) > 0) { cfDefault = atol(szBuffer); } } return cfDefault; }
/* *---------------------------------------------------------------------- * DumpSymbolTable -- * * Dumps a COFF symbol table from an EXE or OBJ. We only use * it to dump tables from OBJs. *---------------------------------------------------------------------- */ void DumpSymbolTable(PIMAGE_SYMBOL pSymbolTable, FILE *fout, unsigned cSymbols) { unsigned i; PSTR stringTable; char sectionName[10]; fprintf(fout, "Symbol Table - %X entries (* = auxillary symbol)\n", cSymbols); fprintf(fout, "Indx Name Value Section cAux Type Storage\n" "---- -------------------- -------- ---------- ----- ------- --------\n"); /* * The string table apparently starts right after the symbol table */ stringTable = (PSTR)&pSymbolTable[cSymbols]; for ( i=0; i < cSymbols; i++ ) { fprintf(fout, "%04X ", i); if ( pSymbolTable->N.Name.Short != 0 ) fprintf(fout, "%-20.8s", pSymbolTable->N.ShortName); else fprintf(fout, "%-20s", stringTable + pSymbolTable->N.Name.Long); fprintf(fout, " %08X", pSymbolTable->Value); GetSectionName(pSymbolTable->SectionNumber, sectionName, sizeof(sectionName)); fprintf(fout, " sect:%s aux:%X type:%02X st:%s\n", sectionName, pSymbolTable->NumberOfAuxSymbols, pSymbolTable->Type, GetSZStorageClass(pSymbolTable->StorageClass) ); #if 0 if ( pSymbolTable->NumberOfAuxSymbols ) DumpAuxSymbols(pSymbolTable); #endif /* * Take into account any aux symbols */ i += pSymbolTable->NumberOfAuxSymbols; pSymbolTable += pSymbolTable->NumberOfAuxSymbols; pSymbolTable++; } }
//------------------------------------------------------------------------ //! Removes the current configuration //------------------------------------------------------------------------ void CViewConfigSectionProfiles::RemoveCurrentConfig() { if (GetSectionName() == m_ViewName) { // Backup strProfile-settings and reset the other settings const CString& strProfiles = ReadSetting(m_ViewName, _T("CurrentProfiles"), _T("")); const CString& activeProfile = ReadSetting(m_ViewName, _T("ActiveProfile"), _T("")); CViewConfigSectionDefault::RemoveCurrentConfig(); WriteSetting(m_ViewName, _T("CurrentProfiles"), strProfiles); WriteSetting(m_ViewName, _T("ActiveProfile"), activeProfile); } else { CViewConfigSectionDefault::RemoveCurrentConfig(); } }
void CDlgTaskEdit::UpdateWeedayCtrl() { HTREEITEM hItem = m_TreeChn.GetSelectedItem(); if (hItem == NULL) { //clear all for (int i = 0; i < 7; ++i) { CComboBox& cmbBox = *(m_vSectionBox[i]); cmbBox.ResetContent(); } return; } int nSel = m_TreeChn.GetItemData(hItem); STCHNSECTIONINFO& chnInfo = g_GlobalInfo.vChnInfo[nSel]; m_cmbChn.SelectString(0, chnInfo.strChnName); //refill section for (int i = 0; i < 7; ++i) { CComboBox& cmbBox = *(m_vSectionBox[i]); cmbBox.ResetContent(); for (size_t j = 0; j< chnInfo.vWeekSections[i].vSections.size(); ++j) { cmbBox.AddString(chnInfo.vWeekSections[i].vSections[j].strSecName); } } ST_ONECHN& oneChnRef = m_vChnCtrlData[nSel]; for (int i = 0; i < 7; ++i) { m_vchkWeekDay[i]->SetCheck(oneChnRef.vWeekDays[i].bEnable== 0? BST_UNCHECKED:BST_CHECKED); if (oneChnRef.vWeekDays[i].strSecID.IsEmpty()) { m_vSectionBox[i]->SetCurSel(-1); } else { m_vSectionBox[i]->SelectString(0, GetSectionName(oneChnRef.vWeekDays[i].strSecID, chnInfo.vWeekSections[i].vSections)); } m_vSectionBox[i]->EnableWindow(oneChnRef.vWeekDays[i].bEnable== 0? FALSE:TRUE); } }
/** * Initializes system settings and included texture LOD settings. * * @param bSetupForEditor Whether to initialize settings for Editor */ void FSystemSettings::Initialize( bool bSetupForEditor ) { TestBitFieldFunctions(); RegisterShowFlagConsoleVariables(); // Load the settings that will be the default for every other compat level, and the editor, and the other split screen levels. FSystemSettingsData DefaultSettings; DefaultSettings.LoadFromIni(GetSectionName(false), GEngineIni, false); bIsEditor = bSetupForEditor; (FSystemSettingsData&)(*this) = DefaultSettings; LoadFromIni(); ApplyOverrides(); IConsoleManager::Get().RegisterConsoleVariableSink_Handle(FConsoleCommandDelegate::CreateRaw(this, &FSystemSettings::CVarSink)); // initialize a critical texture streaming value used by texture loading, etc int32 MinTextureResidentMipCount = 7; GConfig->GetInt(TEXT("TextureStreaming"), TEXT("MinTextureResidentMipCount"), MinTextureResidentMipCount, GEngineIni); UTexture2D::SetMinTextureResidentMipCount(MinTextureResidentMipCount); }
void IniFile::SaveFile (std::wstring& FileName) { // this function dumps a given dictionary into a loadable ini file. FILE *fp; int section_index; wchar_t *section_name; int section_count; int index; int length; wchar_t key[256]; // try to open the INI file in ASCII write mode fp = _wfsopen (FileName.c_str(), L"w", _SH_DENYNO); if (fp == NULL) return; // cancel if unable to open file // keep only the file name for the comment if (wcsrchr (FileName.c_str(), L'/') != NULL) { const wchar_t* Tmp= wcsrchr (FileName.c_str(), L'/') + 1; // print the INI file name as a comment fwprintf (fp, L"# %s\n", Tmp); } else if (wcsrchr (FileName.c_str(), L'\\') != NULL) { const wchar_t* Tmp = wcsrchr (FileName.c_str(), L'\\') + 1; // print the INI file name as a comment fwprintf (fp, L"# %s\n", Tmp); } // get the number of sections there are in this INI dictionary section_count = GetNumberOfSections (); // for each section... for (section_index = 0; section_index < section_count; section_index++) { section_name = GetSectionName (section_index); // read section name // is it the default section ? if (wcscmp (section_name, INIFile_default_section) == 0) fwprintf (fp, L"\n"); // don't put the default section's name in the INI file else fwprintf (fp, L"\n[%s]\n", section_name); // dump all other sections into the INI file // build the section identifier to be used when looking up the dictionary swprintf(key, 256, L"%s%c", section_name, INI_SECTION_SEPARATOR); length = (int) wcslen (key); // then for each entry in the dictionary... for (index = 0; index < Dictionary->entry_count; index++) { if (Dictionary->entries[index].key[0] == 0) continue; // skip empty slots // does this key belong to the section we want ? if so, dump it if (wcsncmp (Dictionary->entries[index].key, key, length) == 0) { // if key starts or ends with a space, enclose it between quotes, else don't if ((Dictionary->entries[index].value[0] != 0) && (iswspace (Dictionary->entries[index].value[0]) || iswspace (Dictionary->entries[index].value[wcslen (Dictionary->entries[index].value) - 1]))) fwprintf (fp, L"%s = \"%s\"\n", Dictionary->entries[index].key + length, Dictionary->entries[index].value); else fwprintf (fp, L"%s = %s\n", Dictionary->entries[index].key + length, Dictionary->entries[index].value); } } } fclose (fp); // finished, close the file return; // and return }
//------------------------------------------------------------------------ //! Resets the current configuration by deleting it and restoring it //! from the in memory default configuration. //------------------------------------------------------------------------ void CViewConfigSectionDefault::ResetConfigDefault() { RemoveSection(GetSectionName()); m_DefaultConfig.CopySettings(*this); }
void CCOF2OMF::MakeSegmentList() { // Make temporary segment conversion list const char * oldname; // Old name of section uint32 namei; // Name index into NameBuffer uint32 align; // Segment alignment = 2^align int32 align2; // align2 = 2^align uint32 flags; // Old flags int i, j; // Loop counters int oldsec; // Old section number // Loop through old sections for (j = 0; j < NSections; j++) { // Old section number oldsec = j + 1; // Get old section header SCOFF_SectionHeader * pSectionHeader = &SectionHeaders[j]; // Get name oldname = GetSectionName(pSectionHeader->Name); // Check for debug sections if (strnicmp(oldname,"debug",5) == 0 || strnicmp(oldname+1,"debug",5) == 0) { // This is a debug section if (cmd.DebugInfo == CMDL_DEBUG_STRIP) { // Remove debug info SectionBuffer[oldsec].NewNumber = 0; cmd.CountDebugRemoved(); continue; } else if (cmd.InputType != cmd.OutputType) { err.submit(1029); // Warn that debug information is incompatible } } // Check for directive sections if (strnicmp(oldname,".drectve",8) == 0 || (pSectionHeader->Flags & (PE_SCN_LNK_INFO | PE_SCN_LNK_REMOVE))) { // This is a directive section if (cmd.ExeptionInfo) { // Remove directive section SectionBuffer[oldsec].NewNumber = 0; cmd.CountExceptionRemoved(); continue; } } // Get alignment align = (pSectionHeader->Flags & PE_SCN_ALIGN_MASK) / PE_SCN_ALIGN_1; if (align > 0) align--; // Alignment = 2^align align2 = 1 << align; // 2^align // Check for previous sections with same name for (i = 0; i < SectionBufferNum; i++) { if (strcmp(oldname, NameBuffer.Buf() + SectionBuffer[i].OldName) == 0) break; // Found same name } if (i < SectionBufferNum) { // Previous section with same name found. // i = first section with this name, oldsec = current section with this name SectionBuffer[oldsec] = SectionBuffer[i]; // Copy record SectionBuffer[oldsec].NewNameI = 0; // Indicate this is not the first record // Check if alignment is the same if (align != SectionBuffer[i].Align) { err.submit(1060, oldname); // Warning different alignments if (align > SectionBuffer[i].Align) SectionBuffer[i].Align = align; // Use highest alignment } // Get section header SectionBuffer[oldsec].psechdr = pSectionHeader; // Get size of this section SectionBuffer[oldsec].Size = pSectionHeader->SizeOfRawData; // Get offset relative to first section with same name SectionBuffer[oldsec].Offset = SectionBuffer[i].Offset + SectionBuffer[i].SegmentSize; // Align this section (We are aligning each section in the segment) SectionBuffer[oldsec].Offset = (SectionBuffer[oldsec].Offset + align2 - 1) & (- align2); // Update total size of all sections with same name SectionBuffer[i].SegmentSize = SectionBuffer[oldsec].Offset + SectionBuffer[oldsec].Size; } else { // No previous section found with same name. Make SOMFSegmentList record SectionBufferNum = oldsec + 1; // End of entries in SectionBuffer // Assign a number to this segment SectionBuffer[oldsec].NewNumber = ++NumSegments; SectionBuffer[oldsec].NewNameI = NumSegments + OMF_LNAME_LAST; // Point to old section header SectionBuffer[oldsec].psechdr = pSectionHeader; // Give it a name namei = NameBuffer.PushString(oldname); // Save name in buffer, because it is volatile SectionBuffer[oldsec].OldName = namei; // Index to name // Segment names like .text and _TEXT are both common. No need to convert the name // Only restriction is length < 256. // Do we need a unique segment name if the alignment is different from segments // with same name in another module? if (strlen(oldname) > 255) { // Segment name too long. This is very unlikely namei = NameBuffer.Push(oldname, 255); // Make truncated name NameBuffer.Push(0, 1); // Terminate by zero } SectionBuffer[oldsec].NewName = namei; // Index to name // Size SectionBuffer[oldsec].Size = pSectionHeader->SizeOfRawData; SectionBuffer[oldsec].SegmentSize = pSectionHeader->SizeOfRawData; SectionBuffer[oldsec].Offset = 0; // Alignment SectionBuffer[oldsec].Align = align; // Segment type flags = pSectionHeader->Flags; // Get segment class if (flags & (PE_SCN_CNT_CODE | PE_SCN_MEM_EXECUTE)) { // Code segment SectionBuffer[oldsec].Class = OMF_LNAME_CODE; } else if (flags & PE_SCN_CNT_UNINIT_DATA) { // Uninitialized data SectionBuffer[oldsec].Class = OMF_LNAME_BSS; } else if (!(flags & PE_SCN_MEM_WRITE)) { // Read only SectionBuffer[oldsec].Class = OMF_LNAME_CONST; } else { // Normal data SectionBuffer[oldsec].Class = OMF_LNAME_DATA; } } } // Add 1 to section count because new section numbers are 1-based SectionBufferNum = NSections + 1; }
//------------------------------------------------------------------------ //! Updates a setting value for the view //! //! @param strName Name of setting //! @param strValue New setting value //------------------------------------------------------------------------ void CViewConfigSection::SetSetting(const CString& strName, const CString& strValue) { WriteSetting(GetSectionName(), strName, strValue); }
//------------------------------------------------------------------------ //! Removes the current configuration //------------------------------------------------------------------------ void CViewConfigSection::RemoveCurrentConfig() { RemoveSection(GetSectionName()); }
/* *---------------------------------------------------------------------- * DumpExternals -- * * Dumps a COFF symbol table from an EXE or OBJ. We only use * it to dump tables from OBJs. *---------------------------------------------------------------------- */ void DumpExternals(PIMAGE_SYMBOL pSymbolTable, FILE *fout, unsigned cSymbols) { unsigned i; PSTR stringTable; char *s; #if MOB char *f; #endif char symbol[1024]; int len; /* * The string table apparently starts right after the symbol table */ stringTable = (PSTR)&pSymbolTable[cSymbols]; for ( i=0; i < cSymbols; i++ ) { // fprintf(fout, "%04X ", i); /* * Require pSymbolTable->Type == 0x20 for only functions */ #if MOB if ((pSymbolTable->SectionNumber > 0 && ( pSymbolTable->Type == 0x0 || pSymbolTable->Type == 0x20) && pSymbolTable->StorageClass == IMAGE_SYM_CLASS_EXTERNAL) || (pSymbolTable->SectionNumber == IMAGE_SYM_UNDEFINED && pSymbolTable->StorageClass == IMAGE_SYM_CLASS_EXTERNAL)) { #else if ((pSymbolTable->SectionNumber > 0 && pSymbolTable->Type == 0x20) && pSymbolTable->StorageClass == IMAGE_SYM_CLASS_EXTERNAL) { #endif #if MOB || 1 if ( pSymbolTable->N.Name.Short != 0 ) { strncpy(symbol, (char*) pSymbolTable->N.ShortName, 8); symbol[8] = 0; } else { strcpy(symbol, stringTable + pSymbolTable->N.Name.Long); } s = symbol; if (*s == '_') { s++; } #if MOB || 1 if (strncmp(s, "??_G", 4) == 0) { goto next; } if (strncmp(s, "??_E", 4) == 0) { goto next; } #endif len = strlen(s); if (s[len - 1] == '2' && s[len - 2] == '1' && s[len - 3] == '@') { s[len - 3] = '\0'; } fprintf(fout, "\t%s\n", s); #else if (pSymbolTable->N.Name.Short != 0) { strncpy(symbol, (char*) pSymbolTable->N.ShortName, 8); symbol[8] = 0; } else { s = stringTable + pSymbolTable->N.Name.Long; strcpy(symbol, s); } s = symbol; #if 0 f = strchr(s, '@'); if (f) { *f = 0; } #endif #if defined(_MSC_VER) && defined(_X86_) if (strncmp(&symbol[1], "_imp_", 5) != 0) fprintf(fout, "\t%s\n", &symbol[1]); #else fprintf(fout, "\t%s\n", symbol); #endif #endif #if OLD } else { char sectionName[10]; if ( pSymbolTable->N.Name.Short != 0 ) { strncpy(symbol, (char*) pSymbolTable->N.ShortName, 8); symbol[8] = 0; } else { strcpy(symbol, stringTable + pSymbolTable->N.Name.Long); } s = symbol; GetSectionName(pSymbolTable->SectionNumber, sectionName, sizeof(sectionName)); fprintf(fout, "SKIP %s, sect %d:%s type 0x%x, sc %d:%s\n", s, pSymbolTable->SectionNumber, sectionName, pSymbolTable->Type, pSymbolTable->StorageClass, GetSZStorageClass(pSymbolTable->StorageClass)); #endif } next: /* * Take into account any aux symbols */ i += pSymbolTable->NumberOfAuxSymbols; pSymbolTable += pSymbolTable->NumberOfAuxSymbols; pSymbolTable++; } } /* *---------------------------------------------------------------------- * DumpObjFile -- * * Dump an object file--either a full listing or just the exported * symbols. *---------------------------------------------------------------------- */ void DumpObjFile(PIMAGE_FILE_HEADER pImageFileHeader, FILE *fout, int full) { PIMAGE_SYMBOL PCOFFSymbolTable; DWORD COFFSymbolCount; PCOFFSymbolTable = (PIMAGE_SYMBOL) ((DWORD)pImageFileHeader + pImageFileHeader->PointerToSymbolTable); COFFSymbolCount = pImageFileHeader->NumberOfSymbols; if (full) { DumpSymbolTable(PCOFFSymbolTable, fout, COFFSymbolCount); } else { DumpExternals(PCOFFSymbolTable, fout, COFFSymbolCount); } }
//------------------------------------------------------------------------ //! Retrieves a setting value for the view //! //! @param strName Name of setting //! @param strDefval Default value to return if no value was found //! @return Value of the setting //------------------------------------------------------------------------ CString CViewConfigSection::GetSetting(const CString& strName, const CString& strDefval) const { return ReadSetting(GetSectionName(), strName, strDefval); }
// Debug dump void CCOFF::Dump(int options) { uint32 i, j; if (options & DUMP_FILEHDR) { // File header printf("\nDump of PE/COFF file %s", FileName); printf("\n-----------------------------------------------"); printf("\nFile size: %i", GetDataSize()); printf("\nFile header:"); printf("\nMachine: %s", Lookup(COFFMachineNames,FileHeader->Machine)); printf("\nTimeDate: 0x%08X", FileHeader->TimeDateStamp); printf(" - %s", timestring(FileHeader->TimeDateStamp)); printf("\nNumber of sections: %2i", FileHeader->NumberOfSections); printf("\nNumber of symbols: %2i", FileHeader->NumberOfSymbols); printf("\nOptional header size: %i", FileHeader->SizeOfOptionalHeader); printf("\nFlags: 0x%04X", FileHeader->Flags); // May be removed: printf("\nSymbol table offset: %i", FileHeader->PSymbolTable); printf("\nString table offset: %i", FileHeader->PSymbolTable + FileHeader->NumberOfSymbols * SIZE_SCOFF_SymTableEntry); printf("\nSection headers offset: %i", (uint32)sizeof(SCOFF_FileHeader) + FileHeader->SizeOfOptionalHeader); // Optional header if (OptionalHeader) { printf("\n\nOptional header:"); if (OptionalHeader->h32.Magic != COFF_Magic_PE64) { // 32 bit optional header printf("\nMagic number: 0x%X", OptionalHeader->h32.Magic); printf("\nSize of code: 0x%X", OptionalHeader->h32.SizeOfCode); printf("\nSize of uninitialized data: 0x%X", OptionalHeader->h32.SizeOfInitializedData); printf("\nAddress of entry point: 0x%X", OptionalHeader->h32.AddressOfEntryPoint); printf("\nBase of code: 0x%X", OptionalHeader->h32.BaseOfCode); printf("\nBase of data: 0x%X", OptionalHeader->h32.BaseOfData); printf("\nImage base: 0x%X", OptionalHeader->h32.ImageBase); printf("\nSection alignment: 0x%X", OptionalHeader->h32.SectionAlignment); printf("\nFile alignment: 0x%X", OptionalHeader->h32.FileAlignment); printf("\nSize of image: 0x%X", OptionalHeader->h32.SizeOfImage); printf("\nSize of headers: 0x%X", OptionalHeader->h32.SizeOfHeaders); printf("\nDll characteristics: 0x%X", OptionalHeader->h32.DllCharacteristics); printf("\nSize of stack reserve: 0x%X", OptionalHeader->h32.SizeOfStackReserve); printf("\nSize of stack commit: 0x%X", OptionalHeader->h32.SizeOfStackCommit); printf("\nSize of heap reserve: 0x%X", OptionalHeader->h32.SizeOfHeapReserve); printf("\nSize of heap commit: 0x%X", OptionalHeader->h32.SizeOfHeapCommit); } else { // 64 bit optional header printf("\nMagic number: 0x%X", OptionalHeader->h64.Magic); printf("\nSize of code: 0x%X", OptionalHeader->h64.SizeOfCode); printf("\nSize of uninitialized data: 0x%X", OptionalHeader->h64.SizeOfInitializedData); printf("\nAddress of entry point: 0x%X", OptionalHeader->h64.AddressOfEntryPoint); printf("\nBase of code: 0x%X", OptionalHeader->h64.BaseOfCode); printf("\nImage base: 0x%08X%08X", HighDWord(OptionalHeader->h64.ImageBase), uint32(OptionalHeader->h64.ImageBase)); printf("\nSection alignment: 0x%X", OptionalHeader->h64.SectionAlignment); printf("\nFile alignment: 0x%X", OptionalHeader->h64.FileAlignment); printf("\nSize of image: 0x%X", OptionalHeader->h64.SizeOfImage); printf("\nSize of headers: 0x%X", OptionalHeader->h64.SizeOfHeaders); printf("\nDll characteristics: 0x%X", OptionalHeader->h64.DllCharacteristics); printf("\nSize of stack reserve: 0x%08X%08X", HighDWord(OptionalHeader->h64.SizeOfStackReserve), uint32(OptionalHeader->h64.SizeOfStackReserve)); printf("\nSize of stack commit: 0x%08X%08X", HighDWord(OptionalHeader->h64.SizeOfStackCommit), uint32(OptionalHeader->h64.SizeOfStackCommit)); printf("\nSize of heap reserve: 0x%08X%08X", HighDWord(OptionalHeader->h64.SizeOfHeapReserve), uint32(OptionalHeader->h64.SizeOfHeapReserve)); printf("\nSize of heap commit: 0x%08X%08X", HighDWord(OptionalHeader->h64.SizeOfHeapCommit), uint32(OptionalHeader->h64.SizeOfHeapCommit)); } // Data directories SCOFF_ImageDirAddress dir; for (i = 0; i < NumImageDirs; i++) { if (GetImageDir(i, &dir)) { printf("\nDirectory %2i, %s:\n Address 0x%04X, Size 0x%04X, Section %i, Offset 0x%04X", i, dir.Name, dir.VirtualAddress, dir.Size, dir.Section, dir.SectionOffset); } } } } if ((options & DUMP_STRINGTB) && FileHeader->PSymbolTable && StringTableSize > 4) { // String table char * p = StringTable + 4; uint32 nread = 4, len; printf("\n\nString table:"); while (nread < StringTableSize) { len = (int)strlen(p); if (len > 0) { printf("\n>>%s<<", p); nread += len + 1; p += len + 1; } } } // Symbol tables if (options & DUMP_SYMTAB) { // Symbol table (object file) if (NumberOfSymbols) PrintSymbolTable(-1); // Import and export tables (executable file) if (OptionalHeader) PrintImportExport(); } // Section headers if (options & (DUMP_SECTHDR | DUMP_SYMTAB | DUMP_RELTAB)) { for (j = 0; j < (uint32)NSections; j++) { SCOFF_SectionHeader * SectionHeader = &SectionHeaders[j]; printf("\n\n%2i Section %s", j+1, GetSectionName(SectionHeader->Name)); //printf("\nFile offset of header: 0x%X", (int)((int8*)SectionHeader-buffer)); printf("\nVirtual size: 0x%X", SectionHeader->VirtualSize); if (SectionHeader->VirtualAddress) { printf("\nVirtual address: 0x%X", SectionHeader->VirtualAddress);} if (SectionHeader->PRawData || SectionHeader->SizeOfRawData) { printf("\nSize of raw data: 0x%X", SectionHeader->SizeOfRawData); printf("\nRaw data pointer: 0x%X", SectionHeader->PRawData); } printf("\nCharacteristics: "); PrintSegmentCharacteristics(SectionHeader->Flags); // print relocations if ((options & DUMP_RELTAB) && SectionHeader->NRelocations > 0) { printf("\nRelocation entries: %i", SectionHeader->NRelocations); printf("\nRelocation entries pointer: 0x%X", SectionHeader->PRelocations); // Pointer to relocation entry union { SCOFF_Relocation * p; // pointer to record int8 * b; // used for address calculation and incrementing } Reloc; Reloc.b = Buf() + SectionHeader->PRelocations; printf("\nRelocations:"); for (i = 0; i < SectionHeader->NRelocations; i++) { printf("\nAddr: 0x%X, symi: %i, type: %s", Reloc.p->VirtualAddress, Reloc.p->SymbolTableIndex, (WordSize == 32) ? Lookup(COFF32RelNames,Reloc.p->Type) : Lookup(COFF64RelNames,Reloc.p->Type)); if (Reloc.p->Type < COFF32_RELOC_SEG12) { // Check if address is within file if (SectionHeader->PRawData + Reloc.p->VirtualAddress < GetDataSize()) { int32 addend = *(int32*)(Buf() + SectionHeader->PRawData + Reloc.p->VirtualAddress); if (addend) printf(", Implicit addend: %i", addend); } else { printf(". Error: Address is outside file"); } } PrintSymbolTable(Reloc.p->SymbolTableIndex); Reloc.b += SIZE_SCOFF_Relocation; // Next relocation record } } // print line numbers if (SectionHeader->NLineNumbers > 0) { printf("\nLine number entries: %i", SectionHeader->NLineNumbers); printf(" Line number pointer: %i\nLines:", SectionHeader->PLineNumbers); // Pointer to line number entry union { SCOFF_LineNumbers * p; // pointer to record int8 * b; // used for address calculation and incrementing } Linnum; Linnum.b = Buf() + SectionHeader->PLineNumbers; for (i = 0; i < SectionHeader->NLineNumbers; i++) { if (Linnum.p->Line) { // Record contains line number printf(" %i:%i", Linnum.p->Line, Linnum.p->Addr); } else { // Record contains function name } Linnum.b += SIZE_SCOFF_LineNumbers; // Next line number record } } } } }
ObjFile *CoffFile::ConvertToObject(std::string outputName, ObjFactory &factory) { ObjFile *fil = new ObjFile(outputName); std::vector<ObjSection *> objectSections; std::map<int, ObjSymbol *> externalMapping; // Create the sections; for (int i=0; i < header.NumberOfSections; i++) { if (!(sections[i].Characteristics & (IMAGE_SCN_LNK_REMOVE | IMAGE_SCN_LNK_INFO)) && strnicmp(sections[i].Name, ".debug", 6)) { std::string sectname = GetSectionName(i); ObjSection * sect = factory.MakeSection(sectname); CoffSectionAux *aux = (CoffSectionAux *)& sectionSymbols[i][1]; sect->SetSize(new ObjExpression(aux->Length)); sect->SetAlignment(IMAGE_SCN_ALIGN(sections[i].Characteristics)); sect->SetQuals(GetSectionQualifiers(i)); fil->Add(sect); objectSections.push_back(sect); } else { objectSections.push_back(NULL); } } // dump comdefs for (int i=1; i < header.NumberOfSymbols; i+= symbols[i].NumberOfAuxSymbols + 1) { if (symbols[i].SectionNumber > header.NumberOfSections && symbols[i].StorageClass == IMAGE_SYM_CLASS_EXTERNAL && symbols[i].Value) { char *sname = symbols[i].Name; std::string symbolName; if (*(unsigned *)sname == 0) { symbolName = strings + *(unsigned *)(sname + 4); } else { symbolName = symbols[i].Name; if (symbolName.size() > 8) symbolName = symbolName.substr(0, 8); } symbolName = std::string("vsb") + symbolName; ObjSection * sect = factory.MakeSection(symbolName); sect->SetSize(new ObjExpression(symbols[i].Value)); sect->SetAlignment(8); sect->SetQuals(ObjSection::ram | ObjSection::max | ObjSection::virt); fil->Add(sect); objectSections.push_back(sect); } } // create the symbols for (int i=0; i < header.NumberOfSymbols; i+= symbols[i].NumberOfAuxSymbols + 1) { if (symbols[i].StorageClass == IMAGE_SYM_CLASS_EXTERNAL && symbols[i].SectionNumber <= header.NumberOfSections) { if (symbols[i].SectionNumber <= 0 || (((CoffSectionAux *)§ionSymbols[symbols[i].SectionNumber-1][1])->Selection <= 1)) { char *sname = symbols[i].Name; std::string symbolName; if (*(unsigned *)sname == 0) { symbolName = strings + *(unsigned *)(sname + 4); if (symbolName == "_WinMain@16") symbolName = "WinMain"; } else { symbolName = symbols[i].Name; if (symbolName.size() > 8) symbolName = symbolName.substr(0, 8); } if (symbols[i].SectionNumber == -1) { ObjSymbol *symbol = factory.MakePublicSymbol(symbolName); ObjExpression *exp = new ObjExpression(symbols[i].Value); symbol->SetOffset(exp); fil->Add(symbol); } else if (symbols[i].SectionNumber) { ObjSymbol *symbol = factory.MakePublicSymbol(symbolName); ObjExpression *exp = new ObjExpression(ObjExpression::eAdd, new ObjExpression(objectSections[symbols[i].SectionNumber-1]), new ObjExpression(symbols[i].Value)); symbol->SetOffset(exp); fil->Add(symbol); } else { ObjSymbol *symbol = factory.MakeExternalSymbol(symbolName); externalMapping[i] = symbol; fil->Add(symbol); } } } } // dump data to the sections for (int i=0; i < header.NumberOfSections; i++) { if (objectSections[i]) { int len = sections[i].SizeOfRawData; if (len) { inputFile->seekg(sections[i].PointerToRawData + libOffset); int relocCount = sections[i].NumberOfRelocations; CoffReloc * relocPointer = relocs[i]; if (relocCount == 0xffff && (sections[i].Characteristics & IMAGE_SCN_LNK_NRELOC_OVFL)) { relocCount = relocPointer[0].VirtualAddress; relocPointer++; } unsigned offset = 0; inputFile->clear(); while (offset < sections[i].SizeOfRawData) { if (!relocCount) { ObjByte *data = new ObjByte[sections[i].SizeOfRawData-offset]; inputFile->read((char *)data, sections[i].SizeOfRawData-offset); if (inputFile->fail()) { return NULL; } ObjMemory *newMem = new ObjMemory(data, sections[i].SizeOfRawData-offset); objectSections[i]->Add(newMem); offset = sections[i].SizeOfRawData; } else { unsigned fixupOffset; int n = relocPointer->VirtualAddress - offset; if (n) { ObjByte *data = new ObjByte[n]; inputFile->read((char *)data, n); if (inputFile->fail()) { return NULL; } ObjMemory *newMem = new ObjMemory(data, n); objectSections[i]->Add(newMem); } inputFile->read((char *)&fixupOffset, sizeof(unsigned)); if (inputFile->fail()) { return NULL; } switch (relocPointer->Type) { ObjExpression *fixupExpr; case IMAGE_REL_I386_DIR32: case IMAGE_REL_I386_REL32: if (symbols[relocPointer->SymbolTableIndex].StorageClass == IMAGE_SYM_CLASS_EXTERNAL) { if (symbols[relocPointer->SymbolTableIndex].SectionNumber == 0) { // external fixupExpr = new ObjExpression(externalMapping[relocPointer->SymbolTableIndex]); } else if (symbols[relocPointer->SymbolTableIndex].SectionNumber > header.NumberOfSections) { fixupExpr = new ObjExpression(ObjExpression::eAdd, new ObjExpression(objectSections[symbols[relocPointer->SymbolTableIndex].SectionNumber-1]), new ObjExpression(0)); } else { // public fixupExpr = new ObjExpression(ObjExpression::eAdd, new ObjExpression(objectSections[symbols[relocPointer->SymbolTableIndex].SectionNumber-1]), new ObjExpression(symbols[relocPointer->SymbolTableIndex].Value)); } } else { // local static fixupExpr = new ObjExpression(ObjExpression::eAdd, new ObjExpression(objectSections[symbols[relocPointer->SymbolTableIndex].SectionNumber-1]), new ObjExpression(symbols[relocPointer->SymbolTableIndex].Value)); } if (relocPointer->Type == IMAGE_REL_I386_REL32) { fixupExpr = new ObjExpression(ObjExpression::eAdd, fixupExpr, new ObjExpression(fixupOffset - 4)); fixupExpr = new ObjExpression(ObjExpression::eSub, fixupExpr, new ObjExpression(ObjExpression::ePC) ); } else if (fixupOffset) { fixupExpr = new ObjExpression(ObjExpression::eAdd, fixupExpr, new ObjExpression(fixupOffset)); } objectSections[i]->Add(new ObjMemory(fixupExpr, 4)); break; default: std::cout << "Invalid relocation" << std::endl; return NULL; } offset += n + 4; relocPointer++; relocCount--; } } } } } for (int i=1; i < header.NumberOfSymbols; i+= symbols[i].NumberOfAuxSymbols + 1) { if (symbols[i].SectionNumber > header.NumberOfSections && symbols[i].StorageClass == IMAGE_SYM_CLASS_EXTERNAL && symbols[i].Value) { int n = symbols[i].SectionNumber-1; ObjByte *data = new ObjByte[symbols[i].Value]; memset(data,0, symbols[i].Value); ObjMemory *newMem = new ObjMemory(data, symbols[i].Value); objectSections[n]->Add(newMem); } } return fil; }
/** * Overridden function that selects the proper ini section to write to */ void FSystemSettings::LoadFromIni() { FSystemSettingsData::LoadFromIni(GetSectionName(bIsEditor)); }
void DwarfFrameManager::ProcessSection(FileShdrPair & aPair, Dwarf_Byte_Ptr aStart, Dwarf_Byte_Ptr aEnd){ CiePtrEncodingMap ptrEncodingMap; CieAugmentationMap augmentationMap; size_t encoded_ptr_size = ENCODED_POINTER_SIZE; size_t bytes_read; Dwarf_Byte_Ptr start = aStart; Dwarf_Byte_Ptr section_start = start; Dwarf_Byte_Ptr end = aEnd; while (start < end) { unsigned char *augmentation_data = NULL; unsigned long augmentation_data_len = 0; size_t offset_size; size_t initial_length_size; Dwarf_Byte_Ptr saved_start = start; Dwarf_Word length = READ_UNALIGNED4(start); start += 4; if (length == 0){ // ZERO terminator - shouldn't see this continue; } if (length >= 0xfffffff0u) { cerr << "Error: 64 bit DWARF not supported\n"; exit(EXIT_FAILURE); } else { offset_size = 4; initial_length_size = 4; } Dwarf_Byte_Ptr block_end = saved_start + length + initial_length_size; if (block_end > end) { cerr << "Warning: Invalid length " << length << " in FDE at 0x" << (unsigned long)(saved_start - section_start) << " in file " << aPair.iXIPFileDetails.iElfFile << "\n"; block_end = end; } Dwarf_Word cie_id = READ_UNALIGNED4(start); if (cie_id != (Dwarf_Word)DW_CIE_ID) WRITE_UNALIGNED4(start, cie_id + GetSectionOffset(aPair.iXIPFileDetails.iElfFile)); start += offset_size; if (cie_id == (Dwarf_Word)DW_CIE_ID) { Dwarf_Ubyte version = *start++; char * augmentation = (char *) start; augmentation_data = NULL; start = (Dwarf_Byte_Ptr) strchr ((char *) start, '\0') + 1; if (augmentation[0] == 'z'){ ULEB128(start, bytes_read); ULEB128(start, bytes_read); if (version == 1){ // fc->ra = GET (1); start++; } else { // fc->ra = LEB (); ULEB128(start, bytes_read); } augmentation_data_len = ULEB128(start, bytes_read); augmentation_data = start; augmentationMap[saved_start] = augmentation_data_len; start += augmentation_data_len; } else if (strcmp (augmentation, "eh") == 0){ //start += eh_addr_size; start += 4; // fc->code_factor = LEB (); // fc->data_factor = SLEB (); ULEB128(start, bytes_read); ULEB128(start, bytes_read); if (version == 1){ //c->ra = GET (1); start++; } else { // fc->ra = LEB (); ULEB128(start, bytes_read); } } else { ULEB128(start, bytes_read); ULEB128(start, bytes_read); if (version == 1){ // fc->ra = GET (1); start++; } else { // fc->ra = LEB (); ULEB128(start, bytes_read); } } if (augmentation_data_len){ unsigned char *p, *q; p = (unsigned char *) augmentation + 1; q = augmentation_data; Dwarf_Ubyte encoding = 0; while (1){ if (*p == 'L') q++; else if (*p == 'P') q += 1 + SizeOfEncodedValue(*q); else if (*p == 'R') encoding = *q++; else break; p++; } if (encoding) ptrEncodingMap[saved_start] = encoding; } } else { Dwarf_Byte_Ptr look_for = section_start + cie_id; Dwarf_Ubyte encoding = 0; CiePtrEncodingMap::iterator iE = ptrEncodingMap.find(look_for); if (iE != ptrEncodingMap.end()){ encoding = iE->second; encoded_ptr_size = SizeOfEncodedValue(encoding); } if ((encoding & 0x70) != DW_EH_PE_pcrel){ // do the nasty LinearAddr addr = GetValue(start, encoded_ptr_size); LinearAddr relocatedAddr = aPair.iXIPFileDetails.Relocate(addr); if (ValueFitsSize(relocatedAddr, encoded_ptr_size)){ WriteValue(start, relocatedAddr, encoded_ptr_size); } else { cerr << "Warning: relocated addresses in " << GetSectionName().c_str() << " section of " << aPair.iXIPFileDetails.iElfFile.c_str() << " too large for encoding. Backtraces may be misleading.\n"; } } start += encoded_ptr_size; // skip the range size start += encoded_ptr_size; CieAugmentationMap::iterator iP = augmentationMap.find(look_for); if (iP != augmentationMap.end()){ ULEB128(start, bytes_read); start += bytes_read; } } Dwarf_Word tmp = 0; while (start < block_end){ unsigned op, opa; op = *start++; opa = op & 0x3f; if (op & 0xc0) op &= 0xc0; switch (op){ case DW_CFA_advance_loc: break; case DW_CFA_offset: ULEB128(start, bytes_read); break; case DW_CFA_restore: break; case DW_CFA_set_loc: start += encoded_ptr_size; break; case DW_CFA_advance_loc1: start += 1; break; case DW_CFA_advance_loc2: start += 2; break; case DW_CFA_advance_loc4: start += 4; break; case DW_CFA_offset_extended: case DW_CFA_val_offset: ULEB128(start, bytes_read); ULEB128(start, bytes_read); break; case DW_CFA_restore_extended: case DW_CFA_undefined: case DW_CFA_same_value: ULEB128(start, bytes_read); break; case DW_CFA_register: case DW_CFA_def_cfa: ULEB128(start, bytes_read); ULEB128(start, bytes_read); break; case DW_CFA_def_cfa_register: case DW_CFA_def_cfa_offset: ULEB128(start, bytes_read); break; case DW_CFA_def_cfa_expression: tmp = ULEB128(start, bytes_read); EditLocationExpression (start, encoded_ptr_size, tmp, aPair); start += tmp; break; case DW_CFA_expression: case DW_CFA_val_expression: ULEB128(start, bytes_read); tmp = ULEB128(start, bytes_read); EditLocationExpression (start, encoded_ptr_size, tmp, aPair); start += tmp; break; #ifndef DW_CFA_offset_extended_sf // seems to be type in dwarf.h #define DW_CFA_offset_extended_sf 0x11 //DW_CFA_cfa_offset_extended_sf #endif case DW_CFA_offset_extended_sf: case DW_CFA_val_offset_sf: case DW_CFA_def_cfa_sf: ULEB128(start, bytes_read); ULEB128(start, bytes_read); break; case DW_CFA_def_cfa_offset_sf: ULEB128(start, bytes_read); break; case DW_CFA_MIPS_advance_loc8: start += 8; break; case DW_CFA_GNU_args_size: ULEB128(start, bytes_read); break; case DW_CFA_GNU_negative_offset_extended: ULEB128(start, bytes_read); ULEB128(start, bytes_read); break; default: break; } } } }
void CCOF2ASM::MakeSectionList() { // Сделать списки секций и релокаций в Disasm uint32 isec; // Индекс секции uint32 irel; // Индекс релокации // Цикл по секциям кода for (isec = 0; isec < (uint32)NSections; isec++) { // Получить заголовок секции SCOFF_SectionHeader * SectionHeader = &SectionHeaders[isec]; // Свойства секции const char * Name = GetSectionName(SectionHeader->Name); uint8 * Buffer = (uint8*)Buf() + SectionHeader->PRawData; uint32 InitSize = SectionHeader->SizeOfRawData; uint32 TotalSize = SectionHeader->VirtualSize; uint32 SectionAddress = SectionHeader->VirtualAddress; uint32 Type = (SectionHeader->Flags & PE_SCN_CNT_CODE) ? 1 : 2; if (SectionHeader->Flags & PE_SCN_CNT_UNINIT_DATA) { // Сегмент BSS. В файле нет данных Buffer = 0; Type = 3; } else if (!(SectionHeader->Flags & (PE_SCN_MEM_WRITE | PE_SCN_MEM_EXECUTE))) { // Сегмент констант Type = 4; } if (SectionHeader->Flags & PE_SCN_LNK_COMDAT) { //Коммунальный сегмент Type |= 0x1000; } if (strnicmp(Name,"debug",5) == 0 || strnicmp(Name+1,"debug",5) == 0) { // Отладочный раздел Type = 0x10; } if (strnicmp(Name,".pdata", 6) == 0) { // В этой секции находится информация об исключениях Type = 0x11; } uint32 Align = (SectionHeader->Flags & PE_SCN_ALIGN_MASK) / PE_SCN_ALIGN_1; if (Align) Align--; // Сохранить запись секции Disasm.AddSection(Buffer, InitSize, TotalSize, SectionAddress, Type, Align, WordSize, Name); // Получить релокации // Указатель на вход в релокации union { SCOFF_Relocation * p; // указатель на запись int8 * b; // используется для вычисления и наращивания адреса } Reloc; Reloc.b = Buf() + SectionHeader->PRelocations; for (irel = 0; irel < SectionHeader->NRelocations; irel++, Reloc.b += SIZE_SCOFF_Relocation) { // Свойства релокации int32 Section = isec + 1; uint32 Offset = Reloc.p->VirtualAddress; int32 Addend = 0; uint32 TargetIndex = Reloc.p->SymbolTableIndex; // Транслировать тип релокации uint32 Type = 0, Size = 0; if (WordSize == 32) { // 32-битные типы релокаций // 0 = unknown, 1 = direct, 2 = self-relative, 3 = image-relative, 4 = segment relative switch(Reloc.p->Type) { case COFF32_RELOC_ABS: // Ignore continue; case COFF32_RELOC_DIR32: // Direct, 32 bits Type = 1; Size = 4; break; case COFF32_RELOC_REL32: // Self-relative, 32 bits Type = 2; Size = 4; Addend = -4; break; case COFF32_RELOC_IMGREL: // Image relative, 32 bits Type = 4; Size = 4; break; case COFF32_RELOC_SECREL: // Section relative, 32 bits Type = 8; Size = 4; break; case COFF32_RELOC_SECTION: // Индекс секции символов, 16 bits Type = 0x200; Size = 2; break; default: // Other/unknown Type = 0; Size = 4; } } else { // WordSize = 64 switch(Reloc.p->Type) { case COFF64_RELOC_ABS: // Ignore continue; case COFF64_RELOC_ABS32: // Absolute 32 bit Type = 1; Size = 4; break; case COFF64_RELOC_ABS64: // Absolute 64 bit Type = 1; Size = 8; break; case COFF64_RELOC_IMGREL: // Image relative 32 bit Type = 4; Size = 4; break; case COFF64_RELOC_REL32: // Self-relative, 32 bits case COFF64_RELOC_REL32_1: // Self-relative + 1 case COFF64_RELOC_REL32_2: // Self-relative + 2 case COFF64_RELOC_REL32_3: // Self-relative + 3 case COFF64_RELOC_REL32_4: // Self-relative + 4 case COFF64_RELOC_REL32_5: // Self-relative + 5 Type = 2; Size = 4; Addend = - (Reloc.p->Type + 4 - COFF64_RELOC_REL32); break; case COFF64_RELOC_SECREL: // Section relative Type = 8; Size = 4; break; default: // Other/unknown Type = 0; Size = 4; } } // Save relocation record Disasm.AddRelocation(Section, Offset, Addend, Type, Size, TargetIndex); } } }