Example #1
0
int main(int argc, char **argv) {
    LCParser  lp;
    Arg porta(lp,"-p",Arg::STRING, "Run server on port" ,"--port");
    Arg helpa(lp,"-h",Arg::BOOL, "Print help" ,"--help");
    lp.parse(argc,argv);
    if (helpa.isValid){
        lp.help(cout);
        return 0;
    }
    Rewriter r;
    for (size_t i = 0; i < lp.unk.size(); i++) {
        r.load_file(lp.unk[i].start());
    }
    if (porta.isValid) {
        cout << "Loaded " << r.rules.size() << endl;
        return TCPFork::start(&r,(int)porta.value);
    }
    else{
        LineTokenizer lt(cin);
        while (lt.next()){
            r.annotate(lt.token(),cout);
            cout << endl;
        }
    }

}
Example #2
0
void html::EscapeText(Rewriter &R, FileID FID,
                      bool EscapeSpaces, bool ReplaceTabs) {

  const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FID);
  const char* C = Buf->getBufferStart();
  const char* FileEnd = Buf->getBufferEnd();

  assert (C <= FileEnd);

  RewriteBuffer &RB = R.getEditBuffer(FID);

  unsigned ColNo = 0;
  for (unsigned FilePos = 0; C != FileEnd ; ++C, ++FilePos) {
    switch (*C) {
    default: ++ColNo; break;
    case '\n':
    case '\r':
      ColNo = 0;
      break;

    case ' ':
      if (EscapeSpaces)
        RB.ReplaceText(FilePos, 1, "&nbsp;");
      ++ColNo;
      break;
    case '\f':
      RB.ReplaceText(FilePos, 1, "<hr>");
      ColNo = 0;
      break;

    case '\t': {
      if (!ReplaceTabs)
        break;
      unsigned NumSpaces = 8-(ColNo&7);
      if (EscapeSpaces)
        RB.ReplaceText(FilePos, 1,
                       StringRef("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
                                       "&nbsp;&nbsp;&nbsp;", 6*NumSpaces));
      else
        RB.ReplaceText(FilePos, 1, StringRef("        ", NumSpaces));
      ColNo += NumSpaces;
      break;
    }
    case '<':
      RB.ReplaceText(FilePos, 1, "&lt;");
      ++ColNo;
      break;

    case '>':
      RB.ReplaceText(FilePos, 1, "&gt;");
      ++ColNo;
      break;

    case '&':
      RB.ReplaceText(FilePos, 1, "&amp;");
      ++ColNo;
      break;
    }
  }
}
Example #3
0
static void dorewrite(terra_State * T, const char * code, const char ** argbegin, const char ** argend, std::string * output, Obj * result) {
    
    llvm::MemoryBuffer * membuffer = llvm::MemoryBuffer::getMemBufferCopy(code, "<buffer>");
    CompilerInstance TheCompInst;
    initializeclang(T, membuffer, argbegin, argend, &TheCompInst);
    
    // Create an AST consumer instance which is going to get called by
    // ParseAST.
    // A Rewriter helps us manage the code rewriting task.
    SourceManager & SourceMgr = TheCompInst.getSourceManager();
    Rewriter TheRewriter;
    TheRewriter.setSourceMgr(SourceMgr, TheCompInst.getLangOpts());
    
    std::stringstream dummy;
    IncludeCConsumer TheConsumer(TheRewriter,dummy,result);

    // Parse the file to AST, registering our consumer as the AST consumer.
    ParseAST(TheCompInst.getPreprocessor(), &TheConsumer,
             TheCompInst.getASTContext());

    // At this point the rewriter's buffer should be full with the rewritten
    // file contents.
    const RewriteBuffer *RewriteBuf =
        TheRewriter.getRewriteBufferFor(SourceMgr.getMainFileID());
    
    std::ostringstream out;
    out << std::string(membuffer->getBufferStart(),membuffer->getBufferEnd()) << "\n" 
    << "void __makeeverythinginclanglive_" << T->C->next_unused_id++ << "() {\n"
    << dummy.str() << "\n}\n";
    *output = out.str();
    //printf("output is %s\n",(*output).c_str());
}
Example #4
0
static void rewrite_jump(Continuation* old_cont, Continuation* new_cont, Rewriter& rewriter) {
    Array<const Def*> args(old_cont->num_args());
    for (size_t i = 0; i< old_cont->num_args(); ++i)
        args[i] = rewriter.instantiate(old_cont->arg(i));

    auto callee = rewriter.instantiate(old_cont->callee());
    new_cont->jump(callee, args, old_cont->jump_debug());
}
int main(int argc, char *argv[]) {
  if (argc != 2) {
    llvm::errs() << "Usage: rewritersample <filename>\n";
    return 1;
  }

  // CompilerInstance will hold the instance of the Clang compiler for us,
  // managing the various objects needed to run the compiler.
  CompilerInstance TheCompInst;
  TheCompInst.createDiagnostics();

  LangOptions &lo = TheCompInst.getLangOpts();
  lo.CPlusPlus = 1;

  // Initialize target info with the default triple for our platform.
  auto TO = std::make_shared<TargetOptions>();
  TO->Triple = llvm::sys::getDefaultTargetTriple();
  TargetInfo *TI =
      TargetInfo::CreateTargetInfo(TheCompInst.getDiagnostics(), TO);
  TheCompInst.setTarget(TI);

  TheCompInst.createFileManager();
  FileManager &FileMgr = TheCompInst.getFileManager();
  TheCompInst.createSourceManager(FileMgr);
  SourceManager &SourceMgr = TheCompInst.getSourceManager();
  TheCompInst.createPreprocessor(TU_Module);
  TheCompInst.createASTContext();

  // A Rewriter helps us manage the code rewriting task.
  Rewriter TheRewriter;
  TheRewriter.setSourceMgr(SourceMgr, TheCompInst.getLangOpts());

  // Set the main file handled by the source manager to the input file.
  const FileEntry *FileIn = FileMgr.getFile(argv[1]);
  SourceMgr.setMainFileID(
      SourceMgr.createFileID(FileIn, SourceLocation(), SrcMgr::C_User));
  TheCompInst.getDiagnosticClient().BeginSourceFile(
      TheCompInst.getLangOpts(), &TheCompInst.getPreprocessor());

  // Create an AST consumer instance which is going to get called by
  // ParseAST.
  MyASTConsumer TheConsumer(TheRewriter);

  // Parse the file to AST, registering our consumer as the AST consumer.
  ParseAST(TheCompInst.getPreprocessor(), &TheConsumer,
           TheCompInst.getASTContext());

  // At this point the rewriter's buffer should be full with the rewritten
  // file contents.
  const RewriteBuffer *RewriteBuf =
      TheRewriter.getRewriteBufferFor(SourceMgr.getMainFileID());
  llvm::outs() << std::string(RewriteBuf->begin(), RewriteBuf->end());

  return 0;
}
Example #6
0
 virtual bool VisitStmt(Stmt *st) {
     if (ReturnStmt *ret = dyn_cast<ReturnStmt>(st)) {
         rewriter.ReplaceText(ret->getRetValue()->getLocStart(), 6, "val");
         errs() << "** Rewrote ReturnStmt\n";
     }        
     if (CallExpr *call = dyn_cast<CallExpr>(st)) {
         rewriter.ReplaceText(call->getLocStart(), 7, "add5");
         errs() << "** Rewrote function call\n";
     }
     return true;
 }
std::unique_ptr<clang::ASTConsumer> FindPatternAction::CreateASTConsumer(CompilerInstance& Compiler, StringRef InFile){

    if(InFile == lastName)
        return 0;
    else{
        llvm::errs()<<"["<<++fileNum<<"/"<<fileTotalNum<<"]"<<" Now analyze the file: "<<InFile<<"\n";
        lastName = InFile;
        Rewriter rewriter;
        rewriter.setSourceMgr(Compiler.getSourceManager(), Compiler.getLangOpts());
        return std::unique_ptr<clang::ASTConsumer>(new FindPatternConsumer(&Compiler, InFile));
    }
}
Example #8
0
int main(int argc, char *argv[])
{
    if (argc != 2) {
        llvm::errs() << "Usage: rewritersample <filename>\n";
        return 1;
    }

    // CompilerInstance will hold the instance of the Clang compiler for us,
    // managing the various objects needed to run the compiler.
    CompilerInstance ci;
    ci.createDiagnostics(0, 0);

    // Initialize target info with the default triple for our platform.
    TargetOptions TO;
    TO.Triple = llvm::sys::getDefaultTargetTriple();
    TargetInfo *TI = TargetInfo::CreateTargetInfo(
        ci.getDiagnostics(), TO);
    ci.setTarget(TI);

    ci.createFileManager();
    FileManager &fm = ci.getFileManager();
    ci.createSourceManager(fm);
    SourceManager &SourceMgr = ci.getSourceManager();
    ci.createPreprocessor();
    ci.createASTContext();

    // A Rewriter helps us manage the code rewriting task.
    Rewriter rw;
    rw.setSourceMgr(SourceMgr, ci.getLangOpts());

    // Set the main file handled by the source manager to the input file.
    const FileEntry *fi = fm.getFile(argv[1]);
    SourceMgr.createMainFileID(fi);
    ci.getDiagnosticClient().BeginSourceFile(
        ci.getLangOpts(),
        &ci.getPreprocessor());

    // Create an AST consumer instance which is going to get called by
    // ParseAST.
    MyASTConsumer astc(rw);

    // Parse the file to AST, registering our consumer as the AST consumer.
    ParseAST(ci.getPreprocessor(), &astc,
             ci.getASTContext());

    // At this point the rewriter's buffer should be full with the rewritten
    // file contents.
    const RewriteBuffer *rwb =
        rw.getRewriteBufferFor(SourceMgr.getMainFileID());
    llvm::outs() << string(rwb->begin(), rwb->end());

    return 0;
}
Example #9
0
int main(int argc, const char **argv) {
    // parse the command-line args passed to your code
    static cl::OptionCategory MyToolCategory("My tool options");
    CommonOptionsParser op(argc, argv, MyToolCategory);        
    // create a new Clang Tool instance (a LibTooling environment)
    ClangTool Tool(op.getCompilations(), op.getSourcePathList());

    // run the Clang Tool, creating a new FrontendAction (explained below)
    int result = Tool.run(newFrontendActionFactory<ExampleFrontendAction>().get());

    errs() << "\nFound " << numFunctions << " functions.\n\n";
    // print out the rewritten source code ("rewriter" is a global var.)
    rewriter.getEditBuffer(rewriter.getSourceMgr().getMainFileID()).write(errs());
    return result;
}
    virtual void run(const MatchFinder::MatchResult &Result){//freeVar
        const DeclRefExpr* DRE = Result.Nodes.getNodeAs<DeclRefExpr>("freeVar");
        #ifdef DEBUG
        llvm::errs()<<"----DRE(freeVar) find----\n";
        #endif
        
        if(!DRE)   return ;

        const SourceManager *SM = Result.SourceManager;
        
        const NamedDecl *ND = DRE->getFoundDecl();
        checkPoint cp;
        cp.name = rewrite.ConvertToString((Stmt*)DRE);
        std::string str_decl = ND->getNameAsString();
        cp.declName = str_decl;
       
        SourceLocation declLocStart = ND->getLocStart();
        std::string str_declLocStart = declLocStart.printToString(*SM);
        loc_strToint(cp.declRow,cp.declCol,str_declLocStart.c_str());

        SourceLocation locStart = DRE->getLocStart();
        std::string str_locStart = locStart.printToString(*SM);
        loc_strToint(cp.row,cp.col,str_locStart.c_str());


        
        cpVecF.push_back(cp);
    #ifdef DEBUG
    llvm::errs()<<"----DRE(freeVar) end----\n";
    #endif
    }
Example #11
0
bool formatAndApplyAllReplacements(
    const std::map<std::string, Replacements> &FileToReplaces, Rewriter &Rewrite,
    StringRef Style) {
  SourceManager &SM = Rewrite.getSourceMgr();
  FileManager &Files = SM.getFileManager();

  bool Result = true;
  for (const auto &FileAndReplaces : groupReplacementsByFile(FileToReplaces)) {
    const std::string &FilePath = FileAndReplaces.first;
    auto &CurReplaces = FileAndReplaces.second;

    const FileEntry *Entry = Files.getFile(FilePath);
    FileID ID = SM.getOrCreateFileID(Entry, SrcMgr::C_User);
    StringRef Code = SM.getBufferData(ID);

    format::FormatStyle CurStyle = format::getStyle(Style, FilePath, "LLVM");
    auto NewReplacements =
        format::formatReplacements(Code, CurReplaces, CurStyle);
    if (!NewReplacements) {
      llvm::errs() << llvm::toString(NewReplacements.takeError()) << "\n";
      return false;
    }
    Result = applyAllReplacements(*NewReplacements, Rewrite) && Result;
  }
  return Result;
}
Example #12
0
/**
 * Instruments given module with rules from json file.
 * @param M module to be instrumented.
 * @param rw parsed rules to apply.
 * @return true if instrumentation was done without problems, false otherwise
 */
bool instrumentModule(Module &M, Rewriter rw) {
	// Instrument global variables
	if(!InstrumentGlobals(M, rw)) return false;

	RewriterConfig rw_config = rw.getConfig();

	// Instrument instructions in functions
	for (Module::iterator Fiterator = M.begin(), E = M.end(); Fiterator != E; ++Fiterator) {

		// Do not instrument functions linked for instrumentation
		string functionName = (&*Fiterator)->getName().str();

		if(functionName.find("__INSTR_")!=string::npos ||
		   functionName.find("__VERIFIER_")!=string::npos) { //TODO just starts with
			logger.write_info("Omitting function " + functionName + " from instrumentation.");
			continue;
		}

		for (inst_iterator Iiterator = inst_begin(&*Fiterator), End = inst_end(&*Fiterator); Iiterator != End; ++Iiterator) {
			// This iterator may be replaced (by an iterator to the following
			// instruction) in the InsertCallInstruction function
			// Check if the instruction is relevant
			if(!CheckInstruction(&*Iiterator, M, &*Fiterator, rw_config, &Iiterator)) return false;
		}
	}
	// Write instrumented module into the output file
	ofstream out_file;
	out_file.open(outputName, ios::out | ios::binary);
	raw_os_ostream rstream(out_file);

	WriteBitcodeToFile(&M, rstream);
    rstream.flush();
    out_file.close();
	return true;
}
Example #13
0
void SynthesizeRemovalConsumer::HandleTranslationUnit(ASTContext &C)
{
  if (compilerInstance->getDiagnostics().hasErrorOccurred()) {
    return;
  }
  
  astContext = &C;
  auto TUD = C.getTranslationUnitDecl();  
  removeSynthesizeDirectives(TUD);
  processDeclContext(TUD);

  if (removeSet.empty()) {
    // nothing is removed
    llvm::errs() << "nothing to remove.\n";
    return;
  }

  SourceManager &SM = rewriter.getSourceMgr();
  FileID FID = SM.getMainFileID();
  const FileEntry* F = SM.getFileEntryForID(FID);
  
  // backup the source
  std::string backupFilename = std::string(F->getName()) + ".bak";
  std::string errInfo;
  llvm::raw_fd_ostream backupStream(backupFilename.c_str(), errInfo,
    llvm::sys::fs::F_Binary);
  if (!errInfo.empty()) {
    llvm::errs() << "Cannot write backup file: " << backupFilename <<
      ", error info: " << errInfo << "\n";
    return;
  }
  backupStream << SM.getBufferData(FID);
  backupStream.flush();

  // write the output
  llvm::raw_fd_ostream outStream(F->getName(), errInfo,
    llvm::sys::fs::F_Binary);
  if (!errInfo.empty()) {
    llvm::errs() << "Cannot write output file: " << F->getName() <<
      ", error info: " << errInfo << "\n";
    return;
  }
    
  const RewriteBuffer *RB = rewriter.getRewriteBufferFor(FID);
  RB->write(outStream);
  outStream.flush();
}
Example #14
0
/// HighlightRange - Highlight a range in the source code with the specified
/// start/end tags.  B/E must be in the same file.  This ensures that
/// start/end tags are placed at the start/end of each line if the range is
/// multiline.
void html::HighlightRange(Rewriter &R, SourceLocation B, SourceLocation E,
                          const char *StartTag, const char *EndTag) {
  SourceManager &SM = R.getSourceMgr();
  B = SM.getInstantiationLoc(B);
  E = SM.getInstantiationLoc(E);
  FileID FID = SM.getFileID(B);
  assert(SM.getFileID(E) == FID && "B/E not in the same file!");

  unsigned BOffset = SM.getFileOffset(B);
  unsigned EOffset = SM.getFileOffset(E);
  
  // Include the whole end token in the range.
  EOffset += Lexer::MeasureTokenLength(E, R.getSourceMgr(), R.getLangOpts());
  
  HighlightRange(R.getEditBuffer(FID), BOffset, EOffset,
                 SM.getBufferData(FID).first, StartTag, EndTag);
}
Example #15
0
void html::AddLineNumbers(Rewriter& R, FileID FID) {

  const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FID);
  const char* FileBeg = Buf->getBufferStart();
  const char* FileEnd = Buf->getBufferEnd();
  const char* C = FileBeg;
  RewriteBuffer &RB = R.getEditBuffer(FID);
  
  assert (C <= FileEnd);
  
  unsigned LineNo = 0;
  unsigned FilePos = 0;
  
  while (C != FileEnd) {    
    
    ++LineNo;
    unsigned LineStartPos = FilePos;
    unsigned LineEndPos = FileEnd - FileBeg;
    
    assert (FilePos <= LineEndPos);
    assert (C < FileEnd);
    
    // Scan until the newline (or end-of-file).
    
    while (C != FileEnd) {
      char c = *C;
      ++C;
      
      if (c == '\n') {
        LineEndPos = FilePos++;
        break;
      }
      
      ++FilePos;
    }
    
    AddLineNumber(RB, LineNo, LineStartPos, LineEndPos);
  }
  
  // Add one big table tag that surrounds all of the code.
  RB.InsertTextBefore(0, "<table class=\"code\">\n",
                      strlen("<table class=\"code\">\n"));
  
  RB.InsertTextAfter(FileEnd - FileBeg, "</table>", strlen("</table>"));
}
Example #16
0
 virtual bool VisitFunctionDecl(FunctionDecl *func) {
     numFunctions++;
     string funcName = func->getNameInfo().getName().getAsString();
     if (funcName == "do_math") {
         rewriter.ReplaceText(func->getLocation(), funcName.length(), "add5");
         errs() << "** Rewrote function def: " << funcName << "\n";
     }    
     return true;
 }
Example #17
0
int RefactoringTool::saveRewrittenFiles(Rewriter &Rewrite) {
  for (Rewriter::buffer_iterator I = Rewrite.buffer_begin(),
                                 E = Rewrite.buffer_end();
       I != E; ++I) {
    // FIXME: This code is copied from the FixItRewriter.cpp - I think it should
    // go into directly into Rewriter (there we also have the Diagnostics to
    // handle the error cases better).
    const FileEntry *Entry =
        Rewrite.getSourceMgr().getFileEntryForID(I->first);
    std::string ErrorInfo;
    llvm::raw_fd_ostream FileStream(Entry->getName(), ErrorInfo,
                                    llvm::sys::fs::F_Binary);
    if (!ErrorInfo.empty())
      return 1;
    I->second.write(FileStream);
    FileStream.flush();
  }
  return 0;
}
Example #18
0
static void rewrite_def(const Def* def, Rewriter& rewriter) {
    if (rewriter.old2new.count(def) || def->isa_continuation())
        return;

    for (auto op : def->ops())
        rewrite_def(op, rewriter);

    auto new_type = rewrite_type(def->world(), def->type());
    if (new_type != def->type()) {
        auto primop = def->as<PrimOp>();
        Array<const Def*> ops(def->num_ops());
        for (size_t i = 0; i < def->num_ops(); ++i)
            ops[i] = rewriter.instantiate(def->op(i));
        rewriter.old2new[primop] = primop->rebuild(ops, new_type);
        for (auto use : primop->uses())
            rewrite_def(use.def(), rewriter);
    } else {
        rewriter.instantiate(def);
    }
}
Example #19
0
/// \brief Convenience function to get rewritten content for \c Filename from
/// \c Rewrites.
///
/// \pre Replacements[i].getFilePath() == Replacements[i+1].getFilePath().
/// \post Replacements.empty() -> Result.empty()
///
/// \param[in] Replacements Replacements to apply
/// \param[in] Rewrites Rewriter to use to apply replacements.
/// \param[out] Result Contents of the file after applying replacements if
/// replacements were provided.
///
/// \returns \li true if all replacements were applied successfully.
///          \li false if at least one replacement failed to apply.
static bool
getRewrittenData(const std::vector<tooling::Replacement> &Replacements,
                 Rewriter &Rewrites, std::string &Result) {
  if (Replacements.empty()) return true;

  if (!tooling::applyAllReplacements(Replacements, Rewrites))
    return false;

  SourceManager &SM = Rewrites.getSourceMgr();
  FileManager &Files = SM.getFileManager();

  StringRef FileName = Replacements.begin()->getFilePath();
  const clang::FileEntry *Entry = Files.getFile(FileName);
  assert(Entry && "Expected an existing file");
  FileID ID = SM.translateFile(Entry);
  assert(!ID.isInvalid() && "Expected a valid FileID");
  const RewriteBuffer *Buffer = Rewrites.getRewriteBufferFor(ID);
  Result = std::string(Buffer->begin(), Buffer->end());

  return true;
}
Example #20
0
int main(int argc, const char **argv) {

    for(int i = 3; i+1< argc; i+=2){
        functionsMap[argv[i]]=argv[i+1];
    }

    CommonOptionsParser op(argc, argv, MyToolCategory);

    ClangTool Tool(op.getCompilations(), op.getSourcePathList());

    int result = Tool.run(newFrontendActionFactory<InserterFrontendAction>().get());

    std::vector<string> paths = op.getSourcePathList();
    StringRef path = (paths[0]).insert(paths[0].find('.'),"Secured");
    std::error_code EC;
    llvm::raw_fd_ostream fd(path, EC, sys::fs::F_RW);

    rewriter.getEditBuffer(rewriter.getSourceMgr().getMainFileID()).write(fd);

    return result;

}
Example #21
0
bool Replacement::apply(Rewriter &Rewrite) const {
  SourceManager &SM = Rewrite.getSourceMgr();
  const FileEntry *Entry = SM.getFileManager().getFile(FilePath);
  if (Entry == NULL)
    return false;
  FileID ID;
  // FIXME: Use SM.translateFile directly.
  SourceLocation Location = SM.translateFileLineCol(Entry, 1, 1);
  ID = Location.isValid() ?
    SM.getFileID(Location) :
    SM.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
  // FIXME: We cannot check whether Offset + Length is in the file, as
  // the remapping API is not public in the RewriteBuffer.
  const SourceLocation Start =
    SM.getLocForStartOfFile(ID).
    getLocWithOffset(Offset);
  // ReplaceText returns false on success.
  // ReplaceText only fails if the source location is not a file location, in
  // which case we already returned false earlier.
  bool RewriteSucceeded = !Rewrite.ReplaceText(Start, Length, ReplacementText);
  assert(RewriteSucceeded);
  return RewriteSucceeded;
}
Example #22
0
void HTMLDiagnostics::HighlightRange(Rewriter& R, FileID BugFileID,
                                     SourceRange Range,
                                     const char *HighlightStart,
                                     const char *HighlightEnd) {
  SourceManager &SM = R.getSourceMgr();
  const LangOptions &LangOpts = R.getLangOpts();

  SourceLocation InstantiationStart = SM.getExpansionLoc(Range.getBegin());
  unsigned StartLineNo = SM.getExpansionLineNumber(InstantiationStart);

  SourceLocation InstantiationEnd = SM.getExpansionLoc(Range.getEnd());
  unsigned EndLineNo = SM.getExpansionLineNumber(InstantiationEnd);

  if (EndLineNo < StartLineNo)
    return;

  if (SM.getFileID(InstantiationStart) != BugFileID ||
      SM.getFileID(InstantiationEnd) != BugFileID)
    return;

  // Compute the column number of the end.
  unsigned EndColNo = SM.getExpansionColumnNumber(InstantiationEnd);
  unsigned OldEndColNo = EndColNo;

  if (EndColNo) {
    // Add in the length of the token, so that we cover multi-char tokens.
    EndColNo += Lexer::MeasureTokenLength(Range.getEnd(), SM, LangOpts)-1;
  }

  // Highlight the range.  Make the span tag the outermost tag for the
  // selected range.

  SourceLocation E =
    InstantiationEnd.getLocWithOffset(EndColNo - OldEndColNo);

  html::HighlightRange(R, InstantiationStart, E, HighlightStart, HighlightEnd);
}
    virtual void run(const MatchFinder::MatchResult &Result){
        const DeclRefExpr* DRE = Result.Nodes.getNodeAs<DeclRefExpr>("mallocVar");
        #ifdef DEBUG
        llvm::errs()<<"----DRE(mallocVar) find----\n";
        #endif

        if(!DRE)   return ;

        const SourceManager *SM = Result.SourceManager;
        SourceLocation locStart = DRE->getLocStart();
        
        std::string str_locStart = locStart.printToString(*SM);
        
        checkPoint cp;
        loc_strToint(cp.row,cp.col,str_locStart.c_str());


        cp.name = rewrite.ConvertToString((Stmt*)DRE);

        //找到该变量原先的声明处 
        const NamedDecl *ND = DRE->getFoundDecl();
        std::string str_decl = ND->getNameAsString();
        cp.declName = ND->getNameAsString();
        
        SourceLocation declLocStart = ND->getLocStart();
        std::string str_declLocStart = declLocStart.printToString(*SM);
        loc_strToint(cp.declRow,cp.declCol,str_declLocStart.c_str());
        
        #ifdef DEBUG
        llvm::errs()<<"\ncp: "
        <<cp.row<<":"<<cp.col<<":"<<cp.declRow<<":"<<cp.declCol<<"\n";
        #endif

        
        cpVec.push_back(cp);
        
        #ifdef DEBUG
        llvm::errs() << cp.name << "|\n" <<  cp.declName <<"|\n"
        << cp.declRow << ":" << cp.declCol << "\n";
        llvm::errs() << "ND:\n";
        ND->dump();
        llvm::errs() << "DRE:\n";
        DRE->dump();

        llvm::errs()<<"----DRE(mallocVar) end----\n";
        #endif

    }
Example #24
0
void SynthesizeRemovalConsumer::renameLocation(SourceLocation L,
  std::string& N) {
  if (L.isMacroID()) {        
    // TODO: emit error using diagnostics
    SourceManager &SM = astContext->getSourceManager();
    if (SM.isMacroArgExpansion(L) || SM.isInSystemMacro(L)) {
      // see if it's the macro expansion we can handle
      // e.g.
      //   #define call(x) x
      //   call(y());   // if we want to rename y()
      L = SM.getSpellingLoc(L);
      
      // this falls through to the rename routine below
    }
    else {
      // if the spelling location is from an actual file that we can
      // touch, then do the replacement, but show a warning          
      SourceManager &SM = astContext->getSourceManager();
      auto SL = SM.getSpellingLoc(L);
      FullSourceLoc FSL(SL, SM);
      const FileEntry *FE = SM.getFileEntryForID(FSL.getFileID());
      if (FE) {
        llvm::errs() << "Warning: Rename attempted as a result of macro "
                     << "expansion may break things, at: " << loc(L) << "\n";            
        L = SL;
        // this falls through to the rename routine below
      }
      else {
        // cannot handle this case
        llvm::errs() << "Error: Token is resulted from macro expansion"
          " and is therefore not renamed, at: " << loc(L) << "\n";
        return;
      }
    }
  }
    
  if (shouldIgnore(L)) {
    return;
  }
    
  auto LE = preprocessor->getLocForEndOfToken(L);
  if (LE.isValid()) {        
    // getLocWithOffset returns the location *past* the token, hence -1
    auto E = LE.getLocWithOffset(-1);
    rewriter.ReplaceText(SourceRange(L, E), N);
  }
}  
Example #25
0
/**
 * Instruments global variable if they should be instrumented.
 * @param M module.
 * @param rw_config parsed rules to apply.
 * @return true if instrumentation of global variables was done without problems, false otherwise
 */
bool InstrumentGlobals(Module& M, Rewriter rw) {
	GlobalVarsRule rw_globals = rw.getGlobalsConfig();

	// If there is no rule for global variables, do not try to instrument
	if(rw_globals.inFunction.empty() || rw_globals.globalVar.globalVariable.empty()) // TODO this is not very nice
	  return true;

	// Iterate through global variables
	Module::global_iterator GI = M.global_begin(), GE = M.global_end();
	for ( ; GI != GE; ++GI) {
	    GlobalVariable *GV = dyn_cast<GlobalVariable>(GI);
	    if (!GV) continue;

	    if(rw_globals.inFunction == "*"){
	      //TODO
	      return false;
	      logger.write_error("Rule for global variables for instrumenting to all function not supported yet.");
	    }
	    else{
	      Function* F = M.getFunction(rw_globals.inFunction);
	      // Get operands of new instruction
	      map <string, Value*> variables;

	      if(rw_globals.globalVar.globalVariable != "*")
		variables[rw_globals.globalVar.globalVariable] = GV;
	      if(rw_globals.globalVar.globalVariable != "*"){
		LLVMContext &Context = getGlobalContext();
		variables[rw_globals.globalVar.getSizeTo] = ConstantInt::get(Type::getInt64Ty(Context), getGlobalVarSize(GV, &M));
	      }

	      // Try to instrument the code
	      if(checkAnalysis(rw_globals.condition,variables)) {
		// Try to apply rule
		inst_iterator IIterator = inst_begin(F);
		Instruction *firstI = &*IIterator; //TODO
		if(applyRule(M, firstI, rw_globals.newInstr, variables) == 1) {
		  logger.write_error("Cannot apply rule.");
		  return false;
		}
	      }
	    }
	}

	return true;
}
Example #26
0
    virtual bool VisitFunctionDecl(FunctionDecl *func) {
        NameCodeMap::const_iterator iterator;
        for (iterator = functionsMap.begin(); iterator != functionsMap.end(); ++iterator) {
            string currentFunctionName = func->getNameInfo().getName().getAsString();
            // TODO: additional checkups


            if(func->isThisDeclarationADefinition() && iterator->first.compare(currentFunctionName)==0){
                // std::cout<<"current function: "<<currentFunctionName<<" lookedup func: "<<iterator->first<<std::endl;
                SourceLocation currentLocation;

                Stmt * definition = func->getBody();
                for (StmtRange range = definition->children(); range; ++range){
                    Stmt * fs = *range;
                    currentLocation = fs->getLocStart();
                    break;
                }
                rewriter.InsertTextBefore(currentLocation,functionsMap[iterator->first]);
            }
        }
        return true;
    }
Example #27
0
void HTMLDiagnostics::HandlePiece(Rewriter& R, FileID BugFileID,
                                  const PathDiagnosticPiece& P,
                                  unsigned num, unsigned max) {

  // For now, just draw a box above the line in question, and emit the
  // warning.
  FullSourceLoc Pos = P.getLocation().asLocation();

  if (!Pos.isValid())
    return;

  SourceManager &SM = R.getSourceMgr();
  assert(&Pos.getManager() == &SM && "SourceManagers are different!");
  std::pair<FileID, unsigned> LPosInfo = SM.getDecomposedExpansionLoc(Pos);

  if (LPosInfo.first != BugFileID)
    return;

  const llvm::MemoryBuffer *Buf = SM.getBuffer(LPosInfo.first);
  const char* FileStart = Buf->getBufferStart();

  // Compute the column number.  Rewind from the current position to the start
  // of the line.
  unsigned ColNo = SM.getColumnNumber(LPosInfo.first, LPosInfo.second);
  const char *TokInstantiationPtr =Pos.getExpansionLoc().getCharacterData();
  const char *LineStart = TokInstantiationPtr-ColNo;

  // Compute LineEnd.
  const char *LineEnd = TokInstantiationPtr;
  const char* FileEnd = Buf->getBufferEnd();
  while (*LineEnd != '\n' && LineEnd != FileEnd)
    ++LineEnd;

  // Compute the margin offset by counting tabs and non-tabs.
  unsigned PosNo = 0;
  for (const char* c = LineStart; c != TokInstantiationPtr; ++c)
    PosNo += *c == '\t' ? 8 : 1;

  // Create the html for the message.

  const char *Kind = 0;
  switch (P.getKind()) {
  case PathDiagnosticPiece::Call:
      llvm_unreachable("Calls should already be handled");
  case PathDiagnosticPiece::Event:  Kind = "Event"; break;
  case PathDiagnosticPiece::ControlFlow: Kind = "Control"; break;
    // Setting Kind to "Control" is intentional.
  case PathDiagnosticPiece::Macro: Kind = "Control"; break;
  }

  std::string sbuf;
  llvm::raw_string_ostream os(sbuf);

  os << "\n<tr><td class=\"num\"></td><td class=\"line\"><div id=\"";

  if (num == max)
    os << "EndPath";
  else
    os << "Path" << num;

  os << "\" class=\"msg";
  if (Kind)
    os << " msg" << Kind;
  os << "\" style=\"margin-left:" << PosNo << "ex";

  // Output a maximum size.
  if (!isa<PathDiagnosticMacroPiece>(P)) {
    // Get the string and determining its maximum substring.
    const std::string& Msg = P.getString();
    unsigned max_token = 0;
    unsigned cnt = 0;
    unsigned len = Msg.size();

    for (std::string::const_iterator I=Msg.begin(), E=Msg.end(); I!=E; ++I)
      switch (*I) {
      default:
        ++cnt;
        continue;
      case ' ':
      case '\t':
      case '\n':
        if (cnt > max_token) max_token = cnt;
        cnt = 0;
      }

    if (cnt > max_token)
      max_token = cnt;

    // Determine the approximate size of the message bubble in em.
    unsigned em;
    const unsigned max_line = 120;

    if (max_token >= max_line)
      em = max_token / 2;
    else {
      unsigned characters = max_line;
      unsigned lines = len / max_line;

      if (lines > 0) {
        for (; characters > max_token; --characters)
          if (len / characters > lines) {
            ++characters;
            break;
          }
      }

      em = characters / 2;
    }

    if (em < max_line/2)
      os << "; max-width:" << em << "em";
  }
  else
    os << "; max-width:100em";

  os << "\">";

  if (max > 1) {
    os << "<table class=\"msgT\"><tr><td valign=\"top\">";
    os << "<div class=\"PathIndex";
    if (Kind) os << " PathIndex" << Kind;
    os << "\">" << num << "</div>";

    if (num > 1) {
      os << "</td><td><div class=\"PathNav\"><a href=\"#Path"
         << (num - 1)
         << "\" title=\"Previous event ("
         << (num - 1)
         << ")\">&#x2190;</a></div></td>";
    }

    os << "</td><td>";
  }

  if (const PathDiagnosticMacroPiece *MP =
        dyn_cast<PathDiagnosticMacroPiece>(&P)) {

    os << "Within the expansion of the macro '";

    // Get the name of the macro by relexing it.
    {
      FullSourceLoc L = MP->getLocation().asLocation().getExpansionLoc();
      assert(L.isFileID());
      StringRef BufferInfo = L.getBufferData();
      std::pair<FileID, unsigned> LocInfo = L.getDecomposedLoc();
      const char* MacroName = LocInfo.second + BufferInfo.data();
      Lexer rawLexer(SM.getLocForStartOfFile(LocInfo.first), PP.getLangOpts(),
                     BufferInfo.begin(), MacroName, BufferInfo.end());

      Token TheTok;
      rawLexer.LexFromRawLexer(TheTok);
      for (unsigned i = 0, n = TheTok.getLength(); i < n; ++i)
        os << MacroName[i];
    }

    os << "':\n";

    if (max > 1) {
      os << "</td>";
      if (num < max) {
        os << "<td><div class=\"PathNav\"><a href=\"#";
        if (num == max - 1)
          os << "EndPath";
        else
          os << "Path" << (num + 1);
        os << "\" title=\"Next event ("
        << (num + 1)
        << ")\">&#x2192;</a></div></td>";
      }

      os << "</tr></table>";
    }

    // Within a macro piece.  Write out each event.
    ProcessMacroPiece(os, *MP, 0);
  }
  else {
    os << html::EscapeText(P.getString());

    if (max > 1) {
      os << "</td>";
      if (num < max) {
        os << "<td><div class=\"PathNav\"><a href=\"#";
        if (num == max - 1)
          os << "EndPath";
        else
          os << "Path" << (num + 1);
        os << "\" title=\"Next event ("
           << (num + 1)
           << ")\">&#x2192;</a></div></td>";
      }
      
      os << "</tr></table>";
    }
  }

  os << "</div></td></tr>";

  // Insert the new html.
  unsigned DisplayPos = LineEnd - FileStart;
  SourceLocation Loc =
    SM.getLocForStartOfFile(LPosInfo.first).getLocWithOffset(DisplayPos);

  R.InsertTextBefore(Loc, os.str());

  // Now highlight the ranges.
  ArrayRef<SourceRange> Ranges = P.getRanges();
  for (ArrayRef<SourceRange>::iterator I = Ranges.begin(),
                                       E = Ranges.end(); I != E; ++I) {
    HighlightRange(R, LPosInfo.first, *I);
  }
}
Example #28
0
 explicit ExampleVisitor(CompilerInstance *CI) 
   : astContext(&(CI->getASTContext())) // initialize private members
 {
     rewriter.setSourceMgr(astContext->getSourceManager(), astContext->getLangOpts());
 }
int main(int argc, char *argv[])
{
    if (argc != 2) {
        llvm::errs() << "Usage: kcov-branch-identify <filename>\n";
        return 1;
    }

    // CompilerInstance will hold the instance of the Clang compiler for us,
    // managing the various objects needed to run the compiler.
    CompilerInstance TheCompInst;
    
    // Diagnostics manage problems and issues in compile 
    TheCompInst.createDiagnostics(NULL, false);

    // Set target platform options 
    // Initialize target info with the default triple for our platform.
    TargetOptions *TO = new TargetOptions();
    TO->Triple = llvm::sys::getDefaultTargetTriple();
    TargetInfo *TI = TargetInfo::CreateTargetInfo(TheCompInst.getDiagnostics(), TO);
    TheCompInst.setTarget(TI);

    // FileManager supports for file system lookup, file system caching, and directory search management.
    TheCompInst.createFileManager();
    FileManager &FileMgr = TheCompInst.getFileManager();
    
    // SourceManager handles loading and caching of source files into memory.
    TheCompInst.createSourceManager(FileMgr);
    SourceManager &SourceMgr = TheCompInst.getSourceManager();
    //global var  m_srcmgr
    //m_srcmgr = &SourceMgr;

    // Prreprocessor runs within a single source file
    TheCompInst.createPreprocessor();
    
    // ASTContext holds long-lived AST nodes (such as types and decls) .
    TheCompInst.createASTContext();

    // Enable HeaderSearch option
    llvm::IntrusiveRefCntPtr<clang::HeaderSearchOptions> hso( new HeaderSearchOptions());
    HeaderSearch headerSearch(hso,
                              TheCompInst.getFileManager(),
                              TheCompInst.getDiagnostics(),
                              TheCompInst.getLangOpts(),
                              TI);

    // <Warning!!> -- Platform Specific Code lives here
    // This depends on A) that you're running linux and
    // B) that you have the same GCC LIBs installed that I do. 
    /*
    $ gcc -xc -E -v -
    ..
     /usr/local/include
     /usr/lib/gcc/x86_64-linux-gnu/4.4.5/include
     /usr/lib/gcc/x86_64-linux-gnu/4.4.5/include-fixed
     /usr/include
    End of search list.
    */
    const char *include_paths[] = {"/usr/local/include",
                "/usr/lib/gcc/x86_64-linux-gnu/4.4.5/include",
                "/usr/lib/gcc/x86_64-linux-gnu/4.4.5/include-fixed",
                "/usr/include"};

    for (int i=0; i<4; i++) 
        hso->AddPath(include_paths[i], 
                    clang::frontend::Angled, 
                    false, 
                    false);
    // </Warning!!> -- End of Platform Specific Code

    InitializePreprocessor(TheCompInst.getPreprocessor(), 
                  TheCompInst.getPreprocessorOpts(),
                  *hso,
                  TheCompInst.getFrontendOpts());


    // A Rewriter helps us manage the code rewriting task.
    Rewriter TheRewriter;
    TheRewriter.setSourceMgr(SourceMgr, TheCompInst.getLangOpts());

    // Set the main file handled by the source manager to the input file.
    const FileEntry *FileIn = FileMgr.getFile(argv[1]);
    SourceMgr.createMainFileID(FileIn);
    
    // Inform Diagnostics that processing of a source file is beginning. 
    TheCompInst.getDiagnosticClient().BeginSourceFile(TheCompInst.getLangOpts(),&TheCompInst.getPreprocessor());
    
    // Create an AST consumer instance which is going to get called by ParseAST.
    MyASTConsumer TheConsumer(SourceMgr);

    // Parse the file to AST, registering our consumer as the AST consumer.
    ParseAST(TheCompInst.getPreprocessor(), &TheConsumer, TheCompInst.getASTContext());
    TheConsumer.printBranchNum();
    return 0;
}
Example #30
0
/// SyntaxHighlight - Relex the specified FileID and annotate the HTML with
/// information about keywords, macro expansions etc.  This uses the macro
/// table state from the end of the file, so it won't be perfectly perfect,
/// but it will be reasonably close.
void html::SyntaxHighlight(Rewriter &R, FileID FID, const Preprocessor &PP) {
  RewriteBuffer &RB = R.getEditBuffer(FID);

  const SourceManager &SM = PP.getSourceManager();
  const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
  Lexer L(FID, FromFile, SM, PP.getLangOpts());
  const char *BufferStart = L.getBuffer().data();

  // Inform the preprocessor that we want to retain comments as tokens, so we
  // can highlight them.
  L.SetCommentRetentionState(true);

  // Lex all the tokens in raw mode, to avoid entering #includes or expanding
  // macros.
  Token Tok;
  L.LexFromRawLexer(Tok);

  while (Tok.isNot(tok::eof)) {
    // Since we are lexing unexpanded tokens, all tokens are from the main
    // FileID.
    unsigned TokOffs = SM.getFileOffset(Tok.getLocation());
    unsigned TokLen = Tok.getLength();
    switch (Tok.getKind()) {
    default: break;
    case tok::identifier:
      llvm_unreachable("tok::identifier in raw lexing mode!");
    case tok::raw_identifier: {
      // Fill in Result.IdentifierInfo and update the token kind,
      // looking up the identifier in the identifier table.
      PP.LookUpIdentifierInfo(Tok);

      // If this is a pp-identifier, for a keyword, highlight it as such.
      if (Tok.isNot(tok::identifier))
        HighlightRange(RB, TokOffs, TokOffs+TokLen, BufferStart,
                       "<span class='keyword'>", "</span>");
      break;
    }
    case tok::comment:
      HighlightRange(RB, TokOffs, TokOffs+TokLen, BufferStart,
                     "<span class='comment'>", "</span>");
      break;
    case tok::utf8_string_literal:
      // Chop off the u part of u8 prefix
      ++TokOffs;
      --TokLen;
      // FALL THROUGH to chop the 8
    case tok::wide_string_literal:
    case tok::utf16_string_literal:
    case tok::utf32_string_literal:
      // Chop off the L, u, U or 8 prefix
      ++TokOffs;
      --TokLen;
      // FALL THROUGH.
    case tok::string_literal:
      // FIXME: Exclude the optional ud-suffix from the highlighted range.
      HighlightRange(RB, TokOffs, TokOffs+TokLen, BufferStart,
                     "<span class='string_literal'>", "</span>");
      break;
    case tok::hash: {
      // If this is a preprocessor directive, all tokens to end of line are too.
      if (!Tok.isAtStartOfLine())
        break;

      // Eat all of the tokens until we get to the next one at the start of
      // line.
      unsigned TokEnd = TokOffs+TokLen;
      L.LexFromRawLexer(Tok);
      while (!Tok.isAtStartOfLine() && Tok.isNot(tok::eof)) {
        TokEnd = SM.getFileOffset(Tok.getLocation())+Tok.getLength();
        L.LexFromRawLexer(Tok);
      }

      // Find end of line.  This is a hack.
      HighlightRange(RB, TokOffs, TokEnd, BufferStart,
                     "<span class='directive'>", "</span>");

      // Don't skip the next token.
      continue;
    }
    }

    L.LexFromRawLexer(Tok);
  }
}