/// <summary>
        ///     Overrides the <see cref="Execute"/> method exposed by the <see cref="SwedishCodeActivity{T}"/> class.
        /// </summary>
        /// <param name="context">The execution context passed when invoked.</param>
        /// <returns>A string back to the caller.</returns>
        /// <inheritdoc cref="SwedishCodeActivity{T}"/>
        protected override object Execute(CodeActivityContext context)
        {
            // TODO: Move to SwedishCodeActivity (with void signature)
            FirstArgument  = FirstInArgument;
            SecondArgument = SecondInArgument;

            string stringProcessId = context.GetValue(FirstArgument);
            string targetPath      = context.GetValue(SecondArgument);

            // Sanity check to help the caller out.
            if (!targetPath.EndsWith("\\"))
            {
                targetPath += "\\";
            }

            // We want this to hard fail.
            int processId = int.Parse(stringProcessId);

            using (Process process = Process.GetProcessById(processId))
            {
                // Process contains a list of loaded modules, which also contains the
                // Native Images loaded, as well; which /can/ be important for debugging
                // purposes (thus, the need to copy them out).
                ProcessModuleCollection modules = process.Modules;

                // Should always be the case, since we're running in the LSA context,
                // but better safe to check than to be sorry and null-reference.
                if (modules.Count > 0)
                {
                    // Added overhead but necessary for parallel operations.
                    List <ProcessModule> modulesList   = modules.Cast <ProcessModule>().ToList();
                    StringBuilder        stringBuilder = new StringBuilder();
                    stringBuilder.AppendLine("Copied: ");
                    Parallel.ForEach(
                        modulesList,
                        module =>
                    {
                        string targetPathQualified = targetPath + module.ModuleName;

                        // TODO: Requires investigation. This is a workaround to prevent duplication
                        if (!File.Exists(targetPathQualified))
                        {
                            File.Copy(module.FileName, targetPathQualified);
                            stringBuilder.AppendLine(module.ModuleName);
                        }
                    });

                    return(stringBuilder.ToString());
                }
                else
                {
                    return("No modules were found to copy...");
                }
            }
        }
        public void TestModuleCollectionBehavior()
        {
            ProcessModule[] mArray = Process.GetCurrentProcess().Modules.Cast <ProcessModule>().ToArray();

            // Constructor
            ProcessModuleCollection moduleCollection = new ProcessModuleCollection(mArray);

            // Count
            Assert.Equal(mArray.Count(), moduleCollection.Count);

            // get_item, Contains, IndexOf
            for (int i = 0; i < mArray.Count(); i++)
            {
                Assert.Equal(mArray[i], moduleCollection[i]);
                Assert.True(moduleCollection.Contains(mArray[i]));
                Assert.Equal(i, moduleCollection.IndexOf(mArray[i]));
            }

            // CopyTo
            ProcessModule[] moduleArray = new ProcessModule[moduleCollection.Count + 1];
            moduleCollection.CopyTo(moduleArray, 1);
            for (int i = 0; i < mArray.Count(); i++)
            {
                Assert.Equal(mArray[i], moduleArray[i + 1]);
            }

            Assert.Throws <ArgumentOutOfRangeException>(() => moduleCollection.CopyTo(moduleArray, -1));

            // Explicit interface implementations
            Assert.False(((ICollection)moduleCollection).IsSynchronized);
            Assert.NotNull(((ICollection)moduleCollection).SyncRoot);

            moduleArray = new ProcessModule[moduleCollection.Count];
            ((ICollection)moduleCollection).CopyTo(moduleArray, 0);
            Assert.Equal(moduleCollection.Cast <ProcessModule>().ToArray(), moduleArray);

            // GetEnumerator
            IEnumerator enumerator = moduleCollection.GetEnumerator();

            Assert.Throws <InvalidOperationException>(() => enumerator.Current);

            for (int i = 0; i < moduleCollection.Count; i++)
            {
                enumerator.MoveNext();
                Assert.Equal(moduleCollection[i], enumerator.Current);
            }
        }
예제 #3
0
        public void TestModuleCollectionBehavior()
        {
            ProcessModule[] mArray = Process.GetCurrentProcess().Modules.Cast<ProcessModule>().ToArray();

            // Constructor
            ProcessModuleCollection moduleCollection = new ProcessModuleCollection(mArray);

            // Count
            Assert.Equal(mArray.Count(), moduleCollection.Count);

            // get_item, Contains, IndexOf
            for (int i = 0; i < mArray.Count(); i++)
            {
                Assert.Equal(mArray[i], moduleCollection[i]);
                Assert.True(moduleCollection.Contains(mArray[i]));
                Assert.Equal(i, moduleCollection.IndexOf(mArray[i]));
            }

            // CopyTo
            ProcessModule[] moduleArray = new ProcessModule[moduleCollection.Count + 1];
            moduleCollection.CopyTo(moduleArray, 1);
            for (int i = 0; i < mArray.Count(); i++)
            {
                Assert.Equal(mArray[i], moduleArray[i + 1]);
            }

            Assert.Throws<ArgumentOutOfRangeException>(() => moduleCollection.CopyTo(moduleArray, -1));

            // Explicit interface implementations
            Assert.False(((ICollection)moduleCollection).IsSynchronized);
            Assert.NotNull(((ICollection)moduleCollection).SyncRoot);

            moduleArray = new ProcessModule[moduleCollection.Count];
            ((ICollection)moduleCollection).CopyTo(moduleArray, 0);
            Assert.Equal(moduleCollection.Cast<ProcessModule>().ToArray(), moduleArray);

            // GetEnumerator
            IEnumerator enumerator = moduleCollection.GetEnumerator();
            Assert.Throws<InvalidOperationException>(() => enumerator.Current);

            for (int i = 0; i < moduleCollection.Count; i++)
            {
                enumerator.MoveNext();
                Assert.Equal(moduleCollection[i], enumerator.Current);
            }
        }
예제 #4
0
        public unsafe static IEnumerable <ProcessModule> AppendHiddenModules(this ProcessModuleCollection collection, Process process = null)
        {
            var    hModules = new IntPtr[1024];
            var    gcHandle = GCHandle.Alloc(hModules, GCHandleType.Pinned); // Don't forget to free this later
            var    pModules = gcHandle.AddrOfPinnedObject();
            var    size     = (uint)(Marshal.SizeOf(typeof(IntPtr)) * (hModules.Length));
            IntPtr minAddress;
            IntPtr maxAddress;
            uint   hProcess;
            MEMORY_BASIC_INFORMATION memBasicInfo;
            uint regionSize               = 0;
            var  sysInfo                  = new SYSTEM_INFO();
            var  processsModuleType       = typeof(ProcessModule);
            var  moduleInfoType           = processsModuleType.Assembly.GetTypes().SingleOrDefault(t => t.FullName == "System.Diagnostics.ModuleInfo");
            var  processModuleConstructor = processsModuleType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { moduleInfoType }, null);
            var  list        = new List <ProcessModule>(collection.Cast <ProcessModule>());
            var  listAddFrom = new List <ProcessModule>();

            GetSystemInfo(out sysInfo);

            minAddress = sysInfo.MinimumApplicationAddress;
            maxAddress = sysInfo.MaximumApplicationAddress;

            if (process == null)
            {
                process = Process.GetCurrentProcess();
            }

            hProcess = OpenProcess(ProcessAccessFlags.QueryInformation | ProcessAccessFlags.VirtualMemoryRead, false, (uint)process.Id);

            memBasicInfo = new MEMORY_BASIC_INFORMATION();

            while (minAddress.ToPointer() < maxAddress.ToPointer())
            {
                uint length  = 0;
                var  builder = new StringBuilder(1024);
                builder.Clear();

                VirtualQueryEx(hProcess, minAddress, out memBasicInfo, 28);

                regionSize = memBasicInfo.RegionSize;

                if (memBasicInfo.Protect == AllocationProtectEnum.PAGE_READONLY | memBasicInfo.Protect == AllocationProtectEnum.PAGE_READWRITE | memBasicInfo.Protect == AllocationProtectEnum.PAGE_EXECUTE_READ | memBasicInfo.Protect == AllocationProtectEnum.PAGE_EXECUTE_READWRITE)
                {
                    length = GetMappedFileName(hProcess, memBasicInfo.BaseAddress, builder, 1024);

                    if (length != 0)
                    {
                        uint   bytesRead  = 0;
                        var    buffer     = new byte[memBasicInfo.RegionSize];
                        var    deviceName = builder.ToString();
                        byte[] bytes;
                        string magic;
                        string signature;

                        ReadProcessMemory(hProcess, memBasicInfo.BaseAddress, buffer, memBasicInfo.RegionSize, ref bytesRead);

                        if (bytesRead >= (DOSHeader.Size + PEHeader.Size))
                        {
                            var assemblyReader = new BinaryReader(buffer.ToMemory());
                            var dosHeader      = DOSHeader.ReadDOSHeader(assemblyReader);

                            bytes = BitConverter.GetBytes(dosHeader.MagicBytes);
                            magic = ASCIIEncoding.ASCII.GetString(bytes, 0, 2);

                            if (magic == "MZ")
                            {
                                var peheader = PEHeader.ReadPEHeader(assemblyReader, dosHeader.COFFHeaderAddress);

                                bytes     = BitConverter.GetBytes(peheader.SignatureBytes);
                                signature = ASCIIEncoding.ASCII.GetString(bytes, 0, 2);

                                if (signature == "PE")
                                {
                                    string fileName;
                                    Files.ConvertDevicePathToLocalPath(deviceName, out fileName);

                                    if (!collection.Cast <ProcessModule>().Any(m => m.FileName.AsCaseless() == fileName))
                                    {
                                        var           moduleInfo = Activator.CreateInstance(moduleInfoType);
                                        string        baseName;
                                        ProcessModule processModule;

                                        baseName = Path.GetFileName(fileName);

                                        moduleInfoType.SetFieldValue("baseName", moduleInfo, baseName);
                                        moduleInfoType.SetFieldValue("baseOfDll", moduleInfo, new IntPtr(memBasicInfo.BaseAddress));
                                        moduleInfoType.SetFieldValue("entryPoint", moduleInfo, new IntPtr(peheader.AddressOfEntryPoint));
                                        moduleInfoType.SetFieldValue("fileName", moduleInfo, fileName);
                                        moduleInfoType.SetFieldValue("sizeOfImage", moduleInfo, (int)peheader.SizeOfImage);

                                        processModule = (ProcessModule)processModuleConstructor.Invoke(new object[] { moduleInfo });

                                        regionSize = peheader.SizeOfImage;

                                        listAddFrom.Add(processModule);
                                    }
                                }
                            }
                        }
                    }
                }

                minAddress += (int)regionSize;
            }

            return(list.Concat(listAddFrom));
        }
예제 #5
0
        public void SetItems(ProcessModuleCollection processModules)
        {
            if (this.Created == false)
            {
                return;
            }

            List <ListViewItem>  list = new List <ListViewItem>();
            List <ProcessModule> processModuleList = processModules.Cast <ProcessModule>().ToList();

            processModuleList.Sort(delegate(ProcessModule a, ProcessModule b)
            {
                return(a.BaseAddress.ToInt64().CompareTo(b.BaseAddress.ToInt64()));
            });

            try
            {
                foreach (ProcessModule processModule in processModuleList)
                {
                    ListViewItem item = new ListViewItem();
                    item.Text = processModule.ModuleName;

                    string startAddress      = String.Format("0x{0}", processModule.BaseAddress.ToString("X16"));
                    string endAddress        = String.Format("0x{0}", (processModule.BaseAddress.ToInt64() + processModule.ModuleMemorySize).ToString("X16"));
                    string entryPointAddress = String.Format("0x{0}", processModule.EntryPointAddress.ToString("X16"));

                    item.SubItems.Add(startAddress);
                    item.SubItems.Add(endAddress);
                    item.SubItems.Add(entryPointAddress);
                    item.SubItems.Add(processModule.FileVersionInfo.ProductVersion);
                    item.SubItems.Add(processModule.FileVersionInfo.FileVersion);
                    item.SubItems.Add(processModule.FileVersionInfo.FileDescription);
                    item.SubItems.Add(processModule.FileVersionInfo.FileName);

                    try
                    {
                        string fileName  = processModule.FileVersionInfo.FileName;
                        string extension = Path.GetExtension(fileName).ToLower();
                        item.ImageKey = extension;

                        if (SmallImageList.Images.ContainsKey(extension) == false)
                        {
                            Icon icon = IconTools.GetIconForFile(fileName, ShellIconSize.SmallIcon);
                            if (icon != null)
                            {
                                SmallImageList.Images.Add(icon);
                                SmallImageList.Images.SetKeyName(SmallImageList.Images.Count - 1, extension);
                            }
                        }
                    }
                    catch
                    {
                    }
                    item.Tag = processModule;

                    list.Add(item);
                }
            }
            catch
            {
            }

            BeginUpdate();
            Items.Clear();
            Items.AddRange(list.ToArray());
            AutoResizeColumns();
            EndUpdate();
        }