Пример #1
1
        void CopyTo(CustomAttribute target, ModuleDefinition context)
        {
            foreach (var arg in ConstructorArguments)
                target.ConstructorArguments.Add(new CustomAttributeArgument(context.ImportReference(arg.Type), arg.Value));

            foreach (var field in Fields)
                target.Fields.Add(new CustomAttributeNamedArgument(field.Name, new CustomAttributeArgument(context.ImportReference(field.Argument.Type), field.Argument.Value)));

            foreach (var prop in Properties)
                target.Properties.Add(new CustomAttributeNamedArgument(prop.Name, new CustomAttributeArgument(context.ImportReference(prop.Argument.Type), prop.Argument.Value)));
        }
 public override void InjectInto(ModuleDefinition gamedef, ModuleDefinition moddef)
 {
     // This injects a call to the mod's static Init() method into the top of the game's central Provider Awake method.
     // Our mod init will run before anything else in the assembly due to this.
     TypeDefinition modtype = moddef.GetType("UnturnedFrenetic.UnturnedFreneticMod");
     MethodReference initmethod = gamedef.ImportReference(GetMethod(modtype, "Init", 0));
     MethodReference initmethod2 = gamedef.ImportReference(GetMethod(modtype, "InitSecondary", 0));
     TypeDefinition providertype = gamedef.GetType("SDG.Unturned.Provider");
     MethodDefinition awakemethod = GetMethod(providertype, "Awake");
     MethodBody awakebody = awakemethod.Body;
     // Call: the mod initialization.
     awakebody.Instructions.Insert(0, Instruction.Create(OpCodes.Call, initmethod));
     // Call: the mod secondary initialization.
     awakebody.Instructions.Insert(117, Instruction.Create(OpCodes.Call, initmethod2));
 }
 public override void InjectInto(ModuleDefinition gamedef, ModuleDefinition moddef)
 {
     // This injects a call to the mod's static AnimalDamaged method for the AnimalDamagedScriptEvent
     TypeDefinition modtype = moddef.GetType("UnturnedFrenetic.UnturnedFreneticMod");
     MethodReference eventmethod = gamedef.ImportReference(GetMethod(modtype, "AnimalDamaged", 4));
     TypeDefinition animaltype = gamedef.GetType("SDG.Unturned.Animal");
     MethodDefinition damagemethod = GetMethod(animaltype, "askDamage", 4);
     MethodBody damagebody = damagemethod.Body;
     InjectInstructions(damagebody, 0, new Instruction[]
     {
             // Load "this" onto the stack.
             Instruction.Create(OpCodes.Ldarg_0),
             // Load "amount" onto the stack.
             Instruction.Create(OpCodes.Ldarga_S, damagemethod.Parameters[0]),
             // Load "newRagdoll" onto the stack.
             Instruction.Create(OpCodes.Ldarga_S, damagemethod.Parameters[1]),
             // Load "xp" onto the stack
             Instruction.Create(OpCodes.Ldarga_S, damagemethod.Parameters[3]),
             // Call the AnimalDamaged method with the above parameters and return a bool.
             Instruction.Create(OpCodes.Call, eventmethod),
             // If the return is false, jump ahead to the original 0th instruction.
             Instruction.Create(OpCodes.Brfalse, damagebody.Instructions[0]),
             // Otherwise, return now.
             Instruction.Create(OpCodes.Ret)
     });
 }
Пример #4
0
        public void Rewrite(ModuleDefinition module, IEnumerable<ImplementedEventSource> loggers)
        {
            var fullNameOfGet = module
                                    .ImportReference(typeof(Enyim.EventSourceFactory)).Resolve()
                                    .FindMethod("Get").FullName;
            var methods = module.Types.SelectMany(t => t.Methods).Where(m => m.HasBody).ToArray();
            var implMap = loggers.ToDictionary(l => l.Old.FullName);
            var localRemap = new Dictionary<string, TypeDefinition>();

            foreach (var method in methods)
            {
                var factoryCalls = (from i in method.GetOpsOf(OpCodes.Call)
                                    let mr = i.Operand as MethodReference
                                    where mr.IsGenericInstance
                                            && mr.Resolve()
                                                    ?.GetElementMethod()
                                                    ?.FullName == fullNameOfGet
                                    select new
                                    {
                                        Instruction = i,
                                        Wanted = ((GenericInstanceMethod)mr).GenericArguments.First().Resolve()
                                    }).ToArray();

                if (factoryCalls.Length > 0)
                {
                    var ilp = method.Body.GetILProcessor();

                    foreach (var tmp in factoryCalls)
                    {
                        ImplementedEventSource ies;
                        var rewriteTo = tmp.Wanted.IsClass
                                            ? tmp.Wanted.Resolve()
                                            : implMap.TryGetValue(tmp.Wanted.FullName, out ies)
                                                ? ies.New
                                                : null;

                        if (rewriteTo == null)
                        {
                            Log.Warn($"Factory: cannot rewrite {tmp.Wanted.FullName}");
                            continue;
                        }

                        var ctor = rewriteTo.FindConstructor();
                        if (ctor == null) throw new InvalidOperationException($"{rewriteTo.FullName} has no constructor");

                        var newobj = Instruction.Create(OpCodes.Newobj, ctor);
                        newobj.SequencePoint = tmp.Instruction.SequencePoint;
                        ilp.Replace(tmp.Instruction, newobj);

                        Log.Info($"Factory: {tmp.Wanted.FullName} -> {rewriteTo.FullName}");

                        localRemap[tmp.Wanted.FullName] = rewriteTo;
                    }
                }

                RewriteLocalVariables(method, localRemap);
            }
        }
Пример #5
0
        public static Mono.Cecil.TypeReference ToMonoTypeReference(this System.Type type)
        {
            String kernel_assembly_file_name = type.Assembly.Location;

            Mono.Cecil.ModuleDefinition md = Mono.Cecil.ModuleDefinition.ReadModule(kernel_assembly_file_name);
            var reference = md.ImportReference(type);

            return(reference);
        }
Пример #6
0
        public void Add(MethodInfo reference)
        {
            String kernel_assembly_file_name = reference.DeclaringType.Assembly.Location;

            Mono.Cecil.ModuleDefinition md    = Campy.Meta.StickyReadMod.StickyReadModule(kernel_assembly_file_name);
            MethodReference             refer = md.ImportReference(reference);

            Add(refer);
        }
 public override void InjectInto(ModuleDefinition gamedef, ModuleDefinition moddef)
 {
     // This injects a call to the mod's static ZombieDamaged method for the ZombieDamagedScriptEvent. Also exposes some zombie variables. Also, disable its AI optionally.
     TypeDefinition zombietype = gamedef.GetType("SDG.Unturned.Zombie");
     FieldDefinition field = GetField(zombietype, "target");
     field.IsPrivate = false;
     field.IsPublic = true;
     FieldDefinition fieldistick = GetField(zombietype, "isTicking");
     fieldistick.IsPrivate = false;
     fieldistick.IsPublic = true;
     FieldDefinition fieldseeker = GetField(zombietype, "seeker");
     fieldseeker.IsPrivate = false;
     fieldseeker.IsPublic = true;
     FieldDefinition fieldpath = GetField(zombietype, "path");
     fieldpath.IsPrivate = false;
     fieldpath.IsPublic = true;
     FieldDefinition aidisabledfield = new FieldDefinition("UFM_AIDisabled", FieldAttributes.Public, gamedef.TypeSystem.Boolean);
     zombietype.Fields.Add(aidisabledfield);
     foreach (MethodDefinition tmethod in zombietype.Methods)
     {
         switch (tmethod.Name)
         {
             case "alert":
                 DisableAI(tmethod.Body, aidisabledfield);
                 break;
             default:
                 break;
         }
     }
     // TODO: Disable things in the update methods too.
     TypeDefinition modtype = moddef.GetType("UnturnedFrenetic.UnturnedFreneticMod");
     MethodReference eventmethod = gamedef.ImportReference(GetMethod(modtype, "ZombieDamaged", 4));
     MethodDefinition damagemethod = GetMethod(zombietype, "askDamage", 4);
     MethodBody damagebody = damagemethod.Body;
     InjectInstructions(damagebody, 0, new Instruction[]
     {
             // Load "this" onto the stack.
             Instruction.Create(OpCodes.Ldarg_0),
             // Load "amount" onto the stack.
             Instruction.Create(OpCodes.Ldarga_S, damagemethod.Parameters[0]),
             // Load "newRagdoll" onto the stack.
             Instruction.Create(OpCodes.Ldarga_S, damagemethod.Parameters[1]),
             // Load "xp" onto the stack
             Instruction.Create(OpCodes.Ldarga_S, damagemethod.Parameters[3]),
             // Call the ZombieDamaged method with the above parameters and return a bool.
             Instruction.Create(OpCodes.Call, eventmethod),
             // If the return is false, jump ahead to the original 0th instruction.
             Instruction.Create(OpCodes.Brfalse, damagebody.Instructions[0]),
             // Otherwise, return now.
             Instruction.Create(OpCodes.Ret)
     });
 }
 public override void InjectInto(ModuleDefinition gamedef, ModuleDefinition moddef)
 {
     // This injects a debug output message to the "debug" command, as well as allowing execution
     // of Frenetic command via the debug command.
     // To use, simple input: debug echo "Hello world!"
     // Replace the command after debug with any valid Frenetic-enabled command.
     TypeDefinition debugtype = gamedef.GetType("SDG.Unturned.CommandDebug");
     MethodDefinition method = GetMethod(debugtype, "execute");
     TypeDefinition modmaintype = moddef.GetType("UnturnedFrenetic.UnturnedFreneticMod");
     MethodDefinition modruncommands = GetMethod(modmaintype, "RunCommands", 1);
     MethodReference game_modruncommands = gamedef.ImportReference(modruncommands);
     TypeDefinition windowtype = gamedef.GetType("SDG.Unturned.CommandWindow");
     MethodDefinition logmethod = GetMethod(windowtype, "Log", 1);
     MethodDefinition isnullorempty = GetMethod(gamedef.TypeSystem.String.Resolve(), "IsNullOrEmpty", 1);
     MethodReference game_isnullorempty = gamedef.ImportReference(isnullorempty);
     MethodBody body = method.Body;
     Instruction ldstr = Instruction.Create(OpCodes.Ldstr, "Frenetic loaded properly!");
     InjectInstructions(body, 3, new Instruction[]
     {
         // Load the parameter onto the stack.
         Instruction.Create(OpCodes.Ldarg_S, method.Parameters[1]),
         // Add whether the string 'is null or empty' to the stack.
         Instruction.Create(OpCodes.Call, game_isnullorempty),
         // Jump to the end if the top of the stack is false.
         Instruction.Create(OpCodes.Brtrue_S, ldstr), // NOTE: Instruction reference will move at the end.
         // Load the parameter onto the stack.
         Instruction.Create(OpCodes.Ldarg_S, method.Parameters[1]),
         // Run commands based on the string on top of the stack.
         Instruction.Create(OpCodes.Call, game_modruncommands),
         // Return so we don't get random debug spam.
         Instruction.Create(OpCodes.Ret),
         // Load the output string onto the stack.
         ldstr,
         // Log the string.
         Instruction.Create(OpCodes.Call, logmethod)
     });
     // Redirect the result of the IF to our new method.
     body.Instructions[1].Operand = body.Instructions[3];
 }
Пример #9
0
        private void Add(MethodInfo method_info)
        {
            String kernel_assembly_file_name = method_info.DeclaringType.Assembly.Location;
            string p        = Path.GetDirectoryName(kernel_assembly_file_name);
            var    resolver = new DefaultAssemblyResolver();

            resolver.AddSearchDirectory(p);
            Mono.Cecil.ModuleDefinition md = Mono.Cecil.ModuleDefinition.ReadModule(
                kernel_assembly_file_name,
                new ReaderParameters {
                AssemblyResolver = resolver, ReadSymbols = true
            });
            MethodReference method_reference = md.ImportReference(method_info);

            Add(method_reference);
        }
Пример #10
0
        private static void JustImport(SimpleKernel simpleKernel)
        {
            System.Reflection.MethodInfo method_info = simpleKernel.Method;
            String kernel_assembly_file_name         = method_info.DeclaringType.Assembly.Location;

            Mono.Cecil.ModuleDefinition md = Campy.Meta.StickyReadMod.StickyReadModule(
                kernel_assembly_file_name, new ReaderParameters {
                ReadSymbols = true
            });
            MethodReference method_reference = md.ImportReference(method_info);

            Campy.Utils.TimePhase.Time("compile     ", () =>
            {
                Singleton._compiler.ImportOnlyCompile(method_reference, simpleKernel.Target);
            });
        }
 public override void InjectInto(ModuleDefinition gamedef, ModuleDefinition moddef)
 {
     // This injects a call to the mod's static Init() method into the top of the game's central Provider Awake method.
     // Our mod init will run before anything else in the assembly due to this.
     TypeDefinition modtype = moddef.GetType("UnturnedFrenetic.UnturnedFreneticMod");
     MethodReference connectingmethod = gamedef.ImportReference(GetMethod(modtype, "PlayerConnecting", 1));
     TypeDefinition providertype = gamedef.GetType("SDG.Unturned.Provider");
     MethodDefinition validatemethod = GetMethod(providertype, "handleValidateAuthTicketResponse", 1);
     MethodBody validatebody = validatemethod.Body;
     // Call: the mod's wrapper method.
     InjectInstructions(validatebody, 45, new Instruction[]
         {
             // Load "steamPending" onto the stack.
             Instruction.Create(OpCodes.Ldloc_0),
             // "Call the connect method with parameter 'steamPending' and returning a bool.
             Instruction.Create(OpCodes.Call, connectingmethod),
             // If the return is false, jump ahead to the original 45th instruction.
             Instruction.Create(OpCodes.Brfalse, validatebody.Instructions[45]),
             // Otherwise,return now.
             Instruction.Create(OpCodes.Ret)
         });
 }
 public override void InjectInto(ModuleDefinition gamedef, ModuleDefinition moddef)
 {
     // This injects a call to the mod's static PlayerChat method for the PlayerChatScriptEvent
     TypeDefinition managertype = gamedef.GetType("SDG.Unturned.ChatManager");
     FieldDefinition managerfield = GetField(managertype, "manager");
     managerfield.IsPrivate = false;
     managerfield.IsPublic = true;
     TypeDefinition modtype = moddef.GetType("UnturnedFrenetic.UnturnedFreneticMod");
     MethodReference eventmethod = gamedef.ImportReference(GetMethod(modtype, "PlayerChat", 5));
     MethodDefinition chatmethod = GetMethod(managertype, "askChat", 3);
     MethodBody chatbody = chatmethod.Body;
     // Remove old color handling
     chatbody.Instructions[53].Operand = chatbody.Instructions[124];
     chatbody.Instructions[81].Operand = chatbody.Instructions[124];
     chatbody.Instructions[109].Operand = chatbody.Instructions[124];
     for (int i = 111; i <= 123; i++)
     {
         chatbody.Instructions.RemoveAt(111);
     }
     InjectInstructions(chatbody, 27, new Instruction[]
         {
             // Load "steamPlayer" onto the stack.
             Instruction.Create(OpCodes.Ldloc_0),
             // Load "mode" onto the stack.
             Instruction.Create(OpCodes.Ldarga_S, chatmethod.Parameters[1]),
             // Load "eChatMode" onto the stack.
             Instruction.Create(OpCodes.Ldloca_S, chatbody.Variables[1]),
             // Load "color" onto the stack.
             Instruction.Create(OpCodes.Ldloca_S, chatbody.Variables[2]),
             // Load "text" onto the stack.
             Instruction.Create(OpCodes.Ldarga_S, chatmethod.Parameters[2]),
             // Call the PlayerChat method with the above parameters and return a bool.
             Instruction.Create(OpCodes.Call, eventmethod),
             // If the return is false, jump ahead to the original 27th instruction.
             Instruction.Create(OpCodes.Brfalse, chatbody.Instructions[27]),
             // Otherwise, return now.
             Instruction.Create(OpCodes.Ret)
         });
 }
        public InterfaceBasedTypeDefs(ModuleDefinition module)
        {
            const string MS = "Microsoft.Diagnostics.Tracing";
            const string SYS = "System.Diagnostics.Tracing";

            BaseTypeRef = GuessBaseType(module).ImportInto(module);
            BaseTypeImpl = BaseTypeRef.Resolve();
            WriteEventFallback = BaseTypeImpl.FindMethod("WriteEvent", module.TypeSystem.Int32, module.ImportReference(typeof(object[]))).ImportInto(module);

            var baseModule = BaseTypeImpl.Module;

            EventLevel = FindOne(baseModule, "EventLevel", MS, SYS).ImportInto(module);
            EventKeywords = FindOne(baseModule, "EventKeywords", MS, SYS).ImportInto(module);
            EventOpcode = FindOne(baseModule, "EventOpcode", MS, SYS).ImportInto(module);
            EventTask = FindOne(baseModule, "EventTask", MS, SYS).ImportInto(module);

            EventSourceAttribute = FindOne(baseModule, "EventSourceAttribute", MS, SYS).ImportInto(module);
            EventAttribute = FindOne(baseModule, "EventAttribute", MS, SYS).ImportInto(module);
            NonEventAttribute = FindOne(baseModule, "NonEventAttribute", MS, SYS).ImportInto(module);

            IsEnabledSpecific = BaseTypeImpl.FindMethod("IsEnabled", EventLevel, EventKeywords).ImportInto(module);
            IsEnabledFallback = BaseTypeImpl.FindMethod("IsEnabled").ImportInto(module);
        }
 public override void InjectInto(ModuleDefinition gamedef, ModuleDefinition moddef)
 {
     // This injects a call to the mod's static PlayerShoot method for the PlayerShootScriptEvent
     TypeDefinition modtype = moddef.GetType("UnturnedFrenetic.UnturnedFreneticMod");
     MethodReference eventmethod = gamedef.ImportReference(GetMethod(modtype, "PlayerShoot", 2));
     TypeDefinition guntype = gamedef.GetType("SDG.Unturned.UseableGun");
     MethodDefinition firemethod = GetMethod(guntype, "fire", 0);
     MethodBody firebody = firemethod.Body;
     InjectInstructions(firebody, 0, new Instruction[]
         {
             // Load "base.player" onto the stack.
             Instruction.Create(OpCodes.Ldarg_0),
             Instruction.Create(OpCodes.Call, GetMethod(gamedef.GetType("SDG.Unturned.PlayerCaller"), "get_player", 0)),
             // Load "this" onto the stack.
             Instruction.Create(OpCodes.Ldarg_0),
             // Call the PlayerShoot method with the above parameters and return a bool.
             Instruction.Create(OpCodes.Call, eventmethod),
             // If the return is false, jump ahead to the original 0th instruction.
             Instruction.Create(OpCodes.Brfalse, firebody.Instructions[0]),
             // Otherwise, return now.
             Instruction.Create(OpCodes.Ret)
         });
 }
Пример #15
0
 public static MethodReference ImportEx(this ModuleDefinition module, MethodReference method)
 {
     return(module.ImportReference(method));
 }
Пример #16
0
        public static Mono.Cecil.TypeReference SubstituteMonoTypeReference(this System.Type type, Mono.Cecil.ModuleDefinition md)
        {
            var reference = md.ImportReference(type);

            return(reference);
        }
Пример #17
0
 public static FieldReference ImportEx(this ModuleDefinition module, FieldReference field)
 {
     return(module.ImportReference(field));
 }
 private static TypeReference GetTypeRef(string nameSpace, string name, string assemblyName, ModuleDefinition targetModule)
 {
     TypeReference typeRef = targetModule.ImportReference(new TypeReference(nameSpace, name, targetModule,
             targetModule.AssemblyReferences.First(x => x.Name == assemblyName)));
     return typeRef;
 }
        public override void InjectInto(ModuleDefinition gamedef, ModuleDefinition moddef)
        {
            // This injects a call to the mod's static PlayerDamaged method for the PlayerDamagedScriptEvent, and exposes relevant fields. It also adds a new parameter to 'PlayerLife.askDamage'.
            TypeDefinition lifetype = gamedef.GetType("SDG.Unturned.PlayerLife");
            MakePublic(GetField(lifetype, "_health"));
            MakePublic(GetField(lifetype, "_isBleeding"));
            MakePublic(GetField(lifetype, "lastBleeding"));
            MakePublic(GetField(lifetype, "lastBleed"));
            MakePublic(GetField(lifetype, "_isBroken"));
            MakePublic(GetField(lifetype, "ragdoll"));

            TypeDefinition skillstype = gamedef.GetType("SDG.Unturned.PlayerSkills");
            MakePublic(GetField(skillstype, "_experience"));

            MethodDefinition damagemethod = GetMethod(lifetype, "askDamage", 6);
            ParameterDefinition objectParam = new ParameterDefinition("obj", ParameterAttributes.None, gamedef.ImportReference(typeof(object)));
            damagemethod.Parameters.Add(objectParam);

            TypeDefinition modtype = moddef.GetType("UnturnedFrenetic.UnturnedFreneticMod");
            MethodReference eventhealmethod = gamedef.ImportReference(GetMethod(modtype, "PlayerHealed", 4));
            MethodDefinition healmethod = GetMethod(lifetype, "askHeal", 3);
            MethodBody healbody = healmethod.Body;
            InjectInstructions(healbody, 0, new Instruction[]
                {
                    // Load "base.player" onto the stack.
                    Instruction.Create(OpCodes.Ldarg_0),
                    Instruction.Create(OpCodes.Call, GetMethod(gamedef.GetType("SDG.Unturned.PlayerCaller"), "get_player", 0)),
                    // Load "amount" onto the stack.
                    Instruction.Create(OpCodes.Ldarga_S, healmethod.Parameters[0]),
                    // Load "healBleeding" onto the stack.
                    Instruction.Create(OpCodes.Ldarga_S, healmethod.Parameters[1]),
                    // Load "healBroken" onto the stack.
                    Instruction.Create(OpCodes.Ldarga_S, healmethod.Parameters[2]),
                    // Call the PlayerHealed method with the above parameters and return a bool.
                    Instruction.Create(OpCodes.Call, eventhealmethod),
                    // If the return is false, jump ahead to the original 0th instruction.
                    Instruction.Create(OpCodes.Brfalse, healbody.Instructions[0]),
                    // Otherwise,return now.
                    Instruction.Create(OpCodes.Ret)
                });

            MethodReference eventmethod = gamedef.ImportReference(GetMethod(modtype, "PlayerDamaged", 7));
            MethodBody damagebody = damagemethod.Body;
            InjectInstructions(damagebody, 0, new Instruction[]
                {
                    // Load "base.player" onto the stack.
                    Instruction.Create(OpCodes.Ldarg_0),
                    Instruction.Create(OpCodes.Call, GetMethod(gamedef.GetType("SDG.Unturned.PlayerCaller"), "get_player", 0)),
                    // Load "amount" onto the stack.
                    Instruction.Create(OpCodes.Ldarga_S, damagemethod.Parameters[0]),
                    // Load "newRagdoll" onto the stack.
                    Instruction.Create(OpCodes.Ldarga_S, damagemethod.Parameters[1]),
                    // Load "newCause" onto the stack.
                    Instruction.Create(OpCodes.Ldarga_S, damagemethod.Parameters[2]),
                    // Load "newLimb" onto the stack.
                    Instruction.Create(OpCodes.Ldarga_S, damagemethod.Parameters[3]),
                    // Load "newKiller" onto the stack.
                    Instruction.Create(OpCodes.Ldarg, damagemethod.Parameters[4]),
                    // Load our custom "obj" onto the stack
                    Instruction.Create(OpCodes.Ldarg, objectParam),
                    // Call the PlayerDamaged method with the above parameters and return a bool.
                    Instruction.Create(OpCodes.Call, eventmethod),
                    // If the return is false, jump ahead to the original 0th instruction.
                    Instruction.Create(OpCodes.Brfalse, damagebody.Instructions[0]),
                    // Otherwise,return now.
                    Instruction.Create(OpCodes.Ret)
                });

            MethodDefinition suicidemethod = GetMethod(lifetype, "askSuicide", 1);
            MethodBody suicidebody = suicidemethod.Body;
               // Load "null" onto the stack.
            InjectInstructions(suicidebody, 19, Instruction.Create(OpCodes.Ldnull));

            MethodDefinition landedmethod = GetMethod(lifetype, "onLanded", 1);
            MethodBody landedbody = landedmethod.Body;
            // Load "null" onto the stack.
            InjectInstructions(landedbody, 34, Instruction.Create(OpCodes.Ldnull));

            MethodDefinition simulatemethod = GetMethod(lifetype, "simulate", 1);
            MethodBody simulatebody = simulatemethod.Body;
            // Load "null" onto the stack.
            InjectInstructions(simulatebody, 986, Instruction.Create(OpCodes.Ldnull));
            // Load "null" onto the stack.
            InjectInstructions(simulatebody, 814, Instruction.Create(OpCodes.Ldnull));
            // Load "null" onto the stack.
            InjectInstructions(simulatebody, 714, Instruction.Create(OpCodes.Ldnull));
            // Load "null" onto the stack.
            InjectInstructions(simulatebody, 626, Instruction.Create(OpCodes.Ldnull));
            // Load "null" onto the stack.
            InjectInstructions(simulatebody, 340, Instruction.Create(OpCodes.Ldnull));
            // Load "null" onto the stack.
            InjectInstructions(simulatebody, 201, Instruction.Create(OpCodes.Ldnull));
            // Load "null" onto the stack.
            InjectInstructions(simulatebody, 158, Instruction.Create(OpCodes.Ldnull));
            // Load "null" onto the stack.
            InjectInstructions(simulatebody, 136, Instruction.Create(OpCodes.Ldnull));
            // Load "null" onto the stack.
            InjectInstructions(simulatebody, 83, Instruction.Create(OpCodes.Ldnull));

            TypeDefinition barriertype = gamedef.GetType("SDG.Unturned.Barrier");
            MethodDefinition barriercollide = GetMethod(barriertype, "OnTriggerEnter", 1);
            MethodBody barriercollidebody = barriercollide.Body;
            // Load "this" onto the stack.
            InjectInstructions(barriercollidebody, 25, Instruction.Create(OpCodes.Ldarg_0));

            TypeDefinition slaytype = gamedef.GetType("SDG.Unturned.CommandSlay");
            MethodDefinition slayexecute = GetMethod(slaytype, "execute", 2);
            MethodBody slayexecutebody = slayexecute.Body;
            // Load "this" onto the stack.
            InjectInstructions(slayexecutebody, 67, Instruction.Create(OpCodes.Ldarg_0));

            TypeDefinition damagetooltype = gamedef.GetType("SDG.Unturned.DamageTool");
            MethodDefinition damagetooldamage = GetMethod(damagetooltype, "damage", 8);
            MethodBody damagetooldamagebody = damagetooldamage.Body;
            // Load "null" onto the stack.
            InjectInstructions(damagetooldamagebody, 24, Instruction.Create(OpCodes.Ldnull));

            TypeDefinition levelmanagertype = gamedef.GetType("SDG.Unturned.LevelManager");
            MethodDefinition levelmanagerplay = GetMethod(levelmanagertype, "arenaPlay", 0);
            MethodBody levelmanagerplaybody = levelmanagerplay.Body;
            // Load "null" onto the stack.
            InjectInstructions(levelmanagerplaybody, 217, Instruction.Create(OpCodes.Ldnull));

            MethodDefinition levelmanagerrestart = GetMethod(levelmanagertype, "arenaRestart", 0);
            MethodBody levelmanagerrestartbody = levelmanagerrestart.Body;
            // Load "null" onto the stack.
            InjectInstructions(levelmanagerrestartbody, 82, Instruction.Create(OpCodes.Ldnull));

            TypeDefinition animaltype = gamedef.GetType("SDG.Unturned.Animal");
            MethodDefinition animalupdate = GetMethod(animaltype, "tick", 0);
            MethodBody animalupdatebody = animalupdate.Body;
            // Load "this" onto the stack.
            InjectInstructions(animalupdatebody, 154, Instruction.Create(OpCodes.Ldarg_0));
            TypeDefinition zombietype = gamedef.GetType("SDG.Unturned.Zombie");
            MethodDefinition zombieupdate = GetMethod(zombietype, "tick", 0);
            MethodBody zombieupdatebody = zombieupdate.Body;
            // Load "this" onto the stack.
            InjectInstructions(zombieupdatebody, 1450, Instruction.Create(OpCodes.Ldarg_0));
        }
        private static TypeReference GuessBaseType(ModuleDefinition module)
        {
            const string MS_EVENT_SOURCE = "Microsoft.Diagnostics.Tracing.EventSource";
            const string MS_ASSEMBLY = "Microsoft.Diagnostics.Tracing.EventSource";

            var msAssemblyRef = module.AssemblyReferences.FirstOrDefault(r => r.Name == MS_ASSEMBLY);
            if (msAssemblyRef != null)
            {
                var msAssembly = module.AssemblyResolver.Resolve(msAssemblyRef);
                var baseType = msAssembly.Modules
                .SelectMany(m => m.Types)
                .FirstOrDefault(t => t.FullName == MS_EVENT_SOURCE);

                if (baseType != null)
                    return module.ImportReference(baseType);
            }

            return module.ImportReference(typeof(System.Diagnostics.Tracing.EventSource));
        }
Пример #21
0
 private static Mono.Cecil.CustomAttribute GetModelDefaultCustomAttribute(string name, string value,
     ModuleDefinition mod)
 {
     var ctor =
         mod.ImportReference(
             typeof (ModelDefaultAttribute).GetConstructor(new[] {typeof (string), typeof (string)}));
     var cb = new Mono.Cecil.CustomAttribute(ctor);
     var tr = mod.ImportReference(typeof (string));
     cb.ConstructorArguments.Add(new CustomAttributeArgument(tr, name));
     cb.ConstructorArguments.Add(new CustomAttributeArgument(tr, value));
     return cb;
 }
Пример #22
0
 public static TypeReference ImportEx(this ModuleDefinition module, TypeReference type, IGenericParameterProvider context)
 {
     return(module.ImportReference(type, context));
 }
Пример #23
0
 internal static CustomAttribute Clone(CustomAttribute custattr, ModuleDefinition context)
 {
     var ca = new CustomAttribute(context.ImportReference(custattr.Constructor));
     custattr.CopyTo(ca, context);
     return ca;
 }
Пример #24
0
 public static TypeReference ImportEx(this ModuleDefinition module, TypeReference type)
 {
     return(module.ImportReference(type));
 }
Пример #25
0
 public static FieldReference ImportEx(this ModuleDefinition module, FieldReference field, IGenericParameterProvider context)
 {
     return(module.ImportReference(field, context));
 }
Пример #26
0
 public static MethodReference ImportEx(this ModuleDefinition module, MethodReference method, IGenericParameterProvider context)
 {
     return(module.ImportReference(method, context));
 }
Пример #27
0
        public static void For(int number_of_threads, SimpleKernel simpleKernel)
        {
            if (Campy.Utils.Options.IsOn("import-only"))
            {
                JustImport(simpleKernel);
                return;
            }

            GCHandle handle1 = default(GCHandle);
            GCHandle handle2 = default(GCHandle);

            try
            {
                unsafe
                {
                    System.Reflection.MethodInfo method_info = simpleKernel.Method;
                    String kernel_assembly_file_name         = method_info.DeclaringType.Assembly.Location;
                    Mono.Cecil.ModuleDefinition md           = Campy.Meta.StickyReadMod.StickyReadModule(
                        kernel_assembly_file_name, new ReaderParameters {
                        ReadSymbols = true
                    });
                    MethodReference method_reference = md.ImportReference(method_info);

                    CUfunction ptr_to_kernel = default(CUfunction);
                    CUmodule   module        = default(CUmodule);

                    Campy.Utils.TimePhase.Time("compile     ", () =>
                    {
                        IntPtr image = Singleton._compiler.Compile(method_reference, simpleKernel.Target);
                        module       = Singleton._compiler.SetModule(method_reference, image);
                        Singleton._compiler.StoreJits(module);
                        ptr_to_kernel = Singleton._compiler.GetCudaFunction(method_reference, module);
                    });

                    RUNTIME.BclCheckHeap();

                    BUFFERS buffer = Singleton.Buffer;
                    IntPtr  kernel_target_object = IntPtr.Zero;

                    Campy.Utils.TimePhase.Time("deep copy ", () =>
                    {
                        int count = simpleKernel.Method.GetParameters().Length;
                        var bb    = Singleton._compiler.GetBasicBlock(method_reference);
                        if (bb.HasThis)
                        {
                            count++;
                        }
                        if (!(count == 1 || count == 2))
                        {
                            throw new Exception("Expecting at least one parameter for kernel.");
                        }

                        if (bb.HasThis)
                        {
                            kernel_target_object = buffer.AddDataStructure(simpleKernel.Target);
                        }
                    });

                    Campy.Utils.TimePhase.Time("kernel cctor set up", () =>
                    {
                        // For each cctor, run on GPU.
                        // Construct dependency graph of methods.
                        List <MethodReference> order_list = COMPILER.Singleton.ConstructCctorOrder();

                        // Finally, call cctors.
                        foreach (var bb in order_list)
                        {
                            if (Campy.Utils.Options.IsOn("trace-cctors"))
                            {
                                System.Console.WriteLine("Executing cctor "
                                                         + bb.FullName);
                            }
                            var cctor = Singleton._compiler.GetCudaFunction(bb, module);

                            var res = CUresult.CUDA_SUCCESS;
                            Campy.Utils.CudaHelpers.MakeLinearTiling(1,
                                                                     out Campy.Utils.CudaHelpers.dim3 tile_size, out Campy.Utils.CudaHelpers.dim3 tiles);

                            res = Cuda.cuLaunchKernel(
                                cctor,
                                tiles.x, tiles.y, tiles.z,             // grid has one block.
                                tile_size.x, tile_size.y, tile_size.z, // n threads.
                                0,                                     // no shared memory
                                default(CUstream),
                                (IntPtr)IntPtr.Zero,
                                (IntPtr)IntPtr.Zero
                                );

                            CudaHelpers.CheckCudaError(res);
                            res = Cuda.cuCtxSynchronize(); // Make sure it's copied back to host.
                            CudaHelpers.CheckCudaError(res);
                        }
                    });

                    if (Campy.Utils.Options.IsOn("trace-cctors"))
                    {
                        System.Console.WriteLine("Done with cctors");
                    }

                    Campy.Utils.TimePhase.Time("kernel call ", () =>
                    {
                        IntPtr[] parm1 = new IntPtr[1];
                        IntPtr[] parm2 = new IntPtr[1];

                        parm1[0] = kernel_target_object;
                        parm2[0] = buffer.New(BUFFERS.SizeOf(typeof(int)));

                        IntPtr[] x1     = parm1;
                        handle1         = GCHandle.Alloc(x1, GCHandleType.Pinned);
                        IntPtr pointer1 = handle1.AddrOfPinnedObject();

                        IntPtr[] x2     = parm2;
                        handle2         = GCHandle.Alloc(x2, GCHandleType.Pinned);
                        IntPtr pointer2 = handle2.AddrOfPinnedObject();

                        IntPtr[] kp = new IntPtr[] { pointer1, pointer2 };
                        var res     = CUresult.CUDA_SUCCESS;
                        fixed(IntPtr * kernelParams = kp)
                        {
                            Campy.Utils.CudaHelpers.MakeLinearTiling(number_of_threads,
                                                                     out Campy.Utils.CudaHelpers.dim3 tile_size, out Campy.Utils.CudaHelpers.dim3 tiles);

                            //MakeLinearTiling(1, out dim3 tile_size, out dim3 tiles);

                            res = Cuda.cuLaunchKernel(
                                ptr_to_kernel,
                                tiles.x, tiles.y, tiles.z,             // grid has one block.
                                tile_size.x, tile_size.y, tile_size.z, // n threads.
                                0,                                     // no shared memory
                                default(CUstream),
                                (IntPtr)kernelParams,
                                (IntPtr)IntPtr.Zero
                                );
                        }
 public override void InjectInto(ModuleDefinition gamedef, ModuleDefinition moddef)
 {
     // Expose the "spawnItem" method in ItemManager for easier use.
     // Then, add all items spawned internally to the item manager's model list as physical entities.
     // This allows us to have better control over items and make them more interactive.
     TypeDefinition type = gamedef.GetType("SDG.Unturned.ItemManager");
     MethodDefinition spawnItemMethod = GetMethod(type, "spawnItem", 8);
     spawnItemMethod.IsPrivate = false;
     spawnItemMethod.IsPublic = true;
     FieldDefinition managerField = GetField(type, "manager");
     managerField.IsPrivate = false;
     managerField.IsPublic = true;
     FieldDefinition fieldregions = GetField(type, "regions");
     fieldregions.IsPrivate = false;
     fieldregions.IsPublic = true;
     FieldDefinition fieldinstcount = GetField(type, "instanceCount");
     fieldinstcount.IsPrivate = false;
     fieldinstcount.IsPublic = true;
     TypeDefinition plInvType = gamedef.GetType("SDG.Unturned.PlayerInventory");
     FieldDefinition plInvItems = GetField(plInvType, "items");
     plInvItems.IsPrivate = false;
     plInvItems.IsPublic = true;
     // Keep track of items by using models
     TypeDefinition itemTracker = moddef.GetType("UnturnedFrenetic.ItemModelTracker");
     // (Item, Vector3)
     MethodReference trackItemMethod = gamedef.ImportReference(GetMethod(itemTracker, "Track", 2));
     // (byte, byte, int)
     MethodReference untrackItemMethod = gamedef.ImportReference(GetMethod(itemTracker, "Untrack", 3));
     // (byte, byte, List<ItemData>)
     MethodReference resetItemsMethod = gamedef.ImportReference(GetMethod(itemTracker, "Reset", 3));
     // For getting 'point' property from ItemSpawnpoint objects
     MethodDefinition getPointProperty = GetMethod(gamedef.GetType("SDG.Unturned.ItemSpawnpoint"), "get_point", 0);
     // Track dropItem
     MethodDefinition dropItemMethod = GetMethod(type, "dropItem", 5);
     InjectInstructions(dropItemMethod.Body, 74, new Instruction[]
     {
         // Load: ItemData itemData
         Instruction.Create(OpCodes.Ldloc_3),
         // Load: Vector3 point
         Instruction.Create(OpCodes.Ldarg_1),
         // ItemModelTracker.Track(itemData, point);
         Instruction.Create(OpCodes.Call, trackItemMethod)
     });
     // Track generateItems
     MethodDefinition generateItemsMethod = GetMethod(type, "generateItems", 2);
     InjectInstructions(generateItemsMethod.Body, 137, new Instruction[]
     {
         // Load: byte x
         Instruction.Create(OpCodes.Ldarg_1),
         // Load: byte y
         Instruction.Create(OpCodes.Ldarg_2),
         // Load: List<ItemData> list
         Instruction.Create(OpCodes.Ldloc_0),
         // Call: ItemModelTracker.Reset(x, y, list);
         Instruction.Create(OpCodes.Call, resetItemsMethod)
     });
     // Track respawnItems
     MethodDefinition respawnItemsMethod = GetMethod(type, "respawnItems", 0);
     InjectInstructions(respawnItemsMethod.Body, 130, new Instruction[]
     {
         // Load: ItemData itemData
         Instruction.Create(OpCodes.Ldloc, respawnItemsMethod.Body.Variables[4]),
         // Load: ItemSpawnpoint itemSpawnpoint
         Instruction.Create(OpCodes.Ldloc_0),
         // Call: 'get_point' on  itemSpawnpoint2 -> add the Vector3 result to the stack.
         Instruction.Create(OpCodes.Callvirt, getPointProperty),
         // Call: ItemModelTracker.Track(itemData, itemSpawnpoint2.point);
         Instruction.Create(OpCodes.Call, trackItemMethod)
     });
     // Untrack askTakeItem
     MethodDefinition askTakeItemMethod = GetMethod(type, "askTakeItem", 8);
     InjectInstructions(askTakeItemMethod.Body, 95, new Instruction[]
     {
         // Load: byte x
         Instruction.Create(OpCodes.Ldarg_2),
         // Load: byte y
         Instruction.Create(OpCodes.Ldarg_3),
         // Load: ushort num
         Instruction.Create(OpCodes.Ldloc_2),
         // Call: ItemModelTracker.Untrack(x, y, num);
         Instruction.Create(OpCodes.Call, untrackItemMethod)
     });
     // Untrack despawnItems
     MethodDefinition despawnItemsMethod = GetMethod(type, "despawnItems", 0);
     InjectInstructions(despawnItemsMethod.Body, 50, new Instruction[]
     {
         // Load: ItemManager.despawnItems_X
         Instruction.Create(OpCodes.Ldsfld, GetField(type, "despawnItems_X")),
         // Load: ItemManager.despawnItems_Y
         Instruction.Create(OpCodes.Ldsfld, GetField(type, "despawnItems_Y")),
         // Load: int i
         Instruction.Create(OpCodes.Ldloc_0),
         // Call: ItemModelTracker.Untrack(ItemManager.despawnItems_X, ItemManager.despawnItems_Y, i);
         Instruction.Create(OpCodes.Call, untrackItemMethod)
     });
 }