**** Merged r40732-r40872 from MCS ****
[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         public class PermissionSet: ISecurityEncodable, ICollection, IEnumerable, IStackWalk, IDeserializationCallback {
48
49                 private static string tagName = "PermissionSet";
50                 private const int version = 1;
51                 private static object[] psNone = new object [1] { PermissionState.None };
52
53                 private PermissionState state;
54                 private ArrayList list;
55                 private int _hashcode;
56                 private PolicyLevel _policyLevel;
57                 private bool _declsec;
58
59                 // constructors
60
61                 // for PolicyLevel (to avoid validation duplication)
62                 internal PermissionSet () 
63                 {
64                         list = new ArrayList ();
65                 }
66
67                 public PermissionSet (PermissionState state) : this ()
68                 {
69                         if (!Enum.IsDefined (typeof (PermissionState), state))
70                                 throw new System.ArgumentException ("state");
71                         this.state = state;
72                 }
73
74                 public PermissionSet (PermissionSet permSet) : this ()
75                 {
76                         // LAMESPEC: This would be handled by the compiler.  No way permSet is not a PermissionSet.
77                         //if (!(permSet is PermissionSet))
78                         //      throw new System.ArgumentException(); // permSet is not an instance of System.Security.PermissionSet.
79                         if (permSet == null)
80                                 state = PermissionState.Unrestricted;
81                         else {
82                                 state = permSet.state;
83                                 foreach (IPermission p in permSet.list)
84                                         list.Add (p);
85                         }
86                 }
87
88                 internal PermissionSet (string xml)
89                         : this ()
90                 {
91                         state = PermissionState.None;
92                         if (xml != null) {
93                                 SecurityElement se = SecurityElement.FromString (xml);
94                                 FromXml (se);
95                         }
96                 }
97
98                 // Light version for creating a (non unrestricted) PermissionSet with
99                 // a single permission. This allows to relax most validations.
100                 internal PermissionSet (IPermission perm)
101                         : this ()
102                 {
103                         if (perm != null) {
104                                 // note: we do not copy IPermission like AddPermission
105                                 list.Add (perm);
106                         }
107                 }
108
109                 // methods
110
111                 public virtual IPermission AddPermission (IPermission perm)
112                 {
113                         if (perm == null)
114                                 return null;
115
116                         // we don't add to an unrestricted permission set unless...
117                         if (state == PermissionState.Unrestricted) {
118                                 // we're adding identity permission as they don't support unrestricted
119                                 if (perm is IUnrestrictedPermission) {
120                                         // we return the union of the permission with unrestricted
121                                         // which results in a permission of the same type initialized 
122                                         // with PermissionState.Unrestricted
123                                         object[] args = new object [1] { PermissionState.Unrestricted };
124                                         return (IPermission) Activator.CreateInstance (perm.GetType (), args);
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 ("Imperative mode isn't supported")]
141                 public virtual void Assert ()
142                 {
143                         new SecurityPermission (SecurityPermissionFlag.Assertion).Demand ();
144
145                         int count = this.Count;
146
147                         // we (current frame) must have the permission to assert it to others
148                         // otherwise we don't assert (but we don't throw an exception)
149                         foreach (IPermission p in list) {
150                                 // note: we ignore non-CAS permissions
151                                 if (p is IStackWalk) {
152                                         if (!SecurityManager.IsGranted (p)) {
153                                                 return;
154                                         }
155                                 } else
156                                         count--;
157                         }
158
159                         // note: we must ignore the stack modifiers for the non-CAS permissions
160                         if (SecurityManager.SecurityEnabled && (count > 0))
161                                 throw new NotSupportedException ("Currently only declarative Assert are supported.");
162                 }
163
164                 internal void Clear () 
165                 {
166                         list.Clear ();
167                 }
168
169                 public virtual PermissionSet Copy ()
170                 {
171                         return new PermissionSet (this);
172                 }
173
174                 public virtual void CopyTo (Array array, int index)
175                 {
176                         if (null == array)
177                                 throw new ArgumentNullException ("array");
178
179                         if (list.Count > 0) {
180                                 if (array.Rank > 1) {
181                                         throw new ArgumentException (Locale.GetText (
182                                                 "Array has more than one dimension"));
183                                 }
184                                 if (index < 0 || index >= array.Length) {
185                                         throw new IndexOutOfRangeException ("index");
186                                 }
187
188                                 list.CopyTo (array, index);
189                         }
190                 }
191
192                 [MonoTODO ("Imperative Assert, Deny and PermitOnly aren't yet supported")]
193                 public virtual void Demand ()
194                 {
195                         // Note: SecurityEnabled only applies to CAS permissions
196                         // so we're not checking for it (yet)
197                         if (IsEmpty ())
198                                 return;
199
200                         PermissionSet cas = this;
201                         // avoid copy (if possible)
202                         if (ContainsNonCodeAccessPermissions ()) {
203                                 // non CAS permissions (e.g. PrincipalPermission) do not requires a stack walk
204                                 cas = this.Copy ();
205                                 foreach (IPermission p in list) {
206                                         Type t = p.GetType ();
207                                         if (!t.IsSubclassOf (typeof (CodeAccessPermission))) {
208                                                 p.Demand ();
209                                                 // we wont have to process this one in the stack walk
210                                                 cas.RemovePermission (t);
211                                         }
212                                 }
213                         }
214
215                         // don't start the stack walk if
216                         // - the permission set only contains non CAS permissions; or
217                         // - security isn't enabled (applis only to CAS!)
218                         if (!cas.IsEmpty () && SecurityManager.SecurityEnabled)
219                                 CasOnlyDemand (_declsec ? 5 : 3);
220                 }
221
222                 // The number of frames to skip depends on who's calling
223                 // - CodeAccessPermission.Demand (imperative)
224                 // - PermissionSet.Demand (imperative)
225                 // - SecurityManager.InternalDemand (declarative)
226                 internal void CasOnlyDemand (int skip)
227                 {
228                         Assembly current = null;
229
230                         // skip ourself, Demand and other security runtime methods
231                         foreach (SecurityFrame sf in SecurityFrame.GetStack (skip)) {
232                                 if (ProcessFrame (sf, ref current))
233                                         return; // reached Assert
234                         }
235
236                         // Is there a CompressedStack to handle ?
237                         CompressedStack stack = Thread.CurrentThread.GetCompressedStack ();
238                         if ((stack != null) && !stack.IsEmpty ()) {
239                                 foreach (SecurityFrame frame in stack.List) {
240                                         if (ProcessFrame (frame, ref current))
241                                                 return; // reached Assert
242                                 }
243                         }
244                 }
245
246                 [MonoTODO ("Imperative mode isn't supported")]
247                 public virtual void Deny ()
248                 {
249                         if (!SecurityManager.SecurityEnabled)
250                                 return;
251
252                         foreach (IPermission p in list) {
253                                 // note: we ignore non-CAS permissions
254                                 if (p is IStackWalk) {
255                                         throw new NotSupportedException ("Currently only declarative Deny are supported.");
256                                 }
257                         }
258                 }
259
260                 [MonoTODO ("adjust class version with current runtime - unification")]
261                 public virtual void FromXml (SecurityElement et)
262                 {
263                         if (et == null)
264                                 throw new ArgumentNullException ("et");
265                         if (et.Tag != tagName) {
266                                 string msg = String.Format ("Invalid tag {0} expected {1}", et.Tag, tagName);
267                                 throw new ArgumentException (msg, "et");
268                         }
269
270                         if (CodeAccessPermission.IsUnrestricted (et))
271                                 state = PermissionState.Unrestricted;
272                         else
273                                 state = PermissionState.None;
274
275                         list.Clear ();
276                         if (et.Children != null) {
277                                 foreach (SecurityElement se in et.Children) {
278                                         string className = se.Attribute ("class");
279                                         if (className == null) {
280                                                 throw new ArgumentException (Locale.GetText (
281                                                         "No permission class is specified."));
282                                         }
283                                         if (Resolver != null) {
284                                                 // policy class names do not have to be fully qualified
285                                                 className = Resolver.ResolveClassName (className);
286                                         }
287                                         // TODO: adjust class version with current runtime (unification)
288                                         // http://blogs.msdn.com/shawnfa/archive/2004/08/05/209320.aspx
289                                         Type classType = Type.GetType (className);
290                                         if (classType != null) {
291                                                 IPermission p = (IPermission) Activator.CreateInstance (classType, psNone);
292                                                 p.FromXml (se);
293                                                 list.Add (p);
294                                         }
295 #if !NET_2_0
296                                         else {
297                                                 string msg = Locale.GetText ("Can't create an instance of permission class {0}.");
298                                                 throw new ArgumentException (String.Format (msg, se.Attribute ("class")));
299                                         }
300 #endif
301                                 }
302                         }
303                 }
304
305                 public virtual IEnumerator GetEnumerator ()
306                 {
307                         return list.GetEnumerator ();
308                 }
309
310                 public virtual bool IsSubsetOf (PermissionSet target)
311                 {
312                         // if target is empty we must be empty too
313                         if ((target == null) || (target.IsEmpty ()))
314                                 return this.IsEmpty ();
315
316                         // TODO - non CAS permissions must be evaluated for unrestricted
317
318                         // if target is unrestricted then we are a subset
319                         if (!this.IsUnrestricted () && target.IsUnrestricted ())
320                                 return true;
321                         // else target isn't unrestricted.
322                         // so if we are unrestricted, the we can't be a subset
323                         if (this.IsUnrestricted () && !target.IsUnrestricted ())
324                                 return false;
325
326                         // if each of our permission is (a) present and (b) a subset of target
327                         foreach (IPermission p in list) {
328                                 // for every type in both list
329                                 IPermission i = target.GetPermission (p.GetType ());
330                                 if (i == null)
331                                         return false; // not present (condition a)
332                                 if (!p.IsSubsetOf (i))
333                                         return false; // not a subset (condition b)
334                         }
335                         return true;
336                 }
337
338                 [MonoTODO ("Imperative mode isn't supported")]
339                 public virtual void PermitOnly ()
340                 {
341                         if (!SecurityManager.SecurityEnabled)
342                                 return;
343
344                         foreach (IPermission p in list) {
345                                 // note: we ignore non-CAS permissions
346                                 if (p is IStackWalk) {
347                                         throw new NotSupportedException ("Currently only declarative Deny are supported.");
348                                 }
349                         }
350                 }
351
352                 public bool ContainsNonCodeAccessPermissions () 
353                 {
354                         foreach (IPermission p in list) {
355                                 if (! p.GetType ().IsSubclassOf (typeof (CodeAccessPermission)))
356                                         return true;
357                         }
358                         return false;
359                 }
360
361                 [MonoTODO ("little documentation in Fx 2.0 beta 1")]
362                 public static byte[] ConvertPermissionSet (string inFormat, byte[] inData, string outFormat) 
363                 {
364                         if (inFormat == null)
365                                 throw new ArgumentNullException ("inFormat");
366                         if (outFormat == null)
367                                 throw new ArgumentNullException ("outFormat");
368                         if (inData == null)
369                                 return null;
370
371                         if (inFormat == outFormat)
372                                 return inData;
373
374                         PermissionSet ps = null;
375
376                         if (inFormat == "BINARY") {
377                                 if (outFormat.StartsWith ("XML")) {
378                                         using (MemoryStream ms = new MemoryStream (inData)) {
379                                                 BinaryFormatter formatter = new BinaryFormatter ();
380                                                 ps = (PermissionSet) formatter.Deserialize (ms);
381                                                 ms.Close ();
382                                         }
383                                         string xml = ps.ToString ();
384                                         switch (outFormat) {
385                                                 case "XML":
386                                                 case "XMLASCII":
387                                                         return Encoding.ASCII.GetBytes (xml);
388                                                 case "XMLUNICODE":
389                                                         return Encoding.Unicode.GetBytes (xml);
390                                         }
391                                 }
392                         }
393                         else if (inFormat.StartsWith ("XML")) {
394                                 if (outFormat == "BINARY") {
395                                         string xml = null;
396                                         switch (inFormat) {
397                                                 case "XML":
398                                                 case "XMLASCII":
399                                                         xml = Encoding.ASCII.GetString (inData);
400                                                         break;
401                                                 case "XMLUNICODE":
402                                                         xml = Encoding.Unicode.GetString (inData);
403                                                         break;
404                                         }
405                                         if (xml != null) {
406                                                 ps = new PermissionSet (PermissionState.None);
407                                                 ps.FromXml (SecurityElement.FromString (xml));
408
409                                                 MemoryStream ms = new MemoryStream ();
410                                                 BinaryFormatter formatter = new BinaryFormatter ();
411                                                 formatter.Serialize (ms, ps);
412                                                 ms.Close ();
413                                                 return ms.ToArray ();
414                                         }
415                                 }
416                                 else if (outFormat.StartsWith ("XML")) {
417                                         string msg = String.Format (Locale.GetText ("Can't convert from {0} to {1}"), inFormat, outFormat);
418 #if NET_2_0
419                                         throw new XmlSyntaxException (msg);
420 #else
421                                         throw new ArgumentException (msg);
422 #endif
423                                 }
424                         }
425                         else {
426                                 // unknown inFormat, returns null
427                                 return null;
428                         }
429                         // unknown outFormat, throw
430                         throw new SerializationException (String.Format (Locale.GetText ("Unknown output format {0}."), outFormat));
431                 }
432
433                 public virtual IPermission GetPermission (Type permClass) 
434                 {
435                         foreach (object o in list) {
436                                 if (o.GetType ().Equals (permClass))
437                                         return (IPermission) o;
438                         }
439                         // it's normal to return null for unrestricted sets
440                         return null;
441                 }
442
443                 public virtual PermissionSet Intersect (PermissionSet other) 
444                 {
445                         // no intersection possible
446                         if ((other == null) || (other.IsEmpty ()) || (this.IsEmpty ()))
447                                 return null;
448
449                         PermissionState state = PermissionState.None;
450                         if (this.IsUnrestricted () && other.IsUnrestricted ())
451                                 state = PermissionState.Unrestricted;
452
453                         PermissionSet interSet = new PermissionSet (state);
454                         if (state == PermissionState.Unrestricted) {
455                                 InternalIntersect (interSet, this, other, true);
456                                 InternalIntersect (interSet, other, this, true);
457                         }
458                         else if (this.IsUnrestricted ()) {
459                                 InternalIntersect (interSet, this, other, true);
460                         }
461                         else if (other.IsUnrestricted ()) {
462                                 InternalIntersect (interSet, other, this, true);
463                         }
464                         else {
465                                 InternalIntersect (interSet, this, other, false);
466                         }
467                         return interSet;
468                 }
469
470                 internal void InternalIntersect (PermissionSet intersect, PermissionSet a, PermissionSet b, bool unrestricted)
471                 {
472                         foreach (IPermission p in b.list) {
473                                 // for every type in both list
474                                 IPermission i = a.GetPermission (p.GetType ());
475                                 if (i != null) {
476                                         // add intersection for this type
477                                         intersect.AddPermission (p.Intersect (i));
478                                 }
479                                 else if (unrestricted && (p is IUnrestrictedPermission)) {
480                                         intersect.AddPermission (p);
481                                 }
482                                 // or reject!
483                         }
484                 }
485
486                 public virtual bool IsEmpty () 
487                 {
488                         // note: Unrestricted isn't empty
489                         if (state == PermissionState.Unrestricted)
490                                 return false;
491                         if ((list == null) || (list.Count == 0))
492                                 return true;
493                         // the set may include some empty permissions
494                         foreach (IPermission p in list) {
495                                 // empty == fully restricted == IsSubsetOg(null) == true
496                                 if (!p.IsSubsetOf (null))
497                                         return false;
498                         }
499                         return true;
500                 }
501
502                 public virtual bool IsUnrestricted () 
503                 {
504                         return (state == PermissionState.Unrestricted);
505                 }
506
507                 public virtual IPermission RemovePermission (Type permClass) 
508                 {
509                         if (permClass == null)
510                                 return null;
511
512                         foreach (object o in list) {
513                                 if (o.GetType ().Equals (permClass)) {
514                                         list.Remove (o);
515                                         return (IPermission) o;
516                                 }
517                         }
518                         return null;
519                 }
520
521                 public virtual IPermission SetPermission (IPermission perm) 
522                 {
523                         if (perm == null)
524                                 return null;
525                         if (perm is IUnrestrictedPermission)
526                                 state = PermissionState.None;
527                         RemovePermission (perm.GetType ());
528                         list.Add (perm);
529                         return perm;
530                 }
531
532                 public override string ToString ()
533                 {
534                         return ToXml ().ToString ();
535                 }
536
537                 public virtual SecurityElement ToXml ()
538                 {
539                         SecurityElement se = new SecurityElement (tagName);
540                         se.AddAttribute ("class", GetType ().FullName);
541                         se.AddAttribute ("version", version.ToString ());
542                         if (state == PermissionState.Unrestricted)
543                                 se.AddAttribute ("Unrestricted", "true");
544
545                         // required for permissions that do not implement IUnrestrictedPermission
546                         foreach (IPermission p in list) {
547                                 se.AddChild (p.ToXml ());
548                         }
549                         return se;
550                 }
551
552                 public virtual PermissionSet Union (PermissionSet other)
553                 {
554                         if (other == null)
555                                 return this.Copy ();
556
557                         PermissionSet copy = this.Copy ();
558                         if (this.IsUnrestricted () || other.IsUnrestricted ()) {
559                                 // so we keep the "right" type
560                                 copy.Clear ();
561                                 copy.state = PermissionState.Unrestricted;
562                                 // copy all permissions that do not implement IUnrestrictedPermission
563                                 foreach (IPermission p in this.list) {
564                                         if (!(p is IUnrestrictedPermission))
565                                                 copy.AddPermission (p);
566                                 }
567                                 foreach (IPermission p in other.list) {
568                                         if (!(p is IUnrestrictedPermission))
569                                                 copy.AddPermission (p);
570                                 }
571                         }
572                         else {
573                                 // PermissionState.None -> copy all permissions
574                                 foreach (IPermission p in other.list) {
575                                         copy.AddPermission (p);
576                                 }
577                         }
578                         return copy;
579                 }
580
581                 public virtual int Count {
582                         get { return list.Count; }
583                 }
584
585                 public virtual bool IsSynchronized {
586                         get { return list.IsSynchronized; }
587                 }
588
589                 public virtual bool IsReadOnly {
590                         get { return false; } // always false
591                 }
592
593                 public virtual object SyncRoot {
594                         get { return this; }
595                 }
596
597                 internal bool DeclarativeSecurity {
598                         get { return _declsec; }
599                         set { _declsec = value; }
600                 }
601
602                 [MonoTODO()]
603                 void IDeserializationCallback.OnDeserialization (object sender) 
604                 {
605                 }
606
607 #if NET_2_0
608                 [ComVisible (false)]
609                 public override bool Equals (object obj)
610                 {
611                         if (obj == null)
612                                 return false;
613                         PermissionSet ps = (obj as PermissionSet);
614                         if (ps == null)
615                                 return false;
616                         if (list.Count != ps.Count)
617                                 return false;
618
619                         for (int i=0; i < list.Count; i++) {
620                                 bool found = false;
621                                 for (int j=0; i < ps.list.Count; j++) {
622                                         if (list [i].Equals (ps.list [j])) {
623                                                 found = true;
624                                                 break;
625                                         }
626                                 }
627                                 if (!found)
628                                         return false;
629                         }
630                         return true;
631                 }
632
633                 [ComVisible (false)]
634                 public override int GetHashCode ()
635                 {
636                         return (list.Count == 0) ? (int) state : base.GetHashCode ();
637                 }
638
639                 [MonoTODO ("what's it doing here?")]
640                 static public void RevertAssert ()
641                 {
642                         // FIXME: There's probably a reason this was added here ?
643                         CodeAccessPermission.RevertAssert ();
644                 }
645 #endif
646
647                 // internal
648
649                 internal PolicyLevel Resolver {
650                         get { return _policyLevel; }
651                         set { _policyLevel = value; }
652                 }
653
654                 internal bool ProcessFrame (SecurityFrame frame, ref Assembly current)
655                 {
656                         if (IsUnrestricted ()) {
657                                 // we request unrestricted
658                                 if (frame.Deny != null) {
659                                         // but have restrictions (some denied permissions)
660                                         CodeAccessPermission.ThrowSecurityException (this, "Deny", frame.Assembly, 
661                                                 frame.Method, SecurityAction.Demand, null);
662                                 } else if (frame.PermitOnly != null) {
663                                         // but have restrictions (onyl some permitted permissions)
664                                         CodeAccessPermission.ThrowSecurityException (this, "PermitOnly", frame.Assembly,
665                                                 frame.Method, SecurityAction.Demand, null);
666                                 }
667                         }
668
669                         foreach (CodeAccessPermission cap in list) {
670                                 if (cap.ProcessFrame (frame, ref current))
671                                         return true; // Assert reached - abort stack walk!
672                         }
673                         return false;
674                 }
675
676                 // 2.0 metadata format
677
678                 internal static PermissionSet CreateFromBinaryFormat (byte[] data)
679                 {
680                         if ((data == null) || (data [0] != 0x2E) || (data.Length < 2)) {
681                                 string msg = Locale.GetText ("Invalid data in 2.0 metadata format.");
682                                 throw new SecurityException (msg);
683                         }
684
685                         int pos = 1;
686                         int numattr = ReadEncodedInt (data, ref pos);
687                         PermissionSet ps = new PermissionSet (PermissionState.None);
688                         for (int i = 0; i < numattr; i++) {
689                                 IPermission p = ProcessAttribute (data, ref pos);
690                                 if (p == null) {
691                                         string msg = Locale.GetText ("Unsupported data found in 2.0 metadata format.");
692                                         throw new SecurityException (msg);
693                                 }
694                                 ps.AddPermission (p);
695                         }
696                         return ps;
697                 }
698
699                 internal static int ReadEncodedInt (byte[] data, ref int position)
700                 {
701                         int len = 0;
702                         if ((data [position] & 0x80) == 0) {
703                                 len = data [position];
704                                 position ++;
705                         } else if ((data [position] & 0x40) == 0) {
706                                 len = ((data [position] & 0x3f) << 8 | data [position + 1]);
707                                 position += 2;
708                         } else {
709                                 len = (((data [position] & 0x1f) << 24) | (data [position + 1] << 16) |
710                                         (data [position + 2] << 8) | (data [position + 3]));
711                                 position += 4;
712                         }
713                         return len;
714                 }
715
716                 static object[] action = new object [1] { (SecurityAction) 0 };
717
718                 // TODO: add support for arrays and enums
719                 internal static IPermission ProcessAttribute (byte[] data, ref int position)
720                 {
721                         int clen = ReadEncodedInt (data, ref position);
722                         string cnam = Encoding.UTF8.GetString (data, position, clen);
723                         position += clen;
724
725                         // TODO: Unification
726                         Type secattr = Type.GetType (cnam);
727                         SecurityAttribute sa = (Activator.CreateInstance (secattr, action) as SecurityAttribute);
728                         if (sa == null)
729                                 return null;
730
731                         /*int optionalParametersLength =*/ ReadEncodedInt (data, ref position);
732                         int numberOfParameters = ReadEncodedInt (data, ref position);
733                         for (int j=0; j < numberOfParameters; j++) {
734                                 bool property = false;
735                                 switch (data [position++]) {
736                                 case 0x53: // field (technically possible and working)
737                                         property = false;
738                                         break;
739                                 case 0x54: // property (common case)
740                                         property = true;
741                                         break;
742                                 default:
743                                         return null;
744                                 }
745
746                                 bool array = false;
747                                 byte type = data [position++];
748                                 if (type == 0x1D) {
749                                         array = true;
750                                         type = data [position++];
751                                 }
752
753                                 int plen = ReadEncodedInt (data, ref position);
754                                 string pnam = Encoding.UTF8.GetString (data, position, plen);
755                                 position += plen;
756
757                                 int arrayLength = 1;
758                                 if (array) {
759                                         arrayLength = BitConverter.ToInt32 (data, position);
760                                         position += 4;
761                                 }
762
763                                 object obj = null;
764                                 object[] arrayIndex = null;
765                                 for (int i = 0; i < arrayLength; i++) {
766                                         if (array) {
767                                                 // TODO - setup index
768                                         }
769
770                                         // sadly type values doesn't match ther TypeCode enum :(
771                                         switch (type) {
772                                         case 0x02: // MONO_TYPE_BOOLEAN
773                                                 obj = (object) Convert.ToBoolean (data [position++]);
774                                                 break;
775                                         case 0x03: // MONO_TYPE_CHAR
776                                                 obj = (object) Convert.ToChar (data [position]);
777                                                 position += 2;
778                                                 break;
779                                         case 0x04: // MONO_TYPE_I1
780                                                 obj = (object) Convert.ToSByte (data [position++]);
781                                                 break;
782                                         case 0x05: // MONO_TYPE_U1
783                                                 obj = (object) Convert.ToByte (data [position++]);
784                                                 break;
785                                         case 0x06: // MONO_TYPE_I2
786                                                 obj = (object) Convert.ToInt16 (data [position]);
787                                                 position += 2;
788                                                 break;
789                                         case 0x07: // MONO_TYPE_U2
790                                                 obj = (object) Convert.ToUInt16 (data [position]);
791                                                 position += 2;
792                                                 break;
793                                         case 0x08: // MONO_TYPE_I4
794                                                 obj = (object) Convert.ToInt32 (data [position]);
795                                                 position += 4;
796                                                 break;
797                                         case 0x09: // MONO_TYPE_U4
798                                                 obj = (object) Convert.ToUInt32 (data [position]);
799                                                 position += 4;
800                                                 break;
801                                         case 0x0A: // MONO_TYPE_I8
802                                                 obj = (object) Convert.ToInt64 (data [position]);
803                                                 position += 8;
804                                                 break;
805                                         case 0x0B: // MONO_TYPE_U8
806                                                 obj = (object) Convert.ToUInt64 (data [position]);
807                                                 position += 8;
808                                                 break;
809                                         case 0x0C: // MONO_TYPE_R4
810                                                 obj = (object) Convert.ToSingle (data [position]);
811                                                 position += 4;
812                                                 break;
813                                         case 0x0D: // MONO_TYPE_R8
814                                                 obj = (object) Convert.ToDouble (data [position]);
815                                                 position += 8;
816                                                 break;
817                                         case 0x0E: // MONO_TYPE_STRING
818                                                 string s = null;
819                                                 if (data [position] != 0xFF) {
820                                                         int slen = ReadEncodedInt (data, ref position);
821                                                         s = Encoding.UTF8.GetString (data, position, slen);
822                                                         position += slen;
823                                                 } else {
824                                                         position++;
825                                                 }
826                                                 obj = (object) s;
827                                                 break;
828                                         case 0x50: // special for TYPE
829                                                 int tlen = ReadEncodedInt (data, ref position);
830                                                 obj = (object) Type.GetType (Encoding.UTF8.GetString (data, position, tlen));
831                                                 position += tlen;
832                                                 break;
833                                         default:
834                                                 return null; // unsupported
835                                         }
836
837                                         if (property) {
838                                                 PropertyInfo pi = secattr.GetProperty (pnam);
839                                                 pi.SetValue (sa, obj, arrayIndex);
840                                         } else {
841                                                 FieldInfo fi = secattr.GetField (pnam);
842                                                 fi.SetValue (sa, obj);
843                                         }
844                                 }
845                         }
846                         return sa.CreatePermission ();
847                 }
848         }
849 }