/// <summary> /// The execute transaction inner. /// </summary> /// <param name="solution"> /// The solution. /// </param> /// <param name="textControl"> /// The text control. /// </param> public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl) { IList <ITokenNode> tokensForLine = Utils.GetTokensForLineFromTextControl(solution, textControl); foreach (ITokenNode tokenNode in tokensForLine) { ITypeArgumentList typeArgumentListNode = tokenNode.GetContainingNode <ITypeArgumentList>(true); if (typeArgumentListNode != null) { ReadabilityRules.SwapToBuiltInTypeAlias(typeArgumentListNode); } IObjectCreationExpression objectCreationExpressionNode = tokenNode.GetContainingNode <IObjectCreationExpression>(true); if (objectCreationExpressionNode != null) { ReadabilityRules.SwapToBuiltInTypeAlias(objectCreationExpressionNode); } IArrayCreationExpression arrayCreationExpressionNode = tokenNode.GetContainingNode <IArrayCreationExpression>(true); if (arrayCreationExpressionNode != null) { ReadabilityRules.SwapToBuiltInTypeAlias(arrayCreationExpressionNode); } IMethodDeclaration methodDeclaration = tokenNode.GetContainingNode <IMethodDeclaration>(true); if (methodDeclaration != null) { ReadabilityRules.SwapToBuiltInTypeAlias(methodDeclaration); } IVariableDeclaration variableDeclaration = tokenNode.GetContainingNode <IVariableDeclaration>(true); if (variableDeclaration != null) { ReadabilityRules.SwapToBuiltInTypeAlias(variableDeclaration); } IMultipleDeclaration multipleDeclarationNode = tokenNode.GetContainingNode <IMultipleDeclaration>(true); if (multipleDeclarationNode != null) { ReadabilityRules.SwapToBuiltInTypeAlias(multipleDeclarationNode); } } }
/// <summary> /// Swap object creation to built in type. /// </summary> /// <param name="objectCreationExpressionNode"> /// The object creation expression node. /// </param> private static void SwapObjectCreationToBuiltInType(IObjectCreationExpression objectCreationExpressionNode) { IPsiModule project = objectCreationExpressionNode.GetPsiModule(); using (WriteLockCookie.Create(true)) { IObjectCreationExpression tmpExpression = (IObjectCreationExpression) CSharpElementFactory.GetInstance(project).CreateExpression("new $0?()", new object[] { objectCreationExpressionNode.Type() }); if (tmpExpression != null) { objectCreationExpressionNode.SetCreatedTypeUsage(tmpExpression.CreatedTypeUsage); } } }
public override void VisitObjectCreationExpression(IObjectCreationExpression operation) { var ctor = operation.Constructor; if (ctor != null) { foreach (var parameter in ctor.Parameters) { var matchingArgument = operation.GetArgumentMatchingParameter(parameter); Visit(matchingArgument); } } base.VisitObjectCreationExpression(operation); }
private void AnalyzeObjectCreationForXmlReaderSettings(ISymbol variable, IObjectCreationExpression objCreation) { XmlReaderSettingsEnvironment xmlReaderSettingsEnv = new XmlReaderSettingsEnvironment(_isFrameworkSecure); if (variable != null) { _xmlReaderSettingsEnvironments[variable] = xmlReaderSettingsEnv; } xmlReaderSettingsEnv.XmlReaderSettingsDefinition = objCreation.Syntax; foreach (ISymbolInitializer init in objCreation.MemberInitializers) { var prop = init as IPropertyInitializer; if (prop != null) { if (SecurityDiagnosticHelpers.IsXmlReaderSettingsXmlResolverProperty( prop.InitializedProperty, _xmlTypes) ) { IConversionExpression operation = prop.Value as IConversionExpression; if (operation == null) { return; } if (SecurityDiagnosticHelpers.IsXmlSecureResolverType(operation.Operand.Type, _xmlTypes)) { xmlReaderSettingsEnv.IsSecureResolver = true; } else if (SecurityDiagnosticHelpers.IsExpressionEqualsNull(operation.Operand)) { xmlReaderSettingsEnv.IsSecureResolver = true; } } else if (SecurityDiagnosticHelpers.IsXmlReaderSettingsDtdProcessingProperty(prop.InitializedProperty, _xmlTypes)) { xmlReaderSettingsEnv.IsDtdProcessingDisabled = !SecurityDiagnosticHelpers.IsExpressionEqualsDtdProcessingParse(prop.Value); } else if (SecurityDiagnosticHelpers.IsXmlReaderSettingsMaxCharactersFromEntitiesProperty(prop.InitializedProperty, _xmlTypes)) { xmlReaderSettingsEnv.IsMaxCharactersFromEntitiesLimited = !SecurityDiagnosticHelpers.IsExpressionEqualsIntZero(prop.Value); } } } }
public Action <ITextControl> FillCurrentParameterWithMock(string shortName, IArgumentList argumentList, IObjectCreationExpression selectedElement, int parameterNumber, ICSharpContextActionDataProvider dataProvider) { var argument = dataProvider.ElementFactory.CreateArgument(ParameterKind.VALUE, dataProvider.ElementFactory.CreateExpression($"{shortName}.Object")); ICSharpArgument arg; var shouldRemoveEndComma = true; if (argumentList.Arguments.Count <= 1) { arg = selectedElement.AddArgumentAfter(argument, null); } else if (parameterNumber != 0) { arg = selectedElement.AddArgumentAfter(argument, argumentList.Arguments[parameterNumber - 1]); } else { arg = selectedElement.AddArgumentBefore(argument, argumentList.Arguments[1]); shouldRemoveEndComma = false; } var argumentRange = arg.GetDocumentRange(); // Remove last comma Hack! return(textControl => { TextRange range; if (shouldRemoveEndComma) { range = new TextRange(argumentRange.EndOffset.Offset, argumentRange.EndOffset.Offset + 1); } else { range = new TextRange(argumentRange.StartOffset.Offset - 2, argumentRange.StartOffset.Offset); } var text = textControl.Document.GetText(range); if (text.Contains(",")) { textControl.Document.DeleteText(range); } }); }
public void Process(IObjectCreationExpression objectCreationExpression) { if (IsValid() == false) { return; } if (objectCreationExpression == null) { return; } Logger.Assert(BlockModelsStack.Count > 0, "[Exceptional] There is no block for invocation statement."); var containingBlockModel = BlockModelsStack.Peek(); containingBlockModel.ThrownExceptions.Add( new ObjectCreationExpressionModel(AnalyzeUnit, objectCreationExpression, containingBlockModel)); }
private static void CheckObjectCreation([NotNull] IObjectCreationExpression objectCreation, [NotNull] IHighlightingConsumer consumer) { var typeReference = objectCreation.TypeReference; if (typeReference == null) { return; } if (objectCreation.IsInTheContextWhereAllocationsAreNotImportant()) { return; } var newKeyword = objectCreation.NewKeyword.NotNull(); var typeElement = typeReference.Resolve().DeclaredElement as ITypeElement; var typeParameter = typeElement as ITypeParameter; if (typeElement is IClass || typeParameter is { IsReferenceType : true })
public static bool IsContructor(IObjectCreationExpression creationExpression, out IConstructor constructor) { constructor = null; try { if (creationExpression.Reference == null) { return false; } var resolveResult = creationExpression.Reference.Resolve(); constructor = resolveResult.DeclaredElement as IConstructor; return constructor != null; } catch (Exception exn) { Debug.WriteLine(exn); return false; } }
private static string GetNameFromDeclaration(IObjectCreationExpression expr) { var constructedType = expr.GetExpressionType().ToIType().GetName(); if (expr.Parent != null) { var assignExpr = expr.Parent as IAssignmentExpression; if (assignExpr != null) { if (assignExpr.Dest.IsClassifiedAsVariable) { var refExpr = assignExpr.Dest as IReferenceExpression; if (refExpr != null) { var expectedType = refExpr.GetExpressionType().ToIType().GetName(); if (constructedType.Equals(expectedType)) { return(refExpr.NameIdentifier.Name); } } } } var varDecl = expr.Parent.Parent as ILocalVariableDeclaration; if (varDecl != null) { var expectedType = varDecl.DeclaredElement.Type.GetName(); var isSameType = constructedType.Equals(expectedType); if (varDecl.IsVar || isSameType) { var nameFromAssign = varDecl.NameIdentifier; return(nameFromAssign.Name); } } } return(null); }
public virtual IClass GetCreationClass([NotNull] IObjectCreationExpression creationExpression) { if (creationExpression == null) { throw new ArgumentNullException("creationExpression"); } if (creationExpression.TypeReference != null) { if (creationExpression.TypeReference.CurrentResolveResult != null) { return(creationExpression.TypeReference.CurrentResolveResult.DeclaredElement as IClass); } else { throw new ExpressionHelperException("Null type reference of creation expression", creationExpression); } } else { throw new ExpressionHelperException("Null resolved result of creation expression", creationExpression); } }
private void AnalyzeObjectCreationForXmlTextReader(OperationAnalysisContext context, ISymbol variable, IObjectCreationExpression objCreation) { XmlTextReaderEnvironment env; if (variable == null || !_xmlTextReaderEnvironments.TryGetValue(variable, out env)) { env = new XmlTextReaderEnvironment(_isFrameworkSecure) { XmlTextReaderDefinition = objCreation.Syntax }; } if (objCreation.Constructor.ContainingType != _xmlTypes.XmlTextReader) { env.IsDtdProcessingDisabled = true; env.IsSecureResolver = true; } foreach (ISymbolInitializer init in objCreation.MemberInitializers) { var prop = init as IPropertyInitializer; if (prop != null) { IConversionExpression operation = prop.Value as IConversionExpression; if (operation != null && SecurityDiagnosticHelpers.IsXmlTextReaderXmlResolverPropertyDerived(prop.InitializedProperty, _xmlTypes)) { env.IsXmlResolverSet = true; if (SecurityDiagnosticHelpers.IsXmlSecureResolverType(operation.Operand.Type, _xmlTypes)) { env.IsSecureResolver = true; } else if (SecurityDiagnosticHelpers.IsExpressionEqualsNull(operation.Operand)) { env.IsSecureResolver = true; } else { env.IsSecureResolver = false; } } else if (SecurityDiagnosticHelpers.IsXmlTextReaderDtdProcessingPropertyDerived(prop.InitializedProperty, _xmlTypes)) { env.IsDtdProcessingSet = true; env.IsDtdProcessingDisabled = !SecurityDiagnosticHelpers.IsExpressionEqualsDtdProcessingParse(prop.Value); } } } // if the XmlResolver or Dtdprocessing property is explicitly set when created, and is to an insecure value, generate a warning if ((env.IsXmlResolverSet && !env.IsSecureResolver) || (env.IsDtdProcessingSet && !env.IsDtdProcessingDisabled)) { Diagnostic diag = Diagnostic.Create( RuleDoNotUseInsecureDtdProcessing, env.XmlTextReaderDefinition.GetLocation(), SecurityDiagnosticHelpers.GetLocalizableResourceString( nameof(DesktopAnalyzersResources.XmlTextReaderSetInsecureResolutionMessage) ) ); context.ReportDiagnostic(diag); } // if the XmlResolver or Dtdprocessing property is not explicitly set when constructed for a non-temp XmlTextReader object, add env to the dictionary. else if (variable != null && !(env.IsDtdProcessingSet && env.IsXmlResolverSet)) { _xmlTextReaderEnvironments[variable] = env; } // if the is not set or set to Parse for a temporary object, report right now. else if (variable == null && !(env.IsDtdProcessingSet && env.IsXmlResolverSet && env.IsDtdProcessingDisabled && env.IsSecureResolver)) { Diagnostic diag = Diagnostic.Create( RuleDoNotUseInsecureDtdProcessing, env.XmlTextReaderDefinition.GetLocation(), SecurityDiagnosticHelpers.GetLocalizableResourceString( nameof(DesktopAnalyzersResources.XmlTextReaderConstructedWithNoSecureResolutionMessage) ) ); context.ReportDiagnostic(diag); } }
private static IMemberElement getObjectCreationExpression_MemberElement(IObjectCreationExpression creationExp) { foreach (var child in creationExp.ObjectType.GetDeclaration().AllChildren) { IMethodElement childMethod = (child as IMethodElement); if ((childMethod != null) && (childMethod.IsConstructor)) { if (creationExp.Arguments.Count == childMethod.Parameters.Count) { if (creationExp.Arguments.Count == 0) return childMethod; for (int i = 0; i < childMethod.Parameters.Count; i++) { if (creationExp.Arguments[i].Is(childMethod.Parameters[i].Type.GetDeclaration() as ITypeElement)) return childMethod; } } } } return null; }
public override void VisitObjectCreationExpression(IObjectCreationExpression operation) { VisitArray(operation.ArgumentsInEvaluationOrder); VisitArray(operation.Initializers); }
public override void VisitObjectCreationExpression(IObjectCreationExpression operation) { VisitArray(operation.ConstructorArguments); VisitArray(operation.MemberInitializers); }
public override void VisitObjectCreationExpression(IObjectCreationExpression operation) { VisitArray(operation.ArgumentsInParameterOrder); VisitArray(operation.MemberInitializers); }
public override bool IsAvailable(IUserDataHolder cache) { var testProjectProvider = ComponentResolver.GetComponent <ITestProjectProvider>(_dataProvider); if (!testProjectProvider.IsTestProject(_dataProvider.PsiModule)) { return(false); } _csharpMemberProvider = ComponentResolver.GetComponent <ICsharpMemberProvider>(_dataProvider); _selectedElement = _dataProvider.GetSelectedElement <IObjectCreationExpression>(false, false); _block = _dataProvider.GetSelectedElement <IBlock>(); _classBody = _dataProvider.GetSelectedElement <IClassBody>(); _classDeclaration = _classBody?.GetContainingTypeDeclaration() as IClassLikeDeclaration; if (_classDeclaration == null || _block == null || _selectedElement == null) { return(false); } if (!(_selectedElement.TypeReference?.Resolve().DeclaredElement is IClass c)) { return(false); } var parameterCount = _selectedElement.ArgumentList?.Arguments.Count(x => x.Kind != ParameterKind.UNKNOWN); _constructor = c.Constructors.ToArray().FirstOrDefault(x => !x.IsParameterless && x.Parameters.Count > parameterCount); if (_constructor == null) { return(false); } var previousTokenType = _dataProvider.TokenBeforeCaret?.NodeType as ITokenNodeType; var nextTokenType = _dataProvider.TokenAfterCaret?.NodeType as ITokenNodeType; if (previousTokenType == null || nextTokenType == null) { return(false); } if (previousTokenType.TokenRepresentation == " ") { previousTokenType = _dataProvider.PsiFile.FindTokenAt(_dataProvider.TokenBeforeCaret.GetTreeStartOffset() - 1)?.NodeType as ITokenNodeType; } if (nextTokenType.TokenRepresentation == " ") { nextTokenType = _dataProvider.PsiFile.FindTokenAt(_dataProvider.TokenBeforeCaret.GetTreeEndOffset() + 1)?.NodeType as ITokenNodeType; } if (previousTokenType == null || nextTokenType == null) { return(false); } var isAvailable = false; if (previousTokenType.TokenRepresentation == "(") { isAvailable = nextTokenType.TokenRepresentation == ")" || nextTokenType.TokenRepresentation == ","; } else if (previousTokenType.TokenRepresentation == ",") { isAvailable = !nextTokenType.IsIdentifier; } if (!isAvailable) { return(false); } _parameterNumber = _csharpMemberProvider.GetCurrentParameterNumber(_selectedElement, _dataProvider); var parameter = _constructor.Parameters[_parameterNumber]; if (!_csharpMemberProvider.IsAbstractOrInterface(parameter)) { return(false); } cache.PutKey(AnchorKey.FillParamWithMockContextActionKey); return(true); }
/// <inheritdoc /> public override IOperation VisitObjectCreationExpression(IObjectCreationExpression operation, object argument) { return(base.VisitObjectCreationExpression(operation, argument)); }
/// <inheritdoc /> public override Expression VisitObjectCreationExpression(IObjectCreationExpression operation, LocalBinder argument) { return(base.VisitObjectCreationExpression(operation, argument)); }
private static void AddMocksToClassDeclaration(IMethodDeclaration methodDeclaration, IObjectCreationExpression ctorExpression, MockInfo[] mockInfos, IClassDeclaration classDeclaration, CSharpElementFactory factory) { var ctorStatement = methodDeclaration.Body.Statements .FirstOrDefault(x => { var expression = (x as IExpressionStatement)?.Expression; if (expression != null && (expression == ctorExpression || (expression as IAssignmentExpression)?.Source == ctorExpression)) { return(true); } var declarationStatement = (x as IDeclarationStatement); if (declarationStatement?.VariableDeclarations.Any(varDeclaration => (varDeclaration.Initial as IExpressionInitializer)?.Value == ctorExpression) ?? false) { return(true); } return(false); }); foreach (var mockInfo in mockInfos) { classDeclaration.AddMemberDeclaration(mockInfo.Type, mockInfo.Name, factory, m => m.All(x => x.DeclaredName != mockInfo.Name)); var elementHasAssigned = methodDeclaration.Body.Statements.Any(x => { var assignmentOperands = ((x as IExpressionStatement)?.Expression as IAssignmentExpression)?.OperatorOperands; return(assignmentOperands != null && assignmentOperands.Any(operand => (operand as IReferenceExpression)?.NameIdentifier.Name == mockInfo.Name)); }); if (!elementHasAssigned) { methodDeclaration.Body.AddStatementBefore(mockInfo.Statement, ctorStatement); } } }
/// <summary>Handles the specified expression.</summary> /// <param name="creationExpression">The invocation expression.</param> /// <param name="statementParameters">The parameters.</param> /// <returns>Returns the string.</returns> public ExpressionDescriptor Handle(IObjectCreationExpression creationExpression, Dictionary<string, string> statementParameters) { string variableName; if (!statementParameters.TryGetValue("VariableName", out variableName)) { variableName = string.Empty; } var typeName = creationExpression.TypeName; if (typeName == null) { return null; } var result = new ExpressionDescriptor { Template = creationExpression.NewKeyword.GetTokenType().TokenRepresentation + " " }; var qualifiedName = string.Empty; var resolveResult = typeName.Reference.Resolve(); if (resolveResult.IsValid()) { var declaredElement = resolveResult.DeclaredElement; var typeElement = declaredElement as ITypeElement; if (typeElement != null) { qualifiedName = typeElement.ShortName; var ns = typeElement.GetContainingNamespace(); if (!string.IsNullOrEmpty(ns.QualifiedName)) { qualifiedName = ns.QualifiedName + "." + qualifiedName; } } } if (string.IsNullOrEmpty(qualifiedName)) { qualifiedName = typeName.QualifiedName; } result.Template += qualifiedName + "("; var index = 0; foreach (var argument in creationExpression.Arguments) { var parameter = argument.MatchingParameter; if (parameter == null) { continue; } var parameterName = parameter.Element.ShortName; if (index > 0) { result.Template += ", "; } index++; var argumentText = argument.GetText(); if (argumentText == variableName) { result.Template += "$VariableName$"; continue; } /* if (argument.Value.IsConstantValue()) { var constantValue = argument.Value.ConstantValue; result.Template += "$" + parameterName + "$"; string s; if (constantValue.IsPureNull(argument.Language)) { s = "null"; } else { s = constantValue.Value.ToString().Replace(",", ",").Replace(",", """); if (constantValue.IsString()) { s = "\"" + s + "\""; } } result.TemplateVariables[parameterName] = "c:" + s; continue; } */ result.Template += "$" + parameterName + "$"; result.TemplateVariables[parameterName] = string.Empty; } result.Template += ")"; return result; }
public override IOperation VisitObjectCreationExpression(IObjectCreationExpression operation, object argument) { return(new ObjectCreationExpression(operation.Constructor, Visit(operation.Initializer), VisitArray(operation.ArgumentsInEvaluationOrder), ((Operation)operation).SemanticModel, operation.Syntax, operation.Type, operation.ConstantValue, operation.IsImplicit)); }
public bool IsAvailable(IUserDataHolder cache) { this.creationExpression = this.provider.GetSelectedElement<IObjectCreationExpression>(true, true); createdClassName = creationExpression.TypeName.ShortName; return creationExpression != null; }
private void AnalyzeObjectCreationForXmlTextReader(OperationAnalysisContext context, ISymbol variable, IObjectCreationExpression objCreation) { if (variable == null || !_xmlTextReaderEnvironments.TryGetValue(variable, out XmlTextReaderEnvironment env)) { env = new XmlTextReaderEnvironment(_isFrameworkSecure) { XmlTextReaderDefinition = objCreation.Syntax }; } if (objCreation.Constructor.ContainingType != _xmlTypes.XmlTextReader) { env.IsDtdProcessingDisabled = true; env.IsSecureResolver = true; } foreach (ISymbolInitializer init in objCreation.MemberInitializers) { if (init is IPropertyInitializer prop) { if (prop.Value is IConversionExpression operation && SecurityDiagnosticHelpers.IsXmlTextReaderXmlResolverPropertyDerived(prop.InitializedProperty, _xmlTypes)) { env.IsXmlResolverSet = true; if (SecurityDiagnosticHelpers.IsXmlSecureResolverType(operation.Operand.Type, _xmlTypes)) { env.IsSecureResolver = true; } else if (SecurityDiagnosticHelpers.IsExpressionEqualsNull(operation.Operand)) { env.IsSecureResolver = true; } else { env.IsSecureResolver = false; } } else if (SecurityDiagnosticHelpers.IsXmlTextReaderDtdProcessingPropertyDerived(prop.InitializedProperty, _xmlTypes)) { env.IsDtdProcessingSet = true; env.IsDtdProcessingDisabled = !SecurityDiagnosticHelpers.IsExpressionEqualsDtdProcessingParse(prop.Value); } } }
public override void VisitObjectCreationExpression(IObjectCreationExpression operation) { var ctor = operation.Constructor; base.VisitObjectCreationExpression(operation); }
public ConvertToGameObjectAddComponentQuickFix(IncorrectMonoBehaviourInstantiationWarning warning) { myWarningCreationExpression = warning.CreationExpression; }
/// <summary> /// Swap object creation to built in type. /// </summary> /// <param name="objectCreationExpressionNode"> /// The object creation expression node. /// </param> private static void SwapObjectCreationToBuiltInType(IObjectCreationExpression objectCreationExpressionNode) { IPsiModule project = objectCreationExpressionNode.GetPsiModule(); using (WriteLockCookie.Create(true)) { IObjectCreationExpression tmpExpression = (IObjectCreationExpression) CSharpElementFactory.GetInstance(project).CreateExpression("new $0?()", new object[] { objectCreationExpressionNode.Type() }); objectCreationExpressionNode.SetCreatedTypeUsage(tmpExpression.CreatedTypeUsage); } }
public static IObjectCreationExpression Update(this IObjectCreationExpression self, IMethodSymbol @constructor, ImmutableArray <ISymbol> @constructorsGroup, ImmutableArray <IOperation> @arguments, ImmutableArray <String> @argumentNamesOpt, ImmutableArray <RefKind> @argumentRefKindsOpt, Boolean @expanded, ImmutableArray <Int32> @argsToParamsOpt, Object @constantValueOpt, IOperation @initializerExpressionOpt, Object @binderOpt, ITypeSymbol @type) => self;
private void AnalyzeObjectCreationForXmlDocument(OperationAnalysisContext context, ISymbol variable, IObjectCreationExpression objCreation) { XmlDocumentEnvironment xmlDocumentEnvironment; if (variable == null || !_xmlDocumentEnvironments.ContainsKey(variable)) { xmlDocumentEnvironment = new XmlDocumentEnvironment { IsSecureResolver = false, IsXmlResolverSet = false }; } else { xmlDocumentEnvironment = _xmlDocumentEnvironments[variable]; } xmlDocumentEnvironment.XmlDocumentDefinition = objCreation.Syntax; SyntaxNode node = objCreation.Syntax; bool isXmlDocumentSecureResolver = false; if (objCreation.Constructor.ContainingType != _xmlTypes.XmlDocument) { isXmlDocumentSecureResolver = true; } // propertyInitlizer is not returned any more // and no way to get propertysymbol foreach (IOperation init in objCreation.Initializers) { if (init is IAssignmentExpression assign) { var propValue = assign.Value; IPropertySymbol prop = context.Compilation.GetSemanticModel(context.Operation.Syntax.SyntaxTree)?.GetSymbolInfo(assign.Target.Syntax).Symbol as IPropertySymbol; if (prop == null) { continue; } if (prop.MatchPropertyDerivedByName(_xmlTypes.XmlDocument, "XmlResolver")) { IConversionExpression operation = propValue as IConversionExpression; if (operation == null) { return; } if (SecurityDiagnosticHelpers.IsXmlSecureResolverType(operation.Operand.Type, _xmlTypes)) { isXmlDocumentSecureResolver = true; } else if (SecurityDiagnosticHelpers.IsExpressionEqualsNull(operation.Operand)) { isXmlDocumentSecureResolver = true; } else // Non secure resolvers { if (operation.Operand is IObjectCreationExpression xmlResolverObjCreated) { Diagnostic diag = Diagnostic.Create( RuleDoNotUseInsecureDtdProcessing, prop.Locations[0], SecurityDiagnosticHelpers.GetLocalizableResourceString( nameof(MicrosoftNetFrameworkAnalyzersResources.XmlDocumentWithNoSecureResolverMessage) ) ); context.ReportDiagnostic(diag); } return; } } else { AnalyzeNeverSetProperties(context, prop, prop.Locations[0]); } } } xmlDocumentEnvironment.IsSecureResolver = isXmlDocumentSecureResolver; if (variable != null) { _xmlDocumentEnvironments[variable] = xmlDocumentEnvironment; } else if (!xmlDocumentEnvironment.IsSecureResolver) // Insecure temp object { Diagnostic diag = Diagnostic.Create( RuleDoNotUseInsecureDtdProcessing, node.GetLocation(), SecurityDiagnosticHelpers.GetLocalizableResourceString( nameof(MicrosoftNetFrameworkAnalyzersResources.XmlDocumentWithNoSecureResolverMessage) ) ); context.ReportDiagnostic(diag); } }
public override void Initialize(AnalysisContext analysisContext) { analysisContext.EnableConcurrentExecution(); analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze); analysisContext.RegisterCompilationStartAction(startContext => { var instantiatedTypes = new ConcurrentBag <INamedTypeSymbol>(); var internalTypes = new ConcurrentBag <INamedTypeSymbol>(); Compilation compilation = startContext.Compilation; // If the assembly being built by this compilation exposes its internals to // any other assembly, don't report any "uninstantiated internal class" errors. // If we were to report an error for an internal type that is not instantiated // by this assembly, and then it turned out that the friend assembly did // instantiate the type, that would be a false positive. We've decided it's // better to have false negatives (which would happen if the type were *not* // instantiated by any friend assembly, but we didn't report the issue) than // to have false positives. INamedTypeSymbol internalsVisibleToAttributeSymbol = compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.InternalsVisibleToAttribute"); if (AssemblyExposesInternals(compilation, internalsVisibleToAttributeSymbol)) { return; } INamedTypeSymbol systemAttributeSymbol = compilation.GetTypeByMetadataName("System.Attribute"); INamedTypeSymbol iConfigurationSectionHandlerSymbol = compilation.GetTypeByMetadataName("System.Configuration.IConfigurationSectionHandler"); INamedTypeSymbol configurationSectionSymbol = compilation.GetTypeByMetadataName("System.Configuration.ConfigurationSection"); INamedTypeSymbol safeHandleSymbol = compilation.GetTypeByMetadataName("System.Runtime.InteropServices.SafeHandle"); INamedTypeSymbol traceListenerSymbol = compilation.GetTypeByMetadataName("System.Diagnostics.TraceListener"); INamedTypeSymbol mef1ExportAttributeSymbol = compilation.GetTypeByMetadataName("System.ComponentModel.Composition.ExportAttribute"); INamedTypeSymbol mef2ExportAttributeSymbol = compilation.GetTypeByMetadataName("System.Composition.ExportAttribute"); startContext.RegisterOperationAction(context => { IObjectCreationExpression expr = (IObjectCreationExpression)context.Operation; var namedType = expr.Type as INamedTypeSymbol; if (namedType != null) { instantiatedTypes.Add(namedType); } }, OperationKind.ObjectCreationExpression); startContext.RegisterSymbolAction(context => { INamedTypeSymbol type = (INamedTypeSymbol)context.Symbol; if (type.GetResultantVisibility() != SymbolVisibility.Public && !IsOkToBeUnused(type, compilation, systemAttributeSymbol, iConfigurationSectionHandlerSymbol, configurationSectionSymbol, safeHandleSymbol, traceListenerSymbol, mef1ExportAttributeSymbol, mef2ExportAttributeSymbol)) { internalTypes.Add(type); } }, SymbolKind.NamedType); startContext.RegisterCompilationEndAction(context => { IEnumerable <INamedTypeSymbol> uninstantiatedInternalTypes = internalTypes .Except(instantiatedTypes) .Where(type => !HasInstantiatedNestedType(type, instantiatedTypes)); foreach (INamedTypeSymbol type in uninstantiatedInternalTypes) { context.ReportDiagnostic(type.CreateDiagnostic(Rule, type.FormatMemberName())); } }); }); }
public ConvertToScriptableObjectCreateInstanceQuickFix(IncorrectScriptableObjectInstantiationWarning warning) { myWarningCreationExpression = warning.CreationExpression; }
private void AnalyzeObjectCreationForXmlDocument(OperationAnalysisContext context, ISymbol variable, IObjectCreationExpression objCreation) { XmlDocumentEnvironment xmlDocumentEnvironment; if (variable == null || !_xmlDocumentEnvironments.ContainsKey(variable)) { xmlDocumentEnvironment = new XmlDocumentEnvironment { IsSecureResolver = false, IsXmlResolverSet = false }; } else { xmlDocumentEnvironment = _xmlDocumentEnvironments[variable]; } xmlDocumentEnvironment.XmlDocumentDefinition = objCreation.Syntax; SyntaxNode node = objCreation.Syntax; bool isXmlDocumentSecureResolver = false; if (objCreation.Constructor.ContainingType != _xmlTypes.XmlDocument) { isXmlDocumentSecureResolver = true; } foreach (ISymbolInitializer init in objCreation.MemberInitializers) { var prop = init as IPropertyInitializer; if (prop != null) { if (prop.InitializedProperty.MatchPropertyDerivedByName(_xmlTypes.XmlDocument, "XmlResolver")) { IConversionExpression operation = prop.Value as IConversionExpression; if (operation == null) { return; } if (SecurityDiagnosticHelpers.IsXmlSecureResolverType(operation.Operand.Type, _xmlTypes)) { isXmlDocumentSecureResolver = true; } else if (SecurityDiagnosticHelpers.IsExpressionEqualsNull(operation.Operand)) { isXmlDocumentSecureResolver = true; } else // Non secure resolvers { IObjectCreationExpression xmlResolverObjCreated = operation.Operand as IObjectCreationExpression; if (xmlResolverObjCreated != null) { Diagnostic diag = Diagnostic.Create( RuleDoNotUseInsecureDtdProcessing, prop.Syntax.GetLocation(), SecurityDiagnosticHelpers.GetLocalizableResourceString( nameof(DesktopAnalyzersResources.XmlDocumentWithNoSecureResolverMessage) ) ); context.ReportDiagnostic(diag); } return; } } else { AnalyzeNeverSetProperties(context, prop.InitializedProperty, prop.Syntax.GetLocation()); } } } xmlDocumentEnvironment.IsSecureResolver = isXmlDocumentSecureResolver; if (variable != null) { _xmlDocumentEnvironments[variable] = xmlDocumentEnvironment; } else if (!xmlDocumentEnvironment.IsSecureResolver) // Insecure temp object { Diagnostic diag = Diagnostic.Create( RuleDoNotUseInsecureDtdProcessing, node.GetLocation(), SecurityDiagnosticHelpers.GetLocalizableResourceString( nameof(DesktopAnalyzersResources.XmlDocumentWithNoSecureResolverMessage) ) ); context.ReportDiagnostic(diag); } }
public virtual void VisitObjectCreationExpression(IObjectCreationExpression operation) { DefaultVisit(operation); }
public CtorPropertyInitializerContextAction(ICSharpContextActionDataProvider provider) { this.provider = provider; factory = provider.ElementFactory; ctorExpression = provider.GetSelectedElement <IObjectCreationExpression>(); }
private void AnalyzeObjectCreationForXmlTextReader(OperationAnalysisContext context, ISymbol variable, IObjectCreationExpression objCreation) { if (variable == null || !_xmlTextReaderEnvironments.TryGetValue(variable, out XmlTextReaderEnvironment env)) { env = new XmlTextReaderEnvironment(_isFrameworkSecure) { XmlTextReaderDefinition = objCreation.Syntax }; } if (objCreation.Constructor.ContainingType != _xmlTypes.XmlTextReader) { env.IsDtdProcessingDisabled = true; env.IsSecureResolver = true; } foreach (IOperation init in objCreation.Initializers) { if (init is IAssignmentExpression assign) { var propValue = assign.Value; IPropertySymbol prop = context.Compilation.GetSemanticModel(context.Operation.Syntax.SyntaxTree)?.GetSymbolInfo(assign.Target.Syntax).Symbol as IPropertySymbol; if (prop == null) { continue; } if (propValue is IConversionExpression operation && SecurityDiagnosticHelpers.IsXmlTextReaderXmlResolverPropertyDerived(prop, _xmlTypes)) { env.IsXmlResolverSet = true; if (SecurityDiagnosticHelpers.IsXmlSecureResolverType(operation.Operand.Type, _xmlTypes)) { env.IsSecureResolver = true; } else if (SecurityDiagnosticHelpers.IsExpressionEqualsNull(operation.Operand)) { env.IsSecureResolver = true; } else { env.IsSecureResolver = false; } } else if (SecurityDiagnosticHelpers.IsXmlTextReaderDtdProcessingPropertyDerived(prop, _xmlTypes)) { env.IsDtdProcessingSet = true; env.IsDtdProcessingDisabled = !SecurityDiagnosticHelpers.IsExpressionEqualsDtdProcessingParse(propValue); } } }
public IncorrectMonoBehaviourInstantiationWarning(IObjectCreationExpression creationExpression) { CreationExpression = creationExpression; }
private static IColorReference ReferenceFromConstructor(IObjectCreationExpression constructorExpression) { var constructedType = constructorExpression.TypeReference?.Resolve().DeclaredElement as ITypeElement; if (constructedType == null) return null; var unityColorTypes = UnityColorTypes.GetInstance(constructedType.Module); if (!unityColorTypes.IsUnityColorType(constructedType)) return null; var arguments = constructorExpression.Arguments; if (arguments.Count < 3 || arguments.Count > 4) return null; Color? color = null; if (unityColorTypes.UnityColorType != null && unityColorTypes.UnityColorType.Equals(constructedType)) { var baseColor = GetColorFromFloatARGB(arguments); if (baseColor == null) return null; color = baseColor.Item1.HasValue ? Color.FromArgb((int) (255.0 * baseColor.Item1.Value), baseColor.Item2) : baseColor.Item2; } else if (unityColorTypes.UnityColor32Type != null && unityColorTypes.UnityColor32Type.Equals(constructedType)) { var baseColor = GetColorFromIntARGB(arguments); if (baseColor == null) return null; color = baseColor.Item1.HasValue ? Color.FromArgb(baseColor.Item1.Value, baseColor.Item2) : baseColor.Item2; } if (color == null) return null; var colorElement = new ColorElement(color.Value); var argumentList = constructorExpression.ArgumentList; return new UnityColorReference(colorElement, constructorExpression, argumentList, argumentList.GetDocumentRange()); }