本文整理汇总了C++中StringRef::data方法的典型用法代码示例。如果您正苦于以下问题:C++ StringRef::data方法的具体用法?C++ StringRef::data怎么用?C++ StringRef::data使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类StringRef
的用法示例。
在下文中一共展示了StringRef::data方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: addDefinedSymbol
/// addDefinedSymbol - Add a defined symbol to the list.
void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
// ignore all llvm.* symbols
if (def->getName().startswith("llvm."))
return;
// string is owned by _defines
SmallString<64> Buffer;
_mangler.getNameWithPrefix(Buffer, def, false);
// set alignment part log2() can have rounding errors
uint32_t align = def->getAlignment();
uint32_t attr = align ? countTrailingZeros(def->getAlignment()) : 0;
// set permissions part
if (isFunction) {
attr |= LTO_SYMBOL_PERMISSIONS_CODE;
} else {
const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
if (gv && gv->isConstant())
attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
else
attr |= LTO_SYMBOL_PERMISSIONS_DATA;
}
// set definition part
if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
def->hasLinkerPrivateWeakLinkage())
attr |= LTO_SYMBOL_DEFINITION_WEAK;
else if (def->hasCommonLinkage())
attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
else
attr |= LTO_SYMBOL_DEFINITION_REGULAR;
// set scope part
if (def->hasHiddenVisibility())
attr |= LTO_SYMBOL_SCOPE_HIDDEN;
else if (def->hasProtectedVisibility())
attr |= LTO_SYMBOL_SCOPE_PROTECTED;
else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
def->hasLinkerPrivateWeakLinkage())
attr |= LTO_SYMBOL_SCOPE_DEFAULT;
else if (def->hasLinkOnceODRAutoHideLinkage())
attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
else
attr |= LTO_SYMBOL_SCOPE_INTERNAL;
StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
entry.setValue(1);
// fill information structure
NameAndAttributes info;
StringRef Name = entry.getKey();
info.name = Name.data();
assert(info.name[Name.size()] == '\0');
info.attributes = attr;
info.isFunction = isFunction;
info.symbol = def;
// add to table of symbols
_symbols.push_back(info);
}
示例2:
uint32_t zlib::crc32(StringRef Buffer) {
return ::crc32(0, (const Bytef *)Buffer.data(), Buffer.size());
}
示例3: ParseBlock
//.........这里部分代码省略.........
return Error("Premature end of bitstream");
uint64_t RecordStartBit = Stream.GetCurrentBitNo();
BitstreamEntry Entry =
Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
switch (Entry.Kind) {
case BitstreamEntry::Error:
return Error("malformed bitcode file");
case BitstreamEntry::EndBlock: {
uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
BlockStats.NumBits += BlockBitEnd-BlockBitStart;
if (Dump) {
outs() << Indent << "</";
if (BlockName)
outs() << BlockName << ">\n";
else
outs() << "UnknownBlock" << BlockID << ">\n";
}
return false;
}
case BitstreamEntry::SubBlock: {
uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
if (ParseBlock(Stream, Entry.ID, IndentLevel+1))
return true;
++BlockStats.NumSubBlocks;
uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
// Don't include subblock sizes in the size of this block.
BlockBitStart += SubBlockBitEnd-SubBlockBitStart;
continue;
}
case BitstreamEntry::Record:
// The interesting case.
break;
}
if (Entry.ID == bitc::DEFINE_ABBREV) {
Stream.ReadAbbrevRecord();
++BlockStats.NumAbbrevs;
continue;
}
Record.clear();
++BlockStats.NumRecords;
StringRef Blob;
unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
// Increment the # occurrences of this code.
if (BlockStats.CodeFreq.size() <= Code)
BlockStats.CodeFreq.resize(Code+1);
BlockStats.CodeFreq[Code].NumInstances++;
BlockStats.CodeFreq[Code].TotalBits +=
Stream.GetCurrentBitNo()-RecordStartBit;
if (Entry.ID != bitc::UNABBREV_RECORD) {
BlockStats.CodeFreq[Code].NumAbbrev++;
++BlockStats.NumAbbreviatedRecords;
}
if (Dump) {
outs() << Indent << " <";
if (const char *CodeName =
GetCodeName(Code, BlockID, *Stream.getBitStreamReader()))
outs() << CodeName;
else
outs() << "UnknownCode" << Code;
if (NonSymbolic &&
GetCodeName(Code, BlockID, *Stream.getBitStreamReader()))
outs() << " codeid=" << Code;
if (Entry.ID != bitc::UNABBREV_RECORD)
outs() << " abbrevid=" << Entry.ID;
for (unsigned i = 0, e = Record.size(); i != e; ++i)
outs() << " op" << i << "=" << (int64_t)Record[i];
outs() << "/>";
if (Blob.data()) {
outs() << " blob data = ";
bool BlobIsPrintable = true;
for (unsigned i = 0, e = Blob.size(); i != e; ++i)
if (!isprint(static_cast<unsigned char>(Blob[i]))) {
BlobIsPrintable = false;
break;
}
if (BlobIsPrintable)
outs() << "'" << Blob << "'";
else
outs() << "unprintable, " << Blob.size() << " bytes.";
}
outs() << "\n";
}
}
}
示例4: processRelocationRef
void RuntimeDyldMachO::processRelocationRef(unsigned SectionID,
RelocationRef RelI,
ObjectImage &Obj,
ObjSectionToIDMap &ObjSectionToID,
const SymbolTableMap &Symbols,
StubMap &Stubs) {
const ObjectFile *OF = Obj.getObjectFile();
const MachOObjectFile *MachO = static_cast<const MachOObjectFile*>(OF);
MachO::any_relocation_info RE= MachO->getRelocation(RelI.getRawDataRefImpl());
uint32_t RelType = MachO->getAnyRelocationType(RE);
// FIXME: Properly handle scattered relocations.
// For now, optimistically skip these: they can often be ignored, as
// the static linker will already have applied the relocation, and it
// only needs to be reapplied if symbols move relative to one another.
// Note: This will fail horribly where the relocations *do* need to be
// applied, but that was already the case.
if (MachO->isRelocationScattered(RE))
return;
RelocationValueRef Value;
SectionEntry &Section = Sections[SectionID];
bool isExtern = MachO->getPlainRelocationExternal(RE);
bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
unsigned Size = MachO->getAnyRelocationLength(RE);
uint64_t Offset;
RelI.getOffset(Offset);
uint8_t *LocalAddress = Section.Address + Offset;
unsigned NumBytes = 1 << Size;
uint64_t Addend = 0;
memcpy(&Addend, LocalAddress, NumBytes);
if (isExtern) {
// Obtain the symbol name which is referenced in the relocation
symbol_iterator Symbol = RelI.getSymbol();
StringRef TargetName;
Symbol->getName(TargetName);
// First search for the symbol in the local symbol table
SymbolTableMap::const_iterator lsi = Symbols.find(TargetName.data());
if (lsi != Symbols.end()) {
Value.SectionID = lsi->second.first;
Value.Addend = lsi->second.second + Addend;
} else {
// Search for the symbol in the global symbol table
SymbolTableMap::const_iterator gsi = GlobalSymbolTable.find(TargetName.data());
if (gsi != GlobalSymbolTable.end()) {
Value.SectionID = gsi->second.first;
Value.Addend = gsi->second.second + Addend;
} else {
Value.SymbolName = TargetName.data();
Value.Addend = Addend;
}
}
} else {
SectionRef Sec = MachO->getRelocationSection(RE);
Value.SectionID = findOrEmitSection(Obj, Sec, true, ObjSectionToID);
uint64_t Addr;
Sec.getAddress(Addr);
Value.Addend = Addend - Addr;
}
if (Arch == Triple::x86_64 && (RelType == MachO::X86_64_RELOC_GOT ||
RelType == MachO::X86_64_RELOC_GOT_LOAD)) {
assert(IsPCRel);
assert(Size == 2);
StubMap::const_iterator i = Stubs.find(Value);
uint8_t *Addr;
if (i != Stubs.end()) {
Addr = Section.Address + i->second;
} else {
Stubs[Value] = Section.StubOffset;
uint8_t *GOTEntry = Section.Address + Section.StubOffset;
RelocationEntry RE(SectionID, Section.StubOffset,
MachO::X86_64_RELOC_UNSIGNED, 0, false, 3);
if (Value.SymbolName)
addRelocationForSymbol(RE, Value.SymbolName);
else
addRelocationForSection(RE, Value.SectionID);
Section.StubOffset += 8;
Addr = GOTEntry;
}
resolveRelocation(Section, Offset, (uint64_t)Addr,
MachO::X86_64_RELOC_UNSIGNED, Value.Addend, true, 2);
} else if (Arch == Triple::arm &&
(RelType & 0xf) == MachO::ARM_RELOC_BR24) {
// This is an ARM branch relocation, need to use a stub function.
// Look up for existing stub.
StubMap::const_iterator i = Stubs.find(Value);
if (i != Stubs.end())
resolveRelocation(Section, Offset,
(uint64_t)Section.Address + i->second,
RelType, 0, IsPCRel, Size);
else {
// Create a new stub function.
Stubs[Value] = Section.StubOffset;
uint8_t *StubTargetAddr = createStubFunction(Section.Address +
Section.StubOffset);
//.........这里部分代码省略.........
示例5: Check
//.........这里部分代码省略.........
Results->NumResults = 0;
// Create a code-completion consumer to capture the results.
CodeCompleteOptions Opts;
Opts.IncludeBriefComments = IncludeBriefComments;
CaptureCompletionResults Capture(Opts, *Results, &TU);
// Perform completion.
AST->CodeComplete(complete_filename, complete_line, complete_column,
RemappedFiles, (options & CXCodeComplete_IncludeMacros),
(options & CXCodeComplete_IncludeCodePatterns),
IncludeBriefComments, Capture,
CXXIdx->getPCHContainerOperations(), *Results->Diag,
Results->LangOpts, *Results->SourceMgr, *Results->FileMgr,
Results->Diagnostics, Results->TemporaryBuffers);
Results->DiagnosticsWrappers.resize(Results->Diagnostics.size());
// Keep a reference to the allocator used for cached global completions, so
// that we can be sure that the memory used by our code completion strings
// doesn't get freed due to subsequent reparses (while the code completion
// results are still active).
Results->CachedCompletionAllocator = AST->getCachedCompletionAllocator();
#ifdef UDP_CODE_COMPLETION_LOGGER
#ifdef UDP_CODE_COMPLETION_LOGGER_PORT
const llvm::TimeRecord &EndTime = llvm::TimeRecord::getCurrentTime();
SmallString<256> LogResult;
llvm::raw_svector_ostream os(LogResult);
// Figure out the language and whether or not it uses PCH.
const char *lang = 0;
bool usesPCH = false;
for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
I != E; ++I) {
if (*I == 0)
continue;
if (strcmp(*I, "-x") == 0) {
if (I + 1 != E) {
lang = *(++I);
continue;
}
}
else if (strcmp(*I, "-include") == 0) {
if (I+1 != E) {
const char *arg = *(++I);
SmallString<512> pchName;
{
llvm::raw_svector_ostream os(pchName);
os << arg << ".pth";
}
pchName.push_back('\0');
struct stat stat_results;
if (stat(pchName.str().c_str(), &stat_results) == 0)
usesPCH = true;
continue;
}
}
}
os << "{ ";
os << "\"wall\": " << (EndTime.getWallTime() - StartTime.getWallTime());
os << ", \"numRes\": " << Results->NumResults;
os << ", \"diags\": " << Results->Diagnostics.size();
os << ", \"pch\": " << (usesPCH ? "true" : "false");
os << ", \"lang\": \"" << (lang ? lang : "<unknown>") << '"';
const char *name = getlogin();
os << ", \"user\": \"" << (name ? name : "unknown") << '"';
os << ", \"clangVer\": \"" << getClangFullVersion() << '"';
os << " }";
StringRef res = os.str();
if (res.size() > 0) {
do {
// Setup the UDP socket.
struct sockaddr_in servaddr;
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(UDP_CODE_COMPLETION_LOGGER_PORT);
if (inet_pton(AF_INET, UDP_CODE_COMPLETION_LOGGER,
&servaddr.sin_addr) <= 0)
break;
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
break;
sendto(sockfd, res.data(), res.size(), 0,
(struct sockaddr *)&servaddr, sizeof(servaddr));
close(sockfd);
}
while (false);
}
#endif
#endif
return Results;
}
示例6: mangleAsString
/// Mangle this entity as a std::string.
std::string LinkEntity::mangleAsString() const {
IRGenMangler mangler;
switch (getKind()) {
case Kind::DispatchThunk:
return mangler.mangleEntity(getDecl(), /*isCurried=*/false,
ASTMangler::SymbolKind::SwiftDispatchThunk);
case Kind::DispatchThunkInitializer:
return mangler.mangleConstructorEntity(
cast<ConstructorDecl>(getDecl()),
/*isAllocating=*/false,
/*isCurried=*/false,
ASTMangler::SymbolKind::SwiftDispatchThunk);
case Kind::DispatchThunkAllocator:
return mangler.mangleConstructorEntity(
cast<ConstructorDecl>(getDecl()),
/*isAllocating=*/true,
/*isCurried=*/false,
ASTMangler::SymbolKind::SwiftDispatchThunk);
case Kind::ValueWitness:
return mangler.mangleValueWitness(getType(), getValueWitness());
case Kind::ValueWitnessTable:
return mangler.mangleValueWitnessTable(getType());
case Kind::TypeMetadataAccessFunction:
return mangler.mangleTypeMetadataAccessFunction(getType());
case Kind::TypeMetadataLazyCacheVariable:
return mangler.mangleTypeMetadataLazyCacheVariable(getType());
case Kind::TypeMetadataInstantiationCache:
return mangler.mangleTypeMetadataInstantiationCache(
cast<NominalTypeDecl>(getDecl()));
case Kind::TypeMetadataInstantiationFunction:
return mangler.mangleTypeMetadataInstantiationFunction(
cast<NominalTypeDecl>(getDecl()));
case Kind::TypeMetadataInPlaceInitializationCache:
return mangler.mangleTypeMetadataInPlaceInitializationCache(
cast<NominalTypeDecl>(getDecl()));
case Kind::TypeMetadataCompletionFunction:
return mangler.mangleTypeMetadataCompletionFunction(
cast<NominalTypeDecl>(getDecl()));
case Kind::TypeMetadata:
switch (getMetadataAddress()) {
case TypeMetadataAddress::FullMetadata:
return mangler.mangleTypeFullMetadataFull(getType());
case TypeMetadataAddress::AddressPoint:
return mangler.mangleTypeMetadataFull(getType());
}
llvm_unreachable("invalid metadata address");
case Kind::TypeMetadataPattern:
return mangler.mangleTypeMetadataPattern(
cast<NominalTypeDecl>(getDecl()));
case Kind::ForeignTypeMetadataCandidate:
return mangler.mangleTypeMetadataFull(getType());
case Kind::SwiftMetaclassStub:
return mangler.mangleClassMetaClass(cast<ClassDecl>(getDecl()));
case Kind::ClassMetadataBaseOffset: // class metadata base offset
return mangler.mangleClassMetadataBaseOffset(cast<ClassDecl>(getDecl()));
case Kind::NominalTypeDescriptor:
return mangler.mangleNominalTypeDescriptor(
cast<NominalTypeDecl>(getDecl()));
case Kind::PropertyDescriptor:
return mangler.manglePropertyDescriptor(
cast<AbstractStorageDecl>(getDecl()));
case Kind::ModuleDescriptor:
return mangler.mangleModuleDescriptor(cast<ModuleDecl>(getDecl()));
case Kind::ExtensionDescriptor:
return mangler.mangleExtensionDescriptor(getExtension());
case Kind::AnonymousDescriptor:
return mangler.mangleAnonymousDescriptor(getDeclContext());
case Kind::ProtocolDescriptor:
return mangler.mangleProtocolDescriptor(cast<ProtocolDecl>(getDecl()));
case Kind::ProtocolConformanceDescriptor:
return mangler.mangleProtocolConformanceDescriptor(
cast<NormalProtocolConformance>(getProtocolConformance()));
case Kind::EnumCase:
return mangler.mangleEnumCase(getDecl());
case Kind::FieldOffset:
//.........这里部分代码省略.........
示例7: create_PRUNTIME_FUNCTION
static void create_PRUNTIME_FUNCTION(uint8_t *Code, size_t Size, StringRef fnname,
uint8_t *Section, size_t Allocated, uint8_t *UnwindData)
{
DWORD mod_size = 0;
#if defined(_CPU_X86_64_)
#if !defined(USE_MCJIT)
uint8_t *catchjmp = Section+Allocated;
UnwindData = (uint8_t*)(((uintptr_t)catchjmp+12+3)&~(uintptr_t)3);
if (!catchjmp[0]) {
catchjmp[0] = 0x48;
catchjmp[1] = 0xb8; // mov RAX, QWORD PTR [...]
*(uint64_t*)(&catchjmp[2]) = (uint64_t)&_seh_exception_handler;
catchjmp[10] = 0xff;
catchjmp[11] = 0xe0; // jmp RAX
UnwindData[0] = 0x09; // version info, UNW_FLAG_EHANDLER
UnwindData[1] = 4; // size of prolog (bytes)
UnwindData[2] = 2; // count of unwind codes (slots)
UnwindData[3] = 0x05; // frame register (rbp) = rsp
UnwindData[4] = 4; // second instruction
UnwindData[5] = 0x03; // mov RBP, RSP
UnwindData[6] = 1; // first instruction
UnwindData[7] = 0x50; // push RBP
*(DWORD*)&UnwindData[8] = (DWORD)(catchjmp - Section); // relative location of catchjmp
mod_size = (DWORD)Allocated+48;
}
PRUNTIME_FUNCTION tbl = (PRUNTIME_FUNCTION)(UnwindData+12);
#else
PRUNTIME_FUNCTION tbl = (PRUNTIME_FUNCTION)malloc(sizeof(RUNTIME_FUNCTION));
#endif
tbl->BeginAddress = (DWORD)(Code - Section);
tbl->EndAddress = (DWORD)(Code - Section + Size);
tbl->UnwindData = (DWORD)(UnwindData - Section);
#else // defined(_CPU_X86_64_)
Section += (uintptr_t)Code;
mod_size = Size;
#endif
if (0) {
assert(!jl_in_stackwalk);
jl_in_stackwalk = 1;
if (mod_size && !SymLoadModuleEx(GetCurrentProcess(), NULL, NULL, NULL, (DWORD64)Section, mod_size, NULL, SLMFLAG_VIRTUAL)) {
#if defined(_CPU_X86_64_) && !defined(USE_MCJIT)
catchjmp[0] = 0;
#endif
static int warned = 0;
if (!warned) {
jl_printf(JL_STDERR, "WARNING: failed to insert module info for backtrace: %lu\n", GetLastError());
warned = 1;
}
}
else {
size_t len = fnname.size()+1;
if (len > MAX_SYM_NAME)
len = MAX_SYM_NAME;
char *name = (char*)alloca(len);
memcpy(name, fnname.data(), len-1);
name[len-1] = 0;
if (!SymAddSymbol(GetCurrentProcess(), (ULONG64)Section, name,
(DWORD64)Code, (DWORD)Size, 0)) {
jl_printf(JL_STDERR, "WARNING: failed to insert function name %s into debug info: %lu\n", name, GetLastError());
}
}
jl_in_stackwalk = 0;
}
#if defined(_CPU_X86_64_)
if (!RtlAddFunctionTable(tbl, 1, (DWORD64)Section)) {
static int warned = 0;
if (!warned) {
jl_printf(JL_STDERR, "WARNING: failed to insert function stack unwind info: %lu\n", GetLastError());
warned = 1;
}
}
#endif
}
示例8: extractValue
bool DWARFFormValue::extractValue(DataExtractor data, uint32_t *offset_ptr,
const DWARFUnit *cu) {
bool indirect = false;
bool is_block = false;
Value.data = nullptr;
// Read the value for the form into value and follow and DW_FORM_indirect
// instances we run into
do {
indirect = false;
switch (Form) {
case DW_FORM_addr:
case DW_FORM_ref_addr: {
if (!cu)
return false;
uint16_t AddrSize =
(Form == DW_FORM_addr)
? cu->getAddressByteSize()
: getRefAddrSize(cu->getAddressByteSize(), cu->getVersion());
RelocAddrMap::const_iterator AI = cu->getRelocMap()->find(*offset_ptr);
if (AI != cu->getRelocMap()->end()) {
const std::pair<uint8_t, int64_t> &R = AI->second;
Value.uval = data.getUnsigned(offset_ptr, AddrSize) + R.second;
} else
Value.uval = data.getUnsigned(offset_ptr, AddrSize);
break;
}
case DW_FORM_exprloc:
case DW_FORM_block:
Value.uval = data.getULEB128(offset_ptr);
is_block = true;
break;
case DW_FORM_block1:
Value.uval = data.getU8(offset_ptr);
is_block = true;
break;
case DW_FORM_block2:
Value.uval = data.getU16(offset_ptr);
is_block = true;
break;
case DW_FORM_block4:
Value.uval = data.getU32(offset_ptr);
is_block = true;
break;
case DW_FORM_data1:
case DW_FORM_ref1:
case DW_FORM_flag:
Value.uval = data.getU8(offset_ptr);
break;
case DW_FORM_data2:
case DW_FORM_ref2:
Value.uval = data.getU16(offset_ptr);
break;
case DW_FORM_data4:
case DW_FORM_ref4: {
Value.uval = data.getU32(offset_ptr);
if (!cu)
break;
RelocAddrMap::const_iterator AI = cu->getRelocMap()->find(*offset_ptr-4);
if (AI != cu->getRelocMap()->end())
Value.uval += AI->second.second;
break;
}
case DW_FORM_data8:
case DW_FORM_ref8:
Value.uval = data.getU64(offset_ptr);
break;
case DW_FORM_sdata:
Value.sval = data.getSLEB128(offset_ptr);
break;
case DW_FORM_strp: {
Value.uval = data.getU32(offset_ptr);
if (!cu)
break;
RelocAddrMap::const_iterator AI = cu->getRelocMap()->find(*offset_ptr-4);
if (AI != cu->getRelocMap()->end())
Value.uval += AI->second.second;
break;
}
case DW_FORM_udata:
case DW_FORM_ref_udata:
Value.uval = data.getULEB128(offset_ptr);
break;
case DW_FORM_string:
Value.cstr = data.getCStr(offset_ptr);
break;
case DW_FORM_indirect:
Form = data.getULEB128(offset_ptr);
indirect = true;
break;
case DW_FORM_sec_offset: {
// FIXME: This is 64-bit for DWARF64.
Value.uval = data.getU32(offset_ptr);
if (!cu)
break;
RelocAddrMap::const_iterator AI = cu->getRelocMap()->find(*offset_ptr-4);
if (AI != cu->getRelocMap()->end())
Value.uval += AI->second.second;
break;
}
case DW_FORM_flag_present:
//.........这里部分代码省略.........
示例9: memoryObject
//.........这里部分代码省略.........
// Stop disassembling either at the beginning of the next symbol or at
// the end of the section.
bool containsNextSym = false;
uint64_t NextSym = 0;
uint64_t NextSymIdx = SymIdx+1;
while (Symbols.size() > NextSymIdx) {
SymbolRef::Type NextSymType;
Symbols[NextSymIdx].getType(NextSymType);
if (NextSymType == SymbolRef::ST_Function) {
Sections[SectIdx].containsSymbol(Symbols[NextSymIdx],
containsNextSym);
Symbols[NextSymIdx].getAddress(NextSym);
NextSym -= SectionAddress;
break;
}
++NextSymIdx;
}
uint64_t SectSize;
Sections[SectIdx].getSize(SectSize);
uint64_t End = containsNextSym ? NextSym : SectSize;
uint64_t Size;
symbolTableWorked = true;
outs() << SymName << ":\n";
DILineInfo lastLine;
for (uint64_t Index = Start; Index < End; Index += Size) {
MCInst Inst;
uint64_t SectAddress = 0;
Sections[SectIdx].getAddress(SectAddress);
outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
// Check the data in code table here to see if this is data not an
// instruction to be disassembled.
DiceTable Dice;
Dice.push_back(std::make_pair(SectAddress + Index, DiceRef()));
dice_table_iterator DTI = std::search(Dices.begin(), Dices.end(),
Dice.begin(), Dice.end(),
compareDiceTableEntries);
if (DTI != Dices.end()){
uint16_t Length;
DTI->second.getLength(Length);
DumpBytes(StringRef(Bytes.data() + Index, Length));
uint16_t Kind;
DTI->second.getKind(Kind);
DumpDataInCode(Bytes.data() + Index, Length, Kind);
continue;
}
if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
DebugOut, nulls())) {
DumpBytes(StringRef(Bytes.data() + Index, Size));
IP->printInst(&Inst, outs(), "");
// Print debug info.
if (diContext) {
DILineInfo dli =
diContext->getLineInfoForAddress(SectAddress + Index);
// Print valid line info if it changed.
if (dli != lastLine && dli.getLine() != 0)
outs() << "\t## " << dli.getFileName() << ':'
<< dli.getLine() << ':' << dli.getColumn();
lastLine = dli;
}
outs() << "\n";
} else {
errs() << "llvm-objdump: warning: invalid instruction encoding\n";
if (Size == 0)
Size = 1; // skip illegible bytes
}
}
}
if (!symbolTableWorked) {
// Reading the symbol table didn't work, disassemble the whole section.
uint64_t SectAddress;
Sections[SectIdx].getAddress(SectAddress);
uint64_t SectSize;
Sections[SectIdx].getSize(SectSize);
uint64_t InstSize;
for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
MCInst Inst;
if (DisAsm->getInstruction(Inst, InstSize, memoryObject, Index,
DebugOut, nulls())) {
outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
DumpBytes(StringRef(Bytes.data() + Index, InstSize));
IP->printInst(&Inst, outs(), "");
outs() << "\n";
} else {
errs() << "llvm-objdump: warning: invalid instruction encoding\n";
if (InstSize == 0)
InstSize = 1; // skip illegible bytes
}
}
}
}
}
示例10: ParsePrintfSpecifier
static PrintfSpecifierResult ParsePrintfSpecifier(FormatStringHandler &H,
const char *&Beg,
const char *E,
unsigned &argIndex,
const LangOptions &LO,
const TargetInfo &Target,
bool Warn,
bool isFreeBSDKPrintf) {
using namespace clang::analyze_format_string;
using namespace clang::analyze_printf;
const char *I = Beg;
const char *Start = nullptr;
UpdateOnReturn <const char*> UpdateBeg(Beg, I);
// Look for a '%' character that indicates the start of a format specifier.
for ( ; I != E ; ++I) {
char c = *I;
if (c == '\0') {
// Detect spurious null characters, which are likely errors.
H.HandleNullChar(I);
return true;
}
if (c == '%') {
Start = I++; // Record the start of the format specifier.
break;
}
}
// No format specifier found?
if (!Start)
return false;
if (I == E) {
// No more characters left?
if (Warn)
H.HandleIncompleteSpecifier(Start, E - Start);
return true;
}
PrintfSpecifier FS;
if (ParseArgPosition(H, FS, Start, I, E))
return true;
if (I == E) {
// No more characters left?
if (Warn)
H.HandleIncompleteSpecifier(Start, E - Start);
return true;
}
if (*I == '{') {
++I;
unsigned char PrivacyFlags = 0;
StringRef MatchedStr;
do {
StringRef Str(I, E - I);
std::string Match = "^[\t\n\v\f\r ]*(private|public)[\t\n\v\f\r ]*(,|})";
llvm::Regex R(Match);
SmallVector<StringRef, 2> Matches;
if (R.match(Str, &Matches)) {
MatchedStr = Matches[1];
I += Matches[0].size();
// Set the privacy flag if the privacy annotation in the
// comma-delimited segment is at least as strict as the privacy
// annotations in previous comma-delimited segments.
if (MatchedStr.equals("private"))
PrivacyFlags = clang::analyze_os_log::OSLogBufferItem::IsPrivate;
else if (PrivacyFlags == 0 && MatchedStr.equals("public"))
PrivacyFlags = clang::analyze_os_log::OSLogBufferItem::IsPublic;
} else {
size_t CommaOrBracePos =
Str.find_if([](char c) { return c == ',' || c == '}'; });
if (CommaOrBracePos == StringRef::npos) {
// Neither a comma nor the closing brace was found.
if (Warn)
H.HandleIncompleteSpecifier(Start, E - Start);
return true;
}
I += CommaOrBracePos + 1;
}
// Continue until the closing brace is found.
} while (*(I - 1) == ',');
// Set the privacy flag.
switch (PrivacyFlags) {
case 0:
break;
case clang::analyze_os_log::OSLogBufferItem::IsPrivate:
FS.setIsPrivate(MatchedStr.data());
break;
case clang::analyze_os_log::OSLogBufferItem::IsPublic:
FS.setIsPublic(MatchedStr.data());
break;
//.........这里部分代码省略.........
示例11: GetDwarfFile
/// GetDwarfFile - takes a file name an number to place in the dwarf file and
/// directory tables. If the file number has already been allocated it is an
/// error and zero is returned and the client reports the error, else the
/// allocated file number is returned. The file numbers may be in any order.
unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
unsigned FileNumber, unsigned CUID) {
// TODO: a FileNumber of zero says to use the next available file number.
// Note: in GenericAsmParser::ParseDirectiveFile() FileNumber was checked
// to not be less than one. This needs to be change to be not less than zero.
SmallVectorImpl<MCDwarfFile *>& MCDwarfFiles = MCDwarfFilesCUMap[CUID];
SmallVectorImpl<StringRef>& MCDwarfDirs = MCDwarfDirsCUMap[CUID];
// Make space for this FileNumber in the MCDwarfFiles vector if needed.
if (FileNumber >= MCDwarfFiles.size()) {
MCDwarfFiles.resize(FileNumber + 1);
} else {
MCDwarfFile *&ExistingFile = MCDwarfFiles[FileNumber];
if (ExistingFile)
// It is an error to use see the same number more than once.
return 0;
}
// Get the new MCDwarfFile slot for this FileNumber.
MCDwarfFile *&File = MCDwarfFiles[FileNumber];
if (Directory.empty()) {
// Separate the directory part from the basename of the FileName.
StringRef tFileName = sys::path::filename(FileName);
if (!tFileName.empty()) {
Directory = sys::path::parent_path(FileName);
if (!Directory.empty())
FileName = tFileName;
}
}
// Find or make a entry in the MCDwarfDirs vector for this Directory.
// Capture directory name.
unsigned DirIndex;
if (Directory.empty()) {
// For FileNames with no directories a DirIndex of 0 is used.
DirIndex = 0;
} else {
DirIndex = 0;
for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
if (Directory == MCDwarfDirs[DirIndex])
break;
}
if (DirIndex >= MCDwarfDirs.size()) {
char *Buf = static_cast<char *>(Allocate(Directory.size()));
memcpy(Buf, Directory.data(), Directory.size());
MCDwarfDirs.push_back(StringRef(Buf, Directory.size()));
}
// The DirIndex is one based, as DirIndex of 0 is used for FileNames with
// no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
// directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
// are stored at MCDwarfFiles[FileNumber].Name .
DirIndex++;
}
// Now make the MCDwarfFile entry and place it in the slot in the MCDwarfFiles
// vector.
char *Buf = static_cast<char *>(Allocate(FileName.size()));
memcpy(Buf, FileName.data(), FileName.size());
File = new (*this) MCDwarfFile(StringRef(Buf, FileName.size()), DirIndex);
// return the allocated FileNumber.
return FileNumber;
}
示例12: LLVMRustGetHostCPUName
extern "C" const char* LLVMRustGetHostCPUName(size_t *len) {
StringRef Name = sys::getHostCPUName();
*len = Name.size();
return Name.data();
}
示例13: copyString
StringRef StringScratchSpace::copyString(StringRef string) {
void *memory = Allocator.Allocate(string.size(), alignof(char));
memcpy(memory, string.data(), string.size());
return StringRef(static_cast<char *>(memory), string.size());
}
示例14: omitNeedlessWords
bool swift::omitNeedlessWords(StringRef &baseName,
MutableArrayRef<StringRef> argNames,
StringRef firstParamName,
OmissionTypeName resultType,
OmissionTypeName contextType,
ArrayRef<OmissionTypeName> paramTypes,
bool returnsSelf,
bool isProperty,
const InheritedNameSet *allPropertyNames,
StringScratchSpace &scratch) {
bool anyChanges = false;
/// Local function that lowercases all of the base names and
/// argument names before returning.
auto lowercaseAcronymsForReturn = [&] {
StringRef newBaseName = toLowercaseInitialisms(baseName, scratch);
if (baseName.data() != newBaseName.data()) {
baseName = newBaseName;
anyChanges = true;
}
for (StringRef &argName : argNames) {
StringRef newArgName = toLowercaseInitialisms(argName, scratch);
if (argName.data() != newArgName.data()) {
argName = newArgName;
anyChanges = true;
}
}
return anyChanges;
};
// If the result type matches the context, remove the context type from the
// prefix of the name.
bool resultTypeMatchesContext = returnsSelf || (resultType == contextType);
if (resultTypeMatchesContext) {
StringRef newBaseName = omitNeedlessWordsFromPrefix(baseName, contextType,
scratch);
if (newBaseName != baseName) {
baseName = newBaseName;
anyChanges = true;
}
}
// Strip the context type from the base name of a method.
if (!isProperty) {
StringRef newBaseName = ::omitNeedlessWords(baseName, contextType,
NameRole::BaseNameSelf,
allPropertyNames, scratch);
if (newBaseName != baseName) {
baseName = newBaseName;
anyChanges = true;
}
}
if (paramTypes.empty()) {
if (resultTypeMatchesContext) {
StringRef newBaseName = ::omitNeedlessWords(
baseName,
returnsSelf ? contextType : resultType,
NameRole::Property,
allPropertyNames,
scratch);
if (newBaseName != baseName) {
baseName = newBaseName;
anyChanges = true;
}
}
return lowercaseAcronymsForReturn();
}
if (camel_case::getFirstWord(baseName) == "set") {
StringRef newBaseName = ::omitNeedlessWords(
baseName,
contextType,
NameRole::Property,
allPropertyNames,
scratch);
if (newBaseName != baseName) {
baseName = newBaseName;
anyChanges = true;
}
}
// If needed, split the base name.
if (!argNames.empty() &&
splitBaseName(baseName, argNames[0], paramTypes[0], firstParamName))
anyChanges = true;
// Omit needless words based on parameter types.
for (unsigned i = 0, n = argNames.size(); i != n; ++i) {
// If there is no corresponding parameter, there is nothing to
// omit.
if (i >= paramTypes.size()) continue;
// Omit needless words based on the type of the parameter.
NameRole role = i > 0 ? NameRole::SubsequentParameter
: argNames[0].empty() ? NameRole::BaseName
: baseName == "init" ? NameRole::SubsequentParameter
//.........这里部分代码省略.........
示例15: emitSection
unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
const SectionRef &Section, bool IsCode) {
StringRef data;
uint64_t Alignment64;
Check(Section.getContents(data));
Check(Section.getAlignment(Alignment64));
unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
bool IsRequired;
bool IsVirtual;
bool IsZeroInit;
bool IsReadOnly;
uint64_t DataSize;
unsigned PaddingSize = 0;
unsigned StubBufSize = 0;
StringRef Name;
Check(Section.isRequiredForExecution(IsRequired));
Check(Section.isVirtual(IsVirtual));
Check(Section.isZeroInit(IsZeroInit));
Check(Section.isReadOnlyData(IsReadOnly));
Check(Section.getSize(DataSize));
Check(Section.getName(Name));
StubBufSize = computeSectionStubBufSize(Obj, Section);
// The .eh_frame section (at least on Linux) needs an extra four bytes padded
// with zeroes added at the end. For MachO objects, this section has a
// slightly different name, so this won't have any effect for MachO objects.
if (Name == ".eh_frame")
PaddingSize = 4;
uintptr_t Allocate;
unsigned SectionID = Sections.size();
uint8_t *Addr;
const char *pData = 0;
// Some sections, such as debug info, don't need to be loaded for execution.
// Leave those where they are.
if (IsRequired) {
Allocate = DataSize + PaddingSize + StubBufSize;
Addr = IsCode ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID,
Name)
: MemMgr->allocateDataSection(Allocate, Alignment, SectionID,
Name, IsReadOnly);
if (!Addr)
report_fatal_error("Unable to allocate section memory!");
// Virtual sections have no data in the object image, so leave pData = 0
if (!IsVirtual)
pData = data.data();
// Zero-initialize or copy the data from the image
if (IsZeroInit || IsVirtual)
memset(Addr, 0, DataSize);
else
memcpy(Addr, pData, DataSize);
// Fill in any extra bytes we allocated for padding
if (PaddingSize != 0) {
memset(Addr + DataSize, 0, PaddingSize);
// Update the DataSize variable so that the stub offset is set correctly.
DataSize += PaddingSize;
}
DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
<< " obj addr: " << format("%p", pData)
<< " new addr: " << format("%p", Addr)
<< " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
<< " Allocate: " << Allocate << "\n");
Obj.updateSectionAddress(Section, (uint64_t)Addr);
} else {
// Even if we didn't load the section, we need to record an entry for it
// to handle later processing (and by 'handle' I mean don't do anything
// with these sections).
Allocate = 0;
Addr = 0;
DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
<< " obj addr: " << format("%p", data.data()) << " new addr: 0"
<< " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
<< " Allocate: " << Allocate << "\n");
}
Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
return SectionID;
}