Skip to content

Instantly share code, notes, and snippets.

@jbevain
Created November 15, 2011 09:49
Show Gist options
  • Save jbevain/1366595 to your computer and use it in GitHub Desktop.
Save jbevain/1366595 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using Mono.Cecil;
class CompactFrameworkPatcher {
static readonly byte [] fwPkToken1 = new byte [] {
0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89
};
static readonly byte [] fwPkToken2 = new byte [] {
0xb0, 0x3f, 0x5f, 0x7f, 0x11, 0xd5, 0x0a, 0x3a
};
static readonly byte [] cfPkToken = new byte [] {
0x96, 0x9d, 0xb8, 0x05, 0x3d, 0x33, 0x22, 0xac
};
static Dictionary<string, byte []> mappableAssemblies = new Dictionary<string, byte []> ();
static CompactFrameworkPatcher ()
{
mappableAssemblies.Add ("mscorlib", fwPkToken1);
mappableAssemblies.Add ("System", fwPkToken1);
mappableAssemblies.Add ("System.Data", fwPkToken1);
mappableAssemblies.Add ("System.Drawing", fwPkToken2);
mappableAssemblies.Add ("System.Web.Services", fwPkToken2);
mappableAssemblies.Add ("System.Windows.Forms", fwPkToken1);
mappableAssemblies.Add ("System.Xml", fwPkToken1);
mappableAssemblies.Add ("Microsoft.VisualBasic", fwPkToken2);
}
bool CheckPublicKeyToken (AssemblyNameReference asm)
{
if (asm.PublicKeyToken == null || asm.PublicKeyToken.Length != 8)
return false;
var corresponding = mappableAssemblies [asm.Name];
for (int i = 0; i < 8; i++)
if (asm.PublicKeyToken [i] != corresponding [i])
return false;
return true;
}
static void FixAssemblyNameReference (AssemblyNameReference asm)
{
if (!mappableAssemblies.ContainsKey (asm.Name))
return;
if (!CheckPublicKeyToken (asm))
return;
asm.Flags |= AssemblyFlags.Retargetable;
asm.PublicKeyToken = cfPkToken;
}
static void Main (string [] args)
{
if (args.Length != 1) {
Usage ();
return;
}
string file = args [0];
var module = ModuleDefinition.ReadModule (file);
foreach (var reference in module.AssemblyReferences)
FixAssemblyNameReference (reference);
module.Write (file);
Console.WriteLine ("Assembly {0} patched", file);
}
static void Usage ()
{
Console.WriteLine ("Mono Assembly To Compact Framework Patcher");
Console.WriteLine ("usage: cf-patcher.exe assembly");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment