Beispiel #1
0
        public static Entity Resolve <TNode>(
            GraphStructuredProgram <TNode> program,
            ResolvedMethod <TNode> method,
            Reference reference)
        {
            if (reference == null)
            {
                Console.Error.WriteLine("Null reference");
                return(null);
            }

            var type = reference.GetType();

            if (!Resolvers.ContainsKey(type))
            {
                Console.Error.WriteLine($"Cannot find resolver for reference type {type}");
            }

            var resolved = Resolvers[type].InternalResolve(program, method, reference);

            if (resolved == null)
            {
                Console.Error.WriteLine($"Reference of type {type} has been resolved as null");
            }

            return(resolved);
        }
Beispiel #2
0
        protected override Entity InternalResolve <TNode>(
            GraphStructuredProgram <TNode> program,
            ResolvedMethod <TNode> method,
            Reference reference)
        {
            var property = (ClassPropertyReference)reference;

            return(Resolve(program, method, new ClassFieldReference(property.Owner, property.Name)));
        }
Beispiel #3
0
 protected override bool Step(
     GraphStructuredProgram <TNode> targetProgram,
     ResolvedMethod <TNode> targetMethod,
     TNode source, Statement statement, TNode target,
     Func <TNode> nodeCreator)
 {
     targetProgram.AddOperation(source, new Operation <TNode>(statement, target));
     return(true);
 }
Beispiel #4
0
        protected override Entity InternalResolve <TNode>(
            GraphStructuredProgram <TNode> program,
            ResolvedMethod <TNode> method,
            Reference reference)
        {
            var real = (ClassReference)reference;

            return(program.GetOrCreateClass(real.ClassId).Id);
        }
        protected override Entity RestoreImplementation <TNode>(
            GraphStructuredProgram <TNode> program,
            ResolvedMethod <TNode> method,
            Entity entity)
        {
            var localFunctionReference = (ResolvedLocalFunctionReference <TNode>)entity;

            method.Methods.TryGetValue(localFunctionReference.MethodId, out var restored);
            localFunctionReference.Method = restored;
            return(localFunctionReference);
        }
Beispiel #6
0
        protected override Entity RestoreImplementation <TNode>(
            GraphStructuredProgram <TNode> program,
            ResolvedMethod <TNode> method,
            Entity entity)
        {
            var classField = (ResolvedClassField)entity;

            var clazz = program.FindClassById(classField.ClassId);

            return(clazz.GetOrCreateField(classField.VariableId));
        }
Beispiel #7
0
        protected override Entity RestoreImplementation <TNode>(
            GraphStructuredProgram <TNode> program,
            ResolvedMethod <TNode> method,
            Entity entity)
        {
            var classMethodReference = (ResolvedClassMethodReference <TNode>)entity;

            classMethodReference.Method =
                program.FindMethodById(classMethodReference.OwnerId, classMethodReference.MethodId);

            return(classMethodReference);
        }
Beispiel #8
0
        public static Entity Restore <TNode>(
            GraphStructuredProgram <TNode> program,
            ResolvedMethod <TNode> method,
            Entity entity)
        {
            var exists = RegisteredRestorers.TryGetValue(entity.GetType(), out var restorer);

            if (exists)
            {
                return(restorer.RestoreImplementation(program, method, entity));
            }

            return(entity);
        }
Beispiel #9
0
        public static InternalStatement Restore <TNode>(
            GraphStructuredProgram <TNode> program,
            ResolvedMethod <TNode> method,
            InternalStatement statement)
        {
            var exists = RegisteredRestorers.TryGetValue(statement.InternalType, out var restorer);

            if (exists)
            {
                return(restorer.RestoreImplementation(program, method, statement));
            }

            return(statement);
        }
Beispiel #10
0
        public static ApiMemberInfo Describe(this ResolvedMethod src)
        {
            var dst  = new ApiMemberInfo();
            var msil = ClrDynamic.msil(src.EntryPoint, src.Uri, src.Method);

            dst.EntryPoint = src.EntryPoint;
            dst.ApiKind    = src.Method.KindId();
            dst.CliSig     = msil.CliSig;
            dst.DisplaySig = src.Method.DisplaySig().Format();
            dst.Token      = msil.Token;
            dst.Uri        = src.Uri.Format();
            dst.MsilCode   = msil.Code;
            return(dst);
        }
        private void RestoreLocalFunctionsVariables(ResolvedMethod <TNode> root)
        {
            foreach (var localFunction in root.Methods.Values)
            {
                foreach (var localFunctionVariable in localFunction.Variables.Keys.ToList())
                {
                    if (root.Variables.ContainsKey(localFunctionVariable))
                    {
                        localFunction.RemoveLocalVariable(localFunctionVariable);
                        localFunction.AddLocalVariable(root.Variables[localFunctionVariable]);
                    }
                }

                RestoreLocalFunctionsVariables(localFunction);
            }
        }
    private static void EnrichFastDemystify(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        ResolvedMethod callerMethod = null !;
        Type?          callerType   = null;
        {
            StackFrame[] frames          = new StackTrace().GetFrames();
            bool         gotToSerilogYet = false;
            for (int i = 0; i < frames.Length; i++)
            {
                MethodBase?tempCallerMethod = frames[i].GetMethod();

                if (tempCallerMethod is null)
                {
                    continue;
                }
                callerMethod = EnhancedStackTrace.GetMethodDisplayString(tempCallerMethod);
                callerType   = callerMethod.DeclaringType;
                if (callerType is null)
                {
                    continue;
                }

                bool isSerilog = callerType.Namespace?.StartsWith("Serilog") ?? false;
                switch (gotToSerilogYet)
                {
                case false when !isSerilog:
                    continue;

                case false:
                    gotToSerilogYet = true;
                    continue;
                }

                if (isSerilog)
                {
                    continue;
                }

                //Finally found the right number
                //https://youtu.be/Vy7RaQUmOzE?t=203
                break;
            }
        }

        //Now do the actual enriching, with nicer names
        string callingMethodStr = callerMethod.Name !;
        string callingTypeStr   = callerType is null ? "<Module>" : StringBuilderPool.BorrowInline(static (sb, callerType) => sb.AppendTypeDisplayName(callerType, false), callerType);
Beispiel #13
0
        protected override Entity RestoreImplementation <TNode>(
            GraphStructuredProgram <TNode> program,
            ResolvedMethod <TNode> method,
            Entity entity)
        {
            var objectMethodReference = (ResolvedObjectMethodReference <TNode>)entity;

            var restoredOwner = (SecondaryEntity)Restore(program, method, objectMethodReference.OwningObject);
            var restored      = new ResolvedObjectMethodReference <TNode>(restoredOwner, objectMethodReference.MethodId)
            {
                FindClassMethod = program.FindMethodById
            };

            method.StoreAdditionalVariable(restored);

            return(restored);
        }
Beispiel #14
0
        protected override InternalStatement RestoreImplementation <TNode>(
            GraphStructuredProgram <TNode> program,
            ResolvedMethod <TNode> method,
            InternalStatement statement)
        {
            var assignment = (ResolvedAssignmentStatement)statement;

            var source = EntitiesRestorer.Restore(program, method, assignment.Source);

            Trace.Assert(assignment.Target != null);
            var target = assignment.Target == null ? null : EntitiesRestorer.Restore(program, method, assignment.Target);

            Trace.Assert(target is SecondaryEntity);

            return(new ResolvedAssignmentStatement(
                       assignment.Location, source, (SecondaryEntity)target, assignment.TargetReferencedByThis));
        }
        protected override Entity InternalResolve <TNode>(
            GraphStructuredProgram <TNode> program,
            ResolvedMethod <TNode> sourceMethod,
            Reference reference)
        {
            var localFunctionReference = (LocalFunctionReference)reference;

            var methodId = program.GetOrCreateMethodId(localFunctionReference.MethodId.Value);
            var method   = sourceMethod.Methods[methodId];

            var resolvedReference = new ResolvedLocalFunctionReference <TNode>(methodId)
            {
                Method = method
            };

            return(resolvedReference);
        }
Beispiel #16
0
        protected override Entity RestoreImplementation <TNode>(
            GraphStructuredProgram <TNode> program,
            ResolvedMethod <TNode> method,
            Entity entity)
        {
            var localVariable = (ResolvedLocalVariable)entity;

            var exists = method.Variables.TryGetValue(localVariable.LocalId, out var variable);

            //Trace.Assert(exists);
            if (!exists)
            {
                method.AddLocalVariable(localVariable);
                variable = localVariable;
            }

            return(variable);
        }
Beispiel #17
0
        private bool InternalStep(
            GraphStructuredProgram <TNode> targetProgram,
            ResolvedMethod <TNode> targetMethod,
            TNode source,
            Statement statement,
            TNode target,
            Func <TNode> nodeCreator)
        {
            //TODO: Check steps order correctness
            var toContinue =
                myComposedWith?.InternalStep(targetProgram, targetMethod, source, statement, target, nodeCreator);

            if (toContinue == null || toContinue.Value)
            {
                return(Step(targetProgram, targetMethod, source, statement, target, nodeCreator));
            }

            return(false);
        }
Beispiel #18
0
        private Func <int, Node> GetLocalMapper(ResolvedMethod <Node> method)
        {
            var localToGlobalIndicesMap = new Dictionary <int, Node>();

            Node Map(int local)
            {
                var exists = localToGlobalIndicesMap.TryGetValue(local, out var global);

                if (!exists)
                {
                    global = myProgram.CreateNode();
                    method.AddOwnedNode(global);
                    localToGlobalIndicesMap.Add(local, global);
                }

                return(global);
            }

            return(Map);
        }
        private static void AppendMethod(this StringBuilder builder, ResolvedMethod method)
        {
            if (method.IsAsync)
            {
                builder.Append("async ");
            }

            if (method.ReturnParameter.Type != null)
            {
                builder
                .AppendParameter(method.ReturnParameter)
                .Append(" ");
            }

            var isSubMethodOrLambda = !string.IsNullOrEmpty(method.SubMethod) || method.IsLambda;

            builder
            .AppendMethodName(method.Name, method.DeclaringTypeName, isSubMethodOrLambda)
            .Append(method.GenericArguments)
            .AppendParameters(method.Parameters, method.MethodBase != null);

            if (isSubMethodOrLambda)
            {
                builder
                .Append("+")
                .Append(method.SubMethod)
                .AppendParameters(method.SubMethodParameters, method.SubMethodBase != null);

                if (method.IsLambda)
                {
                    builder.Append(" => { }");

                    if (method.Ordinal.HasValue)
                    {
                        builder.Append(" [");
                        builder.Append(method.Ordinal);
                        builder.Append("]");
                    }
                }
            }
        }
        protected override Entity InternalResolve <TNode>(
            GraphStructuredProgram <TNode> program,
            ResolvedMethod <TNode> method,
            Reference reference)
        {
            var real   = (LocalVariableReference)reference;
            var exists = method.Variables.TryGetValue(real.Index, out var resolved);

            Trace.Assert(exists);
            if (!exists)
            {
                method.AddLocalVariable(new ResolvedLocalVariable(real.Index));
                resolved = method.Variables[real.Index];
            }

            if (resolved.DefaultClassType < 0 && real.DefaultType != null)
            {
                var defaultType = program.GetOrCreateClass(real.DefaultType);
                resolved.DefaultClassType = defaultType.Id.GlobalId;
            }

            return(resolved);
        }
        public void ClearMethod(ResolvedMethod <TNode> method)
        {
            var toRemove = method.Methods.Keys.ToList();

            foreach (var localFunction in toRemove)
            {
                RemoveMethod(method, localFunction);
            }

            var essential = new[] { method.Start, method.Final };
            var toDelete  = method.GetOwnedNodes().Except(essential);

            foreach (var node in toDelete)
            {
                RemoveVertex(node);
                myOnNodeRemovedHandler(node);
            }

            RemoveOutEdgeIf(method.Start, _ => true);
            RemoveInEdgeIf(method.Final, _ => true);

            method.Clear();
        }
        public ResolvedMethod <TNode> GetOrCreateMethod(IMethodHolder <TNode> owner, string name)
        {
            var rawMethodId = Methods.FindOrAdd(name);
            var methodId    = new ResolvedMethodId(rawMethodId);

            var method = owner.FindLocalMethod(methodId);

            if (method == null)
            {
                var start = myNodesProvider();
                var end   = myNodesProvider();

                AddVertex(start);
                AddVertex(end);

                method = new ResolvedMethod <TNode>(methodId, start, end);

                owner.AddMethod(methodId, method);
                return(method);
            }

            return(method);
        }
        protected override bool Step(
            GraphStructuredProgram <TNode> targetProgram,
            ResolvedMethod <TNode> owningMethod,
            TNode source,
            Statement statement,
            TNode target,
            Func <TNode> nodeCreator)
        {
            SecondaryEntity CreateNewVariable()
            {
                var nextId   = owningMethod.Variables.Keys.Max() + 1;
                var variable = new ResolvedLocalVariable(nextId);

                owningMethod.AddLocalVariable(variable);
                return(variable);
            }

            if (statement is InvocationStatement invocation)
            {
                var passedParameters =
                    invocation.PassedParameters.GroupBy(
                        pair => ReferenceResolver.Resolve(targetProgram, owningMethod, pair.Value),
                        pair => pair.Key)
                    .ToDictionary(
                        pair =>
                {
                    Trace.Assert(pair.Key != null);
                    return(pair.Key);
                },
                        pair =>
                {
                    var targets = pair.ToList();
                    return(targets.Count == 1 ?
                           targets[0] :
                           new ParameterIndicesSet(
                               targets.Select(targetIndex => targetIndex.Value)));
                });

                var returnedValues =
                    invocation.ReturnedValues.ToDictionary(
                        pair =>
                {
                    Trace.Assert(pair.Key != null);
                    return(pair.Key);
                },
                        pair => (SecondaryEntity)ReferenceResolver.Resolve(targetProgram, owningMethod, pair.Value));

                var normalizedPassedParameters = AddIntermediateEdgesIfNeeded(
                    targetProgram, passedParameters, source, nodeCreator, CreateNewVariable, out var newSource);

                ResolvedInvocationStatement <TNode> resolvedInvocationStatement = null;
                if (invocation.InvocationTarget is ClassMethodTarget classMethodTarget)
                {
                    var targetMethodId = targetProgram.GetOrCreateMethodId(classMethodTarget.TargetMethod);
                    var resolvedOwner  = ReferenceResolver.Resolve(
                        targetProgram, owningMethod, classMethodTarget.TargetClass);

                    resolvedInvocationStatement =
                        new ResolvedInvocationStatement <TNode>(
                            invocation, normalizedPassedParameters, returnedValues, resolvedOwner, targetMethodId);
                }

                if (invocation.InvocationTarget is LocalVariableTarget localVariableTarget)
                {
                    var resolvedOwner = ReferenceResolver.Resolve(
                        targetProgram, owningMethod, new LocalVariableReference(localVariableTarget.Index));

                    resolvedInvocationStatement =
                        new ResolvedInvocationStatement <TNode>(
                            invocation, normalizedPassedParameters, returnedValues, resolvedOwner, targetProgram.GetOrCreateMethodId("Invoke"));
                }

                if (invocation.InvocationTarget is ClassFieldTarget classFieldTarget)
                {
                    var resolvedOwner = ReferenceResolver.Resolve(
                        targetProgram, owningMethod, new ClassFieldReference(classFieldTarget.TargetClass, classFieldTarget.TargetField));

                    resolvedInvocationStatement =
                        new ResolvedInvocationStatement <TNode>(
                            invocation, normalizedPassedParameters, returnedValues, resolvedOwner, targetProgram.GetOrCreateMethodId("Invoke"));
                }

                if (invocation.InvocationTarget is ClassPropertyTarget classPropertyTarget)
                {
                    var resolvedOwner = ReferenceResolver.Resolve(
                        targetProgram, owningMethod, new ClassPropertyReference(classPropertyTarget.TargetClass, classPropertyTarget.TargetProperty));

                    resolvedInvocationStatement =
                        new ResolvedInvocationStatement <TNode>(
                            invocation, normalizedPassedParameters, returnedValues, resolvedOwner, targetProgram.GetOrCreateMethodId("Invoke"));
                }

                if (invocation.InvocationTarget is LocalFunctionTarget localFunctionTarget)
                {
                    var resolvedOwner  = owningMethod;
                    var targetMethodId = targetProgram.GetOrCreateMethodId(localFunctionTarget.TargetFunction.Value);

                    resolvedInvocationStatement =
                        new ResolvedInvocationStatement <TNode>(
                            invocation, normalizedPassedParameters, returnedValues, resolvedOwner, targetMethodId);
                }

                Trace.Assert(resolvedInvocationStatement != null);
                var operation = new Operation <TNode>(resolvedInvocationStatement, target);

                targetProgram.AddOperation(newSource, operation);
                return(false);
            }

            return(true);
        }
        protected override Entity InternalResolve <TNode>(
            GraphStructuredProgram <TNode> program,
            ResolvedMethod <TNode> method,
            Reference reference)
        {
            var classFieldReference = (ClassFieldReference)reference;

            if (classFieldReference.Owner is ClassReference classReference)
            {
                var clazz = program.GetOrCreateClass(classReference.ClassId);
                var field = program.GetOrCreateClassField(clazz.Id, classFieldReference.Name);

                if (classFieldReference.DefaultClassType != null)
                {
                    field.DefaultClassType = program.GetOrCreateClass(classFieldReference.DefaultClassType).Id.GlobalId;
                }

                return(field);
            }
            else if (classFieldReference.Owner is LocalVariableReference localVariableReference)
            {
                var localVariable = method.Variables[localVariableReference.Index];
                var fieldId       = program.GetOrCreateFieldId(classFieldReference.Name);

                var resolvedObjectField = new ResolvedObjectField(localVariable, fieldId)
                {
                    FindClassField = program.FindClassFieldById
                };

                method.StoreAdditionalVariable(resolvedObjectField);
                return(resolvedObjectField);
            }
            else if (classFieldReference.Owner is ClassFieldReference anotherReference)
            {
                var resolvedAnotherReference = (SecondaryEntity)Resolve(program, method, anotherReference);
                var fieldId = program.GetOrCreateFieldId(classFieldReference.Name);

                var resolvedObjectField = new ResolvedObjectField(resolvedAnotherReference, fieldId)
                {
                    FindClassField = program.FindClassFieldById
                };

                method.StoreAdditionalVariable(resolvedObjectField);
                return(resolvedObjectField);
            }
            else if (classFieldReference.Owner is ClassPropertyReference propertyReference)
            {
                var resolvedAnotherReference = (SecondaryEntity)Resolve(program, method, propertyReference);
                var fieldId = program.GetOrCreateFieldId(classFieldReference.Name);

                var resolvedObjectField = new ResolvedObjectField(resolvedAnotherReference, fieldId)
                {
                    FindClassField = program.FindClassFieldById
                };

                method.StoreAdditionalVariable(resolvedObjectField);
                return(resolvedObjectField);
            }

            Trace.Assert(false);
            return(null);
        }
Beispiel #25
0
        public void Transform(
            INodeBasedProgram <int> sourceMethod,
            GraphStructuredProgram <TNode> targetProgram,
            ResolvedMethod <TNode> targetMethod,
            Func <int, TNode> mapper)
        {
            int counter = -1;

            TNode CreateNewNode()
            {
                var newNode = mapper(counter--);

                targetMethod.AddOwnedNode(newNode);
                return(newNode);
            }

            var visited = new HashSet <int>();

            var localStarts = sourceMethod.GetStarts();

            var queued = new Stack <(TNode source, int target)>();

            foreach (var localStart in localStarts)
            {
                queued.Push((targetMethod.Start, localStart));
            }

            if (queued.Count == 0)
            {
                targetProgram.AddOperation(targetMethod.Start, new Operation <TNode>(myNop, targetMethod.Final));
            }

            while (queued.Count > 0)
            {
                var(source, rawTarget) = queued.Pop();

                var statement = sourceMethod.StatementAt(rawTarget);
                var target    = mapper(rawTarget);

                InternalStep(targetProgram, targetMethod, source, statement, target, CreateNewNode);

                if (visited.Contains(rawTarget))
                {
                    continue;
                }

                if (sourceMethod.IsFinal(rawTarget))
                {
                    targetProgram.AddOperation(target, new Operation <TNode>(myReturn, targetMethod.Final));
                }
                else
                {
                    var transitions = sourceMethod.Transitions(rawTarget).ToList();
                    foreach (var transition in transitions)
                    {
                        queued.Push((target, transition));
                    }
                }

                visited.Add(rawTarget);
            }
        }
Beispiel #26
0
 protected abstract Entity InternalResolve <TNode>(
     GraphStructuredProgram <TNode> program,
     ResolvedMethod <TNode> method,
     Reference reference);
Beispiel #27
0
 protected abstract Entity RestoreImplementation <TNode>(
     GraphStructuredProgram <TNode> program,
     ResolvedMethod <TNode> method,
     Entity entity);
        private static ResolvedMethod GetMethodDisplay(MethodBase originMethod)
        {
            var methodDisplayInfo = new ResolvedMethod();

            // Special case: no method available
            if (originMethod == null)
            {
                return(methodDisplayInfo);
            }

            var method = originMethod;

            methodDisplayInfo.SubMethodBase = method;

            // Type name
            var type          = method.DeclaringType;
            var subMethodName = method.Name;
            var methodName    = method.Name;

            if (type != null && type.IsDefined(typeof(CompilerGeneratedAttribute)) &&
                (typeof(IAsyncStateMachine).IsAssignableFrom(type) || typeof(IEnumerator).IsAssignableFrom(type)))
            {
                methodDisplayInfo.IsAsync = typeof(IAsyncStateMachine).IsAssignableFrom(type);

                // Convert StateMachine methods to correct overload +MoveNext()
                if (!TryResolveStateMachineMethod(ref method, out type))
                {
                    methodDisplayInfo.SubMethodBase = null;
                    subMethodName = null;
                }

                methodName = method.Name;
            }

            // Method name
            methodDisplayInfo.MethodBase = method;
            methodDisplayInfo.Name       = methodName;
            if (method.Name.IndexOf("<", StringComparison.Ordinal) >= 0)
            {
                if (TryResolveGeneratedName(ref method, out type, out methodName, out subMethodName, out var kind, out var ordinal))
                {
                    methodName = method.Name;
                    methodDisplayInfo.MethodBase = method;
                    methodDisplayInfo.Name       = methodName;
                    methodDisplayInfo.Ordinal    = ordinal;
                }
                else
                {
                    methodDisplayInfo.MethodBase = null;
                }

                methodDisplayInfo.IsLambda = (kind == GeneratedNameKind.LambdaMethod);

                if (methodDisplayInfo.IsLambda && type != null)
                {
                    if (methodName == ".cctor")
                    {
                        var fields = type.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                        foreach (var field in fields)
                        {
                            var value = field.GetValue(field);
                            if (value is Delegate d)
                            {
                                if (ReferenceEquals(d.Method, originMethod) && d.Target.ToString() == originMethod.DeclaringType?.ToString())
                                {
                                    methodDisplayInfo.Name     = field.Name;
                                    methodDisplayInfo.IsLambda = false;
                                    method = originMethod;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
Beispiel #29
0
 protected abstract InternalStatement RestoreImplementation <TNode>(
     GraphStructuredProgram <TNode> program,
     ResolvedMethod <TNode> method,
     InternalStatement statement);