~ruther/csharp-dll-injector

ref: a5cb4605d7b28142f2ae1ab9d8e0f7091530e7e5 csharp-dll-injector/DllUtils/Serializers/RemoteParamSerializer.cs -rw-r--r-- 6.9 KiB
a5cb4605 — František Boháček Add DllUtils 4 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using DllUtils.Attributes;
using DllUtils.Exceptions;
using DllUtils.Memory;
using DllUtils.Process;

namespace DllUtils.Serializers
{
    public class RemoteParamSerializer
    {
        public RemoteParamSerializer(ProcessHandle process)
        {
            Process = process;
        }

        public ProcessHandle Process { get; }

        public AllocatedMemory Serialize<T>(T param)
        {
            AllocatedMemory memory;

            if (param is int)
            {
                return new AllocatedMemory(Process, (IntPtr)Convert.ToInt32(param), null, sizeof(int));
            }

            if (param is Array array)
            {
                memory = SerializeArray(array);
            }
            else if (param.GetType().GetCustomAttribute<CustomFunctionParamsAttribute>() is CustomFunctionParamsAttribute attribute)
            {
                memory = SerializeCustom(param, attribute);
            }
            else
            {
                memory = SerializeUsingMarshal(param);
            }
            

            if (!memory.Alloc())
            {
                throw new MemoryAllocationException("Failed to allocate memory.");
            }

            if (!memory.Write())
            {
                throw new MemoryWriteException("Failed to write to allocated memory.");
            }

            return memory;
        }

        public AllocatedMemory SerializeArray(Array array)
        {
            byte[] bytes = SerializeArrayToBytes(array, out int size);
            return new AllocatedMemory(Process, IntPtr.Zero, bytes, size);
        }

        public AllocatedMemory SerializeCustom<T>(T param, CustomFunctionParamsAttribute customOptions)
        {
            System.Type type = param.GetType();
            IEnumerable<FieldInfo> fields = type.GetFields();
            List<ParamData> dataList = new List<ParamData>();

            foreach (FieldInfo field in fields)
            {
                ParamPositionAttribute positionAttribute = field.GetCustomAttribute<ParamPositionAttribute>();

                if (positionAttribute == null)
                {
                    continue;
                }

                ParamData currentData = new ParamData
                {
                    Position = positionAttribute.Index,
                    ParamType = positionAttribute.ParamType,
                    Value = field.GetValue(param)
                };
                int size;

                if (currentData.ParamType == ParamType.NotSpecified)
                {
                    currentData.ParamType = type.IsValueType ? ParamType.Reference : ParamType.Value;
                }

                if (currentData.Value is string stringVal)
                {
                    switch (customOptions.StringEncoding)
                    {
                        case EncodingType.ASCII:
                            currentData.Value = Encoding.ASCII.GetBytes(stringVal);
                            break;
                        case EncodingType.UTF8:
                            currentData.Value = Encoding.UTF8.GetBytes(stringVal);
                            break;
                        case EncodingType.UTF32:
                            currentData.Value = Encoding.UTF32.GetBytes(stringVal);
                            break;
                        case EncodingType.Unicode:
                            currentData.Value = Encoding.Unicode.GetBytes(stringVal);
                            break;
                    }
                }

                if (currentData.ParamType == ParamType.Reference)
                {

                    currentData.Memory = Serialize(currentData.Value);
                    currentData.Size = Marshal.SizeOf(typeof(IntPtr));
                    currentData.Data = SerializeToBytesUsingMarshal(currentData.Memory.Address, out _);
                }
                else
                {
                    if (currentData.Value is Array array)
                    {
                        currentData.Data = SerializeArrayToBytes(array, out size);
                        currentData.Size = size;
                    }
                    else
                    {
                        currentData.Data = SerializeToBytesUsingMarshal(currentData.Value, out size);
                        currentData.Size = size;
                    }
                }

                dataList.Add(currentData);
            }

            int totalSize = dataList.Sum(x => x.Size);
            int currentPosition = 0;
            byte[] bytes = new byte[totalSize];
            foreach (ParamData data in dataList.OrderBy(x => x.Position))
            {
                Array.Copy(data.Data, 0, bytes, currentPosition, data.Size);
                currentPosition += data.Size;
            }

            return new AllocatedMemory(Process, IntPtr.Zero, bytes, totalSize);
        }

        public AllocatedMemory SerializeUsingMarshal<T>(T param)
        {
            byte[] bytes = SerializeToBytesUsingMarshal(param, out int size);
            AllocatedMemory memory = new AllocatedMemory(Process, IntPtr.Zero, bytes, size);

            return memory;
        }

        protected byte[] SerializeArrayToBytes(Array array, out int size)
        {
            int elementSize;

            try
            {
                elementSize = Marshal.SizeOf(array.GetType().GetElementType());
            }
            catch (Exception exception)
            {
                throw new SerializationException("Only arrays of simple structures allowed.", exception);
            }

            size = elementSize * array.Length;
            IntPtr ptr = Marshal.AllocHGlobal(size);
            IntPtr current = ptr;

            foreach (object value in array)
            {
                Marshal.StructureToPtr(value, current, false);
                current += elementSize;
            }

            byte[] bytes = new byte[size];
            Marshal.Copy(ptr, bytes, 0, size);

            Marshal.FreeHGlobal(ptr);
            return bytes;
        }

        protected byte[] SerializeToBytesUsingMarshal<T>(T param, out int size)
        {
            size = Marshal.SizeOf(param);

            IntPtr ptr = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(param, ptr, false);

            byte[] bytes = new byte[size];
            Marshal.Copy(ptr, bytes, 0, size);

            Marshal.FreeHGlobal(ptr);
            return bytes;
        }

        private class ParamData
        {
            public int Position { get; set; }

            public ParamType ParamType { get; set; }

            public int Size { get; set; }

            public object Value { get; set; }

            public AllocatedMemory Memory { get; set; }

            public byte[] Data { get; set; }
        }
    }
}
Do not follow this link