public DebugStructType(IStructType llvmType
                        , NativeModule module
                        , DIScope scope
                        , string name
                        , DIFile file
                        , uint line
                        , DebugInfoFlags debugFlags
                        , DIType derivedFrom
                        , IEnumerable <DIType> elements
                        , uint alignment = 0
                        )
     : base(llvmType)
 {
     module.VerifyArgNotNull(nameof(module));
     DIType = module.DIBuilder
              .CreateStructType(scope
                                , name
                                , file
                                , line
                                , module.Layout.BitSizeOf(llvmType)
                                , alignment
                                , debugFlags
                                , derivedFrom
                                , elements
                                );
 }
        private DIDerivedType CreateMemberType(NativeModule module, DebugMemberInfo memberInfo)
        {
            UInt64 bitSize;
            UInt32 bitAlign;
            UInt64 bitOffset;

            // if explicit layout info provided, use it;
            // otherwise use module.Layout as the default
            if (memberInfo.ExplicitLayout != null)
            {
                bitSize   = memberInfo.ExplicitLayout.BitSize;
                bitAlign  = memberInfo.ExplicitLayout.BitAlignment;
                bitOffset = memberInfo.ExplicitLayout.BitOffset;
            }
            else
            {
                bitSize   = module.Layout.BitSizeOf(memberInfo.DebugType.NativeType);
                bitAlign  = 0;
                bitOffset = module.Layout.BitOffsetOfElement(NativeType, memberInfo.Index);
            }

            return(module.DIBuilder.CreateMemberType(scope: DIType
                                                     , name: memberInfo.Name
                                                     , file: memberInfo.File
                                                     , line: memberInfo.Line
                                                     , bitSize: bitSize
                                                     , bitAlign: bitAlign
                                                     , bitOffset: bitOffset
                                                     , debugFlags: memberInfo.DebugInfoFlags
                                                     , type: memberInfo.DebugType.DIType
                                                     ));
        }
Exemple #3
0
        private NativeModule CreateSimpleModule(string name, Context ctx = null)
        {
            var retVal = new NativeModule(name, ctx);

            CreateSimpleVoidNopTestFunction(retVal, name);
            return(retVal);
        }
        public override Version GetVersionPresent(object feature)
        {
            if (feature == DesktopComposition)
            {
                if (OnVista)
                {
                    using (var dwmapi = NativeModule.TryLoad("dwmapi.dll"))
                    {
                        if (dwmapi != null)
                        {
                            if (dwmapi.ContainsProcedure("DwmIsCompositionEnabled"))
                            {
                                return(new Version(0, 0, 0, 0));
                            }
                        }
                    }
                }
            }

            if (feature == DropShadow)
            {
                if (OnXP)
                {
                    return(new Version(0, 0, 0, 0));
                }
            }

            return(base.GetVersionPresent(feature));
        }
Exemple #5
0
 private static void AddModuleFlags(NativeModule module)
 {
     module.AddModuleFlag(ModuleFlagBehavior.Warning, NativeModule.DwarfVersionValue, 4);
     module.AddModuleFlag(ModuleFlagBehavior.Warning, NativeModule.DebugVersionValue, NativeModule.DebugMetadataVersion);
     TargetDetails.AddModuleFlags(module);
     module.AddVersionIdentMetadata(VersionIdentString);
 }
Exemple #6
0
        public void ComdatFunctionTest( )
        {
            using (var module = new NativeModule(TestModuleName))
            {
                const string comdatName = "testcomdat";
                const string globalName = "globalwithcomdat";

                Comdat comdat = module.Comdats.Add(comdatName, ComdatKind.SameSize);
                Assert.AreEqual(comdatName, comdat.Name);
                Assert.AreEqual(ComdatKind.SameSize, comdat.Kind);
                Assert.AreEqual(1, module.Comdats.Count);
                CreateSimpleVoidNopTestFunction(module, globalName)
                .Linkage(Linkage.LinkOnceODR)
                .Comdat(globalName);

                Assert.AreEqual(2, module.Comdats.Count, "Unsaved module should have all comdats even if unused");
                Assert.IsTrue(module.Comdats.Contains(comdatName));
                Assert.IsTrue(module.Comdats.Contains(globalName));
                Assert.AreEqual(comdatName, module.Comdats[comdatName].Name);
                Assert.AreEqual(globalName, module.Comdats[globalName].Name);
                Assert.AreEqual(ComdatKind.SameSize, module.Comdats[comdatName].Kind);
                Assert.AreEqual(ComdatKind.Any, module.Comdats[globalName].Kind);

                using (var context2 = new Context( ))
                {
                    var clone = module.Clone(context2);
                    Assert.AreEqual(1, clone.Comdats.Count, "Comdat count should contain the one and only referenced comdat after save/clone");
                    Assert.IsTrue(clone.Comdats.Contains(globalName), "Cloned module should have the referenced comdat");
                    var clonedGlobal = clone.GetFunction(globalName);
                    Assert.AreEqual(globalName, clonedGlobal.Comdat.Name, "Name of the comdat on the cloned global should match the one set in the original module");
                    Assert.AreEqual(ComdatKind.Any, module.Comdats[globalName].Kind);
                }
            }
        }
Exemple #7
0
        public void WriteToFileTest( )
        {
            string path = Path.GetTempFileName( );

            try
            {
                using (var module = new NativeModule(TestModuleName))
                {
                    Function testFunc = CreateSimpleVoidNopTestFunction(module, "foo");
                    module.WriteToFile(path);
                }

                using (var ctx = new Context( ))
                    using (var module2 = NativeModule.LoadFrom(path, ctx))
                    {
                        Function testFunc = module2.GetFunction("foo");

                        // verify basics
                        Assert.IsNotNull(testFunc);
                        string txt = module2.WriteToString( );
                        Assert.IsFalse(string.IsNullOrWhiteSpace(txt));
                        string expectedText = File.ReadAllText("TestModuleAsString.ll")
                                              .Replace("; ModuleID = 'test'", $"; ModuleID = '{path}'");
                        Assert.AreEqual(expectedText, txt);
                    }
            }
            finally
            {
                File.Delete(path);
            }
        }
        private static byte[] DumpDotNetModule(NativeModule module, ImageLayout imageLayout, out string fileName)
        {
            try {
                byte[] peImageData;
                bool   isDotNet;

                peImageData = PEImageHelper.DirectCopy(module, imageLayout);
                peImageData = PEImageHelper.ConvertImageLayout(peImageData, imageLayout, ImageLayout.File);
                using (PEImage peImage = new PEImage(peImageData, true)) {
                    // 确保为有效PE文件
                    fileName = peImage.GetOriginalFilename() ?? ((IntPtr)module.Handle).ToString((ulong)module.Handle > uint.MaxValue ? "X16" : "X8");
                    isDotNet = peImage.ImageNTHeaders.OptionalHeader.DataDirectories[14].VirtualAddress != 0;
                    if (isDotNet)
                    {
                        try {
                            using (ModuleDefMD moduleDef = ModuleDefMD.Load(peImage)) {
                            }
                            // 再次验证是否为.NET程序集
                        }
                        catch {
                            isDotNet = false;
                        }
                    }
                }
                return(isDotNet ? peImageData : null);
            }
            catch {
                fileName = default;
                return(null);
            }
        }
        /// <summary>Creates a new <see cref="DebugArrayType"/></summary>
        /// <param name="llvmType">Underlying LLVM array type to bind debug info to</param>
        /// <param name="elementType">Array element type with debug information</param>
        /// <param name="module">module to use for creating debug information</param>
        /// <param name="count">Number of elements in the array</param>
        /// <param name="lowerBound">Lower bound of the array [default = 0]</param>
        /// <param name="alignment">Alignment for the type</param>
        public DebugArrayType(IArrayType llvmType
                              , IDebugType <ITypeRef, DIType> elementType
                              , NativeModule module
                              , uint count
                              , uint lowerBound = 0
                              , uint alignment  = 0
                              )
            : base(llvmType)
        {
            if (llvmType == null)
            {
                throw new ArgumentNullException(nameof(llvmType));
            }

            if (elementType == null)
            {
                throw new ArgumentNullException(nameof(elementType));
            }

            if (llvmType.ElementType.TypeHandle != elementType.TypeHandle)
            {
                throw new ArgumentException("elementType doesn't match array element type");
            }

            DIType           = CreateDebugInfoForArray(llvmType, elementType, module, count, lowerBound, alignment);
            DebugElementType = elementType;
        }
Exemple #10
0
        public DebugUnionType(NativeModule module
                              , string nativeName
                              , DIScope scope
                              , string name
                              , DIFile file
                              , uint line = 0
                              )
        {
            if (module == null)
            {
                throw new ArgumentNullException(nameof(module));
            }

            if (file == null)
            {
                throw new ArgumentNullException(nameof(file));
            }

            NativeType = module.Context.CreateStructType(nativeName);
            DIType     = module.DIBuilder
                         .CreateReplaceableCompositeType(Tag.UnionType
                                                         , name
                                                         , scope
                                                         , file
                                                         , line
                                                         );
        }
Exemple #11
0
        protected override void OnStart()
        {
            _module   = NativeModule.Load(_moduleName);
            _callback = _module.GetProcedureAddress(_functionName);

            _hook = NativeMethods.SetWindowsHookEx(_hookType, _callback, _module, _threadId);
        }
        public void SetBody(bool packed
                            , NativeModule module
                            , DIScope scope
                            , DIFile diFile
                            , uint line
                            , DebugInfoFlags debugFlags
                            , IEnumerable <ITypeRef> nativeElements
                            , IEnumerable <DebugMemberInfo> debugElements
                            , DIType derivedFrom = null
                            , uint?bitSize       = null
                            , uint bitAlignment  = 0
                            )
        {
            DebugMembers = new ReadOnlyCollection <DebugMemberInfo>(debugElements as IList <DebugMemberInfo> ?? debugElements.ToList( ));
            SetBody(packed, nativeElements.ToArray());
            var memberTypes = from memberInfo in DebugMembers
                              select CreateMemberType(module, memberInfo);

            var concreteType = module.DIBuilder.CreateStructType(scope: scope
                                                                 , name: DIType.Name
                                                                 , file: diFile
                                                                 , line: line
                                                                 , bitSize: bitSize ?? module.Layout.BitSizeOf(NativeType)
                                                                 , bitAlign: bitAlignment
                                                                 , debugFlags: debugFlags
                                                                 , derivedFrom: derivedFrom
                                                                 , elements: memberTypes
                                                                 );

            DIType = concreteType;
        }
Exemple #13
0
 /// <summary>Constructs a new <see cref="DebugArrayType"/></summary>
 /// <param name="elementType">Type of elements in the array</param>
 /// <param name="module"><see cref="NativeModule"/> to use for the context of the debug information</param>
 /// <param name="count">Number of elements in the array</param>
 /// <param name="lowerBound"><see cref="LowerBound"/> value for the array indices [Default: 0]</param>
 public DebugArrayType(IDebugType <ITypeRef, DIType> elementType, NativeModule module, uint count, uint lowerBound = 0)
     : this(elementType.VerifyArgNotNull(nameof(elementType)).CreateArrayType(count)
            , elementType
            , module
            , count
            , lowerBound
            )
 {
 }
Exemple #14
0
 /// <summary>Constructs a new <see cref="DebugPointerType"/></summary>
 /// <param name="llvmElementType">Native type of the pointee</param>
 /// <param name="module"><see cref="NativeModule"/> used for creating the pointer type and debug information</param>
 /// <param name="elementType">Debug type of the pointee</param>
 /// <param name="addressSpace">Target address space for the pointer [Default: 0]</param>
 /// <param name="name">Name of the type [Default: null]</param>
 /// <param name="alignment">Alignment of pointer</param>
 public DebugPointerType(ITypeRef llvmElementType, NativeModule module, DIType elementType, uint addressSpace = 0, string name = null, uint alignment = 0)
     : this(llvmElementType.VerifyArgNotNull(nameof(llvmElementType)).CreatePointerType(addressSpace)
            , module
            , elementType
            , name
            , alignment
            )
 {
 }
Exemple #15
0
 public void AddGlobalTest( )
 {
     using (var module = new NativeModule(TestModuleName))
     {
         module.AddGlobal(module.Context.Int32Type, "TestInt");
         GlobalVariable globalVar = module.GetNamedGlobal("TestInt");
         Assert.AreEqual("TestInt", globalVar.Name);
         Assert.AreSame(module.Context.Int32Type.CreatePointerType( ), globalVar.NativeType);
     }
 }
Exemple #16
0
 /// <summary>Constructs a new <see cref="DebugPointerType"/></summary>
 /// <param name="debugElementType">Debug type of the pointee</param>
 /// <param name="module"><see cref="NativeModule"/> used for creating the pointer type and debug information</param>
 /// <param name="addressSpace">Target address space for the pointer [Default: 0]</param>
 /// <param name="name">Name of the type [Default: null]</param>
 /// <param name="alignment">Alignment on pointer</param>
 public DebugPointerType(IDebugType <ITypeRef, DIType> debugElementType, NativeModule module, uint addressSpace = 0, string name = null, uint alignment = 0)
     : this(debugElementType.VerifyArgNotNull(nameof(debugElementType)).NativeType
            , module
            , debugElementType.VerifyArgNotNull(nameof(debugElementType)).DIType
            , addressSpace
            , name
            , alignment
            )
 {
 }
Exemple #17
0
 private static ClrModule TryGetDacModule(NativeModule module)
 {
     try {
         using (DataTarget dataTarget = DataTarget.AttachToProcess((int)module.Process.Id, 3000, AttachFlag.Passive))
             return(dataTarget.ClrVersions.SelectMany(t => t.CreateRuntime().Modules).First(t => (void *)t.ImageBase == module.Handle));
     }
     catch {
         return(null);
     }
 }
Exemple #18
0
 public DebugPointerType(IPointerType llvmPtrType, NativeModule module, DIType elementType, string name = null, uint alignment = 0)
     : base(llvmPtrType)
 {
     module.VerifyArgNotNull(nameof(module));
     DIType = module.DIBuilder
              .CreatePointerType(elementType
                                 , name
                                 , module.Layout.BitSizeOf(llvmPtrType)
                                 , alignment
                                 );
 }
Exemple #19
0
 public void BasicLinkTest( )
 {
     // verifies linked modules can be disposed
     using (var ctx = new Context( ))
         using (var module = new NativeModule(TestModuleName, ctx))
             using (var otherModule = new NativeModule("Other", ctx))
             {
                 module.Link(otherModule);
                 Assert.IsNull(otherModule.Context);
             }
 }
Exemple #20
0
 public void MultiContextLinkTest( )
 {
     using (var mergedMod = new NativeModule( ))
         using (var m1 = CreateSimpleModule("module1"))
             using (var m2 = CreateSimpleModule("module2"))
             {
                 Assert.AreNotSame(mergedMod.Context, m1.Context);
                 Assert.AreNotSame(mergedMod.Context, m2.Context);
                 mergedMod.Link(m1); // exception expected here.
             }
 }
Exemple #21
0
        private static Function CreateInvalidFunction(NativeModule module, string name)
        {
            var ctx = module.Context;

            var testFunc = module.AddFunction(name, ctx.GetFunctionType(ctx.VoidType));

            testFunc.AppendBasicBlock("entry");

            // UNTERMINATED BLOCK INTENTIONAL
            return(testFunc);
        }
Exemple #22
0
        private static void CreateDoCopyFunctionBody(NativeModule module
                                                     , DataLayout layout
                                                     , Function doCopyFunc
                                                     , IStructType foo
                                                     , GlobalVariable bar
                                                     , GlobalVariable baz
                                                     , Function copyFunc
                                                     )
        {
            var bytePtrType = module.Context.Int8Type.CreatePointerType( );

            // create block for the function body, only need one for this simple sample
            var blk = doCopyFunc.AppendBasicBlock("entry");

            // create instruction builder to build the body
            var instBuilder = new InstructionBuilder(blk);

            bool param0ByVal = copyFunc.Attributes[FunctionAttributeIndex.Parameter0].Contains(AttributeKind.ByVal);

            if (!param0ByVal)
            {
                // create a temp local copy of the global structure
                var dstAddr = instBuilder.Alloca(foo)
                              .RegisterName("agg.tmp")
                              .Alignment(layout.CallFrameAlignmentOf(foo));

                var bitCastDst = instBuilder.BitCast(dstAddr, bytePtrType)
                                 .SetDebugLocation(25, 11, doCopyFunc.DISubProgram);

                var bitCastSrc = instBuilder.BitCast(bar, bytePtrType)
                                 .SetDebugLocation(25, 11, doCopyFunc.DISubProgram);

                instBuilder.MemCpy(module
                                   , bitCastDst
                                   , bitCastSrc
                                   , module.Context.CreateConstant(layout.ByteSizeOf(foo))
                                   , ( int )layout.CallFrameAlignmentOf(foo)
                                   , false
                                   ).SetDebugLocation(25, 11, doCopyFunc.DISubProgram);

                instBuilder.Call(copyFunc, dstAddr, baz)
                .SetDebugLocation(25, 5, doCopyFunc.DISubProgram);
            }
            else
            {
                instBuilder.Call(copyFunc, bar, baz)
                .SetDebugLocation(25, 5, doCopyFunc.DISubProgram)
                .AddAttributes(FunctionAttributeIndex.Parameter0, copyFunc.Parameters[0].Attributes);
            }

            instBuilder.Return( )
            .SetDebugLocation(26, 1, doCopyFunc.DISubProgram);
        }
 private void Serialize(NativeModule m)
 {
     Serialize(m.Name);
     Serialize(m.BaseOfImage);
     Serialize(m.SizeOfImage);
     Serialize(m.Timestamp);
     Serialize(m.Version.Major);
     Serialize(m.Version.Minor);
     Serialize(m.Version.Build);
     Serialize(m.Version.Revision);
     Serialize(m.CvData);
 }
Exemple #24
0
        public void OperandsAreAccessibleTest()
        {
            using (var module = new NativeModule("test.bc", SourceLanguage.CSharp, "test.cs", "unittests"))
                using (var targetMachine = TargetTests.GetTargetMachine(module.Context))
                {
                    module.Layout = targetMachine.TargetData;
                    var intType   = new DebugBasicType(module.Context.Int32Type, module, "int", DiTypeKind.Signed);
                    var arrayType = new DebugArrayType(intType, module, 3u);
                    Assert.IsNotNull(arrayType);

                    var mdnode = arrayType.DIType as DICompositeType;
                    Assert.IsNotNull(mdnode.Operands);
                    Assert.AreEqual(8, mdnode.Operands.Count);

                    Assert.IsNotNull(mdnode.Operands[0]); // File
                    Assert.AreSame(mdnode, mdnode.Operands[0].OwningNode);
                    Assert.IsNull(mdnode.Operands[0].Metadata);

                    Assert.IsNotNull(mdnode.Operands[1]); // Scope
                    Assert.AreSame(mdnode, mdnode.Operands[1].OwningNode);
                    Assert.IsNull(mdnode.Operands[1].Metadata);

                    Assert.IsNotNull(mdnode.Operands[2]); // Name
                    Assert.AreSame(mdnode, mdnode.Operands[2].OwningNode);
                    Assert.IsNull(mdnode.Operands[2].Metadata);

                    Assert.IsNotNull(mdnode.Operands[3]); // BaseType
                    Assert.AreSame(mdnode, mdnode.Operands[3].OwningNode);
                    Assert.IsNotNull(mdnode.Operands[3].Metadata);

                    Assert.IsNotNull(mdnode.Operands[4]); // Elements
                    Assert.AreSame(mdnode, mdnode.Operands[4].OwningNode);
                    Assert.IsNotNull(mdnode.Operands[4].Metadata);

                    Assert.IsNotNull(mdnode.Operands[5]); // VTableHolder
                    Assert.AreSame(mdnode, mdnode.Operands[5].OwningNode);
                    Assert.IsNull(mdnode.Operands[5].Metadata);

                    Assert.IsNotNull(mdnode.Operands[6]); // TemplateParams
                    Assert.AreSame(mdnode, mdnode.Operands[6].OwningNode);
                    Assert.IsNull(mdnode.Operands[6].Metadata);

                    Assert.IsNotNull(mdnode.Operands[7]); // Identifier
                    Assert.AreSame(mdnode, mdnode.Operands[7].OwningNode);
                    Assert.IsNull(mdnode.Operands[7].Metadata);

                    Assert.AreSame(intType.DIType, mdnode.BaseType);
                    Assert.AreEqual(1, mdnode.Elements.Count);
                    var subRange = mdnode.Elements[0] as DISubRange;
                    Assert.IsNotNull(subRange);
                }
        }
Exemple #25
0
        public void VerifyValidModuleTest( )
        {
            using (var module = new NativeModule(TestModuleName))
            {
                Function testFunc = CreateSimpleVoidNopTestFunction(module, "foo");

                // verify basics
                Assert.IsNotNull(testFunc);
                bool isValid = module.Verify(out string msg);
                Assert.IsTrue(isValid);
                Assert.AreEqual(string.Empty, msg);
            }
        }
Exemple #26
0
        private static Function CreateSimpleVoidNopTestFunction(NativeModule module, string name)
        {
            var ctx = module.Context;

            Assert.IsNotNull(ctx);
            var testFunc = module.AddFunction(name, ctx.GetFunctionType(ctx.VoidType));

            testFunc.AppendBasicBlock("entry");
            var irBuilder = new InstructionBuilder(testFunc.EntryBlock);

            irBuilder.Return( );
            return(testFunc);
        }
Exemple #27
0
        protected override void OnStop()
        {
            if (_hook != null)
            {
                _hook.Dispose();
                _hook = null;
            }

            if (_module != null)
            {
                _module.Dispose();
                _module = null;
            }
        }
Exemple #28
0
 public void GetTypeByNameTest( )
 {
     using (var module = new NativeModule(TestModuleName))
     {
         // while GetTypeByName is exposed on the module it isn't really specific to the module
         // That is, the type belongs to the context and GetTypeByName() is just a convenience
         // wrapper to access types for a module.
         var type = module.GetTypeByName(StructTestName);
         Assert.IsNull(type);
         var expectedType = module.Context.CreateStructType(StructTestName);
         var actualType   = module.GetTypeByName(StructTestName);
         Assert.AreSame(expectedType, actualType);
     }
 }
 public FunctionsForm(NativeModule module)
 {
     InitializeComponent();
     _module = module;
     Text    = $"{_resources.GetString("StrExportFunctions")} {_module.Name}(0x{_module.Handle.ToString(Cache.Is64BitProcess ? "X16" : "X8")})";
     typeof(ListView).InvokeMember("DoubleBuffered", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, lvwFunctions, new object[] { true });
     lvwFunctions.ListViewItemSorter = new ListViewItemSorter(lvwFunctions, new Dictionary <int, TypeCode> {
         { 0, TypeCode.String }, { 1, Cache.Is64BitProcess ? TypeCode.UInt64 : TypeCode.UInt32 }, { 2, TypeCode.Int16 }
     })
     {
         AllowHexLeading = true
     };
     RefreshFunctionList();
 }
        public void SetBody(bool packed
                            , NativeModule module
                            , DIScope scope
                            , DIFile diFile
                            , uint line
                            , DebugInfoFlags debugFlags
                            , IEnumerable <DebugMemberInfo> debugElements
                            )
        {
            var debugMembersArray = debugElements as IList <DebugMemberInfo> ?? debugElements.ToList();
            var nativeElements    = debugMembersArray.Select(e => e.DebugType.NativeType);

            SetBody(packed, module, scope, diFile, line, debugFlags, nativeElements, debugMembersArray);
        }