public static ModuleInfo[] GetModuleInfos(int processId) { IntPtr ptr = (IntPtr) (-1); GCHandle handle = new GCHandle(); ArrayList list = new ArrayList(); try { ptr = Microsoft.Win32.NativeMethods.CreateToolhelp32Snapshot(8, processId); if (ptr == ((IntPtr) (-1))) { throw new Win32Exception(); } int num = Marshal.SizeOf(typeof(Microsoft.Win32.NativeMethods.WinModuleEntry)); int val = (num + 260) + 0x100; int[] numArray = new int[val / 4]; handle = GCHandle.Alloc(numArray, GCHandleType.Pinned); IntPtr ptr2 = handle.AddrOfPinnedObject(); Marshal.WriteInt32(ptr2, val); HandleRef ref2 = new HandleRef(null, ptr); if (Microsoft.Win32.NativeMethods.Module32First(ref2, ptr2)) { do { Microsoft.Win32.NativeMethods.WinModuleEntry structure = new Microsoft.Win32.NativeMethods.WinModuleEntry(); Marshal.PtrToStructure(ptr2, structure); ModuleInfo info = new ModuleInfo { baseName = Marshal.PtrToStringAnsi((IntPtr) (((long) ptr2) + num)), fileName = Marshal.PtrToStringAnsi((IntPtr) ((((long) ptr2) + num) + 0x100L)), baseOfDll = structure.modBaseAddr, sizeOfImage = structure.modBaseSize, Id = structure.th32ModuleID }; list.Add(info); Marshal.WriteInt32(ptr2, val); } while (Microsoft.Win32.NativeMethods.Module32Next(ref2, ptr2)); } } finally { if (handle.IsAllocated) { handle.Free(); } if (ptr != ((IntPtr) (-1))) { Microsoft.Win32.SafeNativeMethods.CloseHandle(new HandleRef(null, ptr)); } } ModuleInfo[] array = new ModuleInfo[list.Count]; list.CopyTo(array, 0); return array; }
protected override void Initialize(IServiceProvider serviceProvider, ModuleInfo moduleInfo) { base.Initialize(serviceProvider, moduleInfo); var controlPanel = (IControlPanel)GetService(typeof(IControlPanel)); Debug.Assert(controlPanel != null, "Couldn't get IControlPanel"); //PHPInfo page var modulePageInfo = new ModulePageInfo(this, typeof(PHPInfoPage), Resources.PHPInfoPageTitle, Resources.PHPInfoPageDescription, Resources.PHPLogo16, Resources.PHPLogo32, Resources.PHPInfoPageLongDescription); controlPanel.RegisterPage(modulePageInfo); //PHP Settings page modulePageInfo = new ModulePageInfo(this, typeof(AllSettingsPage), Resources.AllSettingsPageTitle, Resources.AllSettingsPageDescription, Resources.PHPLogo16, Resources.PHPLogo32, Resources.AllSettingsPageLongDescription); controlPanel.RegisterPage(modulePageInfo); modulePageInfo = new ModulePageInfo(this, typeof(ErrorReportingPage), Resources.ErrorReportingPageTitle, Resources.ErrorReportingPageDescription, Resources.PHPLogo16, Resources.PHPLogo32, Resources.ErrorReportingPageLongDescription); controlPanel.RegisterPage(modulePageInfo); modulePageInfo = new ModulePageInfo(this, typeof(RuntimeLimitsPage), Resources.RuntimeLimitsPageTitle, Resources.RuntimeLimitsPageDescription, Resources.PHPLogo16, Resources.PHPLogo32, Resources.RuntimeLimitsPageLongDescription); controlPanel.RegisterPage(modulePageInfo); //PHP Extensions page modulePageInfo = new ModulePageInfo(this, typeof(AllExtensionsPage), Resources.AllExtensionsPageTitle, Resources.AllExtensionsPageDescription, Resources.PHPLogo16, Resources.PHPLogo32, Resources.AllExtensionsPageLongDescription); controlPanel.RegisterPage(modulePageInfo); //PHPPage - PHP feature start page modulePageInfo = new ModulePageInfo(this, typeof(PHPPage), Resources.PHPPageTitle, Resources.PHPPageDescription, Resources.PHPLogo16, Resources.PHPLogo32, Resources.PHPPageLongDescription); controlPanel.RegisterPage(ControlPanelCategoryInfo.Iis, modulePageInfo); controlPanel.RegisterPage(ControlPanelCategoryInfo.ApplicationDevelopment, modulePageInfo); }
private static ModuleInfo[] GetModuleInfos(int processId, bool firstModuleOnly) { Contract.Ensures(Contract.Result<ModuleInfo[]>().Length >= 1); // preserving Everett behavior. if( processId == SystemProcessID || processId == IdleProcessID) { // system process and idle process doesn't have any modules throw new Win32Exception(HResults.EFail,SR.GetString(SR.EnumProcessModuleFailed)); } SafeProcessHandle processHandle = SafeProcessHandle.InvalidHandle; try { processHandle = ProcessManager.OpenProcess(processId, NativeMethods.PROCESS_QUERY_INFORMATION | NativeMethods.PROCESS_VM_READ, true); IntPtr[] moduleHandles = new IntPtr[64]; GCHandle moduleHandlesArrayHandle = new GCHandle(); int moduleCount = 0; for (;;) { bool enumResult = false; try { moduleHandlesArrayHandle = GCHandle.Alloc(moduleHandles, GCHandleType.Pinned); enumResult = NativeMethods.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); // The API we need to use to enumerate process modules differs on two factors: // 1) If our process is running in WOW64. // 2) The bitness of the process we wish to introspect. // // If we are not running in WOW64 or we ARE in WOW64 but want to inspect a 32 bit process // we can call psapi!EnumProcessModules. // // If we are running in WOW64 and we want to inspect the modules of a 64 bit process then // psapi!EnumProcessModules will return false with ERROR_PARTIAL_COPY (299). In this case we can't // do the enumeration at all. So we'll detect this case and bail out. // // Also, EnumProcessModules is not a reliable method to get the modules for a process. // If OS loader is touching module information, this method might fail and copy part of the data. // This is no easy solution to this problem. The only reliable way to fix this is to // suspend all the threads in target process. Of course we don't want to do this in Process class. // So we just to try avoid the ---- by calling the same method 50 (an arbitary number) times. // if (!enumResult) { bool sourceProcessIsWow64 = false; bool targetProcessIsWow64 = false; if (!ProcessManager.IsOSOlderThanXP) { SafeProcessHandle hCurProcess = SafeProcessHandle.InvalidHandle; try { hCurProcess = ProcessManager.OpenProcess(NativeMethods.GetCurrentProcessId(), NativeMethods.PROCESS_QUERY_INFORMATION, true); bool wow64Ret; wow64Ret = SafeNativeMethods.IsWow64Process(hCurProcess, ref sourceProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } wow64Ret = SafeNativeMethods.IsWow64Process(processHandle, ref targetProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } if (sourceProcessIsWow64 && !targetProcessIsWow64) { // Wow64 isn't going to allow this to happen, the best we can do is give a descriptive error to the user. throw new Win32Exception(NativeMethods.ERROR_PARTIAL_COPY, SR.GetString(SR.EnumProcessModuleFailedDueToWow)); } } finally { if (hCurProcess != SafeProcessHandle.InvalidHandle) { hCurProcess.Close(); } } } // If the failure wasn't due to Wow64, try again. for (int i = 0; i < 50; i++) { enumResult = NativeMethods.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); if (enumResult) { break; } Thread.Sleep(1); } } } finally { moduleHandlesArrayHandle.Free(); } if (!enumResult) { throw new Win32Exception(); } moduleCount /= IntPtr.Size; if (moduleCount <= moduleHandles.Length) break; moduleHandles = new IntPtr[moduleHandles.Length * 2]; } ArrayList moduleInfos = new ArrayList(); int ret; for (int i = 0; i < moduleCount; i++) { try { ModuleInfo moduleInfo = new ModuleInfo(); IntPtr moduleHandle = moduleHandles[i]; NativeMethods.NtModuleInfo ntModuleInfo = new NativeMethods.NtModuleInfo(); if (!NativeMethods.GetModuleInformation(processHandle, new HandleRef(null, moduleHandle), ntModuleInfo, Marshal.SizeOf(ntModuleInfo))) throw new Win32Exception(); moduleInfo.sizeOfImage = ntModuleInfo.SizeOfImage; moduleInfo.entryPoint = ntModuleInfo.EntryPoint; moduleInfo.baseOfDll = ntModuleInfo.BaseOfDll; StringBuilder baseName = new StringBuilder(1024); ret = NativeMethods.GetModuleBaseName(processHandle, new HandleRef(null, moduleHandle), baseName, baseName.Capacity * 2); if (ret == 0) throw new Win32Exception(); moduleInfo.baseName = baseName.ToString(); StringBuilder fileName = new StringBuilder(1024); ret = NativeMethods.GetModuleFileNameEx(processHandle, new HandleRef(null, moduleHandle), fileName, fileName.Capacity * 2); if (ret == 0) throw new Win32Exception(); moduleInfo.fileName = fileName.ToString(); // smss.exe is started before the win32 subsystem so it get this funny "\systemroot\.." path. // We change this to the actual path by appending "smss.exe" to GetSystemDirectory() if (string.Compare(moduleInfo.fileName, "\\SystemRoot\\System32\\smss.exe", StringComparison.OrdinalIgnoreCase) == 0) { moduleInfo.fileName = Path.Combine(Environment.SystemDirectory, "smss.exe"); } // Avoid returning Unicode-style long string paths. IO methods cannot handle them. if (moduleInfo.fileName != null && moduleInfo.fileName.Length >= 4 && moduleInfo.fileName.StartsWith(@"\\?\", StringComparison.Ordinal)) { moduleInfo.fileName = moduleInfo.fileName.Substring(4); } moduleInfos.Add(moduleInfo); } catch (Win32Exception e) { if (e.NativeErrorCode == NativeMethods.ERROR_INVALID_HANDLE || e.NativeErrorCode == NativeMethods.ERROR_PARTIAL_COPY) { // It's possible that another thread casued this module to become // unloaded (e.g FreeLibrary was called on the module). Ignore it and // move on. } else { throw; } } // // If the user is only interested in the main module, break now. // This avoid some waste of time. In addition, if the application unloads a DLL // we will not get an exception. // if( firstModuleOnly) { break; } } ModuleInfo[] temp = new ModuleInfo[moduleInfos.Count]; moduleInfos.CopyTo(temp, 0); return temp; } finally { Debug.WriteLineIf(Process.processTracing.TraceVerbose, "Process - CloseHandle(process)"); if (!processHandle.IsInvalid ) { processHandle.Close(); } } }
public static ModuleInfo[] GetModuleInfos(int processId) { IntPtr handle = (IntPtr)(-1); GCHandle bufferHandle = new GCHandle(); ArrayList moduleInfos = new ArrayList(); try { handle = NativeMethods.CreateToolhelp32Snapshot(NativeMethods.TH32CS_SNAPMODULE, processId); if (handle == (IntPtr)(-1)) throw new Win32Exception(); int entrySize = Marshal.SizeOf(typeof(NativeMethods.WinModuleEntry)); int bufferSize = entrySize + NativeMethods.WinModuleEntry.sizeofFileName + NativeMethods.WinModuleEntry.sizeofModuleName; int[] buffer = new int[bufferSize / 4]; bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); IntPtr bufferPtr = bufferHandle.AddrOfPinnedObject(); Marshal.WriteInt32(bufferPtr, bufferSize); HandleRef handleRef = new HandleRef(null, handle); if (NativeMethods.Module32First(handleRef, bufferPtr)) { do { NativeMethods.WinModuleEntry module = new NativeMethods.WinModuleEntry(); Marshal.PtrToStructure(bufferPtr, module); ModuleInfo moduleInfo = new ModuleInfo(); moduleInfo.baseName = Marshal.PtrToStringAnsi((IntPtr)((long)bufferPtr + entrySize)); moduleInfo.fileName = Marshal.PtrToStringAnsi((IntPtr)((long)bufferPtr + entrySize + NativeMethods.WinModuleEntry.sizeofModuleName)); moduleInfo.baseOfDll = module.modBaseAddr; moduleInfo.sizeOfImage = module.modBaseSize; moduleInfo.Id = module.th32ModuleID; moduleInfos.Add(moduleInfo); Marshal.WriteInt32(bufferPtr, bufferSize); } while (NativeMethods.Module32Next(handleRef, bufferPtr)); } } finally { if (bufferHandle.IsAllocated) bufferHandle.Free(); Debug.WriteLineIf(Process.processTracing.TraceVerbose, "Process - CloseHandle(toolhelp32 snapshot handle)"); if (handle != (IntPtr)(-1)) SafeNativeMethods.CloseHandle(handle); } ModuleInfo[] temp = new ModuleInfo[moduleInfos.Count]; moduleInfos.CopyTo(temp, 0); return temp; }
private static ModuleInfo[] GetModuleInfos(int processId, bool firstModuleOnly) { // preserving Everett behavior. if (processId == SystemProcessID || processId == IdleProcessID) { // system process and idle process doesn't have any modules throw new Win32Exception(Interop.mincore.Errors.EFail, SR.EnumProcessModuleFailed); } SafeProcessHandle processHandle = SafeProcessHandle.InvalidHandle; try { processHandle = ProcessManager.OpenProcess(processId, Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.mincore.ProcessOptions.PROCESS_VM_READ, true); IntPtr[] moduleHandles = new IntPtr[64]; GCHandle moduleHandlesArrayHandle = new GCHandle(); int moduleCount = 0; for (; ; ) { bool enumResult = false; try { moduleHandlesArrayHandle = GCHandle.Alloc(moduleHandles, GCHandleType.Pinned); enumResult = Interop.mincore.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); // The API we need to use to enumerate process modules differs on two factors: // 1) If our process is running in WOW64. // 2) The bitness of the process we wish to introspect. // // If we are not running in WOW64 or we ARE in WOW64 but want to inspect a 32 bit process // we can call psapi!EnumProcessModules. // // If we are running in WOW64 and we want to inspect the modules of a 64 bit process then // psapi!EnumProcessModules will return false with ERROR_PARTIAL_COPY (299). In this case we can't // do the enumeration at all. So we'll detect this case and bail out. // // Also, EnumProcessModules is not a reliable method to get the modules for a process. // If OS loader is touching module information, this method might fail and copy part of the data. // This is no easy solution to this problem. The only reliable way to fix this is to // suspend all the threads in target process. Of course we don't want to do this in Process class. // So we just to try avoid the race by calling the same method 50 (an arbitrary number) times. // if (!enumResult) { bool sourceProcessIsWow64 = false; bool targetProcessIsWow64 = false; SafeProcessHandle hCurProcess = SafeProcessHandle.InvalidHandle; try { hCurProcess = ProcessManager.OpenProcess(unchecked((int)Interop.mincore.GetCurrentProcessId()), Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION, true); bool wow64Ret; wow64Ret = Interop.mincore.IsWow64Process(hCurProcess, ref sourceProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } wow64Ret = Interop.mincore.IsWow64Process(processHandle, ref targetProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } if (sourceProcessIsWow64 && !targetProcessIsWow64) { // Wow64 isn't going to allow this to happen, the best we can do is give a descriptive error to the user. throw new Win32Exception(Interop.mincore.Errors.ERROR_PARTIAL_COPY, SR.EnumProcessModuleFailedDueToWow); } } finally { if (hCurProcess != SafeProcessHandle.InvalidHandle) { hCurProcess.Dispose(); } } // If the failure wasn't due to Wow64, try again. for (int i = 0; i < 50; i++) { enumResult = Interop.mincore.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); if (enumResult) { break; } Thread.Sleep(1); } } } finally { moduleHandlesArrayHandle.Free(); } if (!enumResult) { throw new Win32Exception(); } moduleCount /= IntPtr.Size; if (moduleCount <= moduleHandles.Length) break; moduleHandles = new IntPtr[moduleHandles.Length * 2]; } List<ModuleInfo> moduleInfos = new List<ModuleInfo>(firstModuleOnly ? 1 : moduleCount); StringBuilder baseName = new StringBuilder(1024); StringBuilder fileName = new StringBuilder(1024); for (int i = 0; i < moduleCount; i++) { if (i > 0) { // If the user is only interested in the main module, break now. // This avoid some waste of time. In addition, if the application unloads a DLL // we will not get an exception. if (firstModuleOnly) { break; } baseName.Clear(); fileName.Clear(); } IntPtr moduleHandle = moduleHandles[i]; Interop.mincore.NtModuleInfo ntModuleInfo = new Interop.mincore.NtModuleInfo(); if (!Interop.mincore.GetModuleInformation(processHandle, moduleHandle, ntModuleInfo, Marshal.SizeOf(ntModuleInfo))) { HandleError(); continue; } ModuleInfo moduleInfo = new ModuleInfo { _sizeOfImage = ntModuleInfo.SizeOfImage, _entryPoint = ntModuleInfo.EntryPoint, _baseOfDll = ntModuleInfo.BaseOfDll }; int ret = Interop.mincore.GetModuleBaseName(processHandle, moduleHandle, baseName, baseName.Capacity); if (ret == 0) { HandleError(); continue; } moduleInfo._baseName = baseName.ToString(); ret = Interop.mincore.GetModuleFileNameEx(processHandle, moduleHandle, fileName, fileName.Capacity); if (ret == 0) { HandleError(); continue; } moduleInfo._fileName = fileName.ToString(); if (moduleInfo._fileName != null && moduleInfo._fileName.Length >= 4 && moduleInfo._fileName.StartsWith(@"\\?\", StringComparison.Ordinal)) { moduleInfo._fileName = fileName.ToString(4, fileName.Length - 4); } moduleInfos.Add(moduleInfo); } return moduleInfos.ToArray(); } finally { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "Process - CloseHandle(process)"); #endif if (!processHandle.IsInvalid) { processHandle.Dispose(); } } }
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.TypeDefinition); Debug.Assert(index >= 0); if (index < 0) throw new InvalidOperationException(); module.Types.RemoveAt(index); info.Types[j] = typeNode.TypeDefinition; info.Indexes[j] = index; } } }
private static extern int JpfsvGetNextModule( IntPtr EnumHandle, ref ModuleInfo Info );
private void LoadDetails(ModuleInfo details) { try { foreach (string category in details.Categories) { int cat = Convert.ToInt32(category); if (nodes.ContainsKey(cat)) LoadDetailsIntoItem(details, nodes[cat].OwnModules.Find(p => ((ModuleInfo)p.Tag).Id == details.Id), cat); } } catch (Exception e) { Trace.WriteLine(e.ToString()); } }
private void LoadDetailsIntoItem(ModuleInfo details, ListViewItem item, int category) { try { item.SubItems[0].Text = details.Title; item.SubItems[1].Text = details.Author; item.SubItems[2].Text = categories.Find(c => c.Id == category).Title; item.SubItems[3].Text = details.Cards.ToString(); item.SubItems[4].Text = Methods.GetFileSize(details.Size); item.Tag = details; if (item.ListView == null) return; if (item.ListView.Tag is bool && (bool)item.ListView.Tag) { item.Group = null; foreach (ListViewGroup group in item.ListView.Groups) { if (group.Header == details.Author) { item.Group = group; break; } } if (item.Group == null) { ListViewGroup grp = new ListViewGroup(details.Author); item.ListView.Groups.Add(grp); item.Group = grp; } } if (details.IconSmall.Length > 0) { item.ListView.SmallImageList.Images.Add(Image.FromStream(new MemoryStream(details.IconSmall))); item.ImageIndex = item.ListView.LargeImageList.Images.Count - 1; } if (details.IconBig.Length > 0) { item.ListView.LargeImageList.Images.Add(Image.FromStream(new MemoryStream(details.IconBig))); item.ImageIndex = item.ListView.LargeImageList.Images.Count - 1; } } catch (Exception e) { Trace.WriteLine(e.ToString()); } }
private static ModuleInfo[] GetModuleInfos(int processId, bool firstModuleOnly) { ModuleInfo[] infoArray2; if ((processId == SystemProcessID) || (processId == 0)) { throw new Win32Exception(-2147467259, SR.GetString("EnumProcessModuleFailed")); } Microsoft.Win32.SafeHandles.SafeProcessHandle invalidHandle = Microsoft.Win32.SafeHandles.SafeProcessHandle.InvalidHandle; try { bool flag; invalidHandle = ProcessManager.OpenProcess(processId, 0x410, true); IntPtr[] ptrArray = new IntPtr[0x40]; GCHandle handle2 = new GCHandle(); int needed = 0; Label_0045: flag = false; try { handle2 = GCHandle.Alloc(ptrArray, GCHandleType.Pinned); flag = Microsoft.Win32.NativeMethods.EnumProcessModules(invalidHandle, handle2.AddrOfPinnedObject(), ptrArray.Length * IntPtr.Size, ref needed); if (!flag) { bool flag2 = false; bool flag3 = false; if (!ProcessManager.IsOSOlderThanXP) { Microsoft.Win32.SafeHandles.SafeProcessHandle hProcess = Microsoft.Win32.SafeHandles.SafeProcessHandle.InvalidHandle; try { hProcess = ProcessManager.OpenProcess(Microsoft.Win32.NativeMethods.GetCurrentProcessId(), 0x400, true); if (!Microsoft.Win32.SafeNativeMethods.IsWow64Process(hProcess, ref flag2)) { throw new Win32Exception(); } if (!Microsoft.Win32.SafeNativeMethods.IsWow64Process(invalidHandle, ref flag3)) { throw new Win32Exception(); } if (flag2 && !flag3) { throw new Win32Exception(0x12b, SR.GetString("EnumProcessModuleFailedDueToWow")); } } finally { if (hProcess != Microsoft.Win32.SafeHandles.SafeProcessHandle.InvalidHandle) { hProcess.Close(); } } } for (int j = 0; j < 50; j++) { flag = Microsoft.Win32.NativeMethods.EnumProcessModules(invalidHandle, handle2.AddrOfPinnedObject(), ptrArray.Length * IntPtr.Size, ref needed); if (flag) { goto Label_012F; } Thread.Sleep(1); } } } finally { handle2.Free(); } Label_012F: if (!flag) { throw new Win32Exception(); } needed /= IntPtr.Size; if (needed > ptrArray.Length) { ptrArray = new IntPtr[ptrArray.Length * 2]; goto Label_0045; } ArrayList list = new ArrayList(); for (int i = 0; i < needed; i++) { ModuleInfo info = new ModuleInfo(); IntPtr handle = ptrArray[i]; Microsoft.Win32.NativeMethods.NtModuleInfo ntModuleInfo = new Microsoft.Win32.NativeMethods.NtModuleInfo(); if (!Microsoft.Win32.NativeMethods.GetModuleInformation(invalidHandle, new HandleRef(null, handle), ntModuleInfo, Marshal.SizeOf(ntModuleInfo))) { throw new Win32Exception(); } info.sizeOfImage = ntModuleInfo.SizeOfImage; info.entryPoint = ntModuleInfo.EntryPoint; info.baseOfDll = ntModuleInfo.BaseOfDll; StringBuilder baseName = new StringBuilder(0x400); if (Microsoft.Win32.NativeMethods.GetModuleBaseName(invalidHandle, new HandleRef(null, handle), baseName, baseName.Capacity * 2) == 0) { throw new Win32Exception(); } info.baseName = baseName.ToString(); StringBuilder builder2 = new StringBuilder(0x400); if (Microsoft.Win32.NativeMethods.GetModuleFileNameEx(invalidHandle, new HandleRef(null, handle), builder2, builder2.Capacity * 2) == 0) { throw new Win32Exception(); } info.fileName = builder2.ToString(); if (string.Compare(info.fileName, @"\SystemRoot\System32\smss.exe", StringComparison.OrdinalIgnoreCase) == 0) { info.fileName = Path.Combine(Environment.SystemDirectory, "smss.exe"); } if (((info.fileName != null) && (info.fileName.Length >= 4)) && info.fileName.StartsWith(@"\\?\", StringComparison.Ordinal)) { info.fileName = info.fileName.Substring(4); } list.Add(info); if (firstModuleOnly) { break; } } ModuleInfo[] array = new ModuleInfo[list.Count]; list.CopyTo(array, 0); infoArray2 = array; } finally { if (!invalidHandle.IsInvalid) { invalidHandle.Close(); } } return infoArray2; }
/// <summary> /// Loads the content of the web. /// </summary> /// <remarks>Documented by Dev05, 2009-06-26</remarks> public void LoadWebContent(object path) { IsListLoaded = false; IsLoaded = false; string configPath = path as string; nodes = new Dictionary<int, FeedCategoryTreeNode>(); if (TreeView.InvokeRequired) TreeView.Invoke((MethodInvoker)delegate { Nodes.Clear(); }); else Nodes.Clear(); try { if (TreeView.InvokeRequired) TreeView.Invoke((MethodInvoker)delegate { Text = String.IsNullOrWhiteSpace(Feed.Name) ? Resources.FeedTreeNode_Name : Feed.Name; }); else Text = String.IsNullOrWhiteSpace(Feed.Name) ? Resources.FeedTreeNode_Name : Feed.Name; #region read categories XmlReader categoryFeedReader = XmlReader.Create(Feed.CategoriesUri); SyndicationFeed categoryFeed = SyndicationFeed.Load(categoryFeedReader); List<ModuleCategory> categoriesToAdd = new List<ModuleCategory>(); foreach (SyndicationItem item in categoryFeed.Items) { ModuleCategory category = new ModuleCategory() { Id = Convert.ToInt32(item.Id), Title = item.Title.Text, ParentCategory = Convert.ToInt32(item.Links[0].Title) }; categoriesToAdd.Add(category); } categoriesToAdd.Sort((a, b) => a.Id.CompareTo(b.Id)); categoriesToAdd.ForEach(c => AddCategoryNode(c)); #endregion #region read modules XmlReader moduleFeedReader = XmlReader.Create(Feed.ModulesUri); SyndicationFeed moduleFeed = SyndicationFeed.Load(moduleFeedReader); List<ModuleInfo> modules = new List<ModuleInfo>(); XmlSerializer infoSerializer = new XmlSerializer(typeof(ModuleInfo)); Dictionary<string, SyndicationItem> items = new Dictionary<string, SyndicationItem>(); foreach (SyndicationItem item in moduleFeed.Items) { ModuleInfo info; if (item.Summary != null) info = (ModuleInfo)infoSerializer.Deserialize(XmlReader.Create(new StringReader(WebUtility.HtmlDecode(item.Summary.Text)))); else info = new ModuleInfo(); info.Id = item.Id; info.Title = item.Title.Text; info.EditDate = item.LastUpdatedTime.ToString(); if (item.Contributors.Count > 0) { info.Author = item.Contributors[0].Name; info.AuthorMail = item.Contributors[0].Email; info.AuthorUrl = item.Contributors[0].Uri; } if (item.Content is TextSyndicationContent) info.Description = (item.Content as TextSyndicationContent).Text; info.Categories = new SerializableList<string>(); foreach (SyndicationCategory cat in item.Categories) info.Categories.Add(cat.Label); foreach (SyndicationLink link in item.Links) { if (link.RelationshipType == AtomLinkRelationshipType.Module.ToString()) { info.Size = link.Length; info.DownloadUrl = link.Uri.AbsoluteUri; } } modules.Add(info); items.Add(info.Id, item); } categories.ForEach(c => nodes[c.Id].SetModuleList(modules.FindAll(p => p.Categories.Contains(c.Id.ToString())))); #endregion if (TreeView.InvokeRequired) TreeView.Invoke((MethodInvoker)delegate { Expand(); }); else Expand(); IsListLoaded = true; OnContentLoaded(EventArgs.Empty); #region read images using (PersistentMemoryCache<ModuleInfoCacheItem> cache = new PersistentMemoryCache<ModuleInfoCacheItem>("Feed_" + moduleFeed.Id)) { WebClient webClient = new WebClient(); foreach (ModuleInfo basicInfo in modules) { try { ModuleInfo info = basicInfo; SyndicationItem item = items[basicInfo.Id]; string cacheKey = String.Format("{0}##{1}##{2}", moduleFeed.Id, item.Id, item.LastUpdatedTime); if (cache.Contains(cacheKey)) { ModuleInfoCacheItem cacheItem = (ModuleInfoCacheItem)cache[cacheKey]; info.IconSmall = Convert.FromBase64String(cacheItem.IconSmall); info.IconBig = Convert.FromBase64String(cacheItem.IconBig); info.Preview = Convert.FromBase64String(cacheItem.Preview); } else { ModuleInfoCacheItem cacheItem = new ModuleInfoCacheItem(info.Id); foreach (SyndicationLink link in item.Links) { if (link.RelationshipType == AtomLinkRelationshipType.IconSmall.ToString()) cacheItem.IconSmall = Convert.ToBase64String(info.IconSmall = webClient.DownloadData(link.Uri)); if (link.RelationshipType == AtomLinkRelationshipType.IconBig.ToString()) cacheItem.IconBig = Convert.ToBase64String(info.IconBig = webClient.DownloadData(link.Uri)); if (link.RelationshipType == AtomLinkRelationshipType.Preview.ToString()) cacheItem.Preview = Convert.ToBase64String(info.Preview = webClient.DownloadData(link.Uri)); } cache.Set(cacheKey, cacheItem, DateTime.Now.AddYears(1)); } if (TreeView.InvokeRequired) TreeView.Invoke((MethodInvoker)delegate { LoadDetails(info); }); else LoadDetails(info); } catch (Exception exp) { Trace.WriteLine(exp.ToString()); } } cache.Dispose(); } #endregion IsLoaded = true; } catch (Exception) { try { if (TreeView.InvokeRequired) TreeView.Invoke((MethodInvoker)delegate { Text = Resources.FeedTreeNode_Text_Offline; }); else Text = Resources.FeedTreeNode_Text_Offline; } catch (ObjectDisposedException) { } } }
public bool Load( Stream stream, IEmulationInstance emulator, uint baseAddress ) { // Relocate only if we need to if( _needsRelocation == false ) baseAddress = 0; _entryAddress += baseAddress; _initAddress += baseAddress; IMemory memory = emulator.Cpu.Memory; foreach( ElfSection section in _allocSections ) { // Sanity check for broken ELFs if( ( baseAddress != 0 ) && ( baseAddress == section.Address ) ) { // Fuckers lied - no relocation needed! _needsRelocation = false; baseAddress = 0; } uint address = baseAddress + section.Address; section.Address = address; if( section.SectionType == ElfSectionType.NoBits ) { // Write zeros? } else if( section.SectionType == ElfSectionType.ProgramBits ) { stream.Seek( section.ElfOffset, SeekOrigin.Begin ); byte[] bytes = new byte[ section.Length ]; stream.Read( bytes, 0, ( int )section.Length ); memory.WriteBytes( ( int )address, bytes ); _upperAddress = Math.Max( _upperAddress, address + ( uint )bytes.Length ); } } BinaryReader reader = new BinaryReader( stream ); ElfSection sceModuleInfo = _sectionLookup[ ".rodata.sceModuleInfo" ]; reader.BaseStream.Seek( sceModuleInfo.ElfOffset, SeekOrigin.Begin ); ModuleInfo moduleInfo = new ModuleInfo( reader ); _globalPointer = baseAddress + moduleInfo.Gp; // Not sure if this is needed - the header seems to give an ok address //if( _programType == ElfType.Prx ) //{ // ElfSection sceResident = _sectionLookup[ ".rodata.sceResident" ]; // reader.BaseStream.Seek( sceResident.ElfOffset, SeekOrigin.Begin ); // // 2 magic words // reader.BaseStream.Seek( 8, SeekOrigin.Current ); // _entryAddress = reader.ReadUInt32(); //} if( _needsRelocation == true ) { //foreach( ElfRelocation relocation in _relocations ) //{ // this.FixRelocation( reader, memory, relocation, baseAddress ); //} foreach( ElfSection section in _relocSections ) { this.ApplyRelocations( reader, memory, section, baseAddress ); } } //result.Stubs = this.FixupStubs( reader, emulator.Cpu, memory, emulator.Bios, baseAddress ); return true; }
private static ModuleInfo[] GetModuleInfos(int processId, bool firstModuleOnly) { Contract.Ensures(Contract.Result <ModuleInfo[]>().Length >= 1); // preserving Everett behavior. if (processId == SystemProcessID || processId == IdleProcessID) { // system process and idle process doesn't have any modules throw new Win32Exception(Interop.EFail, SR.EnumProcessModuleFailed); } SafeProcessHandle processHandle = SafeProcessHandle.InvalidHandle; try { processHandle = ProcessManager.OpenProcess(processId, Interop.PROCESS_QUERY_INFORMATION | Interop.PROCESS_VM_READ, true); IntPtr[] moduleHandles = new IntPtr[64]; GCHandle moduleHandlesArrayHandle = new GCHandle(); int moduleCount = 0; for (; ;) { bool enumResult = false; try { moduleHandlesArrayHandle = GCHandle.Alloc(moduleHandles, GCHandleType.Pinned); enumResult = Interop.mincore.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); // The API we need to use to enumerate process modules differs on two factors: // 1) If our process is running in WOW64. // 2) The bitness of the process we wish to introspect. // // If we are not running in WOW64 or we ARE in WOW64 but want to inspect a 32 bit process // we can call psapi!EnumProcessModules. // // If we are running in WOW64 and we want to inspect the modules of a 64 bit process then // psapi!EnumProcessModules will return false with ERROR_PARTIAL_COPY (299). In this case we can't // do the enumeration at all. So we'll detect this case and bail out. // // Also, EnumProcessModules is not a reliable method to get the modules for a process. // If OS loader is touching module information, this method might fail and copy part of the data. // This is no easy solution to this problem. The only reliable way to fix this is to // suspend all the threads in target process. Of course we don't want to do this in Process class. // So we just to try avoid the race by calling the same method 50 (an arbitary number) times. // if (!enumResult) { bool sourceProcessIsWow64 = false; bool targetProcessIsWow64 = false; SafeProcessHandle hCurProcess = SafeProcessHandle.InvalidHandle; try { hCurProcess = ProcessManager.OpenProcess(unchecked ((int)Interop.mincore.GetCurrentProcessId()), Interop.PROCESS_QUERY_INFORMATION, true); bool wow64Ret; wow64Ret = Interop.mincore.IsWow64Process(hCurProcess, ref sourceProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } wow64Ret = Interop.mincore.IsWow64Process(processHandle, ref targetProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } if (sourceProcessIsWow64 && !targetProcessIsWow64) { // Wow64 isn't going to allow this to happen, the best we can do is give a descriptive error to the user. throw new Win32Exception(Interop.ERROR_PARTIAL_COPY, SR.EnumProcessModuleFailedDueToWow); } } finally { if (hCurProcess != SafeProcessHandle.InvalidHandle) { hCurProcess.Dispose(); } } // If the failure wasn't due to Wow64, try again. for (int i = 0; i < 50; i++) { enumResult = Interop.mincore.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); if (enumResult) { break; } Thread.Sleep(1); } } } finally { moduleHandlesArrayHandle.Free(); } if (!enumResult) { throw new Win32Exception(); } moduleCount /= IntPtr.Size; if (moduleCount <= moduleHandles.Length) { break; } moduleHandles = new IntPtr[moduleHandles.Length * 2]; } List <ModuleInfo> moduleInfos = new List <ModuleInfo>(); int ret; for (int i = 0; i < moduleCount; i++) { try { ModuleInfo moduleInfo = new ModuleInfo(); IntPtr moduleHandle = moduleHandles[i]; Interop.NtModuleInfo ntModuleInfo = new Interop.NtModuleInfo(); if (!Interop.mincore.GetModuleInformation(processHandle, moduleHandle, ntModuleInfo, Marshal.SizeOf(ntModuleInfo))) { throw new Win32Exception(); } moduleInfo.sizeOfImage = ntModuleInfo.SizeOfImage; moduleInfo.entryPoint = ntModuleInfo.EntryPoint; moduleInfo.baseOfDll = ntModuleInfo.BaseOfDll; StringBuilder baseName = new StringBuilder(1024); ret = Interop.mincore.GetModuleBaseName(processHandle, moduleHandle, baseName, baseName.Capacity * 2); if (ret == 0) { throw new Win32Exception(); } moduleInfo.baseName = baseName.ToString(); StringBuilder fileName = new StringBuilder(1024); ret = Interop.mincore.GetModuleFileNameEx(processHandle, moduleHandle, fileName, fileName.Capacity * 2); if (ret == 0) { throw new Win32Exception(); } moduleInfo.fileName = fileName.ToString(); if (moduleInfo.fileName != null && moduleInfo.fileName.Length >= 4 && moduleInfo.fileName.StartsWith(@"\\?\", StringComparison.Ordinal)) { moduleInfo.fileName = moduleInfo.fileName.Substring(4); } moduleInfos.Add(moduleInfo); } catch (Win32Exception e) { if (e.NativeErrorCode == Interop.ERROR_INVALID_HANDLE || e.NativeErrorCode == Interop.ERROR_PARTIAL_COPY) { // It's possible that another thread casued this module to become // unloaded (e.g FreeLibrary was called on the module). Ignore it and // move on. } else { throw; } } // // If the user is only interested in the main module, break now. // This avoid some waste of time. In addition, if the application unloads a DLL // we will not get an exception. // if (firstModuleOnly) { break; } } ModuleInfo[] temp = new ModuleInfo[moduleInfos.Count]; moduleInfos.CopyTo(temp, 0); return(temp); } finally { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process.processTracing.TraceVerbose, "Process - CloseHandle(process)"); #endif if (!processHandle.IsInvalid) { processHandle.Dispose(); } } }
private static ModuleInfo[] GetModuleInfos(int processId, bool firstModuleOnly) { if (processId == NtProcessManager.SystemProcessID || processId == 0) { throw new Win32Exception(-2147467259, "EnumProcessModuleFailed"); } SafeProcessHandle safeProcessHandle = SafeProcessHandle.InvalidHandle; ModuleInfo[] result; try { safeProcessHandle = ProcessManager.OpenProcess(processId, 1040, true); IntPtr[] array = new IntPtr[64]; GCHandle gCHandle = default(GCHandle); int num = 0; while (true) { bool flag = false; try { gCHandle = GCHandle.Alloc(array, GCHandleType.Pinned); flag = NativeMethods.EnumProcessModules(safeProcessHandle, gCHandle.AddrOfPinnedObject(), array.Length * IntPtr.Size, ref num); if (!flag) { bool flag2 = false; bool flag3 = false; if (true) { SafeProcessHandle safeProcessHandle2 = SafeProcessHandle.InvalidHandle; try { safeProcessHandle2 = ProcessManager.OpenProcess(NativeMethods.GetCurrentProcessId(), 1024, true); if (!SafeNativeMethods.IsWow64Process(safeProcessHandle2, ref flag2)) { throw new Win32Exception(); } if (!SafeNativeMethods.IsWow64Process(safeProcessHandle, ref flag3)) { throw new Win32Exception(); } if (flag2 && !flag3) { throw new Win32Exception(299, "EnumProcessModuleFailedDueToWow"); } } finally { if (safeProcessHandle2 != SafeProcessHandle.InvalidHandle) { safeProcessHandle2.Close(); } } } for (int i = 0; i < 50; i++) { flag = NativeMethods.EnumProcessModules(safeProcessHandle, gCHandle.AddrOfPinnedObject(), array.Length * IntPtr.Size, ref num); if (flag) { break; } Thread.Sleep(1); } } } finally { gCHandle.Free(); } if (!flag) { break; } num /= IntPtr.Size; if (num <= array.Length) { goto IL_157; } array = new IntPtr[array.Length * 2]; } throw new Win32Exception(); IL_157: ArrayList arrayList = new ArrayList(); for (int j = 0; j < num; j++) { try { ModuleInfo moduleInfo = new ModuleInfo(); IntPtr handle = array[j]; NativeMethods.NtModuleInfo ntModuleInfo = new NativeMethods.NtModuleInfo(); if (!NativeMethods.GetModuleInformation(safeProcessHandle, new HandleRef(null, handle), ntModuleInfo, Marshal.SizeOf(ntModuleInfo))) { throw new Win32Exception(); } moduleInfo.sizeOfImage = ntModuleInfo.SizeOfImage; moduleInfo.entryPoint = ntModuleInfo.EntryPoint; moduleInfo.baseOfDll = ntModuleInfo.BaseOfDll; StringBuilder stringBuilder = new StringBuilder(1024); if (NativeMethods.GetModuleBaseName(safeProcessHandle, new HandleRef(null, handle), stringBuilder, stringBuilder.Capacity * 2) == 0) { throw new Win32Exception(); } moduleInfo.baseName = stringBuilder.ToString(); StringBuilder stringBuilder2 = new StringBuilder(1024); if (NativeMethods.GetModuleFileNameEx(safeProcessHandle, new HandleRef(null, handle), stringBuilder2, stringBuilder2.Capacity * 2) == 0) { throw new Win32Exception(); } moduleInfo.fileName = stringBuilder2.ToString(); if (string.Compare(moduleInfo.fileName, "\\SystemRoot\\System32\\smss.exe", StringComparison.OrdinalIgnoreCase) == 0) { moduleInfo.fileName = Path.Combine(Environment.SystemDirectory, "smss.exe"); } if (moduleInfo.fileName != null && moduleInfo.fileName.Length >= 4 && moduleInfo.fileName.StartsWith("\\\\?\\", StringComparison.Ordinal)) { moduleInfo.fileName = moduleInfo.fileName.Substring(4); } arrayList.Add(moduleInfo); } catch (Win32Exception ex) { if (ex.NativeErrorCode != 6 && ex.NativeErrorCode != 299) { throw; } } if (firstModuleOnly) { break; } } ModuleInfo[] array2 = new ModuleInfo[arrayList.Count]; arrayList.CopyTo(array2, 0); result = array2; } finally { if (!safeProcessHandle.IsInvalid) { safeProcessHandle.Close(); } } return result; }
public IEnumerable<ModuleInfo> GetModuleInfos() { ToolHelpHandle ptr = null; var list = new List<ModuleInfo>(); try { ptr = CreateToolhelp32Snapshot(0x8, ProcessId); if (ptr.IsInvalid) { throw new Win32Exception(); } var me32 = new MODULEENTRY32(); me32.dwSize = (uint)Marshal.SizeOf(me32); if (Module32First(ptr, ref me32)) { do { ModuleInfo info = new ModuleInfo { baseName = me32.szModule, fileName = me32.szExePath, baseOfDll = me32.modBaseAddr, sizeOfImage = (int)me32.modBaseSize, Id = (int)me32.th32ModuleID }; list.Add(info); me32.dwSize = (uint)Marshal.SizeOf(me32); } while (Module32Next(ptr, ref me32)); } if (Marshal.GetLastWin32Error() != 18) //ERROR_NO_MORE_FILES throw new Win32Exception(); } finally { if (ptr != null && !ptr.IsInvalid) { ptr.Close(); } } return list; }
/// <devdoc> /// Initialize the module. /// </devdoc> /// <internalonly/> internal ProcessModule(ModuleInfo moduleInfo) { _moduleInfo = moduleInfo; }
/// <devdoc> /// Initialize the module. /// </devdoc> /// <internalonly/> internal ProcessModule(ModuleInfo moduleInfo) { this.moduleInfo = moduleInfo; GC.SuppressFinalize(this); }
public bool NextItem(ref ModuleInfo Info) { Debug.Assert(m_EnumHandle != null); Info.Size = (uint)Marshal.SizeOf(typeof(ModuleInfo)); int hr = JpfsvGetNextModule(m_EnumHandle, ref Info); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); throw new InvalidOperationException("Cannot get here"); } else if (hr == 1) { return false; } else { return true; } }