private void AssertModuleDoesntContainDomains(ClrModule module, params ClrAppDomain[] domainList)
        {
            IList<ClrAppDomain> moduleDomains = module.AppDomains;

            foreach (ClrAppDomain domain in domainList)
                Assert.IsFalse(moduleDomains.Contains(domain));
        }
        private void AssertModuleContainsDomains(ClrModule module, params ClrAppDomain[] domainList)
        {
            IList<ClrAppDomain> moduleDomains = module.AppDomains;
            
            foreach (ClrAppDomain domain in domainList)
                Assert.IsTrue(moduleDomains.Contains(domain));

            Assert.AreEqual(domainList.Length, moduleDomains.Count);
        }
Esempio n. 3
0
        internal static ISet <Namespace> GetReturnTypes(BuiltinFunction func, ProjectState projectState)
        {
            var result = new HashSet <Namespace>();
            var found  = new HashSet <Type>();

            foreach (var target in func.Overloads.Targets)
            {
                var targetInfo = (target as System.Reflection.MethodInfo);
                if (targetInfo != null && !found.Contains(targetInfo.ReturnType))
                {
                    var pyType = ClrModule.GetPythonType(targetInfo.ReturnType);
                    result.Add(((BuiltinClassInfo)projectState.GetNamespaceFromObjects(pyType)).Instance);
                    found.Add(targetInfo.ReturnType);
                }
            }
            return(result);
        }
Esempio n. 4
0
        public static int Main(string[] args)
        {
            var files  = new List <string>();
            var config = new Config();

            config.ParseArgs(args);
            if (!config.Validate())
            {
                ConsoleOps.Usage(true);
            }

            // we don't use the engine, but we create it so we can have a default context.
            ScriptEngine engine = Python.CreateEngine(config.PythonOptions);

            ConsoleOps.Info($"IronPython Compiler for {engine.Setup.DisplayName} ({engine.LanguageVersion})");
            ConsoleOps.Info($"{config}");
            ConsoleOps.Info("compiling...");

            var compileOptions = new Dictionary <string, object>()
            {
                { "mainModule", config.MainName },
                { "assemblyFileVersion", config.FileVersion },
                { "copyright", config.Copyright },
                { "productName", config.ProductName },
                { "productVersion", config.ProductVersion },
            };

            try {
                ClrModule.CompileModules(DefaultContext.DefaultCLS,
                                         Path.Combine(config.OutputPath, Path.ChangeExtension(config.Output, ".dll")),
                                         compileOptions,
                                         config.Files.ToArray());

                var outputfilename = Path.Combine(config.OutputPath, Path.ChangeExtension(config.Output, ".dll"));
                if (config.Target != PEFileKinds.Dll)
                {
                    outputfilename = Path.Combine(config.OutputPath, Path.ChangeExtension(config.Output, ".exe"));
                    GenerateExe(config);
                }
                ConsoleOps.Info($"Saved to {outputfilename}");
            } catch (Exception e) {
                Console.WriteLine();
                ConsoleOps.Error(true, e.Message);
            }
            return(0);
        }
Esempio n. 5
0
        private void InitILInfo()
        {
            ClrModule module   = Type?.Module;
            object    mdImport = module?.MetadataImport;
            uint      rva      = 0;

            if (mdImport is IMetadataImport metadataImport)
            {
                if (metadataImport.GetRVA(_token, out rva, out uint flags) != 0)
                {
                    // GetRVA fail
                    return;
                }
            }
            else if (mdImport is MetaDataImport dacMetaDataImport)
            {
                rva = dacMetaDataImport.GetRva((int)_token);
            }
            ulong il = _runtime.GetILForModule(module, rva);

            if (il != 0)
            {
                _il = new ILInfo();

                if (_runtime.ReadByte(il, out byte b))
                {
                    bool isTinyHeader = (b & (IMAGE_COR_ILMETHOD.FormatMask >> 1)) == IMAGE_COR_ILMETHOD.TinyFormat;
                    if (isTinyHeader)
                    {
                        _il.Address = il + 1;
                        _il.Length  = b >> (int)(IMAGE_COR_ILMETHOD.FormatShift - 1);
                        _il.LocalVarSignatureToken = IMAGE_COR_ILMETHOD.mdSignatureNil;
                    }
                    else if (_runtime.ReadDword(il, out uint tmp))
                    {
                        _il.Flags = tmp;
                        _runtime.ReadDword(il + 4, out tmp);
                        _il.Length = (int)tmp;
                        _runtime.ReadDword(il + 8, out tmp);
                        _il.LocalVarSignatureToken = tmp;
                        _il.Address = il + 12;
                    }
                }
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Loads any extension DLLs present in sys.prefix\DLLs directory and adds references to them.
        ///
        /// This provides an easy drop-in location for .NET assemblies which should be automatically referenced
        /// (exposed via import), COM libraries, and pre-compiled Python code.
        /// </summary>
        private void InitializeExtensionDLLs()
        {
            string dir = Path.Combine(PythonContext.InitialPrefix, "DLLs");

            if (Directory.Exists(dir))
            {
                foreach (string file in Directory.EnumerateFiles(dir, "*.dll"))
                {
                    if (file.ToLower().EndsWith(".dll"))
                    {
                        try {
                            ClrModule.AddReference(PythonContext.SharedContext, new FileInfo(file).Name);
                        } catch {
                        }
                    }
                }
            }
        }
Esempio n. 7
0
        public void ArrayLengthTest()
        {
            using (DataTarget dt = TestTargets.Types.LoadFullDump())
            {
                ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();
                ClrHeap    heap    = runtime.Heap;

                ClrAppDomain domain = runtime.AppDomains.Single();

                ClrModule typesModule = runtime.GetModule("types.exe");
                ClrType   type        = heap.GetTypeByName("Types");

                ulong   s_array   = (ulong)type.GetStaticFieldByName("s_array").GetValue(domain);
                ClrType arrayType = heap.GetObjectType(s_array);

                Assert.Equal(3, arrayType.GetArrayLength(s_array));
            }
        }
Esempio n. 8
0
        public IPYConsole(CommandLine commandLine)
        {
            waitHandles = new WaitHandle[] { lineReceivedEvent, disposedEvent };

            this.commandLine = commandLine;
            dispatcherThread = new Thread(new ThreadStart(DispatcherThreadStartingPoint));
            dispatcherThread.SetApartmentState(ApartmentState.STA);
            dispatcherThread.IsBackground = true;
            dispatcherThread.Start();

            // Only required when running outside REP loop.
            prompt = ">>> ";

            CodeContext codeContext = DefaultContext.Default;

            // Set dispatcher to run on a UI thread independent of both the Control UI thread and thread running the REPL.
            ClrModule.SetCommandDispatcher(codeContext, DispatchCommand);
        }
Esempio n. 9
0
        public static SDClrModule ToSDModel(this ClrModule module)
        {
            var model = new SDClrModule();

            model.AssemblyId   = module.AssemblyId;
            model.AssemblyName = module.AssemblyName;
            model.IsDynamic    = module.IsDynamic;
            model.IsFile       = module.IsFile;
            model.Name         = module.Name;
            model.Pdb          = new SDPdbInfo();
            if (module.Pdb != null)
            {
                model.Pdb.FileName = module.Pdb.FileName;
                model.Pdb.Guid     = module.Pdb.Guid.ToString();
                model.Pdb.Revision = module.Pdb.Revision;
            }
            return(model);
        }
Esempio n. 10
0
        /// <summary>
        /// Implements __reduce_ex__ for .NET types which are serializable.  This uses the .NET
        /// serializer to get a string of raw data which can be serialized.
        /// </summary>
        public static PythonTuple SerializeReduce(CodeContext /*!*/ context, object /*!*/ self, int protocol)
        {
            PythonTuple data = ClrModule.Serialize(self);

            object deserializeNew;
            bool   res = context.LanguageContext.ClrModule.__dict__.TryGetValue(
                "Deserialize",
                out deserializeNew
                );

            Debug.Assert(res);

            return(PythonTuple.MakeTuple(
                       deserializeNew,          // function to call, clr.DeserializeNew
                       data,                    // data to pass to it - our type & the raw data from the .NET serializer
                       null                     // state, unused
                       ));
        }
Esempio n. 11
0
        /// <summary>
        /// Gets the type with the specified name.
        /// </summary>
        /// <param name="name">The CLR type name.</param>
        private CodeType GetClrTypeByName(string name)
        {
            try
            {
                // Try to find code type inside CLR module
                var clrType = ClrModule.GetTypeByName(name);

                if (clrType != null)
                {
                    // Create a code type
                    return(ClrTypes[clrType]);
                }
            }
            catch (Exception)
            {
            }

            return(null);
        }
Esempio n. 12
0
        public void GetDelegateTest()
        {
            using DataTarget dt      = TestTargets.Types.LoadFullDump();
            using ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();
            ClrModule typesModule = runtime.GetModule(TypeTests.ModuleName);
            ClrType   Types       = typesModule.GetTypeByName("Types");

            ClrDelegate TestDelegate = Types.GetStaticFieldByName("TestDelegate").ReadObject(runtime.AppDomains.Single()).AsDelegate();

            ClrDelegateTarget delegateTarget = TestDelegate.GetDelegateTarget();

            Assert.NotNull(delegateTarget);
            CompareToInner(Types, TestDelegate, delegateTarget);

            ClrDelegate       TestEvent   = Types.GetStaticFieldByName("TestEvent").ReadObject(runtime.AppDomains.Single()).AsDelegate();
            ClrDelegateTarget eventTarget = TestEvent.GetDelegateTarget();

            Assert.Null(eventTarget);
        }
Esempio n. 13
0
        public void IsDelegateTest()
        {
            using DataTarget dt      = TestTargets.Types.LoadFullDump();
            using ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();
            ClrModule typesModule = runtime.GetModule(TypeTests.ModuleName);
            ClrType   type        = typesModule.GetTypeByName("Types");

            ClrObject TestDelegate = type.GetStaticFieldByName("TestDelegate").ReadObject(runtime.AppDomains.Single());

            Assert.True(TestDelegate.IsValid);
            Assert.True(TestDelegate.IsDelegate);
            Assert.False(TestDelegate.AsDelegate().HasMultipleTargets);

            ClrObject TestEvent = type.GetStaticFieldByName("TestEvent").ReadObject(runtime.AppDomains.Single());

            Assert.True(TestEvent.IsValid);
            Assert.True(TestEvent.IsDelegate);
            Assert.True(TestEvent.AsDelegate().HasMultipleTargets);
        }
Esempio n. 14
0
        public void TestTypeModifiers()
        {
            using DataTarget dt      = TestTargets.NestedTypes.LoadFullDump();
            using ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();

            ClrModule module  = runtime.GetModule(NestedTypesModuleName);
            ClrType   program = module.GetTypeByName("Program");

            Assert.True(program.IsPublic);
            Assert.False(program.IsAbstract);
            Assert.False(program.IsSealed);

            ClrType publicClass = module.GetTypeByName("Program+PublicClass");

            Assert.True(publicClass.IsPublic);

            ClrType privateClass = module.GetTypeByName("Program+PrivateClass");

            Assert.True(privateClass.IsPrivate);

            ClrType internalClass = module.GetTypeByName("Program+InternalClass");

            Assert.True(internalClass.IsInternal);

            ClrType protectedClass = module.GetTypeByName("Program+ProtectedClass");

            Assert.True(protectedClass.IsProtected);

            ClrType abstractClass = module.GetTypeByName("Program+AbstractClass");

            Assert.True(abstractClass.IsAbstract);
            Assert.False(abstractClass.IsSealed);

            ClrType sealedClass = module.GetTypeByName("Program+SealedClass");

            Assert.True(sealedClass.IsSealed);
            Assert.False(sealedClass.IsAbstract);

            ClrType staticClass = module.GetTypeByName("Program+StaticClass");

            Assert.True(staticClass.IsAbstract);
            Assert.True(staticClass.IsSealed);
        }
Esempio n. 15
0
        public void EnumerateGCRefsArray()
        {
            using DataTarget dataTarget = TestTargets.GCRoot.LoadFullDump();
            using ClrRuntime runtime    = dataTarget.ClrVersions.Single().CreateRuntime();
            ClrHeap heap = runtime.Heap;

            ClrModule module   = heap.Runtime.GetMainModule();
            ClrType   mainType = module.GetTypeByName("GCRootTarget");

            ClrObject obj = mainType.GetStaticObjectValue("TheRoot");

            obj = obj.GetObjectField("Item1");

            Assert.Equal("System.Object[]", obj.Type.Name);

            ClrObject[] refs = obj.EnumerateReferences(false).ToArray();
            Assert.Single(refs);
            Assert.Equal("DoubleRef", refs[0].Type.Name);
        }
Esempio n. 16
0
        private unsafe void InitILInfo()
        {
            ClrModule module = Type?.Module;

            ICorDebug.IMetadataImport metadataImport = module?.MetadataImport as ICorDebug.IMetadataImport;

            if (metadataImport != null)
            {
                uint rva;
                uint flags;
                if (metadataImport.GetRVA(_token, out rva, out flags) == 0)
                {
                    ulong il = _runtime.GetILForModule(module, rva);
                    if (il != 0)
                    {
                        _il = new ILInfo();

                        uint tmp;
                        byte b;
                        if (_runtime.ReadByte(il, out b))
                        {
                            bool isTinyHeader = ((b & (IMAGE_COR_ILMETHOD.FormatMask >> 1)) == IMAGE_COR_ILMETHOD.TinyFormat);
                            if (isTinyHeader)
                            {
                                _il.Address = il + 1;
                                _il.Length  = b >> (int)(IMAGE_COR_ILMETHOD.FormatShift - 1);
                                _il.LocalVarSignatureToken = IMAGE_COR_ILMETHOD.mdSignatureNil;
                            }
                            else if (_runtime.ReadDword(il, out tmp))
                            {
                                _il.Flags = tmp;
                                _runtime.ReadDword(il + 4, out tmp);
                                _il.Length = (int)tmp;
                                _runtime.ReadDword(il + 8, out tmp);
                                _il.LocalVarSignatureToken = tmp;
                                _il.Address = il + 12;
                            }
                        }
                    }
                }
            }
        }
Esempio n. 17
0
        internal static IList <string> DirHelper(object obj, bool showClr)
        {
            NamespaceTracker nt = obj as NamespaceTracker;

            if (nt != null)
            {
                return(nt.GetMemberNames());
            }

            var dir = showClr ? ClrModule.DirClr(obj) : ClrModule.Dir(obj);
            int len = dir.__len__();

            string[] result = new string[len];
            for (int i = 0; i < len; i++)
            {
                // TODO: validate
                result[i] = dir[i] as string;
            }
            return(result);
        }
Esempio n. 18
0
        private ISet <Namespace> AddReference(CallExpression node, Func <string, Assembly> partialLoader)
        {
            // processes a call to clr.AddReference updating project state
            // so that it contains the newly loaded assembly.
            foreach (var arg in node.Args)
            {
                var cexpr = arg.Expression as ConstantExpression;
                if (cexpr == null || !(cexpr.Value is string))
                {
                    // can't process this add reference
                    continue;
                }

                // TODO: Should we do a .NET reflection only load rather than
                // relying on the CLR module here?  That would prevent any code from
                // running although at least we don't taint our own modules which
                // are loaded with this current code.
                var asmName = cexpr.Value as string;
                if (asmName != null && _assemblyLoadList.Add(asmName))
                {
                    Assembly asm = null;
                    try {
                        if (partialLoader != null)
                        {
                            asm = partialLoader(asmName);
                        }
                        else
                        {
                            try {
                                asm = ClrModule.LoadAssemblyByName(_codeContext, asmName);
                            } catch {
                                asm = ClrModule.LoadAssemblyByPartialName(asmName);
                            }
                        }
                    } catch {
                    }
                    AddAssembly(asm);
                }
            }
            return(null);
        }
Esempio n. 19
0
        /// <summary>
        /// Creates a new PythonInterpreter
        /// </summary>
        public PythonInterpreter()
        {
#if !XBOX
            this.PythonEngine = new PythonEngine();
            this.PythonOutput = new MemoryStream();
            this.PythonEngine.SetStandardOutput(PythonOutput);
            this.ASCIIEncoder = new ASCIIEncoding();


            clr = this.PythonEngine.Import("clr") as ClrModule;
            clr.AddReference("Microsoft.Xna.Framework");
            clr.AddReference("Microsoft.Xna.Framework.Game");

            this.PythonEngine.Execute("from Microsoft.Xna.Framework import *");
            this.PythonEngine.Execute("from Microsoft.Xna.Framework.Graphics import *");
            this.PythonEngine.Execute("from Microsoft.Xna.Framework.Content import *");
            //this.PythonEngine.Execute("from System import *");

            multi = "";

            Console = new XnaConsoleComponent();
            XdtkResources.Console.Components.Add(Console);
            Console.Prompt(Prompt, Execute);
            AddGlobal("Console", Console);
            AddGlobal("dc", XdtkResources.Console);
            AddGlobal("game", XdtkResources.Game);

            Execute(
                @"class Tracer(GameComponent):
    def Update(self, gameTime):
        dc.Show(self.k, eval(self.v))
");
            Execute(
                @"def trace(key, value):
    a = Tracer(game)
    a.k = key
    a.v = value
    game.Components.Add(a)
");
#endif
        }
Esempio n. 20
0
        private IEnumerable <ThreadPoolItem> EnumerateLocalThreadPoolItemsInNetCore(ClrModule corelib)
        {
            // in .NET Core, each thread has a dedicated WorkStealingQueue stored in WorkStealingQueueList._queues (a WorkStealingQueue[])
            //
            // until we can access static fields values in .NET Core with ClrMD, we need to browse the whole heap...
            var heap = _clr.Heap;

            if (!heap.CanWalkHeap)
            {
                yield break;
            }

            foreach (var obj in heap.EnumerateObjects())
            {
                if (!obj.IsValid)
                {
                    continue;
                }
                var type = obj.Type;
                if (type == null)
                {
                    continue;
                }

                if (string.CompareOrdinal(type.Name, "System.Threading.ThreadPoolWorkQueue+WorkStealingQueue") == 0)
                {
                    var stealingQueue = obj;
                    var workItems     = stealingQueue.ReadObjectField("m_array").AsArray();
                    for (int current = 0; current < workItems.Length; current++)
                    {
                        var workItem = workItems.GetObjectValue(current);
                        if (!workItem.IsValid)
                        {
                            continue;
                        }

                        yield return(GetThreadPoolItem(workItem));
                    }
                }
            }
        }
Esempio n. 21
0
        public void FieldCachingTest()
        {
            using DataTarget dt             = TestTargets.Types.LoadFullDump();
            dt.CacheOptions.CacheFields     = true;
            dt.CacheOptions.CacheFieldNames = StringCaching.Cache;

            using ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();
            ClrModule module = runtime.GetModule("sharedlibrary.dll");
            ClrType   type   = module.GetTypeByName("Foo");

            Assert.NotEqual(0ul, type.MethodTable);  // Sanity test

            Assert.Equal(type.Fields, type.Fields);
            Assert.Equal(type.StaticFields, type.StaticFields);

            ClrField field  = type.GetFieldByName("o");
            ClrField field2 = type.Fields.Single(f => f.Name == "o");

            Assert.Same(field, field2);
            Assert.Same(field.Name, field.Name);
        }
Esempio n. 22
0
 static void GetModuleFileInfo(ClrModule module, out string name, out string path)
 {
     if (string.IsNullOrEmpty(module.Name))
     {
         // In memory and obfuscated
         name = string.Empty;
         path = string.Empty;
     }
     else if (module.Name.Contains(","))
     {
         // In memory, module.Name is reflection assembly name.
         name = module.Name.Split(',')[0];
         path = string.Empty;
     }
     else
     {
         // In disk
         name = Path.GetFileName(module.Name);
         path = module.Name;
     }
 }
Esempio n. 23
0
        private void InitializeHome()
        {
            //string dir = Path.Combine(PythonContext_InitialPrefix, "DLLs");
            string dir = Home_Path;

            if (Directory.Exists(dir))
            {
                foreach (string file in Directory.GetFiles(dir))
                {
                    if (file.ToLower().EndsWith(".dll"))
                    {
                        try
                        {
                            ClrModule.AddReference(PythonContext_SharedContext, new FileInfo(file).Name);
                        }
                        catch
                        {
                        }
                    }
                }
            }
        }
Esempio n. 24
0
        /// <summary>
        /// Creates a new PythonInterpreter
        /// </summary>
        public PythonInterpreter(Game1 game, SpriteFont font) : base((Game)game)
        {
            this.PythonEngine = new PythonEngine();
            this.PythonOutput = new MemoryStream();
            this.PythonEngine.SetStandardOutput(PythonOutput);
            this.ASCIIEncoder = new ASCIIEncoding();

            ClrModule clr = this.PythonEngine.Import("clr") as ClrModule;

            clr.AddReference("Microsoft.Xna.Framework");
            clr.AddReference("Microsoft.Xna.Framework.Game");

            this.PythonEngine.Execute("from Microsoft.Xna.Framework import *");
            this.PythonEngine.Execute("from Microsoft.Xna.Framework.Graphics import *");
            this.PythonEngine.Execute("from Microsoft.Xna.Framework.Content import *");
            multi = "";

            Console = new XnaConsoleComponent(game, font);
            game.Components.Add(Console);
            Console.Prompt(Prompt, Execute);
            AddGlobal("Console", Console);
        }
Esempio n. 25
0
 static void WriteTypes(ClrModule module)
 {
     foreach (var type in module.DefinedTypes)
     {
         string[] path = type.Name.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
         string   cur  = "./Types";
         bool     flag = false;
         for (int i = 0; i < path.Length; i++)
         {
             string sec = path[i];
             if (!Directory.Exists(cur))
             {
                 Directory.CreateDirectory(cur);
             }
             try
             {
                 cur = Path.Combine(cur, sec);
             }
             catch
             {
                 Console.WriteLine($"Skipped: {type.Name}");
                 flag = true;
                 break;
             }
         }
         if (!flag)
         {
             try
             {
                 WriteType(cur, type);
             }
             catch
             {
                 Console.WriteLine($"Skipped: {type.Name}");
             }
         }
     }
 }
Esempio n. 26
0
        public void NoMethodCachingTest()
        {
            using DataTarget dt              = TestTargets.Types.LoadFullDump();
            dt.CacheOptions.CacheMethods     = false;
            dt.CacheOptions.CacheMethodNames = StringCaching.None;

            using ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();


            ClrModule module = runtime.GetModule("sharedlibrary.dll");
            ClrType   type   = module.GetTypeByName("Foo");
            ClrMethod method = type.GetMethod("Bar");

            Assert.NotEqual(0ul, method.MethodDesc);  // Sanity test

            ClrMethod method2 = type.GetMethod("Bar");

            Assert.Equal(method, method2);
            Assert.NotSame(method, method2);


            string signature1 = method.Signature;
            string signature2 = method2.Signature;

            Assert.NotNull(signature1);
            Assert.Equal(signature1, signature2);

            Assert.Equal(signature1, method.Signature);
            Assert.NotSame(signature1, method.Signature);
            Assert.NotSame(method2.Signature, method.Signature);

            // Ensure that we can swap this at runtime and that we get interned strings
            dt.CacheOptions.CacheMethodNames = StringCaching.Intern;

            Assert.NotNull(method.Signature);
            Assert.Same(method2.Signature, method.Signature);
            Assert.Same(method.Signature, string.Intern(method.Signature));
        }
Esempio n. 27
0
        public ClrModule GetMscorlib()
        {
#if ClrMD2
            var bclModule = _clr.BaseClassLibrary;
            return(bclModule);
#else
            if (CoreLibModule != null)
            {
                return(CoreLibModule);
            }

            foreach (var module in _clr.Modules)
            {
                if (string.IsNullOrEmpty(module.AssemblyName))
                {
                    continue;
                }

                var name = module.AssemblyName.ToLower();

                // in .NET Framework
                if (name.Contains("mscorlib", StringComparison.Ordinal))
                {
                    CoreLibModule = module;
                    break;
                }

                // in .NET Core
                if (name.Contains("corelib", StringComparison.Ordinal))
                {
                    CoreLibModule = module;
                    break;
                }
            }

            return(CoreLibModule);
#endif
        }
Esempio n. 28
0
        /// <summary>
        /// Gets the CLR static variable.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="appDomain">The application domain.</param>
        /// <returns>Static variable if found</returns>
        public Variable GetClrVariable(string name, CsDebugScript.CLR.AppDomain appDomain)
        {
            int    variableNameIndex = name.LastIndexOf('.');
            string typeName          = name.Substring(0, variableNameIndex);
            var    clrType           = ClrModule.GetTypeByName(typeName);

            if (clrType == null)
            {
                throw new Exception("CLR type not found " + typeName);
            }

            string variableName = name.Substring(variableNameIndex + 1);
            var    staticField  = clrType.GetStaticFieldByName(variableName);

            if (staticField == null)
            {
                throw new Exception("Field " + staticField + " wasn't found in CLR type " + typeName);
            }

            var address = staticField.GetAddress(appDomain.ClrAppDomain);

            return(Variable.CreateNoCast(FromClrType(clrType), address, variableName));
        }
Esempio n. 29
0
        public void EnumerateDelegateTest()
        {
            using DataTarget dt      = TestTargets.Types.LoadFullDump();
            using ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();
            ClrModule typesModule = runtime.GetModule(TypeTests.ModuleName);
            ClrType   Types       = typesModule.GetTypeByName("Types");

            ClrDelegate TestDelegate = Types.GetStaticFieldByName("TestDelegate").ReadObject(runtime.AppDomains.Single()).AsDelegate();

            ClrDelegateTarget[] methods = TestDelegate.EnumerateDelegateTargets().ToArray();

            Assert.Single(methods);
            CompareToInner(Types, TestDelegate, methods[0]);


            ClrDelegate TestEvent = Types.GetStaticFieldByName("TestEvent").ReadObject(runtime.AppDomains.Single()).AsDelegate();

            methods = TestEvent.EnumerateDelegateTargets().ToArray();

            Assert.Equal(2, methods.Length);
            CompareToInner(Types, TestEvent, methods[0]);
            CompareToInstanceMethod(Types, TestEvent, methods[1]);
        }
Esempio n. 30
0
        public void MethodHandleSingleDomainTests()
        {
            ulong methodDesc;

            using (DataTarget dt = TestTargets.Types.LoadFullDump())
            {
                using ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();

                ClrModule module = runtime.GetModule("sharedlibrary.dll");
                ClrType   type   = module.GetTypeByName("Foo");
                ClrMethod method = type.GetMethod("Bar");
                methodDesc = method.MethodDesc;

                Assert.NotEqual(0ul, methodDesc);
            }

            using (DataTarget dt = TestTargets.Types.LoadFullDump())
            {
                using ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();
                ClrMethod method = runtime.GetMethodByHandle(methodDesc);

                Assert.NotNull(method);
                Assert.Equal("Bar", method.Name);
                Assert.Equal("Foo", method.Type.Name);
            }

            using (DataTarget dt = TestTargets.Types.LoadFullDump())
            {
                using ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();

                ClrModule module = runtime.GetModule("sharedlibrary.dll");
                ClrType   type   = module.GetTypeByName("Foo");
                ClrMethod method = type.GetMethod("Bar");
                Assert.Equal(methodDesc, method.MethodDesc);
                Assert.Equal(method, runtime.GetMethodByHandle(methodDesc));
            }
        }
Esempio n. 31
0
        private static PdbReader GetReaderForMethod(ClrMethod method)
        {
            ClrModule module = method?.Type?.Module;
            PdbInfo   info   = module?.Pdb;

            PdbReader reader = null;

            if (info != null)
            {
                if (!s_pdbReaders.TryGetValue(info, out reader))
                {
                    SymbolLocator locator = GetSymbolLocator(module);
                    string        pdbPath = locator.FindPdb(info);
                    if (pdbPath != null)
                    {
                        try
                        {
                            reader = new PdbReader(pdbPath);
                        }
                        catch (IOException)
                        {
                            // This will typically happen when trying to load information
                            // from public symbols, or symbol files generated by some weird
                            // compiler. We can ignore this, but there's no need to load
                            // this PDB anymore, so we will put null in the dictionary and
                            // be done with it.
                            reader = null;
                        }
                    }

                    s_pdbReaders[info] = reader;
                }
            }

            return(reader);
        }
Esempio n. 32
0
        public void SystemAndSharedLibraryModulesTest()
        {
            using DataTarget dt = TestTargets.AppDomains.LoadFullDump();
            ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();

            ClrAppDomain systemDomain = runtime.SystemDomain;

            Assert.Equal(0, systemDomain.Modules.Count);

            ClrAppDomain sharedDomain = runtime.SharedDomain;

            if (runtime.ClrInfo.Version.Major == 2)
            {
                Assert.Equal(3, sharedDomain.Modules.Count);
                Assert.Contains("mscorlib.dll", sharedDomain.Modules.Select(m => Path.GetFileName("mscorlib.dll")));
            }
            else
            {
                Assert.Equal(1, sharedDomain.Modules.Count);

                ClrModule mscorlib = sharedDomain.Modules.Single();
                Assert.Equal("mscorlib.dll", Path.GetFileName(mscorlib.FileName), true);
            }
        }
Esempio n. 33
0
 public NativeStackFrame(Address ip, string symbolName, ClrModule module)
 {
     _ip = ip;
     _symbolName = symbolName;
     _module = module;
 }
Esempio n. 34
0
 internal abstract void SetModule(ClrModule module);
Esempio n. 35
0
 internal void AddModule(ClrModule module)
 {
     _modules.Add(module);
 }
Esempio n. 36
0
 internal override void SetModule(ClrModule module)
 {
 }
Esempio n. 37
0
 internal override void SetModule(ClrModule module)
 {
     m_module = (DesktopBaseModule)module;
 }