Merge remote-tracking branch 'refs/remotes/mono/master'
[mono.git] / mcs / class / corlib / System.Security / PermissionSet.cs
1 //
2 // System.Security.PermissionSet.cs
3 //
4 // Authors:
5 //      Nick Drochak(ndrochak@gol.com)
6 //      Sebastien Pouliot  <sebastien@ximian.com>
7 //
8 // (C) Nick Drochak
9 // Portions (C) 2003, 2004 Motus Technologies Inc. (http://www.motus.com)
10 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 using System.Collections;
33 using System.Diagnostics;
34 using System.IO;
35 using System.Reflection;
36 using System.Runtime.InteropServices;
37 using System.Runtime.Serialization;
38 using System.Runtime.Serialization.Formatters.Binary;
39 using System.Security.Permissions;
40 using System.Security.Policy;
41 using System.Text;
42 using System.Threading;
43
44 namespace System.Security {
45
46         [Serializable]
47         // Microsoft public key - i.e. only MS signed assembly can inherit from PermissionSet (1.x) or (2.0) FullTrust assemblies
48         [StrongNameIdentityPermission (SecurityAction.InheritanceDemand, PublicKey="002400000480000094000000060200000024000052534131000400000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8A12436518206DC093344D5AD293")]
49         [ComVisible (true)]
50         [MonoTODO ("CAS support is experimental (and unsupported).")]
51         public class PermissionSet: ISecurityEncodable, ICollection, IEnumerable, IStackWalk, IDeserializationCallback {
52
53                 private const string tagName = "PermissionSet";
54                 private const int version = 1;
55                 private static object[] psUnrestricted = new object [1] { PermissionState.Unrestricted };
56
57                 private PermissionState state;
58                 private ArrayList list;
59                 private PolicyLevel _policyLevel;
60                 private bool _declsec;
61                 private bool _readOnly;
62                 private bool[] _ignored; // for asserts and non-CAS permissions
63
64                 // constructors
65
66                 // for PolicyLevel (to avoid validation duplication)
67                 internal PermissionSet () 
68                 {
69                         list = new ArrayList ();
70                 }
71
72                 public PermissionSet (PermissionState state) : this ()
73                 {
74                         this.state = CodeAccessPermission.CheckPermissionState (state, true);
75                 }
76
77                 public PermissionSet (PermissionSet permSet) : this ()
78                 {
79                         // LAMESPEC: This would be handled by the compiler.  No way permSet is not a PermissionSet.
80                         //if (!(permSet is PermissionSet))
81                         //      throw new System.ArgumentException(); // permSet is not an instance of System.Security.PermissionSet.
82                         if (permSet != null) {
83                                 state = permSet.state;
84                                 foreach (IPermission p in permSet.list)
85                                         list.Add (p);
86                         }
87                 }
88
89                 internal PermissionSet (string xml)
90                         : this ()
91                 {
92                         state = PermissionState.None;
93                         if (xml != null) {
94                                 SecurityElement se = SecurityElement.FromString (xml);
95                                 FromXml (se);
96                         }
97                 }
98
99                 // Light version for creating a (non unrestricted) PermissionSet with
100                 // a single permission. This allows to relax most validations.
101                 internal PermissionSet (IPermission perm)
102                         : this ()
103                 {
104                         if (perm != null) {
105                                 // note: we do not copy IPermission like AddPermission
106                                 list.Add (perm);
107                         }
108                 }
109
110                 // methods
111
112                 public IPermission AddPermission (IPermission perm)
113                 {
114                         if ((perm == null) || _readOnly)
115                                 return perm;
116
117                         // we don't add to an unrestricted permission set unless...
118                         if (state == PermissionState.Unrestricted) {
119                                 // identity permissions can be unrestricted under 2.x
120                                 {
121                                         // we return the union of the permission with unrestricted
122                                         // which results in a permission of the same type initialized 
123                                         // with PermissionState.Unrestricted
124                                         return (IPermission) Activator.CreateInstance (perm.GetType (), psUnrestricted);
125                                 }
126                         }
127
128                         // we can't add two permissions of the same type in a set
129                         // so we remove an existing one, union with it and add it back
130                         IPermission existing = RemovePermission (perm.GetType ());
131                         if (existing != null) {
132                                 perm = perm.Union (existing);
133                         }
134
135                         // note: Add doesn't copy
136                         list.Add (perm);
137                         return perm;
138                 }
139
140                 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
141                 [SecurityPermission (SecurityAction.Demand, Assertion = true)]
142                 public void Assert ()
143                 {
144                         int count = this.Count;
145
146                         // we (current frame) must have the permission to assert it to others
147                         // otherwise we don't assert (but we don't throw an exception)
148                         foreach (IPermission p in list) {
149                                 // note: we ignore non-CAS permissions
150                                 if (p is IStackWalk) {
151                                         if (!SecurityManager.IsGranted (p)) {
152                                                 return;
153                                         }
154                                 } else
155                                         count--;
156                         }
157
158                         // note: we must ignore the stack modifiers for the non-CAS permissions
159                         if (SecurityManager.SecurityEnabled && (count > 0))
160                                 throw new NotSupportedException ("Currently only declarative Assert are supported.");
161                 }
162
163                 internal void Clear () 
164                 {
165                         list.Clear ();
166                 }
167
168                 public virtual PermissionSet Copy ()
169                 {
170                         return new PermissionSet (this);
171                 }
172
173                 public virtual void CopyTo (Array array, int index)
174                 {
175                         if (null == array)
176                                 throw new ArgumentNullException ("array");
177
178                         if (list.Count > 0) {
179                                 if (array.Rank > 1) {
180                                         throw new ArgumentException (Locale.GetText (
181                                                 "Array has more than one dimension"));
182                                 }
183                                 if (index < 0 || index >= array.Length) {
184                                         throw new IndexOutOfRangeException ("index");
185                                 }
186
187                                 list.CopyTo (array, index);
188                         }
189                 }
190
191                 public void Demand ()
192                 {
193                         // Note: SecurityEnabled only applies to CAS permissions
194                         // so we're not checking for it (yet)
195                         if (IsEmpty ())
196                                 return;
197
198                         int n = list.Count;
199                         if ((_ignored == null) || (_ignored.Length != n)) {
200                                 _ignored = new bool [n];
201                         }
202
203                         bool call_cas_only = this.IsUnrestricted ();
204                         // non CAS permissions (e.g. PrincipalPermission) do not requires a stack walk
205                         for (int i = 0; i < n; i++) {
206                                 IPermission p = (IPermission) list [i];
207                                 Type t = p.GetType ();
208                                 if (t.IsSubclassOf (typeof (CodeAccessPermission))) {
209                                         _ignored [i] = false;
210                                         call_cas_only = true;
211                                 } else {
212                                         _ignored [i] = true;
213                                         p.Demand ();
214                                 }
215                         }
216
217                         // don't start the stack walk if
218                         // - the permission set only contains non CAS permissions; or
219                         // - security isn't enabled (applis only to CAS!)
220                         if (call_cas_only && SecurityManager.SecurityEnabled)
221                                 CasOnlyDemand (_declsec ? 5 : 3);
222                 }
223
224                 // The number of frames to skip depends on who's calling
225                 // - CodeAccessPermission.Demand (imperative)
226                 // - PermissionSet.Demand (imperative)
227                 // - SecurityManager.InternalDemand (declarative)
228                 internal void CasOnlyDemand (int skip)
229                 {
230                         Assembly current = null;
231                         AppDomain domain = null;
232
233                         if (_ignored == null) {
234                                 // special case when directly called from CodeAccessPermission.Demand
235                                 _ignored = new bool [list.Count];
236                         }
237                 }
238
239                 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
240                 public void Deny ()
241                 {
242                         if (!SecurityManager.SecurityEnabled)
243                                 return;
244
245                         foreach (IPermission p in list) {
246                                 // note: we ignore non-CAS permissions
247                                 if (p is IStackWalk) {
248                                         throw new NotSupportedException ("Currently only declarative Deny are supported.");
249                                 }
250                         }
251                 }
252
253                 public virtual void FromXml (SecurityElement et)
254                 {
255                         if (et == null)
256                                 throw new ArgumentNullException ("et");
257                         if (et.Tag != tagName) {
258                                 string msg = String.Format ("Invalid tag {0} expected {1}", et.Tag, tagName);
259                                 throw new ArgumentException (msg, "et");
260                         }
261
262                         list.Clear ();
263
264                         if (CodeAccessPermission.IsUnrestricted (et)) {
265                                 state = PermissionState.Unrestricted;
266                                 // no need to continue for an unrestricted permission
267                                 // because identity permissions now "supports" unrestricted
268                                 return;
269                         } else {
270                                 state = PermissionState.None;
271                         }
272
273                         if (et.Children != null) {
274                                 foreach (SecurityElement se in et.Children) {
275                                         string className = se.Attribute ("class");
276                                         if (className == null) {
277                                                 throw new ArgumentException (Locale.GetText (
278                                                         "No permission class is specified."));
279                                         }
280                                         if (Resolver != null) {
281                                                 // policy class names do not have to be fully qualified
282                                                 className = Resolver.ResolveClassName (className);
283                                         }
284
285                                         list.Add (PermissionBuilder.Create (className, se));
286                                 }
287                         }
288                 }
289
290                 public IEnumerator GetEnumerator ()
291                 {
292                         return list.GetEnumerator ();
293                 }
294
295                 public bool IsSubsetOf (PermissionSet target)
296                 {
297                         // if target is empty we must be empty too
298                         if ((target == null) || (target.IsEmpty ()))
299                                 return this.IsEmpty ();
300
301                         // all permissions support unrestricted in 2.0
302                         if (target.IsUnrestricted ())
303                                 return true;
304                         if (this.IsUnrestricted ())
305                                 return false;
306
307                         if (this.IsUnrestricted () && ((target == null) || !target.IsUnrestricted ()))
308                                 return false;
309
310                         // if each of our permission is (a) present and (b) a subset of target
311                         foreach (IPermission p in list) {
312                                 // non CAS permissions must be evaluated for unrestricted
313                                 Type t = p.GetType ();
314                                 IPermission i = null;
315                                 if (target.IsUnrestricted () && (p is CodeAccessPermission) && (p is IUnrestrictedPermission)) {
316                                         i = (IPermission) Activator.CreateInstance (t, psUnrestricted);
317                                 } else {
318                                         i = target.GetPermission (t);
319                                 }
320                                 
321                                 if (!p.IsSubsetOf (i))
322                                         return false; // not a subset (condition b)
323                         }
324                         return true;
325                 }
326
327                 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
328                 public void PermitOnly ()
329                 {
330                         if (!SecurityManager.SecurityEnabled)
331                                 return;
332
333                         foreach (IPermission p in list) {
334                                 // note: we ignore non-CAS permissions
335                                 if (p is IStackWalk) {
336                                         throw new NotSupportedException ("Currently only declarative Deny are supported.");
337                                 }
338                         }
339                 }
340
341                 public bool ContainsNonCodeAccessPermissions () 
342                 {
343                         if (list.Count > 0) {
344                                 foreach (IPermission p in list) {
345                                         if (! p.GetType ().IsSubclassOf (typeof (CodeAccessPermission)))
346                                                 return true;
347                                 }
348                         }
349                         return false;
350                 }
351
352                 // FIXME little documentation in Fx 2.0 beta 1
353                 public static byte[] ConvertPermissionSet (string inFormat, byte[] inData, string outFormat) 
354                 {
355                         if (inFormat == null)
356                                 throw new ArgumentNullException ("inFormat");
357                         if (outFormat == null)
358                                 throw new ArgumentNullException ("outFormat");
359                         if (inData == null)
360                                 return null;
361
362                         if (inFormat == outFormat)
363                                 return inData;
364
365                         PermissionSet ps = null;
366
367                         if (inFormat == "BINARY") {
368                                 if (outFormat.StartsWith ("XML")) {
369                                         using (MemoryStream ms = new MemoryStream (inData)) {
370                                                 BinaryFormatter formatter = new BinaryFormatter ();
371                                                 ps = (PermissionSet) formatter.Deserialize (ms);
372                                                 ms.Close ();
373                                         }
374                                         string xml = ps.ToString ();
375                                         switch (outFormat) {
376                                                 case "XML":
377                                                 case "XMLASCII":
378                                                         return Encoding.ASCII.GetBytes (xml);
379                                                 case "XMLUNICODE":
380                                                         return Encoding.Unicode.GetBytes (xml);
381                                         }
382                                 }
383                         }
384                         else if (inFormat.StartsWith ("XML")) {
385                                 if (outFormat == "BINARY") {
386                                         string xml = null;
387                                         switch (inFormat) {
388                                                 case "XML":
389                                                 case "XMLASCII":
390                                                         xml = Encoding.ASCII.GetString (inData);
391                                                         break;
392                                                 case "XMLUNICODE":
393                                                         xml = Encoding.Unicode.GetString (inData);
394                                                         break;
395                                         }
396                                         if (xml != null) {
397                                                 ps = new PermissionSet (PermissionState.None);
398                                                 ps.FromXml (SecurityElement.FromString (xml));
399
400                                                 MemoryStream ms = new MemoryStream ();
401                                                 BinaryFormatter formatter = new BinaryFormatter ();
402                                                 formatter.Serialize (ms, ps);
403                                                 ms.Close ();
404                                                 return ms.ToArray ();
405                                         }
406                                 }
407                                 else if (outFormat.StartsWith ("XML")) {
408                                         string msg = String.Format (Locale.GetText ("Can't convert from {0} to {1}"), inFormat, outFormat);
409                                         throw new XmlSyntaxException (msg);
410                                 }
411                         }
412                         else {
413                                 // unknown inFormat, returns null
414                                 return null;
415                         }
416                         // unknown outFormat, throw
417                         throw new SerializationException (String.Format (Locale.GetText ("Unknown output format {0}."), outFormat));
418                 }
419
420                 public IPermission GetPermission (Type permClass)
421                 {
422                         if ((permClass == null) || (list.Count == 0))
423                                 return null;
424
425                         foreach (object o in list) {
426                                 if ((o != null) && o.GetType ().Equals (permClass))
427                                         return (IPermission) o;
428                         }
429                         // it's normal to return null for unrestricted sets
430                         return null;
431                 }
432
433                 public PermissionSet Intersect (PermissionSet other)
434                 {
435                         // no intersection possible
436                         if ((other == null) || (other.IsEmpty ()) || (this.IsEmpty ()))
437                                 return null;
438
439                         PermissionState state = PermissionState.None;
440                         if (this.IsUnrestricted () && other.IsUnrestricted ())
441                                 state = PermissionState.Unrestricted;
442
443                         PermissionSet interSet = null;
444                         // much simpler with 2.0
445                         if (state == PermissionState.Unrestricted) {
446                                 interSet = new PermissionSet (state);
447                         } else if (this.IsUnrestricted ()) {
448                                 interSet = other.Copy ();
449                         } else if (other.IsUnrestricted ()) {
450                                 interSet = this.Copy ();
451                         } else {
452                                 interSet = new PermissionSet (state);
453                                 InternalIntersect (interSet, this, other, false);
454                         }
455                         return interSet;
456                 }
457
458                 internal void InternalIntersect (PermissionSet intersect, PermissionSet a, PermissionSet b, bool unrestricted)
459                 {
460                         foreach (IPermission p in b.list) {
461                                 // for every type in both list
462                                 IPermission i = a.GetPermission (p.GetType ());
463                                 if (i != null) {
464                                         // add intersection for this type
465                                         intersect.AddPermission (p.Intersect (i));
466                                 }
467                                 // unrestricted is possible for indentity permissions
468                                 else if (unrestricted) {
469                                         intersect.AddPermission (p);
470                                 }
471                                 // or reject!
472                         }
473                 }
474
475                 public bool IsEmpty ()
476                 {
477                         // note: Unrestricted isn't empty
478                         if (state == PermissionState.Unrestricted)
479                                 return false;
480                         if ((list == null) || (list.Count == 0))
481                                 return true;
482                         // the set may include some empty permissions
483                         foreach (IPermission p in list) {
484                                 // empty == fully restricted == IsSubsetOf(null) == true
485                                 if (!p.IsSubsetOf (null))
486                                         return false;
487                         }
488                         return true;
489                 }
490
491                 public bool IsUnrestricted ()
492                 {
493                         return (state == PermissionState.Unrestricted);
494                 }
495
496                 public IPermission RemovePermission (Type permClass)
497                 {
498                         if ((permClass == null) || _readOnly)
499                                 return null;
500
501                         foreach (object o in list) {
502                                 if (o.GetType ().Equals (permClass)) {
503                                         list.Remove (o);
504                                         return (IPermission) o;
505                                 }
506                         }
507                         return null;
508                 }
509
510                 public IPermission SetPermission (IPermission perm)
511                 {
512                         if ((perm == null) || _readOnly)
513                                 return perm;
514                         IUnrestrictedPermission u = (perm as IUnrestrictedPermission);
515                         if (u == null) {
516                                 state = PermissionState.None;
517                         } else {
518                                 state = u.IsUnrestricted () ? state : PermissionState.None;
519                         }
520                         RemovePermission (perm.GetType ());
521                         list.Add (perm);
522                         return perm;
523                 }
524
525                 public override string ToString ()
526                 {
527                         return ToXml ().ToString ();
528                 }
529
530                 public virtual SecurityElement ToXml ()
531                 {
532                         SecurityElement se = new SecurityElement (tagName);
533                         se.AddAttribute ("class", GetType ().FullName);
534                         se.AddAttribute ("version", version.ToString ());
535                         if (state == PermissionState.Unrestricted)
536                                 se.AddAttribute ("Unrestricted", "true");
537
538                         // required for permissions that do not implement IUnrestrictedPermission
539                         foreach (IPermission p in list) {
540                                 se.AddChild (p.ToXml ());
541                         }
542                         return se;
543                 }
544
545                 public PermissionSet Union (PermissionSet other)
546                 {
547                         if (other == null)
548                                 return this.Copy ();
549
550                         PermissionSet copy = null;
551                         if (this.IsUnrestricted () || other.IsUnrestricted ()) {
552                                 // there are no child elements in unrestricted permission sets
553                                 return new PermissionSet (PermissionState.Unrestricted);
554                         } else {
555                                 copy = this.Copy ();
556                                 // PermissionState.None -> copy all permissions
557                                 foreach (IPermission p in other.list) {
558                                         copy.AddPermission (p);
559                                 }
560                         }
561                         return copy;
562                 }
563
564                 public virtual int Count {
565                         get { return list.Count; }
566                 }
567
568                 public virtual bool IsSynchronized {
569                         get { return list.IsSynchronized; }
570                 }
571
572                 public virtual bool IsReadOnly {
573                         // always false (as documented) but the PermissionSet can be read-only
574                         // e.g. in a PolicyStatement
575                         get { return false; } 
576                 }
577
578                 public virtual object SyncRoot {
579                         get { return this; }
580                 }
581
582                 internal bool DeclarativeSecurity {
583                         get { return _declsec; }
584                         set { _declsec = value; }
585                 }
586
587                 [MonoTODO ("may not be required")]
588                 void IDeserializationCallback.OnDeserialization (object sender) 
589                 {
590                 }
591
592                 [ComVisible (false)]
593                 public override bool Equals (object obj)
594                 {
595                         if (obj == null)
596                                 return false;
597                         PermissionSet ps = (obj as PermissionSet);
598                         if (ps == null)
599                                 return false;
600                         if (state != ps.state)
601                                 return false;
602                         if (list.Count != ps.Count)
603                                 return false;
604
605                         for (int i=0; i < list.Count; i++) {
606                                 bool found = false;
607                                 for (int j=0; i < ps.list.Count; j++) {
608                                         if (list [i].Equals (ps.list [j])) {
609                                                 found = true;
610                                                 break;
611                                         }
612                                 }
613                                 if (!found)
614                                         return false;
615                         }
616                         return true;
617                 }
618
619                 [ComVisible (false)]
620                 public override int GetHashCode ()
621                 {
622                         return (list.Count == 0) ? (int) state : base.GetHashCode ();
623                 }
624
625                 // FIXME what's it doing here? There's probably a reason this was added here.
626                 static public void RevertAssert ()
627                 {
628                         CodeAccessPermission.RevertAssert ();
629                 }
630
631                 // internal
632
633                 internal PolicyLevel Resolver {
634                         get { return _policyLevel; }
635                         set { _policyLevel = value; }
636                 }
637
638                 internal void SetReadOnly (bool value)
639                 {
640                         _readOnly = value;
641                 }
642
643                 private bool AllIgnored ()
644                 {
645                         if (_ignored == null)
646                                 throw new NotSupportedException ("bad bad bad");
647
648                         for (int i=0; i < _ignored.Length; i++) {
649                                 if (!_ignored [i])
650                                         return false;
651                         }
652                         // everything is ignored (i.e. non-CAS permission or asserted permission).
653                         return true;
654                 }
655
656                 // 2.0 metadata format
657
658                 internal static PermissionSet CreateFromBinaryFormat (byte[] data)
659                 {
660                         if ((data == null) || (data [0] != 0x2E) || (data.Length < 2)) {
661                                 string msg = Locale.GetText ("Invalid data in 2.0 metadata format.");
662                                 throw new SecurityException (msg);
663                         }
664
665                         int pos = 1;
666                         int numattr = ReadEncodedInt (data, ref pos);
667                         PermissionSet ps = new PermissionSet (PermissionState.None);
668                         for (int i = 0; i < numattr; i++) {
669                                 IPermission p = ProcessAttribute (data, ref pos);
670                                 if (p == null) {
671                                         string msg = Locale.GetText ("Unsupported data found in 2.0 metadata format.");
672                                         throw new SecurityException (msg);
673                                 }
674                                 ps.AddPermission (p);
675                         }
676                         return ps;
677                 }
678
679                 internal static int ReadEncodedInt (byte[] data, ref int position)
680                 {
681                         int len = 0;
682                         if ((data [position] & 0x80) == 0) {
683                                 len = data [position];
684                                 position ++;
685                         } else if ((data [position] & 0x40) == 0) {
686                                 len = ((data [position] & 0x3f) << 8 | data [position + 1]);
687                                 position += 2;
688                         } else {
689                                 len = (((data [position] & 0x1f) << 24) | (data [position + 1] << 16) |
690                                         (data [position + 2] << 8) | (data [position + 3]));
691                                 position += 4;
692                         }
693                         return len;
694                 }
695
696                 static object[] action = new object [1] { (SecurityAction) 0 };
697
698                 // TODO: add support for arrays and enums (2.0)
699                 internal static IPermission ProcessAttribute (byte[] data, ref int position)
700                 {
701                         int clen = ReadEncodedInt (data, ref position);
702                         string cnam = Encoding.UTF8.GetString (data, position, clen);
703                         position += clen;
704
705                         Type secattr = Type.GetType (cnam);
706                         SecurityAttribute sa = (Activator.CreateInstance (secattr, action) as SecurityAttribute);
707                         if (sa == null)
708                                 return null;
709
710                         /*int optionalParametersLength =*/ ReadEncodedInt (data, ref position);
711                         int numberOfParameters = ReadEncodedInt (data, ref position);
712                         for (int j=0; j < numberOfParameters; j++) {
713                                 bool property = false;
714                                 switch (data [position++]) {
715                                 case 0x53: // field (technically possible and working)
716                                         property = false;
717                                         break;
718                                 case 0x54: // property (common case)
719                                         property = true;
720                                         break;
721                                 default:
722                                         return null;
723                                 }
724
725                                 bool array = false;
726                                 byte type = data [position++];
727                                 if (type == 0x1D) {
728                                         array = true;
729                                         type = data [position++];
730                                 }
731
732                                 int plen = ReadEncodedInt (data, ref position);
733                                 string pnam = Encoding.UTF8.GetString (data, position, plen);
734                                 position += plen;
735
736                                 int arrayLength = 1;
737                                 if (array) {
738                                         arrayLength = BitConverter.ToInt32 (data, position);
739                                         position += 4;
740                                 }
741
742                                 object obj = null;
743                                 object[] arrayIndex = null;
744                                 for (int i = 0; i < arrayLength; i++) {
745                                         if (array) {
746                                                 // TODO - setup index (2.0)
747                                         }
748
749                                         // sadly type values doesn't match ther TypeCode enum :(
750                                         switch (type) {
751                                         case 0x02: // MONO_TYPE_BOOLEAN
752                                                 obj = (object) Convert.ToBoolean (data [position++]);
753                                                 break;
754                                         case 0x03: // MONO_TYPE_CHAR
755                                                 obj = (object) Convert.ToChar (data [position]);
756                                                 position += 2;
757                                                 break;
758                                         case 0x04: // MONO_TYPE_I1
759                                                 obj = (object) Convert.ToSByte (data [position++]);
760                                                 break;
761                                         case 0x05: // MONO_TYPE_U1
762                                                 obj = (object) Convert.ToByte (data [position++]);
763                                                 break;
764                                         case 0x06: // MONO_TYPE_I2
765                                                 obj = (object) Convert.ToInt16 (data [position]);
766                                                 position += 2;
767                                                 break;
768                                         case 0x07: // MONO_TYPE_U2
769                                                 obj = (object) Convert.ToUInt16 (data [position]);
770                                                 position += 2;
771                                                 break;
772                                         case 0x08: // MONO_TYPE_I4
773                                                 obj = (object) Convert.ToInt32 (data [position]);
774                                                 position += 4;
775                                                 break;
776                                         case 0x09: // MONO_TYPE_U4
777                                                 obj = (object) Convert.ToUInt32 (data [position]);
778                                                 position += 4;
779                                                 break;
780                                         case 0x0A: // MONO_TYPE_I8
781                                                 obj = (object) Convert.ToInt64 (data [position]);
782                                                 position += 8;
783                                                 break;
784                                         case 0x0B: // MONO_TYPE_U8
785                                                 obj = (object) Convert.ToUInt64 (data [position]);
786                                                 position += 8;
787                                                 break;
788                                         case 0x0C: // MONO_TYPE_R4
789                                                 obj = (object) Convert.ToSingle (data [position]);
790                                                 position += 4;
791                                                 break;
792                                         case 0x0D: // MONO_TYPE_R8
793                                                 obj = (object) Convert.ToDouble (data [position]);
794                                                 position += 8;
795                                                 break;
796                                         case 0x0E: // MONO_TYPE_STRING
797                                                 string s = null;
798                                                 if (data [position] != 0xFF) {
799                                                         int slen = ReadEncodedInt (data, ref position);
800                                                         s = Encoding.UTF8.GetString (data, position, slen);
801                                                         position += slen;
802                                                 } else {
803                                                         position++;
804                                                 }
805                                                 obj = (object) s;
806                                                 break;
807                                         case 0x50: // special for TYPE
808                                                 int tlen = ReadEncodedInt (data, ref position);
809                                                 obj = (object) Type.GetType (Encoding.UTF8.GetString (data, position, tlen));
810                                                 position += tlen;
811                                                 break;
812                                         default:
813                                                 return null; // unsupported
814                                         }
815
816                                         if (property) {
817                                                 PropertyInfo pi = secattr.GetProperty (pnam);
818                                                 pi.SetValue (sa, obj, arrayIndex);
819                                         } else {
820                                                 FieldInfo fi = secattr.GetField (pnam);
821                                                 fi.SetValue (sa, obj);
822                                         }
823                                 }
824                         }
825                         return sa.CreatePermission ();
826                 }
827         }
828 }