CustomAttributeBuilder.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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. static bool IsValidValue (Type type, object value) {
  109. if (type.IsValueType && value == null)
  110. return false;
  111. if (type.IsArray && type.GetElementType ().IsValueType) {
  112. foreach (var v in (Array)value) {
  113. if (v == null)
  114. return false;
  115. }
  116. }
  117. return true;
  118. }
  119. private void Initialize (ConstructorInfo con, object [] constructorArgs,
  120. PropertyInfo [] namedProperties, object [] propertyValues,
  121. FieldInfo [] namedFields, object [] fieldValues)
  122. {
  123. ctor = con;
  124. if (con == null)
  125. throw new ArgumentNullException ("con");
  126. if (constructorArgs == null)
  127. throw new ArgumentNullException ("constructorArgs");
  128. if (namedProperties == null)
  129. throw new ArgumentNullException ("namedProperties");
  130. if (propertyValues == null)
  131. throw new ArgumentNullException ("propertyValues");
  132. if (namedFields == null)
  133. throw new ArgumentNullException ("namedFields");
  134. if (fieldValues == null)
  135. throw new ArgumentNullException ("fieldValues");
  136. if (con.GetParameterCount () != constructorArgs.Length)
  137. throw new ArgumentException ("Parameter count does not match " +
  138. "passed in argument value count.");
  139. if (namedProperties.Length != propertyValues.Length)
  140. throw new ArgumentException ("Array lengths must be the same.",
  141. "namedProperties, propertyValues");
  142. if (namedFields.Length != fieldValues.Length)
  143. throw new ArgumentException ("Array lengths must be the same.",
  144. "namedFields, fieldValues");
  145. if ((con.Attributes & MethodAttributes.Static) == MethodAttributes.Static ||
  146. (con.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private)
  147. throw new ArgumentException ("Cannot have private or static constructor.");
  148. Type atype = ctor.DeclaringType;
  149. int i;
  150. i = 0;
  151. foreach (FieldInfo fi in namedFields) {
  152. Type t = fi.DeclaringType;
  153. if ((atype != t) && (!t.IsSubclassOf (atype)) && (!atype.IsSubclassOf (t)))
  154. throw new ArgumentException ("Field '" + fi.Name + "' does not belong to the same class as the constructor");
  155. if (!IsValidType (fi.FieldType))
  156. throw new ArgumentException ("Field '" + fi.Name + "' does not have a valid type.");
  157. if (!IsValidValue (fi.FieldType, fieldValues [i]))
  158. throw new ArgumentException ("Field " + fi.Name + " is not a valid value.");
  159. // FIXME: Check enums and TypeBuilders as well
  160. if (fieldValues [i] != null)
  161. // IsEnum does not seem to work on TypeBuilders
  162. if (!(fi.FieldType is TypeBuilder) && !fi.FieldType.IsEnum && !fi.FieldType.IsInstanceOfType (fieldValues [i])) {
  163. //
  164. // mcs allways uses object[] for array types and
  165. // MS.NET allows this
  166. //
  167. if (!fi.FieldType.IsArray)
  168. throw new ArgumentException ("Value of field '" + fi.Name + "' does not match field type: " + fi.FieldType);
  169. }
  170. i ++;
  171. }
  172. i = 0;
  173. foreach (PropertyInfo pi in namedProperties) {
  174. if (!pi.CanWrite)
  175. throw new ArgumentException ("Property '" + pi.Name + "' does not have a setter.");
  176. Type t = pi.DeclaringType;
  177. if ((atype != t) && (!t.IsSubclassOf (atype)) && (!atype.IsSubclassOf (t)))
  178. throw new ArgumentException ("Property '" + pi.Name + "' does not belong to the same class as the constructor");
  179. if (!IsValidType (pi.PropertyType))
  180. throw new ArgumentException ("Property '" + pi.Name + "' does not have a valid type.");
  181. if (!IsValidValue (pi.PropertyType, propertyValues [i]))
  182. throw new ArgumentException ("Property " + pi.Name + " is not a valid value.");
  183. if (propertyValues [i] != null) {
  184. if (!(pi.PropertyType is TypeBuilder) && !pi.PropertyType.IsEnum && !pi.PropertyType.IsInstanceOfType (propertyValues [i]))
  185. if (!pi.PropertyType.IsArray)
  186. throw new ArgumentException ("Value of property '" + pi.Name + "' does not match property type: " + pi.PropertyType + " -> " + propertyValues [i]);
  187. }
  188. i ++;
  189. }
  190. i = 0;
  191. foreach (ParameterInfo pi in GetParameters (con)) {
  192. if (pi != null) {
  193. Type paramType = pi.ParameterType;
  194. if (!IsValidType (paramType))
  195. throw new ArgumentException ("Parameter " + i + " does not have a valid type.");
  196. if (!IsValidValue (paramType, constructorArgs [i]))
  197. throw new ArgumentException ("Parameter " + i + " is not a valid value.");
  198. if (constructorArgs [i] != null) {
  199. if (!(paramType is TypeBuilder) && !paramType.IsEnum && !paramType.IsInstanceOfType (constructorArgs [i]))
  200. if (!paramType.IsArray)
  201. throw new ArgumentException ("Value of argument " + i + " does not match parameter type: " + paramType + " -> " + constructorArgs [i]);
  202. if (!IsValidParam (constructorArgs [i], paramType))
  203. throw new ArgumentException ("Cannot emit a CustomAttribute with argument of type " + constructorArgs [i].GetType () + ".");
  204. }
  205. }
  206. i ++;
  207. }
  208. data = GetBlob (atype.Assembly, con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues);
  209. }
  210. /* helper methods */
  211. internal static int decode_len (byte[] data, int pos, out int rpos) {
  212. int len = 0;
  213. if ((data [pos] & 0x80) == 0) {
  214. len = (int)(data [pos++] & 0x7f);
  215. } else if ((data [pos] & 0x40) == 0) {
  216. len = ((data [pos] & 0x3f) << 8) + data [pos + 1];
  217. pos += 2;
  218. } else {
  219. len = ((data [pos] & 0x1f) << 24) + (data [pos + 1] << 16) + (data [pos + 2] << 8) + data [pos + 3];
  220. pos += 4;
  221. }
  222. rpos = pos;
  223. return len;
  224. }
  225. internal static string string_from_bytes (byte[] data, int pos, int len)
  226. {
  227. return System.Text.Encoding.UTF8.GetString(data, pos, len);
  228. }
  229. internal string string_arg ()
  230. {
  231. int pos = 2;
  232. int len = decode_len (data, pos, out pos);
  233. return string_from_bytes (data, pos, len);
  234. }
  235. internal static UnmanagedMarshal get_umarshal (CustomAttributeBuilder customBuilder, bool is_field) {
  236. byte[] data = customBuilder.Data;
  237. UnmanagedType subtype = (UnmanagedType)0x50; /* NATIVE_MAX */
  238. int sizeConst = -1;
  239. int sizeParamIndex = -1;
  240. bool hasSize = false;
  241. int value;
  242. int utype; /* the (stupid) ctor takes a short or an enum ... */
  243. string marshalTypeName = null;
  244. Type marshalTypeRef = null;
  245. string marshalCookie = String.Empty;
  246. utype = (int)data [2];
  247. utype |= ((int)data [3]) << 8;
  248. string first_type_name = GetParameters (customBuilder.Ctor) [0].ParameterType.FullName;
  249. int pos = 6;
  250. if (first_type_name == "System.Int16")
  251. pos = 4;
  252. int nnamed = (int)data [pos++];
  253. nnamed |= ((int)data [pos++]) << 8;
  254. for (int i = 0; i < nnamed; ++i) {
  255. int paramType; // What is this ?
  256. /* Skip field/property signature */
  257. pos ++;
  258. /* Read type */
  259. paramType = ((int)data [pos++]);
  260. if (paramType == 0x55) {
  261. /* enums, the value is preceeded by the type */
  262. int len2 = decode_len (data, pos, out pos);
  263. string_from_bytes (data, pos, len2);
  264. pos += len2;
  265. }
  266. int len = decode_len (data, pos, out pos);
  267. string named_name = string_from_bytes (data, pos, len);
  268. pos += len;
  269. switch (named_name) {
  270. case "ArraySubType":
  271. value = (int)data [pos++];
  272. value |= ((int)data [pos++]) << 8;
  273. value |= ((int)data [pos++]) << 16;
  274. value |= ((int)data [pos++]) << 24;
  275. subtype = (UnmanagedType)value;
  276. break;
  277. case "SizeConst":
  278. value = (int)data [pos++];
  279. value |= ((int)data [pos++]) << 8;
  280. value |= ((int)data [pos++]) << 16;
  281. value |= ((int)data [pos++]) << 24;
  282. sizeConst = value;
  283. hasSize = true;
  284. break;
  285. case "SafeArraySubType":
  286. value = (int)data[pos++];
  287. value |= ((int)data[pos++]) << 8;
  288. value |= ((int)data[pos++]) << 16;
  289. value |= ((int)data[pos++]) << 24;
  290. subtype = (UnmanagedType)value;
  291. break;
  292. case "IidParameterIndex":
  293. pos += 4;
  294. break;
  295. case "SafeArrayUserDefinedSubType":
  296. len = decode_len (data, pos, out pos);
  297. string_from_bytes (data, pos, len);
  298. pos += len;
  299. break;
  300. case "SizeParamIndex":
  301. value = (int)data [pos++];
  302. value |= ((int)data [pos++]) << 8;
  303. sizeParamIndex = value;
  304. hasSize = true;
  305. break;
  306. case "MarshalType":
  307. len = decode_len (data, pos, out pos);
  308. marshalTypeName = string_from_bytes (data, pos, len);
  309. pos += len;
  310. break;
  311. case "MarshalTypeRef":
  312. len = decode_len (data, pos, out pos);
  313. marshalTypeName = string_from_bytes (data, pos, len);
  314. marshalTypeRef = Type.GetType (marshalTypeName);
  315. pos += len;
  316. break;
  317. case "MarshalCookie":
  318. len = decode_len (data, pos, out pos);
  319. marshalCookie = string_from_bytes (data, pos, len);
  320. pos += len;
  321. break;
  322. default:
  323. throw new Exception ("Unknown MarshalAsAttribute field: " + named_name);
  324. }
  325. }
  326. switch ((UnmanagedType)utype) {
  327. case UnmanagedType.LPArray:
  328. if (hasSize)
  329. return UnmanagedMarshal.DefineLPArrayInternal (subtype, sizeConst, sizeParamIndex);
  330. else
  331. return UnmanagedMarshal.DefineLPArray (subtype);
  332. case UnmanagedType.SafeArray:
  333. return UnmanagedMarshal.DefineSafeArray (subtype);
  334. case UnmanagedType.ByValArray:
  335. if (!is_field)
  336. throw new ArgumentException ("Specified unmanaged type is only valid on fields");
  337. return UnmanagedMarshal.DefineByValArray (sizeConst);
  338. case UnmanagedType.ByValTStr:
  339. return UnmanagedMarshal.DefineByValTStr (sizeConst);
  340. case UnmanagedType.CustomMarshaler:
  341. return UnmanagedMarshal.DefineCustom (marshalTypeRef, marshalCookie, marshalTypeName, Guid.Empty);
  342. default:
  343. return UnmanagedMarshal.DefineUnmanagedMarshal ((UnmanagedType)utype);
  344. }
  345. }
  346. static Type elementTypeToType (int elementType) {
  347. /* Partition II, section 23.1.16 */
  348. switch (elementType) {
  349. case 0x02:
  350. return typeof (bool);
  351. case 0x03:
  352. return typeof (char);
  353. case 0x04:
  354. return typeof (sbyte);
  355. case 0x05:
  356. return typeof (byte);
  357. case 0x06:
  358. return typeof (short);
  359. case 0x07:
  360. return typeof (ushort);
  361. case 0x08:
  362. return typeof (int);
  363. case 0x09:
  364. return typeof (uint);
  365. case 0x0a:
  366. return typeof (long);
  367. case 0x0b:
  368. return typeof (ulong);
  369. case 0x0c:
  370. return typeof (float);
  371. case 0x0d:
  372. return typeof (double);
  373. case 0x0e:
  374. return typeof (string);
  375. default:
  376. throw new Exception ("Unknown element type '" + elementType + "'");
  377. }
  378. }
  379. static object decode_cattr_value (Type t, byte[] data, int pos, out int rpos) {
  380. switch (Type.GetTypeCode (t)) {
  381. case TypeCode.String:
  382. if (data [pos] == 0xff) {
  383. rpos = pos + 1;
  384. return null;
  385. }
  386. int len = decode_len (data, pos, out pos);
  387. rpos = pos + len;
  388. return string_from_bytes (data, pos, len);
  389. case TypeCode.Int32:
  390. rpos = pos + 4;
  391. return data [pos] + (data [pos + 1] << 8) + (data [pos + 2] << 16) + (data [pos + 3] << 24);
  392. case TypeCode.Boolean:
  393. rpos = pos + 1;
  394. return (data [pos] == 0) ? false : true;
  395. case TypeCode.Object:
  396. int subtype = data [pos];
  397. pos += 1;
  398. if (subtype >= 0x02 && subtype <= 0x0e)
  399. return decode_cattr_value (elementTypeToType (subtype), data, pos, out rpos);
  400. else
  401. throw new Exception ("Subtype '" + subtype + "' of type object not yet handled in decode_cattr_value");
  402. default:
  403. throw new Exception ("FIXME: Type " + t + " not yet handled in decode_cattr_value.");
  404. }
  405. }
  406. internal struct CustomAttributeInfo {
  407. public ConstructorInfo ctor;
  408. public object[] ctorArgs;
  409. public string[] namedParamNames;
  410. public object[] namedParamValues;
  411. }
  412. internal static CustomAttributeInfo decode_cattr (CustomAttributeBuilder customBuilder) {
  413. byte[] data = customBuilder.Data;
  414. ConstructorInfo ctor = customBuilder.Ctor;
  415. int pos = 0;
  416. CustomAttributeInfo info = new CustomAttributeInfo ();
  417. // Prolog
  418. if (data.Length < 2)
  419. throw new Exception ("Custom attr length is only '" + data.Length + "'");
  420. if ((data [0] != 0x1) || (data [1] != 0x00))
  421. throw new Exception ("Prolog invalid");
  422. pos = 2;
  423. ParameterInfo [] pi = GetParameters (ctor);
  424. info.ctor = ctor;
  425. info.ctorArgs = new object [pi.Length];
  426. for (int i = 0; i < pi.Length; ++i)
  427. info.ctorArgs [i] = decode_cattr_value (pi [i].ParameterType, data, pos, out pos);
  428. int num_named = data [pos] + (data [pos + 1] * 256);
  429. pos += 2;
  430. info.namedParamNames = new string [num_named];
  431. info.namedParamValues = new object [num_named];
  432. for (int i = 0; i < num_named; ++i) {
  433. int named_type = data [pos++];
  434. int data_type = data [pos++];
  435. string enum_type_name = null;
  436. if (data_type == 0x55) {
  437. int len2 = decode_len (data, pos, out pos);
  438. enum_type_name = string_from_bytes (data, pos, len2);
  439. pos += len2;
  440. }
  441. int len = decode_len (data, pos, out pos);
  442. string name = string_from_bytes (data, pos, len);
  443. info.namedParamNames [i] = name;
  444. pos += len;
  445. if (named_type == 0x53) {
  446. /* Field */
  447. FieldInfo fi = ctor.DeclaringType.GetField (name, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance);
  448. if (fi == null)
  449. throw new Exception ("Custom attribute type '" + ctor.DeclaringType + "' doesn't contain a field named '" + name + "'");
  450. object val = decode_cattr_value (fi.FieldType, data, pos, out pos);
  451. if (enum_type_name != null) {
  452. Type enumType = Type.GetType (enum_type_name);
  453. val = Enum.ToObject (enumType, val);
  454. }
  455. info.namedParamValues [i] = val;
  456. }
  457. else
  458. // FIXME:
  459. throw new Exception ("Unknown named type: " + named_type);
  460. }
  461. return info;
  462. }
  463. void _CustomAttributeBuilder.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  464. {
  465. throw new NotImplementedException ();
  466. }
  467. void _CustomAttributeBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  468. {
  469. throw new NotImplementedException ();
  470. }
  471. void _CustomAttributeBuilder.GetTypeInfoCount (out uint pcTInfo)
  472. {
  473. throw new NotImplementedException ();
  474. }
  475. void _CustomAttributeBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  476. {
  477. throw new NotImplementedException ();
  478. }
  479. static ParameterInfo [] GetParameters (ConstructorInfo ctor)
  480. {
  481. ConstructorBuilder cb = ctor as ConstructorBuilder;
  482. if (cb != null)
  483. return cb.GetParametersInternal ();
  484. return ctor.GetParameters ();
  485. }
  486. }
  487. }