Debian Codegraph @

external/ikvm/reflect/Writer/ModuleWriter.cs

raw
1 /*
2 Copyright (C) 2008-2015 Jeroen Frijters
3
4 This software is provided 'as-is', without any express or implied
5 warranty. In no event will the authors be held liable for any damages
6 arising from the use of this software.
7
8 Permission is granted to anyone to use this software for any purpose,
9 including commercial applications, and to alter it and redistribute it
10 freely, subject to the following restrictions:
11
12 1. The origin of this software must not be misrepresented; you must not
13 claim that you wrote the original software. If you use this software
14 in a product, an acknowledgment in the product documentation would be
15 appreciated but is not required.
16 2. Altered source versions must be plainly marked as such, and must not be
17 misrepresented as being the original software.
18 3. This notice may not be removed or altered from any source distribution.
19
20 Jeroen Frijters
21 [email protected]
22
23 */
24 using System;
25 using System.Collections.Generic;
26 using System.Diagnostics;
27 using System.IO;
28 using System.Security.Cryptography;
29 using IKVM.Reflection.Emit;
30 using IKVM.Reflection.Impl;
31 using IKVM.Reflection.Metadata;
32
33 namespace IKVM.Reflection.Writer
34 {
35 static class ModuleWriter
36 {
37 internal static void WriteModule(StrongNameKeyPair keyPair, byte[] publicKey, ModuleBuilder moduleBuilder,
38 PEFileKinds fileKind, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine,
39 ResourceSection resources, int entryPointToken)
40 {
41 WriteModule(keyPair, publicKey, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, resources, entryPointToken, null);
42 }
43
44 internal static void WriteModule(StrongNameKeyPair keyPair, byte[] publicKey, ModuleBuilder moduleBuilder,
45 PEFileKinds fileKind, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine,
46 ResourceSection resources, int entryPointToken, Stream stream)
47 {
48 if (stream == null)
49 {
50 string fileName = moduleBuilder.FullyQualifiedName;
51 bool mono = System.Type.GetType("Mono.Runtime") != null;
52 if (mono)
53 {
54 try
55 {
56 // Mono mmaps the file, so unlink the previous version since it may be in use
57 File.Delete(fileName);
58 }
59 catch { }
60 }
61 using (FileStream fs = new FileStream(fileName, FileMode.Create))
62 {
63 WriteModuleImpl(keyPair, publicKey, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, resources, entryPointToken, fs);
64 }
65 // if we're running on Mono, mark the module as executable by using a Mono private API extension
66 if (mono)
67 {
68 File.SetAttributes(fileName, (FileAttributes)(unchecked((int)0x80000000)));
69 }
70 }
71 else
72 {
73 WriteModuleImpl(keyPair, publicKey, moduleBuilder, fileKind, portableExecutableKind, imageFileMachine, resources, entryPointToken, stream);
74 }
75 }
76
77 private static void WriteModuleImpl(StrongNameKeyPair keyPair, byte[] publicKey, ModuleBuilder moduleBuilder,
78 PEFileKinds fileKind, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine,
79 ResourceSection resources, int entryPointToken, Stream stream)
80 {
81 moduleBuilder.ApplyUnmanagedExports(imageFileMachine);
82 moduleBuilder.FixupMethodBodyTokens();
83
84 int moduleVersionIdIndex = moduleBuilder.Guids.Add(moduleBuilder.GetModuleVersionIdOrEmpty());
85 moduleBuilder.ModuleTable.Add(0, moduleBuilder.Strings.Add(moduleBuilder.moduleName), moduleVersionIdIndex, 0, 0);
86
87 if (moduleBuilder.UserStrings.IsEmpty)
88 {
89 // for compat with Ref.Emit, if there aren't any user strings, we add one
90 moduleBuilder.UserStrings.Add(" ");
91 }
92
93 if (resources != null)
94 {
95 resources.Finish();
96 }
97
98 PEWriter writer = new PEWriter(stream);
99 writer.Headers.OptionalHeader.FileAlignment = (uint)moduleBuilder.__FileAlignment;
100 switch (imageFileMachine)
101 {
102 case ImageFileMachine.I386:
103 writer.Headers.FileHeader.Machine = IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_I386;
104 writer.Headers.FileHeader.Characteristics |= IMAGE_FILE_HEADER.IMAGE_FILE_32BIT_MACHINE;
105 writer.Headers.OptionalHeader.SizeOfStackReserve = moduleBuilder.GetStackReserve(0x100000);
106 break;
107 case ImageFileMachine.ARM:
108 writer.Headers.FileHeader.Machine = IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_ARM;
109 writer.Headers.FileHeader.Characteristics |= IMAGE_FILE_HEADER.IMAGE_FILE_32BIT_MACHINE | IMAGE_FILE_HEADER.IMAGE_FILE_LARGE_ADDRESS_AWARE;
110 writer.Headers.OptionalHeader.SizeOfStackReserve = moduleBuilder.GetStackReserve(0x100000);
111 writer.Headers.OptionalHeader.SectionAlignment = 0x1000;
112 break;
113 case ImageFileMachine.AMD64:
114 writer.Headers.FileHeader.Machine = IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_AMD64;
115 writer.Headers.FileHeader.Characteristics |= IMAGE_FILE_HEADER.IMAGE_FILE_LARGE_ADDRESS_AWARE;
116 writer.Headers.FileHeader.SizeOfOptionalHeader = 0xF0;
117 writer.Headers.OptionalHeader.Magic = IMAGE_OPTIONAL_HEADER.IMAGE_NT_OPTIONAL_HDR64_MAGIC;
118 writer.Headers.OptionalHeader.SizeOfStackReserve = moduleBuilder.GetStackReserve(0x400000);
119 writer.Headers.OptionalHeader.SizeOfStackCommit = 0x4000;
120 writer.Headers.OptionalHeader.SizeOfHeapCommit = 0x2000;
121 break;
122 case ImageFileMachine.IA64:
123 writer.Headers.FileHeader.Machine = IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_IA64;
124 writer.Headers.FileHeader.Characteristics |= IMAGE_FILE_HEADER.IMAGE_FILE_LARGE_ADDRESS_AWARE;
125 writer.Headers.FileHeader.SizeOfOptionalHeader = 0xF0;
126 writer.Headers.OptionalHeader.Magic = IMAGE_OPTIONAL_HEADER.IMAGE_NT_OPTIONAL_HDR64_MAGIC;
127 writer.Headers.OptionalHeader.SizeOfStackReserve = moduleBuilder.GetStackReserve(0x400000);
128 writer.Headers.OptionalHeader.SizeOfStackCommit = 0x4000;
129 writer.Headers.OptionalHeader.SizeOfHeapCommit = 0x2000;
130 break;
131 default:
132 throw new ArgumentOutOfRangeException("imageFileMachine");
133 }
134 if (fileKind == PEFileKinds.Dll)
135 {
136 writer.Headers.FileHeader.Characteristics |= IMAGE_FILE_HEADER.IMAGE_FILE_DLL;
137 }
138
139 switch (fileKind)
140 {
141 case PEFileKinds.WindowApplication:
142 writer.Headers.OptionalHeader.Subsystem = IMAGE_OPTIONAL_HEADER.IMAGE_SUBSYSTEM_WINDOWS_GUI;
143 break;
144 default:
145 writer.Headers.OptionalHeader.Subsystem = IMAGE_OPTIONAL_HEADER.IMAGE_SUBSYSTEM_WINDOWS_CUI;
146 break;
147 }
148 writer.Headers.OptionalHeader.DllCharacteristics = (ushort)moduleBuilder.__DllCharacteristics;
149
150 CliHeader cliHeader = new CliHeader();
151 cliHeader.Cb = 0x48;
152 cliHeader.MajorRuntimeVersion = 2;
153 cliHeader.MinorRuntimeVersion = moduleBuilder.MDStreamVersion < 0x20000 ? (ushort)0 : (ushort)5;
154 if ((portableExecutableKind & PortableExecutableKinds.ILOnly) != 0)
155 {
156 cliHeader.Flags |= CliHeader.COMIMAGE_FLAGS_ILONLY;
157 }
158 if ((portableExecutableKind & PortableExecutableKinds.Required32Bit) != 0)
159 {
160 cliHeader.Flags |= CliHeader.COMIMAGE_FLAGS_32BITREQUIRED;
161 }
162 if ((portableExecutableKind & PortableExecutableKinds.Preferred32Bit) != 0)
163 {
164 cliHeader.Flags |= CliHeader.COMIMAGE_FLAGS_32BITREQUIRED | CliHeader.COMIMAGE_FLAGS_32BITPREFERRED;
165 }
166 if (keyPair != null)
167 {
168 cliHeader.Flags |= CliHeader.COMIMAGE_FLAGS_STRONGNAMESIGNED;
169 }
170 if (ModuleBuilder.IsPseudoToken(entryPointToken))
171 {
172 entryPointToken = moduleBuilder.ResolvePseudoToken(entryPointToken);
173 }
174 cliHeader.EntryPointToken = (uint)entryPointToken;
175
176 moduleBuilder.Strings.Freeze();
177 moduleBuilder.UserStrings.Freeze();
178 moduleBuilder.Guids.Freeze();
179 moduleBuilder.Blobs.Freeze();
180 MetadataWriter mw = new MetadataWriter(moduleBuilder, stream);
181 moduleBuilder.Tables.Freeze(mw);
182 TextSection code = new TextSection(writer, cliHeader, moduleBuilder, ComputeStrongNameSignatureLength(publicKey));
183
184 // Export Directory
185 if (code.ExportDirectoryLength != 0)
186 {
187 writer.Headers.OptionalHeader.DataDirectory[0].VirtualAddress = code.ExportDirectoryRVA;
188 writer.Headers.OptionalHeader.DataDirectory[0].Size = code.ExportDirectoryLength;
189 }
190
191 // Import Directory
192 if (code.ImportDirectoryLength != 0)
193 {
194 writer.Headers.OptionalHeader.DataDirectory[1].VirtualAddress = code.ImportDirectoryRVA;
195 writer.Headers.OptionalHeader.DataDirectory[1].Size = code.ImportDirectoryLength;
196 }
197
198 // Import Address Table Directory
199 if (code.ImportAddressTableLength != 0)
200 {
201 writer.Headers.OptionalHeader.DataDirectory[12].VirtualAddress = code.ImportAddressTableRVA;
202 writer.Headers.OptionalHeader.DataDirectory[12].Size = code.ImportAddressTableLength;
203 }
204
205 // COM Descriptor Directory
206 writer.Headers.OptionalHeader.DataDirectory[14].VirtualAddress = code.ComDescriptorRVA;
207 writer.Headers.OptionalHeader.DataDirectory[14].Size = code.ComDescriptorLength;
208
209 // Debug Directory
210 if (code.DebugDirectoryLength != 0)
211 {
212 writer.Headers.OptionalHeader.DataDirectory[6].VirtualAddress = code.DebugDirectoryRVA;
213 writer.Headers.OptionalHeader.DataDirectory[6].Size = code.DebugDirectoryLength;
214 }
215
216 // Set the PE File timestamp
217 writer.Headers.FileHeader.TimeDateStamp = moduleBuilder.GetTimeDateStamp();
218
219 // we need to start by computing the number of sections, because code.PointerToRawData depends on that
220 writer.Headers.FileHeader.NumberOfSections = 2;
221
222 if (moduleBuilder.initializedData.Length != 0)
223 {
224 // .sdata
225 writer.Headers.FileHeader.NumberOfSections++;
226 }
227
228 if (resources != null)
229 {
230 // .rsrc
231 writer.Headers.FileHeader.NumberOfSections++;
232 }
233
234 SectionHeader text = new SectionHeader();
235 text.Name = ".text";
236 text.VirtualAddress = code.BaseRVA;
237 text.VirtualSize = (uint)code.Length;
238 text.PointerToRawData = code.PointerToRawData;
239 text.SizeOfRawData = writer.ToFileAlignment((uint)code.Length);
240 text.Characteristics = SectionHeader.IMAGE_SCN_CNT_CODE | SectionHeader.IMAGE_SCN_MEM_EXECUTE | SectionHeader.IMAGE_SCN_MEM_READ;
241
242 SectionHeader sdata = new SectionHeader();
243 sdata.Name = ".sdata";
244 sdata.VirtualAddress = text.VirtualAddress + writer.ToSectionAlignment(text.VirtualSize);
245 sdata.VirtualSize = (uint)moduleBuilder.initializedData.Length;
246 sdata.PointerToRawData = text.PointerToRawData + text.SizeOfRawData;
247 sdata.SizeOfRawData = writer.ToFileAlignment((uint)moduleBuilder.initializedData.Length);
248 sdata.Characteristics = SectionHeader.IMAGE_SCN_CNT_INITIALIZED_DATA | SectionHeader.IMAGE_SCN_MEM_READ | SectionHeader.IMAGE_SCN_MEM_WRITE;
249
250 SectionHeader rsrc = new SectionHeader();
251 rsrc.Name = ".rsrc";
252 rsrc.VirtualAddress = sdata.VirtualAddress + writer.ToSectionAlignment(sdata.VirtualSize);
253 rsrc.PointerToRawData = sdata.PointerToRawData + sdata.SizeOfRawData;
254 rsrc.VirtualSize = resources == null ? 0 : (uint)resources.Length;
255 rsrc.SizeOfRawData = writer.ToFileAlignment(rsrc.VirtualSize);
256 rsrc.Characteristics = SectionHeader.IMAGE_SCN_MEM_READ | SectionHeader.IMAGE_SCN_CNT_INITIALIZED_DATA;
257
258 if (rsrc.SizeOfRawData != 0)
259 {
260 // Resource Directory
261 writer.Headers.OptionalHeader.DataDirectory[2].VirtualAddress = rsrc.VirtualAddress;
262 writer.Headers.OptionalHeader.DataDirectory[2].Size = rsrc.VirtualSize;
263 }
264
265 SectionHeader reloc = new SectionHeader();
266 reloc.Name = ".reloc";
267 reloc.VirtualAddress = rsrc.VirtualAddress + writer.ToSectionAlignment(rsrc.VirtualSize);
268 reloc.VirtualSize = code.PackRelocations();
269 reloc.PointerToRawData = rsrc.PointerToRawData + rsrc.SizeOfRawData;
270 reloc.SizeOfRawData = writer.ToFileAlignment(reloc.VirtualSize);
271 reloc.Characteristics = SectionHeader.IMAGE_SCN_MEM_READ | SectionHeader.IMAGE_SCN_CNT_INITIALIZED_DATA | SectionHeader.IMAGE_SCN_MEM_DISCARDABLE;
272
273 if (reloc.SizeOfRawData != 0)
274 {
275 // Base Relocation Directory
276 writer.Headers.OptionalHeader.DataDirectory[5].VirtualAddress = reloc.VirtualAddress;
277 writer.Headers.OptionalHeader.DataDirectory[5].Size = reloc.VirtualSize;
278 }
279
280 writer.Headers.OptionalHeader.SizeOfCode = text.SizeOfRawData;
281 writer.Headers.OptionalHeader.SizeOfInitializedData = sdata.SizeOfRawData + rsrc.SizeOfRawData + reloc.SizeOfRawData;
282 writer.Headers.OptionalHeader.SizeOfUninitializedData = 0;
283 writer.Headers.OptionalHeader.SizeOfImage = reloc.VirtualAddress + writer.ToSectionAlignment(reloc.VirtualSize);
284 writer.Headers.OptionalHeader.SizeOfHeaders = text.PointerToRawData;
285 writer.Headers.OptionalHeader.BaseOfCode = code.BaseRVA;
286 writer.Headers.OptionalHeader.BaseOfData = sdata.VirtualAddress;
287 writer.Headers.OptionalHeader.ImageBase = (ulong)moduleBuilder.__ImageBase;
288
289 if (imageFileMachine == ImageFileMachine.IA64)
290 {
291 // apparently for IA64 AddressOfEntryPoint points to the address of the entry point
292 // (i.e. there is an additional layer of indirection), so we add the offset to the pointer
293 writer.Headers.OptionalHeader.AddressOfEntryPoint = code.StartupStubRVA + 0x20;
294 }
295 else
296 {
297 writer.Headers.OptionalHeader.AddressOfEntryPoint = code.StartupStubRVA + writer.Thumb;
298 }
299
300 writer.WritePEHeaders();
301 writer.WriteSectionHeader(text);
302 if (sdata.SizeOfRawData != 0)
303 {
304 writer.WriteSectionHeader(sdata);
305 }
306 if (rsrc.SizeOfRawData != 0)
307 {
308 writer.WriteSectionHeader(rsrc);
309 }
310 if (reloc.SizeOfRawData != 0)
311 {
312 writer.WriteSectionHeader(reloc);
313 }
314
315 stream.Seek(text.PointerToRawData, SeekOrigin.Begin);
316 uint guidHeapOffset;
317 code.Write(mw, sdata.VirtualAddress, out guidHeapOffset);
318
319 if (sdata.SizeOfRawData != 0)
320 {
321 stream.Seek(sdata.PointerToRawData, SeekOrigin.Begin);
322 mw.Write(moduleBuilder.initializedData);
323 }
324
325 if (rsrc.SizeOfRawData != 0)
326 {
327 stream.Seek(rsrc.PointerToRawData, SeekOrigin.Begin);
328 resources.Write(mw, rsrc.VirtualAddress);
329 }
330
331 if (reloc.SizeOfRawData != 0)
332 {
333 stream.Seek(reloc.PointerToRawData, SeekOrigin.Begin);
334 code.WriteRelocations(mw);
335 }
336
337 // file alignment
338 stream.SetLength(reloc.PointerToRawData + reloc.SizeOfRawData);
339
340 // if we don't have a guid, generate one based on the contents of the assembly
341 if (moduleBuilder.universe.Deterministic && moduleBuilder.GetModuleVersionIdOrEmpty() == Guid.Empty)
342 {
343 Guid guid = GenerateModuleVersionId(stream);
344 stream.Position = guidHeapOffset + (moduleVersionIdIndex - 1) * 16;
345 stream.Write(guid.ToByteArray(), 0, 16);
346 moduleBuilder.__SetModuleVersionId(guid);
347 }
348
349 // do the strong naming
350 if (keyPair != null)
351 {
352 StrongName(stream, keyPair, writer.HeaderSize, text.PointerToRawData, code.StrongNameSignatureRVA - text.VirtualAddress + text.PointerToRawData, code.StrongNameSignatureLength);
353 }
354
355 #if !NO_SYMBOL_WRITER
356 if (moduleBuilder.symbolWriter != null)
357 {
358 moduleBuilder.WriteSymbolTokenMap();
359 moduleBuilder.symbolWriter.Close();
360 }
361 #endif
362 }
363
364 private static int ComputeStrongNameSignatureLength(byte[] publicKey)
365 {
366 if (publicKey == null)
367 {
368 return 0;
369 }
370 else if (publicKey.Length == 16)
371 {
372 // it must be the ECMA pseudo public key, we don't know the key size of the real key, but currently both Mono and Microsoft use a 1024 bit key size
373 return 128;
374 }
375 else
376 {
377 // for the supported strong naming algorithms, the signature size is the same as the key size
378 // (we have to subtract 32 for the header)
379 return publicKey.Length - 32;
380 }
381 }
382
383 private static void StrongName(Stream stream, StrongNameKeyPair keyPair, uint headerLength, uint textSectionFileOffset, uint strongNameSignatureFileOffset, uint strongNameSignatureLength)
384 {
385 using (var hash = SHA1.Create())
386 {
387 using (CryptoStream cs = new CryptoStream(Stream.Null, hash, CryptoStreamMode.Write))
388 {
389 stream.Seek(0, SeekOrigin.Begin);
390 byte[] buf = new byte[8192];
391 HashChunk(stream, cs, buf, (int)headerLength);
392 stream.Seek(textSectionFileOffset, SeekOrigin.Begin);
393 HashChunk(stream, cs, buf, (int)(strongNameSignatureFileOffset - textSectionFileOffset));
394 stream.Seek(strongNameSignatureLength, SeekOrigin.Current);
395 HashChunk(stream, cs, buf, (int)(stream.Length - (strongNameSignatureFileOffset + strongNameSignatureLength)));
396 }
397 using (RSA rsa = keyPair.CreateRSA())
398 {
399 RSAPKCS1SignatureFormatter sign = new RSAPKCS1SignatureFormatter(rsa);
400 byte[] signature = sign.CreateSignature(hash);
401 Array.Reverse(signature);
402 if (signature.Length != strongNameSignatureLength)
403 {
404 throw new InvalidOperationException("Signature length mismatch");
405 }
406 stream.Seek(strongNameSignatureFileOffset, SeekOrigin.Begin);
407 stream.Write(signature, 0, signature.Length);
408 }
409
410 // compute the PE checksum
411 stream.Seek(0, SeekOrigin.Begin);
412 int count = (int)stream.Length / 4;
413 BinaryReader br = new BinaryReader(stream);
414 long sum = 0;
415 for (int i = 0; i < count; i++)
416 {
417 sum += br.ReadUInt32();
418 int carry = (int)(sum >> 32);
419 sum &= 0xFFFFFFFFU;
420 sum += carry;
421 }
422 while ((sum >> 16) != 0)
423 {
424 sum = (sum & 0xFFFF) + (sum >> 16);
425 }
426 sum += stream.Length;
427
428 // write the PE checksum, note that it is always at offset 0xD8 in the file
429 ByteBuffer bb = new ByteBuffer(4);
430 bb.Write((int)sum);
431 stream.Seek(0xD8, SeekOrigin.Begin);
432 bb.WriteTo(stream);
433 }
434 }
435
436 internal static void HashChunk(Stream stream, CryptoStream cs, byte[] buf, int length)
437 {
438 while (length > 0)
439 {
440 int read = stream.Read(buf, 0, Math.Min(buf.Length, length));
441 cs.Write(buf, 0, read);
442 length -= read;
443 }
444 }
445
446 private static Guid GenerateModuleVersionId(Stream stream)
447 {
448 using (var hash = SHA1.Create())
449 {
450 using (CryptoStream cs = new CryptoStream(Stream.Null, hash, CryptoStreamMode.Write))
451 {
452 stream.Seek(0, SeekOrigin.Begin);
453 byte[] buf = new byte[8192];
454 HashChunk(stream, cs, buf, (int)stream.Length);
455 }
456 byte[] bytes = new byte[16];
457 Buffer.BlockCopy(hash.Hash, 0, bytes, 0, bytes.Length);
458 // set GUID type to "version 4" (random)
459 bytes[7] &= 0x0F;
460 bytes[7] |= 0x40;
461 bytes[8] &= 0x3F;
462 bytes[8] |= 0x80;
463 return new Guid(bytes);
464 }
465 }
466 }
467 }