2 // InjectSecurityAttributes.cs
5 // Jb Evain (jbevain@novell.com)
7 // (C) 2009 Novell, Inc.
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 using System.Collections;
36 using Mono.Linker.Steps;
40 namespace Mono.Tuner {
42 public class InjectSecurityAttributes : BaseStep {
49 protected enum AttributeType {
54 const string _safe_critical = "System.Security.SecuritySafeCriticalAttribute";
55 const string _critical = "System.Security.SecurityCriticalAttribute";
57 const string sec_attr_folder = "secattrs";
59 protected AssemblyDefinition _assembly;
61 MethodDefinition _safe_critical_ctor;
62 MethodDefinition _critical_ctor;
66 protected override bool ConditionToProcess ()
68 if (!Context.HasParameter (sec_attr_folder)) {
69 Console.Error.WriteLine ("Warning: no secattrs folder specified.");
73 data_folder = Context.GetParameter (sec_attr_folder);
77 protected override void ProcessAssembly (AssemblyDefinition assembly)
79 if (Annotations.GetAction (assembly) != AssemblyAction.Link)
82 string secattr_file = Path.Combine (
84 assembly.Name.Name + ".secattr");
86 if (!File.Exists (secattr_file)) {
87 Console.Error.WriteLine ("Warning: file '{0}' not found, skipping.", secattr_file);
93 // remove existing [SecurityCritical] and [SecuritySafeCritical]
94 RemoveSecurityAttributes ();
96 // add [SecurityCritical] and [SecuritySafeCritical] from the data file
97 ProcessSecurityAttributeFile (secattr_file);
100 protected void RemoveSecurityAttributes ()
102 foreach (TypeDefinition type in _assembly.MainModule.Types) {
103 RemoveSecurityAttributes (type);
106 foreach (MethodDefinition method in type.Methods)
107 RemoveSecurityAttributes (method);
111 static void RemoveSecurityDeclarations (ISecurityDeclarationProvider provider)
113 // also remove already existing CAS security declarations
115 if (provider == null)
118 if (!provider.HasSecurityDeclarations)
121 provider.SecurityDeclarations.Clear ();
124 static void RemoveSecurityAttributes (ICustomAttributeProvider provider)
126 RemoveSecurityDeclarations (provider as ISecurityDeclarationProvider);
128 if (!provider.HasCustomAttributes)
131 var attributes = provider.CustomAttributes;
132 for (int i = 0; i < attributes.Count; i++) {
133 CustomAttribute attribute = attributes [i];
134 switch (attribute.Constructor.DeclaringType.FullName) {
137 attributes.RemoveAt (i--);
143 void ProcessSecurityAttributeFile (string file)
145 using (StreamReader reader = File.OpenText (file)) {
147 while ((line = reader.ReadLine ()) != null)
152 void ProcessLine (string line)
154 if (line == null || line.Length < 6)
157 int sep = line.IndexOf (": ");
161 string marker = line.Substring (0, sep);
162 string target = line.Substring (sep + 2);
164 ProcessSecurityAttributeEntry (
165 DecomposeAttributeType (marker),
166 DecomposeTargetKind (marker),
170 static AttributeType DecomposeAttributeType (string marker)
172 if (marker.StartsWith ("SC"))
173 return AttributeType.Critical;
174 else if (marker.StartsWith ("SSC"))
175 return AttributeType.SafeCritical;
177 throw new ArgumentException ();
180 static TargetKind DecomposeTargetKind (string marker)
182 switch (marker [marker.Length - 1]) {
184 return TargetKind.Type;
186 return TargetKind.Method;
188 throw new ArgumentException ();
192 void ProcessSecurityAttributeEntry (AttributeType type, TargetKind kind, string target)
194 ICustomAttributeProvider provider = GetTarget (kind, target);
195 if (provider == null)
199 case AttributeType.Critical:
200 AddCriticalAttribute (provider);
202 case AttributeType.SafeCritical:
203 AddSafeCriticalAttribute (provider);
208 protected void AddCriticalAttribute (ICustomAttributeProvider provider)
210 // a [SecurityCritical] replaces a [SecuritySafeCritical]
211 if (HasSecurityAttribute (provider, AttributeType.SafeCritical))
212 RemoveSecurityAttributes (provider);
214 AddSecurityAttribute (provider, AttributeType.Critical);
217 void AddSafeCriticalAttribute (ICustomAttributeProvider provider)
219 // a [SecuritySafeCritical] is ignored if a [SecurityCritical] is present
220 if (HasSecurityAttribute (provider, AttributeType.Critical))
223 AddSecurityAttribute (provider, AttributeType.SafeCritical);
226 void AddSecurityAttribute (ICustomAttributeProvider provider, AttributeType type)
228 if (HasSecurityAttribute (provider, type))
231 var attributes = provider.CustomAttributes;
233 case AttributeType.Critical:
234 attributes.Add (CreateCriticalAttribute ());
236 case AttributeType.SafeCritical:
237 attributes.Add (CreateSafeCriticalAttribute ());
242 protected static bool HasSecurityAttribute (ICustomAttributeProvider provider, AttributeType type)
244 if (!provider.HasCustomAttributes)
247 foreach (CustomAttribute attribute in provider.CustomAttributes) {
248 switch (attribute.Constructor.DeclaringType.Name) {
250 if (type == AttributeType.Critical)
255 if (type == AttributeType.SafeCritical)
265 ICustomAttributeProvider GetTarget (TargetKind kind, string target)
268 case TargetKind.Type:
269 return GetType (target);
270 case TargetKind.Method:
271 return GetMethod (target);
273 throw new ArgumentException ();
277 TypeDefinition GetType (string fullname)
279 return _assembly.MainModule.GetType (fullname);
282 MethodDefinition GetMethod (string signature)
284 int pos = signature.IndexOf (" ");
286 throw new ArgumentException ();
288 string tmp = signature.Substring (pos + 1);
290 pos = tmp.IndexOf ("::");
292 throw new ArgumentException ();
294 string type_name = tmp.Substring (0, pos);
296 int parpos = tmp.IndexOf ("(");
298 throw new ArgumentException ();
300 string method_name = tmp.Substring (pos + 2, parpos - pos - 2);
302 TypeDefinition type = GetType (type_name);
306 return GetMethod (type.Methods, signature);
309 static MethodDefinition GetMethod (IEnumerable methods, string signature)
311 foreach (MethodDefinition method in methods)
312 if (GetFullName (method) == signature)
318 static string GetFullName (MethodReference method)
320 var sentinel = method.Parameters.FirstOrDefault (p => p.ParameterType.IsSentinel);
321 var sentinel_pos = -1;
322 if (sentinel != null)
323 sentinel_pos = method.Parameters.IndexOf (sentinel);
325 StringBuilder sb = new StringBuilder ();
326 sb.Append (method.ReturnType.FullName);
328 sb.Append (method.DeclaringType.FullName);
330 sb.Append (method.Name);
331 if (method.HasGenericParameters) {
333 for (int i = 0; i < method.GenericParameters.Count; i++ ) {
336 sb.Append (method.GenericParameters [i].Name);
341 if (method.HasParameters) {
342 for (int i = 0; i < method.Parameters.Count; i++) {
346 if (i == sentinel_pos)
349 sb.Append (method.Parameters [i].ParameterType.FullName);
353 return sb.ToString ();
356 static MethodDefinition GetDefaultConstructor (TypeDefinition type)
358 foreach (MethodDefinition ctor in type.Methods.Where (m => m.IsConstructor))
359 if (ctor.Parameters.Count == 0)
365 MethodDefinition GetSafeCriticalCtor ()
367 if (_safe_critical_ctor != null)
368 return _safe_critical_ctor;
370 TypeDefinition safe_critical_type = Context.GetType (_safe_critical);
371 if (safe_critical_type == null)
372 throw new InvalidOperationException (String.Format ("{0} type not found", _safe_critical));
374 _safe_critical_ctor = GetDefaultConstructor (safe_critical_type);
375 return _safe_critical_ctor;
378 MethodDefinition GetCriticalCtor ()
380 if (_critical_ctor != null)
381 return _critical_ctor;
383 TypeDefinition critical_type = Context.GetType (_critical);
384 if (critical_type == null)
385 throw new InvalidOperationException (String.Format ("{0} type not found", _critical));
387 _critical_ctor = GetDefaultConstructor (critical_type);
388 return _critical_ctor;
391 MethodReference Import (MethodDefinition method)
393 return _assembly.MainModule.Import (method);
396 CustomAttribute CreateSafeCriticalAttribute ()
398 return new CustomAttribute (Import (GetSafeCriticalCtor ()));
401 CustomAttribute CreateCriticalAttribute ()
403 return new CustomAttribute (Import (GetCriticalCtor ()));