Преглед изворни кода

1.增加ILRuntime库
2.热更新dll提供async await支持

tanghai пре 9 година
родитељ
комит
63e7a52024
100 измењених фајлова са 6638 додато и 20 уклоњено
  1. 0 6
      Config/StartConfig/192.168.1.134.txt
  2. 6 0
      Config/StartConfig/192.168.12.112.txt
  3. 0 6
      Config/StartConfig/192.168.12.188.txt
  4. 6 0
      Config/StartConfig/192.168.9.182.txt
  5. 1 1
      Config/StartConfig/ClientConfig.txt
  6. 1 1
      Tools/cwRsync/Config/rsyncConfig.txt
  7. BIN
      Unity/Assets/CSharp 6.0 Support/Editor/CSharp60Support.dll
  8. 2 2
      Unity/Assets/CSharp vNext Support.meta
  9. 0 0
      Unity/Assets/CSharp vNext Support/AsyncTools.meta
  10. 0 0
      Unity/Assets/CSharp vNext Support/AsyncTools/Plugins.meta
  11. 0 0
      Unity/Assets/CSharp vNext Support/AsyncTools/Plugins/AsyncBridge.Net35.dll
  12. 0 0
      Unity/Assets/CSharp vNext Support/AsyncTools/Plugins/AsyncBridge.Net35.dll.meta
  13. 0 0
      Unity/Assets/CSharp vNext Support/AsyncTools/Plugins/AsyncBridge.Net35.xml
  14. 0 0
      Unity/Assets/CSharp vNext Support/AsyncTools/Plugins/AsyncBridge.Net35.xml.meta
  15. 0 0
      Unity/Assets/CSharp vNext Support/AsyncTools/Plugins/System.Threading.dll
  16. 0 0
      Unity/Assets/CSharp vNext Support/AsyncTools/Plugins/System.Threading.dll.meta
  17. 0 0
      Unity/Assets/CSharp vNext Support/AsyncTools/Plugins/System.Threading.xml
  18. 0 0
      Unity/Assets/CSharp vNext Support/AsyncTools/Plugins/System.Threading.xml.meta
  19. 68 0
      Unity/Assets/CSharp vNext Support/AsyncTools/UnityScheduler.cs
  20. 12 0
      Unity/Assets/CSharp vNext Support/AsyncTools/UnityScheduler.cs.meta
  21. 38 0
      Unity/Assets/CSharp vNext Support/AsyncTools/UnitySynchronizationContext.cs
  22. 12 0
      Unity/Assets/CSharp vNext Support/AsyncTools/UnitySynchronizationContext.cs.meta
  23. 87 0
      Unity/Assets/CSharp vNext Support/AsyncTools/UnityTaskScheduler.cs
  24. 12 0
      Unity/Assets/CSharp vNext Support/AsyncTools/UnityTaskScheduler.cs.meta
  25. 1 1
      Unity/Assets/CSharp vNext Support/Editor.meta
  26. BIN
      Unity/Assets/CSharp vNext Support/Editor/CSharpVNextSupport.dll
  27. 3 1
      Unity/Assets/CSharp vNext Support/Editor/CSharpVNextSupport.dll.meta
  28. 11 0
      Unity/Assets/CSharp vNext Support/Editor/UnitySchedulerEditor.cs
  29. 12 0
      Unity/Assets/CSharp vNext Support/Editor/UnitySchedulerEditor.cs.meta
  30. 2 2
      Unity/Assets/CSharp vNext Support/FormattableString.meta
  31. 82 0
      Unity/Assets/CSharp vNext Support/FormattableString/FormattableString.cs
  32. 12 0
      Unity/Assets/CSharp vNext Support/FormattableString/FormattableString.cs.meta
  33. 59 0
      Unity/Assets/CSharp vNext Support/FormattableString/FormattableStringFactory.cs
  34. 12 0
      Unity/Assets/CSharp vNext Support/FormattableString/FormattableStringFactory.cs.meta
  35. 1 0
      Unity/Assets/CSharpCompilerWrapper.rsp
  36. 8 0
      Unity/Assets/CSharpCompilerWrapper.rsp.meta
  37. 9 0
      Unity/Assets/ILRuntime.meta
  38. 9 0
      Unity/Assets/ILRuntime/ILRuntime.meta
  39. 9 0
      Unity/Assets/ILRuntime/ILRuntime/CLR.meta
  40. 9 0
      Unity/Assets/ILRuntime/ILRuntime/CLR/Method.meta
  41. 353 0
      Unity/Assets/ILRuntime/ILRuntime/CLR/Method/CLRMethod.cs
  42. 12 0
      Unity/Assets/ILRuntime/ILRuntime/CLR/Method/CLRMethod.cs.meta
  43. 26 0
      Unity/Assets/ILRuntime/ILRuntime/CLR/Method/ExceptionHandler.cs
  44. 12 0
      Unity/Assets/ILRuntime/ILRuntime/CLR/Method/ExceptionHandler.cs.meta
  45. 555 0
      Unity/Assets/ILRuntime/ILRuntime/CLR/Method/ILMethod.cs
  46. 12 0
      Unity/Assets/ILRuntime/ILRuntime/CLR/Method/ILMethod.cs.meta
  47. 33 0
      Unity/Assets/ILRuntime/ILRuntime/CLR/Method/IMethod.cs
  48. 12 0
      Unity/Assets/ILRuntime/ILRuntime/CLR/Method/IMethod.cs.meta
  49. 9 0
      Unity/Assets/ILRuntime/ILRuntime/CLR/TypeSystem.meta
  50. 468 0
      Unity/Assets/ILRuntime/ILRuntime/CLR/TypeSystem/CLRType.cs
  51. 12 0
      Unity/Assets/ILRuntime/ILRuntime/CLR/TypeSystem/CLRType.cs.meta
  52. 162 0
      Unity/Assets/ILRuntime/ILRuntime/CLR/TypeSystem/ILGenericParameterType.cs
  53. 12 0
      Unity/Assets/ILRuntime/ILRuntime/CLR/TypeSystem/ILGenericParameterType.cs.meta
  54. 863 0
      Unity/Assets/ILRuntime/ILRuntime/CLR/TypeSystem/ILType.cs
  55. 12 0
      Unity/Assets/ILRuntime/ILRuntime/CLR/TypeSystem/ILType.cs.meta
  56. 57 0
      Unity/Assets/ILRuntime/ILRuntime/CLR/TypeSystem/IType.cs
  57. 12 0
      Unity/Assets/ILRuntime/ILRuntime/CLR/TypeSystem/IType.cs.meta
  58. 9 0
      Unity/Assets/ILRuntime/ILRuntime/CLR/Utils.meta
  59. 165 0
      Unity/Assets/ILRuntime/ILRuntime/CLR/Utils/Extensions.cs
  60. 12 0
      Unity/Assets/ILRuntime/ILRuntime/CLR/Utils/Extensions.cs.meta
  61. 9 0
      Unity/Assets/ILRuntime/ILRuntime/Other.meta
  62. 9 0
      Unity/Assets/ILRuntime/ILRuntime/Other/DelegateExportAttribute.cs
  63. 12 0
      Unity/Assets/ILRuntime/ILRuntime/Other/DelegateExportAttribute.cs.meta
  64. 10 0
      Unity/Assets/ILRuntime/ILRuntime/Other/NeedAdaptorAttribute.cs
  65. 12 0
      Unity/Assets/ILRuntime/ILRuntime/Other/NeedAdaptorAttribute.cs.meta
  66. 9 0
      Unity/Assets/ILRuntime/ILRuntime/Reflection.meta
  67. 79 0
      Unity/Assets/ILRuntime/ILRuntime/Reflection/Extensions.cs
  68. 12 0
      Unity/Assets/ILRuntime/ILRuntime/Reflection/Extensions.cs.meta
  69. 201 0
      Unity/Assets/ILRuntime/ILRuntime/Reflection/ILRuntimeFieldInfo.cs
  70. 12 0
      Unity/Assets/ILRuntime/ILRuntime/Reflection/ILRuntimeFieldInfo.cs.meta
  71. 110 0
      Unity/Assets/ILRuntime/ILRuntime/Reflection/ILRuntimeMethodInfo.cs
  72. 12 0
      Unity/Assets/ILRuntime/ILRuntime/Reflection/ILRuntimeMethodInfo.cs.meta
  73. 325 0
      Unity/Assets/ILRuntime/ILRuntime/Reflection/ILRuntimeType.cs
  74. 12 0
      Unity/Assets/ILRuntime/ILRuntime/Reflection/ILRuntimeType.cs.meta
  75. 9 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime.meta
  76. 9 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Adaptors.meta
  77. 73 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Adaptors/CLRCrossBindingAdaptors.cs
  78. 12 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Adaptors/CLRCrossBindingAdaptors.cs.meta
  79. 9 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/CLRBinding.meta
  80. 1074 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/CLRBinding/BindingCodeGenerator.cs
  81. 12 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/CLRBinding/BindingCodeGenerator.cs.meta
  82. 9 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger.meta
  83. 61 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/BreakPointContext.cs
  84. 12 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/BreakPointContext.cs.meta
  85. 14 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/BreakpointInfo.cs
  86. 12 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/BreakpointInfo.cs.meta
  87. 25 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/DebugMessageType.cs
  88. 12 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/DebugMessageType.cs.meta
  89. 498 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/DebugService.cs
  90. 12 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/DebugService.cs.meta
  91. 235 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/DebugSocket.cs
  92. 12 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/DebugSocket.cs.meta
  93. 9 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/DebuggerServer.meta
  94. 340 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/DebuggerServer/DebuggerServer.cs
  95. 12 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/DebuggerServer/DebuggerServer.cs.meta
  96. 9 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/Protocol.meta
  97. 16 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/Protocol/CSBindBreakpoint.cs
  98. 12 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/Protocol/CSBindBreakpoint.cs.meta
  99. 12 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/Protocol/CSDeleteBreakpoint.cs
  100. 12 0
      Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/Protocol/CSDeleteBreakpoint.cs.meta

+ 0 - 6
Config/StartConfig/192.168.1.134.txt

@@ -1,6 +0,0 @@
-{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : "Config", "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.1.134", "Port" : 20000 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.1.134", "Port" : 10000 }], "AppId" : 1, "AppType" : "Manager", "ServerIP" : "192.168.1.134" }
-{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : "Config", "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.1.134", "Port" : 20001 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.1.134", "Port" : 10001 }], "AppId" : 2, "AppType" : "Realm", "ServerIP" : "192.168.1.134" }
-{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : "Config", "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.1.134", "Port" : 20002 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.1.134", "Port" : 10002 }], "AppId" : 3, "AppType" : "Gate", "ServerIP" : "192.168.1.134" }
-{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : "Config", "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.1.134", "Port" : 20003 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.1.134", "Port" : 10003 }], "AppId" : 4, "AppType" : "Gate", "ServerIP" : "192.168.1.134" }
-{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : "Config", "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.1.134", "Port" : 20004 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.1.134", "Port" : 10004 }], "AppId" : 5, "AppType" : "Gate", "ServerIP" : "192.168.1.134" }
-{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : "Config", "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.1.134", "Port" : 20005 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.1.134", "Port" : 10005 }], "AppId" : 6, "AppType" : "Gate", "ServerIP" : "192.168.1.134" }

+ 6 - 0
Config/StartConfig/192.168.12.112.txt

@@ -0,0 +1,6 @@
+{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : 4, "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.12.112", "Port" : 20000 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.12.188", "Port" : 10000 }], "AppId" : 1, "AppType" : "Manager", "ServerIP" : "192.168.12.112" }
+{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : 4, "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.12.112", "Port" : 20001 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.12.188", "Port" : 10001 }], "AppId" : 2, "AppType" : "Realm", "ServerIP" : "192.168.12.112" }
+{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : 4, "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.12.112", "Port" : 20002 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.12.188", "Port" : 10002 }], "AppId" : 3, "AppType" : "Gate", "ServerIP" : "192.168.12.112" }
+{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : 4, "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.12.112", "Port" : 20003 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.12.188", "Port" : 10003 }], "AppId" : 4, "AppType" : "Gate", "ServerIP" : "192.168.12.112" }
+{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : 4, "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.12.112", "Port" : 20004 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.12.188", "Port" : 10004 }], "AppId" : 5, "AppType" : "Gate", "ServerIP" : "192.168.12.112" }
+{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : 4, "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.12.112", "Port" : 20005 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.12.188", "Port" : 10005 }], "AppId" : 6, "AppType" : "Gate", "ServerIP" : "192.168.12.112" }

+ 0 - 6
Config/StartConfig/192.168.12.188.txt

@@ -1,6 +0,0 @@
-{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : "Config", "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.12.188", "Port" : 20000 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.12.188", "Port" : 10000 }], "AppId" : 1, "AppType" : "Manager", "ServerIP" : "192.168.12.188" }
-{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : "Config", "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.12.188", "Port" : 20001 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.12.188", "Port" : 10001 }], "AppId" : 2, "AppType" : "Realm", "ServerIP" : "192.168.12.188" }
-{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : "Config", "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.12.188", "Port" : 20002 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.12.188", "Port" : 10002 }], "AppId" : 3, "AppType" : "Gate", "ServerIP" : "192.168.12.188" }
-{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : "Config", "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.12.188", "Port" : 20003 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.12.188", "Port" : 10003 }], "AppId" : 4, "AppType" : "Gate", "ServerIP" : "192.168.12.188" }
-{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : "Config", "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.12.188", "Port" : 20004 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.12.188", "Port" : 10004 }], "AppId" : 5, "AppType" : "Gate", "ServerIP" : "192.168.12.188" }
-{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : "Config", "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.12.188", "Port" : 20005 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.12.188", "Port" : 10005 }], "AppId" : 6, "AppType" : "Gate", "ServerIP" : "192.168.12.188" }

+ 6 - 0
Config/StartConfig/192.168.9.182.txt

@@ -0,0 +1,6 @@
+{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : 4, "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.9.182", "Port" : 20000 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.9.182", "Port" : 10000 }], "AppId" : 1, "AppType" : "Manager", "ServerIP" : "192.168.9.182" }
+{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : 4, "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.9.182", "Port" : 20001 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.9.182", "Port" : 10001 }], "AppId" : 2, "AppType" : "Realm", "ServerIP" : "192.168.9.182" }
+{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : 4, "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.9.182", "Port" : 20002 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.9.182", "Port" : 10002 }], "AppId" : 3, "AppType" : "Gate", "ServerIP" : "192.168.9.182" }
+{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : 4, "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.9.182", "Port" : 20003 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.9.182", "Port" : 10003 }], "AppId" : 4, "AppType" : "Gate", "ServerIP" : "192.168.9.182" }
+{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : 4, "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.9.182", "Port" : 20004 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.9.182", "Port" : 10004 }], "AppId" : 5, "AppType" : "Gate", "ServerIP" : "192.168.9.182" }
+{ "_t" : "StartConfig", "_id" : NumberLong("96832366182401"), "Type" : 4, "components" : [{ "_t" : "InnerConfig", "_id" : NumberLong("96832366182402"), "Host" : "192.168.9.182", "Port" : 20005 }, { "_t" : "OuterConfig", "_id" : NumberLong("96832366182403"), "Host" : "192.168.9.182", "Port" : 10005 }], "AppId" : 6, "AppType" : "Gate", "ServerIP" : "192.168.9.182" }

+ 1 - 1
Config/StartConfig/ClientConfig.txt

@@ -1 +1 @@
-{ "_t" : "StartConfig", "_id" : NumberLong("96935508377601"), "Type" : 4, "components" : [{ "_t" : "ClientConfig", "_id" : NumberLong("96935508377602"), "Host" : "127.0.0.1", "Port" : 10000 }], "AppId" : 0, "AppType" : "Client", "ServerIP" : "*" }
+{ "_t" : "StartConfig", "_id" : NumberLong("96935508377601"), "Type" : 4, "components" : [{ "_t" : "ClientConfig", "_id" : NumberLong("96935508377602"), "Host" : "192.168.9.182", "Port" : 10000 }], "AppId" : 0, "AppType" : "Client", "ServerIP" : "*" }

+ 1 - 1
Tools/cwRsync/Config/rsyncConfig.txt

@@ -1 +1 @@
-{ "_t" : "RsyncConfig", "Host" : "192.168.9.210", "Account" : "tanghai", "Password" : "1234567890", "RelativePath" : "Source/Egametang", "Exclude" : [".git/", "Logs/", "Tools/", "Bin/", "Server/packages/", "Temp/", "Server/Server.sdf", "Unity/Library/", "Unity/Temp/", "*/obj"] }
+{ "_t" : "RsyncConfig", "Host" : "192.168.9.182", "Account" : "tanghai", "Password" : "1234567890", "RelativePath" : "Source/Egametang", "Exclude" : [".git/", "Logs/", "Tools/", "Bin/", "Server/packages/", "Temp/", "Server/Server.sdf", "Unity/Library/", "Unity/Temp/", "*/obj"] }

BIN
Unity/Assets/CSharp 6.0 Support/Editor/CSharp60Support.dll


+ 2 - 2
Unity/Assets/ResBundles.meta → Unity/Assets/CSharp vNext Support.meta

@@ -1,7 +1,7 @@
 fileFormatVersion: 2
-guid: 1b61bf6e70b518e44b8fdd81e42956f3
+guid: bd6f26ee6280c2d42a6d003d346592fa
 folderAsset: yes
-timeCreated: 1486452520
+timeCreated: 1451846465
 licenseType: Pro
 DefaultImporter:
   userData: 

+ 0 - 0
Unity/Assets/CSharp 6.0 Support/AsyncTools.meta → Unity/Assets/CSharp vNext Support/AsyncTools.meta


+ 0 - 0
Unity/Assets/CSharp 6.0 Support/AsyncTools/Plugins.meta → Unity/Assets/CSharp vNext Support/AsyncTools/Plugins.meta


+ 0 - 0
Unity/Assets/CSharp 6.0 Support/AsyncTools/Plugins/AsyncBridge.Net35.dll → Unity/Assets/CSharp vNext Support/AsyncTools/Plugins/AsyncBridge.Net35.dll


+ 0 - 0
Unity/Assets/CSharp 6.0 Support/AsyncTools/Plugins/AsyncBridge.Net35.dll.meta → Unity/Assets/CSharp vNext Support/AsyncTools/Plugins/AsyncBridge.Net35.dll.meta


+ 0 - 0
Unity/Assets/CSharp 6.0 Support/AsyncTools/Plugins/AsyncBridge.Net35.xml → Unity/Assets/CSharp vNext Support/AsyncTools/Plugins/AsyncBridge.Net35.xml


+ 0 - 0
Unity/Assets/CSharp 6.0 Support/AsyncTools/Plugins/AsyncBridge.Net35.xml.meta → Unity/Assets/CSharp vNext Support/AsyncTools/Plugins/AsyncBridge.Net35.xml.meta


+ 0 - 0
Unity/Assets/CSharp 6.0 Support/AsyncTools/Plugins/System.Threading.dll → Unity/Assets/CSharp vNext Support/AsyncTools/Plugins/System.Threading.dll


+ 0 - 0
Unity/Assets/CSharp 6.0 Support/AsyncTools/Plugins/System.Threading.dll.meta → Unity/Assets/CSharp vNext Support/AsyncTools/Plugins/System.Threading.dll.meta


+ 0 - 0
Unity/Assets/CSharp 6.0 Support/AsyncTools/Plugins/System.Threading.xml → Unity/Assets/CSharp vNext Support/AsyncTools/Plugins/System.Threading.xml


+ 0 - 0
Unity/Assets/CSharp 6.0 Support/AsyncTools/Plugins/System.Threading.xml.meta → Unity/Assets/CSharp vNext Support/AsyncTools/Plugins/System.Threading.xml.meta


+ 68 - 0
Unity/Assets/CSharp vNext Support/AsyncTools/UnityScheduler.cs

@@ -0,0 +1,68 @@
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using UnityEngine;
+
+public class UnityScheduler : MonoBehaviour
+{
+	public static int MainThreadId { get; private set; }
+
+	/// <summary>
+	/// Use UpdateScheduler, LateUpdateScheduler or FixedUpdateScheduler instead.
+	/// </summary>
+	[Obsolete]
+	public static UnityTaskScheduler MainThreadScheduler => UpdateScheduler;
+
+	/// <summary>
+	/// Executes tasks in the main thread, Update context.
+	/// </summary>
+	public static UnityTaskScheduler UpdateScheduler { get; private set; }
+	
+	/// <summary>
+	/// Executes tasks in the main thread, LateUpdate context.
+	/// </summary>
+	public static UnityTaskScheduler LateUpdateScheduler { get; private set; }
+
+	/// <summary>
+	/// Executes tasks in the main thread, FixedUpdate context.
+	/// </summary>
+	public static UnityTaskScheduler FixedUpdateScheduler { get; private set; }
+
+	public static UnityTaskScheduler EditorUpdateScheduler { get; private set; }
+
+	/// <summary>
+	/// Executes tasks in the thread pool. It's an alias for TaskScheduler.Default.
+	/// </summary>
+	public static TaskScheduler ThreadPoolScheduler => TaskScheduler.Default;
+
+	[RuntimeInitializeOnLoadMethod]
+	private static void Initialize()
+	{
+		MainThreadId = Thread.CurrentThread.ManagedThreadId;
+
+		UpdateScheduler = new UnityTaskScheduler("Update");
+		LateUpdateScheduler = new UnityTaskScheduler("LateUpdate");
+		FixedUpdateScheduler = new UnityTaskScheduler("FixedUpdate");
+
+		SynchronizationContext.SetSynchronizationContext(UpdateScheduler.Context);
+
+		var go = new GameObject("UnityScheduler");
+		go.hideFlags = HideFlags.HideAndDontSave;
+		go.AddComponent<UnityScheduler>();
+	}
+
+	public static void InitializeInEditor()
+	{
+		MainThreadId = Thread.CurrentThread.ManagedThreadId;
+		EditorUpdateScheduler = new UnityTaskScheduler("EditorUpdate");
+		SynchronizationContext.SetSynchronizationContext(EditorUpdateScheduler.Context);
+	}
+
+	public static void ProcessEditorUpdate() => EditorUpdateScheduler.Activate();
+
+	private void Update() => UpdateScheduler.Activate();
+
+	private void LateUpdate() => LateUpdateScheduler.Activate();
+
+	private void FixedUpdate() => FixedUpdateScheduler.Activate();
+}

+ 12 - 0
Unity/Assets/CSharp vNext Support/AsyncTools/UnityScheduler.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 94133cd8b5ef43349b9e07e1f80baaa7
+timeCreated: 1431638967
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: -10000
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 38 - 0
Unity/Assets/CSharp vNext Support/AsyncTools/UnitySynchronizationContext.cs

@@ -0,0 +1,38 @@
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Threading;
+
+public class UnitySynchronizationContext : SynchronizationContext
+{
+	private readonly BlockingCollection<KeyValuePair<SendOrPostCallback, object>> queue = new BlockingCollection<KeyValuePair<SendOrPostCallback, object>>();
+
+	public string Name { get; }
+
+	public event EventHandler Activated;
+
+	public UnitySynchronizationContext(string name)
+	{
+		Name = name;
+	}
+
+	public void Activate()
+	{
+		Activated?.Invoke(this, EventArgs.Empty);
+		Activated = null;
+	}
+
+	public override void Post(SendOrPostCallback d, object state)
+	{
+		queue.Add(new KeyValuePair<SendOrPostCallback, object>(d, state));
+	}
+
+	public void ExecutePendingContinuations()
+	{
+		KeyValuePair<SendOrPostCallback, object> workItem;
+		while (queue.TryTake(out workItem))
+		{
+			workItem.Key(workItem.Value);
+		}
+	}
+}

+ 12 - 0
Unity/Assets/CSharp vNext Support/AsyncTools/UnitySynchronizationContext.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: abcd1fe92309a994293767b78d3cd211
+timeCreated: 1451598383
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 87 - 0
Unity/Assets/CSharp vNext Support/AsyncTools/UnityTaskScheduler.cs

@@ -0,0 +1,87 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+
+public class UnityTaskScheduler : TaskScheduler
+{
+	public string Name { get; }
+	public UnitySynchronizationContext Context { get; }
+	private readonly LinkedList<Task> queue = new LinkedList<Task>();
+
+	public UnityTaskScheduler(string name)
+	{
+		Name = name;
+		Context = new UnitySynchronizationContext(name);
+	}
+
+	public void Activate()
+	{
+		SynchronizationContext.SetSynchronizationContext(Context);
+		Context.Activate();
+
+		ExecutePendingTasks();
+		Context.ExecutePendingContinuations();
+	}
+
+	protected override IEnumerable<Task> GetScheduledTasks()
+	{
+		lock (queue)
+		{
+			return queue.ToArray();
+		}
+	}
+
+	protected override void QueueTask(Task task)
+	{
+		lock (queue)
+		{
+			queue.AddLast(task);
+		}
+	}
+
+	protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
+	{
+		if (Context != SynchronizationContext.Current)
+		{
+			return false;
+		}
+
+		if (taskWasPreviouslyQueued)
+		{
+			lock (queue)
+			{
+				queue.Remove(task);
+			}
+		}
+
+		return TryExecuteTask(task);
+	}
+
+	private void ExecutePendingTasks()
+	{
+		while (true)
+		{
+			Task task;
+			lock (queue)
+			{
+				if (queue.Count == 0)
+				{
+					break;
+				}
+				task = queue.First.Value;
+				queue.RemoveFirst();
+			}
+
+			if (task != null)
+			{
+				var result = TryExecuteTask(task);
+				if (result == false)
+				{
+					throw new InvalidOperationException();
+				}
+			}
+		}
+	}
+}

+ 12 - 0
Unity/Assets/CSharp vNext Support/AsyncTools/UnityTaskScheduler.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 998646c27a6d1084499e5fd0e2ab0c2e
+timeCreated: 1451598383
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 1 - 1
Unity/Assets/CSharp 6.0 Support/Editor.meta → Unity/Assets/CSharp vNext Support/Editor.meta

@@ -1,5 +1,5 @@
 fileFormatVersion: 2
-guid: f5851f88ad65c574cae1d6d39bf704b4
+guid: ad1316e00c55aa44d8b28322993767d4
 folderAsset: yes
 timeCreated: 1446591068
 licenseType: Pro

BIN
Unity/Assets/CSharp vNext Support/Editor/CSharpVNextSupport.dll


+ 3 - 1
Unity/Assets/CSharp 6.0 Support/Editor/CSharp60Support.dll.meta → Unity/Assets/CSharp vNext Support/Editor/CSharpVNextSupport.dll.meta

@@ -1,5 +1,7 @@
 fileFormatVersion: 2
-guid: e6afa6c5125e5af4289ce4bf422f504a
+guid: e4f9cb46e577ef8479f0e8e582cb6333
+timeCreated: 1459889200
+licenseType: Pro
 PluginImporter:
   serializedVersion: 1
   iconMap: {}

+ 11 - 0
Unity/Assets/CSharp vNext Support/Editor/UnitySchedulerEditor.cs

@@ -0,0 +1,11 @@
+using UnityEditor;
+
+public static class UnitySchedulerEditor
+{
+	[InitializeOnLoadMethod]
+	private static void InitializeInEditor()
+	{
+		UnityScheduler.InitializeInEditor();
+		EditorApplication.update += UnityScheduler.ProcessEditorUpdate;
+	}
+}

+ 12 - 0
Unity/Assets/CSharp vNext Support/Editor/UnitySchedulerEditor.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: fd7028abf67117e4a98bcde72172cdbe
+timeCreated: 1473459342
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 2 - 2
Unity/Assets/CSharp 6.0 Support.meta → Unity/Assets/CSharp vNext Support/FormattableString.meta

@@ -1,7 +1,7 @@
 fileFormatVersion: 2
-guid: f815cca01d9b82141bab30cea117fe27
+guid: 31cb7cff77bc5ba44ba9dcc254122cfd
 folderAsset: yes
-timeCreated: 1463827725
+timeCreated: 1461347836
 licenseType: Pro
 DefaultImporter:
   userData: 

+ 82 - 0
Unity/Assets/CSharp vNext Support/FormattableString/FormattableString.cs

@@ -0,0 +1,82 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+/*============================================================
+**
+** Class:  FormattableString
+**
+**
+** Purpose: implementation of the FormattableString
+** class.
+**
+===========================================================*/
+namespace System
+{
+    /// <summary>
+    /// A composite format string along with the arguments to be formatted. An instance of this
+    /// type may result from the use of the C# or VB language primitive "interpolated string".
+    /// </summary>
+    public abstract class FormattableString : IFormattable
+    {
+        /// <summary>
+        /// The composite format string.
+        /// </summary>
+        public abstract string Format { get; }
+
+        /// <summary>
+        /// Returns an object array that contains zero or more objects to format. Clients should not
+        /// mutate the contents of the array.
+        /// </summary>
+        public abstract object[] GetArguments();
+
+        /// <summary>
+        /// The number of arguments to be formatted.
+        /// </summary>
+        public abstract int ArgumentCount { get; }
+
+        /// <summary>
+        /// Returns one argument to be formatted from argument position <paramref name="index"/>.
+        /// </summary>
+        public abstract object GetArgument(int index);
+
+        /// <summary>
+        /// Format to a string using the given culture.
+        /// </summary>
+        public abstract string ToString(IFormatProvider formatProvider);
+
+        string IFormattable.ToString(string ignored, IFormatProvider formatProvider)
+        {
+            return ToString(formatProvider);
+        }
+
+        /// <summary>
+        /// Format the given object in the invariant culture. This static method may be
+        /// imported in C# by
+        /// <code>
+        /// using static System.FormattableString;
+        /// </code>.
+        /// Within the scope
+        /// of that import directive an interpolated string may be formatted in the
+        /// invariant culture by writing, for example,
+        /// <code>
+        /// Invariant($"{{ lat = {latitude}; lon = {longitude} }}")
+        /// </code>
+        /// </summary>
+        public static string Invariant(FormattableString formattable)
+        {
+            if (formattable == null)
+            {
+                throw new ArgumentNullException("formattable");
+            }
+
+            return formattable.ToString(Globalization.CultureInfo.InvariantCulture);
+        }
+
+        public override string ToString()
+        {
+            return ToString(Globalization.CultureInfo.CurrentCulture);
+        }
+    }
+}
+

+ 12 - 0
Unity/Assets/CSharp vNext Support/FormattableString/FormattableString.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 3f75f902cf93cf144becd3aeb61a5cb0
+timeCreated: 1461347850
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 59 - 0
Unity/Assets/CSharp vNext Support/FormattableString/FormattableStringFactory.cs

@@ -0,0 +1,59 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+/*============================================================
+**
+** Class:  FormattableStringFactory
+**
+**
+** Purpose: implementation of the FormattableStringFactory
+** class.
+**
+===========================================================*/
+namespace System.Runtime.CompilerServices
+{
+    /// <summary>
+    /// A factory type used by compilers to create instances of the type <see cref="FormattableString"/>.
+    /// </summary>
+    public static class FormattableStringFactory
+    {
+        /// <summary>
+        /// Create a <see cref="FormattableString"/> from a composite format string and object
+        /// array containing zero or more objects to format.
+        /// </summary>
+        public static FormattableString Create(string format, params object[] arguments)
+        {
+            if (format == null)
+            {
+                throw new ArgumentNullException("format");
+            }
+
+            if (arguments == null)
+            {
+                throw new ArgumentNullException("arguments");
+            }
+
+            return new ConcreteFormattableString(format, arguments);
+        }
+
+        private sealed class ConcreteFormattableString : FormattableString
+        {
+            private readonly string _format;
+            private readonly object[] _arguments;
+
+            internal ConcreteFormattableString(string format, object[] arguments)
+            {
+                _format = format;
+                _arguments = arguments;
+            }
+
+            public override string Format { get { return _format; } }
+            public override object[] GetArguments() { return _arguments; }
+            public override int ArgumentCount { get { return _arguments.Length; } }
+            public override object GetArgument(int index) { return _arguments[index]; }
+            public override string ToString(IFormatProvider formatProvider) { return string.Format(formatProvider, _format, _arguments); }
+        }
+    }
+}
+

+ 12 - 0
Unity/Assets/CSharp vNext Support/FormattableString/FormattableStringFactory.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 4263742f7d8ddd34a8d5906cc734cb47
+timeCreated: 1461347850
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 1 - 0
Unity/Assets/CSharpCompilerWrapper.rsp

@@ -0,0 +1 @@
+-unsafe

+ 8 - 0
Unity/Assets/CSharpCompilerWrapper.rsp.meta

@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 551fa6d36e775364280976f8ff8cffad
+timeCreated: 1486621181
+licenseType: Pro
+DefaultImporter:
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 9 - 0
Unity/Assets/ILRuntime.meta

@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: c7f6e299339884644accd7ca650313b1
+folderAsset: yes
+timeCreated: 1486603921
+licenseType: Pro
+DefaultImporter:
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 9 - 0
Unity/Assets/ILRuntime/ILRuntime.meta

@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: 87596c56637b1f840a506371ff9e9e6a
+folderAsset: yes
+timeCreated: 1486603934
+licenseType: Pro
+DefaultImporter:
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 9 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR.meta

@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: d542c719c306ebf42bcded60a947e102
+folderAsset: yes
+timeCreated: 1486603934
+licenseType: Pro
+DefaultImporter:
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 9 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR/Method.meta

@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: b0743254a9a39824a996c5fcc817b513
+folderAsset: yes
+timeCreated: 1486603934
+licenseType: Pro
+DefaultImporter:
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 353 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR/Method/CLRMethod.cs

@@ -0,0 +1,353 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using System.Text;
+
+using Mono.Cecil;
+using ILRuntime.Runtime.Intepreter;
+using ILRuntime.Runtime.Enviorment;
+using ILRuntime.CLR.TypeSystem;
+using ILRuntime.Runtime.Stack;
+using ILRuntime.CLR.Utils;
+namespace ILRuntime.CLR.Method
+{
+    public class CLRMethod : IMethod
+    {
+        MethodInfo def;
+        ConstructorInfo cDef;
+        List<IType> parameters;
+        ILRuntime.Runtime.Enviorment.AppDomain appdomain;
+        CLRType declaringType;
+        ParameterInfo[] param;
+        bool isConstructor;
+        CLRRedirectionDelegate redirect;
+        IType[] genericArguments;
+        object[] invocationParam;
+        bool isDelegateInvoke;
+
+        public IType DeclearingType
+        {
+            get
+            {
+                return declaringType;
+            }
+        }
+        public string Name
+        {
+            get
+            {
+                return def.Name;
+            }
+        }
+        public bool HasThis
+        {
+            get
+            {
+                return isConstructor ? !cDef.IsStatic : !def.IsStatic;
+            }
+        }
+        public int GenericParameterCount
+        {
+            get
+            {
+                if (def.ContainsGenericParameters && def.IsGenericMethodDefinition)
+                {
+                    return def.GetGenericArguments().Length;
+                }
+                return 0;
+            }
+        }
+        public bool IsGenericInstance
+        {
+            get
+            {
+                return genericArguments != null;
+            }
+        }
+
+        public bool IsDelegateInvoke
+        {
+            get
+            {
+                return isDelegateInvoke;
+            }
+        }
+
+        public bool IsStatic
+        {
+            get { return def.IsStatic; }
+        }
+
+        public CLRRedirectionDelegate Redirection { get { return redirect; } }
+
+        public MethodInfo MethodInfo { get { return def; } }
+
+        public ConstructorInfo ConstructorInfo { get { return cDef; } }
+
+        public IType[] GenericArguments { get { return genericArguments; } }
+
+        internal CLRMethod(MethodInfo def, CLRType type, ILRuntime.Runtime.Enviorment.AppDomain domain)
+        {
+            this.def = def;
+            declaringType = type;
+            this.appdomain = domain;
+            param = def.GetParameters();
+            if (!def.ContainsGenericParameters)
+            {
+                ReturnType = domain.GetType(def.ReturnType.FullName);
+                if (ReturnType == null)
+                {
+                    ReturnType = domain.GetType(def.ReturnType.AssemblyQualifiedName);
+                }
+            }
+            if (type.IsDelegate && def.Name == "Invoke")
+                isDelegateInvoke = true;
+            isConstructor = false;
+
+            if (def != null)
+            {
+                if (def.IsGenericMethod && !def.IsGenericMethodDefinition)
+                {
+                    appdomain.RedirectMap.TryGetValue(def.GetGenericMethodDefinition(), out redirect);
+                }
+                else
+                    appdomain.RedirectMap.TryGetValue(def, out redirect);
+            }
+        }
+        internal CLRMethod(ConstructorInfo def, CLRType type, ILRuntime.Runtime.Enviorment.AppDomain domain)
+        {
+            this.cDef = def;
+            declaringType = type;
+            this.appdomain = domain;
+            param = def.GetParameters();
+            if (!def.ContainsGenericParameters)
+            {
+                ReturnType = type;
+            }
+            isConstructor = true;
+
+            if (def != null)
+            {
+                appdomain.RedirectMap.TryGetValue(cDef, out redirect);
+            }
+        }
+
+        public int ParameterCount
+        {
+            get
+            {
+                return param != null ? param.Length : 0;
+            }
+        }
+
+
+        public List<IType> Parameters
+        {
+            get
+            {
+                if (parameters == null)
+                {
+                    InitParameters();
+                }
+                return parameters;
+            }
+        }
+
+        public IType ReturnType
+        {
+            get;
+            private set;
+        }
+
+        public bool IsConstructor
+        {
+            get
+            {
+                return cDef != null;
+            }
+        }
+
+        void InitParameters()
+        {
+            parameters = new List<IType>();
+            foreach (var i in param)
+            {
+                IType type = appdomain.GetType(i.ParameterType.FullName);
+                if (type == null)
+                    type = appdomain.GetType(i.ParameterType.AssemblyQualifiedName);
+                if (i.ParameterType.IsGenericTypeDefinition)
+                {
+                    if (type == null)
+                        type = appdomain.GetType(i.ParameterType.GetGenericTypeDefinition().FullName);
+                    if (type == null)
+                        type = appdomain.GetType(i.ParameterType.GetGenericTypeDefinition().AssemblyQualifiedName);
+                }
+                if (i.ParameterType.ContainsGenericParameters)
+                {
+                    var t = i.ParameterType;
+                    if (t.HasElementType)
+                        t = i.ParameterType.GetElementType();
+                    else if (t.GetGenericArguments().Length > 0)
+                    {
+                        t = t.GetGenericArguments()[0];
+                    }
+                    type = new ILGenericParameterType(t.Name);
+                }
+                if (type == null)
+                    throw new TypeLoadException();
+                parameters.Add(type);
+            }
+        }
+
+        unsafe StackObject* Minus(StackObject* a, int b)
+        {
+            return (StackObject*)((long)a - sizeof(StackObject) * b);
+        }
+
+        public unsafe object Invoke(Runtime.Intepreter.ILIntepreter intepreter, StackObject* esp, List<object> mStack, bool isNewObj = false)
+        {
+            if (parameters == null)
+            {
+                InitParameters();
+            }
+            int paramCount = ParameterCount;
+            if (invocationParam == null)
+                invocationParam = new object[paramCount];
+            object[] param = invocationParam;
+            for (int i = paramCount; i >= 1; i--)
+            {
+                var p = Minus(esp, i);
+                var obj = this.param[paramCount - i].ParameterType.CheckCLRTypes(appdomain, StackObject.ToObject(p, appdomain, mStack));
+                obj = ILIntepreter.CheckAndCloneValueType(obj, appdomain);
+                param[paramCount - i] = obj;
+            }
+
+            if (isConstructor)
+            {
+                if (!isNewObj)
+                {
+                    if (!cDef.IsStatic)
+                    {
+                        object instance = declaringType.TypeForCLR.CheckCLRTypes(appdomain, StackObject.ToObject((Minus(esp, paramCount + 1)), appdomain, mStack));
+                        if (instance == null)
+                            throw new NullReferenceException();
+                        if (instance is CrossBindingAdaptorType)//It makes no sense to call the Adaptor's constructor
+                            return null;
+                        cDef.Invoke(instance, param);
+                        return null;
+                    }
+                    else
+                    {
+                        throw new NotImplementedException();
+                    }
+                }
+                else
+                {
+                    var res = cDef.Invoke(param);
+
+                    FixReference(paramCount, esp, param, mStack);
+                    return res;
+                }
+
+            }
+            else
+            {
+                object instance = null;
+
+                if (!def.IsStatic)
+                {
+                    instance = declaringType.TypeForCLR.CheckCLRTypes(appdomain, StackObject.ToObject((Minus(esp, paramCount + 1)), appdomain, mStack));
+                    if (instance == null)
+                        throw new NullReferenceException();
+                }
+                object res = null;
+                /*if (redirect != null)
+                    res = redirect(new ILContext(appdomain, intepreter, esp, mStack, this), instance, param, genericArguments);
+                else*/
+                {
+                    res = def.Invoke(instance, param);
+                }
+
+                FixReference(paramCount, esp, param, mStack);
+                return res;
+            }
+        }
+
+        unsafe void FixReference(int paramCount, StackObject* esp, object[] param, List<object> mStack)
+        {
+            for (int i = paramCount; i >= 1; i--)
+            {
+                var p = Minus(esp, i);
+                var val = param[paramCount - i];
+                switch (p->ObjectType)
+                {
+                    case ObjectTypes.StackObjectReference:
+                        {
+                            var dst = *(StackObject**)&p->Value;
+                            if (dst->ObjectType >= ObjectTypes.Object)
+                            {
+                                var obj = val;
+                                if (obj is CrossBindingAdaptorType)
+                                    obj = ((CrossBindingAdaptorType)obj).ILInstance;
+                                mStack[dst->Value] = obj;
+                            }
+                            else
+                            {
+                                ILIntepreter.UnboxObject(dst, val);
+                            }
+                        }
+                        break;
+                    case ObjectTypes.FieldReference:
+                        {
+                            var obj = mStack[p->Value];
+                            if(obj is ILTypeInstance)
+                            {
+                                ((ILTypeInstance)obj)[p->ValueLow] = val;
+                            }
+                            else
+                            {
+                                var t = appdomain.GetType(obj.GetType()) as CLRType;
+                                t.GetField(p->ValueLow).SetValue(obj, val);
+                            }
+                        }
+                        break;
+                    case ObjectTypes.StaticFieldReference:
+                        {
+                            var t = appdomain.GetType(p->Value);
+                            if(t is ILType)
+                            {
+                                ((ILType)t).StaticInstance[p->ValueLow] = val;
+                            }
+                            else
+                            {
+                                ((CLRType)t).GetField(p->ValueLow).SetValue(null, val);
+                            }
+                        }
+                        break;
+                }
+            }
+        }
+
+        public IMethod MakeGenericMethod(IType[] genericArguments)
+        {
+            Type[] p = new Type[genericArguments.Length];
+            for (int i = 0; i < genericArguments.Length; i++)
+            {
+                p[i] = genericArguments[i].TypeForCLR;
+            }
+            var t = def.MakeGenericMethod(p);
+            var res = new CLRMethod(t, declaringType, appdomain);
+            res.genericArguments = genericArguments;
+            return res;
+        }
+
+        public override string ToString()
+        {
+            if (def != null)
+                return def.ToString();
+            else
+                return cDef.ToString();
+        }
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR/Method/CLRMethod.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: e3a93984f12c9da43b98d43930dd8c49
+timeCreated: 1486603952
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 26 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR/Method/ExceptionHandler.cs

@@ -0,0 +1,26 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+using ILRuntime.CLR.TypeSystem;
+
+namespace ILRuntime.CLR.Method
+{
+    enum ExceptionHandlerType
+    {
+        Catch,
+        Finally,
+        Fault,
+    }
+    class ExceptionHandler
+    {
+        public ExceptionHandlerType HandlerType { get; set; }
+
+        public int TryStart { get; set; }
+        public int TryEnd { get; set; }
+        public int HandlerStart { get; set; }
+        public int HandlerEnd { get; set; }
+        public IType CatchType { get; set; }
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR/Method/ExceptionHandler.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 99ef6f3b1f4f7894ebd5e1878c08fcb5
+timeCreated: 1486603951
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 555 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR/Method/ILMethod.cs

@@ -0,0 +1,555 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Reflection;
+
+using Mono.Cecil;
+using ILRuntime.Runtime.Intepreter.OpCodes;
+using ILRuntime.Runtime.Intepreter;
+using ILRuntime.Runtime.Debugger;
+using ILRuntime.CLR.TypeSystem;
+using ILRuntime.Reflection;
+namespace ILRuntime.CLR.Method
+{
+    public class ILMethod : IMethod
+    {
+        OpCode[] body;
+        MethodDefinition def;
+        List<IType> parameters;
+        ILRuntime.Runtime.Enviorment.AppDomain appdomain;
+        ILType declaringType;
+        ExceptionHandler[] exceptionHandler;
+        KeyValuePair<string, IType>[] genericParameters;
+        Dictionary<int, int[]> jumptables;
+        bool isDelegateInvoke;
+        ILRuntimeMethodInfo refletionMethodInfo;
+        int paramCnt, localVarCnt;
+
+        public MethodDefinition Definition { get { return def; } }
+
+        public Dictionary<int, int[]> JumpTables { get { return jumptables; } }
+
+        internal IDelegateAdapter DelegateAdapter { get; set; }
+
+        internal int StartLine { get; set; }
+
+        internal int EndLine { get; set; }
+
+        public MethodInfo ReflectionMethodInfo
+        {
+            get
+            {
+                if (refletionMethodInfo == null)
+                    refletionMethodInfo = new ILRuntimeMethodInfo(this);
+                return refletionMethodInfo;
+            }
+        }
+
+        internal ExceptionHandler[] ExceptionHandler
+        {
+            get
+            {
+                if (body == null)
+                    InitCodeBody();
+                return exceptionHandler;
+            }
+        }
+
+        public string Name
+        {
+            get
+            {
+                return def.Name;
+            }
+        }
+
+        public IType DeclearingType
+        {
+            get
+            {
+                return declaringType;
+            }
+        }
+
+        public bool HasThis
+        {
+            get
+            {
+                return def.HasThis;
+            }
+        }
+        public int GenericParameterCount
+        {
+            get
+            {
+                return def.GenericParameters.Count;
+            }
+        }
+        public bool IsGenericInstance
+        {
+            get
+            {
+                return genericParameters != null;
+            }
+        }
+        public ILMethod(MethodDefinition def, ILType type, ILRuntime.Runtime.Enviorment.AppDomain domain)
+        {
+            this.def = def;
+            declaringType = type;
+            if (def.ReturnType.IsGenericParameter)
+            {
+                ReturnType = FindGenericArgument(def.ReturnType.Name);
+            }
+            else
+                ReturnType = domain.GetType(def.ReturnType, type, this);
+            if (type.IsDelegate && def.Name == "Invoke")
+                isDelegateInvoke = true;
+            this.appdomain = domain;
+            paramCnt = def.HasParameters ? def.Parameters.Count : 0;
+            localVarCnt = def.HasBody ? def.Body.Variables.Count : 0;
+#if DEBUG
+            if (def.HasBody)
+            {
+                var sp = DebugService.FindSequencePoint(def.Body.Instructions[0]);
+                if (sp != null)
+                {
+                    StartLine = sp.StartLine;
+                    sp = DebugService.FindSequencePoint(def.Body.Instructions[def.Body.Instructions.Count - 1]);
+                    if (sp != null)
+                    {
+                        EndLine = sp.EndLine;
+                    }
+                }
+            }
+#endif
+        }
+
+        public IType FindGenericArgument(string name)
+        {
+            IType res = declaringType.FindGenericArgument(name);
+            if (res == null && genericParameters != null)
+            {
+                foreach (var i in genericParameters)
+                {
+                    if (i.Key == name)
+                        return i.Value;
+                }
+            }
+            else
+                return res;
+            return null;
+        }
+
+        internal OpCode[] Body
+        {
+            get
+            {
+                if (body == null)
+                    InitCodeBody();
+                return body;
+            }
+        }
+
+        public int LocalVariableCount
+        {
+            get
+            {
+                return localVarCnt;
+            }
+        }
+
+        public bool IsConstructor
+        {
+            get
+            {
+                return def.IsConstructor;
+            }
+        }
+
+        public bool IsDelegateInvoke
+        {
+            get
+            {
+                return isDelegateInvoke;
+            }
+        }
+
+        public bool IsStatic
+        {
+            get { return def.IsStatic; }
+        }
+
+        public int ParameterCount
+        {
+            get
+            {
+                return paramCnt;
+            }
+        }
+
+
+        public List<IType> Parameters
+        {
+            get
+            {
+                if (def.HasParameters && parameters == null)
+                {
+                    InitParameters();
+                }
+                return parameters;
+            }
+        }
+
+        public IType ReturnType
+        {
+            get;
+            private set;
+        }
+        void InitCodeBody()
+        {
+            if (def.HasBody)
+            {
+                body = new OpCode[def.Body.Instructions.Count];
+                Dictionary<Mono.Cecil.Cil.Instruction, int> addr = new Dictionary<Mono.Cecil.Cil.Instruction, int>();
+                for (int i = 0; i < body.Length; i++)
+                {
+                    var c = def.Body.Instructions[i];
+                    OpCode code = new OpCode();
+                    code.Code = (OpCodeEnum)c.OpCode.Code;
+                    addr[c] = i;
+                    body[i] = code;
+                }
+                for (int i = 0; i < body.Length; i++)
+                {
+                    var c = def.Body.Instructions[i];
+                    InitToken(ref body[i], c.Operand, addr);
+                }
+
+                for (int i = 0; i < def.Body.ExceptionHandlers.Count; i++)
+                {
+                    var eh = def.Body.ExceptionHandlers[i];
+                    if (exceptionHandler == null)
+                        exceptionHandler = new Method.ExceptionHandler[def.Body.ExceptionHandlers.Count];
+                    ExceptionHandler e = new ExceptionHandler();
+                    e.HandlerStart = addr[eh.HandlerStart];
+                    e.HandlerEnd = addr[eh.HandlerEnd] - 1;
+                    e.TryStart = addr[eh.TryStart];
+                    e.TryEnd = addr[eh.TryEnd] - 1;
+                    switch (eh.HandlerType)
+                    {
+                        case Mono.Cecil.Cil.ExceptionHandlerType.Catch:
+                            e.CatchType = appdomain.GetType(eh.CatchType, declaringType, this);
+                            e.HandlerType = ExceptionHandlerType.Catch;
+                            break;
+                        case Mono.Cecil.Cil.ExceptionHandlerType.Finally:
+                            e.HandlerType = ExceptionHandlerType.Finally;
+                            break;
+                        case Mono.Cecil.Cil.ExceptionHandlerType.Fault:
+                            e.HandlerType = ExceptionHandlerType.Fault;
+                            break;
+                        default:
+                            throw new NotImplementedException();
+                    }
+                    exceptionHandler[i] = e;
+                    //Mono.Cecil.Cil.ExceptionHandlerType.
+                }
+            }
+            else
+                body = new OpCode[0];
+        }
+
+        unsafe void InitToken(ref OpCode code, object token, Dictionary<Mono.Cecil.Cil.Instruction, int> addr)
+        {
+            switch (code.Code)
+            {
+                case OpCodeEnum.Leave:
+                case OpCodeEnum.Leave_S:
+                case OpCodeEnum.Br:
+                case OpCodeEnum.Br_S:
+                case OpCodeEnum.Brtrue:
+                case OpCodeEnum.Brtrue_S:
+                case OpCodeEnum.Brfalse:
+                case OpCodeEnum.Brfalse_S:
+                //比较流程控制
+                case OpCodeEnum.Beq:
+                case OpCodeEnum.Beq_S:
+                case OpCodeEnum.Bne_Un:
+                case OpCodeEnum.Bne_Un_S:
+                case OpCodeEnum.Bge:
+                case OpCodeEnum.Bge_S:
+                case OpCodeEnum.Bge_Un:
+                case OpCodeEnum.Bge_Un_S:
+                case OpCodeEnum.Bgt:
+                case OpCodeEnum.Bgt_S:
+                case OpCodeEnum.Bgt_Un:
+                case OpCodeEnum.Bgt_Un_S:
+                case OpCodeEnum.Ble:
+                case OpCodeEnum.Ble_S:
+                case OpCodeEnum.Ble_Un:
+                case OpCodeEnum.Ble_Un_S:
+                case OpCodeEnum.Blt:
+                case OpCodeEnum.Blt_S:
+                case OpCodeEnum.Blt_Un:
+                case OpCodeEnum.Blt_Un_S:
+                    code.TokenInteger = addr[(Mono.Cecil.Cil.Instruction)token];
+                    break;
+                case OpCodeEnum.Ldc_I4:
+                    code.TokenInteger = (int)token;
+                    break;
+                case OpCodeEnum.Ldc_I4_S:
+                    code.TokenInteger = (sbyte)token;
+                    break;
+                case OpCodeEnum.Ldc_I8:
+                    code.TokenLong = (long)token;
+                    break;
+                case OpCodeEnum.Ldc_R4:
+                    {
+                        float val = (float)token;
+                        code.TokenInteger = *(int*)&val;
+                    }
+                    break;
+                case OpCodeEnum.Ldc_R8:
+                    {
+                        double val = (double)token;
+                        code.TokenLong = *(long*)&val;
+                    }
+                    break;
+                case OpCodeEnum.Stloc:
+                case OpCodeEnum.Stloc_S:
+                case OpCodeEnum.Ldloc:
+                case OpCodeEnum.Ldloc_S:
+                case OpCodeEnum.Ldloca:
+                case OpCodeEnum.Ldloca_S:
+                    {
+                        Mono.Cecil.Cil.VariableDefinition vd = (Mono.Cecil.Cil.VariableDefinition)token;
+                        code.TokenInteger = vd.Index;
+                    }
+                    break;
+                case OpCodeEnum.Ldarg_S:
+                case OpCodeEnum.Ldarg:
+                case OpCodeEnum.Ldarga:
+                case OpCodeEnum.Ldarga_S:
+                case OpCodeEnum.Starg:
+                case OpCodeEnum.Starg_S:
+                    {
+                        Mono.Cecil.ParameterDefinition vd = (Mono.Cecil.ParameterDefinition)token;
+                        code.TokenInteger = vd.Index;
+                        if (HasThis)
+                            code.TokenInteger++;
+                    }
+                    break;
+                case OpCodeEnum.Call:
+                case OpCodeEnum.Newobj:
+                case OpCodeEnum.Ldftn:
+                case OpCodeEnum.Ldvirtftn:
+                case OpCodeEnum.Callvirt:
+                    {
+                        bool invalidToken;
+                        var m = appdomain.GetMethod(token, declaringType, this, out invalidToken);
+                        if (m != null)
+                        {
+                            if (invalidToken)
+                                code.TokenInteger = m.GetHashCode();
+                            else
+                                code.TokenInteger = token.GetHashCode();
+                        }
+                    }
+                    break;
+                case OpCodeEnum.Constrained:
+                case OpCodeEnum.Box:
+                case OpCodeEnum.Unbox_Any:
+                case OpCodeEnum.Unbox:
+                case OpCodeEnum.Initobj:
+                case OpCodeEnum.Isinst:
+                case OpCodeEnum.Newarr:
+                case OpCodeEnum.Stobj:
+                case OpCodeEnum.Ldobj:
+                    {
+                        code.TokenInteger = GetTypeTokenHashCode(token);
+                    }
+                    break;
+                case OpCodeEnum.Stfld:
+                case OpCodeEnum.Ldfld:
+                case OpCodeEnum.Ldflda:
+                    {
+                        code.TokenInteger = appdomain.GetFieldIndex(token, declaringType, this);
+                    }
+                    break;
+
+                case OpCodeEnum.Stsfld:
+                case OpCodeEnum.Ldsfld:
+                case OpCodeEnum.Ldsflda:
+                    {
+                        code.TokenLong = appdomain.GetStaticFieldIndex(token, declaringType, this);
+                    }
+                    break;
+                case OpCodeEnum.Ldstr:
+                    {
+                        long hashCode = appdomain.CacheString(token);
+                        code.TokenLong = hashCode;
+                    }
+                    break;
+                case OpCodeEnum.Ldtoken:
+                    {
+                        if (token is FieldReference)
+                        {
+                            code.TokenInteger = 0;
+                            code.TokenLong = appdomain.GetStaticFieldIndex(token, declaringType, this);
+                        }
+                        else if (token is TypeReference)
+                        {
+                            code.TokenInteger = 1;
+                            code.TokenLong = GetTypeTokenHashCode(token);
+                        }
+                        else
+                            throw new NotImplementedException();
+                    }
+                    break;
+                case OpCodeEnum.Switch:
+                    {
+                        PrepareJumpTable(token, addr);
+                        code.TokenInteger = token.GetHashCode();
+                    }
+                    break;
+            }
+        }
+
+        int GetTypeTokenHashCode(object token)
+        {
+            var t = appdomain.GetType(token, declaringType, this);
+            bool isGenericParameter = token is TypeReference && ((TypeReference)token).IsGenericParameter;
+            if (t == null && isGenericParameter)
+            {
+                t = FindGenericArgument(((TypeReference)token).Name);
+            }
+            if (t != null)
+            {
+                if (t is ILType)
+                {
+                    return ((ILType)t).TypeReference.GetHashCode();
+                }
+                else if (isGenericParameter)
+                {
+                    return t.TypeForCLR.GetHashCode();
+                }
+                else
+                    return token.GetHashCode();
+            }
+            return 0;
+        }
+
+        void PrepareJumpTable(object token, Dictionary<Mono.Cecil.Cil.Instruction, int> addr)
+        {
+            int hashCode = token.GetHashCode();
+
+            if (jumptables == null)
+                jumptables = new Dictionary<int, int[]>();
+            if (jumptables.ContainsKey(hashCode))
+                return;
+            Mono.Cecil.Cil.Instruction[] e = token as Mono.Cecil.Cil.Instruction[];
+            int[] addrs = new int[e.Length];
+            for (int i = 0; i < e.Length; i++)
+            {
+                addrs[i] = addr[e[i]];
+            }
+
+            jumptables[hashCode] = addrs;
+        }
+
+        void InitParameters()
+        {
+            parameters = new List<IType>();
+            foreach (var i in def.Parameters)
+            {
+                IType type = null;
+                bool isByRef = false;
+                bool isArray = false;
+                TypeReference pt = i.ParameterType;
+                if (i.ParameterType.IsByReference)
+                {
+                    isByRef = true;
+                    pt = pt.GetElementType();
+                }
+                if (i.ParameterType.IsArray)
+                {
+                    isArray = true;
+                    pt = pt.GetElementType();
+                }
+                if (pt.IsGenericParameter)
+                {
+                    type = FindGenericArgument(pt.Name);
+                    if (type == null && def.HasGenericParameters)
+                    {
+                        bool found = false;
+                        foreach (var j in def.GenericParameters)
+                        {
+                            if (j.Name == pt.Name)
+                            {
+                                found = true;
+                                break;
+                            }
+                        }
+                        if (found)
+                        {
+                            type = new ILGenericParameterType(pt.Name);
+                        }
+                        else
+                            throw new NotSupportedException("Cannot find Generic Parameter " + pt.Name + " in " + def.FullName);
+                    }
+
+                    if (isByRef)
+                        type = type.MakeByRefType();
+                    if (isArray)
+                        type = type.MakeArrayType();
+                }
+                else
+                    type = appdomain.GetType(i.ParameterType, declaringType, this);
+                parameters.Add(type);
+            }
+        }
+
+        public IMethod MakeGenericMethod(IType[] genericArguments)
+        {
+            KeyValuePair<string, IType>[] genericParameters = new KeyValuePair<string, IType>[genericArguments.Length];
+            for (int i = 0; i < genericArguments.Length; i++)
+            {
+                string name = def.GenericParameters[i].Name;
+                IType val = genericArguments[i];
+                genericParameters[i] = new KeyValuePair<string, IType>(name, val);
+            }
+
+            ILMethod m = new ILMethod(def, declaringType, appdomain);
+            m.genericParameters = genericParameters;
+            if (m.def.ReturnType.IsGenericParameter)
+            {
+                m.ReturnType = m.FindGenericArgument(m.def.ReturnType.Name);
+            }
+            return m;
+        }
+
+        public override string ToString()
+        {
+            StringBuilder sb = new StringBuilder();
+            sb.Append(declaringType.FullName);
+            sb.Append('.');
+            sb.Append(Name);
+            sb.Append('(');
+            bool isFirst = true;
+            if (parameters == null)
+                InitParameters();
+            for (int i = 0; i < parameters.Count; i++)
+            {
+                if (isFirst)
+                    isFirst = false;
+                else
+                    sb.Append(", ");
+                sb.Append(parameters[i].Name);
+                sb.Append(' ');
+                sb.Append(def.Parameters[i].Name);
+            }
+            sb.Append(')');
+            return sb.ToString();
+        }
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR/Method/ILMethod.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 4d61dbf18ea786940ad2dda2466cde64
+timeCreated: 1486603950
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 33 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR/Method/IMethod.cs

@@ -0,0 +1,33 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+using ILRuntime.CLR.TypeSystem;
+namespace ILRuntime.CLR.Method
+{
+    public interface IMethod
+    {
+        string Name { get; }
+        int ParameterCount { get; }
+
+        bool HasThis { get; }
+
+        IType DeclearingType { get; }
+
+        IType ReturnType { get; }
+        List<IType> Parameters { get; }
+
+        int GenericParameterCount { get; }
+
+        bool IsGenericInstance { get; }
+
+        bool IsConstructor { get; }
+
+        bool IsDelegateInvoke { get; }
+
+        bool IsStatic { get; }
+
+        IMethod MakeGenericMethod(IType[] genericArguments);
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR/Method/IMethod.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 3ee73b411c3d8c34cbcc5578441c854a
+timeCreated: 1486603950
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 9 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR/TypeSystem.meta

@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: dc9d077bf71a98747bf2b50f52bd9063
+folderAsset: yes
+timeCreated: 1486603934
+licenseType: Pro
+DefaultImporter:
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 468 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR/TypeSystem/CLRType.cs

@@ -0,0 +1,468 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Reflection;
+
+using Mono.Cecil;
+using ILRuntime.CLR.Method;
+namespace ILRuntime.CLR.TypeSystem
+{
+    public class CLRType : IType
+    {
+        Type clrType;
+        Dictionary<string, List<CLRMethod>> methods;
+        ILRuntime.Runtime.Enviorment.AppDomain appdomain;
+        List<CLRMethod> constructors;
+        KeyValuePair<string,IType>[] genericArguments;
+        List<CLRType> genericInstances;
+        Dictionary<string, int> fieldMapping;
+        Dictionary<int, FieldInfo> fieldInfoCache;
+        Dictionary<int, int> fieldTokenMapping;
+        IType byRefType, arrayType;
+        bool isDelegate;
+        IType baseType;
+        bool isBaseTypeInitialized = false;
+        MethodInfo memberwiseClone;
+
+        public Dictionary<int, FieldInfo> Fields
+        {
+            get
+            {
+                if (fieldMapping == null)
+                    InitializeFields();
+                return fieldInfoCache;
+            }
+        }
+        public ILRuntime.Runtime.Enviorment.AppDomain AppDomain
+        {
+            get
+            {
+                return appdomain;
+            }
+        }
+
+        public CLRType(Type clrType, Runtime.Enviorment.AppDomain appdomain)
+        {
+            this.clrType = clrType;
+            this.appdomain = appdomain;
+            isDelegate = clrType.BaseType == typeof(MulticastDelegate);
+        }
+        
+        public bool IsGenericInstance
+        {
+            get
+            {
+                return genericArguments != null;
+            }
+        }
+
+        public KeyValuePair<string, IType>[] GenericArguments
+        {
+            get
+            {
+                return genericArguments;
+            }
+        }
+        public bool HasGenericParameter
+        {
+            get
+            {
+                return clrType.ContainsGenericParameters;
+            }
+        }
+
+        public Type TypeForCLR
+        {
+            get
+            {
+                return clrType;
+            }
+        }
+
+        public Type ReflectionType
+        {
+            get
+            {
+                return clrType;
+            }
+        }
+        public IType ByRefType
+        {
+            get
+            {
+                return byRefType;
+            }
+        }
+        public IType ArrayType
+        {
+            get
+            {
+                return arrayType;
+            }
+        }
+        public bool IsValueType
+        {
+            get
+            {
+                return clrType.IsValueType;
+            }
+        }
+        public bool IsDelegate
+        {
+            get
+            {
+                return isDelegate;
+            }
+        }
+        public string FullName
+        {
+            get
+            {
+                return clrType.FullName;
+            }
+        }
+        public string Name
+        {
+            get
+            {
+                return clrType.Name;
+            }
+        }
+
+        public IType BaseType
+        {
+            get
+            {
+                if (!isBaseTypeInitialized)
+                    InitializeBaseType();
+                return baseType;
+            }
+        }
+
+        public new MethodInfo MemberwiseClone
+        {
+            get
+            {
+                if(clrType.IsValueType && memberwiseClone == null)
+                {
+                    memberwiseClone = clrType.GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
+                }
+                return memberwiseClone;
+            }
+        }
+
+        void InitializeBaseType()
+        {
+            baseType = appdomain.GetType(clrType.BaseType);
+            if (baseType.TypeForCLR == typeof(Enum) || baseType.TypeForCLR == typeof(object) || baseType.TypeForCLR == typeof(ValueType) || baseType.TypeForCLR == typeof(System.Enum))
+            {//都是这样,无所谓
+                baseType = null;
+            }
+            isBaseTypeInitialized = true;
+        }
+
+        public FieldInfo GetField(int hash)
+        {
+            var dic = Fields;
+            FieldInfo res;
+            if (dic.TryGetValue(hash, out res))
+                return res;
+            else if (BaseType != null)
+                return ((CLRType)BaseType).GetField(hash);
+            else
+                return null;
+        }
+
+        void InitializeMethods()
+        {
+            methods = new Dictionary<string, List<CLRMethod>>();
+            constructors = new List<CLRMethod>();
+            foreach (var i in clrType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static))
+            {
+                if (i.IsPrivate)
+                    continue;
+                List<CLRMethod> lst;
+                if (!methods.TryGetValue(i.Name, out lst))
+                {
+                    lst = new List<CLRMethod>();
+                    methods[i.Name] = lst;
+                }
+                lst.Add(new CLRMethod(i, this, appdomain));
+            }
+            foreach (var i in clrType.GetConstructors())
+            {
+                constructors.Add(new CLRMethod(i, this, appdomain));
+            }
+        }
+        public List<IMethod> GetMethods()
+        {
+            if (methods == null)
+                InitializeMethods();
+            List<IMethod> res = new List<IMethod>();
+            foreach (var i in methods)
+            {
+                foreach (var j in i.Value)
+                    res.Add(j);
+            }
+
+            return res;
+        }
+
+        public IMethod GetVirtualMethod(IMethod method)
+        {
+            var m = GetMethod(method.Name, method.Parameters, null, method.ReturnType);
+            if (m == null)
+            {
+                return method;
+            }
+            else
+                return m;
+        }
+
+        void InitializeFields()
+        {
+            fieldMapping = new Dictionary<string, int>();
+            fieldInfoCache = new Dictionary<int, FieldInfo>();
+
+            var fields = clrType.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static);
+            foreach (var i in fields)
+            {
+                if (i.IsPublic || i.IsFamily)
+                {
+                    int hashCode = i.GetHashCode();
+                    fieldMapping[i.Name] = hashCode;
+                    fieldInfoCache[hashCode] = i;
+                }
+            }
+        }
+        public int GetFieldIndex(object token)
+        {
+            if (fieldMapping == null)
+                InitializeFields();
+            int idx;
+            int hashCode = token.GetHashCode();
+            if (fieldTokenMapping == null)
+                fieldTokenMapping = new Dictionary<int, int>();
+            if (fieldTokenMapping.TryGetValue(hashCode, out idx))
+                return idx;
+            FieldReference f = token as FieldReference;
+            if (fieldMapping.TryGetValue(f.Name, out idx))
+            {
+                fieldTokenMapping[hashCode] = idx;
+                return idx;
+            }
+
+            return -1;
+        }
+        public IType FindGenericArgument(string key)
+        {
+            if (genericArguments != null)
+            {
+                foreach (var i in genericArguments)
+                {
+                    if (i.Key == key)
+                        return i.Value;
+                }
+            }
+            return null;
+        }
+        public IMethod GetMethod(string name, int paramCount)
+        {
+            if (methods == null)
+                InitializeMethods();
+            List<CLRMethod> lst;
+            if (methods.TryGetValue(name, out lst))
+            {
+                foreach (var i in lst)
+                {
+                    if (i.ParameterCount == paramCount)
+                        return i;
+                }
+            }
+            return null;
+        }
+
+        public IMethod GetMethod(string name, List<IType> param, IType[] genericArguments, IType returnType = null)
+        {
+            if (methods == null)
+                InitializeMethods();
+            List<CLRMethod> lst;
+            IMethod genericMethod = null;
+            if (methods.TryGetValue(name, out lst))
+            {
+                foreach (var i in lst)
+                {
+                    if (i.ParameterCount == param.Count)
+                    {
+                        bool match = true;
+                        if (genericArguments != null && i.GenericParameterCount == genericArguments.Length)
+                        {
+                            for (int j = 0; j < param.Count; j++)
+                            {
+                                var p = i.Parameters[j].TypeForCLR;
+                                var q = param[j].TypeForCLR;
+
+                                if (i.Parameters[j].HasGenericParameter)
+                                {
+                                    //TODO should match the generic parameters;
+                                    continue;
+                                }
+                                if (q != p)
+                                {
+                                    match = false;
+                                    break;
+                                }
+                            }
+                            if (match)
+                            {
+                                genericMethod = i;
+                                break;
+                            }                            
+                        }
+                        else
+                        {
+                            match = genericArguments == null;
+                            for (int j = 0; j < param.Count; j++)
+                            {
+                                var typeA = param[j].TypeForCLR.IsByRef ? param[j].TypeForCLR.GetElementType() : param[j].TypeForCLR;
+                                var typeB = i.Parameters[j].TypeForCLR.IsByRef ? i.Parameters[j].TypeForCLR.GetElementType() : i.Parameters[j].TypeForCLR;
+
+                                if (typeA != typeB)
+                                {
+                                    match = false;
+                                    break;
+                                }
+                            }
+                            if (match)
+                            {
+                                match = returnType == null || i.ReturnType.TypeForCLR == returnType.TypeForCLR;
+                            }
+                            if (match)
+                            {
+                                
+                                if (i.IsGenericInstance)
+                                {
+                                    if (i.GenericArguments.Length == genericArguments.Length)
+                                    {
+                                        for (int j = 0; j < genericArguments.Length; j++)
+                                        {
+                                            if(i.GenericArguments[j] != genericArguments[j])
+                                            {
+                                                match = false;
+                                                break;
+                                            }
+                                        }
+                                        if (match)
+                                            return i;
+                                    }
+                                }
+                                else
+                                    return i;
+                            }
+                        }
+                    }
+                }
+            }
+            if (genericArguments != null && genericMethod != null)
+            {
+                var m = genericMethod.MakeGenericMethod(genericArguments);
+                lst.Add((CLRMethod)m);
+                return m;
+            }
+            return null;
+        }
+        public bool CanAssignTo(IType type)
+        {
+            if (this == type)
+            {
+                return true;
+            }
+            else
+                return false;
+        }
+
+        public IMethod GetConstructor(List<IType> param)
+        {
+            if (constructors == null)
+                InitializeMethods();
+            foreach (var i in constructors)
+            {
+                if (i.ParameterCount == param.Count)
+                {
+                    bool match = true;
+
+                    for (int j = 0; j < param.Count; j++)
+                    {
+                        if (param[j].TypeForCLR != i.Parameters[j].TypeForCLR)
+                        {
+                            match = false;
+                            break;
+                        }
+                    }
+                    if (match)
+                    {
+                        return i;
+                    }
+                }
+            }
+            
+            return null;
+        }
+
+        public IType MakeGenericInstance(KeyValuePair<string, IType>[] genericArguments)
+        {
+            if (genericInstances == null)
+                genericInstances = new List<CLRType>();
+            foreach (var i in genericInstances)
+            {
+                bool match = true;
+                for (int j = 0; j < genericArguments.Length; j++)
+                {
+                    if (i.genericArguments[j].Value != genericArguments[j].Value)
+                    {
+                        match = false;
+                        break;
+                    }
+                }
+                if (match)
+                    return i;
+            }
+            Type[] args = new Type[genericArguments.Length];
+            for (int i = 0; i < genericArguments.Length; i++)
+            {
+                args[i] = genericArguments[i].Value.TypeForCLR;
+            }
+            Type newType = clrType.MakeGenericType(args);
+            var res = new CLRType(newType, appdomain);
+            res.genericArguments = genericArguments;
+
+            genericInstances.Add(res);
+            return res;
+        }
+
+        public IType MakeByRefType()
+        {
+            if (byRefType == null)
+            {
+                Type t = clrType.MakeByRefType();
+                byRefType = new CLRType(t, appdomain);
+            }
+            return byRefType;
+        }
+        public IType MakeArrayType()
+        {
+            if (arrayType == null)
+            {
+                Type t = clrType.MakeArrayType();
+                arrayType = new CLRType(t, appdomain);
+            }
+            return arrayType;
+        }
+
+        public IType ResolveGenericType(IType contextType)
+        {
+            throw new NotImplementedException();
+        }
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR/TypeSystem/CLRType.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 77e1f51e465e9e24ba3a42bb88b7ad34
+timeCreated: 1486603951
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 162 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR/TypeSystem/ILGenericParameterType.cs

@@ -0,0 +1,162 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace ILRuntime.CLR.TypeSystem
+{
+    class ILGenericParameterType : IType
+    {
+        string name;
+        ILGenericParameterType arrayType;
+        public ILGenericParameterType(string name)
+        {
+            this.name = name;
+        }
+        public bool IsGenericInstance
+        {
+            get { return false; }
+        }
+
+        public KeyValuePair<string, IType>[] GenericArguments
+        {
+            get { return null; }
+        }
+        public bool HasGenericParameter
+        {
+            get
+            {
+                return true;
+            }
+        }
+
+        public Type TypeForCLR
+        {
+            get { return typeof(ILGenericParameterType); }
+        }
+
+        public string FullName
+        {
+            get { return name; }
+        }
+
+        public Runtime.Enviorment.AppDomain AppDomain
+        {
+            get { return null; }
+        }
+
+        public Method.IMethod GetMethod(string name, int paramCount)
+        {
+            return null;
+        }
+
+        public Method.IMethod GetMethod(string name, List<IType> param, IType[] genericArguments, IType returnType = null)
+        {
+            return null;
+        }
+
+        public List<Method.IMethod> GetMethods()
+        {
+            return null;
+        }
+
+        public Method.IMethod GetConstructor(List<IType> param)
+        {
+            return null;
+        }
+
+        public bool CanAssignTo(IType type)
+        {
+            return false;
+        }
+
+        public IType MakeGenericInstance(KeyValuePair<string, IType>[] genericArguments)
+        {
+            return null;
+        }
+
+        public IType ResolveGenericType(IType contextType)
+        {
+            throw new NotImplementedException();
+        }
+
+
+        public int GetFieldIndex(object token)
+        {
+            return -1;
+        }
+
+
+        public IType FindGenericArgument(string key)
+        {
+            return null;
+        }
+
+
+        public IType ByRefType
+        {
+            get { throw new NotImplementedException(); }
+        }
+
+        public IType MakeByRefType()
+        {
+            return this;
+        }
+
+
+        public IType ArrayType
+        {
+            get { return arrayType; }
+        }
+
+        public IType MakeArrayType()
+        {
+            if (arrayType == null)
+                arrayType = new ILGenericParameterType(name + "[]");
+            return arrayType;
+        }
+
+
+        public bool IsValueType
+        {
+            get { throw new NotImplementedException(); }
+        }
+
+        public string Name
+        {
+            get
+            {
+                return name;
+            }
+        }
+
+        public bool IsDelegate
+        {
+            get
+            {
+                return false;
+            }
+        }
+
+        public Type ReflectionType
+        {
+            get
+            {
+                throw new NotImplementedException();
+            }
+        }
+
+        public IType BaseType
+        {
+            get
+            {
+                return null;
+            }
+        }
+
+        public Method.IMethod GetVirtualMethod(Method.IMethod method)
+        {
+            return method;
+        }
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR/TypeSystem/ILGenericParameterType.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: ea169e3908d84da4088fc6eae41d3c41
+timeCreated: 1486603953
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 863 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR/TypeSystem/ILType.cs

@@ -0,0 +1,863 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+using Mono.Cecil;
+using ILRuntime.Runtime.Enviorment;
+using ILRuntime.CLR.Method;
+using ILRuntime.Runtime.Intepreter;
+using ILRuntime.Reflection;
+
+namespace ILRuntime.CLR.TypeSystem
+{
+    public class ILType : IType
+    {
+        Dictionary<string, List<ILMethod>> methods;
+        TypeReference typeRef;
+        TypeDefinition definition;
+        ILRuntime.Runtime.Enviorment.AppDomain appdomain;
+        ILMethod staticConstructor;
+        List<ILMethod> constructors;
+        IType[] fieldTypes;
+        FieldDefinition[] fieldDefinitions;
+        IType[] staticFieldTypes;
+        FieldDefinition[] staticFieldDefinitions;
+        Dictionary<string, int> fieldMapping;
+        Dictionary<string, int> staticFieldMapping;
+        ILTypeStaticInstance staticInstance;
+        Dictionary<int, int> fieldTokenMapping = new Dictionary<int, int>();
+        int fieldStartIdx = -1;
+        int totalFieldCnt = -1;
+        KeyValuePair<string, IType>[] genericArguments;
+        IType baseType, byRefType, arrayType, enumType;
+        IType[] interfaces;
+        bool baseTypeInitialized = false;
+        bool interfaceInitialized = false;
+        List<ILType> genericInstances;
+        bool isDelegate;
+        ILRuntimeType reflectionType;
+        IType firstCLRBaseType, firstCLRInterface;
+        public TypeDefinition TypeDefinition { get { return definition; } }
+
+        public TypeReference TypeReference
+        {
+            get { return typeRef; }
+            set
+            {
+                typeRef = value;
+                RetriveDefinitino(value);
+            }
+        }
+
+        public IType BaseType
+        {
+            get
+            {
+                if (!baseTypeInitialized)
+                    InitializeBaseType();
+                return baseType;
+            }
+        }
+
+        public IType[] Implements
+        {
+            get
+            {
+                if (!interfaceInitialized)
+                    InitializeInterfaces();
+                return interfaces;
+            }
+        }
+
+        public ILTypeStaticInstance StaticInstance
+        {
+            get
+            {
+                if (fieldMapping == null)
+                    InitializeFields();
+                if (methods == null)
+                    InitializeMethods();
+                return staticInstance;
+            }
+        }
+
+        public IType[] FieldTypes
+        {
+            get
+            {
+                if (fieldMapping == null)
+                    InitializeFields();
+                return fieldTypes;
+            }
+        }
+
+        public IType[] StaticFieldTypes
+        {
+            get
+            {
+                if (fieldMapping == null)
+                    InitializeFields();
+                return staticFieldTypes;
+            }
+        }
+
+        public FieldDefinition[] StaticFieldDefinitions
+        {
+            get
+            {
+                if (fieldMapping == null)
+                    InitializeFields();
+                return staticFieldDefinitions;
+            }
+        }
+
+        public Dictionary<string, int> FieldMapping
+        {
+            get
+            {
+                if (fieldMapping == null)
+                    InitializeFields(); return fieldMapping;
+            }
+        }
+
+        public IType FirstCLRBaseType
+        {
+            get
+            {
+                if (!baseTypeInitialized)
+                    InitializeBaseType();
+                return firstCLRBaseType;
+            }
+        }
+
+        IType FirstCLRInterface
+        {
+            get
+            {
+                if (!interfaceInitialized)
+                    InitializeInterfaces();
+                return firstCLRInterface;
+            }
+        }
+        public bool HasGenericParameter
+        {
+            get
+            {
+                return definition.HasGenericParameters && genericArguments == null;
+            }
+        }
+
+        public Dictionary<string, int> StaticFieldMapping { get { return staticFieldMapping; } }
+        public ILRuntime.Runtime.Enviorment.AppDomain AppDomain
+        {
+            get
+            {
+                return appdomain;
+            }
+        }
+
+        internal int FieldStartIndex
+        {
+            get
+            {
+                if (fieldStartIdx < 0)
+                {
+                    if (BaseType != null)
+                    {
+                        if (BaseType is ILType)
+                        {
+                            fieldStartIdx = ((ILType)BaseType).TotalFieldCount;
+                        }
+                        else
+                            fieldStartIdx = 0;
+                    }
+                    else
+                        fieldStartIdx = 0;
+                }
+                return fieldStartIdx;
+            }
+        }
+
+        public int TotalFieldCount
+        {
+            get
+            {
+                if (totalFieldCnt < 0)
+                {
+                    if (fieldMapping == null)
+                        InitializeFields();
+                    if (BaseType != null)
+                    {
+                        if (BaseType is ILType)
+                        {
+                            totalFieldCnt = ((ILType)BaseType).TotalFieldCount + fieldTypes.Length;
+                        }
+                        else
+                            totalFieldCnt = fieldTypes.Length;
+                    }
+                    else
+                        totalFieldCnt = fieldTypes.Length;
+                }
+                return totalFieldCnt;
+            }
+        }
+
+        /// <summary>
+        /// 初始化IL类型
+        /// </summary>
+        /// <param name="def">MONO返回的类型定义</param>
+        /// <param name="domain">ILdomain</param>
+        public ILType(TypeReference def, Runtime.Enviorment.AppDomain domain)
+        {
+            this.typeRef = def;
+            RetriveDefinitino(def);
+            appdomain = domain;
+        }
+
+        /// <summary>
+        /// 加载类型
+        /// </summary>
+        /// <param name="def"></param>
+        void RetriveDefinitino(TypeReference def)
+        {
+            TypeReference res;
+            if (def is GenericInstanceType)
+            {
+                res = ((GenericInstanceType)def).ElementType;
+            }
+            else if (def is ByReferenceType)
+            {
+                res = ((ByReferenceType)def).ElementType;
+            }
+            else if (def.IsArray)
+            {
+                res = (TypeDefinition)def.GetElementType();
+            }
+            else
+                res = (TypeDefinition)def;
+
+
+            if (!res.IsGenericParameter)
+            {
+                definition = res as TypeDefinition;
+            }
+
+        }
+
+        public bool IsGenericInstance
+        {
+            get
+            {
+                return genericArguments != null;
+            }
+        }
+        public KeyValuePair<string, IType>[] GenericArguments
+        {
+            get
+            {
+                return genericArguments;
+            }
+        }
+
+        public bool IsValueType
+        {
+            get
+            {
+                return definition.IsValueType;
+            }
+        }
+
+        public bool IsDelegate
+        {
+            get
+            {
+                if (!baseTypeInitialized)
+                    InitializeBaseType();
+                return isDelegate;
+            }
+        }
+
+        public Type TypeForCLR
+        {
+            get
+            {
+                if (!baseTypeInitialized)
+                    InitializeBaseType();
+                if (definition.IsEnum)
+                {
+                    if (enumType == null)
+                        InitializeFields();
+                    if (enumType == null)
+                    {
+
+                    }
+                    return enumType.TypeForCLR;
+                }
+                else if (FirstCLRBaseType != null && FirstCLRBaseType is CrossBindingAdaptor)
+                {
+                    return ((CrossBindingAdaptor)FirstCLRBaseType).RuntimeType.TypeForCLR;
+                }
+                else if (FirstCLRInterface != null && FirstCLRInterface is CrossBindingAdaptor)
+                {
+                    return ((CrossBindingAdaptor)FirstCLRInterface).RuntimeType.TypeForCLR;
+                }
+                else
+                    return typeof(ILTypeInstance);
+            }
+        }
+
+        public Type ReflectionType
+        {
+            get
+            {
+                if (reflectionType == null)
+                    reflectionType = new ILRuntimeType(this);
+                return reflectionType;
+            }
+        }
+
+        public IType ByRefType
+        {
+            get
+            {
+                return byRefType;
+            }
+        }
+        public IType ArrayType
+        {
+            get
+            {
+                return arrayType;
+            }
+        }
+
+        public bool IsEnum
+        {
+            get
+            {
+                return definition.IsEnum;
+            }
+        }
+        public string FullName
+        {
+            get
+            {
+                return typeRef.FullName;
+            }
+        }
+        public string Name
+        {
+            get
+            {
+                return typeRef.Name;
+            }
+        }
+        public List<IMethod> GetMethods()
+        {
+            if (methods == null)
+                InitializeMethods();
+            List<IMethod> res = new List<IMethod>();
+            foreach (var i in methods)
+            {
+                foreach (var j in i.Value)
+                    res.Add(j);
+            }
+
+            return res;
+        }
+        void InitializeInterfaces()
+        {
+            interfaceInitialized = true;
+            if (definition.HasInterfaces)
+            {
+                interfaces = new IType[definition.Interfaces.Count];
+                for (int i = 0; i < interfaces.Length; i++)
+                {
+                    interfaces[i] = appdomain.GetType(definition.Interfaces[i], this, null);
+                    if (interfaces[i] is CLRType)
+                    {
+                        CrossBindingAdaptor adaptor;
+                        if (appdomain.CrossBindingAdaptors.TryGetValue(interfaces[i].TypeForCLR, out adaptor))
+                        {
+                            interfaces[i] = adaptor;
+                            firstCLRInterface = adaptor;
+                        }
+                        else
+                            throw new TypeLoadException("Cannot find Adaptor for:" + interfaces[i].TypeForCLR.ToString());
+                    }
+                }
+            }
+        }
+        void InitializeBaseType()
+        {
+            baseTypeInitialized = true;
+            if (definition.BaseType != null)
+            {
+                baseType = appdomain.GetType(definition.BaseType, this, null);
+                if (baseType is CLRType)
+                {
+                    if (baseType.TypeForCLR == typeof(Enum) || baseType.TypeForCLR == typeof(object) || baseType.TypeForCLR == typeof(ValueType) || baseType.TypeForCLR == typeof(System.Enum))
+                    {//都是这样,无所谓
+                        baseType = null;
+                    }
+                    else if (baseType.TypeForCLR == typeof(MulticastDelegate))
+                    {
+                        baseType = null;
+                        isDelegate = true;
+                    }
+                    else
+                    {
+                        CrossBindingAdaptor adaptor;
+                        if (appdomain.CrossBindingAdaptors.TryGetValue(baseType.TypeForCLR, out adaptor))
+                        {
+                            baseType = adaptor;
+                        }
+                        else
+                            throw new TypeLoadException("Cannot find Adaptor for:" + baseType.TypeForCLR.ToString());
+                        //继承了其他系统类型
+                        //env.logger.Log_Error("ScriptType:" + Name + " Based On a SystemType:" + BaseType.Name);
+                        //HasSysBase = true;
+                        //throw new Exception("不得继承系统类型,脚本类型系统和脚本类型系统是隔离的");
+                    }
+                }
+            }
+            var curBase = baseType;
+            while (curBase is ILType)
+            {
+                curBase = curBase.BaseType;
+            }
+            firstCLRBaseType = curBase;
+        }
+
+        public IMethod GetMethod(string name)
+        {
+            if (methods == null)
+                InitializeMethods();
+            List<ILMethod> lst;
+            if (methods.TryGetValue(name, out lst))
+            {
+                return lst[0];
+            }
+            return null;
+        }
+
+        public IMethod GetMethod(string name, int paramCount)
+        {
+            if (methods == null)
+                InitializeMethods();
+            List<ILMethod> lst;
+            if (methods.TryGetValue(name, out lst))
+            {
+                foreach (var i in lst)
+                {
+                    if (i.ParameterCount == paramCount)
+                        return i;
+                }
+            }
+            return null;
+        }
+
+        void InitializeMethods()
+        {
+            methods = new Dictionary<string, List<ILMethod>>();
+            constructors = new List<ILMethod>();
+            foreach (var i in definition.Methods)
+            {
+                if (i.IsConstructor)
+                {
+                    if (i.IsStatic)
+                        staticConstructor = new ILMethod(i, this, appdomain);
+                    else
+                        constructors.Add(new ILMethod(i, this, appdomain));
+                }
+                else
+                {
+                    List<ILMethod> lst;
+                    if (!methods.TryGetValue(i.Name, out lst))
+                    {
+                        lst = new List<ILMethod>();
+                        methods[i.Name] = lst;
+                    }
+                    var m = new ILMethod(i, this, appdomain);
+                    lst.Add(new ILMethod(i, this, appdomain));
+                }
+            }
+
+            if (staticConstructor != null)
+            {
+                appdomain.Invoke(staticConstructor, null, null);
+            }
+        }
+
+        public IMethod GetVirtualMethod(IMethod method)
+        {
+            var m = GetMethod(method.Name, method.Parameters, null, method.ReturnType);
+            if (m == null)
+            {
+                if (BaseType != null)
+                {
+                    return BaseType.GetVirtualMethod(method);
+                }
+                else
+                    return null;//BaseType == null means base type is Object or Enum
+            }
+            else if (m.IsGenericInstance == method.IsGenericInstance)
+                return m;
+            else
+                return method;
+        }
+
+        public IMethod GetMethod(string name, List<IType> param, IType[] genericArguments, IType returnType = null)
+        {
+            if (methods == null)
+                InitializeMethods();
+            List<ILMethod> lst;
+            IMethod genericMethod = null;
+            if (methods.TryGetValue(name, out lst))
+            {
+                foreach (var i in lst)
+                {
+                    int pCnt = param != null ? param.Count : 0;
+                    if (i.ParameterCount == pCnt)
+                    {
+                        bool match = true;
+                        if (genericArguments != null && i.GenericParameterCount == genericArguments.Length)
+                        {
+                            genericMethod = CheckGenericParams(i, param, ref match);
+                            if (genericMethod != null)
+                                break;
+                        }
+                        else
+                        {
+                            match = genericArguments == null;
+                            for (int j = 0; j < pCnt; j++)
+                            {
+                                if (param[j] != i.Parameters[j])
+                                {
+                                    match = false;
+                                    break;
+                                }
+                            }
+                            if (match)
+                            {
+                                match = returnType == null || i.ReturnType == returnType;
+                            }
+                            if (match)
+                                return i;
+                        }
+                    }
+                }
+            }
+            if (genericArguments != null && genericMethod != null)
+            {
+                var m = genericMethod.MakeGenericMethod(genericArguments);
+                lst.Add((ILMethod)m);
+                return m;
+            }
+            return null;
+        }
+
+        ILMethod CheckGenericParams(ILMethod i, List<IType> param, ref bool match)
+        {
+            ILMethod genericMethod = null;
+            for (int j = 0; j < param.Count; j++)
+            {
+                var p = i.Parameters[j];
+                if (p.HasGenericParameter)
+                {
+                    //TODO should match the generic parameters;
+                    continue;
+                }
+
+                if (param[j] != p)
+                {
+                    match = false;
+                    break;
+                }
+            }
+            if (match)
+            {
+                genericMethod = i;
+            }
+            return genericMethod;
+        }
+
+        public IMethod GetConstructor(int paramCnt)
+        {
+            if (constructors == null)
+                InitializeMethods();
+            foreach (var i in constructors)
+            {
+                if (i.ParameterCount == paramCnt)
+                {
+                    return i;
+                }
+            }
+            return null;
+        }
+
+        public IMethod GetConstructor(List<IType> param)
+        {
+            if (constructors == null)
+                InitializeMethods();
+            foreach (var i in constructors)
+            {
+                if (i.ParameterCount == param.Count)
+                {
+                    bool match = true;
+
+                    for (int j = 0; j < param.Count; j++)
+                    {
+                        if (param[j] != i.Parameters[j])
+                        {
+                            match = false;
+                            break;
+                        }
+                    }
+
+                    if (match)
+                        return i;
+                }
+            }
+            return null;
+        }
+
+        public int GetFieldIndex(object token)
+        {
+            if (fieldMapping == null)
+                InitializeFields();
+            int idx;
+            int hashCode = token.GetHashCode();
+            if (fieldTokenMapping.TryGetValue(hashCode, out idx))
+                return idx;
+            FieldReference f = token as FieldReference;
+            if (staticFieldMapping != null && staticFieldMapping.TryGetValue(f.Name, out idx))
+            {
+                fieldTokenMapping[hashCode] = idx;
+                return idx;
+            }
+            if (fieldMapping.TryGetValue(f.Name, out idx))
+            {
+                fieldTokenMapping[hashCode] = idx;
+                return idx;
+            }
+
+            return -1;
+        }
+
+        public IType GetField(string name, out int fieldIdx)
+        {
+            if (fieldMapping == null)
+                InitializeFields();
+            if (fieldMapping.TryGetValue(name, out fieldIdx))
+            {
+                return fieldTypes[fieldIdx - FieldStartIndex];
+            }
+            else if (BaseType != null && BaseType is ILType)
+            {
+                return ((ILType)BaseType).GetField(name, out fieldIdx);
+            }
+            else
+                return null;
+        }
+
+        public IType GetField(int fieldIdx, out FieldDefinition fd)
+        {
+            if (fieldMapping == null)
+                InitializeFields();
+            if (fieldIdx < FieldStartIndex)
+                return ((ILType)BaseType).GetField(fieldIdx, out fd);
+            else
+            {
+                fd = fieldDefinitions[fieldIdx - FieldStartIndex];
+                return fieldTypes[fieldIdx - FieldStartIndex];
+            }
+        }
+
+        void InitializeFields()
+        {
+            fieldMapping = new Dictionary<string, int>();
+            fieldTypes = new IType[definition.Fields.Count];
+            fieldDefinitions = new FieldDefinition[definition.Fields.Count];
+            var fields = definition.Fields;
+            int idx = FieldStartIndex;
+            int idxStatic = 0;
+            for (int i = 0; i < fields.Count; i++)
+            {
+                var field = fields[i];
+                if (field.IsStatic)
+                {
+                    if (staticFieldTypes == null)
+                    {
+                        staticFieldTypes = new IType[definition.Fields.Count];
+                        staticFieldDefinitions = new FieldDefinition[definition.Fields.Count];
+                        staticFieldMapping = new Dictionary<string, int>();
+                    }
+                    staticFieldMapping[field.Name] = idxStatic;
+                    staticFieldDefinitions[idxStatic] = field;
+                    if (field.FieldType.IsGenericParameter)
+                    {
+                        staticFieldTypes[idxStatic] = FindGenericArgument(field.FieldType.Name);
+                    }
+                    else
+                        staticFieldTypes[idxStatic] = appdomain.GetType(field.FieldType, this, null);
+                    idxStatic++;
+                }
+                else
+                {
+                    fieldMapping[field.Name] = idx;
+                    fieldDefinitions[idx - FieldStartIndex] = field;
+                    if (field.FieldType.IsGenericParameter)
+                    {
+                        fieldTypes[idx - FieldStartIndex] = FindGenericArgument(field.FieldType.Name);
+                    }
+                    else
+                        fieldTypes[idx - FieldStartIndex] = appdomain.GetType(field.FieldType, this, null);
+                    if (IsEnum)
+                    {
+                        enumType = fieldTypes[idx - FieldStartIndex];
+                    }
+                    idx++;
+                }
+            }
+            Array.Resize(ref fieldTypes, idx - FieldStartIndex);
+            Array.Resize(ref fieldDefinitions, idx - FieldStartIndex);
+
+            if (staticFieldTypes != null)
+            {
+                Array.Resize(ref staticFieldTypes, idxStatic);
+                Array.Resize(ref staticFieldDefinitions, idxStatic);
+                staticInstance = new ILTypeStaticInstance(this);
+            }
+        }
+
+        public IType FindGenericArgument(string key)
+        {
+            if (genericArguments != null)
+            {
+                foreach (var i in genericArguments)
+                {
+                    if (i.Key == key)
+                        return i.Value;
+                }
+            }
+            return null;
+        }
+
+        public bool CanAssignTo(IType type)
+        {
+            if (this == type)
+            {
+                return true;
+            }
+            else if (BaseType != null)
+                return BaseType.CanAssignTo(type);
+            else if (Implements != null)
+            {
+                for (int i = 0; i < interfaces.Length; i++)
+                {
+                    var im = interfaces[i];
+                    bool res = im.CanAssignTo(type);
+                    if (res)
+                        return true;
+                }
+            }
+            return false;
+        }
+
+        public ILTypeInstance Instantiate(bool callDefaultConstructor = true)
+        {
+            var res = new ILTypeInstance(this);
+            if (callDefaultConstructor)
+            {
+                var m = GetConstructor(CLR.Utils.Extensions.EmptyParamList);
+                if (m != null)
+                {
+                    appdomain.Invoke(m, res, null);
+                }
+            }
+            return res;
+        }
+        public IType MakeGenericInstance(KeyValuePair<string, IType>[] genericArguments)
+        {
+            if (genericInstances == null)
+                genericInstances = new List<ILType>();
+            foreach (var i in genericInstances)
+            {
+                bool match = true;
+                for (int j = 0; j < genericArguments.Length; j++)
+                {
+                    if (i.genericArguments[j].Value != genericArguments[j].Value)
+                    {
+                        match = false;
+                        break;
+                    }
+                }
+                if (match)
+                    return i;
+            }
+            var res = new ILType(definition, appdomain);
+            res.genericArguments = genericArguments;
+
+            genericInstances.Add(res);
+            return res;
+        }
+
+        public IType MakeByRefType()
+        {
+            if (byRefType == null)
+            {
+                var def = new ByReferenceType(typeRef);
+                byRefType = new ILType(def, appdomain);
+            }
+            return byRefType;
+        }
+
+        public IType MakeArrayType()
+        {
+            if (arrayType == null)
+            {
+                var def = new ArrayType(typeRef);
+                arrayType = new ILType(def, appdomain);
+            }
+            return arrayType;
+        }
+
+        public IType ResolveGenericType(IType contextType)
+        {
+            var ga = contextType.GenericArguments;
+            IType[] kv = new IType[definition.GenericParameters.Count];
+            for (int i = 0; i < kv.Length; i++)
+            {
+                var gp = definition.GenericParameters[i];
+                string name = gp.Name;
+                foreach (var j in ga)
+                {
+                    if (j.Key == name)
+                    {
+                        kv[i] = j.Value;
+                        break;
+                    }
+                }
+            }
+
+            foreach (var i in genericInstances)
+            {
+                bool match = true;
+                for (int j = 0; j < kv.Length; j++)
+                {
+                    if (i.genericArguments[j].Value != kv[j])
+                    {
+                        match = false;
+                        break;
+                    }
+                }
+                if (match)
+                    return i;
+            }
+
+            return null;
+        }
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR/TypeSystem/ILType.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: a657d8c53554fdb498c23061939379d5
+timeCreated: 1486603952
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 57 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR/TypeSystem/IType.cs

@@ -0,0 +1,57 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+using ILRuntime.CLR.Method;
+
+namespace ILRuntime.CLR.TypeSystem
+{
+    public interface IType
+    {
+        bool IsGenericInstance { get; }
+        KeyValuePair<string, IType>[] GenericArguments { get; }
+        Type TypeForCLR { get; }
+        Type ReflectionType { get; }
+
+        IType BaseType { get; }
+
+        IType ByRefType { get; }
+
+        IType ArrayType { get; }
+
+        string FullName { get; }
+
+        string Name { get; }
+
+        bool IsValueType { get; }
+
+        bool IsDelegate { get; }
+
+        bool HasGenericParameter { get; }
+
+        ILRuntime.Runtime.Enviorment.AppDomain AppDomain { get; }
+
+        IMethod GetMethod(string name, int paramCount);
+
+        IMethod GetMethod(string name, List<IType> param, IType[] genericArguments, IType returnType = null);
+        IMethod GetVirtualMethod(IMethod method);
+
+        List<IMethod> GetMethods();
+
+        int GetFieldIndex(object token);
+
+        IMethod GetConstructor(List<IType> param);
+
+        bool CanAssignTo(IType type);
+
+        IType MakeGenericInstance(KeyValuePair<string, IType>[] genericArguments);
+
+        IType MakeByRefType();
+
+        IType MakeArrayType();
+        IType FindGenericArgument(string key);
+
+        IType ResolveGenericType(IType contextType);
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR/TypeSystem/IType.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 2d59f9c8b6bc1b542a95502fa20ddea8
+timeCreated: 1486603950
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 9 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR/Utils.meta

@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: 5f09998325ae1e74e82ad6cb5c0b6897
+folderAsset: yes
+timeCreated: 1486603934
+licenseType: Pro
+DefaultImporter:
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 165 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR/Utils/Extensions.cs

@@ -0,0 +1,165 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+using ILRuntime.CLR.TypeSystem;
+using ILRuntime.CLR.Method;
+using Mono.Cecil;
+using ILRuntime.Runtime.Intepreter;
+namespace ILRuntime.CLR.Utils
+{
+    public delegate TResult Func<T1, T2, T3, T4, T5, TResult>(T1 a1, T2 a2, T3 a3, T4 a4, T5 a5);
+
+    public static class Extensions
+    {
+        public static List<IType> EmptyParamList = new List<IType>();
+        public static List<IType> GetParamList(this MethodReference def, ILRuntime.Runtime.Enviorment.AppDomain appdomain, IType contextType, IMethod contextMethod, IType[] genericArguments)
+        {
+            if (def.HasParameters)
+            {
+                List<IType> param = new List<IType>();
+                var dt = appdomain.GetType(def.DeclaringType, contextType, contextMethod);
+                foreach (var i in def.Parameters)
+                {
+                    IType t = null;
+                    t = appdomain.GetType(i.ParameterType, dt, null);
+                    if (t == null && def.IsGenericInstance)
+                    {
+                        GenericInstanceMethod gim = (GenericInstanceMethod)def;
+                        string name = i.ParameterType.IsByReference ? i.ParameterType.GetElementType().FullName : i.ParameterType.FullName;
+                        
+                        for (int j = 0; j < gim.GenericArguments.Count; j++)
+                        {
+                            var gp = gim.ElementMethod.GenericParameters[j];
+                            var ga = gim.GenericArguments[j];
+                            if (name == gp.Name)
+                            {
+                                t = appdomain.GetType(ga, contextType, contextMethod);
+                                if (t == null && genericArguments != null)
+                                    t = genericArguments[j];
+                                break;
+                            }
+                            else if (name.Contains(gp.Name))
+                            {
+                                if (name == gp.Name)
+                                {
+                                    name = ga.FullName;
+                                }
+                                else if (name == gp.Name + "[]")
+                                {
+                                    name = ga.FullName + "[]";
+                                }
+                                else
+                                {
+                                    /*name = name.Replace("<" + gp.Name + ">", "<" + ga.FullName + ">");
+                                    name = name.Replace("<" + gp.Name + "[", "<" + ga.FullName + "[");
+                                    name = name.Replace("<" + gp.Name + ",", "<" + ga.FullName + ",");
+                                    name = name.Replace("," + gp.Name + ">", "," + ga.FullName + ">");
+                                    name = name.Replace("," + gp.Name + "[", "," + ga.FullName + "[");
+                                    name = name.Replace("," + gp.Name + ",", "," + ga.FullName + ",");
+                                    name = name.Replace("," + gp.Name + "[", "," + ga.FullName + "[");*/
+                                    name = ReplaceGenericArgument(name, gp.Name, ga.FullName);
+                                }
+                            }
+                        }
+                        if (t == null)
+                            t = appdomain.GetType(name);
+                    }
+
+                    param.Add(t);
+                }
+                return param;
+            }
+            else
+                return EmptyParamList;
+        }
+
+        static string ReplaceGenericArgument(string typename, string argumentName, string argumentType)
+        {
+            string baseType;
+            StringBuilder sb = new StringBuilder();
+            List<string> ga;
+            bool isArray;
+            Runtime.Enviorment.AppDomain.ParseGenericType(typename, out baseType, out ga, out isArray);
+            if (baseType == argumentName)
+                sb.Append(argumentType);
+            else
+                sb.Append(baseType);
+            if (ga != null && ga.Count > 0)
+            {
+                sb.Append("<");
+                bool isFirst = true;
+                foreach(var i in ga)
+                {
+                    if (isFirst)
+                        isFirst = false;
+                    else
+                        sb.Append(",");
+
+                    sb.Append(ReplaceGenericArgument(i, argumentName, argumentType));
+                }
+                sb.Append(">");
+            }
+            if (isArray)
+                sb.Append("[]");
+            return sb.ToString();
+        }
+
+        public static object CheckCLRTypes(this Type pt, Runtime.Enviorment.AppDomain domain, object obj)
+        {
+            if (obj == null)
+                return null;
+            if (pt.IsPrimitive && pt != typeof(int))
+            {
+                if (pt == typeof(bool) && !(obj is bool))
+                {
+                    obj = (int)obj == 1;
+                }
+                else if (pt == typeof(byte) && !(obj is byte))
+                    obj = (byte)(int)obj;
+                else if (pt == typeof(short) && !(obj is short))
+                    obj = (short)(int)obj;
+                else if (pt == typeof(char) && !(obj is char))
+                    obj = (char)(int)obj;
+                else if (pt == typeof(ushort) && !(obj is ushort))
+                    obj = (ushort)(int)obj;
+                else if (pt == typeof(uint) && !(obj is uint))
+                    obj = (uint)(int)obj;
+                else if (pt == typeof(sbyte) && !(obj is sbyte))
+                    obj = (sbyte)(int)obj;
+                else if (pt == typeof(ulong) && !(obj is ulong))
+                {
+                    obj = (ulong)(long)obj;
+                }
+            }
+            else if (pt == typeof(Delegate) || pt.IsSubclassOf(typeof(Delegate)))
+            {
+                if (obj is Delegate)
+                    return obj;
+                if (pt == typeof(Delegate))
+                    return ((IDelegateAdapter)obj).Delegate;
+                return ((IDelegateAdapter)obj).GetConvertor(pt);
+            }
+            else if (pt.IsByRef)
+            {
+                return CheckCLRTypes(pt.GetElementType(), domain, obj);
+            }
+            else if (pt.IsEnum)
+            {
+                return Enum.ToObject(pt, obj);
+            }
+            else if (obj is ILTypeInstance)
+            {
+                if (!(obj is ILEnumTypeInstance))
+                {
+                    var ins = (ILTypeInstance)obj;
+                    if (ins.IsValueType)
+                        ins = ins.Clone();
+                    return ins.CLRInstance;
+                }
+            }
+            return obj;
+        }
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/CLR/Utils/Extensions.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: ed1e47ba193179f4b9f21caedbc1b605
+timeCreated: 1486603953
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 9 - 0
Unity/Assets/ILRuntime/ILRuntime/Other.meta

@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: c3d9e18bda0f1f54bb1ec400743f78ee
+folderAsset: yes
+timeCreated: 1486603934
+licenseType: Pro
+DefaultImporter:
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 9 - 0
Unity/Assets/ILRuntime/ILRuntime/Other/DelegateExportAttribute.cs

@@ -0,0 +1,9 @@
+namespace ILRuntime.Other
+{
+    /// <summary>
+    /// A Delegate Custom Attr, It tells the CodeGenerationTools : this delegate need to register a delegate convertor,when generate ILRuntimeHelper.cs file.
+    /// </summary>
+    public class DelegateExportAttribute : System.Attribute
+    {
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/Other/DelegateExportAttribute.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: eb007a85cca9ce54ea6e3b32ab7ddceb
+timeCreated: 1486603953
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 10 - 0
Unity/Assets/ILRuntime/ILRuntime/Other/NeedAdaptorAttribute.cs

@@ -0,0 +1,10 @@
+namespace ILRuntime.Other
+{
+    /// <summary>
+    /// A Class Custom Attr, It tells the CodeGenerationTools :there is a class need to generate an adaptor for ILScript
+    /// </summary>
+    public class NeedAdaptorAttribute : System.Attribute
+    {
+
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/Other/NeedAdaptorAttribute.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: fd1e000bd78872247b5ee948842785e9
+timeCreated: 1486603953
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 9 - 0
Unity/Assets/ILRuntime/ILRuntime/Reflection.meta

@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: 4de0bdaa0e6ff7b4696881fd8240823e
+folderAsset: yes
+timeCreated: 1486603934
+licenseType: Pro
+DefaultImporter:
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 79 - 0
Unity/Assets/ILRuntime/ILRuntime/Reflection/Extensions.cs

@@ -0,0 +1,79 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+using Mono.Cecil;
+using ILRuntime.CLR.Method;
+using ILRuntime.CLR.TypeSystem;
+
+namespace ILRuntime.Reflection
+{
+    static class Extensions
+    {
+        public static object CreateInstance(this CustomAttribute attribute, IType at, Runtime.Enviorment.AppDomain appdomain)
+        {
+            object ins;
+            List<IType> param = null;
+            if (at is ILType)
+            {
+                var it = (ILType)at;
+                if (!attribute.HasConstructorArguments)
+                    ins = it.Instantiate(true);
+                else
+                {
+                    ins = it.Instantiate(false);
+                    if (param == null)
+                        param = new List<IType>();
+                    param.Clear();
+                    object[] p = new object[attribute.ConstructorArguments.Count];
+                    for (int j = 0; j < attribute.ConstructorArguments.Count; j++)
+                    {
+                        var ca = attribute.ConstructorArguments[j];
+                        param.Add(appdomain.GetType(ca.Type, null, null));
+                        p[j] = ca.Value;
+                    }
+                    var ctor = it.GetConstructor(param);
+                    appdomain.Invoke(ctor, ins, p);
+                }
+
+                if (attribute.HasProperties)
+                {
+                    object[] p = new object[1];
+                    foreach (var j in attribute.Properties)
+                    {
+                        p[0] = j.Argument.Value;
+                        var setter = it.GetMethod("set_" + j.Name, 1);
+                        appdomain.Invoke(setter, ins, p);
+                    }
+                }
+            }
+            else
+            {
+                param = new List<IType>();
+                object[] p = null;
+                if (attribute.HasConstructorArguments)
+                {
+                    p = new object[attribute.ConstructorArguments.Count];
+                    for (int j = 0; j < attribute.ConstructorArguments.Count; j++)
+                    {
+                        var ca = attribute.ConstructorArguments[j];
+                        param.Add(appdomain.GetType(ca.Type, null, null));
+                        p[j] = ca.Value;
+                    }
+                }
+                ins = ((CLRMethod)at.GetConstructor(param)).ConstructorInfo.Invoke(p);
+                if (attribute.HasProperties)
+                {
+                    foreach (var j in attribute.Properties)
+                    {
+                        var prop = at.TypeForCLR.GetProperty(j.Name);
+                        prop.SetValue(ins, j.Argument.Value, null);
+                    }
+                }
+            }
+
+            return ins;
+        }
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/Reflection/Extensions.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: ccb5490caeef4b7419ab1fc0690f19bd
+timeCreated: 1486603952
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 201 - 0
Unity/Assets/ILRuntime/ILRuntime/Reflection/ILRuntimeFieldInfo.cs

@@ -0,0 +1,201 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Reflection;
+using System.Globalization;
+
+using Mono.Cecil;
+using ILRuntime.CLR.Utils;
+using ILRuntime.CLR.TypeSystem;
+using ILRuntime.Runtime;
+using ILRuntime.Runtime.Stack;
+using ILRuntime.Runtime.Enviorment;
+using ILRuntime.Runtime.Intepreter;
+
+namespace ILRuntime.Reflection
+{
+    public class ILRuntimeFieldInfo : FieldInfo
+    {
+        System.Reflection.FieldAttributes attr = System.Reflection.FieldAttributes.Public;
+        ILRuntimeType dType;
+        ILType ilType;
+        IType fieldType;
+        bool isStatic;
+        int fieldIdx;
+        string name;
+        FieldDefinition definition;
+        Runtime.Enviorment.AppDomain appdomain;
+        object[] customAttributes;
+        Type[] attributeTypes;
+
+        public IType ILFieldType { get { return fieldType; } }
+
+        public ILRuntimeFieldInfo(FieldDefinition def, ILRuntimeType declaredType, bool isStatic, int fieldIdx)
+        {
+            definition = def;
+            this.name = def.Name;
+            dType = declaredType;
+            ilType = dType.ILType;
+            appdomain = ilType.AppDomain;
+            this.isStatic = isStatic;
+            this.fieldIdx = fieldIdx; 
+            if (isStatic)
+                attr |= System.Reflection.FieldAttributes.Static;
+            fieldType = isStatic ? ilType.StaticFieldTypes[fieldIdx] : ilType.FieldTypes[fieldIdx];
+        }
+
+        public ILRuntimeFieldInfo(FieldDefinition def, ILRuntimeType declaredType, int fieldIdx, IType fieldType)
+        {
+            definition = def;
+            this.name = def.Name;
+            dType = declaredType;
+            ilType = dType.ILType;
+            appdomain = ilType.AppDomain;
+            this.isStatic = false;
+            this.fieldIdx = fieldIdx;
+            if (isStatic)
+                attr |= System.Reflection.FieldAttributes.Static;
+            this.fieldType = fieldType;
+        }
+
+        void InitializeCustomAttribute()
+        {
+            customAttributes = new object[definition.CustomAttributes.Count];
+            attributeTypes = new Type[customAttributes.Length];
+            for (int i = 0; i < definition.CustomAttributes.Count; i++)
+            {
+                var attribute = definition.CustomAttributes[i];
+                var at = appdomain.GetType(attribute.AttributeType, null, null);
+                try
+                {
+                    object ins = attribute.CreateInstance(at, appdomain);
+
+                    attributeTypes[i] = at.ReflectionType;
+                    customAttributes[i] = ins;
+                }
+                catch
+                {
+                    attributeTypes[i] = typeof(Attribute);
+                }
+            }
+        }
+        public override System.Reflection.FieldAttributes Attributes
+        {
+            get
+            {
+                return attr;
+            }
+        }
+
+        public override Type DeclaringType
+        {
+            get
+            {
+                return dType;
+            }
+        }
+
+        public override RuntimeFieldHandle FieldHandle
+        {
+            get
+            {
+                throw new NotImplementedException();
+            }
+        }
+
+        public override Type FieldType
+        {
+            get
+            {
+                return fieldType.ReflectionType;
+            }
+        }
+
+        public override string Name
+        {
+            get
+            {
+                return name;
+            }
+        }
+
+        public override Type ReflectedType
+        {
+            get
+            {
+                return fieldType.ReflectionType;
+            }
+        }
+
+        public override object[] GetCustomAttributes(bool inherit)
+        {
+            if (customAttributes == null)
+                InitializeCustomAttribute();
+
+            return customAttributes;
+        }
+
+        public override object[] GetCustomAttributes(Type attributeType, bool inherit)
+        {
+            if (customAttributes == null)
+                InitializeCustomAttribute();
+            List<object> res = new List<object>();
+            for (int i = 0; i < customAttributes.Length; i++)
+            {
+                if (attributeTypes[i] == attributeType)
+                    res.Add(customAttributes[i]);
+            }
+            return res.ToArray();
+        }
+
+        public override object GetValue(object obj)
+        {
+            unsafe
+            {
+                StackObject esp;
+                ILTypeInstance ins;
+                if (isStatic)
+                {
+                    ins = ilType.StaticInstance;
+                }
+                else
+                {
+                    if (obj is ILTypeInstance)
+                        ins = (ILTypeInstance)obj;
+                    else
+                        ins = ((CrossBindingAdaptorType)obj).ILInstance;
+                }
+                return ins[fieldIdx];
+            }
+        }
+
+        public override bool IsDefined(Type attributeType, bool inherit)
+        {
+            throw new NotImplementedException();
+        }
+
+        public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
+        {
+            unsafe
+            {
+                StackObject esp;
+                if (value is CrossBindingAdaptorType)
+                    value = ((CrossBindingAdaptorType)value).ILInstance;
+                ILTypeInstance ins;
+                if (isStatic)
+                {
+                    ins = ilType.StaticInstance;
+                }
+                else
+                {
+                    if (obj is ILTypeInstance)
+                        ins = (ILTypeInstance)obj;
+                    else
+                        ins = ((CrossBindingAdaptorType)obj).ILInstance;
+                }
+                ins[fieldIdx] = value;
+            }
+        }
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/Reflection/ILRuntimeFieldInfo.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 05340a76bcd08e843b481e980988b984
+timeCreated: 1486603950
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 110 - 0
Unity/Assets/ILRuntime/ILRuntime/Reflection/ILRuntimeMethodInfo.cs

@@ -0,0 +1,110 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Reflection;
+using System.Globalization;
+
+using ILRuntime.CLR.Method;
+
+namespace ILRuntime.Reflection
+{
+    public class ILRuntimeMethodInfo : MethodInfo
+    {
+        ILMethod method;
+        public ILRuntimeMethodInfo(ILMethod m)
+        {
+            method = m;
+        }
+
+        internal ILMethod ILMethod { get { return method; } }
+        public override MethodAttributes Attributes
+        {
+            get
+            {
+                return MethodAttributes.Public;
+            }
+        }
+
+        public override Type DeclaringType
+        {
+            get
+            {
+                return method.DeclearingType.ReflectionType;
+            }
+        }
+
+        public override RuntimeMethodHandle MethodHandle
+        {
+            get
+            {
+                throw new NotImplementedException();
+            }
+        }
+
+        public override string Name
+        {
+            get
+            {
+                return method.Name;
+            }
+        }
+
+        public override Type ReflectedType
+        {
+            get
+            {
+                return method.DeclearingType.ReflectionType;
+            }
+        }
+
+        public override ICustomAttributeProvider ReturnTypeCustomAttributes
+        {
+            get
+            {
+                throw new NotImplementedException();
+            }
+        }
+
+        public override MethodInfo GetBaseDefinition()
+        {
+            return this;
+        }
+
+        public override object[] GetCustomAttributes(bool inherit)
+        {
+            throw new NotImplementedException();
+        }
+
+        public override object[] GetCustomAttributes(Type attributeType, bool inherit)
+        {
+            throw new NotImplementedException();
+        }
+
+        public override MethodImplAttributes GetMethodImplementationFlags()
+        {
+            throw new NotImplementedException();
+        }
+
+        public override ParameterInfo[] GetParameters()
+        {
+            throw new NotImplementedException();
+        }
+
+        public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
+        {
+            if (method.HasThis)
+            {
+                var res = method.DeclearingType.AppDomain.Invoke(method, obj, parameters);
+                return res;
+            }
+            else
+                return method.DeclearingType.AppDomain.Invoke(method, null, parameters);
+        }
+
+        public override bool IsDefined(Type attributeType, bool inherit)
+        {
+            throw new NotImplementedException();
+        }
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/Reflection/ILRuntimeMethodInfo.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: e975e373cbb39824c9dbf99b5b834f76
+timeCreated: 1486603952
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 325 - 0
Unity/Assets/ILRuntime/ILRuntime/Reflection/ILRuntimeType.cs

@@ -0,0 +1,325 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Reflection;
+using System.Text;
+using ILRuntime.CLR.TypeSystem;
+using ILRuntime.CLR.Method;
+using ILRuntime.Runtime.Intepreter;
+
+namespace ILRuntime.Reflection
+{
+    public class ILRuntimeType : Type
+    {
+        ILType type;
+        Runtime.Enviorment.AppDomain appdomain;
+        object[] customAttributes;
+        Type[] attributeTypes;
+        ILRuntimeFieldInfo[] fields;
+
+        public ILType ILType { get { return type; } }
+        
+        public ILRuntimeType(ILType t)
+        {
+            type = t;
+            appdomain = t.AppDomain;
+        }
+
+        void InitializeCustomAttribute()
+        {
+            customAttributes = new object[type.TypeDefinition.CustomAttributes.Count];
+            attributeTypes = new Type[customAttributes.Length];
+            for (int i = 0; i < type.TypeDefinition.CustomAttributes.Count; i++)
+            {
+                var attribute = type.TypeDefinition.CustomAttributes[i];
+                var at = appdomain.GetType(attribute.AttributeType, type, null);
+                try
+                {
+                    object ins = attribute.CreateInstance(at, appdomain);
+
+                    attributeTypes[i] = at.ReflectionType;
+                    customAttributes[i] = ins;
+                }
+                catch
+                {
+                    attributeTypes[i] = typeof(Attribute);
+                }               
+            }
+
+        }
+
+        void InitializeFields()
+        {
+            int staticCnt = type.StaticFieldTypes != null ? type.StaticFieldTypes.Length : 0;
+            fields = new ILRuntimeFieldInfo[type.TotalFieldCount + staticCnt];
+            for (int i = 0; i < type.TotalFieldCount; i++)
+            {
+                Mono.Cecil.FieldDefinition fd;
+                var t = type.GetField(i, out fd);
+                fields[i] = new ILRuntimeFieldInfo(fd, this, i, t);
+            }
+            for (int i = type.TotalFieldCount; i < type.TotalFieldCount + staticCnt; i++)
+            {
+                fields[i] = new ILRuntimeFieldInfo(type.StaticFieldDefinitions[i - type.TotalFieldCount], this, true, i - type.TotalFieldCount);
+            }
+        }
+
+        public override Assembly Assembly
+        {
+            get
+            {
+                return typeof(ILRuntimeType).Assembly;
+            }
+        }
+
+        public override string AssemblyQualifiedName
+        {
+            get
+            {
+                return type.FullName;
+            }
+        }
+
+        public override Type BaseType
+        {
+            get
+            {
+                return type.BaseType != null ? type.BaseType.ReflectionType : null;
+            }
+        }
+
+        public override string FullName
+        {
+            get
+            {
+                return type.FullName;
+            }
+        }
+
+        public override Guid GUID
+        {
+            get
+            {
+                throw new NotImplementedException();
+            }
+        }
+
+        public override Module Module
+        {
+            get
+            {
+                throw new NotImplementedException();
+            }
+        }
+
+        public override string Name
+        {
+            get
+            {
+                return type.Name;
+            }
+        }
+
+        public override string Namespace
+        {
+            get
+            {
+                throw new NotImplementedException();
+            }
+        }
+
+        public override Type UnderlyingSystemType
+        {
+            get
+            {
+                return typeof(ILTypeInstance);
+            }
+        }
+
+        public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
+        {
+            throw new NotImplementedException();
+        }
+
+        public override object[] GetCustomAttributes(bool inherit)
+        {
+            if (customAttributes == null)
+                InitializeCustomAttribute();
+
+            return customAttributes;
+        }
+
+        public override object[] GetCustomAttributes(Type attributeType, bool inherit)
+        {
+            if (customAttributes == null)
+                InitializeCustomAttribute();
+            List<object> res = new List<object>();
+            for(int i = 0; i < customAttributes.Length; i++)
+            {
+                if (attributeTypes[i] == attributeType)
+                    res.Add(customAttributes[i]);
+            }
+            return res.ToArray();
+        }
+
+        public override Type GetElementType()
+        {
+            throw new NotImplementedException();
+        }
+
+        public override EventInfo GetEvent(string name, BindingFlags bindingAttr)
+        {
+            throw new NotImplementedException();
+        }
+
+        public override EventInfo[] GetEvents(BindingFlags bindingAttr)
+        {
+            throw new NotImplementedException();
+        }
+
+        public override FieldInfo GetField(string name, BindingFlags bindingAttr)
+        {
+            if (fields == null)
+                InitializeFields();
+            foreach(var i in fields)
+            {
+                if (i.Name == name)
+                    return i;
+            }
+            return null;
+        }
+
+        public override FieldInfo[] GetFields(BindingFlags bindingAttr)
+        {
+            if (fields == null)
+                InitializeFields();
+            return fields;
+        }
+
+        public override Type GetInterface(string name, bool ignoreCase)
+        {
+            throw new NotImplementedException();
+        }
+
+        public override Type[] GetInterfaces()
+        {
+            throw new NotImplementedException();
+        }
+
+        public override MemberInfo[] GetMembers(BindingFlags bindingAttr)
+        {
+            throw new NotImplementedException();
+        }
+
+        public override MethodInfo[] GetMethods(BindingFlags bindingAttr)
+        {
+            throw new NotImplementedException();
+        }
+
+        public override Type GetNestedType(string name, BindingFlags bindingAttr)
+        {
+            throw new NotImplementedException();
+        }
+
+        public override Type[] GetNestedTypes(BindingFlags bindingAttr)
+        {
+            throw new NotImplementedException();
+        }
+
+        public override PropertyInfo[] GetProperties(BindingFlags bindingAttr)
+        {
+            throw new NotImplementedException();
+        }
+
+        public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
+        {
+            throw new NotImplementedException();
+        }
+
+        public override bool IsDefined(Type attributeType, bool inherit)
+        {
+            throw new NotImplementedException();
+        }
+
+        protected override TypeAttributes GetAttributeFlagsImpl()
+        {
+            throw new NotImplementedException();
+        }
+
+        protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+        {
+            throw new NotImplementedException();
+        }
+
+        protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+        {
+            IMethod res;
+            if (types == null)
+                res = type.GetMethod(name);
+            else
+            {
+                List<IType> param = new List<IType>();
+                for (int i = 0; i < types.Length; i++)
+                {
+                    if (types[i] is ILRuntimeType)
+                        param.Add(((ILRuntimeType)types[i]).type);
+                    else
+                    {
+                        var t = appdomain.GetType(types[i]);
+                        if (t == null)
+                            t = appdomain.GetType(types[i].AssemblyQualifiedName);
+                        if (t == null)
+                            throw new TypeLoadException();
+                        param.Add(t);
+                    }
+                }
+
+                res = type.GetMethod(name, param, null);
+            }
+            if (res != null)
+                return ((ILMethod)res).ReflectionMethodInfo;
+            else
+                return null;
+        }
+
+        protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
+        {
+            throw new NotImplementedException();
+        }
+
+        protected override bool HasElementTypeImpl()
+        {
+            return false;
+        }
+
+        protected override bool IsArrayImpl()
+        {
+            return false;
+        }
+
+        protected override bool IsByRefImpl()
+        {
+            return false;
+        }
+
+        protected override bool IsCOMObjectImpl()
+        {
+            return false;
+        }
+
+        protected override bool IsPointerImpl()
+        {
+            return false;
+        }
+
+        protected override bool IsPrimitiveImpl()
+        {
+            return false;
+        }
+        public override int GetHashCode()
+        {
+            return type.GetHashCode();
+        }
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/Reflection/ILRuntimeType.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: f3a1f2fbaeb2b8446a4001bf4537351d
+timeCreated: 1486603953
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 9 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime.meta

@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: cfa8ba5fa2cea2d46ad6b593ee6e2575
+folderAsset: yes
+timeCreated: 1486603934
+licenseType: Pro
+DefaultImporter:
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 9 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Adaptors.meta

@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: 94e60d4ce90761b4497ec3f9f968e3e2
+folderAsset: yes
+timeCreated: 1486603934
+licenseType: Pro
+DefaultImporter:
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 73 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Adaptors/CLRCrossBindingAdaptors.cs

@@ -0,0 +1,73 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+using ILRuntime.CLR.Method;
+using ILRuntime.Runtime.Enviorment;
+using ILRuntime.Runtime.Intepreter;
+
+namespace ILRuntime.Runtime.Adaptors
+{
+    class AttributeAdaptor : CrossBindingAdaptor
+    {
+        public override Type AdaptorType
+        {
+            get
+            {
+                return typeof(Adaptor);
+            }
+        }
+
+        public override Type BaseCLRType
+        {
+            get
+            {
+                return typeof(Attribute);
+            }
+        }
+
+        public override object CreateCLRInstance(Enviorment.AppDomain appdomain, ILTypeInstance instance)
+        {
+            return new Adaptor(appdomain, instance);
+        }
+
+        class Adaptor : Attribute, CrossBindingAdaptorType
+        {
+            ILTypeInstance instance;
+            ILRuntime.Runtime.Enviorment.AppDomain appdomain;
+
+            bool isToStringGot;
+            IMethod toString;
+
+            public Adaptor(ILRuntime.Runtime.Enviorment.AppDomain appdomain, ILTypeInstance instance)
+            {
+                this.appdomain = appdomain;
+                this.instance = instance;
+            }
+            public ILTypeInstance ILInstance
+            {
+                get
+                {
+                    return instance;
+                }
+            }
+
+            public override string ToString()
+            {
+                if (!isToStringGot)
+                {
+                    isToStringGot = true;
+                    IMethod m = appdomain.ObjectType.GetMethod("ToString", 0);
+                    toString = instance.Type.GetVirtualMethod(m);
+                }
+                if (toString == null || toString is ILMethod)
+                {
+                    return instance.ToString();
+                }
+                else
+                    return instance.Type.FullName;
+            }
+        }
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Adaptors/CLRCrossBindingAdaptors.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 9c62df830a323ae4185db20e52d0a559
+timeCreated: 1486603951
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 9 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/CLRBinding.meta

@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: af221dfc6c56ebd45a5d24edf9e004d1
+folderAsset: yes
+timeCreated: 1486603934
+licenseType: Pro
+DefaultImporter:
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 1074 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/CLRBinding/BindingCodeGenerator.cs

@@ -0,0 +1,1074 @@
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Linq;
+using System.Text;
+using ILRuntime.Runtime.Enviorment;
+
+namespace ILRuntime.Runtime.CLRBinding
+{
+    public class BindingCodeGenerator
+    {
+        public static void GenerateBindingCode(List<Type> types, string outputPath, HashSet<MethodBase> excludes = null)
+        {
+            if (!System.IO.Directory.Exists(outputPath))
+                System.IO.Directory.CreateDirectory(outputPath);
+            string[] oldFiles = System.IO.Directory.GetFiles(outputPath, "*.cs");
+            foreach (var i in oldFiles)
+            {
+                System.IO.File.Delete(i);
+            }
+            List<string> clsNames = new List<string>();
+            foreach (var i in types)
+            {
+                string clsName, realClsName;
+                bool isByRef;
+                if (i.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length > 0)
+                    continue;
+                GetClassName(i, out clsName, out realClsName, out isByRef);
+                clsNames.Add(clsName);
+                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputPath + "/" + clsName + ".cs", false, Encoding.UTF8))
+                {
+                    sw.Write(@"using System;
+using System.Collections.Generic;
+using System.Reflection;
+
+using ILRuntime.CLR.TypeSystem;
+using ILRuntime.CLR.Method;
+using ILRuntime.Runtime.Enviorment;
+using ILRuntime.Runtime.Intepreter;
+using ILRuntime.Runtime.Stack;
+using ILRuntime.Reflection;
+using ILRuntime.CLR.Utils;
+
+namespace ILRuntime.Runtime.Generated
+{
+    unsafe class ");
+                    sw.WriteLine(clsName);
+                    sw.Write(@"    {
+        public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app)
+        {
+            BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
+            MethodBase method;
+            Type[] args;
+            Type type = typeof(");
+                    sw.Write(realClsName);
+                    sw.WriteLine(");");
+                    MethodInfo[] methods = i.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);
+                    string registerCode = GenerateRegisterCode(i, methods, excludes);
+                    string commonCode = GenerateCommonCode(i, realClsName);
+                    ConstructorInfo[] ctors = i.GetConstructors(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);
+                    string ctorRegisterCode = GenerateConstructorRegisterCode(i, ctors, excludes);
+                    string wraperCode = GenerateWraperCode(i, methods, realClsName, excludes);
+                    string ctorWraperCode = GenerateConstructorWraperCode(i, ctors, realClsName, excludes);
+                    sw.WriteLine(registerCode);
+                    sw.WriteLine(ctorRegisterCode);
+                    sw.WriteLine("        }");
+                    sw.WriteLine();
+                    sw.WriteLine(commonCode);
+                    sw.WriteLine(wraperCode);
+                    sw.WriteLine(ctorWraperCode);
+                    sw.WriteLine("    }");
+                    sw.WriteLine("}");
+                    sw.Flush();
+                }
+            }
+
+            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputPath + "/CLRBindings.cs", false, Encoding.UTF8))
+            {
+                sw.WriteLine(@"using System;
+using System.Collections.Generic;
+using System.Reflection;
+
+namespace ILRuntime.Runtime.Generated
+{
+    class CLRBindings
+    {
+        /// <summary>
+        /// Initialize the CLR binding, please invoke this AFTER CLR Redirection registration
+        /// </summary>
+        public static void Initialize(ILRuntime.Runtime.Enviorment.AppDomain app)
+        {");
+                foreach (var i in clsNames)
+                {
+                    sw.Write("            ");
+                    sw.Write(i);
+                    sw.WriteLine(".Register(app);");
+                }
+
+                sw.WriteLine(@"        }
+    }
+}");
+            }
+        }
+
+        static bool ShouldSkipMethod(Type type, MethodBase i)
+        {
+            if (i.IsPrivate)
+                return true;
+            if (i.IsGenericMethod)
+                return true;
+            //EventHandler is currently not supported
+            if (i.IsSpecialName)
+            {
+                string[] t = i.Name.Split('_');
+                if (t[0] == "add" || t[0] == "remove")
+                    return true;
+                if (t[0] == "get" || t[0] == "set")
+                {
+                    var prop = type.GetProperty(t[1]);
+                    if (prop == null)
+                        return true;
+                    if (prop.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length > 0)
+                        return true;
+                }
+            }
+            if (i.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length > 0)
+                return true;
+            var param = i.GetParameters();
+            foreach(var j in param)
+            {
+                if (j.ParameterType.IsPointer)
+                    return true;
+            }
+            return false;
+        }
+
+        static string GenerateRegisterCode(Type type, MethodInfo[] methods, HashSet<MethodBase> excludes)
+        {
+            StringBuilder sb = new StringBuilder();
+            int idx = 0;
+            foreach (var i in methods)
+            {
+                if (excludes != null && excludes.Contains(i))
+                    continue;
+                if (ShouldSkipMethod(type, i))
+                    continue;
+                bool isProperty = i.IsSpecialName;
+                var param = i.GetParameters();
+                StringBuilder sb2 = new StringBuilder();
+                sb2.Append("{");
+                bool first = true;
+                foreach (var j in param)
+                {
+                    if (first)
+                        first = false;
+                    else
+                        sb2.Append(", ");
+                    sb2.Append("typeof(");
+                    string tmp, clsName;
+                    bool isByRef;
+                    GetClassName(j.ParameterType, out tmp, out clsName, out isByRef);
+                    sb2.Append(clsName);
+                    sb2.Append(")");
+                    if (isByRef)
+                        sb2.Append(".MakeByRefType()");
+                }
+                sb2.Append("}");
+                sb.AppendLine(string.Format("            args = new Type[]{0};", sb2));
+                sb.AppendLine(string.Format("            method = type.GetMethod(\"{0}\", flag, null, args, null);", i.Name));
+                sb.AppendLine(string.Format("            app.RegisterCLRMethodRedirection(method, {0}_{1});", i.Name, idx));
+
+                idx++;
+            }
+            return sb.ToString();
+        }
+
+        static string GenerateConstructorRegisterCode(Type type, ConstructorInfo[] methods, HashSet<MethodBase> excludes)
+        {
+            StringBuilder sb = new StringBuilder();
+            int idx = 0;
+            foreach (var i in methods)
+            {
+                if (excludes != null && excludes.Contains(i))
+                    continue;
+                if (ShouldSkipMethod(type, i))
+                    continue;
+                var param = i.GetParameters();
+                StringBuilder sb2 = new StringBuilder();
+                sb2.Append("{");
+                bool first = true;
+                foreach (var j in param)
+                {
+                    if (first)
+                        first = false;
+                    else
+                        sb2.Append(", ");
+                    sb2.Append("typeof(");
+                    string tmp, clsName;
+                    bool isByRef;
+                    GetClassName(j.ParameterType, out tmp, out clsName, out isByRef);
+                    sb2.Append(clsName);
+                    sb2.Append(")");
+                    if (isByRef)
+                        sb2.Append(".MakeByRefType()");
+                }
+                sb2.Append("}");
+                sb.AppendLine(string.Format("            args = new Type[]{0};", sb2));
+                sb.AppendLine("            method = type.GetConstructor(flag, null, args, null);");
+                sb.AppendLine(string.Format("            app.RegisterCLRMethodRedirection(method, Ctor_{0});",idx));
+
+                idx++;
+            }
+            return sb.ToString();
+        }
+
+        static string GenerateCommonCode(Type type, string typeClsName)
+        {
+            if (!type.IsValueType)
+                return "";
+            StringBuilder sb = new StringBuilder();
+            if (type.IsPrimitive)
+            {
+                sb.AppendLine(string.Format("        static {0} GetInstance(ILRuntime.Runtime.Enviorment.AppDomain __domain, StackObject* ptr_of_this_method, List<object> __mStack)", typeClsName));
+                sb.AppendLine("        {");
+                if (type.IsPrimitive || type.IsValueType)
+                    sb.AppendLine("            ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);");
+                sb.AppendLine(string.Format("            {0} instance_of_this_method;", typeClsName));
+                sb.Append(@"            switch(ptr_of_this_method->ObjectType)
+            {
+                case ObjectTypes.FieldReference:
+                    {
+                        var instance_of_fieldReference = __mStack[ptr_of_this_method->Value];
+                        if(instance_of_fieldReference is ILTypeInstance)
+                        {
+                            instance_of_this_method = (");
+                sb.Append(typeClsName);
+                sb.Append(")((ILTypeInstance)instance_of_fieldReference)[ptr_of_this_method->ValueLow];");
+                sb.Append(@"
+                        }
+                        else
+                        {
+                            var t = __domain.GetType(instance_of_fieldReference.GetType()) as CLRType;
+                            instance_of_this_method = (");
+                sb.Append(typeClsName);
+                sb.Append(")t.GetField(ptr_of_this_method->ValueLow).GetValue(instance_of_fieldReference);");
+                sb.Append(@"
+                        }
+                    }
+                    break;
+                case ObjectTypes.StaticFieldReference:
+                    {
+                        var t = __domain.GetType(ptr_of_this_method->Value);
+                        if(t is ILType)
+                        {
+                            instance_of_this_method = (");
+                sb.Append(typeClsName);
+                sb.Append(@")((ILType)t).StaticInstance[ptr_of_this_method->ValueLow];
+                        }
+                        else
+                        {
+                            instance_of_this_method = (");
+                sb.Append(typeClsName);
+                sb.Append(@")((CLRType)t).GetField(ptr_of_this_method->ValueLow).GetValue(null);
+                        }
+                    }
+                    break;
+                case ObjectTypes.ArrayReference:
+                    {
+                        var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as ");
+                sb.Append(typeClsName);
+                sb.AppendLine(@"[];
+                        instance_of_this_method = instance_of_arrayReference[ptr_of_this_method->ValueLow];                        
+                    }
+                    break;
+                default:");
+                sb.AppendLine(string.Format("                    instance_of_this_method = {0};", GetRetrieveValueCode(type, typeClsName)));
+                sb.AppendLine(@"                    break;
+            }
+            return instance_of_this_method;");
+                sb.AppendLine("        }");
+            }
+            if (!type.IsPrimitive && !type.IsAbstract)
+            {
+                sb.AppendLine(string.Format("        static void WriteBackInstance(ILRuntime.Runtime.Enviorment.AppDomain __domain, StackObject* ptr_of_this_method, List<object> __mStack, ref {0} instance_of_this_method)", typeClsName));
+                sb.AppendLine("        {");
+                sb.AppendLine(@"            ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);
+            switch(ptr_of_this_method->ObjectType)
+            {
+                case ObjectTypes.Object:
+                    {
+                        __mStack[ptr_of_this_method->Value] = instance_of_this_method;");
+                sb.Append(@"                    }
+                    break;
+                case ObjectTypes.FieldReference:
+                    {
+                        var ___obj = __mStack[ptr_of_this_method->Value];
+                        if(___obj is ILTypeInstance)
+                        {
+                            ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = instance_of_this_method");
+                sb.Append(@";
+                        }
+                        else
+                        {
+                            var t = __domain.GetType(___obj.GetType()) as CLRType;
+                            t.GetField(ptr_of_this_method->ValueLow).SetValue(___obj, instance_of_this_method");
+                sb.Append(@");
+                        }
+                    }
+                    break;
+                case ObjectTypes.StaticFieldReference:
+                    {
+                        var t = __domain.GetType(ptr_of_this_method->Value);
+                        if(t is ILType)
+                        {
+                            ((ILType)t).StaticInstance[ptr_of_this_method->ValueLow] = instance_of_this_method");
+                sb.Append(@";
+                        }
+                        else
+                        {
+                            ((CLRType)t).GetField(ptr_of_this_method->ValueLow).SetValue(null, instance_of_this_method");
+                sb.Append(@");
+                        }
+                    }
+                    break;
+                 case ObjectTypes.ArrayReference:
+                    {
+                        var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as ");
+                sb.Append(typeClsName);
+                sb.AppendLine(@"[];
+                        instance_of_arrayReference[ptr_of_this_method->ValueLow] = instance_of_this_method;
+                    }
+                    break;
+            }");
+                sb.AppendLine(@"        }");
+            }
+            return sb.ToString();
+        }
+
+        static string GenerateConstructorWraperCode(Type type, ConstructorInfo[] methods, string typeClsName, HashSet<MethodBase> excludes)
+        {
+            StringBuilder sb = new StringBuilder();
+
+            int idx = 0;
+            foreach (var i in methods)
+            {
+                if (excludes != null && excludes.Contains(i))
+                    continue;
+                if (ShouldSkipMethod(type, i) || i.IsStatic)
+                    continue;
+                var param = i.GetParameters();
+                int paramCnt = param.Length;
+                sb.AppendLine(string.Format("        static StackObject* Ctor_{0}(ILIntepreter __intp, StackObject* __esp, List<object> __mStack, CLRMethod __method, bool isNewObj)", idx));
+                sb.AppendLine("        {");
+                sb.AppendLine("            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;");
+                sb.AppendLine("            StackObject* ptr_of_this_method;");
+                sb.AppendLine(string.Format("            StackObject* __ret = ILIntepreter.Minus(__esp, {0});", paramCnt));
+                for (int j = param.Length; j > 0; j--)
+                {
+                    var p = param[j - 1];
+                    sb.AppendLine(string.Format("            ptr_of_this_method = ILIntepreter.Minus(__esp, {0});", param.Length - j + 1));
+                    string tmp, clsName;
+                    bool isByRef;
+                    GetClassName(p.ParameterType, out tmp, out clsName, out isByRef);
+                    if (isByRef)
+                        sb.AppendLine("            ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);");
+                    sb.AppendLine(string.Format("            {0} {1} = {2};", clsName, p.Name, GetRetrieveValueCode(p.ParameterType, clsName)));
+                    if (!isByRef && !p.ParameterType.IsPrimitive)
+                        sb.AppendLine("            __intp.Free(ptr_of_this_method);");
+                }
+                sb.AppendLine();
+                sb.Append("            var result_of_this_method = ");
+                {
+                    string tmp, clsName;
+                    bool isByRef;
+                    GetClassName(type, out tmp, out clsName, out isByRef);
+                    sb.Append(string.Format("new {0}(", clsName));
+                    AppendParameters(param, sb);
+                    sb.AppendLine(");");
+
+                }
+                sb.AppendLine();
+                if (type.IsValueType)
+                {
+                    sb.AppendLine(@"            if(!isNewObj)
+            {
+                __ret--;
+                WriteBackInstance(__domain, __ret, __mStack, ref result_of_this_method);
+                return __ret;
+            }"); 
+                }
+
+                //Ref/Out
+                for (int j = param.Length; j > 0; j--)
+                {
+                    var p = param[j - 1];
+                    if (!p.ParameterType.IsByRef)
+                        continue;
+                    string tmp, clsName;
+                    bool isByRef;
+                    GetClassName(p.ParameterType.GetElementType(), out tmp, out clsName, out isByRef);
+                    sb.AppendLine(string.Format("            ptr_of_this_method = ILIntepreter.Minus(__esp, {0});", param.Length - j + 1));
+                    sb.AppendLine(@"            switch(ptr_of_this_method->ObjectType)
+            {
+                case ObjectTypes.StackObjectReference:
+                    {
+                        var dst = *(StackObject**)&ptr_of_this_method->Value;");
+                    GetRefWriteBackValueCode(p.ParameterType.GetElementType(), sb, p.Name);
+                    sb.Append(@"                    }
+                    break;
+                case ObjectTypes.FieldReference:
+                    {
+                        var ___obj = __mStack[ptr_of_this_method->Value];
+                        if(___obj is ILTypeInstance)
+                        {
+                            ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = ");
+                    sb.Append(p.Name);
+                    sb.Append(@";
+                        }
+                        else
+                        {
+                            var t = __domain.GetType(___obj.GetType()) as CLRType;
+                            t.GetField(ptr_of_this_method->ValueLow).SetValue(___obj, ");
+                    sb.Append(p.Name);
+                    sb.Append(@");
+                        }
+                    }
+                    break;
+                case ObjectTypes.StaticFieldReference:
+                    {
+                        var t = __domain.GetType(ptr_of_this_method->Value);
+                        if(t is ILType)
+                        {
+                            ((ILType)t).StaticInstance[ptr_of_this_method->ValueLow] = ");
+                    sb.Append(p.Name);
+                    sb.Append(@";
+                        }
+                        else
+                        {
+                            ((CLRType)t).GetField(ptr_of_this_method->ValueLow).SetValue(null, ");
+                    sb.Append(p.Name);
+                    sb.Append(@");
+                        }
+                    }
+                    break;
+                 case ObjectTypes.ArrayReference:
+                    {
+                        var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as ");
+                    sb.Append(clsName);
+                    sb.Append(@"[];
+                        instance_of_arrayReference[ptr_of_this_method->ValueLow] = ");
+                    sb.Append(p.Name);
+                    sb.AppendLine(@";
+                    }
+                    break;
+            }");
+                    sb.AppendLine();
+                }
+                sb.AppendLine("            return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);");
+
+                sb.AppendLine("        }");
+                sb.AppendLine();
+                idx++;
+            }
+
+            return sb.ToString();
+        }
+
+        static string GenerateWraperCode(Type type, MethodInfo[] methods, string typeClsName, HashSet<MethodBase> excludes)
+        {
+            StringBuilder sb = new StringBuilder();
+
+            int idx = 0;
+            foreach (var i in methods)
+            {
+                if (excludes != null && excludes.Contains(i))
+                    continue;
+                if (ShouldSkipMethod(type, i))
+                    continue;
+                bool isProperty = i.IsSpecialName;
+                var param = i.GetParameters();
+                int paramCnt = param.Length;
+                if (!i.IsStatic)
+                    paramCnt++;
+                sb.AppendLine(string.Format("        static StackObject* {0}_{1}(ILIntepreter __intp, StackObject* __esp, List<object> __mStack, CLRMethod __method, bool isNewObj)", i.Name, idx));
+                sb.AppendLine("        {");
+                sb.AppendLine("            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;");
+                sb.AppendLine("            StackObject* ptr_of_this_method;");
+                sb.AppendLine(string.Format("            StackObject* __ret = ILIntepreter.Minus(__esp, {0});", paramCnt));
+                for (int j = param.Length; j > 0; j--)
+                {
+                    var p = param[j - 1];
+                    sb.AppendLine(string.Format("            ptr_of_this_method = ILIntepreter.Minus(__esp, {0});", param.Length - j + 1));
+                    string tmp, clsName;
+                    bool isByRef;
+                    GetClassName(p.ParameterType, out tmp, out clsName, out isByRef);
+                    if (isByRef)
+                        sb.AppendLine("            ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);");
+                    sb.AppendLine(string.Format("            {0} {1} = {2};", clsName, p.Name, GetRetrieveValueCode(p.ParameterType, clsName)));
+                    if (!isByRef && !p.ParameterType.IsPrimitive)
+                        sb.AppendLine("            __intp.Free(ptr_of_this_method);");
+                }
+                if (!i.IsStatic)
+                {
+                    sb.AppendLine(string.Format("            ptr_of_this_method = ILIntepreter.Minus(__esp, {0});", paramCnt));
+                    if (type.IsPrimitive)
+                        sb.AppendLine(string.Format("            {0} instance_of_this_method = GetInstance(__domain, ptr_of_this_method, __mStack);", typeClsName));
+                    else
+                    {
+                        if (type.IsValueType)
+                            sb.AppendLine("            ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);");
+                        sb.AppendLine(string.Format("            {0} instance_of_this_method;", typeClsName));
+                        sb.AppendLine(string.Format("            instance_of_this_method = {0};", GetRetrieveValueCode(type, typeClsName)));
+                        if (!type.IsValueType)
+                            sb.AppendLine("            __intp.Free(ptr_of_this_method);");
+                    }
+                }
+                sb.AppendLine();
+                if (i.ReturnType != typeof(void))
+                {
+                    sb.Append("            var result_of_this_method = ");
+                }
+                else
+                    sb.Append("            ");
+                if (i.IsStatic)
+                {
+                    if (isProperty)
+                    {
+                        string[] t = i.Name.Split('_');
+                        string propType = t[0];
+
+                        if (propType == "get")
+                        {
+                            bool isIndexer = param.Length > 0;
+                            if (isIndexer)
+                            {
+                                sb.AppendLine(string.Format("{1}[{0}];", param[0].Name, typeClsName));
+                            }
+                            else
+                                sb.AppendLine(string.Format("{1}.{0};", t[1], typeClsName));
+                        }
+                        else if (propType == "set")
+                        {
+                            bool isIndexer = param.Length > 1;
+                            if (isIndexer)
+                            {
+                                sb.AppendLine(string.Format("{2}[{0}] = {1};", param[0].Name, param[1].Name, typeClsName));
+                            }
+                            else
+                                sb.AppendLine(string.Format("{2}.{0} = {1};", t[1], param[0].Name, typeClsName));
+                        }
+                        else if (propType == "op")
+                        {
+                            switch (t[1])
+                            {
+                                case "Equality":
+                                    sb.AppendLine(string.Format("{0} == {1};", param[0].Name, param[1].Name));
+                                    break;
+                                case "Inequality":
+                                    sb.AppendLine(string.Format("{0} != {1};", param[0].Name, param[1].Name));
+                                    break;
+                                case "Addition":
+                                    sb.AppendLine(string.Format("{0} + {1};", param[0].Name, param[1].Name));
+                                    break;
+                                case "Subtraction":
+                                    sb.AppendLine(string.Format("{0} - {1};", param[0].Name, param[1].Name));
+                                    break;
+                                case "Multiply":
+                                    sb.AppendLine(string.Format("{0} * {1};", param[0].Name, param[1].Name));
+                                    break;
+                                case "Division":
+                                    sb.AppendLine(string.Format("{0} / {1};", param[0].Name, param[1].Name));
+                                    break;
+                                case "GreaterThan":
+                                    sb.AppendLine(string.Format("{0} > {1};", param[0].Name, param[1].Name));
+                                    break;
+                                case "GreaterThanOrEqual":
+                                    sb.AppendLine(string.Format("{0} >= {1};", param[0].Name, param[1].Name));
+                                    break;
+                                case "LessThan":
+                                    sb.AppendLine(string.Format("{0} < {1};", param[0].Name, param[1].Name));
+                                    break;
+                                case "LessThanOrEqual":
+                                    sb.AppendLine(string.Format("{0} <= {1};", param[0].Name, param[1].Name));
+                                    break;
+                                case "UnaryNegation":
+                                    sb.AppendLine(string.Format("-{0};", param[0].Name));
+                                    break;
+                                case "Implicit":
+                                case "Explicit":
+                                    {
+                                        string tmp, clsName;
+                                        bool isByRef;
+                                        GetClassName(i.ReturnType, out tmp, out clsName, out isByRef);
+                                        sb.AppendLine(string.Format("({1}){0};", param[0].Name, clsName));
+                                    }
+                                    break;
+                                default:
+                                    throw new NotImplementedException(i.Name);
+                            }
+                        }
+                        else
+                            throw new NotImplementedException();
+                    }
+                    else
+                    {
+                        sb.Append(string.Format("{0}.{1}(", typeClsName, i.Name));
+                        AppendParameters(param, sb);
+                        sb.AppendLine(");");
+                    }
+                }
+                else
+                {
+                    if (isProperty)
+                    {
+                        string[] t = i.Name.Split('_');
+                        string propType = t[0];
+
+                        if (propType == "get")
+                        {
+                            bool isIndexer = param.Length > 0;
+                            if (isIndexer)
+                            {
+                                sb.AppendLine(string.Format("instance_of_this_method[{0}];", param[0].Name));
+                            }
+                            else
+                                sb.AppendLine(string.Format("instance_of_this_method.{0};", t[1]));
+                        }
+                        else if (propType == "set")
+                        {
+                            bool isIndexer = param.Length > 1;
+                            if (isIndexer)
+                            {
+                                sb.AppendLine(string.Format("instance_of_this_method[{0}] = {1};", param[0].Name, param[1].Name));
+                            }
+                            else
+                                sb.AppendLine(string.Format("instance_of_this_method.{0} = {1};", t[1], param[0].Name));
+                        }
+                        else
+                            throw new NotImplementedException();
+                    }
+                    else
+                    {
+                        sb.Append(string.Format("instance_of_this_method.{0}(", i.Name));
+                        AppendParameters(param, sb);
+                        sb.AppendLine(");");
+                    }
+                }
+                sb.AppendLine();
+
+
+                if (!i.IsStatic && type.IsValueType && !type.IsPrimitive)//need to write back value type instance
+                {
+                    sb.AppendLine("            WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method);");
+                    sb.AppendLine();
+                }
+                //Ref/Out
+                for (int j = param.Length; j > 0; j--)
+                {
+                    var p = param[j - 1];
+                    if (!p.ParameterType.IsByRef)
+                        continue;
+                    string tmp, clsName;
+                    bool isByRef;
+                    GetClassName(p.ParameterType.GetElementType(), out tmp, out clsName, out isByRef);
+                    sb.AppendLine(string.Format("            ptr_of_this_method = ILIntepreter.Minus(__esp, {0});", param.Length - j + 1));
+                    sb.AppendLine(@"            switch(ptr_of_this_method->ObjectType)
+            {
+                case ObjectTypes.StackObjectReference:
+                    {
+                        var dst = *(StackObject**)&ptr_of_this_method->Value;");
+                    GetRefWriteBackValueCode(p.ParameterType.GetElementType(), sb, p.Name);
+                    sb.Append(@"                    }
+                    break;
+                case ObjectTypes.FieldReference:
+                    {
+                        var ___obj = __mStack[ptr_of_this_method->Value];
+                        if(___obj is ILTypeInstance)
+                        {
+                            ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = ");
+                    sb.Append(p.Name);
+                    sb.Append(@";
+                        }
+                        else
+                        {
+                            var t = __domain.GetType(___obj.GetType()) as CLRType;
+                            t.GetField(ptr_of_this_method->ValueLow).SetValue(___obj, ");
+                    sb.Append(p.Name);
+                    sb.Append(@");
+                        }
+                    }
+                    break;
+                case ObjectTypes.StaticFieldReference:
+                    {
+                        var t = __domain.GetType(ptr_of_this_method->Value);
+                        if(t is ILType)
+                        {
+                            ((ILType)t).StaticInstance[ptr_of_this_method->ValueLow] = ");
+                    sb.Append(p.Name);
+                    sb.Append(@";
+                        }
+                        else
+                        {
+                            ((CLRType)t).GetField(ptr_of_this_method->ValueLow).SetValue(null, ");
+                    sb.Append(p.Name);
+                    sb.Append(@");
+                        }
+                    }
+                    break;
+                 case ObjectTypes.ArrayReference:
+                    {
+                        var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as ");
+                    sb.Append(clsName);
+                    sb.Append(@"[];
+                        instance_of_arrayReference[ptr_of_this_method->ValueLow] = ");
+                    sb.Append(p.Name);
+                    sb.AppendLine(@";
+                    }
+                    break;
+            }");
+                    sb.AppendLine();
+                }
+                if (i.ReturnType != typeof(void))
+                {
+                    GetReturnValueCode(i.ReturnType, sb);
+                }
+                else
+                    sb.AppendLine("            return __ret;");
+                sb.AppendLine("        }");
+                sb.AppendLine();
+                idx++;
+            }
+
+            return sb.ToString();
+        }
+
+        static void AppendParameters(ParameterInfo[] param, StringBuilder sb)
+        {
+            bool first = true;
+            foreach (var j in param)
+            {
+                if (first)
+                    first = false;
+                else
+                    sb.Append(", ");
+                if (j.IsOut)
+                    sb.Append("out ");
+                else if (j.ParameterType.IsByRef)
+                    sb.Append("ref ");
+                sb.Append(j.Name);
+            }
+        }
+
+        static void GetRefWriteBackValueCode(Type type, StringBuilder sb, string paramName)
+        {
+            if (type.IsPrimitive)
+            {
+                if (type == typeof(int))
+                {
+                    sb.AppendLine("                        dst->ObjectType = ObjectTypes.Integer;");
+                    sb.Append("                        dst->Value = " + paramName);
+                    sb.AppendLine(";");
+                }
+                else if (type == typeof(long))
+                {
+                    sb.AppendLine("                        dst->ObjectType = ObjectTypes.Long;");
+                    sb.Append("                        *(long*)&dst->Value = " + paramName);
+                    sb.AppendLine(";");
+                }
+                else if (type == typeof(short))
+                {
+                    sb.AppendLine("                        dst->ObjectType = ObjectTypes.Integer;");
+                    sb.Append("                        dst->Value = " + paramName);
+                    sb.AppendLine(";");
+                }
+                else if (type == typeof(bool))
+                {
+                    sb.AppendLine("                        dst->ObjectType = ObjectTypes.Integer;");
+                    sb.Append("                        dst->Value = " + paramName + " ? 1 : 0;");
+                    sb.AppendLine(";");
+                }
+                else if (type == typeof(ushort))
+                {
+                    sb.AppendLine("                        dst->ObjectType = ObjectTypes.Integer;");
+                    sb.Append("                        dst->Value = " + paramName);
+                    sb.AppendLine(";");
+                }
+                else if (type == typeof(float))
+                {
+                    sb.AppendLine("                        dst->ObjectType = ObjectTypes.Float;");
+                    sb.Append("                        *(float*)&dst->Value = " + paramName);
+                    sb.AppendLine(";");
+                }
+                else if (type == typeof(double))
+                {
+                    sb.AppendLine("                        dst->ObjectType = ObjectTypes.Double;");
+                    sb.Append("                        *(double*)&dst->Value = " + paramName);
+                    sb.AppendLine(";");
+                }
+                else if (type == typeof(byte))
+                {
+                    sb.AppendLine("                        dst->ObjectType = ObjectTypes.Integer;");
+                    sb.Append("                        dst->Value = " + paramName);
+                    sb.AppendLine(";");
+                }
+                else if (type == typeof(sbyte))
+                {
+                    sb.AppendLine("                        dst->ObjectType = ObjectTypes.Integer;");
+                    sb.Append("                        dst->Value = " + paramName);
+                    sb.AppendLine(";");
+                }
+                else if (type == typeof(uint))
+                {
+                    sb.AppendLine("                        dst->ObjectType = ObjectTypes.Integer;");
+                    sb.Append("                        dst->Value = (int)" + paramName);
+                    sb.AppendLine(";");
+                }
+                else if (type == typeof(char))
+                {
+                    sb.AppendLine("                        dst->ObjectType = ObjectTypes.Integer;");
+                    sb.Append("                        dst->Value = (int)" + paramName);
+                    sb.AppendLine(";");
+                }
+                else if (type == typeof(ulong))
+                {
+                    sb.AppendLine("                        dst->ObjectType = ObjectTypes.Long;");
+                    sb.Append("                        *(ulong*)&dst->Value = " + paramName);
+                    sb.AppendLine(";");
+                }
+                else
+                    throw new NotImplementedException();
+            }
+            else
+            {
+                if (!type.IsValueType)
+                {
+                    sb.Append(@"                        object ___obj = ");
+                    sb.Append(paramName);
+                    sb.AppendLine(";");
+
+                    sb.AppendLine(@"                        if (___obj is CrossBindingAdaptorType)
+                            ___obj = ((CrossBindingAdaptorType)___obj).ILInstance;
+                        __mStack[dst->Value] = ___obj; ");
+                }
+                else
+                {
+                    sb.Append("                        __mStack[dst->Value] = ");
+                    sb.Append(paramName);
+                    sb.AppendLine(";");
+                }
+            }
+        }
+
+        static void GetReturnValueCode(Type type, StringBuilder sb)
+        {
+            if (type.IsPrimitive)
+            {
+                if (type == typeof(int))
+                {
+                    sb.AppendLine("            __ret->ObjectType = ObjectTypes.Integer;");
+                    sb.AppendLine("            __ret->Value = result_of_this_method;");
+                }
+                else if (type == typeof(long))
+                {
+                    sb.AppendLine("            __ret->ObjectType = ObjectTypes.Long;");
+                    sb.AppendLine("            *(long*)&__ret->Value = result_of_this_method;");
+                }
+                else if (type == typeof(short))
+                {
+                    sb.AppendLine("            __ret->ObjectType = ObjectTypes.Integer;");
+                    sb.AppendLine("            __ret->Value = result_of_this_method;");
+                }
+                else if (type == typeof(bool))
+                {
+                    sb.AppendLine("            __ret->ObjectType = ObjectTypes.Integer;");
+                    sb.AppendLine("            __ret->Value = result_of_this_method ? 1 : 0;");
+                }
+                else if (type == typeof(ushort))
+                {
+                    sb.AppendLine("            __ret->ObjectType = ObjectTypes.Integer;");
+                    sb.AppendLine("            __ret->Value = result_of_this_method;");
+                }
+                else if (type == typeof(float))
+                {
+                    sb.AppendLine("            __ret->ObjectType = ObjectTypes.Float;");
+                    sb.AppendLine("            *(float*)&__ret->Value = result_of_this_method;");
+                }
+                else if (type == typeof(double))
+                {
+                    sb.AppendLine("            __ret->ObjectType = ObjectTypes.Double;");
+                    sb.AppendLine("            *(double*)&__ret->Value = result_of_this_method;");
+                }
+                else if (type == typeof(byte))
+                {
+                    sb.AppendLine("            __ret->ObjectType = ObjectTypes.Integer;");
+                    sb.AppendLine("            __ret->Value = result_of_this_method;");
+                }
+                else if (type == typeof(sbyte))
+                {
+                    sb.AppendLine("            __ret->ObjectType = ObjectTypes.Integer;");
+                    sb.AppendLine("            __ret->Value = result_of_this_method;");
+                }
+                else if (type == typeof(uint))
+                {
+                    sb.AppendLine("            __ret->ObjectType = ObjectTypes.Integer;");
+                    sb.AppendLine("            __ret->Value = (int)result_of_this_method;");
+                }
+                else if (type == typeof(char))
+                {
+                    sb.AppendLine("            __ret->ObjectType = ObjectTypes.Integer;");
+                    sb.AppendLine("            __ret->Value = (int)result_of_this_method;");
+                }
+                else if (type == typeof(ulong))
+                {
+                    sb.AppendLine("            __ret->ObjectType = ObjectTypes.Long;");
+                    sb.AppendLine("            *(ulong*)&__ret->Value = result_of_this_method;");
+                }
+                else
+                    throw new NotImplementedException();
+                sb.AppendLine("            return __ret + 1;");
+
+            }
+            else
+            {
+                if (!type.IsSealed && type != typeof(ILRuntime.Runtime.Intepreter.ILTypeInstance))
+                {
+                    sb.AppendLine(@"            object obj_result_of_this_method = result_of_this_method;
+            if(obj_result_of_this_method is CrossBindingAdaptorType)
+            {    
+                return ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance);
+            }");
+                }
+                sb.AppendLine("            return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);");
+            }
+        }
+
+        static string GetRetrieveValueCode(Type type, string realClsName)
+        {
+            if (type.IsByRef)
+                type = type.GetElementType();
+            if (type.IsPrimitive)
+            {
+                if (type == typeof(int))
+                {
+                    return "ptr_of_this_method->Value";
+                }
+                else if (type == typeof(long))
+                {
+                    return "*(long*)&ptr_of_this_method->Value";
+                }
+                else if (type == typeof(short))
+                {
+                    return "(short)ptr_of_this_method->Value";
+                }
+                else if (type == typeof(bool))
+                {
+                    return "ptr_of_this_method->Value == 1";
+                }
+                else if (type == typeof(ushort))
+                {
+                    return "(ushort)ptr_of_this_method->Value";
+                }
+                else if (type == typeof(float))
+                {
+                    return "*(float*)&ptr_of_this_method->Value";
+                }
+                else if (type == typeof(double))
+                {
+                    return "*(double*)&ptr_of_this_method->Value";
+                }
+                else if (type == typeof(byte))
+                {
+                    return "(byte)ptr_of_this_method->Value";
+                }
+                else if (type == typeof(sbyte))
+                {
+                    return "(sbyte)ptr_of_this_method->Value";
+                }
+                else if (type == typeof(uint))
+                {
+                    return "(uint)ptr_of_this_method->Value";
+                }
+                else if (type == typeof(char))
+                {
+                    return "(char)ptr_of_this_method->Value";
+                }
+                else if (type == typeof(ulong))
+                {
+                    return "*(ulong*)&ptr_of_this_method->Value";
+                }
+                else
+                    throw new NotImplementedException();
+            }
+            else
+            {
+                return string.Format("({0})typeof({0}).CheckCLRTypes(__domain, StackObject.ToObject(ptr_of_this_method, __domain, __mStack))", realClsName);
+            }
+        }
+
+        static void GetClassName(Type type, out string clsName, out string realClsName, out bool isByRef, bool simpleClassName = false)
+        {
+            isByRef = type.IsByRef;
+            bool isArray = type.IsArray;
+            if (isByRef)
+                type = type.GetElementType();
+            if (isArray)
+                type = type.GetElementType();
+            string realNamespace = null;
+            if (type.IsNested)
+            {
+                string bClsName, bRealClsName;
+                bool tmp;
+                GetClassName(type.ReflectedType, out bClsName, out bRealClsName, out tmp);
+                clsName = simpleClassName ? "" : bClsName + "_";
+                realNamespace = bRealClsName + ".";
+            }
+            else
+            {
+                clsName = simpleClassName ? "" : (!string.IsNullOrEmpty(type.Namespace) ? type.Namespace.Replace(".", "_") + "_" : "");
+                realNamespace = !string.IsNullOrEmpty(type.Namespace) ? type.Namespace + "." : null;
+            }
+            clsName = clsName + type.Name.Replace(".", "_").Replace("`", "_").Replace("<", "_").Replace(">", "_");
+            bool isGeneric = false;
+            string ga = null;
+            if (type.IsGenericType)
+            {
+                isGeneric = true;
+                clsName += "_";
+                ga = "<";
+                var args = type.GetGenericArguments();
+                bool first = true;
+                foreach (var j in args)
+                {
+                    if (first)
+                        first = false;
+                    else
+                    {
+                        clsName += "_";
+                        ga += ", ";
+                    }
+                    string a, b;
+                    bool tmp;
+                    GetClassName(j, out a, out b, out tmp, true);
+                    clsName += a;
+                    ga += b;
+                }
+                ga += ">";
+            }
+            if (!simpleClassName)
+                clsName += "_Binding";
+            if (!simpleClassName && isArray)
+                clsName += "_Array";
+
+            realClsName = realNamespace;
+            if (isGeneric)
+            {
+                int idx = type.Name.IndexOf("`");
+                if (idx > 0)
+                {
+                    realClsName += type.Name.Substring(0, idx);
+                    realClsName += ga;
+                }
+                else
+                    realClsName += type.Name;
+            }
+            else
+                realClsName += type.Name;
+
+            if (isArray)
+                realClsName += "[]";
+
+        }
+
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/CLRBinding/BindingCodeGenerator.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 4e7ba7f4b3e5e4843a17ebdf3ff249ef
+timeCreated: 1486603950
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 9 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger.meta

@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: d13f66766121a994fae9cf07b8221201
+folderAsset: yes
+timeCreated: 1486603934
+licenseType: Pro
+DefaultImporter:
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 61 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/BreakPointContext.cs

@@ -0,0 +1,61 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+using ILRuntime.Runtime.Intepreter;
+using ILRuntime.Runtime.Stack;
+namespace ILRuntime.Runtime.Debugger
+{
+    unsafe class BreakPointContext
+    {
+        public ILIntepreter Interpreter { get; set; }
+        public Exception Exception { get; set; }
+
+        public string DumpContext()
+        {
+            /*StringBuilder sb = new StringBuilder();
+            if (Exception != null)
+                sb.AppendLine(Exception.Message);
+            StackFrame[] frames = Interpreter.Stack.Frames.ToArray();
+            StackFrame topFrame = frames[0];
+            var m = topFrame.Method;
+            if (m.HasThis)
+            {
+                sb.AppendLine("this:");
+                sb.AppendLine(DebugService.Instance.GetThisInfo(Interpreter));
+            }
+            sb.AppendLine("->" + topFrame.Method.Definition.Body.Instructions[topFrame.Address.Value]);
+            sb.AppendLine("Local Variables:");
+            sb.AppendLine(DebugService.Instance.GetLocalVariableInfo(Interpreter));
+
+            sb.Append(DebugService.Instance.GetStackTrance(Interpreter));
+            return sb.ToString();*/
+            return null;
+        }
+
+        string GetStackObjectValue(StackObject val, List<object> mStack)
+        {
+            string v;
+            switch (val.ObjectType)
+            {
+                case ObjectTypes.Null:
+                    v = "null";
+                    break;
+                case ObjectTypes.Integer:
+                    v = val.Value.ToString();
+                    break;
+                case ObjectTypes.Object:
+                    {
+                        object obj = Interpreter.Stack.ManagedStack[val.Value];
+                        v = obj.ToString();
+                    }
+                    break;
+                default:
+                    v = "Unknown type";
+                    break;
+            }
+            return v;
+        }        
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/BreakPointContext.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: bfeefe6a2f833e2459c51dec09120b28
+timeCreated: 1486603952
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 14 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/BreakpointInfo.cs

@@ -0,0 +1,14 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace ILRuntime.Runtime.Debugger
+{
+    class BreakpointInfo
+    {
+        public int BreakpointHashCode { get; set; }
+        public int MethodHashCode { get; set; }
+        public int StartLine { get; set; }
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/BreakpointInfo.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: c1e1d9861d746594485e121a90ef9c38
+timeCreated: 1486603952
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 25 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/DebugMessageType.cs

@@ -0,0 +1,25 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace ILRuntime.Runtime.Debugger
+{
+    public enum DebugMessageType
+    {
+        CSAttach,
+        SCAttachResult,
+        CSBindBreakpoint,
+        SCBindBreakpointResult,
+        SCModuleLoaded,
+        SCThreadStarted,
+        SCThreadEnded,
+        SCBreakpointHit,
+        CSDeleteBreakpoint,
+        CSExecute,
+        CSStep,
+        SCStepComplete,
+        CSResolveVariable,
+        SCResolveVariableResult
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/DebugMessageType.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: a564f69cbf727c844bb66d4ef14055b8
+timeCreated: 1486603952
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 498 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/DebugService.cs

@@ -0,0 +1,498 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading;
+
+using ILRuntime.CLR.Method;
+using ILRuntime.Runtime.Intepreter;
+using ILRuntime.Runtime.Stack;
+using ILRuntime.CLR.Utils;
+
+namespace ILRuntime.Runtime.Debugger
+{
+    public class DebugService
+    {
+        BreakPointContext curBreakpoint;
+        DebuggerServer server;
+        Runtime.Enviorment.AppDomain domain;
+        Dictionary<int, LinkedList<BreakpointInfo>> activeBreakpoints = new Dictionary<int, LinkedList<BreakpointInfo>>();
+        Dictionary<int, BreakpointInfo> breakpointMapping = new Dictionary<int, BreakpointInfo>();
+        AutoResetEvent evt = new AutoResetEvent(false);
+        
+        public Action<string> OnBreakPoint;
+
+        public Enviorment.AppDomain AppDomain { get { return domain; } }
+
+        public AutoResetEvent BlockEvent { get { return evt; } }
+
+        public bool IsDebuggerAttached
+        {
+            get
+            {
+#if DEBUG
+                return (server != null && server.IsAttached);
+#else
+                return false;
+#endif
+            }
+        }
+
+        public DebugService(Runtime.Enviorment.AppDomain domain)
+        {
+            this.domain = domain;
+        }
+
+        /// <summary>
+        /// Start Debugger Server
+        /// </summary>
+        /// <param name="port">Port to listen on</param>
+        public void StartDebugService(int port)
+        {
+#if DEBUG
+            server = new Debugger.DebuggerServer(this);
+            server.Port = port;
+            server.Start();
+#endif
+        }
+
+        /// <summary>
+        /// Stop Debugger Server
+        /// </summary>
+        public void StopDebugService()
+        {
+#if DEBUG
+            server.Stop();
+            server = null;
+#endif
+        }
+
+        /// <summary>
+        /// 中断运行
+        /// </summary>
+        /// <param name="intpreter"></param>
+        /// <param name="ex"></param>
+        /// <returns>如果挂的有调试器则返回true</returns>
+        internal bool Break(ILIntepreter intpreter, Exception ex = null)
+        {
+            BreakPointContext ctx = new BreakPointContext();
+            ctx.Interpreter = intpreter;
+            ctx.Exception = ex;
+
+            curBreakpoint = ctx;
+
+            if (OnBreakPoint != null)
+            {
+                OnBreakPoint(ctx.DumpContext());
+                return true;
+            }
+            return false;
+        }
+
+        internal string GetStackTrance(ILIntepreter intepreper)
+        {
+            StringBuilder sb = new StringBuilder();
+            ILRuntime.CLR.Method.ILMethod m;
+            StackFrame[] frames = intepreper.Stack.Frames.ToArray();
+            Mono.Cecil.Cil.Instruction ins = null;
+            if (frames[0].Address != null)
+            {
+                ins = frames[0].Method.Definition.Body.Instructions[frames[0].Address.Value];
+                sb.AppendLine(ins.ToString());
+            }
+            for (int i = 0; i < frames.Length; i++)
+            {
+                var f = frames[i];
+                m = f.Method;
+                string document = "";
+                if (f.Address != null)
+                {
+                    ins = m.Definition.Body.Instructions[f.Address.Value];
+                    var seq = FindSequencePoint(ins);
+                    if (seq != null)
+                    {
+                        document = string.Format("{0}:Line {1}", seq.Document.Url, seq.StartLine);
+                    }
+                }
+                sb.AppendFormat("at {0} {1}\r\n", m, document);
+            }
+
+            return sb.ToString();
+        }
+
+        internal unsafe string GetThisInfo(ILIntepreter intepreter)
+        {
+            var topFrame = intepreter.Stack.Frames.Peek();
+            var arg = Minus(topFrame.LocalVarPointer, topFrame.Method.ParameterCount);
+            if (topFrame.Method.HasThis)
+                arg--;
+            if (arg->ObjectType == ObjectTypes.StackObjectReference)
+                arg = *(StackObject**)&arg->Value;
+            ILTypeInstance instance = arg->ObjectType != ObjectTypes.Null ? intepreter.Stack.ManagedStack[arg->Value] as ILTypeInstance : null;
+            if (instance == null)
+                return "null";
+            var fields = instance.Type.TypeDefinition.Fields;
+            int idx = 0;
+            StringBuilder sb = new StringBuilder();
+            for (int i = 0; i < fields.Count; i++)
+            {
+                var f = fields[i];
+                if (f.IsStatic)
+                    continue;
+                var field = instance.Fields[idx];
+                var v = StackObject.ToObject(&field, intepreter.AppDomain, instance.ManagedObjects);
+                if (v == null)
+                    v = "null";
+                string name = f.Name;
+                sb.AppendFormat("{0} {1} = {2}", f.FieldType.Name, name, v);
+                if ((idx % 3 == 0 && idx != 0) || idx == instance.Fields.Length - 1)
+                    sb.AppendLine();
+                else
+                    sb.Append(", ");
+                idx++;
+            }
+            return sb.ToString();
+        }
+
+        internal unsafe string GetLocalVariableInfo(ILIntepreter intepreter)
+        {
+            StackFrame topFrame = intepreter.Stack.Frames.Peek();
+            var m = topFrame.Method;
+            StringBuilder sb = new StringBuilder();
+            for (int i = 0; i < m.LocalVariableCount; i++)
+            {
+                var lv = m.Definition.Body.Variables[i];
+                var val = Add(topFrame.LocalVarPointer, i);
+                var v = StackObject.ToObject(val, intepreter.AppDomain, intepreter.Stack.ManagedStack);
+                if (v == null)
+                    v = "null";
+                string name = string.IsNullOrEmpty(lv.Name) ? "v" + lv.Index : lv.Name;
+                sb.AppendFormat("{0} {1} = {2}", lv.VariableType.Name, name, v);
+                if ((i % 3 == 0 && i != 0) || i == m.LocalVariableCount - 1)
+                    sb.AppendLine();
+                else
+                    sb.Append(", ");
+            }
+            return sb.ToString();
+        }
+
+        internal static Mono.Cecil.Cil.SequencePoint FindSequencePoint(Mono.Cecil.Cil.Instruction ins)
+        {
+            Mono.Cecil.Cil.Instruction cur = ins;
+            while (cur.SequencePoint == null && cur.Previous != null)
+                cur = cur.Previous;
+
+            return cur.SequencePoint;
+        }
+
+        unsafe StackObject* Add(StackObject* a, int b)
+        {
+            return (StackObject*)((long)a + sizeof(StackObject) * b);
+        }
+
+        unsafe StackObject* Minus(StackObject* a, int b)
+        {
+            return (StackObject*)((long)a - sizeof(StackObject) * b);
+        }
+
+        internal void NotifyModuleLoaded(string moduleName)
+        {
+            if (server != null && server.IsAttached)
+                server.NotifyModuleLoaded(moduleName);
+        }
+
+        internal void SetBreakPoint(int methodHash, int bpHash, int startLine)
+        {
+            lock (activeBreakpoints)
+            {
+                LinkedList<BreakpointInfo> lst;
+                if(!activeBreakpoints.TryGetValue(methodHash, out lst))
+                {
+                    lst = new LinkedList<Debugger.BreakpointInfo>();
+                    activeBreakpoints[methodHash] = lst;
+                }
+
+                BreakpointInfo bpInfo = new BreakpointInfo();
+                bpInfo.BreakpointHashCode = bpHash;
+                bpInfo.MethodHashCode = methodHash;
+                bpInfo.StartLine = startLine;
+
+                lst.AddLast(bpInfo);
+                breakpointMapping[bpHash] = bpInfo;
+            }
+        }
+
+        internal void DeleteBreakpoint(int bpHash)
+        {
+            lock (activeBreakpoints)
+            {
+                BreakpointInfo bpInfo;
+                if (breakpointMapping.TryGetValue(bpHash, out bpInfo))
+                {
+                    LinkedList<BreakpointInfo> lst;
+                    if(activeBreakpoints.TryGetValue(bpInfo.MethodHashCode, out lst))
+                    {
+                        lst.Remove(bpInfo);                        
+                    }
+                    breakpointMapping.Remove(bpHash);
+                }
+            }
+        }
+
+        internal void ExecuteThread(int threadHash)
+        {
+            lock (AppDomain.FreeIntepreters)
+            {
+                foreach(var i in AppDomain.Intepreters)
+                {
+                    //We should resume all threads on execute
+                    i.Value.ClearDebugState();
+                    i.Value.Resume();
+                }
+            }
+        }
+
+        internal unsafe void StepThread(int threadHash, StepTypes type)
+        {
+            lock (AppDomain.FreeIntepreters)
+            {
+                ILIntepreter intp;
+                if(AppDomain.Intepreters.TryGetValue(threadHash, out intp))
+                {
+                    intp.ClearDebugState();
+                    intp.CurrentStepType = type;
+                    intp.LastStepFrameBase = intp.Stack.Frames.Count > 0 ? intp.Stack.Frames.Peek().BasePointer : (StackObject*)0;
+                    intp.LastStepInstructionIndex = intp.Stack.Frames.Count > 0 ? intp.Stack.Frames.Peek().Address.Value : 0;
+
+                    intp.Resume();
+                }
+            }
+        }
+
+        unsafe internal void CheckShouldBreak(ILMethod method, ILIntepreter intp, int ip)
+        {
+            if (server != null && server.IsAttached)
+            {
+                int methodHash = method.GetHashCode();
+                lock (activeBreakpoints)
+                {
+                    LinkedList<BreakpointInfo> lst;
+                    bool bpHit = false;
+
+                    if (activeBreakpoints.TryGetValue(methodHash, out lst))
+                    {
+                        var sp = method.Definition.Body.Instructions[ip].SequencePoint;
+                        if (sp != null)
+                        {
+                            foreach (var i in lst)
+                            {
+                                if ((i.StartLine + 1) == sp.StartLine)
+                                {
+                                    DoBreak(intp, i.BreakpointHashCode, false);
+                                    bpHit = true;
+                                    break;
+                                }
+                            }
+                        }
+                    }
+
+                    if (!bpHit)
+                    {
+                        var sp = method.Definition.Body.Instructions[ip].SequencePoint;
+                        if (sp != null && IsSequenceValid(sp))
+                        {                            
+                            switch (intp.CurrentStepType)
+                            {
+                                case StepTypes.Into:
+                                    DoBreak(intp, 0, true);
+                                    break;
+                                case StepTypes.Over:
+                                    if (intp.Stack.Frames.Peek().BasePointer <= intp.LastStepFrameBase && ip != intp.LastStepInstructionIndex)
+                                    {
+                                        DoBreak(intp, 0, true);
+                                    }
+                                    break;
+                                case StepTypes.Out:
+                                    {
+                                        if (intp.Stack.Frames.Count > 0 && intp.Stack.Frames.Peek().BasePointer < intp.LastStepFrameBase)
+                                        {
+                                            DoBreak(intp, 0, true);
+                                        }
+                                    }
+                                    break;
+                            }
+                        }
+                    }
+                }
+            }
+        }
+
+        bool IsSequenceValid(Mono.Cecil.Cil.SequencePoint sp)
+        {
+            return sp.StartLine != sp.EndLine || sp.StartColumn != sp.EndColumn;
+        }
+
+        void DoBreak(ILIntepreter intp, int bpHash, bool isStep)
+        {
+            KeyValuePair<int, StackFrameInfo[]>[] frames = new KeyValuePair<int, StackFrameInfo[]>[AppDomain.Intepreters.Count];
+            frames[0] = new KeyValuePair<int, StackFrameInfo[]>(intp.GetHashCode(), GetStackFrameInfo(intp));
+            int idx = 1;
+            foreach (var j in AppDomain.Intepreters)
+            {
+                if (j.Value != intp)
+                {
+                    j.Value.ShouldBreak = true;
+                    frames[idx++] = new KeyValuePair<int, Debugger.StackFrameInfo[]>(j.Value.GetHashCode(), GetStackFrameInfo(j.Value));
+                }
+            }
+            if (!isStep)
+                server.SendSCBreakpointHit(intp.GetHashCode(), bpHash, frames);
+            else
+                server.SendSCStepComplete(intp.GetHashCode(), frames);
+            //Breakpoint hit
+            intp.Break();
+        }
+
+        unsafe StackFrameInfo[] GetStackFrameInfo(ILIntepreter intp)
+        {
+            StackFrame[] frames = intp.Stack.Frames.ToArray();
+            Mono.Cecil.Cil.Instruction ins = null;
+            ILMethod m;
+            StackFrameInfo[] frameInfos = new StackFrameInfo[frames.Length];
+
+            for (int j = 0; j < frames.Length; j++)
+            {
+                StackFrameInfo info = new Debugger.StackFrameInfo();
+                var f = frames[j];
+                m = f.Method;
+                info.MethodName = m.ToString();
+
+                if (f.Address != null)
+                {
+                    ins = m.Definition.Body.Instructions[f.Address.Value];
+                    var seq = FindSequencePoint(ins);
+                    if (seq != null)
+                    {
+                        info.DocumentName = seq.Document.Url;
+                        info.StartLine = seq.StartLine - 1;
+                        info.StartColumn = seq.StartColumn - 1;
+                        info.EndLine = seq.EndLine - 1;
+                        info.EndColumn = seq.EndColumn - 1;
+                    }
+                }
+                StackFrame topFrame = f;
+                m = topFrame.Method;
+                int argumentCount = m.ParameterCount;
+                if (m.HasThis)
+                    argumentCount++;
+                info.LocalVariables = new VariableInfo[argumentCount + m.LocalVariableCount];
+                for(int i = 0; i < argumentCount; i++)
+                {
+                    int argIdx = m.HasThis ? i - 1 : i;
+                    var arg = Minus(topFrame.LocalVarPointer, argumentCount);
+                    string name = null;
+                    object v = null;
+                    string typeName = null;
+                    var val = Add(arg, i);
+                    v =  StackObject.ToObject(val, intp.AppDomain, intp.Stack.ManagedStack);
+                    if (v == null)
+                        v = "null";
+                    if (argIdx >= 0)
+                    {
+                        var lv = m.Definition.Parameters[argIdx];
+                        name = string.IsNullOrEmpty(lv.Name) ? "arg" + lv.Index : lv.Name;
+                        typeName = lv.ParameterType.FullName;
+                        if (v != null)
+                            v = m.Parameters[argIdx].TypeForCLR.CheckCLRTypes(intp.AppDomain, v);
+                    }
+                    else
+                    {
+                        name = "this";
+                        typeName = m.DeclearingType.FullName;
+                    }
+
+                    VariableInfo vinfo = new Debugger.VariableInfo();
+                    vinfo.Address = (long)val;
+                    vinfo.Name = name;
+                    vinfo.Value = v.ToString();
+                    vinfo.TypeName = typeName;
+                    vinfo.Expandable = GetValueExpandable(val, intp.Stack.ManagedStack);
+
+                    info.LocalVariables[i] = vinfo;
+                }
+                for (int i = argumentCount; i < info.LocalVariables.Length; i++)
+                {
+                    var locIdx = i - argumentCount;
+                    var lv = m.Definition.Body.Variables[locIdx];
+                    var val = Add(topFrame.LocalVarPointer, locIdx);
+                    var v = StackObject.ToObject(val, intp.AppDomain, intp.Stack.ManagedStack);
+                    if (v == null)
+                        v = "null";
+                    else
+                        v = intp.AppDomain.GetType(lv.VariableType, m.DeclearingType, m).TypeForCLR.CheckCLRTypes(intp.AppDomain, v);
+                    string name = string.IsNullOrEmpty(lv.Name) ? "v" + lv.Index : lv.Name;
+                    VariableInfo vinfo = new Debugger.VariableInfo();
+                    vinfo.Address = (long)val;
+                    vinfo.Name = name;
+                    vinfo.Value = v.ToString();
+                    vinfo.TypeName = lv.VariableType.FullName;
+                    vinfo.Expandable = GetValueExpandable(val, intp.Stack.ManagedStack);
+                    info.LocalVariables[i] = vinfo;
+                }
+                frameInfos[j] = info;
+            }
+            return frameInfos;
+        }
+
+        internal VariableInfo ResolveVariable(VariableReference parent, string name)
+        {
+            return null;
+        }
+
+        unsafe bool GetValueExpandable(StackObject* esp, List<object> mStack)
+        {
+            if (esp->ObjectType < ObjectTypes.Object)
+                return false;
+            else
+            {
+                var obj = mStack[esp->Value];
+                if (obj == null)
+                    return false;
+                if (obj is ILTypeInstance)
+                    return true;
+                else if (obj.GetType().IsPrimitive)
+                    return false;
+                else
+                    return true;
+
+            }
+        }
+
+        internal void ThreadStarted(ILIntepreter intp)
+        {
+            if (server != null && server.IsAttached)
+            {
+                server.SendSCThreadStarted(intp.GetHashCode());
+            }
+        }
+
+        internal void ThreadEnded(ILIntepreter intp)
+        {
+            if (server != null && server.IsAttached)
+            {
+                server.SendSCThreadEnded(intp.GetHashCode());
+            }
+        }
+
+        internal void Detach()
+        {
+            activeBreakpoints.Clear();
+            breakpointMapping.Clear();
+            foreach (var j in AppDomain.Intepreters)
+            {
+                j.Value.ClearDebugState();
+                j.Value.Resume();
+            }
+        }
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/DebugService.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: bca0b6c7c373ab74b96df13b5517171c
+timeCreated: 1486603952
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 235 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/DebugSocket.cs

@@ -0,0 +1,235 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.IO;
+using System.Net.Sockets;
+
+namespace ILRuntime.Runtime.Debugger
+{
+    public class DebugSocket
+    {
+        private Socket _socket = null;
+        private bool _ready = false;
+        bool connectFailed = false;
+        private const int MAX_BUFF_SIZE = 256 * 1024;
+        private const int HEAD_SIZE = 8;
+        private byte[] _headBuffer = new byte[HEAD_SIZE];
+        private byte[] _sendBuffer = new byte[64 * 1024];
+        //private MemoryPoolSafe<Package> _packagePool = new MemoryPoolSafe<Package>();
+        //private Package _currPackage = null;
+        private System.IO.MemoryStream _sendStream = null;
+        BinaryWriter bw;
+        const int RECV_BUFFER_SIZE = 1024;
+        private MemoryStream recvBuffer = new MemoryStream();
+        private int lastMsgLength = -1;
+
+        private byte[] socketAsyncBuffer = new byte[RECV_BUFFER_SIZE];
+        private SocketAsyncEventArgs saeArgs;
+        private object socketLockObj = new object();
+        private byte[] _sendHeaderBuffer = new byte[HEAD_SIZE];
+
+        public bool Disconnected { get { return _socket == null || !_socket.Connected; } }
+        public Action OnConnect { get; set; }
+
+        public Action OnConnectFailed { get; set; }
+        public Action OnClose { get; set; }
+
+        public Action<DebugMessageType, byte[]> OnReciveMessage { get; set; }
+
+
+        public DebugSocket()
+        {
+            _sendStream = new System.IO.MemoryStream(_sendBuffer);
+            bw = new BinaryWriter(_sendStream);
+        }
+        public DebugSocket(Socket _socket)
+            : this()
+        {
+            this._socket = _socket;
+            BeginReceive();
+            _ready = true;
+        }
+        public void Connect(string ip, int port)
+        {
+            Close();
+            Socket socket;
+            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+            socket.BeginConnect(ip, port, new AsyncCallback(onConnected), this);
+            _socket = socket;
+            _ready = false;
+        }
+
+        private void AsyncRecv_Completed(object sender, SocketAsyncEventArgs e)
+        {
+            if (e.SocketError == SocketError.Success && e.BytesTransferred > 0)
+            {
+                try
+                {
+                    ReceivePayload(e.Buffer, e.BytesTransferred);
+                }
+                catch (Exception ex)
+                {
+                    Close();
+                    return;
+                }
+            }
+            else
+            {
+                Close();
+                return;
+            }
+
+            try
+            {
+                //继续接受数据
+                if (!_socket.ReceiveAsync(saeArgs))
+                {
+                    AsyncRecv_Completed(null, saeArgs);
+                }
+            }
+            catch (Exception ex)
+            {
+                Close();
+                throw ex;
+            }
+        }
+
+        private void ReceivePayload(byte[] data, int length)
+        {
+            if (_socket == null)
+                return;
+            if (!_socket.Connected)
+            {
+                Close();
+                return;
+            }
+            //接受数据并拼接成message
+            byte[] msgBuff;
+            //写入缓存
+            recvBuffer.Position = recvBuffer.Length;
+            recvBuffer.Write(data, 0, length);
+            //如果长度有错,返回
+            if (lastMsgLength < 0 && recvBuffer.Length < 4)
+            {
+                msgBuff = null;
+                return;
+            }
+
+            recvBuffer.Position = 0;
+            BinaryReader br = new BinaryReader(recvBuffer);
+            //读取消息长度
+            if (lastMsgLength < 0)
+            {
+                lastMsgLength = br.ReadInt32() - 4;
+                if (lastMsgLength > MAX_BUFF_SIZE)
+                {
+                    Close();
+                    throw new Exception("Too long package length!");
+                }
+            }
+            int remaining = (int)(recvBuffer.Length - recvBuffer.Position);
+            //消息已经完整
+            while (remaining >= lastMsgLength && lastMsgLength > 0)
+            {
+
+                //读取一条消息
+                int type = br.ReadInt32();
+                msgBuff = br.ReadBytes(lastMsgLength - 4);
+
+                if (OnReciveMessage != null)
+                    OnReciveMessage((DebugMessageType)type, msgBuff);
+
+                lastMsgLength = -1;
+                remaining = (int)(recvBuffer.Length - recvBuffer.Position);
+                //保留剩余数据
+                if (remaining >= 4)
+                {
+                    lastMsgLength = br.ReadInt32() - 4;
+                    remaining -= 4;
+                    if (lastMsgLength > MAX_BUFF_SIZE)
+                    {
+                        Close();
+                        throw new Exception("Too long package length!");
+                    }
+                }
+            }
+
+            remaining = (int)(recvBuffer.Length - recvBuffer.Position);
+            if (remaining > 0)
+            {
+                byte[] buffer = recvBuffer.GetBuffer();
+                Array.Copy(buffer, recvBuffer.Position, buffer, 0, remaining);
+            }
+            recvBuffer.Position = 0;
+            recvBuffer.SetLength(remaining);
+        }
+        private void onConnected(IAsyncResult result)
+        {
+            if (_socket.Connected)
+            {
+                _socket.EndConnect(result);
+
+                BeginReceive();
+                if (OnConnect != null)
+                    OnConnect();
+                //ReceiveOnce();
+            }
+            else
+            {
+                if (OnConnectFailed != null)
+                    OnConnectFailed();
+            }
+        }
+
+        void BeginReceive()
+        {
+            saeArgs = new SocketAsyncEventArgs();
+            saeArgs.Completed += AsyncRecv_Completed;
+            saeArgs.SetBuffer(socketAsyncBuffer, 0, socketAsyncBuffer.Length);
+            _socket.ReceiveAsync(saeArgs);
+            _ready = true;
+        }
+
+        //len type msg
+        public void Send(DebugMessageType type, byte[] buffer, int len)
+        {
+            if (!_ready)
+                return;
+
+            //timeStamp = UnityEngine.Time.realtimeSinceStartup;
+            _sendStream.Position = 0;
+            bw.Write(len + HEAD_SIZE);
+            bw.Write((int)type);
+            bw.Write(buffer, 0, len);
+            int totalLen = (int)_sendStream.Position;
+
+            RawSend(_socket, _sendBuffer, totalLen);
+            //_socket.Send(_sendBuffer, len, SocketFlags.None);
+        }
+
+        private void RawSend(Socket sock, byte[] buf, int end)
+        {
+            if (sock == null)
+                return;
+            if (end < 0)
+                end = buf.Length;
+            sock.Send(buf, end, SocketFlags.None);
+        }
+
+        public void Close()
+        {
+            if (_socket == null || !_ready)
+                return;
+            if (saeArgs != null)
+                saeArgs.Dispose();
+            _socket.Close();
+            _socket = null;
+            _ready = false;
+            if (OnClose != null)
+            {
+                OnClose();
+            }
+        }
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/DebugSocket.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: e514adc780b8fd94d94c8bedf0cdc91f
+timeCreated: 1486603952
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 9 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/DebuggerServer.meta

@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: 42158ac895f5be84694c2f7718da4dbd
+folderAsset: yes
+timeCreated: 1486603935
+licenseType: Pro
+DefaultImporter:
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 340 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/DebuggerServer/DebuggerServer.cs

@@ -0,0 +1,340 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Net.Sockets;
+using ILRuntime.CLR.TypeSystem;
+using ILRuntime.CLR.Method;
+using ILRuntime.Runtime.Debugger.Protocol;
+
+namespace ILRuntime.Runtime.Debugger
+{
+    public class DebuggerServer
+    {
+        public const int Version = 1;
+        TcpListener listener;
+        //HashSet<Session<T>> clients = new HashSet<Session<T>>();
+        bool isUp = false;
+        int maxNewConnections = 1;
+        int port;
+        Thread mainLoop;
+        DebugSocket clientSocket;
+        System.IO.MemoryStream sendStream = new System.IO.MemoryStream(64 * 1024);
+        System.IO.BinaryWriter bw;
+        DebugService ds;
+
+        /// <summary>
+        /// 服务器监听的端口
+        /// </summary>
+        public int Port { get { return port; } set { this.port = value; } }
+
+        public DebugSocket Client { get { return clientSocket; } }
+
+        public bool IsAttached { get { return clientSocket != null && !clientSocket.Disconnected; } }
+
+        public DebuggerServer(DebugService ds)
+        {
+            this.ds = ds;
+            bw = new System.IO.BinaryWriter(sendStream);
+        }
+
+        public virtual bool Start()
+        {
+            mainLoop = new Thread(new ThreadStart(this.NetworkLoop));
+            mainLoop.Start();
+
+            this.listener = new TcpListener(port);
+            try { listener.Start(); }
+            catch
+            {
+                return false;
+            }
+            isUp = true;
+            return true;
+        }
+
+        public virtual void Stop()
+        {
+            isUp = false;
+            if (this.listener != null)
+                this.listener.Stop();
+            mainLoop.Abort();
+            mainLoop = null;
+        }
+
+        void NetworkLoop()
+        {
+            while (true)
+            {
+                try
+                {
+                    // let new clients (max 10) connect
+                    if (isUp && clientSocket == null)
+                    {
+                        for (int i = 0; listener.Pending() && i < maxNewConnections; i++)
+                        {
+                            CreateNewSession(listener);
+                        }
+                    }
+                    System.Threading.Thread.Sleep(1);
+                }
+                catch (ThreadAbortException)
+                {
+                }
+                catch (Exception)
+                {
+                    
+                }
+            }
+        }
+
+        void CreateNewSession(TcpListener listener)
+        {
+            Socket sock = listener.AcceptSocket();
+            clientSocket = new DebugSocket(sock);           
+            clientSocket.OnReciveMessage = OnReceive;
+            clientSocket.OnClose = OnClose;
+            ClientConnected();
+        }
+
+        void ClientConnected()
+        {
+
+        }
+
+        void OnClose()
+        {
+            ds.Detach();
+            clientSocket = null;
+        }
+
+        void OnReceive(DebugMessageType type, byte[] buffer)
+        {
+            if (clientSocket == null || clientSocket.Disconnected)
+                return;
+            System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer);
+            System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
+
+            switch (type)
+            {
+                case DebugMessageType.CSAttach:
+                    {
+                        SendAttachResult();
+                    }
+                    break;
+                case DebugMessageType.CSBindBreakpoint:
+                    {
+                        CSBindBreakpoint msg = new Protocol.CSBindBreakpoint();
+                        msg.BreakpointHashCode = br.ReadInt32();
+                        msg.TypeName = br.ReadString();
+                        msg.MethodName = br.ReadString();
+                        msg.StartLine = br.ReadInt32();
+                        msg.EndLine = br.ReadInt32();
+                        TryBindBreakpoint(msg);
+                    }
+                    break;
+                case DebugMessageType.CSDeleteBreakpoint:
+                    {
+                        CSDeleteBreakpoint msg = new Protocol.CSDeleteBreakpoint();
+                        msg.BreakpointHashCode = br.ReadInt32();
+                        ds.DeleteBreakpoint(msg.BreakpointHashCode);
+                    }
+                    break;
+                case DebugMessageType.CSExecute:
+                    {
+                        CSExecute msg = new Protocol.CSExecute();
+                        msg.ThreadHashCode = br.ReadInt32();
+                        ds.ExecuteThread(msg.ThreadHashCode);
+                    }
+                    break;
+                case DebugMessageType.CSStep:
+                    {
+                        CSStep msg = new CSStep();
+                        msg.ThreadHashCode = br.ReadInt32();
+                        msg.StepType = (StepTypes)br.ReadByte();
+                        ds.StepThread(msg.ThreadHashCode, msg.StepType);
+                    }
+                    break;
+                case DebugMessageType.CSResolveVariable:
+                    {
+                        CSResolveVariable msg = new CSResolveVariable();
+                        msg.Name = br.ReadString();
+                        msg.Parent = ReadVariableReference(br);
+                        var info = ds.ResolveVariable(msg.Parent, msg.Name);
+                    }
+                    break;
+            }
+
+        }
+
+        VariableReference ReadVariableReference(System.IO.BinaryReader br)
+        {
+            VariableReference res = null;
+            if (br.ReadBoolean())
+            {
+                res = new Debugger.VariableReference();
+                res.Address = br.ReadInt64();
+                res.Type = (VariableTypes)br.ReadByte();
+                res.Offset = br.ReadInt32();
+                res.Parent = ReadVariableReference(br);
+            }
+            return res;
+        }
+
+        void SendAttachResult()
+        {
+            sendStream.Position = 0;
+            bw.Write((byte)AttachResults.OK);
+            bw.Write(Version);
+            DoSend(DebugMessageType.SCAttachResult);
+            lock (ds.AppDomain.FreeIntepreters)
+            {
+                foreach (var i in ds.AppDomain.Intepreters)
+                {
+                    SendSCThreadStarted(i.Key);
+                }
+            }
+        }
+
+        void DoSend(DebugMessageType type)
+        {
+            if (clientSocket != null && !clientSocket.Disconnected)
+                clientSocket.Send(type, sendStream.GetBuffer(), (int)sendStream.Position);
+        }
+
+        void TryBindBreakpoint(CSBindBreakpoint msg)
+        {
+            var domain = ds.AppDomain;
+            SCBindBreakpointResult res = new Protocol.SCBindBreakpointResult();
+            res.BreakpointHashCode = msg.BreakpointHashCode;
+            IType type;
+            if (domain.LoadedTypes.TryGetValue(msg.TypeName, out type))
+            {
+                if(type is ILType)
+                {
+                    ILType it = (ILType)type;
+                    ILMethod found = null;
+                    foreach(var i in it.GetMethods())
+                    {
+                        if(i.Name == msg.MethodName)
+                        {
+                            ILMethod ilm = (ILMethod)i;
+                            if (ilm.StartLine <= (msg.StartLine + 1) && ilm.EndLine >= (msg.StartLine + 1))
+                            {
+                                found = ilm;
+                                break;
+                            }
+                        }
+                    }
+                    if(found != null)
+                    {
+                        ds.SetBreakPoint(found.GetHashCode(), msg.BreakpointHashCode, msg.StartLine);
+                        res.Result = BindBreakpointResults.OK;
+                    }
+                    else
+                    {
+                        res.Result = BindBreakpointResults.CodeNotFound;
+                    }
+                }
+                else
+                {
+                    res.Result = BindBreakpointResults.TypeNotFound;
+                }
+            }
+            else
+            {
+                res.Result = BindBreakpointResults.TypeNotFound;
+            }
+            SendSCBindBreakpointResult(res);
+        }
+
+        void SendSCBindBreakpointResult(SCBindBreakpointResult msg)
+        {
+            sendStream.Position = 0;
+            bw.Write(msg.BreakpointHashCode);
+            bw.Write((byte)msg.Result);
+            DoSend(DebugMessageType.SCBindBreakpointResult);
+        }
+
+        internal void SendSCBreakpointHit(int intpHash, int bpHash, KeyValuePair<int, StackFrameInfo[]>[] info)
+        {
+            sendStream.Position = 0;
+            bw.Write(bpHash);
+            bw.Write(intpHash);
+            WriteStackFrames(info);
+            DoSend(DebugMessageType.SCBreakpointHit);
+        }
+
+        internal void SendSCStepComplete(int intpHash, KeyValuePair<int, StackFrameInfo[]>[] info)
+        {
+            sendStream.Position = 0;
+            bw.Write(intpHash);
+            WriteStackFrames(info);
+            DoSend(DebugMessageType.SCStepComplete);
+        }
+
+        void SendSCResolveVariableResult(VariableInfo info)
+        {
+            sendStream.Position = 0;
+            WriteVariableInfo(info);
+            DoSend(DebugMessageType.SCResolveVariableResult);
+        }
+
+        void WriteStackFrames(KeyValuePair<int, StackFrameInfo[]>[] info)
+        {
+            bw.Write(info.Length);
+            foreach (var i in info)
+            {
+                bw.Write(i.Key);
+                bw.Write(i.Value.Length);
+                foreach (var j in i.Value)
+                {
+                    bw.Write(j.MethodName);
+                    bw.Write(j.DocumentName);
+                    bw.Write(j.StartLine);
+                    bw.Write(j.StartColumn);
+                    bw.Write(j.EndLine);
+                    bw.Write(j.EndColumn);
+                    bw.Write(j.LocalVariables.Length);
+                    foreach (var k in j.LocalVariables)
+                    {
+                        WriteVariableInfo(k);
+                    }
+                }
+            }
+        }
+
+        void WriteVariableInfo(VariableInfo k)
+        {
+            bw.Write(k.Address);
+            bw.Write((byte)k.Type);
+            bw.Write(k.Offset);
+            bw.Write(k.Name);
+            bw.Write(k.Value);
+            bw.Write(k.TypeName);
+            bw.Write(k.Expandable);
+        }
+
+        internal void SendSCThreadStarted(int threadHash)
+        {
+            sendStream.Position = 0;
+            bw.Write(threadHash);
+            DoSend(DebugMessageType.SCThreadStarted);
+        }
+
+        internal void SendSCThreadEnded(int threadHash)
+        {
+            sendStream.Position = 0;
+            bw.Write(threadHash);
+            DoSend(DebugMessageType.SCThreadEnded);
+        }
+
+        public void NotifyModuleLoaded(string modulename)
+        {
+            sendStream.Position = 0;
+            bw.Write(modulename);
+            DoSend(DebugMessageType.SCModuleLoaded);
+        }
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/DebuggerServer/DebuggerServer.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 52306472508bb034f8fd1b68d450ce8e
+timeCreated: 1486603950
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 9 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/Protocol.meta

@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: 0b6dc6efcc1ee084ea277d2446c90b1a
+folderAsset: yes
+timeCreated: 1486603934
+licenseType: Pro
+DefaultImporter:
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 16 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/Protocol/CSBindBreakpoint.cs

@@ -0,0 +1,16 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace ILRuntime.Runtime.Debugger.Protocol
+{
+    public class CSBindBreakpoint
+    {
+        public int BreakpointHashCode { get; set; }
+        public string TypeName { get; set; }
+        public string MethodName { get; set; }
+        public int StartLine { get; set; }
+        public int EndLine { get; set; }
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/Protocol/CSBindBreakpoint.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: aa0ea609114467a41941ebad10e2c081
+timeCreated: 1486603952
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/Protocol/CSDeleteBreakpoint.cs

@@ -0,0 +1,12 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace ILRuntime.Runtime.Debugger.Protocol
+{
+    public class CSDeleteBreakpoint
+    {
+        public int BreakpointHashCode { get; set; }
+    }
+}

+ 12 - 0
Unity/Assets/ILRuntime/ILRuntime/Runtime/Debugger/Protocol/CSDeleteBreakpoint.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 58263d5697f506248a2a9fe66a69f3b1
+timeCreated: 1486603951
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

Неке датотеке нису приказане због велике количине промена