2010-04-06 Jb Evain <jbevain@novell.com>
[mcs.git] / class / corlib / System.Security / PermissionSet.cs
blob2a9b3e40c444df354ced988184df249f27ce822a
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)
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.
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;
44 namespace System.Security {
46 [Serializable]
47 // Microsoft public key - i.e. only MS signed assembly can inherit from PermissionSet (1.x) or (2.0) FullTrust assemblies
48 [StrongNameIdentityPermission (SecurityAction.InheritanceDemand, PublicKey="002400000480000094000000060200000024000052534131000400000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8A12436518206DC093344D5AD293")]
49 [ComVisible (true)]
50 [MonoTODO ("CAS support is experimental (and unsupported).")]
51 public class PermissionSet: ISecurityEncodable, ICollection, IEnumerable, IStackWalk, IDeserializationCallback {
53 private const string tagName = "PermissionSet";
54 private const int version = 1;
55 private static object[] psUnrestricted = new object [1] { PermissionState.Unrestricted };
57 private PermissionState state;
58 private ArrayList list;
59 private PolicyLevel _policyLevel;
60 private bool _declsec;
61 private bool _readOnly;
62 private bool[] _ignored; // for asserts and non-CAS permissions
64 // constructors
66 // for PolicyLevel (to avoid validation duplication)
67 internal PermissionSet ()
69 list = new ArrayList ();
72 public PermissionSet (PermissionState state) : this ()
74 this.state = CodeAccessPermission.CheckPermissionState (state, true);
77 public PermissionSet (PermissionSet permSet) : this ()
79 // LAMESPEC: This would be handled by the compiler. No way permSet is not a PermissionSet.
80 //if (!(permSet is PermissionSet))
81 // throw new System.ArgumentException(); // permSet is not an instance of System.Security.PermissionSet.
82 if (permSet != null) {
83 state = permSet.state;
84 foreach (IPermission p in permSet.list)
85 list.Add (p);
89 internal PermissionSet (string xml)
90 : this ()
92 state = PermissionState.None;
93 if (xml != null) {
94 SecurityElement se = SecurityElement.FromString (xml);
95 FromXml (se);
99 // Light version for creating a (non unrestricted) PermissionSet with
100 // a single permission. This allows to relax most validations.
101 internal PermissionSet (IPermission perm)
102 : this ()
104 if (perm != null) {
105 // note: we do not copy IPermission like AddPermission
106 list.Add (perm);
110 // methods
112 public IPermission AddPermission (IPermission perm)
114 if ((perm == null) || _readOnly)
115 return perm;
117 // we don't add to an unrestricted permission set unless...
118 if (state == PermissionState.Unrestricted) {
119 // identity permissions can be unrestricted under 2.x
121 // we return the union of the permission with unrestricted
122 // which results in a permission of the same type initialized
123 // with PermissionState.Unrestricted
124 return (IPermission) Activator.CreateInstance (perm.GetType (), psUnrestricted);
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);
135 // note: Add doesn't copy
136 list.Add (perm);
137 return perm;
140 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
141 [SecurityPermission (SecurityAction.Demand, Assertion = true)]
142 public void Assert ()
144 int count = this.Count;
146 // we (current frame) must have the permission to assert it to others
147 // otherwise we don't assert (but we don't throw an exception)
148 foreach (IPermission p in list) {
149 // note: we ignore non-CAS permissions
150 if (p is IStackWalk) {
151 if (!SecurityManager.IsGranted (p)) {
152 return;
154 } else
155 count--;
158 // note: we must ignore the stack modifiers for the non-CAS permissions
159 if (SecurityManager.SecurityEnabled && (count > 0))
160 throw new NotSupportedException ("Currently only declarative Assert are supported.");
163 internal void Clear ()
165 list.Clear ();
168 public virtual PermissionSet Copy ()
170 return new PermissionSet (this);
173 public virtual void CopyTo (Array array, int index)
175 if (null == array)
176 throw new ArgumentNullException ("array");
178 if (list.Count > 0) {
179 if (array.Rank > 1) {
180 throw new ArgumentException (Locale.GetText (
181 "Array has more than one dimension"));
183 if (index < 0 || index >= array.Length) {
184 throw new IndexOutOfRangeException ("index");
187 list.CopyTo (array, index);
191 public void Demand ()
193 // Note: SecurityEnabled only applies to CAS permissions
194 // so we're not checking for it (yet)
195 if (IsEmpty ())
196 return;
198 int n = list.Count;
199 if ((_ignored == null) || (_ignored.Length != n)) {
200 _ignored = new bool [n];
203 bool call_cas_only = this.IsUnrestricted ();
204 // non CAS permissions (e.g. PrincipalPermission) do not requires a stack walk
205 for (int i = 0; i < n; i++) {
206 IPermission p = (IPermission) list [i];
207 Type t = p.GetType ();
208 if (t.IsSubclassOf (typeof (CodeAccessPermission))) {
209 _ignored [i] = false;
210 call_cas_only = true;
211 } else {
212 _ignored [i] = true;
213 p.Demand ();
217 // don't start the stack walk if
218 // - the permission set only contains non CAS permissions; or
219 // - security isn't enabled (applis only to CAS!)
220 if (call_cas_only && SecurityManager.SecurityEnabled)
221 CasOnlyDemand (_declsec ? 5 : 3);
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)
230 Assembly current = null;
231 AppDomain domain = null;
233 if (_ignored == null) {
234 // special case when directly called from CodeAccessPermission.Demand
235 _ignored = new bool [list.Count];
238 ArrayList frames = SecurityFrame.GetStack (skip);
239 if ((frames != null) && (frames.Count > 0)) {
240 SecurityFrame first = ((SecurityFrame) frames [0]);
241 current = first.Assembly;
242 domain = first.Domain;
243 // skip ourself, Demand and other security runtime methods
244 foreach (SecurityFrame sf in frames) {
245 if (ProcessFrame (sf, ref current, ref domain)) {
246 if (AllIgnored ())
247 return; // reached Assert
250 SecurityFrame last = ((SecurityFrame) frames [frames.Count - 1]);
251 CheckAssembly (current, last);
252 CheckAppDomain (domain, last);
255 // Is there a CompressedStack to handle ?
256 CompressedStack stack = Thread.CurrentThread.GetCompressedStack ();
257 if ((stack != null) && !stack.IsEmpty ()) {
258 foreach (SecurityFrame frame in stack.List) {
259 if (ProcessFrame (frame, ref current, ref domain)) {
260 if (AllIgnored ())
261 return; // reached Assert
267 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
268 public void Deny ()
270 if (!SecurityManager.SecurityEnabled)
271 return;
273 foreach (IPermission p in list) {
274 // note: we ignore non-CAS permissions
275 if (p is IStackWalk) {
276 throw new NotSupportedException ("Currently only declarative Deny are supported.");
281 public virtual void FromXml (SecurityElement et)
283 if (et == null)
284 throw new ArgumentNullException ("et");
285 if (et.Tag != tagName) {
286 string msg = String.Format ("Invalid tag {0} expected {1}", et.Tag, tagName);
287 throw new ArgumentException (msg, "et");
290 list.Clear ();
292 if (CodeAccessPermission.IsUnrestricted (et)) {
293 state = PermissionState.Unrestricted;
294 // no need to continue for an unrestricted permission
295 // because identity permissions now "supports" unrestricted
296 return;
297 } else {
298 state = PermissionState.None;
301 if (et.Children != null) {
302 foreach (SecurityElement se in et.Children) {
303 string className = se.Attribute ("class");
304 if (className == null) {
305 throw new ArgumentException (Locale.GetText (
306 "No permission class is specified."));
308 if (Resolver != null) {
309 // policy class names do not have to be fully qualified
310 className = Resolver.ResolveClassName (className);
313 list.Add (PermissionBuilder.Create (className, se));
318 public IEnumerator GetEnumerator ()
320 return list.GetEnumerator ();
323 public bool IsSubsetOf (PermissionSet target)
325 // if target is empty we must be empty too
326 if ((target == null) || (target.IsEmpty ()))
327 return this.IsEmpty ();
329 // all permissions support unrestricted in 2.0
330 if (target.IsUnrestricted ())
331 return true;
332 if (this.IsUnrestricted ())
333 return false;
335 if (this.IsUnrestricted () && ((target == null) || !target.IsUnrestricted ()))
336 return false;
338 // if each of our permission is (a) present and (b) a subset of target
339 foreach (IPermission p in list) {
340 // non CAS permissions must be evaluated for unrestricted
341 Type t = p.GetType ();
342 IPermission i = null;
343 if (target.IsUnrestricted () && (p is CodeAccessPermission) && (p is IUnrestrictedPermission)) {
344 i = (IPermission) Activator.CreateInstance (t, psUnrestricted);
345 } else {
346 i = target.GetPermission (t);
349 if (!p.IsSubsetOf (i))
350 return false; // not a subset (condition b)
352 return true;
355 [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
356 public void PermitOnly ()
358 if (!SecurityManager.SecurityEnabled)
359 return;
361 foreach (IPermission p in list) {
362 // note: we ignore non-CAS permissions
363 if (p is IStackWalk) {
364 throw new NotSupportedException ("Currently only declarative Deny are supported.");
369 public bool ContainsNonCodeAccessPermissions ()
371 if (list.Count > 0) {
372 foreach (IPermission p in list) {
373 if (! p.GetType ().IsSubclassOf (typeof (CodeAccessPermission)))
374 return true;
377 return false;
380 // FIXME little documentation in Fx 2.0 beta 1
381 public static byte[] ConvertPermissionSet (string inFormat, byte[] inData, string outFormat)
383 if (inFormat == null)
384 throw new ArgumentNullException ("inFormat");
385 if (outFormat == null)
386 throw new ArgumentNullException ("outFormat");
387 if (inData == null)
388 return null;
390 if (inFormat == outFormat)
391 return inData;
393 PermissionSet ps = null;
395 if (inFormat == "BINARY") {
396 if (outFormat.StartsWith ("XML")) {
397 using (MemoryStream ms = new MemoryStream (inData)) {
398 BinaryFormatter formatter = new BinaryFormatter ();
399 ps = (PermissionSet) formatter.Deserialize (ms);
400 ms.Close ();
402 string xml = ps.ToString ();
403 switch (outFormat) {
404 case "XML":
405 case "XMLASCII":
406 return Encoding.ASCII.GetBytes (xml);
407 case "XMLUNICODE":
408 return Encoding.Unicode.GetBytes (xml);
412 else if (inFormat.StartsWith ("XML")) {
413 if (outFormat == "BINARY") {
414 string xml = null;
415 switch (inFormat) {
416 case "XML":
417 case "XMLASCII":
418 xml = Encoding.ASCII.GetString (inData);
419 break;
420 case "XMLUNICODE":
421 xml = Encoding.Unicode.GetString (inData);
422 break;
424 if (xml != null) {
425 ps = new PermissionSet (PermissionState.None);
426 ps.FromXml (SecurityElement.FromString (xml));
428 MemoryStream ms = new MemoryStream ();
429 BinaryFormatter formatter = new BinaryFormatter ();
430 formatter.Serialize (ms, ps);
431 ms.Close ();
432 return ms.ToArray ();
435 else if (outFormat.StartsWith ("XML")) {
436 string msg = String.Format (Locale.GetText ("Can't convert from {0} to {1}"), inFormat, outFormat);
437 throw new XmlSyntaxException (msg);
440 else {
441 // unknown inFormat, returns null
442 return null;
444 // unknown outFormat, throw
445 throw new SerializationException (String.Format (Locale.GetText ("Unknown output format {0}."), outFormat));
448 public IPermission GetPermission (Type permClass)
450 if ((permClass == null) || (list.Count == 0))
451 return null;
453 foreach (object o in list) {
454 if ((o != null) && o.GetType ().Equals (permClass))
455 return (IPermission) o;
457 // it's normal to return null for unrestricted sets
458 return null;
461 public PermissionSet Intersect (PermissionSet other)
463 // no intersection possible
464 if ((other == null) || (other.IsEmpty ()) || (this.IsEmpty ()))
465 return null;
467 PermissionState state = PermissionState.None;
468 if (this.IsUnrestricted () && other.IsUnrestricted ())
469 state = PermissionState.Unrestricted;
471 PermissionSet interSet = null;
472 // much simpler with 2.0
473 if (state == PermissionState.Unrestricted) {
474 interSet = new PermissionSet (state);
475 } else if (this.IsUnrestricted ()) {
476 interSet = other.Copy ();
477 } else if (other.IsUnrestricted ()) {
478 interSet = this.Copy ();
479 } else {
480 interSet = new PermissionSet (state);
481 InternalIntersect (interSet, this, other, false);
483 return interSet;
486 internal void InternalIntersect (PermissionSet intersect, PermissionSet a, PermissionSet b, bool unrestricted)
488 foreach (IPermission p in b.list) {
489 // for every type in both list
490 IPermission i = a.GetPermission (p.GetType ());
491 if (i != null) {
492 // add intersection for this type
493 intersect.AddPermission (p.Intersect (i));
495 // unrestricted is possible for indentity permissions
496 else if (unrestricted) {
497 intersect.AddPermission (p);
499 // or reject!
503 public bool IsEmpty ()
505 // note: Unrestricted isn't empty
506 if (state == PermissionState.Unrestricted)
507 return false;
508 if ((list == null) || (list.Count == 0))
509 return true;
510 // the set may include some empty permissions
511 foreach (IPermission p in list) {
512 // empty == fully restricted == IsSubsetOf(null) == true
513 if (!p.IsSubsetOf (null))
514 return false;
516 return true;
519 public bool IsUnrestricted ()
521 return (state == PermissionState.Unrestricted);
524 public IPermission RemovePermission (Type permClass)
526 if ((permClass == null) || _readOnly)
527 return null;
529 foreach (object o in list) {
530 if (o.GetType ().Equals (permClass)) {
531 list.Remove (o);
532 return (IPermission) o;
535 return null;
538 public IPermission SetPermission (IPermission perm)
540 if ((perm == null) || _readOnly)
541 return perm;
542 IUnrestrictedPermission u = (perm as IUnrestrictedPermission);
543 if (u == null) {
544 state = PermissionState.None;
545 } else {
546 state = u.IsUnrestricted () ? state : PermissionState.None;
548 RemovePermission (perm.GetType ());
549 list.Add (perm);
550 return perm;
553 public override string ToString ()
555 return ToXml ().ToString ();
558 public virtual SecurityElement ToXml ()
560 SecurityElement se = new SecurityElement (tagName);
561 se.AddAttribute ("class", GetType ().FullName);
562 se.AddAttribute ("version", version.ToString ());
563 if (state == PermissionState.Unrestricted)
564 se.AddAttribute ("Unrestricted", "true");
566 // required for permissions that do not implement IUnrestrictedPermission
567 foreach (IPermission p in list) {
568 se.AddChild (p.ToXml ());
570 return se;
573 public PermissionSet Union (PermissionSet other)
575 if (other == null)
576 return this.Copy ();
578 PermissionSet copy = null;
579 if (this.IsUnrestricted () || other.IsUnrestricted ()) {
580 // there are no child elements in unrestricted permission sets
581 return new PermissionSet (PermissionState.Unrestricted);
582 } else {
583 copy = this.Copy ();
584 // PermissionState.None -> copy all permissions
585 foreach (IPermission p in other.list) {
586 copy.AddPermission (p);
589 return copy;
592 public virtual int Count {
593 get { return list.Count; }
596 public virtual bool IsSynchronized {
597 get { return list.IsSynchronized; }
600 public virtual bool IsReadOnly {
601 // always false (as documented) but the PermissionSet can be read-only
602 // e.g. in a PolicyStatement
603 get { return false; }
606 public virtual object SyncRoot {
607 get { return this; }
610 internal bool DeclarativeSecurity {
611 get { return _declsec; }
612 set { _declsec = value; }
615 [MonoTODO ("may not be required")]
616 void IDeserializationCallback.OnDeserialization (object sender)
620 [ComVisible (false)]
621 public override bool Equals (object obj)
623 if (obj == null)
624 return false;
625 PermissionSet ps = (obj as PermissionSet);
626 if (ps == null)
627 return false;
628 if (state != ps.state)
629 return false;
630 if (list.Count != ps.Count)
631 return false;
633 for (int i=0; i < list.Count; i++) {
634 bool found = false;
635 for (int j=0; i < ps.list.Count; j++) {
636 if (list [i].Equals (ps.list [j])) {
637 found = true;
638 break;
641 if (!found)
642 return false;
644 return true;
647 [ComVisible (false)]
648 public override int GetHashCode ()
650 return (list.Count == 0) ? (int) state : base.GetHashCode ();
653 // FIXME what's it doing here? There's probably a reason this was added here.
654 static public void RevertAssert ()
656 CodeAccessPermission.RevertAssert ();
659 // internal
661 internal PolicyLevel Resolver {
662 get { return _policyLevel; }
663 set { _policyLevel = value; }
666 internal void SetReadOnly (bool value)
668 _readOnly = value;
671 private bool AllIgnored ()
673 if (_ignored == null)
674 throw new NotSupportedException ("bad bad bad");
676 for (int i=0; i < _ignored.Length; i++) {
677 if (!_ignored [i])
678 return false;
680 // everything is ignored (i.e. non-CAS permission or asserted permission).
681 return true;
684 internal bool ProcessFrame (SecurityFrame frame, ref Assembly current, ref AppDomain domain)
686 if (IsUnrestricted ()) {
687 // we request unrestricted
688 if (frame.Deny != null) {
689 // but have restrictions (some denied permissions)
690 CodeAccessPermission.ThrowSecurityException (this, "Deny", frame, SecurityAction.Demand, null);
691 } else if ((frame.PermitOnly != null) && !frame.PermitOnly.IsUnrestricted ()) {
692 // but have restrictions (only some permitted permissions)
693 CodeAccessPermission.ThrowSecurityException (this, "PermitOnly", frame, SecurityAction.Demand, null);
697 // skip next steps if no Assert, Deny or PermitOnly are present
698 if (frame.HasStackModifiers) {
699 for (int i = 0; i < list.Count; i++) {
700 CodeAccessPermission cap = (CodeAccessPermission) list [i];
701 if (cap.ProcessFrame (frame)) {
702 _ignored [i] = true; // asserted
703 if (AllIgnored ())
704 return true; // no more, abort stack walk!
709 // however the "final" grant set is resolved by assembly, so
710 // there's no need to check it every time (just when we're
711 // changing assemblies between frames).
712 if (frame.Assembly != current) {
713 CheckAssembly (current, frame);
714 current = frame.Assembly;
717 if (frame.Domain != domain) {
718 CheckAppDomain (domain, frame);
719 domain = frame.Domain;
722 return false;
725 internal void CheckAssembly (Assembly a, SecurityFrame frame)
727 IPermission p = SecurityManager.CheckPermissionSet (a, this, false);
728 if (p != null) {
729 CodeAccessPermission.ThrowSecurityException (this, "Demand failed assembly permissions checks.",
730 frame, SecurityAction.Demand, p);
734 internal void CheckAppDomain (AppDomain domain, SecurityFrame frame)
736 IPermission p = SecurityManager.CheckPermissionSet (domain, this);
737 if (p != null) {
738 CodeAccessPermission.ThrowSecurityException (this, "Demand failed appdomain permissions checks.",
739 frame, SecurityAction.Demand, p);
743 // 2.0 metadata format
745 internal static PermissionSet CreateFromBinaryFormat (byte[] data)
747 if ((data == null) || (data [0] != 0x2E) || (data.Length < 2)) {
748 string msg = Locale.GetText ("Invalid data in 2.0 metadata format.");
749 throw new SecurityException (msg);
752 int pos = 1;
753 int numattr = ReadEncodedInt (data, ref pos);
754 PermissionSet ps = new PermissionSet (PermissionState.None);
755 for (int i = 0; i < numattr; i++) {
756 IPermission p = ProcessAttribute (data, ref pos);
757 if (p == null) {
758 string msg = Locale.GetText ("Unsupported data found in 2.0 metadata format.");
759 throw new SecurityException (msg);
761 ps.AddPermission (p);
763 return ps;
766 internal static int ReadEncodedInt (byte[] data, ref int position)
768 int len = 0;
769 if ((data [position] & 0x80) == 0) {
770 len = data [position];
771 position ++;
772 } else if ((data [position] & 0x40) == 0) {
773 len = ((data [position] & 0x3f) << 8 | data [position + 1]);
774 position += 2;
775 } else {
776 len = (((data [position] & 0x1f) << 24) | (data [position + 1] << 16) |
777 (data [position + 2] << 8) | (data [position + 3]));
778 position += 4;
780 return len;
783 static object[] action = new object [1] { (SecurityAction) 0 };
785 // TODO: add support for arrays and enums (2.0)
786 internal static IPermission ProcessAttribute (byte[] data, ref int position)
788 int clen = ReadEncodedInt (data, ref position);
789 string cnam = Encoding.UTF8.GetString (data, position, clen);
790 position += clen;
792 Type secattr = Type.GetType (cnam);
793 SecurityAttribute sa = (Activator.CreateInstance (secattr, action) as SecurityAttribute);
794 if (sa == null)
795 return null;
797 /*int optionalParametersLength =*/ ReadEncodedInt (data, ref position);
798 int numberOfParameters = ReadEncodedInt (data, ref position);
799 for (int j=0; j < numberOfParameters; j++) {
800 bool property = false;
801 switch (data [position++]) {
802 case 0x53: // field (technically possible and working)
803 property = false;
804 break;
805 case 0x54: // property (common case)
806 property = true;
807 break;
808 default:
809 return null;
812 bool array = false;
813 byte type = data [position++];
814 if (type == 0x1D) {
815 array = true;
816 type = data [position++];
819 int plen = ReadEncodedInt (data, ref position);
820 string pnam = Encoding.UTF8.GetString (data, position, plen);
821 position += plen;
823 int arrayLength = 1;
824 if (array) {
825 arrayLength = BitConverter.ToInt32 (data, position);
826 position += 4;
829 object obj = null;
830 object[] arrayIndex = null;
831 for (int i = 0; i < arrayLength; i++) {
832 if (array) {
833 // TODO - setup index (2.0)
836 // sadly type values doesn't match ther TypeCode enum :(
837 switch (type) {
838 case 0x02: // MONO_TYPE_BOOLEAN
839 obj = (object) Convert.ToBoolean (data [position++]);
840 break;
841 case 0x03: // MONO_TYPE_CHAR
842 obj = (object) Convert.ToChar (data [position]);
843 position += 2;
844 break;
845 case 0x04: // MONO_TYPE_I1
846 obj = (object) Convert.ToSByte (data [position++]);
847 break;
848 case 0x05: // MONO_TYPE_U1
849 obj = (object) Convert.ToByte (data [position++]);
850 break;
851 case 0x06: // MONO_TYPE_I2
852 obj = (object) Convert.ToInt16 (data [position]);
853 position += 2;
854 break;
855 case 0x07: // MONO_TYPE_U2
856 obj = (object) Convert.ToUInt16 (data [position]);
857 position += 2;
858 break;
859 case 0x08: // MONO_TYPE_I4
860 obj = (object) Convert.ToInt32 (data [position]);
861 position += 4;
862 break;
863 case 0x09: // MONO_TYPE_U4
864 obj = (object) Convert.ToUInt32 (data [position]);
865 position += 4;
866 break;
867 case 0x0A: // MONO_TYPE_I8
868 obj = (object) Convert.ToInt64 (data [position]);
869 position += 8;
870 break;
871 case 0x0B: // MONO_TYPE_U8
872 obj = (object) Convert.ToUInt64 (data [position]);
873 position += 8;
874 break;
875 case 0x0C: // MONO_TYPE_R4
876 obj = (object) Convert.ToSingle (data [position]);
877 position += 4;
878 break;
879 case 0x0D: // MONO_TYPE_R8
880 obj = (object) Convert.ToDouble (data [position]);
881 position += 8;
882 break;
883 case 0x0E: // MONO_TYPE_STRING
884 string s = null;
885 if (data [position] != 0xFF) {
886 int slen = ReadEncodedInt (data, ref position);
887 s = Encoding.UTF8.GetString (data, position, slen);
888 position += slen;
889 } else {
890 position++;
892 obj = (object) s;
893 break;
894 case 0x50: // special for TYPE
895 int tlen = ReadEncodedInt (data, ref position);
896 obj = (object) Type.GetType (Encoding.UTF8.GetString (data, position, tlen));
897 position += tlen;
898 break;
899 default:
900 return null; // unsupported
903 if (property) {
904 PropertyInfo pi = secattr.GetProperty (pnam);
905 pi.SetValue (sa, obj, arrayIndex);
906 } else {
907 FieldInfo fi = secattr.GetField (pnam);
908 fi.SetValue (sa, obj);
912 return sa.CreatePermission ();