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