Esempio n. 1
0
 public LlePspCpu(string Name, InjectContext InjectContext, CpuProcessor CpuProcessor, uint EntryPoint = 0x1fc00000)
 {
     this.Name = Name;
     //this.CachedGetMethodCache = PspEmulatorContext.GetInstance<CachedGetMethodCache>();
     this.CpuThreadState = new CpuThreadState(CpuProcessor);
     this.EntryPoint = EntryPoint;
 }
Esempio n. 2
0
 public void TestInjectionExtended()
 {
     var Context = new InjectContext();
     var Test = Context.GetInstance<Test3>();
     Assert.AreEqual(Context, Test.InjectContext1);
     Assert.AreEqual(Context, Test.InjectContext2);
 }
Esempio n. 3
0
        public void ElfLoaderConstructorTest()
        {
            var InjectContext = new InjectContext();
            InjectContext.SetInstanceType<PspMemory, LazyPspMemory>();
            var Memory = InjectContext.GetInstance<PspMemory>();
            var MemoryStream = new PspMemoryStream(Memory);
            var MemoryPartition = new MemoryPartition(InjectContext, PspMemory.MainOffset, PspMemory.MainOffset + PspMemory.MainSize);

            var ElfLoader = new ElfLoader();

            ElfLoader.Load(File.OpenRead("../../../TestInput/minifire.elf"), "minifire.elf");
            ElfLoader.AllocateAndWrite(MemoryStream, MemoryPartition);
            Assert.AreEqual(1, ElfLoader.ProgramHeaders.Length);
            Assert.AreEqual(3, ElfLoader.SectionHeaders.Length);

            Assert.AreEqual(
                "['','.rodata.sceModuleInfo']".Replace('\'', '"'),
                ElfLoader.SectionHeadersByName.Keys.ToJson()
            );

            //ElfLoader.LoadAllocateMemory(MemoryPartition);
            //ElfLoader.LoadWriteToMemory(MemoryStream);

            //var ModuleInfo = ElfLoader.ModuleInfo;

            var PC = ElfLoader.Header.EntryPoint;
            //var GP = ModuleInfo.GP;

            Assert.AreEqual(0x08900008, (int)PC);
            //Assert.AreEqual(0x00004821, (int)GP);
        }
Esempio n. 4
0
 /// <summary>
 ///     Injects the specified TypeDef to another module.
 /// </summary>
 /// <param name="typeDef">The source TypeDef.</param>
 /// <param name="target">The target module.</param>
 /// <returns>The injected TypeDef.</returns>
 public static TypeDef Inject(TypeDef typeDef, ModuleDef target)
 {
     var ctx = new InjectContext(typeDef.Module, target);
     PopulateContext(typeDef, ctx);
     Copy(typeDef, ctx, true);
     return (TypeDef)ctx.Map[typeDef];
 }
Esempio n. 5
0
 /// <summary>
 ///     Injects the specified MethodDef to another module.
 /// </summary>
 /// <param name="methodDef">The source MethodDef.</param>
 /// <param name="target">The target module.</param>
 /// <returns>The injected MethodDef.</returns>
 public static MethodDef Inject(MethodDef methodDef, ModuleDef target)
 {
     var ctx = new InjectContext(methodDef.Module, target);
     ctx.Map[methodDef] = Clone(methodDef);
     CopyMethodDef(methodDef, ctx);
     return (MethodDef)ctx.Map[methodDef];
 }
Esempio n. 6
0
 public void TestInjection()
 {
     var Context = new InjectContext();
     var Test = Context.GetInstance<Test>();
     Assert.AreEqual(Context, Test.InjectContext1);
     Assert.AreEqual(Context, Test.InjectContext2);
     Assert.AreEqual(null, Test.InjectContext3);
 }
Esempio n. 7
0
 /// <summary>
 ///     Injects the members of specified TypeDef to another module.
 /// </summary>
 /// <param name="typeDef">The source TypeDef.</param>
 /// <param name="newType">The new type.</param>
 /// <param name="target">The target module.</param>
 /// <returns>Injected members.</returns>
 public static IEnumerable<IDnlibDef> Inject(TypeDef typeDef, TypeDef newType, ModuleDef target)
 {
     var ctx = new InjectContext(typeDef.Module, target);
     ctx.Map[typeDef] = newType;
     PopulateContext(typeDef, ctx);
     Copy(typeDef, ctx, false);
     return ctx.Map.Values.Except(new[] { newType });
 }
Esempio n. 8
0
 public static CpuProcessor CreateCpuProcessor(PspMemory Memory = null)
 {
     if (Memory == null) Memory = LazyPspMemory;
     var InjectContext = new InjectContext();
     InjectContext.SetInstance<PspMemory>(Memory);
     InjectContext.SetInstance<ICpuConnector>(new TestConnector());
     InjectContext.SetInstance<IInterruptManager>(new TestInterruptManager());
     return InjectContext.GetInstance<CpuProcessor>();
 }
Esempio n. 9
0
 public Program()
 {
     var InjectContext = new InjectContext();
     {
         InjectContext.SetInstanceType<PspMemory, DebugPspMemory>();
         InjectContext.SetInstanceType<DebugPspMemory, DebugPspMemory>();
     }
     InjectContext.InjectDependencesTo(this);
 }
Esempio n. 10
0
        public VirtualTimer(InjectContext InjectContext, string Name)
        {
            InjectContext.InjectDependencesTo(this);

            this.Timer = PspRtc.CreateVirtualTimer(Handler);
            this.Name = Name;
            this.Timer.Enabled = false;
            this.PspSharedInfoMemoryPartition = MemoryManager.GetPartition(MemoryPartitions.Kernel0).Allocate(
                sizeof(PspSharedInfoStruct),
                Name: "VTimer.PspSharedInfoStruct"
            );
            this.PspSharedInfo = (PspSharedInfoStruct*)CpuProcessor.Memory.PspAddressToPointerSafe(this.PspSharedInfoMemoryPartition.Low);
        }
Esempio n. 11
0
        public void ParsePathTest()
        {
            var InjectContext = new InjectContext();
            var HleIoManager = InjectContext.GetInstance<HleIoManager>();
            var DriverName = "ms:";
            var Driver = new HleIoDriverLocalFileSystem("C:/$INVALID$PATH$");
            HleIoManager.SetDriver(DriverName, Driver);

            var Parts = HleIoManager.ParsePath("ms3:/path/to/file.txt");

            Assert.AreEqual(Driver, Parts.HleIoDrvFileArg.HleIoDriver);
            Assert.AreEqual(3, Parts.HleIoDrvFileArg.FileSystemNumber);
            Assert.AreEqual("/path/to/file.txt", Parts.LocalPath);
        }
Esempio n. 12
0
		/// <summary>
		///     Populates the context mappings.
		/// </summary>
		/// <param name="typeDef">The origin TypeDef.</param>
		/// <param name="ctx">The injection context.</param>
		/// <returns>The new TypeDef.</returns>
		static TypeDef PopulateContext(TypeDef typeDef, InjectContext ctx) {
			TypeDef ret;
			IDnlibDef existing;
			if (!ctx.Map.TryGetValue(typeDef, out existing)) {
				ret = Clone(typeDef);
				ctx.Map[typeDef] = ret;
			}
			else
				ret = (TypeDef)existing;

			foreach (TypeDef nestedType in typeDef.NestedTypes)
				ret.NestedTypes.Add(PopulateContext(nestedType, ctx));

			foreach (MethodDef method in typeDef.Methods)
				ret.Methods.Add((MethodDef)(ctx.Map[method] = Clone(method)));

			foreach (FieldDef field in typeDef.Fields)
				ret.Fields.Add((FieldDef)(ctx.Map[field] = Clone(field)));

			return ret;
		}
            internal InternalFunctionCompiler(InjectContext InjectContext, MipsMethodEmitter MipsMethodEmitter, DynarecFunctionCompiler DynarecFunctionCompiler, IInstructionReader InstructionReader, Action<uint> _ExploreNewPcCallback, uint EntryPC, bool DoLog)
            {
                InjectContext.InjectDependencesTo(this);
                this._ExploreNewPcCallback = _ExploreNewPcCallback;
                this.MipsMethodEmitter = MipsMethodEmitter;
                this.CpuEmitter = new CpuEmitter(InjectContext, MipsMethodEmitter, InstructionReader);
                this.GlobalInstructionStats = CpuProcessor.GlobalInstructionStats;
                //this.InstructionStats = MipsMethodEmitter.InstructionStats;
                this.InstructionStats = new Dictionary<string, uint>();
                this.NewInstruction = new Dictionary<string, bool>();
                this.DoLog = DoLog;

                this.DynarecFunctionCompiler = DynarecFunctionCompiler;
                this.InstructionReader = InstructionReader;
                this.EntryPC = EntryPC;

                if (!PspMemory.IsAddressValid(EntryPC))
                {
                    throw (new InvalidOperationException(String.Format("Trying to get invalid function 0x{0:X8}", EntryPC)));
                }
            }
Esempio n. 14
0
 public object GetCpuProcessor()
 {
     return(InjectContext.GetInstance <CpuProcessor>());
 }
Esempio n. 15
0
 public Matching(InjectContext InjectContext)
 {
     InjectContext.InjectDependencesTo(this);
 }
Esempio n. 16
0
            public Atrac(InjectContext InjectContext, CodecType CodecType)
            {
                InjectContext.InjectDependencesTo(this);

                PrimaryBuffer = HleMemoryManager.GetPartition(MemoryPartitions.User).Allocate(1024);

                this.CodecType = CodecType;
            }
Esempio n. 17
0
        void CreateNewContextAndRemoveOldOne()
        {
            Console.WriteLine("----------------------------------------------");
            // Stops the current context if it has one already.
            if (PspRunner != null)
            {
                PspRunner.StopSynchronized();

                InjectContext.GetInstance<PspMemory>().Dispose();
                InjectContext.GetInstance<GpuImpl>().StopSynchronized();
                InjectContext.GetInstance<PspAudioImpl>().StopSynchronized();

                PspRunner = null;
                _InjectContext.Dispose();
                _InjectContext = null;
                GC.Collect();
            }

            lock (this)
            {

                _InjectContext = PspInjectContext.CreateInjectContext(StoredConfig, Test: false);
                _InjectContext.SetInstanceType<IGuiExternalInterface, PspEmulator>();

                _InjectContext.InjectDependencesTo(this);

                PspRunner.StartSynchronized();
            }

            //GpuImpl.InitSynchronizedOnce();
        }
Esempio n. 18
0
 public PluginInfo GetGpuPluginInfo()
 {
     return(InjectContext.GetInstance <GpuImpl>().PluginInfo);
 }
Esempio n. 19
0
 Hoge CreateHogeMethod(InjectContext context)
 {
     return(new Hoge());
 }
Esempio n. 20
0
        /// <summary>
        ///     Copies the information from the origin method to injected method.
        /// </summary>
        /// <param name="methodDef">The origin MethodDef.</param>
        /// <param name="ctx">The injection context.</param>
        static void CopyMethodDef(MethodDef methodDef, InjectContext ctx)
        {
            var newMethodDef = ctx.Map(methodDef)?.ResolveMethodDefThrow();

            newMethodDef.Signature = ctx.Importer.Import(methodDef.Signature);
            newMethodDef.Parameters.UpdateParameterTypes();

            if (methodDef.ImplMap != null)
            {
                newMethodDef.ImplMap = new ImplMapUser(new ModuleRefUser(ctx.TargetModule, methodDef.ImplMap.Module.Name), methodDef.ImplMap.Name, methodDef.ImplMap.Attributes);
            }

            foreach (CustomAttribute ca in methodDef.CustomAttributes)
            {
                newMethodDef.CustomAttributes.Add(new CustomAttribute((ICustomAttributeType)ctx.Importer.Import(ca.Constructor)));
            }

            if (methodDef.HasBody)
            {
                newMethodDef.Body          = new CilBody(methodDef.Body.InitLocals, new List <Instruction>(), new List <ExceptionHandler>(), new List <Local>());
                newMethodDef.Body.MaxStack = methodDef.Body.MaxStack;

                var bodyMap = new Dictionary <object, object>();

                foreach (Local local in methodDef.Body.Variables)
                {
                    var newLocal = new Local(ctx.Importer.Import(local.Type));
                    newMethodDef.Body.Variables.Add(newLocal);
                    newLocal.Name = local.Name;

                    bodyMap[local] = newLocal;
                }

                foreach (Instruction instr in methodDef.Body.Instructions)
                {
                    var newInstr = new Instruction(instr.OpCode, instr.Operand);
                    newInstr.SequencePoint = instr.SequencePoint;

                    if (newInstr.Operand is IType)
                    {
                        newInstr.Operand = ctx.Importer.Import((IType)newInstr.Operand);
                    }

                    else if (newInstr.Operand is IMethod)
                    {
                        newInstr.Operand = ctx.Importer.Import((IMethod)newInstr.Operand);
                    }

                    else if (newInstr.Operand is IField)
                    {
                        newInstr.Operand = ctx.Importer.Import((IField)newInstr.Operand);
                    }

                    newMethodDef.Body.Instructions.Add(newInstr);
                    bodyMap[instr] = newInstr;
                }

                foreach (Instruction instr in newMethodDef.Body.Instructions)
                {
                    if (instr.Operand != null && bodyMap.ContainsKey(instr.Operand))
                    {
                        instr.Operand = bodyMap[instr.Operand];
                    }

                    else if (instr.Operand is Instruction[])
                    {
                        instr.Operand = ((Instruction[])instr.Operand).Select(target => (Instruction)bodyMap[target]).ToArray();
                    }
                }

                foreach (ExceptionHandler eh in methodDef.Body.ExceptionHandlers)
                {
                    newMethodDef.Body.ExceptionHandlers.Add(new ExceptionHandler(eh.HandlerType)
                    {
                        CatchType    = eh.CatchType == null ? null : (ITypeDefOrRef)ctx.Importer.Import(eh.CatchType),
                        TryStart     = (Instruction)bodyMap[eh.TryStart],
                        TryEnd       = (Instruction)bodyMap[eh.TryEnd],
                        HandlerStart = (Instruction)bodyMap[eh.HandlerStart],
                        HandlerEnd   = (Instruction)bodyMap[eh.HandlerEnd],
                        FilterStart  = eh.FilterStart == null ? null : (Instruction)bodyMap[eh.FilterStart]
                    });
                }

                newMethodDef.Body.SimplifyMacros(newMethodDef.Parameters);
            }
        }
Esempio n. 21
0
 IEnumerable <Foo> CreateFoos(InjectContext ctx)
 {
     yield return(new Foo());
 }
Esempio n. 22
0
 void IInjectInitialize.Initialize()
 {
     _InjectContext2 = _InjectContext1;
 }
Esempio n. 23
0
 public PluginInfo GetGpuPluginInfo() => InjectContext.GetInstance <GpuImpl>().PluginInfo;
Esempio n. 24
0
        private object ExecuteConstructor(IContainer container, IInjectContext parentContext, ConstructorInfoCache constructor, Type type, params object[] addDependencies)
        {
            ParameterInfoCache[] parameters = constructor.Parameters;

            if (parameters == null || parameters.Length == 0)
            {
                return(constructor.ConstructorInfo.Invoke(null));
            }

            // Resolve parameters

            object[] paramObjects = new object[parameters.Length];

            for (int i = 0; i < parameters.Length; i++)
            {
                ParameterInfoCache parameter     = parameters[i];
                ParameterInfo      parameterInfo = parameter.ParameterInfo;

                // Can we resolve this?
                if (container.HasBindingFor(parameterInfo.ParameterType))
                {
                    bool isCircularDependency = false;

                    foreach (Type resolvingType in _currentlyResolvingTypes)
                    {
                        if (parameterInfo.ParameterType.IsAssignableFrom(resolvingType))
                        {
                            isCircularDependency = true;
                        }
                    }

                    // Prevent recursive / circular dependency...
                    if (isCircularDependency)
                    {
                        LogHandler?.Invoke("Injector: Circular dependency detected in Type {0} parameter index: {1}", type, i);
                        paramObjects[i] = null;
                    }
                    else
                    {
                        InjectContext injectContext = new InjectContext(container, constructor.DeclaringType, parentContext);

                        object paramInstance = container.ResolveWithCategory(parameterInfo.ParameterType, parameters[i].InjectAttribute?.Category, injectContext);
                        paramObjects[i] = paramInstance;
                    }
                }
                else
                {
                    bool hasAdditionalDependency = false;

                    // Check additional dependencies...
                    foreach (object dependency in addDependencies)
                    {
                        if (parameterInfo.ParameterType.IsInstanceOfType(dependency))
                        {
                            hasAdditionalDependency = true;
                            paramObjects[i]         = dependency;

                            break;
                        }
                    }

                    if (!hasAdditionalDependency)
                    {
                        LogHandler?.Invoke("Injector: {0} - Type is not bound in the container, assigning as null {1}, parameter index: {2}", type, parameterInfo.ParameterType, i);
                        paramObjects[i] = null;
                    }
                }
            }


            // Invoke constructor...
            object instance = constructor.ConstructorInfo.Invoke(paramObjects);

            return(instance);
        }
    private bool IsColor(InjectContext _injectContext)
    {
        var test = _injectContext.ObjectInstance as SelectionDetector_NoSolid;

        return(test != null && test.m_isColor);
    }
Esempio n. 26
0
 void IDisposable.Dispose()
 {
     Console.WriteLine("PspEmulator.Dispose()");
     InjectContext.Dispose();
     _InjectContext = null;
 }
 protected abstract TAction GetCommandAction(InjectContext context);
Esempio n. 28
0
 Foo CreateFoo(InjectContext ctx)
 {
     return(new Foo());
 }
 private async void OnMainAssetStoreInstantiated(InjectContext ctx, MainAssetStore mainAssetStore)
 {
     await mainAssetStore.LoadAllMetaAsync(_config.AssetType);
 }
Esempio n. 30
0
        /// <summary>
        ///     Copies the information from the origin field to injected field.
        /// </summary>
        /// <param name="fieldDef">The origin FieldDef.</param>
        /// <param name="ctx">The injection context.</param>
        static void CopyFieldDef(FieldDef fieldDef, InjectContext ctx)
        {
            var newFieldDef = ctx.Map(fieldDef).ResolveFieldDefThrow();

            newFieldDef.Signature = ctx.Importer.Import(fieldDef.Signature);
        }
Esempio n. 31
0
 public override IEnumerable <ZenjectResolveException> ValidateBinding(InjectContext context)
 {
     return(context.Container.ValidateObjectGraph <TCommand>(context, typeof(TAction)));
 }
Esempio n. 32
0
        public static InjectContext CreateInjectContext(PspStoredConfig StoredConfig, bool Test)
        {
            var _InjectContext = new InjectContext();
            _InjectContext.SetInstance<PspStoredConfig>(StoredConfig);
            _InjectContext.GetInstance<HleConfig>().HleModulesDll = typeof(HleModulesRoot).Assembly;
            _InjectContext.SetInstanceType<ICpuConnector, HleThreadManager>();
            _InjectContext.SetInstanceType<IGpuConnector, HleThreadManager>();
            _InjectContext.SetInstanceType<IInterruptManager, HleInterruptManager>();

            // Memory
            #if true // Disabled because crashes on x86
            if (StoredConfig.UseFastMemory)
            {
                _InjectContext.SetInstanceType<PspMemory, FastPspMemory>();
            }
            else
            #endif
            {
                _InjectContext.SetInstanceType<PspMemory, NormalPspMemory>();
            }

            if (!Test)
            {
                // GPU
                PspPluginImpl.SelectWorkingPlugin<GpuImpl>(_InjectContext,
            #if false
                    typeof(GpuImplNull)
            #else
                    typeof(OpenglGpuImpl),
                    //typeof(GpuImplOpenglEs),
                    //typeof(GpuImplSoft),
                    typeof(GpuImplNull)
            #endif
                );

                // AUDIO

                var AudioPlugins = new List<Type>();

                AudioPlugins.Add(typeof(PspAudioOpenalImpl));

                if (Platform.OS == OS.Windows)
                {
                    AudioPlugins.Add(typeof(PspAudioWaveOutImpl));
                }
                if (Platform.OS == OS.Linux)
                {
                    AudioPlugins.Add(typeof(AudioAlsaImpl));
                }
                AudioPlugins.Add(typeof(AudioImplNull));

                PspPluginImpl.SelectWorkingPlugin<PspAudioImpl>(_InjectContext, AudioPlugins.ToArray());
            }
            else
            {
                _InjectContext.SetInstanceType<GpuImpl, OpenglGpuImpl>();
                _InjectContext.SetInstanceType<PspAudioImpl, AudioImplNull>();
            }

            return _InjectContext;
        }
Esempio n. 33
0
 public CpuEmitter(InjectContext InjectContext, MipsMethodEmitter MipsMethodEmitter, IInstructionReader InstructionReader)
 {
     InjectContext.InjectDependencesTo(this);
     this.MipsMethodEmitter = MipsMethodEmitter;
     this.InstructionReader = InstructionReader;
 }
Esempio n. 34
0
 void IDisposable.Dispose()
 {
     Console.WriteLine("PspEmulator.Dispose()");
     InjectContext.Dispose();
     _InjectContext = null;
 }
Esempio n. 35
0
        public HleThread(InjectContext InjectContext, CpuThreadState CpuThreadState)
        {
            InjectContext.InjectDependencesTo(this);
            //this.PspConfig = CpuThreadState.CpuProcessor.CpuConfig;

            if (this.HleConfig.UseCoRoutines)
            {
                this.Coroutine = HleThreadManager.CoroutinePool.CreateCoroutine(this.Name, MainLoop);
            }
            else
            {
                this.GreenThread = new GreenThread();
                GreenThread.InitAndStartStopped(MainLoop);
            }

            this.CpuThreadState = CpuThreadState;
        }
Esempio n. 36
0
 public PluginInfo GetAudioPluginInfo()
 {
     return(InjectContext.GetInstance <PspAudioImpl>().PluginInfo);
 }
Esempio n. 37
0
 protected DiContainer SubContainerInstanceGetter(InjectContext containerContext)
 {
     return(containerContext.Container.ResolveId <DiContainer>(SubContainerName));
 }
Esempio n. 38
0
            public Atrac(InjectContext InjectContext, byte* Data, int DataLength)
            {
                InjectContext.InjectDependencesTo(this);

                PrimaryBuffer = HleMemoryManager.GetPartition(MemoryPartitions.User).Allocate(1024);

                CodecType = CodecType.PSP_MODE_AT_3_PLUS;
                SetData(Data, DataLength);
            }
Esempio n. 39
0
        /// <summary>
        /// Imports a <see cref="MethodBase"/> as a <see cref="IMethod"/>. This will be either
        /// a <see cref="MemberRef"/> or a <see cref="MethodSpec"/>.
        /// </summary>
        /// <param name="source">The source module.</param>
        /// <param name="methodBase">The method</param>
        /// <returns>The imported method or <c>null</c> if <paramref name="methodBase"/> is invalid
        /// or if we failed to import the method</returns>
        public static IMethod Import(ModuleDef target, MethodBase methodBase)
        {
            var ctx = new InjectContext(null, target);

            return(ctx.Importer.Import(methodBase));
        }
Esempio n. 40
0
		/// <summary>
		///     Copies the information from the origin field to injected field.
		/// </summary>
		/// <param name="fieldDef">The origin FieldDef.</param>
		/// <param name="ctx">The injection context.</param>
		static void CopyFieldDef(FieldDef fieldDef, InjectContext ctx) {
			var newFieldDef = (FieldDef)ctx.Map[fieldDef];

			newFieldDef.Signature = ctx.Importer.Import(fieldDef.Signature);
		}
Esempio n. 41
0
 public void CaptureGpuFrame()
 {
     InjectContext.GetInstance <GpuProcessor>().CaptureFrame();
 }
Esempio n. 42
0
 private void SetOnInstatiated(InjectContext arg1, Employee arg2)
 {
     arg2.stateMachineClass = new StateMachineClass <EmployeeState>();
 }
Esempio n. 43
0
 public PluginInfo GetAudioPluginInfo() => InjectContext.GetInstance <PspAudioImpl>().PluginInfo;
Esempio n. 44
0
 public Type GetInstanceType(InjectContext context)
 {
     return(_contractType);
 }
Esempio n. 45
0
        public void Inject(object objValue, IInjectContext parentContext)
        {
            Type tType = objValue.GetType();

            // Ensure cached reflection...
            PreInjectReflection(tType);

            _currentlyResolvingTypes.Add(tType);

            // Inject methods...
            for (int i = 0; i < _cachedMethods[tType].Count(); i++)
            {
                MethodInfoCache method = _cachedMethods[tType].ElementAt(i);

                InjectMethod(_container, parentContext, tType, objValue, method);
            }

            // Inject into Fields...
            for (int i = 0; i < _cachedFields[tType].Count(); i++)
            {
                MemberInfoCache memberCache = _cachedFields[tType].ElementAt(i);
                FieldInfo       field       = (FieldInfo)memberCache.MemberInfo;

                bool isCircularReference = false;

                if (field.FieldType.IsAssignableFrom(typeof(IContainer)))
                {
                    field.SetValue(objValue, _container);
                    continue;
                }

                foreach (Type type in _currentlyResolvingTypes)
                {
                    if (field.FieldType.IsAssignableFrom(type))
                    {
                        var binding = _container.GetBinding(field.FieldType, memberCache.InjectAttribute.Category);

                        if (binding != null && binding.BindingType == BindingType.Transient)
                        {
                            isCircularReference = true;
                        }
                    }
                }

                if (isCircularReference)
                {
                    LogHandler?.Invoke("Injector: Circular dependency detected in Field {0}.{1}", tType, field.Name);
                }
                else
                {
                    InjectContext injectContext = new InjectContext(_container, memberCache.DeclaringType, parentContext);

                    object fieldValue = _container.ResolveWithCategory(field.FieldType, memberCache.InjectAttribute.Category, injectContext);

                    field.SetValue(objValue, fieldValue);
                }
            }

            // Inject into Properties...
            for (int i = 0; i < _cachedProperties[tType].Count(); i++)
            {
                MemberInfoCache memberCache = _cachedProperties[tType].ElementAt(i);
                PropertyInfo    property    = (PropertyInfo)memberCache.MemberInfo;

                bool isCircularReference = false;

                if (property.PropertyType.IsAssignableFrom(typeof(IContainer)))
                {
                    property.SetValue(objValue, _container, null);
                    continue;
                }

                foreach (Type type in _currentlyResolvingTypes)
                {
                    if (property.PropertyType.IsAssignableFrom(type))
                    {
                        var binding = _container.GetBinding(property.PropertyType, memberCache.InjectAttribute.Category);

                        if (binding != null && binding.BindingType == BindingType.Transient)
                        {
                            isCircularReference = true;
                        }
                    }
                }

                if (isCircularReference)
                {
                    LogHandler?.Invoke("Injector: Circular dependency detected in Property {0}.{1}", tType, property.Name);
                }
                else
                {
                    InjectContext injectContext = new InjectContext(_container, memberCache.DeclaringType, parentContext);

                    object propertyValue = _container.ResolveWithCategory(property.PropertyType, memberCache.InjectAttribute.Category, injectContext);

                    property.SetValue(objValue, propertyValue, null);
                }
            }

            _currentlyResolvingTypes.Remove(tType);
        }
Esempio n. 46
0
		public Mpeg(InjectContext InjectContext)
		{
			InjectContext.InjectDependencesTo(this);
			Create();
		}
 public Type GetInstanceType(InjectContext context)
 {
     return(typeof(GameObject));
 }
Esempio n. 48
0
		/// <summary>
		///     Copies the information from the origin method to injected method.
		/// </summary>
		/// <param name="methodDef">The origin MethodDef.</param>
		/// <param name="ctx">The injection context.</param>
		static void CopyMethodDef(MethodDef methodDef, InjectContext ctx) {
			var newMethodDef = (MethodDef)ctx.Map[methodDef];

			newMethodDef.Signature = ctx.Importer.Import(methodDef.Signature);
			newMethodDef.Parameters.UpdateParameterTypes();

			if (methodDef.ImplMap != null)
				newMethodDef.ImplMap = new ImplMapUser(new ModuleRefUser(ctx.TargetModule, methodDef.ImplMap.Module.Name), methodDef.ImplMap.Name, methodDef.ImplMap.Attributes);

			foreach (CustomAttribute ca in methodDef.CustomAttributes)
				newMethodDef.CustomAttributes.Add(new CustomAttribute((ICustomAttributeType)ctx.Importer.Import(ca.Constructor)));

			if (methodDef.HasBody) {
				newMethodDef.Body = new CilBody(methodDef.Body.InitLocals, new List<Instruction>(), new List<ExceptionHandler>(), new List<Local>());
				newMethodDef.Body.MaxStack = methodDef.Body.MaxStack;

				var bodyMap = new Dictionary<object, object>();

				foreach (Local local in methodDef.Body.Variables) {
					var newLocal = new Local(ctx.Importer.Import(local.Type));
					newMethodDef.Body.Variables.Add(newLocal);
					newLocal.Name = local.Name;
					newLocal.PdbAttributes = local.PdbAttributes;

					bodyMap[local] = newLocal;
				}

				foreach (Instruction instr in methodDef.Body.Instructions) {
					var newInstr = new Instruction(instr.OpCode, instr.Operand);
					newInstr.SequencePoint = instr.SequencePoint;

					if (newInstr.Operand is IType)
						newInstr.Operand = ctx.Importer.Import((IType)newInstr.Operand);

					else if (newInstr.Operand is IMethod)
						newInstr.Operand = ctx.Importer.Import((IMethod)newInstr.Operand);

					else if (newInstr.Operand is IField)
						newInstr.Operand = ctx.Importer.Import((IField)newInstr.Operand);

					newMethodDef.Body.Instructions.Add(newInstr);
					bodyMap[instr] = newInstr;
				}

				foreach (Instruction instr in newMethodDef.Body.Instructions) {
					if (instr.Operand != null && bodyMap.ContainsKey(instr.Operand))
						instr.Operand = bodyMap[instr.Operand];

					else if (instr.Operand is Instruction[])
						instr.Operand = ((Instruction[])instr.Operand).Select(target => (Instruction)bodyMap[target]).ToArray();
				}

				foreach (ExceptionHandler eh in methodDef.Body.ExceptionHandlers)
					newMethodDef.Body.ExceptionHandlers.Add(new ExceptionHandler(eh.HandlerType) {
						CatchType = eh.CatchType == null ? null : (ITypeDefOrRef)ctx.Importer.Import(eh.CatchType),
						TryStart = (Instruction)bodyMap[eh.TryStart],
						TryEnd = (Instruction)bodyMap[eh.TryEnd],
						HandlerStart = (Instruction)bodyMap[eh.HandlerStart],
						HandlerEnd = (Instruction)bodyMap[eh.HandlerEnd],
						FilterStart = eh.FilterStart == null ? null : (Instruction)bodyMap[eh.FilterStart]
					});

				newMethodDef.Body.SimplifyMacros(newMethodDef.Parameters);
			}
		}
Esempio n. 49
0
 /// <summary>
 /// エラーレスポンスを返すAPIのスタブを持ったテスト対象クラスを作成する
 /// </summary>
 /// <param name="_"></param>
 /// <returns></returns>
 private SpeechToTextUsecase CreateSutWithErrorApiStub(InjectContext _)
 {
     return(new SpeechToTextUsecase(
                new SpeechToTextApiStub(() => "Error")));
 }
Esempio n. 50
0
		/// <summary>
		///     Copies the information to the injected definitions.
		/// </summary>
		/// <param name="typeDef">The origin TypeDef.</param>
		/// <param name="ctx">The injection context.</param>
		/// <param name="copySelf">if set to <c>true</c>, copy information of <paramref name="typeDef" />.</param>
		static void Copy(TypeDef typeDef, InjectContext ctx, bool copySelf) {
			if (copySelf)
				CopyTypeDef(typeDef, ctx);

			foreach (TypeDef nestedType in typeDef.NestedTypes)
				Copy(nestedType, ctx, true);

			foreach (MethodDef method in typeDef.Methods)
				CopyMethodDef(method, ctx);

			foreach (FieldDef field in typeDef.Fields)
				CopyFieldDef(field, ctx);
		}
Esempio n. 51
0
        private static void CopyFieldDef(FieldDef fieldDef, InjectContext ctx)
        {
            var newFieldDef = (FieldDef)ctx.map[fieldDef];

            newFieldDef.Signature = ctx.Importer.Import(fieldDef.Signature);
        }
Esempio n. 52
0
		/// <summary>
		///     Copies the information from the origin type to injected type.
		/// </summary>
		/// <param name="typeDef">The origin TypeDef.</param>
		/// <param name="ctx">The injection context.</param>
		static void CopyTypeDef(TypeDef typeDef, InjectContext ctx) {
			var newTypeDef = (TypeDef)ctx.Map[typeDef];

			newTypeDef.BaseType = (ITypeDefOrRef)ctx.Importer.Import(typeDef.BaseType);

			foreach (InterfaceImpl iface in typeDef.Interfaces)
				newTypeDef.Interfaces.Add(new InterfaceImplUser((ITypeDefOrRef)ctx.Importer.Import(iface.Interface)));
		}
Esempio n. 53
0
        private static void CopyMethodDef(MethodDef methodDef, InjectContext ctx)
        {
            var newMethodDef = (MethodDef)ctx.map[methodDef];

            newMethodDef.Signature = ctx.Importer.Import(methodDef.Signature);
            newMethodDef.Parameters.UpdateParameterTypes();

            if (methodDef.ImplMap != null)
            {
                newMethodDef.ImplMap = new ImplMapUser(new ModuleRefUser(ctx.TargetModule, methodDef.ImplMap.Module.Name), methodDef.ImplMap.Name, methodDef.ImplMap.Attributes);
            }

            foreach (var ca in methodDef.CustomAttributes)
            {
                newMethodDef.CustomAttributes.Add(new CustomAttribute((ICustomAttributeType)ctx.Importer.Import(ca.Constructor)));
            }

            if (!methodDef.HasBody)
            {
                return;
            }
            newMethodDef.Body = new CilBody(methodDef.Body.InitLocals, new List <Instruction>(),
                                            new List <ExceptionHandler>(), new List <Local>())
            {
                MaxStack = methodDef.Body.MaxStack
            };

            var bodyMap = new Dictionary <object, object>();

            foreach (var local in methodDef.Body.Variables)
            {
                var newLocal = new Local(ctx.Importer.Import(local.Type));
                newMethodDef.Body.Variables.Add(newLocal);
                newLocal.Name       = local.Name;
                newLocal.Attributes = local.Attributes;

                bodyMap[local] = newLocal;
            }

            foreach (var instr in methodDef.Body.Instructions)
            {
                var newInstr = new Instruction(instr.OpCode, instr.Operand)
                {
                    SequencePoint = instr.SequencePoint
                };

                switch (newInstr.Operand)
                {
                case IType type:
                    newInstr.Operand = ctx.Importer.Import(type);
                    break;

                case IMethod method:
                    newInstr.Operand = ctx.Importer.Import(method);
                    break;

                case IField field:
                    newInstr.Operand = ctx.Importer.Import(field);
                    break;
                }

                newMethodDef.Body.Instructions.Add(newInstr);
                bodyMap[instr] = newInstr;
            }

            foreach (var instr in newMethodDef.Body.Instructions)
            {
                if (instr.Operand != null && bodyMap.ContainsKey(instr.Operand))
                {
                    instr.Operand = bodyMap[instr.Operand];
                }
                else if (instr.Operand is Instruction[] v)
                {
                    instr.Operand = v.Select(target => (Instruction)bodyMap[target]).ToArray();
                }
            }

            foreach (var eh in methodDef.Body.ExceptionHandlers)
            {
                newMethodDef.Body.ExceptionHandlers.Add(new ExceptionHandler(eh.HandlerType)
                {
                    CatchType    = eh.CatchType == null ? null : ctx.Importer.Import(eh.CatchType),
                    TryStart     = (Instruction)bodyMap[eh.TryStart],
                    TryEnd       = (Instruction)bodyMap[eh.TryEnd],
                    HandlerStart = (Instruction)bodyMap[eh.HandlerStart],
                    HandlerEnd   = (Instruction)bodyMap[eh.HandlerEnd],
                    FilterStart  = eh.FilterStart == null ? null : (Instruction)bodyMap[eh.FilterStart]
                });
            }

            newMethodDef.Body.SimplifyMacros(newMethodDef.Parameters);
        }
Esempio n. 54
0
 Dictionary <string, IFactory <Foo> > GetFooFactories(InjectContext ctx)
 {
     return(ctx.Container.AllContracts.Where(
                x => x.Type == typeof(Foo.Factory))
            .ToDictionary(x => (string)x.Identifier, x => (IFactory <Foo>)ctx.Container.ResolveId <Foo.Factory>(x.Identifier)));
 }
 public Type GetInstanceType(InjectContext context)
 {
     return(typeof(TReturn));
 }