Example #1
0
static best_guess tok_type(clang::Preprocessor &pp, const char *macro_name,
                           const clang::Token &t, StringSet *seen) {
    using namespace clang;
    tok::TokenKind k = t.getKind();

    if(k == tok::identifier) {
        IdentifierInfo *ii = t.getIdentifierInfo();
        if(ii && !seen->count(ii->getNameStart()))
            return macro_type(pp, ii->getNameStart(),
                              pp.getMacroInfo(ii), seen);

        return tok_ok;
    }

    if (k == tok::l_paren || k == tok::r_paren || k == tok::amp || k == tok::plus ||
        k == tok::star || k == tok::minus || k == tok::tilde || k == tok::slash ||
        k == tok::percent || k == tok::lessless || k == tok::greatergreater ||
        k == tok::caret || k == tok::pipe || k == tok::exclaim ||
        k == tok::kw_int || k == tok::kw_float || k == tok::kw_double ||
        k == tok::kw_long || k == tok::kw_signed || k == tok::kw_unsigned)

        return tok_ok;

    return tok_invalid;
}
void IdentifierResolver::updatingIdentifier(IdentifierInfo &II) {
  if (II.isOutOfDate())
    PP.getExternalSource()->updateOutOfDateIdentifier(II);
  
  if (II.isFromAST())
    II.setFETokenInfoChangedSinceDeserialization();
}
Example #3
0
bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
  Token Tok;
  LexUnexpandedToken(Tok);

  if (Tok.isNot(tok::identifier)) {
    Diag(Tok, diag::ext_on_off_switch_syntax);
    return true;
  }
  IdentifierInfo *II = Tok.getIdentifierInfo();
  if (II->isStr("ON"))
    Result = tok::OOS_ON;
  else if (II->isStr("OFF"))
    Result = tok::OOS_OFF;
  else if (II->isStr("DEFAULT"))
    Result = tok::OOS_DEFAULT;
  else {
    Diag(Tok, diag::ext_on_off_switch_syntax);
    return true;
  }

  // Verify that this is followed by EOD.
  LexUnexpandedToken(Tok);
  if (Tok.isNot(tok::eod))
    Diag(Tok, diag::ext_pragma_syntax_eod);
  return false;
}
Example #4
0
	virtual Action::DeclPtrTy
	ActOnDeclarator(Scope *S, Declarator &D) {
		// Print names of global variables. Differentiating between
		// global variables and global functions is Hard in C, so this
		// is only an approximation.
		
		const DeclSpec& DS = D.getDeclSpec();
		SourceLocation loc = D.getIdentifierLoc();
		
		if (
			// Only global declarations...
			D.getContext() == Declarator::FileContext
			
			// ...that aren't typedefs or `extern` declarations...
			&& DS.getStorageClassSpec() != DeclSpec::SCS_extern
			&& DS.getStorageClassSpec() != DeclSpec::SCS_typedef
			
			// ...and no functions...
			&& !D.isFunctionDeclarator()
			
			// ...and in a user header
			&& !pp.getSourceManager().isInSystemHeader(loc)
			) {
			IdentifierInfo *II = D.getIdentifier();
			std::cerr << "Found global user declarator " << II->getName() << std::endl;
		}
		
		return MinimalAction::ActOnDeclarator(S, D);
	}
Example #5
0
ObjCStringFormatFamily Selector::getStringFormatFamilyImpl(Selector sel) {
  IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
  if (!first) return SFF_None;
  
  StringRef name = first->getName();
  
  switch (name.front()) {
    case 'a':
      if (name == "appendFormat") return SFF_NSString;
      break;
      
    case 'i':
      if (name == "initWithFormat") return SFF_NSString;
      break;
      
    case 'l':
      if (name == "localizedStringWithFormat") return SFF_NSString;
      break;
      
    case 's':
      if (name == "stringByAppendingFormat" ||
          name == "stringWithFormat") return SFF_NSString;
      break;
  }
  return SFF_None;
}
Example #6
0
/// \brief Handle \#pragma pop_macro.
///
/// The syntax is:
/// \code
///   #pragma pop_macro("macro")
/// \endcode
void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
  SourceLocation MessageLoc = PopMacroTok.getLocation();

  // Parse the pragma directive and get the macro IdentifierInfo*.
  IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
  if (!IdentInfo) return;

  // Find the vector<MacroInfo*> associated with the macro.
  llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
    PragmaPushMacroInfo.find(IdentInfo);
  if (iter != PragmaPushMacroInfo.end()) {
    // Forget the MacroInfo currently associated with IdentInfo.
    if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
      if (MI->isWarnIfUnused())
        WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
      appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
    }

    // Get the MacroInfo we want to reinstall.
    MacroInfo *MacroToReInstall = iter->second.back();

    if (MacroToReInstall)
      // Reinstall the previously pushed macro.
      appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);

    // Pop PragmaPushMacroInfo stack.
    iter->second.pop_back();
    if (iter->second.size() == 0)
      PragmaPushMacroInfo.erase(iter);
  } else {
    Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
      << IdentInfo->getName();
  }
}
Example #7
0
/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
/// identifier information for the token and install it into the token,
/// updating the token kind accordingly.
IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
  assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");

  // Look up this token, see if it is a macro, or if it is a language keyword.
  IdentifierInfo *II;
  if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
    // No cleaning needed, just use the characters from the lexed buffer.
    II = getIdentifierInfo(Identifier.getRawIdentifier());
  } else {
    // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
    SmallString<64> IdentifierBuffer;
    StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);

    if (Identifier.hasUCN()) {
      SmallString<64> UCNIdentifierBuffer;
      expandUCNs(UCNIdentifierBuffer, CleanedStr);
      II = getIdentifierInfo(UCNIdentifierBuffer);
    } else {
      II = getIdentifierInfo(CleanedStr);
    }
  }

  // Update the token info (identifier info and appropriate token kind).
  Identifier.setIdentifierInfo(II);
  if (getLangOpts().MSVCCompat && II->isCPlusPlusOperatorKeyword() &&
      getSourceManager().isInSystemHeader(Identifier.getLocation()))
    Identifier.setKind(clang::tok::identifier);
  else
    Identifier.setKind(II->getTokenID());

  return II;
}
Example #8
0
/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
/// identifier information for the token and install it into the token,
/// updating the token kind accordingly.
IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
  assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");

  // Look up this token, see if it is a macro, or if it is a language keyword.
  IdentifierInfo *II;
  if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
    // No cleaning needed, just use the characters from the lexed buffer.
    II = getIdentifierInfo(Identifier.getRawIdentifier());
  } else {
    // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
    SmallString<64> IdentifierBuffer;
    StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);

    if (Identifier.hasUCN()) {
      SmallString<64> UCNIdentifierBuffer;
      expandUCNs(UCNIdentifierBuffer, CleanedStr);
      II = getIdentifierInfo(UCNIdentifierBuffer);
    } else {
      II = getIdentifierInfo(CleanedStr);
    }
  }

  // Update the token info (identifier info and appropriate token kind).
  Identifier.setIdentifierInfo(II);
  Identifier.setKind(II->getTokenID());

  return II;
}
Example #9
0
ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) {
  IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
  if (!first) return OIT_None;
  
  StringRef name = first->getName();
  
  if (name.empty()) return OIT_None;
  switch (name.front()) {
    case 'a':
      if (startsWithWord(name, "array")) return OIT_Array;
      break;
    case 'd':
      if (startsWithWord(name, "default")) return OIT_ReturnsSelf;
      if (startsWithWord(name, "dictionary")) return OIT_Dictionary;
      break;
    case 's':
      if (startsWithWord(name, "shared")) return OIT_ReturnsSelf;
      if (startsWithWord(name, "standard")) return OIT_Singleton;
    case 'i':
      if (startsWithWord(name, "init")) return OIT_Init;
    default:
      break;
  }
  return OIT_None;
}
Example #10
0
/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
/// in its expansion, currently expands to that token literally.
static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
                                          const IdentifierInfo *MacroIdent,
                                          Preprocessor &PP) {
  IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();

  // If the token isn't an identifier, it's always literally expanded.
  if (II == 0) return true;

  // If the information about this identifier is out of date, update it from
  // the external source.
  if (II->isOutOfDate())
    PP.getExternalSource()->updateOutOfDateIdentifier(*II);

  // If the identifier is a macro, and if that macro is enabled, it may be
  // expanded so it's not a trivial expansion.
  if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
      // Fast expanding "#define X X" is ok, because X would be disabled.
      II != MacroIdent)
    return false;

  // If this is an object-like macro invocation, it is safe to trivially expand
  // it.
  if (MI->isObjectLike()) return true;

  // If this is a function-like macro invocation, it's safe to trivially expand
  // as long as the identifier is not a macro argument.
  for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
       I != E; ++I)
    if (*I == II)
      return false;   // Identifier is a macro argument.

  return true;
}
Example #11
0
void PthreadLockChecker::PostVisitCallExpr(CheckerContext &C,
                                           const CallExpr *CE) {
  const GRState *state = C.getState();
  const Expr *Callee = CE->getCallee();
  const FunctionTextRegion *R =
    dyn_cast_or_null<FunctionTextRegion>(state->getSVal(Callee).getAsRegion());
  
  if (!R)
    return;
  
  IdentifierInfo *II = R->getDecl()->getIdentifier();
  if (!II)   // if no identifier, not a simple C function
    return;
  llvm::StringRef FName = II->getName();
  
  if (FName == "pthread_mutex_lock") {
    if (CE->getNumArgs() != 1)
      return;
    AcquireLock(C, CE, state->getSVal(CE->getArg(0)), false);
  }
  else if (FName == "pthread_mutex_trylock") {
    if (CE->getNumArgs() != 1)
      return;
    AcquireLock(C, CE, state->getSVal(CE->getArg(0)), true);
  }  
  else if (FName == "pthread_mutex_unlock") {
    if (CE->getNumArgs() != 1)
      return;
    ReleaseLock(C, CE, state->getSVal(CE->getArg(0)));
  }
}
Example #12
0
/// LookupBuiltin - Lookup for built-in functions
static bool LookupBuiltin(Sema &S, LookupResult &R) {
	Sema::LookupNameKind NameKind = R.getLookupKind();

	// If we didn't find a use of this identifier, and if the identifier
	// corresponds to a compiler builtin, create the defn object for the builtin
	// now, injecting it into system scope, and return it.
	if (NameKind == Sema::LookupOrdinaryName) {
		IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
		if (II) {
			// If this is a builtin on this (or all) targets, create the defn.
			if (unsigned BuiltinID = II->getBuiltinID()) {
				if (NamedDefn *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
	                                                BuiltinID, S.BaseWorkspace,
	                                                /*R.isForRedeclaration()*/false,
	                                                R.getNameLoc())) {
					R.addDefn(D);
					return true;
				}

				//FIXME yabin
				// should i deal with this situation in gmat?
//				if (R.isForRedeclaration()) {
//					// If we're redeclaring this function anyway, forget that
//					// this was a builtin at all.
//					S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID,
//							S.Context.Idents);
//				}

				return false;
			}
		}
	}

	return false;
}
Example #13
0
ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) {
  IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
  if (!first) return OIT_None;
  
  StringRef name = first->getName();
  
  if (name.empty()) return OIT_None;
  switch (name.front()) {
    case 'a':
      if (startsWithWord(name, "alloc")) return OIT_MemManage;
      else
        if (startsWithWord(name, "array")) return OIT_Array;
      break;
    case 'd':
      if (startsWithWord(name, "dictionary")) return OIT_Dictionary;
      break;
    case 'i':
      if (startsWithWord(name, "init")) return OIT_MemManage;
      break;
    case 's':
      if (startsWithWord(name, "string")) return OIT_NSString;
      else
        if (startsWithWord(name, "set")) return OIT_NSSet;
      break;
    case 'U':
      if (startsWithWord(name, "URL")) return OIT_NSURL;
      break;
    default:
      break;
  }
  return OIT_None;
}
Example #14
0
static void PrintTypeSpec(const NamedDecl *D, std::string &S) {
  IdentifierInfo *II = D->getIdentifier();
  if (S.empty())
    S = II->getName().str();
  else
    S = II->getName().str() + ' ' + S;
}
void 
PragmaOpenCLExtensionHandler::HandlePragma(Preprocessor &PP, 
                                           PragmaIntroducerKind Introducer,
                                           Token &Tok) {
  PP.LexUnexpandedToken(Tok);
  if (Tok.isNot(tok::identifier)) {
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) <<
      "OPENCL";
    return;
  }
  IdentifierInfo *ename = Tok.getIdentifierInfo();
  SourceLocation NameLoc = Tok.getLocation();

  PP.Lex(Tok);
  if (Tok.isNot(tok::colon)) {
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_colon) << ename;
    return;
  }

  PP.Lex(Tok);
  if (Tok.isNot(tok::identifier)) {
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_enable_disable);
    return;
  }
  IdentifierInfo *op = Tok.getIdentifierInfo();

  unsigned state;
  if (op->isStr("enable")) {
    state = 1;
  } else if (op->isStr("disable")) {
    state = 0;
  } else {
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_enable_disable);
    return;
  }
  SourceLocation StateLoc = Tok.getLocation();

  PP.Lex(Tok);
  if (Tok.isNot(tok::eod)) {
    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
      "OPENCL EXTENSION";
    return;
  }

  OpenCLExtData data(ename, state);
  Token *Toks =
    (Token*) PP.getPreprocessorAllocator().Allocate(
      sizeof(Token) * 1, llvm::alignOf<Token>());
  new (Toks) Token();
  Toks[0].startToken();
  Toks[0].setKind(tok::annot_pragma_opencl_extension);
  Toks[0].setLocation(NameLoc);
  Toks[0].setAnnotationValue(data.getOpaqueValue());
  PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
                      /*OwnsTokens=*/false);

  if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
      Callbacks->PragmaOpenCLExtension(NameLoc, ename, StateLoc, state);
  }
}
Example #16
0
    bool VisitVarDecl(VarDecl *VD) {
        if (VD != Consumer->TheVarDecl)
            return true;

        Rewriter &TheRewriter = Consumer->TheRewriter;
        const SourceManager &SM = TheRewriter.getSourceMgr();

        SourceLocation NameLoc = VD->getLocation();
        IdentifierInfo *IdInfo = VD->getIdentifier();
        assert(IdInfo && "Nameless variable");
        unsigned NameLength = IdInfo->getLength();
        assert(NameLength && "Variable name has no length");

        SourceLocation TypeLocStart = VD->getLocStart();
        const std::string ElemTypeName = getVectorElemTypeName(VD);

        SourceLocation NameLocM1 = NameLoc.getLocWithOffset(-1);
        bool isInvalid = false;
        const char *charBeforeName = SM.getCharacterData(NameLocM1, &isInvalid);
        assert(!isInvalid && "failed to get char before name");

        TheRewriter.ReplaceText(NameLoc.getLocWithOffset(NameLength), 0,
                                ARRAY_SUFFIX);
        if (!std::isspace(*charBeforeName))
            TheRewriter.InsertText(NameLoc, " ");
        TheRewriter.ReplaceText(SourceRange(TypeLocStart, NameLocM1), ElemTypeName);

        return true;
    }
Example #17
0
void Parser::ClassifyToken(Token &T) {
  if (T.isNot(tok::identifier))
    return;

  // Set the identifier info for this token.
  llvm::SmallVector<llvm::StringRef, 2> Spelling;
  TheLexer.getSpelling(T, Spelling);
  std::string NameStr = Tok.CleanLiteral(Spelling);

  // We assume that the "common case" is that if an identifier is also a
  // keyword, it will most likely be used as a keyword. I.e., most programs are
  // sane, and won't use keywords for variable names. We mark it as a keyword
  // for ease in parsing. But it's weak and can change into an identifier or
  // builtin depending upon the context.
  if (IdentifierInfo *KW = Identifiers.lookupKeyword(NameStr)) {
    T.setIdentifierInfo(KW);
    T.setKind(KW->getTokenID());
  } else if (IdentifierInfo *BI = Identifiers.lookupBuiltin(NameStr)) {
    T.setIdentifierInfo(BI);
    T.setKind(BI->getTokenID());
  } else {
    IdentifierInfo *II = getIdentifierInfo(NameStr);
    T.setIdentifierInfo(II);
    T.setKind(II->getTokenID());
  }
}
Example #18
0
StringRef CheckerContext::getCalleeName(const FunctionDecl *FunDecl) const {
  if (!FunDecl)
    return StringRef();
  IdentifierInfo *funI = FunDecl->getIdentifier();
  if (!funI)
    return StringRef();
  return funI->getName();
}
Example #19
0
int DeclarationName::compare(DeclarationName LHS, DeclarationName RHS) {
    if (LHS.getNameKind() != RHS.getNameKind())
        return (LHS.getNameKind() < RHS.getNameKind() ? -1 : 1);

    switch (LHS.getNameKind()) {
    case DeclarationName::Identifier: {
        IdentifierInfo *LII = LHS.getAsIdentifierInfo();
        IdentifierInfo *RII = RHS.getAsIdentifierInfo();
        if (!LII) return RII ? -1 : 0;
        if (!RII) return 1;

        return LII->getName().compare(RII->getName());
    }

    case DeclarationName::ObjCZeroArgSelector:
    case DeclarationName::ObjCOneArgSelector:
    case DeclarationName::ObjCMultiArgSelector: {
        Selector LHSSelector = LHS.getObjCSelector();
        Selector RHSSelector = RHS.getObjCSelector();
        unsigned LN = LHSSelector.getNumArgs(), RN = RHSSelector.getNumArgs();
        for (unsigned I = 0, N = std::min(LN, RN); I != N; ++I) {
            switch (LHSSelector.getNameForSlot(I).compare(
                        RHSSelector.getNameForSlot(I))) {
            case -1:
                return true;
            case 1:
                return false;
            default:
                break;
            }
        }

        return compareInt(LN, RN);
    }

    case DeclarationName::CXXConstructorName:
    case DeclarationName::CXXDestructorName:
    case DeclarationName::CXXConversionFunctionName:
        if (QualTypeOrdering()(LHS.getCXXNameType(), RHS.getCXXNameType()))
            return -1;
        if (QualTypeOrdering()(RHS.getCXXNameType(), LHS.getCXXNameType()))
            return 1;
        return 0;

    case DeclarationName::CXXOperatorName:
        return compareInt(LHS.getCXXOverloadedOperator(),
                          RHS.getCXXOverloadedOperator());

    case DeclarationName::CXXLiteralOperatorName:
        return LHS.getCXXLiteralIdentifier()->getName().compare(
                   RHS.getCXXLiteralIdentifier()->getName());

    case DeclarationName::CXXUsingDirective:
        return 0;
    }

    return 0;
}
Example #20
0
StringRef CheckerContext::getCalleeName(const CallExpr *CE) const {
  const FunctionDecl *funDecl = getCalleeDecl(CE);
  if (!funDecl)
    return StringRef();
  IdentifierInfo *funI = funDecl->getIdentifier();
  if (!funI)
    return StringRef();
  return funI->getName();
}
Example #21
0
C2::ExprResult C2Sema::ActOnIdExpression(IdentifierInfo& symII, SourceLocation symLoc) {
    std::string id(symII.getNameStart(), symII.getLength());
#ifdef SEMA_DEBUG
    std::cerr << COL_SEMA"SEMA: identifier " << id << " at ";
    symLoc.dump(SourceMgr);
    std::cerr << ANSI_NORMAL"\n";
#endif
    return ExprResult(new IdentifierExpr(symLoc, id));
}
void WalkAST::VisitCallExpr(CallExpr *CE) {
  // Get the callee.
  const FunctionDecl *FD = CE->getDirectCallee();

  if (!FD)
    return;

  // Get the name of the callee. If it's a builtin, strip off the prefix.
  IdentifierInfo *II = FD->getIdentifier();
  if (!II)   // if no identifier, not a simple C function
    return;
  StringRef Name = II->getName();
  if (Name.startswith("__builtin_"))
    Name = Name.substr(10);

  // Set the evaluation function by switching on the callee name.
  FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name)
    .Case("bcmp", &WalkAST::checkCall_bcmp)
    .Case("bcopy", &WalkAST::checkCall_bcopy)
    .Case("bzero", &WalkAST::checkCall_bzero)
    .Case("gets", &WalkAST::checkCall_gets)
    .Case("getpw", &WalkAST::checkCall_getpw)
    .Case("mktemp", &WalkAST::checkCall_mktemp)
    .Case("mkstemp", &WalkAST::checkCall_mkstemp)
    .Case("mkdtemp", &WalkAST::checkCall_mkstemp)
    .Case("mkstemps", &WalkAST::checkCall_mkstemp)
    .Cases("strcpy", "__strcpy_chk", &WalkAST::checkCall_strcpy)
    .Cases("strcat", "__strcat_chk", &WalkAST::checkCall_strcat)
    .Cases("sprintf", "vsprintf", "scanf", "wscanf", "fscanf", "fwscanf",
           "vscanf", "vwscanf", "vfscanf", "vfwscanf",
           &WalkAST::checkDeprecatedOrUnsafeBufferHandling)
    .Cases("sscanf", "swscanf", "vsscanf", "vswscanf", "swprintf",
           "snprintf", "vswprintf", "vsnprintf", "memcpy", "memmove",
           &WalkAST::checkDeprecatedOrUnsafeBufferHandling)
    .Cases("strncpy", "strncat", "memset",
           &WalkAST::checkDeprecatedOrUnsafeBufferHandling)
    .Case("drand48", &WalkAST::checkCall_rand)
    .Case("erand48", &WalkAST::checkCall_rand)
    .Case("jrand48", &WalkAST::checkCall_rand)
    .Case("lrand48", &WalkAST::checkCall_rand)
    .Case("mrand48", &WalkAST::checkCall_rand)
    .Case("nrand48", &WalkAST::checkCall_rand)
    .Case("lcong48", &WalkAST::checkCall_rand)
    .Case("rand", &WalkAST::checkCall_rand)
    .Case("rand_r", &WalkAST::checkCall_rand)
    .Case("random", &WalkAST::checkCall_random)
    .Case("vfork", &WalkAST::checkCall_vfork)
    .Default(nullptr);

  // If the callee isn't defined, it is not of security concern.
  // Check and evaluate the call.
  if (evalFunction)
    (this->*evalFunction)(CE, FD);

  // Recurse and check children.
  VisitChildren(CE);
}
Example #23
0
llvm::StringRef
ParserImpl::MergeTokensUntil(const unsigned int* toks,
                             unsigned int num_toks,
                             SourceLocation* start,
                             SourceLocation* end,
                             llvm::SmallVectorImpl<char>& buffer,
                             bool stop_at_eos,
                             bool stop_at_ws)
{
    buffer.clear();
    *start = *end = m_token.getLocation();
    for (;;)
    {
        // If we found one of the tokens, stop.
        for (unsigned i = 0; i < num_toks; ++i)
        {
            if (m_token.is(toks[i]))
                goto done;
        }

        // If we hit end of statement, stop.
        if (stop_at_eos && m_token.isEndOfStatement())
            break;

        // Turn the token back into characters.
        // The first if's are optimizations for common cases.
        llvm::StringRef data;
        if (m_token.isLiteral())
        {
            data = m_token.getLiteral();
        }
        else if (m_token.is(Token::identifier) || m_token.is(Token::label))
        {
            IdentifierInfo* ii = m_token.getIdentifierInfo();
            data = ii->getName();
        }
        else
        {
            // Get the raw data from the source manager.
            SourceManager& smgr = m_preproc.getSourceManager();
            data =
                llvm::StringRef(smgr.getCharacterData(m_token.getLocation()),
                                m_token.getLength());
        }
        buffer.append(data.begin(), data.end());
        *end = m_token.getEndLocation();
        ConsumeAnyToken();

        // If we hit a token with leading space, stop.
        // We do this down here in case the first token had preceding ws.
        if (stop_at_ws && m_token.hasLeadingSpace())
            break;
    }
done:
    return llvm::StringRef(buffer.data(), buffer.size());
}
// getIdentifierInfo - Given a Name and a range of tokens, find the associated
// IdentifierInfo*.
static IdentifierInfo *getIdentifierInfo(StringRef Name,
                                         ArrayRef<Token> AsmToks,
                                         unsigned Begin, unsigned End) {
  for (unsigned i = Begin; i <= End; ++i) {
    IdentifierInfo *II = AsmToks[i].getIdentifierInfo();
    if (II && II->getName() == Name)
      return II;
  }
  return 0;
}
Example #25
0
static std::string getFunctionName(const Decl *D) {
  if (const ObjCMethodDecl *ID = dyn_cast<ObjCMethodDecl>(D)) {
    return ID->getSelector().getAsString();
  }
  if (const FunctionDecl *ND = dyn_cast<FunctionDecl>(D)) {
    IdentifierInfo *II = ND->getIdentifier();
    if (II)
      return II->getName();
  }
  return "";
}
void PHPZPPCheckerImpl::initIdentifierInfo(ASTContext &Ctx) const {
  if (IIzpp)
    return;

  IIzpp = &Ctx.Idents.get("zend_parse_parameters");
  IIzpp_ex = &Ctx.Idents.get("zend_parse_parameters_ex");
  IIzpmp = &Ctx.Idents.get("zend_parse_method_parameters");
  IIzpmp_ex = &Ctx.Idents.get("zend_parse_method_parameters_ex");

  IdentifierInfo *tsrm = &Ctx.Idents.get("ZTS");
  TSRMBuild = tsrm->hasMacroDefinition();
}
Example #27
0
/// EvaluateDefined - Process a 'defined(sym)' expression.
static bool EvaluateDefined(PPValue &Result, Token &PeekTok,
        DefinedTracker &DT, bool ValueLive, Preprocessor &PP) {
  IdentifierInfo *II;
  Result.setBegin(PeekTok.getLocation());

  // Get the next token, don't expand it.
  PP.LexUnexpandedToken(PeekTok);

  // Two options, it can either be a pp-identifier or a (.
  SourceLocation LParenLoc;
  if (PeekTok.is(tok::l_paren)) {
    // Found a paren, remember we saw it and skip it.
    LParenLoc = PeekTok.getLocation();
    PP.LexUnexpandedToken(PeekTok);
  }

  // If we don't have a pp-identifier now, this is an error.
  if ((II = PeekTok.getIdentifierInfo()) == 0) {
    PP.Diag(PeekTok, diag::err_pp_defined_requires_identifier);
    return true;
  }

  // Otherwise, we got an identifier, is it defined to something?
  Result.Val = II->hasMacroDefinition();
  Result.Val.setIsUnsigned(false);  // Result is signed intmax_t.

  // If there is a macro, mark it used.
  if (Result.Val != 0 && ValueLive) {
    MacroInfo *Macro = PP.getMacroInfo(II);
    Macro->setIsUsed(true);
  }

  // Consume identifier.
  Result.setEnd(PeekTok.getLocation());
  PP.LexNonComment(PeekTok);

  // If we are in parens, ensure we have a trailing ).
  if (LParenLoc.isValid()) {
    if (PeekTok.isNot(tok::r_paren)) {
      PP.Diag(PeekTok.getLocation(), diag::err_pp_missing_rparen) << "defined";
      PP.Diag(LParenLoc, diag::note_matching) << "(";
      return true;
    }
    // Consume the ).
    Result.setEnd(PeekTok.getLocation());
    PP.LexNonComment(PeekTok);
  }

  // Success, remember that we saw defined(X).
  DT.State = DefinedTracker::DefinedMacro;
  DT.TheMacro = II;
  return false;
}
Example #28
0
static StringRef getCalleeName(ProgramStateRef State,
                               const CallExpr *CE,
                               const LocationContext *LCtx) {
  const Expr *Callee = CE->getCallee();
  SVal L = State->getSVal(Callee, LCtx);
  const FunctionDecl *funDecl =  L.getAsFunctionDecl();
  if (!funDecl)
    return StringRef();
  IdentifierInfo *funI = funDecl->getIdentifier();
  if (!funI)
    return StringRef();
  return funI->getName();
}
void 
PragmaOpenCLExtensionHandler::HandlePragma(Preprocessor &PP, 
                                           PragmaIntroducerKind Introducer,
                                           Token &Tok) {
  PP.LexUnexpandedToken(Tok);
  if (Tok.isNot(tok::identifier)) {
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) <<
      "OPENCL";
    return;
  }
  IdentifierInfo *ename = Tok.getIdentifierInfo();
  SourceLocation NameLoc = Tok.getLocation();

  PP.Lex(Tok);
  if (Tok.isNot(tok::colon)) {
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_colon) << ename;
    return;
  }

  PP.Lex(Tok);
  if (Tok.isNot(tok::identifier)) {
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_enable_disable);
    return;
  }
  IdentifierInfo *op = Tok.getIdentifierInfo();

  unsigned state;
  if (op->isStr("enable")) {
    state = 1;
  } else if (op->isStr("disable")) {
    state = 0;
  } else {
    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_enable_disable);
    return;
  }

  OpenCLOptions &f = Actions.getOpenCLOptions();
  // OpenCL 1.1 9.1: "The all variant sets the behavior for all extensions,
  // overriding all previously issued extension directives, but only if the
  // behavior is set to disable."
  if (state == 0 && ename->isStr("all")) {
#define OPENCLEXT(nm)   f.nm = 0;
#include "clang/Basic/OpenCLExtensions.def"
  }
#define OPENCLEXT(nm) else if (ename->isStr(#nm)) { f.nm = state; }
#include "clang/Basic/OpenCLExtensions.def"
  else {
    PP.Diag(NameLoc, diag::warn_pragma_unknown_extension) << ename;
    return;
  }
}
Example #30
0
/// \brief Returns a diagnostic message kind for reporting a future keyword as
/// appropriate for the identifier and specified language.
static diag::kind getFutureCompatDiagKind(const IdentifierInfo &II,
                                          const LangOptions &LangOpts) {
  assert(II.isFutureCompatKeyword() && "diagnostic should not be needed");

  if (LangOpts.CPlusPlus)
    return llvm::StringSwitch<diag::kind>(II.getName())
#define CXX11_KEYWORD(NAME, FLAGS)                                             \
        .Case(#NAME, diag::warn_cxx11_keyword)
#include "clang/Basic/TokenKinds.def"
        ;

  llvm_unreachable(
      "Keyword not known to come from a newer Standard or proposed Standard");
}