Debian Codegraph @

external/ikvm/reflect/Writer/TextSection.cs

raw
1 /*
2 Copyright (C) 2008-2013 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.Diagnostics;
26 using System.IO;
27 using System.Collections.Generic;
28 using System.Text;
29 using IKVM.Reflection.Emit;
30 using IKVM.Reflection.Impl;
31 using IKVM.Reflection.Metadata;
32
33 namespace IKVM.Reflection.Writer
34 {
35 sealed class TextSection
36 {
37 private readonly PEWriter peWriter;
38 private readonly CliHeader cliHeader;
39 private readonly ModuleBuilder moduleBuilder;
40 private readonly uint strongNameSignatureLength;
41 private readonly uint manifestResourcesLength;
42 private readonly ExportTables exportTables;
43 private readonly List<RelocationBlock> relocations = new List<RelocationBlock>();
44
45 internal TextSection(PEWriter peWriter, CliHeader cliHeader, ModuleBuilder moduleBuilder, int strongNameSignatureLength)
46 {
47 this.peWriter = peWriter;
48 this.cliHeader = cliHeader;
49 this.moduleBuilder = moduleBuilder;
50 this.strongNameSignatureLength = (uint)strongNameSignatureLength;
51 this.manifestResourcesLength = (uint)moduleBuilder.GetManifestResourcesLength();
52 if (moduleBuilder.unmanagedExports.Count != 0)
53 {
54 this.exportTables = new ExportTables(this);
55 }
56 }
57
58 internal uint PointerToRawData
59 {
60 get { return peWriter.ToFileAlignment(peWriter.HeaderSize); }
61 }
62
63 internal uint BaseRVA
64 {
65 get { return peWriter.Headers.OptionalHeader.SectionAlignment; }
66 }
67
68 internal uint ImportAddressTableRVA
69 {
70 get { return BaseRVA; }
71 }
72
73 internal uint ImportAddressTableLength
74 {
75 get { return peWriter.Is32Bit ? 8u : 16u; }
76 }
77
78 internal uint ComDescriptorRVA
79 {
80 get { return ImportAddressTableRVA + ImportAddressTableLength; }
81 }
82
83 internal uint ComDescriptorLength
84 {
85 get { return cliHeader.Cb; }
86 }
87
88 internal uint MethodBodiesRVA
89 {
90 get { return (ComDescriptorRVA + ComDescriptorLength + 7) & ~7U; }
91 }
92
93 private uint MethodBodiesLength
94 {
95 get { return (uint)moduleBuilder.methodBodies.Length; }
96 }
97
98 private uint ResourcesRVA
99 {
100 get
101 {
102 switch (peWriter.Headers.FileHeader.Machine)
103 {
104 case IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_I386:
105 case IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_ARM:
106 return (MethodBodiesRVA + MethodBodiesLength + 3) & ~3U;
107 default:
108 return (MethodBodiesRVA + MethodBodiesLength + 15) & ~15U;
109 }
110 }
111 }
112
113 private uint ResourcesLength
114 {
115 get { return manifestResourcesLength; }
116 }
117
118 internal uint StrongNameSignatureRVA
119 {
120 get
121 {
122 return (ResourcesRVA + ResourcesLength + 3) & ~3U;
123 }
124 }
125
126 internal uint StrongNameSignatureLength
127 {
128 get
129 {
130 return strongNameSignatureLength;
131 }
132 }
133
134 private uint MetadataRVA
135 {
136 get
137 {
138 return (StrongNameSignatureRVA + StrongNameSignatureLength + 3) & ~3U;
139 }
140 }
141
142 private uint MetadataLength
143 {
144 get { return (uint)moduleBuilder.MetadataLength; }
145 }
146
147 private uint VTableFixupsRVA
148 {
149 get { return (MetadataRVA + MetadataLength + 7) & ~7U; }
150 }
151
152 private uint VTableFixupsLength
153 {
154 get { return (uint)moduleBuilder.vtablefixups.Count * 8; }
155 }
156
157 internal uint DebugDirectoryRVA
158 {
159 get { return VTableFixupsRVA + VTableFixupsLength; }
160 }
161
162 internal uint DebugDirectoryLength
163 {
164 get
165 {
166 if (DebugDirectoryContentsLength != 0)
167 {
168 return 28;
169 }
170 return 0;
171 }
172 }
173
174 private uint DebugDirectoryContentsLength
175 {
176 get
177 {
178 if (moduleBuilder.symbolWriter != null)
179 {
180 IMAGE_DEBUG_DIRECTORY idd = new IMAGE_DEBUG_DIRECTORY();
181 return (uint)SymbolSupport.GetDebugInfo(moduleBuilder.symbolWriter, ref idd).Length;
182 }
183 return 0;
184 }
185 }
186
187 internal uint ExportDirectoryRVA
188 {
189 get { return (DebugDirectoryRVA + DebugDirectoryLength + DebugDirectoryContentsLength + 15) & ~15U; }
190 }
191
192 internal uint ExportDirectoryLength
193 {
194 get { return moduleBuilder.unmanagedExports.Count == 0 ? 0U : 40U; }
195 }
196
197 private uint ExportTablesRVA
198 {
199 get { return ExportDirectoryRVA + ExportDirectoryLength; }
200 }
201
202 private uint ExportTablesLength
203 {
204 get { return exportTables == null ? 0U : exportTables.Length; }
205 }
206
207 internal uint ImportDirectoryRVA
208 {
209 // on AMD64 (and probably IA64) the import directory needs to be 16 byte aligned (on I386 4 byte alignment is sufficient)
210 get { return (ExportTablesRVA + ExportTablesLength + 15) & ~15U; }
211 }
212
213 internal uint ImportDirectoryLength
214 {
215 get { return (ImportHintNameTableRVA - ImportDirectoryRVA) + 27; }
216 }
217
218 private uint ImportHintNameTableRVA
219 {
220 get
221 {
222 return peWriter.Is32Bit
223 ? (ImportDirectoryRVA + 48 + 15) & ~15U
224 : (ImportDirectoryRVA + 52 + 15) & ~15U;
225 }
226 }
227
228 internal uint StartupStubRVA
229 {
230 get
231 {
232 if (peWriter.Headers.FileHeader.Machine == IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_IA64)
233 {
234 // note that the alignment is driven by the requirement that the two relocation fixups are in a single page
235 return (ImportDirectoryRVA + ImportDirectoryLength + 15U) & ~15U;
236 }
237 else
238 {
239 // the additional 2 bytes padding are to align the address in the jump (which is a relocation fixup)
240 return 2 + ((ImportDirectoryRVA + ImportDirectoryLength + 3U) & ~3U);
241 }
242 }
243 }
244
245 internal uint StartupStubLength
246 {
247 get
248 {
249 switch (peWriter.Headers.FileHeader.Machine)
250 {
251 case IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_I386:
252 return 6;
253 case IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_AMD64:
254 case IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_ARM:
255 return 12;
256 case IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_IA64:
257 return 48;
258 default:
259 throw new NotSupportedException();
260 }
261 }
262 }
263
264 private void WriteRVA(MetadataWriter mw, uint rva)
265 {
266 switch (peWriter.Headers.FileHeader.Machine)
267 {
268 case IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_I386:
269 case IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_ARM:
270 mw.Write(rva);
271 break;
272 default:
273 mw.Write((ulong)rva);
274 break;
275 }
276 }
277
278 internal void Write(MetadataWriter mw, uint sdataRVA, out uint guidHeapOffset)
279 {
280 // Now that we're ready to start writing, we need to do some fix ups
281 moduleBuilder.TypeRef.Fixup(moduleBuilder);
282 moduleBuilder.MethodDef.Fixup(this);
283 moduleBuilder.MethodImpl.Fixup(moduleBuilder);
284 moduleBuilder.MethodSemantics.Fixup(moduleBuilder);
285 moduleBuilder.InterfaceImpl.Fixup();
286 moduleBuilder.ResolveInterfaceImplPseudoTokens();
287 moduleBuilder.MemberRef.Fixup(moduleBuilder);
288 moduleBuilder.Constant.Fixup(moduleBuilder);
289 moduleBuilder.FieldMarshal.Fixup(moduleBuilder);
290 moduleBuilder.DeclSecurity.Fixup(moduleBuilder);
291 moduleBuilder.GenericParam.Fixup(moduleBuilder);
292 moduleBuilder.CustomAttribute.Fixup(moduleBuilder);
293 moduleBuilder.FieldLayout.Fixup(moduleBuilder);
294 moduleBuilder.FieldRVA.Fixup(moduleBuilder, (int)sdataRVA, (int)this.MethodBodiesRVA);
295 moduleBuilder.ImplMap.Fixup(moduleBuilder);
296 moduleBuilder.ExportedType.Fixup(moduleBuilder);
297 moduleBuilder.ManifestResource.Fixup(moduleBuilder);
298 moduleBuilder.MethodSpec.Fixup(moduleBuilder);
299 moduleBuilder.GenericParamConstraint.Fixup(moduleBuilder);
300
301 // Import Address Table
302 AssertRVA(mw, ImportAddressTableRVA);
303 if (ImportAddressTableLength != 0)
304 {
305 WriteRVA(mw, ImportHintNameTableRVA);
306 WriteRVA(mw, 0);
307 }
308
309 // CLI Header
310 AssertRVA(mw, ComDescriptorRVA);
311 cliHeader.MetaData.VirtualAddress = MetadataRVA;
312 cliHeader.MetaData.Size = MetadataLength;
313 if (ResourcesLength != 0)
314 {
315 cliHeader.Resources.VirtualAddress = ResourcesRVA;
316 cliHeader.Resources.Size = ResourcesLength;
317 }
318 if (StrongNameSignatureLength != 0)
319 {
320 cliHeader.StrongNameSignature.VirtualAddress = StrongNameSignatureRVA;
321 cliHeader.StrongNameSignature.Size = StrongNameSignatureLength;
322 }
323 if (VTableFixupsLength != 0)
324 {
325 cliHeader.VTableFixups.VirtualAddress = VTableFixupsRVA;
326 cliHeader.VTableFixups.Size = VTableFixupsLength;
327 }
328 cliHeader.Write(mw);
329
330 // alignment padding
331 for (int i = (int)(MethodBodiesRVA - (ComDescriptorRVA + ComDescriptorLength)); i > 0; i--)
332 {
333 mw.Write((byte)0);
334 }
335
336 // Method Bodies
337 mw.Write(moduleBuilder.methodBodies);
338
339 // alignment padding
340 for (int i = (int)(ResourcesRVA - (MethodBodiesRVA + MethodBodiesLength)); i > 0; i--)
341 {
342 mw.Write((byte)0);
343 }
344
345 // Resources
346 moduleBuilder.WriteResources(mw);
347
348 // The strong name signature live here (if it exists), but it will written later
349 // and the following alignment padding will take care of reserving the space.
350
351 // alignment padding
352 for (int i = (int)(MetadataRVA - (ResourcesRVA + ResourcesLength)); i > 0; i--)
353 {
354 mw.Write((byte)0);
355 }
356
357 // Metadata
358 AssertRVA(mw, MetadataRVA);
359 moduleBuilder.WriteMetadata(mw, out guidHeapOffset);
360
361 // alignment padding
362 for (int i = (int)(VTableFixupsRVA - (MetadataRVA + MetadataLength)); i > 0; i--)
363 {
364 mw.Write((byte)0);
365 }
366
367 // VTableFixups
368 AssertRVA(mw, VTableFixupsRVA);
369 WriteVTableFixups(mw, sdataRVA);
370
371 // Debug Directory
372 AssertRVA(mw, DebugDirectoryRVA);
373 WriteDebugDirectory(mw);
374
375 // alignment padding
376 for (int i = (int)(ExportDirectoryRVA - (DebugDirectoryRVA + DebugDirectoryLength + DebugDirectoryContentsLength)); i > 0; i--)
377 {
378 mw.Write((byte)0);
379 }
380
381 // Export Directory
382 AssertRVA(mw, ExportDirectoryRVA);
383 WriteExportDirectory(mw);
384
385 // Export Tables
386 AssertRVA(mw, ExportTablesRVA);
387 WriteExportTables(mw, sdataRVA);
388
389 // alignment padding
390 for (int i = (int)(ImportDirectoryRVA - (ExportTablesRVA + ExportTablesLength)); i > 0; i--)
391 {
392 mw.Write((byte)0);
393 }
394
395 // Import Directory
396 AssertRVA(mw, ImportDirectoryRVA);
397 if (ImportDirectoryLength != 0)
398 {
399 WriteImportDirectory(mw);
400 }
401
402 // alignment padding
403 for (int i = (int)(StartupStubRVA - (ImportDirectoryRVA + ImportDirectoryLength)); i > 0; i--)
404 {
405 mw.Write((byte)0);
406 }
407
408 // Startup Stub
409 AssertRVA(mw, StartupStubRVA);
410 if (peWriter.Headers.FileHeader.Machine == IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_AMD64)
411 {
412 /*
413 * 48 A1 00 20 40 00 00 00 00 00 mov rax,qword ptr [0000000000402000h]
414 * FF E0 jmp rax
415 */
416 mw.Write((ushort)0xA148);
417 mw.Write(peWriter.Headers.OptionalHeader.ImageBase + ImportAddressTableRVA);
418 mw.Write((ushort)0xE0FF);
419 }
420 else if (peWriter.Headers.FileHeader.Machine == IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_IA64)
421 {
422 mw.Write(new byte[] {
423 0x0B, 0x48, 0x00, 0x02, 0x18, 0x10, 0xA0, 0x40, 0x24, 0x30, 0x28, 0x00, 0x00, 0x00, 0x04, 0x00,
424 0x10, 0x08, 0x00, 0x12, 0x18, 0x10, 0x60, 0x50, 0x04, 0x80, 0x03, 0x00, 0x60, 0x00, 0x80, 0x00
425 });
426 mw.Write(peWriter.Headers.OptionalHeader.ImageBase + StartupStubRVA);
427 mw.Write(peWriter.Headers.OptionalHeader.ImageBase + BaseRVA);
428 }
429 else if (peWriter.Headers.FileHeader.Machine == IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_I386)
430 {
431 mw.Write((ushort)0x25FF);
432 mw.Write((uint)peWriter.Headers.OptionalHeader.ImageBase + ImportAddressTableRVA);
433 }
434 else if (peWriter.Headers.FileHeader.Machine == IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_ARM)
435 {
436 uint rva = (uint)peWriter.Headers.OptionalHeader.ImageBase + ImportAddressTableRVA;
437 ushort lo = (ushort)rva;
438 ushort hi = (ushort)(rva >> 16);
439 mw.Write((ushort)(0xF240 + (lo >> 12)));
440 mw.Write((ushort)(0x0C00 + ((lo << 4) & 0xF000) + (lo & 0xFF)));
441 mw.Write((ushort)(0xF2C0 + (hi >> 12)));
442 mw.Write((ushort)(0x0C00 + ((hi << 4) & 0xF000) + (hi & 0xFF)));
443 mw.Write((ushort)0xF8DC);
444 mw.Write((ushort)0xF000);
445 }
446 else
447 {
448 throw new NotSupportedException();
449 }
450 }
451
452 [Conditional("DEBUG")]
453 private void AssertRVA(MetadataWriter mw, uint rva)
454 {
455 Debug.Assert(mw.Position - PointerToRawData + BaseRVA == rva);
456 }
457
458 private void WriteVTableFixups(MetadataWriter mw, uint sdataRVA)
459 {
460 foreach (ModuleBuilder.VTableFixups fixups in moduleBuilder.vtablefixups)
461 {
462 mw.Write(fixups.initializedDataOffset + sdataRVA);
463 mw.Write(fixups.count);
464 mw.Write(fixups.type);
465 }
466 }
467
468 private void WriteDebugDirectory(MetadataWriter mw)
469 {
470 if (DebugDirectoryLength != 0)
471 {
472 IMAGE_DEBUG_DIRECTORY idd = new IMAGE_DEBUG_DIRECTORY();
473 idd.Characteristics = 0;
474 idd.TimeDateStamp = peWriter.Headers.FileHeader.TimeDateStamp;
475 byte[] buf = SymbolSupport.GetDebugInfo(moduleBuilder.symbolWriter, ref idd);
476 idd.PointerToRawData = (DebugDirectoryRVA - BaseRVA) + DebugDirectoryLength + PointerToRawData;
477 idd.AddressOfRawData = DebugDirectoryRVA + DebugDirectoryLength;
478 mw.Write(idd.Characteristics);
479 mw.Write(idd.TimeDateStamp);
480 mw.Write(idd.MajorVersion);
481 mw.Write(idd.MinorVersion);
482 mw.Write(idd.Type);
483 mw.Write(idd.SizeOfData);
484 mw.Write(idd.AddressOfRawData);
485 mw.Write(idd.PointerToRawData);
486 mw.Write(buf);
487 }
488 }
489
490 private sealed class ExportTables
491 {
492 private readonly TextSection text;
493 internal readonly uint entries;
494 internal readonly uint ordinalBase;
495 internal readonly uint nameCount;
496 internal readonly uint namesLength;
497 internal readonly uint exportAddressTableRVA;
498 internal readonly uint exportNamePointerTableRVA;
499 internal readonly uint exportOrdinalTableRVA;
500 internal readonly uint namesRVA;
501 internal readonly uint stubsRVA;
502 private readonly uint stubLength;
503
504 internal ExportTables(TextSection text)
505 {
506 this.text = text;
507 ordinalBase = GetOrdinalBase(out entries);
508 namesLength = GetExportNamesLength(out nameCount);
509 exportAddressTableRVA = text.ExportTablesRVA;
510 exportNamePointerTableRVA = exportAddressTableRVA + 4 * entries;
511 exportOrdinalTableRVA = exportNamePointerTableRVA + 4 * nameCount;
512 namesRVA = exportOrdinalTableRVA + 2 * nameCount;
513 stubsRVA = (namesRVA + namesLength + 15) & ~15U;
514 // note that we align the stubs to avoid having to deal with the relocation crossing a page boundary
515 switch (text.peWriter.Headers.FileHeader.Machine)
516 {
517 case IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_I386:
518 stubLength = 8;
519 break;
520 case IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_AMD64:
521 case IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_ARM:
522 stubLength = 16;
523 break;
524 default:
525 throw new NotSupportedException();
526 }
527 }
528
529 internal uint Length
530 {
531 get { return (stubsRVA + stubLength * (uint)text.moduleBuilder.unmanagedExports.Count) - text.ExportTablesRVA; }
532 }
533
534 private uint GetOrdinalBase(out uint entries)
535 {
536 uint min = uint.MaxValue;
537 uint max = uint.MinValue;
538 foreach (UnmanagedExport exp in text.moduleBuilder.unmanagedExports)
539 {
540 uint ordinal = (uint)exp.ordinal;
541 min = Math.Min(min, ordinal);
542 max = Math.Max(max, ordinal);
543 }
544 entries = 1 + (max - min);
545 return min;
546 }
547
548 private uint GetExportNamesLength(out uint nameCount)
549 {
550 nameCount = 0;
551 // the first name in the names list is the module name (the Export Directory contains a name of the current module)
552 uint length = (uint)text.moduleBuilder.fileName.Length + 1;
553 foreach (UnmanagedExport exp in text.moduleBuilder.unmanagedExports)
554 {
555 if (exp.name != null)
556 {
557 nameCount++;
558 length += (uint)exp.name.Length + 1;
559 }
560 }
561 return length;
562 }
563
564 internal void Write(MetadataWriter mw, uint sdataRVA)
565 {
566 // sort the exports by ordinal
567 text.moduleBuilder.unmanagedExports.Sort(CompareUnmanagedExportOrdinals);
568
569 // Now write the Export Address Table
570 text.AssertRVA(mw, exportAddressTableRVA);
571 for (int i = 0, pos = 0; i < entries; i++)
572 {
573 if (text.moduleBuilder.unmanagedExports[pos].ordinal == i + ordinalBase)
574 {
575 mw.Write(text.peWriter.Thumb + stubsRVA + (uint)pos * stubLength);
576 pos++;
577 }
578 else
579 {
580 mw.Write(0);
581 }
582 }
583
584 // sort the exports by name
585 text.moduleBuilder.unmanagedExports.Sort(CompareUnmanagedExportNames);
586
587 // Now write the Export Name Pointer Table
588 text.AssertRVA(mw, exportNamePointerTableRVA);
589 uint nameOffset = (uint)text.moduleBuilder.fileName.Length + 1;
590 foreach (UnmanagedExport exp in text.moduleBuilder.unmanagedExports)
591 {
592 if (exp.name != null)
593 {
594 mw.Write(namesRVA + nameOffset);
595 nameOffset += (uint)exp.name.Length + 1;
596 }
597 }
598
599 // Now write the Export Ordinal Table
600 text.AssertRVA(mw, exportOrdinalTableRVA);
601 foreach (UnmanagedExport exp in text.moduleBuilder.unmanagedExports)
602 {
603 if (exp.name != null)
604 {
605 mw.Write((ushort)(exp.ordinal - ordinalBase));
606 }
607 }
608
609 // Now write the actual names
610 text.AssertRVA(mw, namesRVA);
611 mw.WriteAsciiz(text.moduleBuilder.fileName);
612 foreach (UnmanagedExport exp in text.moduleBuilder.unmanagedExports)
613 {
614 if (exp.name != null)
615 {
616 mw.WriteAsciiz(exp.name);
617 }
618 }
619 text.AssertRVA(mw, namesRVA + namesLength);
620
621 // alignment padding
622 for (int i = (int)(stubsRVA - (namesRVA + namesLength)); i > 0; i--)
623 {
624 mw.Write((byte)0);
625 }
626
627 // sort the exports by ordinal
628 text.moduleBuilder.unmanagedExports.Sort(CompareUnmanagedExportOrdinals);
629
630 // Now write the stubs
631 text.AssertRVA(mw, stubsRVA);
632
633 for (int i = 0, pos = 0; i < entries; i++)
634 {
635 if (text.moduleBuilder.unmanagedExports[pos].ordinal == i + ordinalBase)
636 {
637 switch (text.peWriter.Headers.FileHeader.Machine)
638 {
639 case IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_I386:
640 mw.Write((byte)0xFF);
641 mw.Write((byte)0x25);
642 mw.Write((uint)text.peWriter.Headers.OptionalHeader.ImageBase + text.moduleBuilder.unmanagedExports[pos].rva.initializedDataOffset + sdataRVA);
643 mw.Write((short)0); // alignment
644 break;
645 case IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_AMD64:
646 mw.Write((byte)0x48);
647 mw.Write((byte)0xA1);
648 mw.Write(text.peWriter.Headers.OptionalHeader.ImageBase + text.moduleBuilder.unmanagedExports[pos].rva.initializedDataOffset + sdataRVA);
649 mw.Write((byte)0xFF);
650 mw.Write((byte)0xE0);
651 mw.Write(0); // alignment
652 break;
653 case IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_ARM:
654 mw.Write((ushort)0xF8DF);
655 mw.Write((ushort)0xC008);
656 mw.Write((ushort)0xF8DC);
657 mw.Write((ushort)0xC000);
658 mw.Write((ushort)0x4760);
659 mw.Write((ushort)0xDEFE);
660 mw.Write((uint)text.peWriter.Headers.OptionalHeader.ImageBase + text.moduleBuilder.unmanagedExports[pos].rva.initializedDataOffset + sdataRVA);
661 break;
662 default:
663 throw new NotSupportedException();
664 }
665 pos++;
666 }
667 }
668 }
669
670 private static int CompareUnmanagedExportNames(UnmanagedExport x, UnmanagedExport y)
671 {
672 if (x.name == null)
673 {
674 return y.name == null ? 0 : 1;
675 }
676 if (y.name == null)
677 {
678 return -1;
679 }
680 return String.CompareOrdinal(x.name, y.name);
681 }
682
683 private static int CompareUnmanagedExportOrdinals(UnmanagedExport x, UnmanagedExport y)
684 {
685 return x.ordinal.CompareTo(y.ordinal);
686 }
687
688 internal void GetRelocations(List<Relocation> list)
689 {
690 ushort type;
691 uint rva;
692 switch (text.peWriter.Headers.FileHeader.Machine)
693 {
694 case IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_I386:
695 type = 0x3000;
696 rva = stubsRVA + 2;
697 break;
698 case IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_AMD64:
699 type = 0xA000;
700 rva = stubsRVA + 2;
701 break;
702 case IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_ARM:
703 type = 0x3000;
704 rva = stubsRVA + 12;
705 break;
706 default:
707 throw new NotSupportedException();
708 }
709
710 // we assume that unmanagedExports is still sorted by ordinal
711 for (int i = 0, pos = 0; i < entries; i++)
712 {
713 if (text.moduleBuilder.unmanagedExports[pos].ordinal == i + ordinalBase)
714 {
715 list.Add(new Relocation(type, rva + (uint)pos * stubLength));
716 pos++;
717 }
718 }
719 }
720 }
721
722 private uint GetOrdinalBase(out uint entries)
723 {
724 uint min = uint.MaxValue;
725 uint max = uint.MinValue;
726 foreach (UnmanagedExport exp in moduleBuilder.unmanagedExports)
727 {
728 uint ordinal = (uint)exp.ordinal;
729 min = Math.Min(min, ordinal);
730 max = Math.Max(max, ordinal);
731 }
732 entries = 1 + (max - min);
733 return min;
734 }
735
736 private uint GetExportNamesLength(out uint nameCount)
737 {
738 nameCount = 0;
739 uint length = 0;
740 foreach (UnmanagedExport exp in moduleBuilder.unmanagedExports)
741 {
742 if (exp.name != null)
743 {
744 nameCount++;
745 length += (uint)exp.name.Length + 1;
746 }
747 }
748 return length;
749 }
750
751 private void WriteExportDirectory(MetadataWriter mw)
752 {
753 if (ExportDirectoryLength != 0)
754 {
755 // Flags
756 mw.Write(0);
757 // Date/Time Stamp
758 mw.Write(peWriter.Headers.FileHeader.TimeDateStamp);
759 // Major Version
760 mw.Write((short)0);
761 // Minor Version
762 mw.Write((short)0);
763 // Name RVA
764 mw.Write(exportTables.namesRVA);
765 // Ordinal Base
766 mw.Write(exportTables.ordinalBase);
767 // Address Table Entries
768 mw.Write(exportTables.entries);
769 // Number of Name Pointers
770 mw.Write(exportTables.nameCount);
771 // Export Address Table RVA
772 mw.Write(exportTables.exportAddressTableRVA);
773 // Name Pointer RVA
774 mw.Write(exportTables.exportNamePointerTableRVA);
775 // Ordinal Table RVA
776 mw.Write(exportTables.exportOrdinalTableRVA);
777 }
778 }
779
780 private void WriteExportTables(MetadataWriter mw, uint sdataRVA)
781 {
782 if (exportTables != null)
783 {
784 exportTables.Write(mw, sdataRVA);
785 }
786 }
787
788 private void WriteImportDirectory(MetadataWriter mw)
789 {
790 mw.Write(ImportDirectoryRVA + 40); // ImportLookupTable
791 mw.Write(0); // DateTimeStamp
792 mw.Write(0); // ForwarderChain
793 mw.Write(ImportHintNameTableRVA + 14); // Name
794 mw.Write(ImportAddressTableRVA);
795 mw.Write(new byte[20]);
796 // Import Lookup Table
797 mw.Write(ImportHintNameTableRVA); // Hint/Name Table RVA
798 int size = 48;
799 if (!peWriter.Is32Bit)
800 {
801 size += 4;
802 mw.Write(0);
803 }
804 mw.Write(0);
805
806 // alignment padding
807 for (int i = (int)(ImportHintNameTableRVA - (ImportDirectoryRVA + size)); i > 0; i--)
808 {
809 mw.Write((byte)0);
810 }
811
812 // Hint/Name Table
813 AssertRVA(mw, ImportHintNameTableRVA);
814 mw.Write((ushort)0); // Hint
815 if ((peWriter.Headers.FileHeader.Characteristics & IMAGE_FILE_HEADER.IMAGE_FILE_DLL) != 0)
816 {
817 mw.WriteAsciiz("_CorDllMain");
818 }
819 else
820 {
821 mw.WriteAsciiz("_CorExeMain");
822 }
823 // Name
824 mw.WriteAsciiz("mscoree.dll");
825 mw.Write((byte)0);
826 }
827
828 internal int Length
829 {
830 get { return (int)(StartupStubRVA - BaseRVA + StartupStubLength); }
831 }
832
833 struct Relocation : IComparable<Relocation>
834 {
835 internal readonly uint rva;
836 internal readonly ushort type;
837
838 internal Relocation(ushort type, uint rva)
839 {
840 this.type = type;
841 this.rva = rva;
842 }
843
844 int IComparable<Relocation>.CompareTo(Relocation other)
845 {
846 return rva.CompareTo(other.rva);
847 }
848 }
849
850 struct RelocationBlock
851 {
852 internal readonly uint PageRVA;
853 internal readonly ushort[] TypeOffset;
854
855 internal RelocationBlock(uint pageRva, ushort[] typeOffset)
856 {
857 this.PageRVA = pageRva;
858 this.TypeOffset = typeOffset;
859 }
860 }
861
862 internal void WriteRelocations(MetadataWriter mw)
863 {
864 foreach (RelocationBlock block in relocations)
865 {
866 mw.Write(block.PageRVA);
867 mw.Write(8 + block.TypeOffset.Length * 2);
868 foreach (ushort typeOffset in block.TypeOffset)
869 {
870 mw.Write(typeOffset);
871 }
872 }
873 }
874
875 internal uint PackRelocations()
876 {
877 List<Relocation> list = new List<Relocation>();
878 switch (peWriter.Headers.FileHeader.Machine)
879 {
880 case IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_I386:
881 list.Add(new Relocation(0x3000, this.StartupStubRVA + 2));
882 break;
883 case IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_AMD64:
884 list.Add(new Relocation(0xA000, this.StartupStubRVA + 2));
885 break;
886 case IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_IA64:
887 list.Add(new Relocation(0xA000, this.StartupStubRVA + 0x20));
888 list.Add(new Relocation(0xA000, this.StartupStubRVA + 0x28));
889 break;
890 case IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE_ARM:
891 list.Add(new Relocation(0x7000, this.StartupStubRVA));
892 break;
893 default:
894 throw new NotSupportedException();
895 }
896 if (exportTables != null)
897 {
898 exportTables.GetRelocations(list);
899 }
900 list.Sort();
901 uint size = 0;
902 for (int i = 0; i < list.Count; )
903 {
904 uint pageRVA = list[i].rva & ~0xFFFU;
905 int count = 1;
906 while (i + count < list.Count && (list[i + count].rva & ~0xFFFU) == pageRVA)
907 {
908 count++;
909 }
910 ushort[] typeOffset = new ushort[(count + 1) & ~1];
911 for (int j = 0; j < count; j++, i++)
912 {
913 typeOffset[j] = (ushort)(list[i].type + (list[i].rva - pageRVA));
914 }
915 relocations.Add(new RelocationBlock(pageRVA, typeOffset));
916 size += (uint)(8 + typeOffset.Length * 2);
917 }
918 return size;
919 }
920 }
921 }