This repository has been archived by the owner on Apr 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
657 lines (542 loc) · 27.7 KB
/
Program.cs
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
//-----------------------------------------------------------------------
// <copyright company="CoApp Project">
// Original Copyright (c) 2009 Microsoft Corporation. All rights reserved.
// Changes Copyright (c) 2010 Garrett Serack. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
// -----------------------------------------------------------------------
// Original Code:
// (c) 2009 Microsoft Corporation -- All rights reserved
// This code is licensed under the MS-PL
// http://www.opensource.org/licenses/ms-pl.html
// Courtesy of the Open Source Techology Center: http://port25.technet.com
// -----------------------------------------------------------------------
namespace CoApp.DllExport {
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using Toolkit.Exceptions;
using Toolkit.Extensions;
using Toolkit.Utility;
public class DllExportUtility {
private static string help =
@"
DllExport for .NET 4.0
----------------------
DllExport will create a DLL that exposes standard C style function calls
which are transparently thunked to static methods in a .NET assembly.
To export a static method in a .NET class, mark each method with an
attribute called DllExportAttribute (see help for an example attribute class)
Usage:
DllExport [options] Assembly.dll -- This creates the native thunks in an
assembly called $TargetAssembly.dll
This is good for development--it
preserves the original assembly and
allows for easy debugging.
Options:
--merge -- this will generate the thunking
functions and merge them into the
target assembly.
This is good for when you want to
produce a release build.
** Warning **
This overwrites the target assembly.
--keep-temp-files -- leaves the working files in the
current directory.
--rescan-tools -- causes the tool to search for its
dependent tools (ilasm and ildasm)
instead of using the cached values.
--nologo -- suppresses informational messages.
--output-filename=<file> -- creates the native dll as <file>
--create-lib -- creates a lib file
--platform=<arch> -- outputs the native DLL as arch
(x64, x86)
--create-header=<file> -- creates a C header file for the library
More Help:
DllExport --help -- Displays this help.
DllExport --sampleClass -- Displays the DllExportAttribute
source code that you should include
in your assembly.
DllExport --sampleUsage -- Displays some examples of using the
DllExport attribute.";
// internal static List<ExportableMember> members = new List<ExportableMember>();
private static bool keepTempFiles;
private static bool quiet;
private static bool debug;
private static string finalOuputFilename;
private static string headerFilename;
private static bool createLib;
private static string platform = "x86";
private static readonly List<string> exports = new List<string> {"EXPORTS"};
private static readonly List<string> functions = new List<string> {
@"#pragma once
//-----------------------------------------------------------------------
// This file has been autogenerated by the CoApp DllExport utility
// Warning: Changes to this file will not be persisted if regenerated
//-----------------------------------------------------------------------
#ifdef __cplusplus
#define __EXTERN_C extern ""C""
#else
#define __EXTERN_C
#endif
"
};
private static readonly Dictionary<CallingConvention, Type> ModOpt = new Dictionary<CallingConvention, Type> {
{CallingConvention.Cdecl, typeof (CallConvCdecl)},
{CallingConvention.FastCall, typeof (CallConvFastcall)},
{CallingConvention.Winapi, typeof (CallConvStdcall)},
{CallingConvention.StdCall, typeof (CallConvStdcall)},
{CallingConvention.ThisCall, typeof (CallConvThiscall)}
};
private static readonly Dictionary<CallingConvention, string> CCallingConvention = new Dictionary<CallingConvention, string> {
{CallingConvention.Cdecl, "__cdecl"},
{CallingConvention.FastCall, "__fastcall"},
{CallingConvention.Winapi, "__stdcall"},
{CallingConvention.StdCall, "__stdcall"},
{CallingConvention.ThisCall, "__thiscall"}
};
private readonly Dictionary<string, string> enumTypeDefs = new Dictionary<string, string>();
private static void Delete(string filename) {
if (keepTempFiles) {
if (!quiet) {
Console.WriteLine(" Warning: leaving temporary file [{0}]", filename);
}
}
else {
File.Delete(filename);
}
}
private static void Main(string[] args) {
new DllExportUtility().main(args);
}
private string CType(Type t, UnmanagedType? customType = null) {
switch (t.Name) {
case "Byte":
case "byte":
return "unsigned __int8";
case "SByte":
case "sbyte":
return "__int8";
case "int":
case "Int32":
return "__int32";
case "uint":
case "UInt32":
return "unsigned __int32";
case "Int16":
case "short":
return "__int16";
case "UInt16":
case "ushort":
return "unsigned __int16";
case "Int64":
case "long":
return "__int64";
case "UInt64":
case "ulong":
return "unsigned __int64";
case "Single":
case "float":
return "float";
case "Double":
case "double":
return "double";
case "Char":
case "char":
return "wchar_t";
case "bool":
case "Boolean":
return "bool";
case "string":
case "String":
if (customType.HasValue && customType.Value == UnmanagedType.LPWStr) {
return "const wchar_t*";
}
return "const char_t*";
case "IntPtr":
return "void*";
}
if (t.IsEnum) {
if (enumTypeDefs.ContainsKey(t.Name)) {
return t.Name;
}
var enumType = CType(t.GetEnumUnderlyingType());
var enumValues = t.GetEnumValues();
var first = true;
var evitems = string.Empty;
foreach (var ev in enumValues) {
evitems += "{2}\r\n {0} = {1}".format(t.GetEnumName(ev), (int) ev, first ? "" : ",");
first = false;
}
var tyepdefenum = "typedef enum {{ {2}\r\n}} {0};\r\n".format(t.Name, enumType, evitems); /* : {1} */
enumTypeDefs.Add(t.Name, tyepdefenum);
return t.Name;
}
return "/* UNKNOWN : {0} */".format(t.Name);
}
private string GenerateShimAssembly(string originalAssemblyPath) {
Assembly assembly;
try {
assembly = Assembly.Load(File.ReadAllBytes(originalAssemblyPath));
}
catch {
throw new ConsoleException(
"Error: unable to load the specified original assembly \r\n [{0}].\r\n\r\nMost likely, it has already been modified--and can't be modified again.",
originalAssemblyPath);
}
IEnumerable<ExportableMember> members = GetExportableMembers(assembly);
if (members.Count() == 0) {
throw new ConsoleException("No members found with DllExport attributes in the target assembly \r\n [{0}]",
originalAssemblyPath);
}
var assemblyName = new AssemblyName("$" + assembly.GetName());
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, assemblyName.Name + ".dll");
int index = 0;
var modopts = new Type[1];
foreach (ExportableMember exportableMember in members) {
var methodInfo = exportableMember.member as MethodInfo;
if (methodInfo != null) {
ParameterInfo[] pinfo = methodInfo.GetParameters();
var parameterTypes = new Type[pinfo.Length];
var requiredCustomModifiers = new Type[pinfo.Length][];
var optionalCustomModifiers = new Type[pinfo.Length][];
var customAttributes = new object[pinfo.Length][];
for (int i = 0; i < pinfo.Length; i++) {
parameterTypes[i] = pinfo[i].ParameterType;
requiredCustomModifiers[i] = pinfo[i].GetRequiredCustomModifiers();
optionalCustomModifiers[i] = pinfo[i].GetOptionalCustomModifiers();
customAttributes[i] = pinfo[i].GetCustomAttributes(false);
}
modopts[0] = ModOpt[exportableMember.callingConvention];
string decl =
@" __EXTERN_C __declspec( dllimport ) {1} {0} {2}(".format(CCallingConvention[exportableMember.callingConvention],
CType(methodInfo.ReturnType), exportableMember.exportedName);
int pc = 0;
foreach (ParameterInfo parameterInfo in pinfo) {
IList<CustomAttributeData> customAttributeData = parameterInfo.GetCustomAttributesData();
UnmanagedType? customType = null;
foreach (CustomAttributeTypedArgument ctorarg in
customAttributeData.Where(cattr => cattr.Constructor.DeclaringType.Name == "MarshalAsAttribute").SelectMany(
cattr => cattr.ConstructorArguments.Where(ctorarg => ctorarg.ArgumentType.Name == "UnmanagedType"))) {
customType = (UnmanagedType) ctorarg.Value;
}
decl += "{2}{0} {1}".format(CType(parameterInfo.ParameterType, customType), parameterInfo.Name,
(pc == 0) ? "" : ", ");
pc++;
}
decl += ");\r\n";
functions.Add(decl);
// stdcall functions need to have the @size after the name.
if (platform == "x86" && exportableMember.callingConvention == CallingConvention.StdCall) {
exportableMember.exportedName = exportableMember.exportedName + "@" + (pc*4);
}
exports.Add(exportableMember.exportedName);
MethodBuilder methodBuilder = moduleBuilder.DefineGlobalMethod(methodInfo.Name,
MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, methodInfo.ReturnType, null, modopts,
parameterTypes, requiredCustomModifiers, optionalCustomModifiers);
ILGenerator ilGenerator = methodBuilder.GetILGenerator();
// this is to pull the ol' swicheroo later.
ilGenerator.Emit(OpCodes.Ldstr, string.Format(".export [{0}] as {1}", index++, exportableMember.exportedName));
int n = 0;
foreach (ParameterInfo parameterInfo in pinfo) {
switch (n) {
case 0:
ilGenerator.Emit(OpCodes.Ldarg_0);
break;
case 1:
ilGenerator.Emit(OpCodes.Ldarg_1);
break;
case 2:
ilGenerator.Emit(OpCodes.Ldarg_2);
break;
case 3:
ilGenerator.Emit(OpCodes.Ldarg_3);
break;
default:
ilGenerator.Emit(OpCodes.Ldarg_S, (byte) n);
break;
}
n++;
ParameterBuilder pbuilder = methodBuilder.DefineParameter(n, parameterInfo.Attributes, parameterInfo.Name);
//1-based... *sigh*...
// Copy over custom attributes (important for marshalling)
IList<CustomAttributeData> customAttributeData = parameterInfo.GetCustomAttributesData();
foreach (CustomAttributeData attr in customAttributeData) {
var cargs = new object[attr.ConstructorArguments.Count];
for (int j = 0; j < attr.ConstructorArguments.Count; j++) {
cargs[j] = attr.ConstructorArguments[j].Value;
}
// test?
var pi = new List<PropertyInfo>();
var fi = new List<FieldInfo>();
var pid = new List<object>();
var fid = new List<object>();
foreach (CustomAttributeNamedArgument ni in attr.NamedArguments) {
if (ni.MemberInfo is PropertyInfo) {
pi.Add(ni.MemberInfo as PropertyInfo);
pid.Add(ni.TypedValue.Value);
}
if (ni.MemberInfo is FieldInfo) {
fi.Add(ni.MemberInfo as FieldInfo);
fid.Add(ni.TypedValue.Value);
}
}
var cb = new CustomAttributeBuilder(attr.Constructor, cargs, pi.ToArray(), pid.ToArray(), fi.ToArray(),
fid.ToArray());
pbuilder.SetCustomAttribute(cb);
}
}
ilGenerator.EmitCall(OpCodes.Call, methodInfo, null);
ilGenerator.Emit(OpCodes.Ret);
}
}
moduleBuilder.CreateGlobalFunctions();
string outputFilename = assemblyName.Name + ".dll";
if (File.Exists(outputFilename)) {
File.Delete(outputFilename);
}
assemblyBuilder.Save(outputFilename);
return outputFilename;
}
private IEnumerable<ExportableMember> GetExportableMembers(Assembly assembly) {
CallingConvention callingConvention;
var exportedName = string.Empty;
foreach (
MemberInfo mi in assembly.GetTypes().Aggregate(Enumerable.Empty<MemberInfo>(), (current, type) => current.Union(type.GetMethods(BindingFlags.Public | BindingFlags.Static)))) {
foreach ( object attrib in from attrib in mi.GetCustomAttributes(false) where attrib.GetType().Name.Equals("DllExportAttribute") select attrib) {
try {
exportedName = attrib.GetType().GetProperty("ExportedName").GetValue(attrib, null).ToString();
callingConvention = (CallingConvention) attrib.GetType().GetProperty("CallingConvention").GetValue(attrib, null);
}
catch (Exception) {
Console.Error.WriteLine( "Warning: Found DllExport on Member {0}, but unable to get ExportedName or CallingConvention property.");
continue;
}
yield return new ExportableMember {
member = mi,
exportedName = exportedName,
callingConvention = callingConvention
};
}
}
}
private int main(string[] args) {
bool mergeAssemblies = false;
Dictionary<string, IEnumerable<string>> options = args.Switches();
IEnumerable<string> parameters = args.Parameters();
foreach (string arg in options.Keys) {
IEnumerable<string> argumentParameters = options[arg];
switch (arg) {
case "nologo":
this.Assembly().SetLogo("");
quiet = true;
break;
case "merge":
mergeAssemblies = true;
break;
case "keep-temp-files":
keepTempFiles = true;
break;
case "rescan-tools":
ProgramFinder.IgnoreCache = true;
break;
case "debug":
debug = true;
break;
case "sampleusage":
SampleUsage();
return 0;
case "sampleclass":
SampleClass();
return 0;
case "output-filename":
finalOuputFilename = argumentParameters.FirstOrDefault();
break;
case "create-header":
headerFilename = argumentParameters.FirstOrDefault();
break;
case "platform":
platform = (argumentParameters.FirstOrDefault() ?? "x86").Equals("x64", StringComparison.CurrentCultureIgnoreCase)
? "x64"
: "x86";
break;
case "create-lib":
createLib = true;
break;
case "help":
Help();
return 0;
default:
Logo();
return Fail("Error: unrecognized switch:{0}", arg);
}
}
if (parameters.Count() != 1) {
Help();
return 0;
}
if (!quiet) {
Logo();
}
var ILDasm = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("ildasm.exe", "4.0.30319.1"));
var ILAsm = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("ilasm.exe", "4.0.30319.1"));
var Lib = new ProcessUtility(ProgramFinder.ProgramFilesAndDotNet.ScanForFile("lib.exe"));
string originalAssemblyPath = parameters.First().GetFullPath();
if (!File.Exists(originalAssemblyPath)) {
return Fail("Error: the specified original assembly \r\n [{0}]\r\ndoes not exist.", originalAssemblyPath);
}
string shimAssemblyPath = GenerateShimAssembly(originalAssemblyPath);
finalOuputFilename = string.IsNullOrEmpty(finalOuputFilename)
? (mergeAssemblies ? originalAssemblyPath : shimAssemblyPath)
: finalOuputFilename;
string temporaryIlFilename = shimAssemblyPath + ".il";
int rc = ILDasm.Exec(@"/text /nobar /typelist ""{0}""", shimAssemblyPath);
if (0 != rc) {
return Fail("Error: unable to disassemble the temporary assembly\r\n [{0}]\r\nMore Information:\r\n{1}", shimAssemblyPath,
ILDasm.StandardOut);
}
Delete(shimAssemblyPath); // eliminate it regardless of result.
string ilSource = Regex.Replace(ILDasm.StandardOut, @"IL_0000:.*ldstr.*\""(?<x>.*)\""", "${x}");
if (mergeAssemblies) {
int start = ilSource.IndexOf("\r\n.method");
int end = ilSource.LastIndexOf("// end of global method");
ilSource = ilSource.Substring(start, end - start);
// arg! needed this to make sure the resources came out. grrr
rc = ILDasm.Exec(@"/nobar /typelist ""{0}"" /out=""{1}""", originalAssemblyPath, temporaryIlFilename);
rc = ILDasm.Exec(@"/nobar /text /typelist ""{0}""", originalAssemblyPath);
if (0 != rc) {
return Fail("Error: unable to disassemble the target assembly\r\n [{0}]\r\nMore Information:\r\n{1}", shimAssemblyPath,
ILDasm.StandardOut);
}
string ilTargetSource = ILDasm.StandardOut;
start = Math.Min(ilTargetSource.IndexOf(".method"), ilTargetSource.IndexOf(".class"));
ilSource = ilTargetSource.Substring(0, start) + ilSource + ilTargetSource.Substring(start);
}
File.WriteAllText(temporaryIlFilename, ilSource);
rc = ILAsm.Exec(@"{3} /dll {2} /output={0} ""{1}""", shimAssemblyPath, temporaryIlFilename, debug ? "/debug" : "",
platform == "x64" ? "/X64" : "");
if (!debug) {
Delete(temporaryIlFilename); // delete temp file regardless of result.
}
if (0 != rc) {
return Fail("Error: unable to assemble the merged assembly\r\n [{0}]\r\n [{1}]\r\nMore Information:\r\n{2}",
shimAssemblyPath, temporaryIlFilename, ILAsm.StandardError);
}
if (originalAssemblyPath.Equals(finalOuputFilename, StringComparison.CurrentCultureIgnoreCase)) {
File.Delete(originalAssemblyPath + ".orig");
File.Move(originalAssemblyPath, originalAssemblyPath + ".orig");
}
File.Delete(finalOuputFilename);
File.Move(shimAssemblyPath, finalOuputFilename);
if (!quiet) {
Console.WriteLine("Created Exported functions in Assembly: {0}", finalOuputFilename);
}
if (createLib) {
string defFile = Path.GetFileNameWithoutExtension(finalOuputFilename) + ".def";
string libFile = Path.GetFileNameWithoutExtension(finalOuputFilename) + ".lib";
File.WriteAllLines(defFile, exports);
Lib.ExecNoRedirections("/NOLOGO /machine:{0} /def:{1} /OUT:{2}", platform, defFile, libFile);
}
if (headerFilename != null) {
foreach (var e in enumTypeDefs) {
functions.Insert(1, e.Value);
}
File.WriteAllLines(headerFilename, functions);
}
return 0;
}
public static void SampleClass() {
using (new ConsoleColors(ConsoleColor.Green, ConsoleColor.Black)) {
Console.WriteLine(
@"
using System;
using System.Runtime.InteropServices;
/// <summary>
/// This class is used by the DllExport utility to generate a C-style
/// native binding for any static methods in a .NET assembly.
///
/// Namespace is not important--feel free to set the namespace to anything
/// convenient for your project.
/// -----------------------------------------------------------------------
/// (c) 2009 Microsoft Corporation -- All rights reserved
/// This code is licensed under the MS-PL
/// http://www.opensource.org/licenses/ms-pl.html
/// Courtesy of the Open Source Techology Center: http://port25.technet.com
/// -----------------------------------------------------------------------
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public class DllExportAttribute: Attribute {
public DllExportAttribute(string exportName)
: this(CallingConvention.StdCall,exportName) {
}
public DllExportAttribute(CallingConvention convention, string name) {
ExportedName = name;
this.CallingConvention = convention;
}
public string ExportedName { get; set; }
public CallingConvention CallingConvention { get; set; }
}");
}
}
public static void SampleUsage() {
using (new ConsoleColors(ConsoleColor.Green, ConsoleColor.Black)) {
Console.WriteLine(
@"
DllExport Usage
----------------
To use the DllExport Attribute in your code, include the class in your
project. Namespace is not important.
On any method you wish to export as a C-style function, simply use the
attribute on any static method in a class:
...
// example 1
// note the exported function name doesn't have to match the method name
[DllExport(""myFunction"")]
public static int MyFunction( int age, string name ){
// ....
}
// example 2
// On this example, we've marked set the calling convention to CDECL
[DllExport( CallingConvention.Cdecl, ""myNextFunction"")]
public static int MyFunctionTwo( float someParameter, string name ){
// ....
}
");
}
}
#region fail/help/logo
public static int Fail(string text, params object[] par) {
using (new ConsoleColors(ConsoleColor.Red, ConsoleColor.Black)) {
Console.WriteLine("Error:{0}", text.format(par));
}
return 1;
}
private static int Help() {
using (new ConsoleColors(ConsoleColor.White, ConsoleColor.Black)) {
help.Print();
}
return 0;
}
private void Logo() {
using (new ConsoleColors(ConsoleColor.Cyan, ConsoleColor.Black)) {
this.Assembly().Logo().Print();
}
this.Assembly().SetLogo("");
}
#endregion
#region Nested type: ExportableMember
internal class ExportableMember {
internal CallingConvention callingConvention;
internal string exportedName;
internal MemberInfo member;
}
#endregion
}
}