std::unique_ptr<Directive> Directive::create(bool RegexKind,
                                             SourceLocation DirectiveLoc,
                                             SourceLocation DiagnosticLoc,
                                             bool MatchAnyLine, StringRef Text,
                                             unsigned Min, unsigned Max) {
  if (!RegexKind)
    return llvm::make_unique<StandardDirective>(DirectiveLoc, DiagnosticLoc,
                                                MatchAnyLine, Text, Min, Max);

  // Parse the directive into a regular expression.
  std::string RegexStr;
  StringRef S = Text;
  while (!S.empty()) {
    if (S.startswith("{{")) {
      S = S.drop_front(2);
      size_t RegexMatchLength = S.find("}}");
      assert(RegexMatchLength != StringRef::npos);
      // Append the regex, enclosed in parentheses.
      RegexStr += "(";
      RegexStr.append(S.data(), RegexMatchLength);
      RegexStr += ")";
      S = S.drop_front(RegexMatchLength + 2);
    } else {
      size_t VerbatimMatchLength = S.find("{{");
      if (VerbatimMatchLength == StringRef::npos)
        VerbatimMatchLength = S.size();
      // Escape and append the fixed string.
      RegexStr += llvm::Regex::escape(S.substr(0, VerbatimMatchLength));
      S = S.drop_front(VerbatimMatchLength);
    }
  }

  return llvm::make_unique<RegexDirective>(
      DirectiveLoc, DiagnosticLoc, MatchAnyLine, Text, Min, Max, RegexStr);
}
Example #2
0
ErrorOr<StringRef> ELFLinkingContext::searchLibrary(StringRef libName) const {
    bool hasColonPrefix = libName[0] == ':';
    SmallString<128> path;
    for (StringRef dir : _inputSearchPaths) {
        // Search for dynamic library
        if (!_isStaticExecutable) {
            buildSearchPath(path, dir, _sysrootPath);
            llvm::sys::path::append(path, hasColonPrefix
                                    ? libName.drop_front()
                                    : Twine("lib", libName) + ".so");
            if (exists(path.str()))
                return path.str().copy(_allocator);
        }
        // Search for static libraries too
        buildSearchPath(path, dir, _sysrootPath);
        llvm::sys::path::append(path, hasColonPrefix
                                ? libName.drop_front()
                                : Twine("lib", libName) + ".a");
        if (exists(path.str()))
            return path.str().copy(_allocator);
    }
    if (hasColonPrefix && exists(libName.drop_front()))
        return libName.drop_front();

    return make_error_code(llvm::errc::no_such_file_or_directory);
}
Example #3
0
Optional<ReplacementItem>
formatv_object_base::parseReplacementItem(StringRef Spec) {
  StringRef RepString = Spec.trim("{}");

  // If the replacement sequence does not start with a non-negative integer,
  // this is an error.
  char Pad = ' ';
  std::size_t Align = 0;
  AlignStyle Where = AlignStyle::Right;
  StringRef Options;
  size_t Index = 0;
  RepString = RepString.trim();
  if (RepString.consumeInteger(0, Index)) {
    assert(false && "Invalid replacement sequence index!");
    return ReplacementItem{};
  }
  RepString = RepString.trim();
  if (!RepString.empty() && RepString.front() == ',') {
    RepString = RepString.drop_front();
    if (!consumeFieldLayout(RepString, Where, Align, Pad))
      assert(false && "Invalid replacement field layout specification!");
  }
  RepString = RepString.trim();
  if (!RepString.empty() && RepString.front() == ':') {
    Options = RepString.drop_front().trim();
    RepString = StringRef();
  }
  RepString = RepString.trim();
  if (!RepString.empty()) {
    assert(false && "Unexpected characters found in replacement string!");
  }

  return ReplacementItem{Spec, Index, Align, Where, Pad, Options};
}
Example #4
0
bool formatv_object_base::consumeFieldLayout(StringRef &Spec, AlignStyle &Where,
                                             size_t &Align, char &Pad) {
  Where = AlignStyle::Right;
  Align = 0;
  Pad = ' ';
  if (Spec.empty())
    return true;

  if (Spec.size() > 1) {
    // A maximum of 2 characters at the beginning can be used for something
    // other
    // than the width.
    // If Spec[1] is a loc char, then Spec[0] is a pad char and Spec[2:...]
    // contains the width.
    // Otherwise, if Spec[0] is a loc char, then Spec[1:...] contains the width.
    // Otherwise, Spec[0:...] contains the width.
    if (auto Loc = translateLocChar(Spec[1])) {
      Pad = Spec[0];
      Where = *Loc;
      Spec = Spec.drop_front(2);
    } else if (auto Loc = translateLocChar(Spec[0])) {
      Where = *Loc;
      Spec = Spec.drop_front(1);
    }
  }

  bool Failed = Spec.consumeInteger(0, Align);
  return !Failed;
}
Example #5
0
std::pair<ReplacementItem, StringRef>
formatv_object_base::splitLiteralAndReplacement(StringRef Fmt) {
  std::size_t From = 0;
  while (From < Fmt.size() && From != StringRef::npos) {
    std::size_t BO = Fmt.find_first_of('{', From);
    // Everything up until the first brace is a literal.
    if (BO != 0)
      return std::make_pair(ReplacementItem{Fmt.substr(0, BO)}, Fmt.substr(BO));

    StringRef Braces =
        Fmt.drop_front(BO).take_while([](char C) { return C == '{'; });
    // If there is more than one brace, then some of them are escaped.  Treat
    // these as replacements.
    if (Braces.size() > 1) {
      size_t NumEscapedBraces = Braces.size() / 2;
      StringRef Middle = Fmt.substr(BO, NumEscapedBraces);
      StringRef Right = Fmt.drop_front(BO + NumEscapedBraces * 2);
      return std::make_pair(ReplacementItem{Middle}, Right);
    }
    // An unterminated open brace is undefined.  We treat the rest of the string
    // as a literal replacement, but we assert to indicate that this is
    // undefined and that we consider it an error.
    std::size_t BC = Fmt.find_first_of('}', BO);
    if (BC == StringRef::npos) {
      assert(
          false &&
          "Unterminated brace sequence.  Escape with {{ for a literal brace.");
      return std::make_pair(ReplacementItem{Fmt}, StringRef());
    }

    // Even if there is a closing brace, if there is another open brace before
    // this closing brace, treat this portion as literal, and try again with the
    // next one.
    std::size_t BO2 = Fmt.find_first_of('{', BO + 1);
    if (BO2 < BC)
      return std::make_pair(ReplacementItem{Fmt.substr(0, BO2)},
                            Fmt.substr(BO2));

    StringRef Spec = Fmt.slice(BO + 1, BC);
    StringRef Right = Fmt.substr(BC + 1);

    auto RI = parseReplacementItem(Spec);
    if (RI.hasValue())
      return std::make_pair(*RI, Right);

    // If there was an error parsing the replacement item, treat it as an
    // invalid replacement spec, and just continue.
    From = BC + 1;
  }
  return std::make_pair(ReplacementItem{Fmt}, StringRef());
}
Example #6
0
bool llvm::consumeSignedInteger(StringRef &Str, unsigned Radix,
                                long long &Result) {
  unsigned long long ULLVal;

  // Handle positive strings first.
  if (Str.empty() || Str.front() != '-') {
    if (consumeUnsignedInteger(Str, Radix, ULLVal) ||
        // Check for value so large it overflows a signed value.
        (long long)ULLVal < 0)
      return true;
    Result = ULLVal;
    return false;
  }

  // Get the positive part of the value.
  StringRef Str2 = Str.drop_front(1);
  if (consumeUnsignedInteger(Str2, Radix, ULLVal) ||
      // Reject values so large they'd overflow as negative signed, but allow
      // "-0".  This negates the unsigned so that the negative isn't undefined
      // on signed overflow.
      (long long)-ULLVal > 0)
    return true;

  Str = Str2;
  Result = -ULLVal;
  return false;
}
Example #7
0
void printSymbolVersionDefinition(const typename ELFT::Shdr &Shdr,
                                  ArrayRef<uint8_t> Contents,
                                  StringRef StrTab) {
  outs() << "Version definitions:\n";

  const uint8_t *Buf = Contents.data();
  uint32_t VerdefIndex = 1;
  // sh_info contains the number of entries in the SHT_GNU_verdef section. To
  // make the index column have consistent width, we should insert blank spaces
  // according to sh_info.
  uint16_t VerdefIndexWidth = std::to_string(Shdr.sh_info).size();
  while (Buf) {
    auto *Verdef = reinterpret_cast<const typename ELFT::Verdef *>(Buf);
    outs() << format_decimal(VerdefIndex++, VerdefIndexWidth) << " "
           << format("0x%02" PRIx16 " ", (uint16_t)Verdef->vd_flags)
           << format("0x%08" PRIx32 " ", (uint32_t)Verdef->vd_hash);

    const uint8_t *BufAux = Buf + Verdef->vd_aux;
    uint16_t VerdauxIndex = 0;
    while (BufAux) {
      auto *Verdaux = reinterpret_cast<const typename ELFT::Verdaux *>(BufAux);
      if (VerdauxIndex)
        outs() << std::string(VerdefIndexWidth + 17, ' ');
      outs() << StringRef(StrTab.drop_front(Verdaux->vda_name).data()) << '\n';
      BufAux = Verdaux->vda_next ? BufAux + Verdaux->vda_next : nullptr;
      ++VerdauxIndex;
    }
    Buf = Verdef->vd_next ? Buf + Verdef->vd_next : nullptr;
  }
}
static bool matchesStyle(StringRef Name,
                         IdentifierNamingCheck::NamingStyle Style) {
  static llvm::Regex Matchers[] = {
      llvm::Regex("^.*$"),
      llvm::Regex("^[a-z][a-z0-9_]*$"),
      llvm::Regex("^[a-z][a-zA-Z0-9]*$"),
      llvm::Regex("^[A-Z][A-Z0-9_]*$"),
      llvm::Regex("^[A-Z][a-zA-Z0-9]*$"),
      llvm::Regex("^[A-Z]([a-z0-9]*(_[A-Z])?)*"),
      llvm::Regex("^[a-z]([a-z0-9]*(_[A-Z])?)*"),
  };

  bool Matches = true;
  if (Name.startswith(Style.Prefix))
    Name = Name.drop_front(Style.Prefix.size());
  else
    Matches = false;

  if (Name.endswith(Style.Suffix))
    Name = Name.drop_back(Style.Suffix.size());
  else
    Matches = false;

  // Ensure the name doesn't have any extra underscores beyond those specified
  // in the prefix and suffix.
  if (Name.startswith("_") || Name.endswith("_"))
    Matches = false;

  if (Style.Case && !Matchers[static_cast<size_t>(*Style.Case)].match(Name))
    Matches = false;

  return Matches;
}
Example #9
0
void X86AsmPrinter::GenerateExportDirective(const MCSymbol *Sym, bool IsData) {
  SmallString<128> Directive;
  raw_svector_ostream OS(Directive);
  StringRef Name = Sym->getName();
  const Triple &TT = TM.getTargetTriple();

  if (TT.isKnownWindowsMSVCEnvironment())
    OS << " /EXPORT:";
  else
    OS << " -export:";

  if ((TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) &&
      (Name[0] == getDataLayout().getGlobalPrefix()))
    Name = Name.drop_front();

  OS << Name;

  if (IsData) {
    if (TT.isKnownWindowsMSVCEnvironment())
      OS << ",DATA";
    else
      OS << ",data";
  }

  OS.flush();
  OutStreamer->EmitBytes(Directive);
}
static bool matchesStyle(StringRef Name,
                         IdentifierNamingCheck::NamingStyle Style) {
  static llvm::Regex Matchers[] = {
      llvm::Regex("^.*$"),
      llvm::Regex("^[a-z][a-z0-9_]*$"),
      llvm::Regex("^[a-z][a-zA-Z0-9]*$"),
      llvm::Regex("^[A-Z][A-Z0-9_]*$"),
      llvm::Regex("^[A-Z][a-zA-Z0-9]*$"),
      llvm::Regex("^[A-Z]([a-z0-9]*(_[A-Z])?)*"),
      llvm::Regex("^[a-z]([a-z0-9]*(_[A-Z])?)*"),
  };

  bool Matches = true;
  if (Name.startswith(Style.Prefix))
    Name = Name.drop_front(Style.Prefix.size());
  else
    Matches = false;

  if (Name.endswith(Style.Suffix))
    Name = Name.drop_back(Style.Suffix.size());
  else
    Matches = false;

  if (!Matchers[static_cast<size_t>(Style.Case)].match(Name))
    Matches = false;

  return Matches;
}
Example #11
0
void X86AsmPrinter::GenerateExportDirective(const MCSymbol *Sym, bool IsData) {
  SmallString<128> Directive;
  raw_svector_ostream OS(Directive);
  StringRef Name = Sym->getName();

  if (Subtarget->isTargetKnownWindowsMSVC())
    OS << " /EXPORT:";
  else
    OS << " -export:";

  if ((Subtarget->isTargetWindowsGNU() || Subtarget->isTargetWindowsCygwin()) &&
      (Name[0] == getDataLayout().getGlobalPrefix()))
    Name = Name.drop_front();

  OS << Name;

  if (IsData) {
    if (Subtarget->isTargetKnownWindowsMSVC())
      OS << ",DATA";
    else
      OS << ",data";
  }

  OS.flush();
  OutStreamer.EmitBytes(Directive);
}
Example #12
0
static Check::CheckType FindCheckType(StringRef Buffer, StringRef Prefix) {
  char NextChar = Buffer[Prefix.size()];

  // Verify that the : is present after the prefix.
  if (NextChar == ':')
    return Check::CheckPlain;

  if (NextChar != '-')
    return Check::CheckNone;

  StringRef Rest = Buffer.drop_front(Prefix.size() + 1);
  if (Rest.startswith("NEXT:"))
    return Check::CheckNext;

  if (Rest.startswith("SAME:"))
    return Check::CheckSame;

  if (Rest.startswith("NOT:"))
    return Check::CheckNot;

  if (Rest.startswith("DAG:"))
    return Check::CheckDAG;

  if (Rest.startswith("LABEL:"))
    return Check::CheckLabel;

  return Check::CheckNone;
}
Example #13
0
IAMResult IAMInference::inferVar(const clang::VarDecl *varDecl) {
  auto fail = [varDecl]() -> IAMResult {
    DEBUG(llvm::dbgs() << "failed to infer variable: ");
    DEBUG(varDecl->print(llvm::dbgs()));
    DEBUG(llvm::dbgs() << "\n");
    ++FailInferVar;
    return {};
  };

  // Try to find a type to add this as a static property to
  StringRef workingName = varDecl->getName();
  if (workingName.empty())
    return fail();

  // Special pattern: constants of the form "kFooBarBaz", extend "FooBar" with
  // property "Baz"
  if (*camel_case::getWords(workingName).begin() == "k")
    workingName = workingName.drop_front(1);

  NameBuffer remainingName;
  if (auto effectiveDC = findTypeAndMatch(workingName, remainingName))

    return importAsStaticProperty(remainingName, effectiveDC);

  return fail();
}
Example #14
0
void ModuleInfo::addSymbol(const SymbolRef &Symbol) {
  SymbolRef::Type SymbolType;
  if (error(Symbol.getType(SymbolType)))
    return;
  if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
    return;
  uint64_t SymbolAddress;
  if (error(Symbol.getAddress(SymbolAddress)) ||
      SymbolAddress == UnknownAddressOrSize)
    return;
  uint64_t SymbolSize;
  // Getting symbol size is linear for Mach-O files, so assume that symbol
  // occupies the memory range up to the following symbol.
  if (isa<MachOObjectFile>(Module))
    SymbolSize = 0;
  else if (error(Symbol.getSize(SymbolSize)) ||
           SymbolSize == UnknownAddressOrSize)
    return;
  StringRef SymbolName;
  if (error(Symbol.getName(SymbolName)))
    return;
  // Mach-O symbol table names have leading underscore, skip it.
  if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
    SymbolName = SymbolName.drop_front();
  // FIXME: If a function has alias, there are two entries in symbol table
  // with same address size. Make sure we choose the correct one.
  SymbolMapTy &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
  SymbolDesc SD = { SymbolAddress, SymbolSize };
  M.insert(std::make_pair(SD, SymbolName));
}
Example #15
0
static bool stripPrefix(StringRef &string, const char (&data)[N]) {
  constexpr size_t prefixLength = N - 1;
  if (!string.startswith(StringRef(data, prefixLength)))
    return false;
  string = string.drop_front(prefixLength);
  return true;
}
Example #16
0
// Try to find the first match in buffer for any prefix. If a valid match is
// found, return that prefix and set its type and location.  If there are almost
// matches (e.g. the actual prefix string is found, but is not an actual check
// string), but no valid match, return an empty string and set the position to
// resume searching from. If no partial matches are found, return an empty
// string and the location will be StringRef::npos. If one prefix is a substring
// of another, the maximal match should be found. e.g. if "A" and "AA" are
// prefixes then AA-CHECK: should match the second one.
static StringRef FindFirstCandidateMatch(StringRef &Buffer,
                                         Check::CheckType &CheckTy,
                                         size_t &CheckLoc) {
  StringRef FirstPrefix;
  size_t FirstLoc = StringRef::npos;
  size_t SearchLoc = StringRef::npos;
  Check::CheckType FirstTy = Check::CheckNone;

  CheckTy = Check::CheckNone;
  CheckLoc = StringRef::npos;

  for (prefix_iterator I = CheckPrefixes.begin(), E = CheckPrefixes.end();
       I != E; ++I) {
    StringRef Prefix(*I);
    size_t PrefixLoc = Buffer.find(Prefix);

    if (PrefixLoc == StringRef::npos)
      continue;

    // Track where we are searching for invalid prefixes that look almost right.
    // We need to only advance to the first partial match on the next attempt
    // since a partial match could be a substring of a later, valid prefix.
    // Need to skip to the end of the word, otherwise we could end up
    // matching a prefix in a substring later.
    if (PrefixLoc < SearchLoc)
      SearchLoc = SkipWord(Buffer, PrefixLoc);

    // We only want to find the first match to avoid skipping some.
    if (PrefixLoc > FirstLoc)
      continue;
    // If one matching check-prefix is a prefix of another, choose the
    // longer one.
    if (PrefixLoc == FirstLoc && Prefix.size() < FirstPrefix.size())
      continue;

    StringRef Rest = Buffer.drop_front(PrefixLoc);
    // Make sure we have actually found the prefix, and not a word containing
    // it. This should also prevent matching the wrong prefix when one is a
    // substring of another.
    if (PrefixLoc != 0 && IsPartOfWord(Buffer[PrefixLoc - 1]))
      FirstTy = Check::CheckNone;
    else
      FirstTy = FindCheckType(Rest, Prefix);

    FirstLoc = PrefixLoc;
    FirstPrefix = Prefix;
  }

  // If the first prefix is invalid, we should continue the search after it.
  if (FirstTy == Check::CheckNone) {
    CheckLoc = SearchLoc;
    return "";
  }

  CheckTy = FirstTy;
  CheckLoc = FirstLoc;
  return FirstPrefix;
}
/// Get the function name from the record, removing the filename prefix if
/// necessary.
static StringRef getFuncNameWithoutPrefix(const CoverageMappingRecord &Record) {
  StringRef FunctionName = Record.FunctionName;
  if (Record.Filenames.empty())
    return FunctionName;
  StringRef Filename = sys::path::filename(Record.Filenames[0]);
  if (FunctionName.startswith(Filename))
    FunctionName = FunctionName.drop_front(Filename.size() + 1);
  return FunctionName;
}
Example #18
0
size_t StringRef::find_lower(StringRef Str, size_t From) const {
  StringRef This = substr(From);
  while (This.size() >= Str.size()) {
    if (This.startswith_lower(Str))
      return From;
    This = This.drop_front();
    ++From;
  }
  return npos;
}
Example #19
0
ID types::lookupTypeForExtension(StringRef Ext) {
  if (Ext.empty())
    return TY_INVALID;
  assert(Ext.front() == '.' && "not a file extension");
  return llvm::StringSwitch<types::ID>(Ext.drop_front())
#define TYPE(NAME, ID, SUFFIX, FLAGS) \
           .Case(SUFFIX, TY_##ID)
#include "swift/Driver/Types.def"
           .Default(TY_INVALID);
}
Example #20
0
bool HSAILELFMCAsmInfo::isValidUnquotedName(StringRef Name) const {
  char First = Name.front();
  assert((First == '%' || First == '&' || First == '@') &&
         "Missing valid prefix character");
  Name = Name.drop_front(1);

  if (!Name.empty()) {
    if (!isValidFirstChar(Name.front()))
      return false;

    Name = Name.drop_front();
  }

  for (char C : Name) {
    if (!isValidChar(C))
      return false;
  }

  return true;
}
void ELFObjectWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
                                       const MCAsmLayout &Layout) {
  MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
  StringRef SectionName = Section.getSectionName();

  auto &MC = Asm.getContext();
  const auto &MAI = MC.getAsmInfo();

  // Compressing debug_frame requires handling alignment fragments which is
  // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
  // for writing to arbitrary buffers) for little benefit.
  bool CompressionEnabled =
      MAI->compressDebugSections() != DebugCompressionType::None;
  if (!CompressionEnabled || !SectionName.startswith(".debug_") ||
      SectionName == ".debug_frame") {
    Asm.writeSectionData(&Section, Layout);
    return;
  }

  assert((MAI->compressDebugSections() == DebugCompressionType::Z ||
          MAI->compressDebugSections() == DebugCompressionType::GNU) &&
         "expected zlib or zlib-gnu style compression");

  SmallVector<char, 128> UncompressedData;
  raw_svector_ostream VecOS(UncompressedData);
  raw_pwrite_stream &OldStream = getStream();
  setStream(VecOS);
  Asm.writeSectionData(&Section, Layout);
  setStream(OldStream);

  SmallVector<char, 128> CompressedContents;
  if (Error E = zlib::compress(
          StringRef(UncompressedData.data(), UncompressedData.size()),
          CompressedContents)) {
    consumeError(std::move(E));
    getStream() << UncompressedData;
    return;
  }

  bool ZlibStyle = MAI->compressDebugSections() == DebugCompressionType::Z;
  if (!maybeWriteCompression(UncompressedData.size(), CompressedContents,
                             ZlibStyle, Sec.getAlignment())) {
    getStream() << UncompressedData;
    return;
  }

  if (ZlibStyle)
    // Set the compressed flag. That is zlib style.
    Section.setFlags(Section.getFlags() | ELF::SHF_COMPRESSED);
  else
    // Add "z" prefix to section name. This is zlib-gnu style.
    MC.renameELFSection(&Section, (".z" + SectionName.drop_front(1)).str());
  getStream() << CompressedContents;
}
Example #22
0
Optional<EditorPlaceholderData>
swift::parseEditorPlaceholder(StringRef PlaceholderText) {
  if (!PlaceholderText.startswith("<#") ||
      !PlaceholderText.endswith("#>"))
    return None;

  PlaceholderText = PlaceholderText.drop_front(2).drop_back(2);
  EditorPlaceholderData PHDataBasic;
  PHDataBasic.Kind = EditorPlaceholderKind::Basic;
  PHDataBasic.Display = PlaceholderText;

  if (!PlaceholderText.startswith("T##")) {
    // Basic.
    return PHDataBasic;
  }

  // Typed.
  EditorPlaceholderData PHDataTyped;
  PHDataTyped.Kind = EditorPlaceholderKind::Typed;

  assert(PlaceholderText.startswith("T##"));
  PlaceholderText = PlaceholderText.drop_front(3);
  size_t Pos = PlaceholderText.find("##");
  if (Pos == StringRef::npos) {
    PHDataTyped.Display = PHDataTyped.Type = PHDataTyped.TypeForExpansion =
      PlaceholderText;
    return PHDataTyped;
  }
  PHDataTyped.Display = PlaceholderText.substr(0, Pos);

  PlaceholderText = PlaceholderText.substr(Pos+2);
  Pos = PlaceholderText.find("##");
  if (Pos == StringRef::npos) {
    PHDataTyped.Type = PHDataTyped.TypeForExpansion = PlaceholderText;
  } else {
    PHDataTyped.Type = PlaceholderText.substr(0, Pos);
    PHDataTyped.TypeForExpansion = PlaceholderText.substr(Pos+2);
  }

  return PHDataTyped;
}
Example #23
0
void CommentASTToXMLConverter::appendToResultWithCDATAEscaping(StringRef S) {
  if (S.empty())
    return;

  Result << "<![CDATA[";
  while (!S.empty()) {
    size_t Pos = S.find("]]>");
    if (Pos == 0) {
      Result << "]]]]><![CDATA[>";
      S = S.drop_front(3);
      continue;
    }
    if (Pos == StringRef::npos)
      Pos = S.size();

    Result << S.substr(0, Pos);

    S = S.drop_front(Pos);
  }
  Result << "]]>";
}
Example #24
0
void ArrayOrderPass::perform(std::unique_ptr<MutableFile> &f) {
  auto definedAtoms = f->definedAtoms();

  // Move sections need to be sorted into the separate continious group.
  // That reduces a number of sorting elements and simplifies conditions
  // in the sorting predicate.
  auto last = std::stable_partition(definedAtoms.begin(), definedAtoms.end(),
                                    [](const DefinedAtom *atom) {
    if (atom->sectionChoice() != DefinedAtom::sectionCustomRequired)
      return false;

    StringRef name = atom->customSectionName();
    return name.startswith(".init_array") || name.startswith(".fini_array");
  });

  std::stable_sort(definedAtoms.begin(), last,
                   [](const DefinedAtom *left, const DefinedAtom *right) {
    StringRef leftSec = left->customSectionName();
    StringRef rightSec = right->customSectionName();

    // Drop the front dot from the section name and get
    // an optional section's number starting after the second dot.
    StringRef leftNum = leftSec.drop_front().rsplit('.').second;
    StringRef rightNum = rightSec.drop_front().rsplit('.').second;

    // Sort {.init_array, .fini_array}[.<num>] sections
    // according to their number. Sections without optional
    // numer suffix should go last.

    uint32_t leftPriority = std::numeric_limits<uint32_t>::max();
    if (!leftNum.empty())
      leftNum.getAsInteger(10, leftPriority);

    uint32_t rightPriority = std::numeric_limits<uint32_t>::max();
    if (!rightNum.empty())
      rightNum.getAsInteger(10, rightPriority);

    return leftPriority < rightPriority;
  });
}
static std::string
fixupWithStyle(StringRef Name,
               const IdentifierNamingCheck::NamingStyle &Style) {
  if (Name.find('_') != StringRef::npos && Name.startswith(Style.Prefix))
    Name = Name.drop_front(Style.Prefix.size());

  const std::string Fixed = fixupWithCase(
      Name, Style.Case.getValueOr(IdentifierNamingCheck::CaseType::CT_AnyCase));
  StringRef Mid = StringRef(Fixed).trim("_");
  if (Mid.empty())
    Mid = "_";
  return (Style.Prefix + Mid + Style.Suffix).str();
}
Example #26
0
void
swift::trimLeadingWhitespaceFromLines(StringRef RawText,
                                      unsigned WhitespaceToTrim,
                                      SmallVectorImpl<StringRef> &OutLines) {
  SmallVector<StringRef, 8> Lines;

  bool IsFirstLine = true;

  while (!RawText.empty()) {
    size_t Pos = RawText.find_first_of("\n\r");
    if (Pos == StringRef::npos)
      Pos = RawText.size();

    StringRef Line = RawText.substr(0, Pos);
    Lines.push_back(Line);
    if (!IsFirstLine) {
      size_t NonWhitespacePos = RawText.find_first_not_of(' ');
      if (NonWhitespacePos != StringRef::npos)
        WhitespaceToTrim =
            std::min(WhitespaceToTrim,
                     static_cast<unsigned>(NonWhitespacePos));
    }
    IsFirstLine = false;

    RawText = RawText.drop_front(Pos);
    unsigned NewlineBytes = measureNewline(RawText);
    RawText = RawText.drop_front(NewlineBytes);
  }

  IsFirstLine = true;
  for (auto &Line : Lines) {
    if (!IsFirstLine) {
      Line = Line.drop_front(WhitespaceToTrim);
    }
    IsFirstLine = false;
  }

  OutLines.append(Lines.begin(), Lines.end());
}
Example #27
0
Error loadNaiveFormatLog(StringRef Data, XRayFileHeader &FileHeader,
                         std::vector<XRayRecord> &Records) {
  // Check that there is at least a header
  if (Data.size() < 32)
    return make_error<StringError>(
        "Not enough bytes for an XRay log.",
        std::make_error_code(std::errc::invalid_argument));

  if (Data.size() - 32 == 0 || Data.size() % 32 != 0)
    return make_error<StringError>(
        "Invalid-sized XRay data.",
        std::make_error_code(std::errc::invalid_argument));

  if (auto E = readBinaryFormatHeader(Data, FileHeader))
    return E;

  // Each record after the header will be 32 bytes, in the following format:
  //
  //   (2)   uint16 : record type
  //   (1)   uint8  : cpu id
  //   (1)   uint8  : type
  //   (4)   sint32 : function id
  //   (8)   uint64 : tsc
  //   (4)   uint32 : thread id
  //   (12)  -      : padding
  for (auto S = Data.drop_front(32); !S.empty(); S = S.drop_front(32)) {
    DataExtractor RecordExtractor(S, true, 8);
    uint32_t OffsetPtr = 0;
    Records.emplace_back();
    auto &Record = Records.back();
    Record.RecordType = RecordExtractor.getU16(&OffsetPtr);
    Record.CPU = RecordExtractor.getU8(&OffsetPtr);
    auto Type = RecordExtractor.getU8(&OffsetPtr);
    switch (Type) {
    case 0:
      Record.Type = RecordTypes::ENTER;
      break;
    case 1:
      Record.Type = RecordTypes::EXIT;
      break;
    default:
      return make_error<StringError>(
          Twine("Unknown record type '") + Twine(int{Type}) + "'",
          std::make_error_code(std::errc::executable_format_error));
    }
    Record.FuncId = RecordExtractor.getSigned(&OffsetPtr, sizeof(int32_t));
    Record.TSC = RecordExtractor.getU64(&OffsetPtr);
    Record.TId = RecordExtractor.getU32(&OffsetPtr);
  }
  return Error::success();
}
Example #28
0
void printSymbolVersionDependency(ArrayRef<uint8_t> Contents,
                                  StringRef StrTab) {
  outs() << "Version References:\n";

  const uint8_t *Buf = Contents.data();
  while (Buf) {
    auto *Verneed = reinterpret_cast<const typename ELFT::Verneed *>(Buf);
    outs() << "  required from "
           << StringRef(StrTab.drop_front(Verneed->vn_file).data()) << ":\n";

    const uint8_t *BufAux = Buf + Verneed->vn_aux;
    while (BufAux) {
      auto *Vernaux = reinterpret_cast<const typename ELFT::Vernaux *>(BufAux);
      outs() << "    "
             << format("0x%08" PRIx32 " ", (uint32_t)Vernaux->vna_hash)
             << format("0x%02" PRIx16 " ", (uint16_t)Vernaux->vna_flags)
             << format("%02" PRIu16 " ", (uint16_t)Vernaux->vna_other)
             << StringRef(StrTab.drop_front(Vernaux->vna_name).data()) << '\n';
      BufAux = Vernaux->vna_next ? BufAux + Vernaux->vna_next : nullptr;
    }
    Buf = Verneed->vn_next ? Buf + Verneed->vn_next : nullptr;
  }
}
Example #29
0
std::unique_ptr<Acceptor> Acceptor::Create(StringRef name,
                                           const bool child_processes_inherit,
                                           Error &error) {
  error.Clear();

  Socket::SocketProtocol socket_protocol = Socket::ProtocolUnixDomain;
  int port;
  std::string scheme, host, path;
  // Try to match socket name as URL - e.g., tcp://localhost:5555
  if (UriParser::Parse(name.str(), scheme, host, port, path)) {
    if (!FindProtocolByScheme(scheme.c_str(), socket_protocol))
      error.SetErrorStringWithFormat("Unknown protocol scheme \"%s\"",
                                     scheme.c_str());
    else
      name = name.drop_front(scheme.size() + strlen("://"));
  } else {
    std::string host_str;
    std::string port_str;
    int32_t port = INT32_MIN;
    // Try to match socket name as $host:port - e.g., localhost:5555
    if (Socket::DecodeHostAndPort(name, host_str, port_str, port, nullptr))
      socket_protocol = Socket::ProtocolTcp;
  }

  if (error.Fail())
    return std::unique_ptr<Acceptor>();

  std::unique_ptr<Socket> listener_socket_up =
      Socket::Create(socket_protocol, child_processes_inherit, error);

  LocalSocketIdFunc local_socket_id;
  if (error.Success()) {
    if (listener_socket_up->GetSocketProtocol() == Socket::ProtocolTcp) {
      TCPSocket *tcp_socket =
          static_cast<TCPSocket *>(listener_socket_up.get());
      local_socket_id = [tcp_socket]() {
        auto local_port = tcp_socket->GetLocalPortNumber();
        return (local_port != 0) ? llvm::to_string(local_port) : "";
      };
    } else {
      const std::string socket_name = name;
      local_socket_id = [socket_name]() { return socket_name; };
    }

    return std::unique_ptr<Acceptor>(
        new Acceptor(std::move(listener_socket_up), name, local_socket_id));
  }

  return std::unique_ptr<Acceptor>();
}
Example #30
0
static UTF32 chopOneUTF32(StringRef &Buffer) {
  UTF32 C;
  const UTF8 *const Begin8Const =
      reinterpret_cast<const UTF8 *>(Buffer.begin());
  const UTF8 *Begin8 = Begin8Const;
  UTF32 *Begin32 = &C;

  // In lenient mode we will always end up with a "reasonable" value in C for
  // non-empty input.
  assert(!Buffer.empty());
  ConvertUTF8toUTF32(&Begin8, reinterpret_cast<const UTF8 *>(Buffer.end()),
                     &Begin32, &C + 1, lenientConversion);
  Buffer = Buffer.drop_front(Begin8 - Begin8Const);
  return C;
}