Example #1
0
        private List <Constant> ReadConstants(ISymbolScope scope)
        {
            // Read the constants.
            // IldbSymbols.dll doesn't support ISymUnmanagedScope2 so nothing we can do for ILDB to read
            // constants (even though it does support writing them).  But RefEmit doesn't ever emit constants
            // anyway, so there should be no need for this.
            if (symFormat == SymbolFormat.ILDB)
            {
                return(null);
            }

            // Note - ISymbolConstants are written to the xml, but cannot be easily round-tripped.
            // The SigTokens cannot be easily retrieved from either the pdb or the assembly metadata
            List <Constant> constants = new List <Constant>();
            ISymbolScope2   scope2    = (ISymbolScope2)scope;

            foreach (ISymbolConstant c in scope2.GetConstants())
            {
                Constant constData = new Constant();
                constData.name      = c.GetName();
                constData.value     = c.GetValue().ToString();
                constData.signature = Util.ToHexString(c.GetSignature());
                constants.Add(constData);
            }
            return(constants);
        }
Example #2
0
        private Scope ReadScope(ISymbolScope scope)
        {
            Scope scopeData = new Scope();

            // If this is the root scope, then it was created implicitly and should not be explicitly
            // opened by a writer
            if (scope.Parent == null)
            {
                scopeData.isImplicit = true;
            }
            scopeData.startOffset = scope.StartOffset;
            scopeData.endOffset   = scope.EndOffset;

            // Read the locals, constants and namespaces in this scope (may be empty)
            scopeData.locals         = ReadLocals(scope);
            scopeData.constants      = ReadConstants(scope);
            scopeData.usedNamespaces = ReadUsedNamespaces(scope);

            // Read the child scopes recursively
            scopeData.scopes = new List <Scope>();
            foreach (ISymbolScope child in scope.GetChildren())
            {
                Scope childData = ReadScope(child);
                scopeData.scopes.Add(childData);
            }

            return(scopeData);
        }
Example #3
0
        public void Execute(Action <DaemonStageResult> committer)
        {
            IPsiSourceFile sourceFile  = DaemonProcess.SourceFile;
            IPsiServices   psiServices = sourceFile.GetPsiServices();
            ISymbolScope   symbolScope = psiServices.Symbols.GetSymbolScope(LibrarySymbolScope.FULL, false, sourceFile.ResolveContext);

            ITypeElement typeElement = symbolScope.GetTypeElementByCLRName("TestStack.BDDfy.BDDfyExtensions");

            if (typeElement == null)
            {
                return;
            }

            IEnumerable <IMethod> bddfyMethods = typeElement.Methods.Where(method => method.ShortName == "BDDfy" || method.ShortName == "LazyBDDfy");
            ISearchDomain         searchDomain = searchDomainFactory.CreateSearchDomain(sourceFile);

            IReference[] references = bddfyMethods.SelectMany(method => psiServices.Finder.FindReferences(method, searchDomain, NullProgressIndicator.Instance)).ToArray();
            foreach (IReference reference in references)
            {
                var node = reference.GetTreeNode() as ICSharpTreeNode;
                if (node != null)
                {
                    var classDeclaration = node.GetContainingTypeDeclaration() as IClassDeclaration;
                    if (classDeclaration != null)
                    {
                        SetClassAndMembersUsed(classDeclaration);
                    }
                }
            }
        }
Example #4
0
        static void ReadScopeAndLocals(ISymbolScope scope, Cil.Scope parent, Cil.MethodBody body, IDictionary instructions)
        {
            Cil.Scope s = new Cil.Scope();
            s.Start = GetInstruction(body, instructions, scope.StartOffset);
            s.End   = GetInstruction(body, instructions, scope.EndOffset);

            if (parent != null)
            {
                parent.Scopes.Add(s);
            }
            else
            {
                body.Scopes.Add(s);
            }

            foreach (ISymbolVariable local in scope.GetLocals())
            {
                Cil.VariableDefinition variable = body.Variables [local.AddressField1];
                variable.Name = local.Name;

                s.Variables.Add(variable);
            }

            foreach (ISymbolScope child in scope.GetChildren())
            {
                ReadScopeAndLocals(child, s, body, instructions);
            }
        }
        public static CppInclusionContextResult CreateInclusionContextResult(
            CppGlobalSymbolCache cache,
            CppFileLocation rootFile,
            IEnumerable <CppFileLocation> includeLocations,
            FileProcessingOptions options,
            CppCompilationProperties compilationProperties,
            ISymbolScope symbolScope,
            long cacheVersion,
            Lifetime lifetime)
        {
            var languageDialect   = CppProjectConfigurationUtil.GetLanguageDialect(compilationProperties);
            var randomProjectFile = rootFile.GetRandomProjectFile(cache.Solution);
            var inclusionContext  = CppRootInclusionContext.Create(compilationProperties, randomProjectFile.GetProject(),
                                                                   randomProjectFile, cache, rootFile, options.File, languageDialect,
                                                                   cacheVersion, options.AllowPendingActions, options.CollectPPUsages, lifetime, symbolScope);
            var directory = randomProjectFile.Location.Directory;

            inclusionContext.ProcessDefine(CppPPDefineSymbol.ParsePredefinedMacro("SHADER_API_D3D11"));
            inclusionContext.ProcessDefine(CppPPDefineSymbol.ParsePredefinedMacro("__RESHARPER__"));
            inclusionContext.ProcessDefine(CppPPDefineSymbol.ParsePredefinedMacro("INTERNAL_DATA= "));
            inclusionContext.ProcessDefine(CppPPDefineSymbol.ParsePredefinedMacro("WorldReflectionVector(data,normal)=data.worldRefl"));
            inclusionContext.ProcessDefine(CppPPDefineSymbol.ParsePredefinedMacro("WorldNormalVector(data,normal)=normal"));
            inclusionContext.PushInclude(rootFile, directory, false);
            foreach (CppFileLocation includeLocation in includeLocations)
            {
                if (includeLocation.IsValid() && !includeLocation.Equals(rootFile))
                {
                    cache.LookupAndProcessTableForFile(rootFile, includeLocation, options, inclusionContext, directory);
                }
            }
            inclusionContext.PopInclude(false);
            return(CppInclusionContextResult.Ok(inclusionContext));
        }
        // Helper method to write the local variables in the given scope.
        // Scopes match an IL range, and also have child scopes.
        void WriteLocalsHelper(ISymbolScope scope)
        {
            foreach (ISymbolVariable l in scope.GetLocals())
            {
                m_writer.WriteStartElement("local");
                {
                    m_writer.WriteAttributeString("name", l.Name);

                    // Each local maps to a unique "IL Index" or "slot" number.
                    // This index is what you pass to ICorDebugILFrame::GetLocalVariable() to get
                    // a specific local variable.
                    Debug.Assert(l.AddressKind == SymAddressKind.ILOffset);
                    int slot = l.AddressField1;
                    m_writer.WriteAttributeString("il_index", slot.ToString());

                    // Provide scope range
                    m_writer.WriteAttributeString("il_start", Util.AsIlOffset(scope.StartOffset));
                    m_writer.WriteAttributeString("il_end", Util.AsIlOffset(scope.EndOffset));
                }
                m_writer.WriteEndElement();                 // local
            }

            foreach (ISymbolScope childScope in scope.GetChildren())
            {
                WriteLocalsHelper(childScope);
            }
        }
Example #7
0
        public Scope(ISymbolScope scope, VariableDefinition[] locals, Dictionary <int, Instruction> insns)
        {
            m_start = insns[scope.StartOffset];
            m_end   = insns[scope.EndOffset];

            foreach (var v in scope.GetLocals())
            {
                if (v.AddressKind == SymAddressKind.ILOffset)
                {
                    var local = locals[v.AddressField1];

                    if (m_variables == null)
                    {
                        m_variables = new List <VariableDebugInformation> ();
                    }

                    m_variables.Add(new VariableDebugInformation(local, v.Name));
                }
            }

            foreach (var s in scope.GetChildren())
            {
                if (m_scopes == null)
                {
                    m_scopes = new List <Scope> ();
                }

                m_scopes.Add(new Scope(s, locals, insns));
            }
        }
Example #8
0
 public SymbolScope(ISymbolMethod method, ISymbolScope parent, int startOffset, int endOffset)
 {
     _children    = new List <ISymbolScope>();
     _locals      = new List <ISymbolVariable>();
     _startOffset = startOffset;
     _endOffset   = endOffset;
     _parent      = parent;
 }
Example #9
0
        private static List <IClrDeclaredElement> FindType(ISolution solution, string typeToFind)
        {
            ISymbolScope declarationsCache = solution.GetPsiServices().Symbols
                                             .GetSymbolScope(LibrarySymbolScope.FULL, false);

            List <IClrDeclaredElement> results = declarationsCache.GetElementsByShortName(typeToFind).ToList();

            return(results);
        }
Example #10
0
        private static List <IClrDeclaredElement> FindType(ISolution solution, string typeToFind)
        {
            ISymbolScope declarationsCache = solution.GetPsiServices().Symbols
                                             .GetSymbolScope(LibrarySymbolScope.FULL, context: UniversalModuleReferenceContext.Instance, caseSensitive: false);

            List <IClrDeclaredElement> results = declarationsCache.GetElementsByShortName(typeToFind).ToList();

            return(results);
        }
Example #11
0
        IEnumerable <ValueReference> GetLocals(CorEvaluationContext ctx, ISymbolScope scope, int offset, bool showHidden)
        {
            if (ctx.Frame.FrameType != CorFrameType.ILFrame)
            {
                yield break;
            }

            if (scope == null)
            {
                ISymbolMethod met = ctx.Frame.Function.GetSymbolMethod(ctx.Session);
                if (met != null)
                {
                    scope = met.RootScope;
                }
                else
                {
                    int count = ctx.Frame.GetLocalVariablesCount();
                    for (int n = 0; n < count; n++)
                    {
                        int       locn = n;
                        CorValRef vref = new CorValRef(delegate {
                            return(ctx.Frame.GetLocalVariable(locn));
                        });
                        yield return(new VariableReference(ctx, vref, "local_" + (n + 1), ObjectValueFlags.Variable));
                    }
                    yield break;
                }
            }

            foreach (ISymbolVariable var in scope.GetLocals())
            {
                if (var.Name == "$site")
                {
                    continue;
                }
                if (var.Name.IndexOfAny(new char[] { '$', '<', '>' }) == -1 || showHidden)
                {
                    int       addr = var.AddressField1;
                    CorValRef vref = new CorValRef(delegate {
                        return(ctx.Frame.GetLocalVariable(addr));
                    });
                    yield return(new VariableReference(ctx, vref, var.Name, ObjectValueFlags.Variable));
                }
            }

            foreach (ISymbolScope cs in scope.GetChildren())
            {
                if (cs.StartOffset <= offset && cs.EndOffset >= offset)
                {
                    foreach (VariableReference var in GetLocals(ctx, cs, offset, showHidden))
                    {
                        yield return(var);
                    }
                }
            }
        }
Example #12
0
 private SymScope(SymScope parent, int endOffset, int startOffset)
 {
     // Create a new child scope.
     this.method      = parent.method;
     this.parent      = parent;
     this.children    = new ISymbolScope [0];
     this.locals      = new ISymbolVariable [0];
     this.endOffset   = endOffset;
     this.startOffset = startOffset;
 }
Example #13
0
 internal SymScope(ISymbolMethod method)
 {
     // Create the root scope for a method.
     this.method      = method;
     this.parent      = null;
     this.children    = new ISymbolScope [0];
     this.locals      = new ISymbolVariable [0];
     this.endOffset   = Int32.MaxValue;
     this.startOffset = 0;
 }
Example #14
0
	private SymScope(SymScope parent, int endOffset, int startOffset)
			{
				// Create a new child scope.
				this.method = parent.method;
				this.parent = parent;
				this.children = new ISymbolScope [0];
				this.locals = new ISymbolVariable [0];
				this.endOffset = endOffset;
				this.startOffset = startOffset;
			}
Example #15
0
	internal SymScope(ISymbolMethod method)
			{
				// Create the root scope for a method.
				this.method = method;
				this.parent = null;
				this.children = new ISymbolScope [0];
				this.locals = new ISymbolVariable [0];
				this.endOffset = Int32.MaxValue;
				this.startOffset = 0;
			}
Example #16
0
		public ISymbolScope[] GetChildren() {
			uint numScopes;
			scope.GetChildren(0, out numScopes, null);
			var unScopes = new ISymUnmanagedScope[numScopes];
			scope.GetChildren((uint)unScopes.Length, out numScopes, unScopes);
			var scopes = new ISymbolScope[numScopes];
			for (uint i = 0; i < numScopes; i++)
				scopes[i] = new SymbolScope(unScopes[i]);
			return scopes;
		}
Example #17
0
        ISymbolScope[] ISymbolScope.GetChildren()
        {
            var scopes = new ISymbolScope[Children.Count];

            for (int i = 0; i < scopes.Length; i++)
            {
                scopes[i] = Children[i];
            }
            return(scopes);
        }
Example #18
0
    public static IEnumerable <ISymbolScope> GetInnerScopesRecursive(this ISymbolScope scope)
    {
        yield return(scope);

        foreach (var innerScope in scope.GetChildren()
                 .SelectMany(innerScope => innerScope.GetInnerScopesRecursive()))
        {
            yield return(innerScope);
        }
    }
Example #19
0
 void VisitLocals(ISymbolScope iSymbolScope)
 {
     foreach (var s in iSymbolScope.GetLocals())
     {
         _names [s.AddressField1] = s.Name;
     }
     foreach (var c in iSymbolScope.GetChildren())
     {
         VisitLocals(c);
     }
 }
Example #20
0
        // Write the local variables in the given scope.
        // Scopes match an IL range, and also have child scopes.
        private List <Variable> ReadLocals(ISymbolScope scope)
        {
            List <Variable> locals = new List <Variable>();

            foreach (ISymbolVariable l in scope.GetLocals())
            {
                Variable localData = ReadVariable(l);
                locals.Add(localData);
            }
            return(locals);
        }
Example #21
0
        private List <Namespace> ReadUsedNamespaces(ISymbolScope scope)
        {
            List <Namespace> namespaces = new List <Namespace>();

            foreach (ISymbolNamespace symNs in scope.GetNamespaces())
            {
                Namespace n = new Namespace();
                n.name = symNs.Name;
                namespaces.Add(n);
            }
            return(namespaces);
        }
 void VisitLocals(ISymbolScope iSymbolScope)
 {
     foreach (var s in iSymbolScope.GetLocals())
     {
         Console.WriteLine("  Found Local Variable: " + s.Name);
         _names[s.AddressField1] = s.Name;
     }
     foreach (var c in iSymbolScope.GetChildren())
     {
         VisitLocals(c);
     }
 }
        public static List <IClrDeclaredElement> FindClass(ISolution solution, string classNameToFind,
                                                           IList <IProject> restrictToTheseProjects)
        {
            ISymbolScope declarationsCache = solution.GetPsiServices().Symbols
                                             .GetSymbolScope(LibrarySymbolScope.FULL, false); //, currentProject.GetResolveContext());

            List <IClrDeclaredElement> results = declarationsCache.GetElementsByShortName(classNameToFind).ToList();

            RemoveElementsNotInProjects(results, restrictToTheseProjects);

            return(results);
        }
Example #24
0
        // Insert a new scope into this one at a particular position.
        private SymScope InsertScope(int index, int endOffset, int startOffset)
        {
            SymScope scope = new SymScope(this, endOffset, startOffset);

            ISymbolScope[] newChildren;
            newChildren = new ISymbolScope [children.Length + 1];
            Array.Copy(children, 0, newChildren, 0, index);
            Array.Copy(children, index, newChildren, index + 1,
                       children.Length - index);
            newChildren[index] = scope;
            children           = newChildren;
            return(scope);
        }
Example #25
0
        public static IEnumerable <ITypeElement> GetTypeElementsByClrName(ISolution solution, string clrName)
        {
            IPsiServices psiServices = solution.GetComponent <IPsiServices>();

            psiServices.Files.CommitAllDocuments();

            ISymbolCache symbolCache = psiServices.Symbols;
            ISymbolScope symbolScope = symbolCache.GetSymbolScope(LibrarySymbolScope.FULL, true);

            IEnumerable <ITypeElement> validTypeElements = symbolScope.GetTypeElementsByCLRName(clrName)
                                                           .Where(element => element.IsValid());

            return(SkipDefaultProfileIfRuntimeExist(validTypeElements));
        }
Example #26
0
        private IEnumerable <IClrDeclaredElement> FindReferencesWithinAssociatedAssembly(IDataContext context,
                                                                                         ISolution solution, ITextControl textControl, IClrTypeName clrTypeClassName,
                                                                                         IEnumerable <TestCopProjectItem> targetProjects)
        {
            if (clrTypeClassName == null)
            {
                ResharperHelper.AppendLineToOutputWindow(solution.Locks,
                                                         "FindReferencesWithinAssociatedAssembly() - clrTypeClassName was null");
                return(new List <IClrDeclaredElement>());
            }

            IPsiServices services = solution.GetPsiServices();

            ISearchDomain searchDomain;

            if (this.Settings.FindAnyUsageInTestAssembly)
            {
                searchDomain = PsiShared.GetComponent <SearchDomainFactory>().CreateSearchDomain(
                    targetProjects.SelectMany(proj => proj.Project.GetAllProjectFiles().Select(p => p.GetPsiModule())));
            }
            else
            {
                // look for similar named files that also have references to this code
                List <ProjectFileFinder.Match> items = new List <ProjectFileFinder.Match>();

                foreach (TestCopProjectItem projectItem in targetProjects)
                {
                    projectItem.Project.Accept(new ProjectFileFinder(items, projectItem.FilePattern));
                }

                searchDomain = PsiShared.GetComponent <SearchDomainFactory>()
                               .CreateSearchDomain(items.Select(p => p.ProjectFile.ToSourceFile()));
            }

            ISymbolScope declarationsCache = solution.GetPsiServices().Symbols
                                             .GetSymbolScope(LibrarySymbolScope.NONE, false); //, currentProject.GetResolveContext());

            ITypeElement declaredElement = declarationsCache.GetTypeElementByCLRName(clrTypeClassName);

            IReference[] findReferences =
                services.Finder.FindReferences(declaredElement, searchDomain, new ProgressIndicator(textControl.Lifetime));

            List <IClassDeclaration> findReferencesWithinAssociatedAssembly =
                findReferences.Select(p => p.GetTreeNode().GetContainingNode <IClassDeclaration>(true)).ToList();

            return(findReferencesWithinAssociatedAssembly
                   .Select(p => p.DeclaredElement).ToList()
                   .Select(p => p as IClrDeclaredElement).ToList());
        }
Example #27
0
        public ISymbolScope[] GetChildren()
        {
            m_target.GetChildren(0, out var count, null);
            ISymUnmanagedScope[] uScopes = new ISymUnmanagedScope[count];
            m_target.GetChildren(count, out count, uScopes);

            int i;

            ISymbolScope[] scopes = new ISymbolScope[count];
            for (i = 0; i < count; i++)
            {
                scopes[i] = new SymScope(uScopes[i]);
            }
            return(scopes);
        }
Example #28
0
        /// <summary>
        /// Returns the child lexical scopes of the current lexical scope.
        /// </summary>
        /// <returns></returns>
        public ISymbolScope[] GetChildren()
        {
            int chNum;

            private_scope.GetChildren(0, out chNum, null);
            ISymUnmanagedScope[] unScps  = new ISymUnmanagedScope[chNum];
            ISymbolScope[]       manScps = new ISymbolScope[chNum];

            private_scope.GetChildren(chNum, out chNum, unScps);
            for (int i = 0; i < chNum; i++)
            {
                manScps[i] = new SymbolScope(unScps[i]);
            }
            return(manScps);
        }
Example #29
0
        public ISymbolScope[] GetChildren()
        {
            uint numScopes;

            scope.GetChildren(0, out numScopes, null);
            var unScopes = new ISymUnmanagedScope[numScopes];

            scope.GetChildren((uint)unScopes.Length, out numScopes, unScopes);
            var scopes = new ISymbolScope[numScopes];

            for (uint i = 0; i < numScopes; i++)
            {
                scopes[i] = new SymbolScope(unScopes[i]);
            }
            return(scopes);
        }
Example #30
0
        private Variable[] enumerateLocals(ISymbolScope scope)
        {
            var variables = new List<Variable>();
            foreach (var local in scope.GetLocals())
            {
                if (isHidden(local))
                    continue;
                var value = _thread.ActiveFrame.GetLocalVariable(local.AddressField1);
                var something = getValue(value);
                variables.Add(new Variable(local.Name, something));
            }

            foreach (var child in scope.GetChildren())
                variables.AddRange(enumerateLocals(child));
            return variables.ToArray();
        }
        public static CppInclusionContextResult CreateInclusionContextResult(
            CppGlobalSymbolCache cache,
            CppFileLocation rootFile,
            FileProcessingOptions options,
            CppCompilationProperties compilationProperties,
            ISymbolScope symbolScope,
            long cacheVersion,
            Lifetime lifetime)
        {
            var languageDialect   = CppProjectConfigurationUtil.GetLanguageDialect(compilationProperties);
            var randomProjectFile = rootFile.GetRandomProjectFile(cache.Solution);
            var inclusionContext  = CppRootInclusionContext.Create(compilationProperties, randomProjectFile.GetProject(),
                                                                   randomProjectFile, cache, rootFile, options.File, languageDialect,
                                                                   cacheVersion, options.AllowPendingActions, options.CollectPPUsages, lifetime, symbolScope);
            var directory = randomProjectFile.Location.Directory;

            var shaderCache = cache.Solution.GetComponent <InjectedHlslFileLocationTracker>();

            var(includes, defines) = shaderCache.GetProgramInfo(rootFile);

            inclusionContext.ProcessDefine(CppPPDefineSymbol.ParsePredefinedMacro("SHADER_API_D3D11"));
            inclusionContext.ProcessDefine(CppPPDefineSymbol.ParsePredefinedMacro("__RESHARPER__"));
            inclusionContext.ProcessDefine(CppPPDefineSymbol.ParsePredefinedMacro("INTERNAL_DATA= "));
            inclusionContext.ProcessDefine(CppPPDefineSymbol.ParsePredefinedMacro("WorldReflectionVector(data,normal)=data.worldRefl"));
            inclusionContext.ProcessDefine(CppPPDefineSymbol.ParsePredefinedMacro("WorldNormalVector(data,normal)=normal"));

            foreach (var define in defines)
            {
                inclusionContext.ProcessDefine(CppPPDefineSymbol.ParsePredefinedMacro($"{define.Key}={define.Value}"));
            }

            // TODO 1) is cache ready? what will happen under document transaction? check for bad moment?
            // TODO 2) what will happen under psi transaction? include in cache could be out-of date. Try use include quickfix when cginclude is after cgprogram where QF is used


            inclusionContext.PushInclude(rootFile, directory, false);
            foreach (CppFileLocation includeLocation in includes)
            {
                if (includeLocation.IsValid() && !includeLocation.Equals(rootFile))
                {
                    cache.LookupAndProcessTableForFile(rootFile, includeLocation, options, inclusionContext, directory);
                }
            }
            inclusionContext.PopInclude(false);
            return(CppInclusionContextResult.Ok(inclusionContext));
        }
Example #32
0
        private void ProcessNamespace(INamespace element, ISymbolScope scope,
                                      ICollection <HandlerCompletionItem> handlers)
        {
            var nestedNamespaces = element.GetNestedNamespaces(scope);

            foreach (var @namespace in nestedNamespaces)
            {
                ProcessNamespace(@namespace, scope, handlers);
            }

            var classes = element.GetNestedElements(scope).OfType <IClass>();

            foreach (var @class in classes)
            {
                ProcessClass(@class, handlers);
            }
        }
        public ISymbolScope[] GetChildren()
        {
            int size;

            HRESULT.ThrowOnFailure(_unmanaged.GetChildren(0, out size, null));

            var unmanagedScopes = new ISymUnmanagedScope[size];

            HRESULT.ThrowOnFailure(_unmanaged.GetChildren(unmanagedScopes.Length, out size, unmanagedScopes));

            var scopes = new ISymbolScope[size];

            for (int i = 0; i < size; i++)
            {
                scopes[i] = new SymbolScope(unmanagedScopes[i]);
            }

            return(scopes);
        }
Example #34
0
		static void ReadScopeAndLocals (ISymbolScope scope, Cil.Scope parent, Cil.MethodBody body, IDictionary instructions)
		{
			Cil.Scope s = new Cil.Scope ();
			s.Start = GetInstruction (body, instructions, scope.StartOffset);
			s.End = GetInstruction (body, instructions, scope.EndOffset);

			if (parent != null)
				parent.Scopes.Add (s);
			else
				body.Scopes.Add (s);

			foreach (ISymbolVariable local in scope.GetLocals ()) {
				Cil.VariableDefinition variable = body.Variables [local.AddressField1];
				variable.Name = local.Name;

				s.Variables.Add (variable);
			}

			foreach (ISymbolScope child in scope.GetChildren ())
				ReadScopeAndLocals (child, s, body, instructions);
		}
Example #35
0
        private static IEnumerable <ITypeElement> FindTypeElements(INamespace ns,
                                                                   ISymbolScope symbolScope)
        {
            foreach (var te in ns.GetNestedTypeElements(symbolScope))
            {
                yield return(te);

                foreach (var nte in te.NestedTypes)
                {
                    yield return(nte);
                }
            }

            foreach (var nsNested in ns.GetNestedNamespaces(symbolScope))
            {
                foreach (var te in FindTypeElements(nsNested, symbolScope))
                {
                    yield return(te);
                }
            }
        }
Example #36
0
        private List<Namespace> ReadUsedNamespaces(ISymbolScope scope)
        {
            List<Namespace> namespaces = new List<Namespace>();

            foreach (ISymbolNamespace symNs in scope.GetNamespaces())
            {
                Namespace n = new Namespace();
                n.name = symNs.Name;
                namespaces.Add(n);
            }
            return namespaces;
        }
Example #37
0
        private Scope ReadScope(ISymbolScope scope)
        {
            Scope scopeData = new Scope();

            // If this is the root scope, then it was created implicitly and should not be explicitly
            // opened by a writer
            if (scope.Parent == null)
            {
                scopeData.isImplicit = true;
            }
            scopeData.startOffset = scope.StartOffset;
            scopeData.endOffset = scope.EndOffset;

            // Read the locals, constants and namespaces in this scope (may be empty)
            scopeData.locals = ReadLocals(scope);
            scopeData.constants = ReadConstants(scope);
            scopeData.usedNamespaces = ReadUsedNamespaces(scope);

            // Read the child scopes recursively
            scopeData.scopes = new List<Scope>();
            foreach (ISymbolScope child in scope.GetChildren())
            {
                Scope childData = ReadScope(child);
                scopeData.scopes.Add(childData);
            }

            return scopeData;
        }
Example #38
0
 // Write the local variables in the given scope.
 // Scopes match an IL range, and also have child scopes.
 private List<Variable> ReadLocals(ISymbolScope scope)
 {
     List<Variable> locals = new List<Variable>();
     foreach (ISymbolVariable l in scope.GetLocals())
     {
         Variable localData = ReadVariable(l);
         locals.Add(localData);
     }
     return locals;
 }
Example #39
0
        private List<Constant> ReadConstants(ISymbolScope scope)
        {
            // Read the constants.
            // IldbSymbols.dll doesn't support ISymUnmanagedScope2 so nothing we can do for ILDB to read
            // constants (even though it does support writing them).  But RefEmit doesn't ever emit constants
            // anyway, so there should be no need for this.
            if (_symFormat == SymbolFormat.ILDB)
            {
                return null;
            }

            // Note - ISymbolConstants are written to the xml, but cannot be easily round-tripped.
            // The SigTokens cannot be easily retrieved from either the pdb or the assembly metadata
            List<Constant> constants = new List<Constant>();
            ISymbolScope2 scope2 = (ISymbolScope2)scope;
            foreach (ISymbolConstant c in scope2.GetConstants())
            {
                Constant constData = new Constant();
                constData.name = c.GetName();
                constData.value = c.GetValue().ToString();
                constData.signature = Util.ToHexString(c.GetSignature());
                constants.Add(constData);
            }
            return constants;
        }
Example #40
0
		ISymbolScope[] ISymbolScope.GetChildren() {
			var scopes = new ISymbolScope[Children.Count];
			for (int i = 0; i < scopes.Length; i++)
				scopes[i] = Children[i];
			return scopes;
		}
Example #41
0
        // Helper method to write the local variables in the given scope.
        // Scopes match an IL range, and also have child scopes.
        void WriteLocalsHelper(ISymbolScope scope)
        {
            foreach (ISymbolVariable l in scope.GetLocals())
            {
                m_writer.WriteStartElement("local");
                {
                    m_writer.WriteAttributeString("name", l.Name);

                    // Each local maps to a unique "IL Index" or "slot" number.
                    // This index is what you pass to ICorDebugILFrame::GetLocalVariable() to get
                    // a specific local variable. 
                    Debug.Assert(l.AddressKind == SymAddressKind.ILOffset);
                    int slot = l.AddressField1;
                    m_writer.WriteAttributeString("il_index", slot.ToString());

                    // Provide scope range
                    m_writer.WriteAttributeString("il_start", Util.AsIlOffset(scope.StartOffset));
                    m_writer.WriteAttributeString("il_end", Util.AsIlOffset(scope.EndOffset));
                }
                m_writer.WriteEndElement(); // local
            }

            foreach (ISymbolScope childScope in scope.GetChildren())
            {
                WriteLocalsHelper(childScope);
            }
        }
Example #42
0
 /// <summary>
 /// Create a new scope from a ISymbolScope
 /// </summary>
 /// <param name="scope"></param>
 internal PDBScope(ISymbolScope scope)
 {
     _scope = scope;
 }
Example #43
0
	// Insert a new scope into this one at a particular position.
	private SymScope InsertScope(int index, int endOffset, int startOffset)
			{
				SymScope scope = new SymScope(this, endOffset, startOffset);
				ISymbolScope[] newChildren;
				newChildren = new ISymbolScope [children.Length + 1];
				Array.Copy(children, 0, newChildren, 0, index);
				Array.Copy(children, index, newChildren, index + 1,
						   children.Length - index);
				newChildren[index] = scope;
				children = newChildren;
				return scope;
			}
Example #44
0
        /// <summary>
        /// Returns the child lexical scopes of the current lexical scope.
        /// </summary>
        /// <returns></returns>
        public ISymbolScope[] GetChildren()
        {
            int chNum;
              private_scope.GetChildren(0, out chNum, null);
              ISymUnmanagedScope[] unScps = new ISymUnmanagedScope[chNum];
              ISymbolScope[] manScps = new ISymbolScope[chNum];

              private_scope.GetChildren(chNum, out chNum, unScps);
              for (int i = 0; i < chNum; i++)
            manScps[i] = new SymbolScope(unScps[i]);
              return manScps;
        }
Example #45
0
        private void AddLocalVariablesToList(CorFrame frame, int ip, ArrayList listToAdd, ISymbolScope scope)
        {
            Debug.Assert(frame.FunctionToken == m_function.Token);

            foreach (ISymbolVariable isv in scope.GetLocals())
            {
                Debug.Assert(isv.AddressKind == SymAddressKind.ILOffset);
                CorValue v = null;
                try
                {
                    v = frame.GetLocalVariable(isv.AddressField1);
                }
                catch (System.Runtime.InteropServices.COMException e)
                {
                    if (e.ErrorCode != (int)Microsoft.Samples.Debugging.CorDebug.HResult.CORDBG_E_IL_VAR_NOT_AVAILABLE)
                        throw;
                }

                listToAdd.Add(new MDbgValue(m_module.Process, isv.Name, v));
            }

            foreach (ISymbolScope s in scope.GetChildren())
            {
                if (s.StartOffset <= ip && s.EndOffset >= ip)
                    AddLocalVariablesToList(frame, ip, listToAdd, s);
            }
        }
Example #46
0
 /// <summary>
 /// Create a new scope from a ISymbolScope
 /// </summary>
 /// <param name="scope"></param>
 internal PDBScope(ISymbolScope scope)
 {
     Contract.Requires(scope != null);
     _scope = scope;
 }
Example #47
0
		static PdbScope CreateScope(CilBody body, ISymbolScope symScope) {
			if (symScope == null)
				return null;

			// Don't use recursive calls
			var stack = new Stack<CreateScopeState>();
			var state = new CreateScopeState() { SymScope = symScope };
recursive_call:
			int instrIndex = 0;
			state.PdbScope = new PdbScope() {
				Start = GetInstruction(body.Instructions, state.SymScope.StartOffset, ref instrIndex),
				End   = GetInstruction(body.Instructions, state.SymScope.EndOffset, ref instrIndex),
			};

			foreach (var symLocal in state.SymScope.GetLocals()) {
				if (symLocal.AddressKind != SymAddressKind.ILOffset)
					continue;

				int localIndex = symLocal.AddressField1;
				if ((uint)localIndex >= (uint)body.Variables.Count)
					continue;
				var local = body.Variables[localIndex];
				local.Name = symLocal.Name;
				var attributes = symLocal.Attributes;
				if (attributes is int)
					local.PdbAttributes = (int)attributes;
				state.PdbScope.Variables.Add(local);
			}

			foreach (var ns in state.SymScope.GetNamespaces())
				state.PdbScope.Namespaces.Add(ns.Name);

			// Here's the now somewhat obfuscated for loop
			state.ChildrenIndex = 0;
			state.Children = state.SymScope.GetChildren();
do_return:
			if (state.ChildrenIndex < state.Children.Length) {
				var child = state.Children[state.ChildrenIndex];
				stack.Push(state);
				state = new CreateScopeState() { SymScope = child };
				goto recursive_call;
			}

			if (stack.Count == 0)
				return state.PdbScope;

			// Return from recursive call, and execute the last part of the for loop
			var newPdbScope = state.PdbScope;
			state = stack.Pop();
			state.PdbScope.Scopes.Add(newPdbScope);
			state.ChildrenIndex++;
			goto do_return;
		}
Example #48
0
        public ISymbolScope[] GetChildren()
        {
            int count;
            m_target.GetChildren(0, out count, null);
            ISymUnmanagedScope[] uScopes = new ISymUnmanagedScope[count];
            m_target.GetChildren(count, out count, uScopes);

            int i;
            ISymbolScope[] scopes = new ISymbolScope[count];
            for (i = 0; i < count; i++)
            {
                scopes[i] = new SymScope(uScopes[i]);
            }
            return scopes;
        }
Example #49
0
            private string GetLocalVariableName(ISymbolScope scope, uint localIndex)
            {
                ISymbolVariable[] localVariables = null;
                try
                {
                    localVariables = scope.GetLocals();
                    foreach (var localVar in localVariables)
                    {
                        if (localVar.AddressKind == SymAddressKind.ILOffset &&
                            localVar.AddressField1 == localIndex)
                            return localVar.Name;
                    }

                    foreach (var childScope in scope.GetChildren())
                    {
                        string result = GetLocalVariableName(childScope, localIndex);
                        if (result != null)
                            return result;
                    }

                    return null;
                }
                finally
                {
                    if (localVariables != null)
                    {
                        foreach (var localVar in localVariables)
                            ((IDisposable)localVar).Dispose();
                    }
                    ((IDisposable)scope).Dispose();
                }
            }
Example #50
0
        private void WriteLocalsHelper(ISymbolScope scope, Dictionary<int, ImmutableArray<string>> slotNames, bool includeChildScopes)
        {
            foreach (ISymbolVariable l in scope.GetLocals())
            {
                writer.WriteStartElement("local");
                {
                    writer.WriteAttributeString("name", l.Name);

                    // Each local maps to a "IL Index" or "slot" number. 
                    // The index is not necessarily unique. Several locals may refer to the same slot. 
                    // It just means that the same local is known under different names inside the same or different scopes.
                    // This index is what you pass to ICorDebugILFrame::GetLocalVariable() to get
                    // a specific local variable. 
                    // NOTE: VB emits "fake" locals for resumable locals which are actually backed by fields.
                    //       These locals always map to the slot #0 which is just a valid number that is 
                    //       not used. Only scoping information is used by EE in this case.
                    Debug.Assert(l.AddressKind == SymAddressKind.ILOffset);
                    int slot = l.AddressField1;
                    writer.WriteAttributeString("il_index", CultureInvariantToString(slot));

                    bool reusingSlot = false;

                    // collect slot names so that we can verify ISymUnmanagedReader APIs
                    if (slotNames != null)
                    {
                        ImmutableArray<string> existingNames;
                        if (slotNames.TryGetValue(slot, out existingNames))
                        {
                            slotNames[slot] = existingNames.Add(l.Name);
                            reusingSlot = true;
                        }
                        else
                        {
                            slotNames.Add(slot, ImmutableArray.Create(l.Name));
                        }
                    }

                    // Provide scope range
                    writer.WriteAttributeString("il_start", AsILOffset(scope.StartOffset));
                    writer.WriteAttributeString("il_end", AsILOffset(scope.EndOffset));
                    writer.WriteAttributeString("attributes", l.Attributes.ToString());

                    if (reusingSlot)
                    {
                        writer.WriteAttributeString("reusingslot", reusingSlot.ToString(CultureInfo.InvariantCulture));
                    }
                }
                writer.WriteEndElement(); // </local>
            }

            foreach (ISymbolConstant c in ((ISymbolScope2)scope).GetConstants())
            {
                // Note: We can retrieve constant tokens by saving it into signature blob
                // in our implementation of IMetadataImport.GetSigFromToken.
                writer.WriteStartElement("constant");
                {
                    writer.WriteAttributeString("name", c.GetName());
                    
                    object value = c.GetValue();
                    string typeName = value.GetType().Name;

                    // certain Unicode characters will give Xml writers fits...in order to avoid this, we'll replace
                    // problematic characters/sequences with their hexadecimal equivalents, like U+0000, etc...
                    var chars = value as string;
                    if (chars != null)
                    {
                        PooledStringBuilder pooled = PooledStringBuilder.GetInstance();
                        var valueWithPlaceholders = pooled.Builder;
                        foreach (var ch in chars)
                        {
                            // if we end up with more, we can add them here
                            if (0 == (int)ch)
                            {
                                valueWithPlaceholders.AppendFormat("U+{0:X4}", (int)ch);
                            }
                            else
                            {
                                valueWithPlaceholders.Append(ch);
                            }
                        }
                        if (valueWithPlaceholders.Length > chars.Length)
                        {
                            value = valueWithPlaceholders.ToString();
                        }
                        pooled.Free();
                    }

                    writer.WriteAttributeString("value", value.ToString());
                    writer.WriteAttributeString("type", typeName);
                }
                writer.WriteEndElement(); // </constant>
            }
            if (includeChildScopes)
            {
                foreach (ISymbolScope childScope in scope.GetChildren())
                {
                    WriteLocalsHelper(childScope, slotNames, includeChildScopes);
                }
            }
        }