Beispiel #1
0
        /// <summary>
        /// Jumps to the specified reference.
        /// </summary>
        /// <returns>
        /// Returns a task that will signal completion when the decompilation of the jump target has finished.
        /// The task will be marked as canceled if the decompilation is canceled.
        /// </returns>
        public Task JumpToReferenceAsync(object reference)
        {
            decompilationTask = TaskHelper.CompletedTask;
            ILSpyTreeNode treeNode = FindTreeNode(reference);

            if (treeNode != null)
            {
                SelectNode(treeNode);
            }
            else if (reference is Mono.Cecil.Cil.OpCode)
            {
                string link = "http://msdn.microsoft.com/library/system.reflection.emit.opcodes." + ((Mono.Cecil.Cil.OpCode)reference).Code.ToString().ToLowerInvariant() + ".aspx";
                try {
                    Process.Start(link);
                } catch {
                }
            }
            return(decompilationTask);
        }
Beispiel #2
0
        public static DataGrid PrepareDataGrid(TabPageModel tabPage, ILSpyTreeNode selectedNode)
        {
            if (!(tabPage.Content is DataGrid view && view.Name == "MetadataView"))
            {
                view = new MetaDataGrid()
                {
                    Name = "MetadataView",
                    GridLinesVisibility        = DataGridGridLinesVisibility.None,
                    CanUserAddRows             = false,
                    CanUserDeleteRows          = false,
                    CanUserReorderColumns      = false,
                    HeadersVisibility          = DataGridHeadersVisibility.Column,
                    EnableColumnVirtualization = true,
                    EnableRowVirtualization    = true,
                    RowHeight        = 20,
                    IsReadOnly       = true,
                    SelectionMode    = DataGridSelectionMode.Single,
                    SelectionUnit    = DataGridSelectionUnit.FullRow,
                    SelectedTreeNode = selectedNode,
                    CellStyle        = (Style)MetadataTableViews.Instance["DataGridCellStyle"],
                };
                ContextMenuProvider.Add(view);
                DataGridFilter.SetIsAutoFilterEnabled(view, true);
                DataGridFilter.SetContentFilterFactory(view, new RegexContentFilterFactory());
            }
            DataGridFilter.GetFilter(view).Clear();
            view.RowDetailsTemplateSelector       = null;
            view.RowDetailsVisibilityMode         = DataGridRowDetailsVisibilityMode.Collapsed;
            view.EnableColumnVirtualization       = true;
            view.EnableRowVirtualization          = true;
            ((MetaDataGrid)view).SelectedTreeNode = selectedNode;
            if (!view.AutoGenerateColumns)
            {
                view.Columns.Clear();
            }
            view.AutoGenerateColumns = true;

            view.AutoGeneratingColumn += View_AutoGeneratingColumn;
            view.AutoGeneratedColumns += View_AutoGeneratedColumns;

            return(view);
        }
Beispiel #3
0
        public static void WriteOffsetComment(this ITextOutput output, IResourceNode node)
        {
            if (!DecompilerSettingsPanel.CurrentDecompilerSettings.ShowTokenAndRvaComments)
            {
                return;
            }

            ulong fo = node.FileOffset;

            if (fo == 0)
            {
                return;
            }

            var mod      = ILSpyTreeNode.GetModule((SharpTreeNode)node);
            var filename = mod == null ? null : mod.Location;

            output.WriteReference(string.Format("0x{0:X8}", fo), new AddressReference(filename, false, fo, node.Length), TextTokenType.Comment);
            output.Write(": ", TextTokenType.Comment);
        }
Beispiel #4
0
        FieldDefSettingsCommand(FieldTreeNode fieldNode, FieldDefOptions options)
        {
            this.fieldNode   = fieldNode;
            this.newOptions  = options;
            this.origOptions = new FieldDefOptions(fieldNode.FieldDefinition);

            this.origParentNode       = (ILSpyTreeNode)fieldNode.Parent;
            this.origParentChildIndex = this.origParentNode.Children.IndexOf(fieldNode);
            Debug.Assert(this.origParentChildIndex >= 0);
            if (this.origParentChildIndex < 0)
            {
                throw new InvalidOperationException();
            }

            this.nameChanged = origOptions.Name != newOptions.Name;
            if (this.nameChanged)
            {
                this.memberRefInfos = RefFinder.FindMemberRefsToThisModule(ILSpyTreeNode.GetModule(fieldNode)).Where(a => RefFinder.FieldEqualityComparerInstance.Equals(a, fieldNode.FieldDefinition)).Select(a => new MemberRefInfo(a)).ToArray();
            }
        }
        public void JumpToReference(object reference)
        {
            ILSpyTreeNode treeNode = FindTreeNode(reference);

            if (treeNode != null)
            {
                SelectNode(treeNode);
            }
            else if (reference is Mono.Cecil.Cil.OpCode)
            {
                string link = "http://msdn.microsoft.com/library/system.reflection.emit.opcodes." + ((Mono.Cecil.Cil.OpCode)reference).Code.ToString().ToLowerInvariant() + ".aspx";
                try
                {
                    Process.Start(link);
                }
                catch
                {
                }
            }
        }
Beispiel #6
0
		TypeDefSettingsCommand(ModuleDef module, TypeTreeNode typeNode, TypeDefOptions options)
		{
			this.module = module;
			this.typeNode = typeNode;
			this.newOptions = options;
			this.origOptions = new TypeDefOptions(typeNode.TypeDefinition);

			this.origParentNode = (ILSpyTreeNode)typeNode.Parent;
			this.origParentChildIndex = this.origParentNode.Children.IndexOf(typeNode);
			Debug.Assert(this.origParentChildIndex >= 0);
			if (this.origParentChildIndex < 0)
				throw new InvalidOperationException();

			this.nameChanged = origOptions.Name != newOptions.Name;
			if (this.origParentNode is NamespaceTreeNode) {
				var asmNode = (AssemblyTreeNode)this.origParentNode.Parent;
				if (AssemblyTreeNode.NamespaceStringComparer.Compare(newOptions.Namespace, origOptions.Namespace) != 0)
					this.nsNodeCreator = new NamespaceTreeNodeCreator(newOptions.Namespace, asmNode);
			}
		}
Beispiel #7
0
        static AddressReference GetAddressReference(ContextMenuEntryContext context)
        {
            if (context.SelectedTreeNodes == null || context.SelectedTreeNodes.Length != 1)
            {
                return(null);
            }

            var rsrc = context.SelectedTreeNodes[0] as IResourceNode;

            if (rsrc != null && rsrc.FileOffset != 0)
            {
                var mod = ILSpyTreeNode.GetModule((ILSpyTreeNode)rsrc);
                if (mod != null && File.Exists(mod.Location))
                {
                    return(new AddressReference(mod.Location, false, rsrc.FileOffset, rsrc.Length));
                }
            }

            return(null);
        }
Beispiel #8
0
        private void DecompileSelectedNodes(DecompilerTextViewState state = null)
        {
            if (ignoreDecompilationRequests)
            {
                return;
            }

            if (treeView.SelectedItems.Count == 1)
            {
                ILSpyTreeNode node = treeView.SelectedItem as ILSpyTreeNode;
                if (node != null && node.View(decompilerTextView))
                {
                    return;
                }
            }
            decompilerTextView.Decompile(this.CurrentLanguage, this.SelectedNodes, new DecompilationOptions()
            {
                TextViewState = state
            });
        }
Beispiel #9
0
		static void Execute(ILSpyTreeNode[] nodes)
		{
			if (!CanExecute(nodes))
				return;

			var typeNode = (TypeTreeNode)nodes[0];

			var module = ILSpyTreeNode.GetModule(nodes[0]);
			Debug.Assert(module != null);
			if (module == null)
				throw new InvalidOperationException();

			var data = new TypeOptionsVM(new TypeDefOptions(typeNode.TypeDefinition), module, MainWindow.Instance.CurrentLanguage, typeNode.TypeDefinition);
			var win = new TypeOptionsDlg();
			win.DataContext = data;
			win.Owner = MainWindow.Instance;
			if (win.ShowDialog() != true)
				return;

			UndoCommandManager.Instance.Add(new TypeDefSettingsCommand(module, typeNode, data.CreateTypeDefOptions()));
		}
Beispiel #10
0
        public static bool IsInSameModule(this ILSpyTreeNode[] nodes)
        {
            if (nodes == null || nodes.Length == 0)
            {
                return(false);
            }
            var module = ILSpyTreeNode.GetModule(nodes[0]);

            if (module == null)
            {
                return(false);
            }
            for (int i = 0; i < nodes.Length; i++)
            {
                if (module != ILSpyTreeNode.GetModule(nodes[i]))
                {
                    return(false);
                }
            }
            return(true);
        }
Beispiel #11
0
        private static void RenamePath(ILSpyTreeNode node, string[] path, string oldName, string newName)
        {
            if (node is TypeTreeNode)
            {
                string oldns;
                TypeParts(oldName, out oldns, out oldName);

                string newns;
                TypeParts(newName, out newns, out newName);

                if (path.Length > 1)
                {
                    path[path.Length - 2] = path[path.Length - 2].Replace(oldns, newns);
                }
            }

            if (path.Length > 0)
            {
                path[path.Length - 1] = path[path.Length - 1].Replace(oldName, newName);
            }
        }
Beispiel #12
0
        public InjectWindowViewModel(ILSpyTreeNode node, Window window, bool canInjectExisting)
        {
            //Stores the given parameters
            _node   = node;
            _window = window;
            InjectExistingEnabled = canInjectExisting;

            //Loads the injectors
            Injectors = GlobalContainer.Injectors.Where(x => x.CanInjectInNode(node)).ToArray();

            //Writes data for the header
            InjectInIcon    = (ImageSource)node.Icon;
            InjectInContent = node.Text;

            //Finds the module
            var moduleNode = Helpers.Tree.GetModuleNode(node);

            DestinationModule = moduleNode == null ? null : moduleNode.Module;

            //Finds the enclosing type (if any)
            EnclosingType = Helpers.Tree.GetType(node);

            //Prepares the filters for the inject existing part
            if (canInjectExisting)
            {
                ExistingMemberFilter      = node is ModuleTreeNode ? MemberFilters.Types : null;
                ExistingSelectableMembers = node is ModuleTreeNode ? new[] { TokenType.TypeDef } : new[] { TokenType.TypeDef, TokenType.Field, TokenType.Property, TokenType.Method, TokenType.Event };
            }

            //Prepares the commands
            _InjectCommand = new RelayCommand(InjectCommandImpl);

            //Loads from the settings the values of the properties of the 'existing' part
            var settings = GlobalContainer.InjectionSettings.Element("InjectExistingSettings");

            ExistingPreview = bool.Parse(settings.Attribute("Preview").Value);
            ExistingImportAsNestedTypesEnabled = !(node is ModuleTreeNode);
            ExistingImportAsNestedTypes        = ExistingImportAsNestedTypesEnabled && bool.Parse(settings.Attribute("ImportAsNestedTypes").Value);
        }
Beispiel #13
0
        internal static string GetFilename(ILSpyTreeNode node)
        {
            var asmNode = ILSpyTreeNode.GetNode <AssemblyTreeNode>(node);

            if (asmNode == null)
            {
                return(null);
            }
            var mod = asmNode.DnSpyFile.ModuleDef;

            if (mod != null && File.Exists(mod.Location))
            {
                return(mod.Location);
            }
            var peImage = asmNode.DnSpyFile.PEImage;

            if (peImage != null && File.Exists(peImage.FileName))
            {
                return(peImage.FileName);
            }
            return(null);
        }
Beispiel #14
0
            public void Delete(NamespaceTreeNode[] nodes, ILSpyTreeNode[] parents)
            {
                Debug.Assert(parents != null && nodes.Length == parents.Length);
                Debug.Assert(infos == null);
                if (infos != null)
                {
                    throw new InvalidOperationException();
                }

                infos = new ModuleInfo[nodes.Length];

                for (int i = 0; i < infos.Length; i++)
                {
                    var node   = nodes[i];
                    var module = ILSpyTreeNode.GetModule(parents[i]);
                    Debug.Assert(module != null);
                    if (module == null)
                    {
                        throw new InvalidOperationException();
                    }

                    var info = new ModuleInfo(module, node.Children.Count);
                    infos[i] = info;

                    for (int j = 0; j < node.Children.Count; j++)
                    {
                        var typeNode = (TypeTreeNode)node.Children[j];
                        int index    = module.Types.IndexOf(typeNode.TypeDef);
                        Debug.Assert(index >= 0);
                        if (index < 0)
                        {
                            throw new InvalidOperationException();
                        }
                        module.Types.RemoveAt(index);
                        info.Types[j]   = typeNode.TypeDef;
                        info.Indexes[j] = index;
                    }
                }
            }
Beispiel #15
0
        static LoadedAssembly GetLoadedAssembly(SharpTreeNode node)
        {
            var asmNode = ILSpyTreeNode.GetNode <AssemblyTreeNode>(node);

            if (asmNode == null)
            {
                return(null);
            }

            var module = asmNode.LoadedAssembly.ModuleDefinition as ModuleDefMD;

            if (module == null)
            {
                return(null);
            }
            if (!module.MetaData.PEImage.IsMemoryMappedIO)
            {
                return(null);
            }

            return(asmNode.LoadedAssembly);
        }
Beispiel #16
0
        internal static void Execute(ILSpyTreeNode[] nodes, uint[] offsets = null)
        {
            if (!CanExecute(nodes))
            {
                return;
            }

            var methodNode = (MethodTreeNode)nodes[0];

            var module = ILSpyTreeNode.GetModule(nodes[0]);

            Debug.Assert(module != null);
            if (module == null)
            {
                throw new InvalidOperationException();
            }

            var data = new MethodBodyVM(new MethodBodyOptions(methodNode.MethodDefinition), module, MainWindow.Instance.CurrentLanguage, methodNode.MethodDefinition.DeclaringType, methodNode.MethodDefinition);
            var win  = new MethodBodyDlg();

            win.DataContext = data;
            win.Owner       = MainWindow.Instance;
            win.Title       = string.Format("{0} - {1}", win.Title, methodNode.ToString());

            if (data.IsCilBody && offsets != null)
            {
                data.CilBodyVM.Select(offsets);
            }

            if (win.ShowDialog() != true)
            {
                return;
            }

            UndoCommandManager.Instance.Add(new MethodBodySettingsCommand(methodNode, data.CreateMethodBodyOptions()));
        }
Beispiel #17
0
		static void Execute(ILSpyTreeNode[] nodes)
		{
			if (!CanExecute(nodes))
				return;

			var nsNode = ILSpyTreeNode.GetNode<NamespaceTreeNode>(nodes[0]);
			string ns = nsNode == null ? string.Empty : nsNode.Name;

			var module = ILSpyTreeNode.GetModule(nodes[0]);
			Debug.Assert(module != null);
			if (module == null)
				throw new InvalidOperationException();
			var options = TypeDefOptions.Create(ns, TypeConstants.DEFAULT_TYPE_NAME, module.CorLibTypes.Object.TypeDefOrRef, false);

			var data = new TypeOptionsVM(options, module, MainWindow.Instance.CurrentLanguage, null);
			var win = new TypeOptionsDlg();
			win.Title = "Create Type";
			win.DataContext = data;
			win.Owner = MainWindow.Instance;
			if (win.ShowDialog() != true)
				return;

			UndoCommandManager.Instance.Add(new CreateTypeDefCommand(module.Types, nodes[0], data.CreateTypeDefOptions()));
		}
Beispiel #18
0
        ObservableCollection <TabInfo> CreateCollection()
        {
            var list = new List <TabInfo>();

            foreach (var tabState in MainWindow.Instance.GetTabStateInOrder())
            {
                var info = new TabInfo();
                info.TabState = tabState;
                var module = ILSpyTreeNode.GetModule(tabState.DecompiledNodes);
                if (module != null)
                {
                    info.FirstModuleName     = module.Name;
                    info.FirstModuleFullName = module.Location;
                }
                else
                {
                    info.FirstModuleName     = string.Empty;
                    info.FirstModuleFullName = string.Empty;
                }
                list.Add(info);
            }
            list.Sort((a, b) => StringComparer.InvariantCultureIgnoreCase.Compare(a.TabState.ShortHeader, b.TabState.ShortHeader));
            return(new ObservableCollection <TabInfo>(list));
        }
Beispiel #19
0
 public void ShowNode(AvalonEditTextOutput textOutput, ILSpyTreeNode node, IHighlightingDefinition highlighting = null)
 {
     ShowNodes(textOutput, new[] { node }, highlighting);
 }
Beispiel #20
0
            /// <summary>
            /// Adds a TypeDefinition to the given node
            /// </summary>
            /// <param name="node">Destination node</param>
            /// <param name="type">Type to inject</param>
            /// <param name="afterModule">Action to call when the destination module is available</param>
            /// <param name="afterEnclosingType">Action to call when the enclosing type is available</param>
            public static void AddTreeNode(ILSpyTreeNode node, TypeDefinition type, Action <ModuleDefinition> afterModule, Action <TypeDefinition> afterEnclosingType)
            {
                //Ensures the lazy children of the node
                node.EnsureLazyChildren();

                //Checks if the node is a module or not
                if (node is ModuleTreeNode)
                {
                    //Module node
                    var moduleNode = (ModuleTreeNode)node;

                    //Injects in the module
                    var module = moduleNode.Module;
                    module.Types.Add(type);
                    if (afterModule != null)
                    {
                        afterModule(module);
                    }

                    //Checks for the namespace
                    var namespaceNode =
                        moduleNode.Children
                        .OfType <NamespaceTreeNode>()
                        .FirstOrDefault(x => x.Text.ToString().ToLower() == (string.IsNullOrEmpty(type.Namespace) ? "-" : type.Namespace.ToLower()));
                    if (namespaceNode != null)
                    {
                        //Adds the node to the namespace
                        namespaceNode.Children.Add(new ILEditTreeNode(type, false));
                        SortChildren(namespaceNode);
                    }
                    else
                    {
                        //Creates a new namespace containing the new type and adds it to the module node
                        namespaceNode = new NamespaceTreeNode(type.Namespace);
                        namespaceNode.Children.Add(new ILEditTreeNode(type, false));
                        moduleNode.Children.Add(namespaceNode);
                        SortChildren(moduleNode);
                    }
                }
                else
                {
                    //Marks the class as nested public
                    type.Attributes    |= TypeAttributes.NestedPublic;
                    type.IsNestedPublic = true;

                    //Injects in the type
                    var type2 = (TypeDefinition)((IMemberTreeNode)node).Member;
                    type2.NestedTypes.Add(type);
                    if (afterEnclosingType != null)
                    {
                        afterEnclosingType(type2);
                    }

                    //Adds a node to the tree
                    node.Children.Add(new ILEditTreeNode(type, false));
                    if (node is ILEditTreeNode)
                    {
                        ((ILEditTreeNode)node).RefreshChildren();
                    }
                    else
                    {
                        SortChildren((TypeTreeNode)node);
                    }
                }
            }
Beispiel #21
0
        static void Execute(ILSpyTreeNode[] nodes)
        {
            if (!CanExecute(nodes))
            {
                return;
            }

            var ownerNode = nodes[0];

            if (!(ownerNode is TypeTreeNode))
            {
                ownerNode = (ILSpyTreeNode)ownerNode.Parent;
            }
            var typeNode = ownerNode as TypeTreeNode;

            Debug.Assert(typeNode != null);
            if (typeNode == null)
            {
                throw new InvalidOperationException();
            }

            var module = ILSpyTreeNode.GetModule(typeNode);

            Debug.Assert(module != null);
            if (module == null)
            {
                throw new InvalidOperationException();
            }

            FieldDefOptions options;
            var             type = typeNode.TypeDefinition;

            if (type.IsEnum)
            {
                var ts = type.GetEnumUnderlyingType();
                if (ts != null)
                {
                    options             = FieldDefOptions.Create("MyField", new FieldSig(new ValueTypeSig(typeNode.TypeDefinition)));
                    options.Constant    = module.UpdateRowId(new ConstantUser(ModelUtils.GetDefaultValue(ts), ts.RemovePinnedAndModifiers().GetElementType()));
                    options.Attributes |= FieldAttributes.Literal | FieldAttributes.Static | FieldAttributes.HasDefault;
                }
                else
                {
                    options             = FieldDefOptions.Create("value__", new FieldSig(module.CorLibTypes.Int32));
                    options.Attributes |= FieldAttributes.SpecialName | FieldAttributes.RTSpecialName;
                }
            }
            else if (type.IsAbstract && type.IsSealed)
            {
                options             = FieldDefOptions.Create("MyField", new FieldSig(module.CorLibTypes.Int32));
                options.Attributes |= FieldAttributes.Static;
            }
            else
            {
                options = FieldDefOptions.Create("MyField", new FieldSig(module.CorLibTypes.Int32));
            }

            var data = new FieldOptionsVM(options, module, MainWindow.Instance.CurrentLanguage, type);
            var win  = new FieldOptionsDlg();

            win.Title       = "Create Field";
            win.DataContext = data;
            win.Owner       = MainWindow.Instance;
            if (win.ShowDialog() != true)
            {
                return;
            }

            UndoCommandManager.Instance.Add(new CreateFieldDefCommand(typeNode, data.CreateFieldDefOptions()));
        }
 public bool CanInjectInNode(ILSpyTreeNode node)
 {
     //Can inject only in ReferenceFolderTreeNode
     return(node is ReferenceFolderTreeNode);
 }