CustomAttributeBuilder.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. //
  2. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining
  5. // a copy of this software and associated documentation files (the
  6. // "Software"), to deal in the Software without restriction, including
  7. // without limitation the rights to use, copy, modify, merge, publish,
  8. // distribute, sublicense, and/or sell copies of the Software, and to
  9. // permit persons to whom the Software is furnished to do so, subject to
  10. // the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be
  13. // included in all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  19. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  20. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  21. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. //
  23. //
  24. // System.Reflection.Emit/CustomAttributeBuilder.cs
  25. //
  26. // Author:
  27. // Paolo Molaro ([email protected])
  28. //
  29. // (C) 2001 Ximian, Inc. http://www.ximian.com
  30. //
  31. using System;
  32. using System.Reflection;
  33. using System.Reflection.Emit;
  34. using System.Runtime.CompilerServices;
  35. using System.Runtime.InteropServices;
  36. namespace System.Reflection.Emit {
  37. [ComVisible (true)]
  38. [ComDefaultInterface (typeof (_CustomAttributeBuilder))]
  39. [ClassInterface (ClassInterfaceType.None)]
  40. public class CustomAttributeBuilder : _CustomAttributeBuilder {
  41. ConstructorInfo ctor;
  42. byte[] data;
  43. internal ConstructorInfo Ctor {
  44. get {return ctor;}
  45. }
  46. internal byte[] Data {
  47. get {return data;}
  48. }
  49. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  50. static extern byte[] GetBlob(Assembly asmb, ConstructorInfo con, object[] constructorArgs, PropertyInfo[] namedProperties, object[] propertyValues, FieldInfo[] namedFields, object[] fieldValues);
  51. internal CustomAttributeBuilder( ConstructorInfo con, byte[] cdata) {
  52. ctor = con;
  53. data = (byte[])cdata.Clone ();
  54. /* should we check that the user supplied data is correct? */
  55. }
  56. public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs)
  57. {
  58. Initialize (con, constructorArgs, new PropertyInfo [0], new object [0],
  59. new FieldInfo [0], new object [0]);
  60. }
  61. public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs,
  62. FieldInfo[] namedFields, object[] fieldValues)
  63. {
  64. Initialize (con, constructorArgs, new PropertyInfo [0], new object [0],
  65. namedFields, fieldValues);
  66. }
  67. public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs,
  68. PropertyInfo[] namedProperties, object[] propertyValues)
  69. {
  70. Initialize (con, constructorArgs, namedProperties, propertyValues, new FieldInfo [0],
  71. new object [0]);
  72. }
  73. public CustomAttributeBuilder( ConstructorInfo con, object[] constructorArgs,
  74. PropertyInfo[] namedProperties, object[] propertyValues,
  75. FieldInfo[] namedFields, object[] fieldValues)
  76. {
  77. Initialize (con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues);
  78. }
  79. private bool IsValidType (Type t)
  80. {
  81. /* FIXME: Add more checks */
  82. if (t.IsArray && t.GetArrayRank () > 1)
  83. return false;
  84. if (t is TypeBuilder && t.IsEnum) {
  85. // Check that the enum is properly constructed, the unmanaged code
  86. // depends on this
  87. Enum.GetUnderlyingType (t);
  88. }
  89. if (t.IsClass && !(t.IsArray || t == typeof (object) || t == typeof (Type) || t == typeof (string) || t.Assembly.GetName ().Name == "mscorlib"))
  90. return false;
  91. if (t.IsValueType && !(t.IsPrimitive || t.IsEnum || ((t.Assembly is AssemblyBuilder) && t.Assembly.GetName ().Name == "mscorlib")))
  92. return false;
  93. return true;
  94. }
  95. private bool IsValidParam (object o, Type paramType)
  96. {
  97. Type t = o.GetType ();
  98. if (!IsValidType (t))
  99. return false;
  100. if (paramType == typeof (object)) {
  101. if (t.IsArray && t.GetArrayRank () == 1)
  102. return IsValidType (t.GetElementType ());
  103. if (!t.IsPrimitive && !typeof (Type).IsAssignableFrom (t) && t != typeof (string) && !t.IsEnum)
  104. return false;
  105. }
  106. return true;
  107. }
  108. private void Initialize (ConstructorInfo con, object [] constructorArgs,
  109. PropertyInfo [] namedProperties, object [] propertyValues,
  110. FieldInfo [] namedFields, object [] fieldValues)
  111. {
  112. ctor = con;
  113. if (con == null)
  114. throw new ArgumentNullException ("con");
  115. if (constructorArgs == null)
  116. throw new ArgumentNullException ("constructorArgs");
  117. if (namedProperties == null)
  118. throw new ArgumentNullException ("namedProperties");
  119. if (propertyValues == null)
  120. throw new ArgumentNullException ("propertyValues");
  121. if (namedFields == null)
  122. throw new ArgumentNullException ("namedFields");
  123. if (fieldValues == null)
  124. throw new ArgumentNullException ("fieldValues");
  125. if (con.GetParameterCount () != constructorArgs.Length)
  126. throw new ArgumentException ("Parameter count does not match " +
  127. "passed in argument value count.");
  128. if (namedProperties.Length != propertyValues.Length)
  129. throw new ArgumentException ("Array lengths must be the same.",
  130. "namedProperties, propertyValues");
  131. if (namedFields.Length != fieldValues.Length)
  132. throw new ArgumentException ("Array lengths must be the same.",
  133. "namedFields, fieldValues");
  134. if ((con.Attributes & MethodAttributes.Static) == MethodAttributes.Static ||
  135. (con.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private)
  136. throw new ArgumentException ("Cannot have private or static constructor.");
  137. Type atype = ctor.DeclaringType;
  138. int i;
  139. i = 0;
  140. foreach (FieldInfo fi in namedFields) {
  141. Type t = fi.DeclaringType;
  142. if ((atype != t) && (!t.IsSubclassOf (atype)) && (!atype.IsSubclassOf (t)))
  143. throw new ArgumentException ("Field '" + fi.Name + "' does not belong to the same class as the constructor");
  144. if (!IsValidType (fi.FieldType))
  145. throw new ArgumentException ("Field '" + fi.Name + "' does not have a valid type.");
  146. // FIXME: Check enums and TypeBuilders as well
  147. if (fieldValues [i] != null)
  148. // IsEnum does not seem to work on TypeBuilders
  149. if (!(fi.FieldType is TypeBuilder) && !fi.FieldType.IsEnum && !fi.FieldType.IsInstanceOfType (fieldValues [i])) {
  150. //
  151. // mcs allways uses object[] for array types and
  152. // MS.NET allows this
  153. //
  154. if (!fi.FieldType.IsArray)
  155. throw new ArgumentException ("Value of field '" + fi.Name + "' does not match field type: " + fi.FieldType);
  156. }
  157. i ++;
  158. }
  159. i = 0;
  160. foreach (PropertyInfo pi in namedProperties) {
  161. if (!pi.CanWrite)
  162. throw new ArgumentException ("Property '" + pi.Name + "' does not have a setter.");
  163. Type t = pi.DeclaringType;
  164. if ((atype != t) && (!t.IsSubclassOf (atype)) && (!atype.IsSubclassOf (t)))
  165. throw new ArgumentException ("Property '" + pi.Name + "' does not belong to the same class as the constructor");
  166. if (!IsValidType (pi.PropertyType))
  167. throw new ArgumentException ("Property '" + pi.Name + "' does not have a valid type.");
  168. if (propertyValues [i] != null) {
  169. if (!(pi.PropertyType is TypeBuilder) && !pi.PropertyType.IsEnum && !pi.PropertyType.IsInstanceOfType (propertyValues [i]))
  170. if (!pi.PropertyType.IsArray)
  171. throw new ArgumentException ("Value of property '" + pi.Name + "' does not match property type: " + pi.PropertyType + " -> " + propertyValues [i]);
  172. }
  173. i ++;
  174. }
  175. i = 0;
  176. foreach (ParameterInfo pi in GetParameters (con)) {
  177. if (pi != null) {
  178. Type paramType = pi.ParameterType;
  179. if (!IsValidType (paramType))
  180. throw new ArgumentException ("Parameter " + i + " does not have a valid type.");
  181. if (constructorArgs [i] != null) {
  182. if (!(paramType is TypeBuilder) && !paramType.IsEnum && !paramType.IsInstanceOfType (constructorArgs [i]))
  183. if (!paramType.IsArray)
  184. throw new ArgumentException ("Value of argument " + i + " does not match parameter type: " + paramType + " -> " + constructorArgs [i]);
  185. if (!IsValidParam (constructorArgs [i], paramType))
  186. throw new ArgumentException ("Cannot emit a CustomAttribute with argument of type " + constructorArgs [i].GetType () + ".");
  187. }
  188. }
  189. i ++;
  190. }
  191. data = GetBlob (atype.Assembly, con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues);
  192. }
  193. /* helper methods */
  194. internal static int decode_len (byte[] data, int pos, out int rpos) {
  195. int len = 0;
  196. if ((data [pos] & 0x80) == 0) {
  197. len = (int)(data [pos++] & 0x7f);
  198. } else if ((data [pos] & 0x40) == 0) {
  199. len = ((data [pos] & 0x3f) << 8) + data [pos + 1];
  200. pos += 2;
  201. } else {
  202. len = ((data [pos] & 0x1f) << 24) + (data [pos + 1] << 16) + (data [pos + 2] << 8) + data [pos + 3];
  203. pos += 4;
  204. }
  205. rpos = pos;
  206. return len;
  207. }
  208. internal static string string_from_bytes (byte[] data, int pos, int len)
  209. {
  210. return System.Text.Encoding.UTF8.GetString(data, pos, len);
  211. }
  212. internal string string_arg ()
  213. {
  214. int pos = 2;
  215. int len = decode_len (data, pos, out pos);
  216. return string_from_bytes (data, pos, len);
  217. }
  218. internal static UnmanagedMarshal get_umarshal (CustomAttributeBuilder customBuilder, bool is_field) {
  219. byte[] data = customBuilder.Data;
  220. UnmanagedType subtype = (UnmanagedType)0x50; /* NATIVE_MAX */
  221. int sizeConst = -1;
  222. int sizeParamIndex = -1;
  223. bool hasSize = false;
  224. int value;
  225. int utype; /* the (stupid) ctor takes a short or an enum ... */
  226. string marshalTypeName = null;
  227. Type marshalTypeRef = null;
  228. string marshalCookie = String.Empty;
  229. utype = (int)data [2];
  230. utype |= ((int)data [3]) << 8;
  231. string first_type_name = GetParameters (customBuilder.Ctor) [0].ParameterType.FullName;
  232. int pos = 6;
  233. if (first_type_name == "System.Int16")
  234. pos = 4;
  235. int nnamed = (int)data [pos++];
  236. nnamed |= ((int)data [pos++]) << 8;
  237. for (int i = 0; i < nnamed; ++i) {
  238. int paramType; // What is this ?
  239. /* Skip field/property signature */
  240. pos ++;
  241. /* Read type */
  242. paramType = ((int)data [pos++]);
  243. if (paramType == 0x55) {
  244. /* enums, the value is preceeded by the type */
  245. int len2 = decode_len (data, pos, out pos);
  246. string_from_bytes (data, pos, len2);
  247. pos += len2;
  248. }
  249. int len = decode_len (data, pos, out pos);
  250. string named_name = string_from_bytes (data, pos, len);
  251. pos += len;
  252. switch (named_name) {
  253. case "ArraySubType":
  254. value = (int)data [pos++];
  255. value |= ((int)data [pos++]) << 8;
  256. value |= ((int)data [pos++]) << 16;
  257. value |= ((int)data [pos++]) << 24;
  258. subtype = (UnmanagedType)value;
  259. break;
  260. case "SizeConst":
  261. value = (int)data [pos++];
  262. value |= ((int)data [pos++]) << 8;
  263. value |= ((int)data [pos++]) << 16;
  264. value |= ((int)data [pos++]) << 24;
  265. sizeConst = value;
  266. hasSize = true;
  267. break;
  268. case "SafeArraySubType":
  269. value = (int)data[pos++];
  270. value |= ((int)data[pos++]) << 8;
  271. value |= ((int)data[pos++]) << 16;
  272. value |= ((int)data[pos++]) << 24;
  273. subtype = (UnmanagedType)value;
  274. break;
  275. case "IidParameterIndex":
  276. pos += 4;
  277. break;
  278. case "SafeArrayUserDefinedSubType":
  279. len = decode_len (data, pos, out pos);
  280. string_from_bytes (data, pos, len);
  281. pos += len;
  282. break;
  283. case "SizeParamIndex":
  284. value = (int)data [pos++];
  285. value |= ((int)data [pos++]) << 8;
  286. sizeParamIndex = value;
  287. hasSize = true;
  288. break;
  289. case "MarshalType":
  290. len = decode_len (data, pos, out pos);
  291. marshalTypeName = string_from_bytes (data, pos, len);
  292. pos += len;
  293. break;
  294. case "MarshalTypeRef":
  295. len = decode_len (data, pos, out pos);
  296. marshalTypeName = string_from_bytes (data, pos, len);
  297. marshalTypeRef = Type.GetType (marshalTypeName);
  298. pos += len;
  299. break;
  300. case "MarshalCookie":
  301. len = decode_len (data, pos, out pos);
  302. marshalCookie = string_from_bytes (data, pos, len);
  303. pos += len;
  304. break;
  305. default:
  306. throw new Exception ("Unknown MarshalAsAttribute field: " + named_name);
  307. }
  308. }
  309. switch ((UnmanagedType)utype) {
  310. case UnmanagedType.LPArray:
  311. if (hasSize)
  312. return UnmanagedMarshal.DefineLPArrayInternal (subtype, sizeConst, sizeParamIndex);
  313. else
  314. return UnmanagedMarshal.DefineLPArray (subtype);
  315. case UnmanagedType.SafeArray:
  316. return UnmanagedMarshal.DefineSafeArray (subtype);
  317. case UnmanagedType.ByValArray:
  318. if (!is_field)
  319. throw new ArgumentException ("Specified unmanaged type is only valid on fields");
  320. return UnmanagedMarshal.DefineByValArray (sizeConst);
  321. case UnmanagedType.ByValTStr:
  322. return UnmanagedMarshal.DefineByValTStr (sizeConst);
  323. case UnmanagedType.CustomMarshaler:
  324. return UnmanagedMarshal.DefineCustom (marshalTypeRef, marshalCookie, marshalTypeName, Guid.Empty);
  325. default:
  326. return UnmanagedMarshal.DefineUnmanagedMarshal ((UnmanagedType)utype);
  327. }
  328. }
  329. static Type elementTypeToType (int elementType) {
  330. /* Partition II, section 23.1.16 */
  331. switch (elementType) {
  332. case 0x02:
  333. return typeof (bool);
  334. case 0x03:
  335. return typeof (char);
  336. case 0x04:
  337. return typeof (sbyte);
  338. case 0x05:
  339. return typeof (byte);
  340. case 0x06:
  341. return typeof (short);
  342. case 0x07:
  343. return typeof (ushort);
  344. case 0x08:
  345. return typeof (int);
  346. case 0x09:
  347. return typeof (uint);
  348. case 0x0a:
  349. return typeof (long);
  350. case 0x0b:
  351. return typeof (ulong);
  352. case 0x0c:
  353. return typeof (float);
  354. case 0x0d:
  355. return typeof (double);
  356. case 0x0e:
  357. return typeof (string);
  358. default:
  359. throw new Exception ("Unknown element type '" + elementType + "'");
  360. }
  361. }
  362. static object decode_cattr_value (Type t, byte[] data, int pos, out int rpos) {
  363. switch (Type.GetTypeCode (t)) {
  364. case TypeCode.String:
  365. if (data [pos] == 0xff) {
  366. rpos = pos + 1;
  367. return null;
  368. }
  369. int len = decode_len (data, pos, out pos);
  370. rpos = pos + len;
  371. return string_from_bytes (data, pos, len);
  372. case TypeCode.Int32:
  373. rpos = pos + 4;
  374. return data [pos] + (data [pos + 1] << 8) + (data [pos + 2] << 16) + (data [pos + 3] << 24);
  375. case TypeCode.Boolean:
  376. rpos = pos + 1;
  377. return (data [pos] == 0) ? false : true;
  378. case TypeCode.Object:
  379. int subtype = data [pos];
  380. pos += 1;
  381. if (subtype >= 0x02 && subtype <= 0x0e)
  382. return decode_cattr_value (elementTypeToType (subtype), data, pos, out rpos);
  383. else
  384. throw new Exception ("Subtype '" + subtype + "' of type object not yet handled in decode_cattr_value");
  385. default:
  386. throw new Exception ("FIXME: Type " + t + " not yet handled in decode_cattr_value.");
  387. }
  388. }
  389. internal struct CustomAttributeInfo {
  390. public ConstructorInfo ctor;
  391. public object[] ctorArgs;
  392. public string[] namedParamNames;
  393. public object[] namedParamValues;
  394. }
  395. internal static CustomAttributeInfo decode_cattr (CustomAttributeBuilder customBuilder) {
  396. byte[] data = customBuilder.Data;
  397. ConstructorInfo ctor = customBuilder.Ctor;
  398. int pos = 0;
  399. CustomAttributeInfo info = new CustomAttributeInfo ();
  400. // Prolog
  401. if (data.Length < 2)
  402. throw new Exception ("Custom attr length is only '" + data.Length + "'");
  403. if ((data [0] != 0x1) || (data [1] != 0x00))
  404. throw new Exception ("Prolog invalid");
  405. pos = 2;
  406. ParameterInfo [] pi = GetParameters (ctor);
  407. info.ctor = ctor;
  408. info.ctorArgs = new object [pi.Length];
  409. for (int i = 0; i < pi.Length; ++i)
  410. info.ctorArgs [i] = decode_cattr_value (pi [i].ParameterType, data, pos, out pos);
  411. int num_named = data [pos] + (data [pos + 1] * 256);
  412. pos += 2;
  413. info.namedParamNames = new string [num_named];
  414. info.namedParamValues = new object [num_named];
  415. for (int i = 0; i < num_named; ++i) {
  416. int named_type = data [pos++];
  417. int data_type = data [pos++];
  418. string enum_type_name = null;
  419. if (data_type == 0x55) {
  420. int len2 = decode_len (data, pos, out pos);
  421. enum_type_name = string_from_bytes (data, pos, len2);
  422. pos += len2;
  423. }
  424. int len = decode_len (data, pos, out pos);
  425. string name = string_from_bytes (data, pos, len);
  426. info.namedParamNames [i] = name;
  427. pos += len;
  428. if (named_type == 0x53) {
  429. /* Field */
  430. FieldInfo fi = ctor.DeclaringType.GetField (name, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance);
  431. if (fi == null)
  432. throw new Exception ("Custom attribute type '" + ctor.DeclaringType + "' doesn't contain a field named '" + name + "'");
  433. object val = decode_cattr_value (fi.FieldType, data, pos, out pos);
  434. if (enum_type_name != null) {
  435. Type enumType = Type.GetType (enum_type_name);
  436. val = Enum.ToObject (enumType, val);
  437. }
  438. info.namedParamValues [i] = val;
  439. }
  440. else
  441. // FIXME:
  442. throw new Exception ("Unknown named type: " + named_type);
  443. }
  444. return info;
  445. }
  446. void _CustomAttributeBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  447. {
  448. throw new NotImplementedException ();
  449. }
  450. void _CustomAttributeBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  451. {
  452. throw new NotImplementedException ();
  453. }
  454. void _CustomAttributeBuilder.GetTypeInfoCount (out uint pcTInfo)
  455. {
  456. throw new NotImplementedException ();
  457. }
  458. void _CustomAttributeBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  459. {
  460. throw new NotImplementedException ();
  461. }
  462. static ParameterInfo [] GetParameters (ConstructorInfo ctor)
  463. {
  464. ConstructorBuilder cb = ctor as ConstructorBuilder;
  465. if (cb != null)
  466. return cb.GetParametersInternal ();
  467. return ctor.GetParameters ();
  468. }
  469. }
  470. }