Fix typo in OIDs corresponding to SHA256, SHA384, and SHA512 (#21707)
[mono-project.git] / mcs / tools / mono-shlib-cop / mono-shlib-cop.cs
blob228796999ffe6a57edd04bb797feb189ed458105
1 //
2 // mono-shlib-cop.cs: Check unmanaged dependencies
3 //
4 // Compile as:
5 // mcs mono-shlib-cop.cs ../../class/Mono.Options/Mono.Options/Options.cs -r:Mono.Posix
6 //
7 // Authors:
8 // Jonathan Pryor (jonpryor@vt.edu)
9 // Jonathan Pryor (jpryor@novell.com)
11 // (C) 2005 Jonathan Pryor
12 // (C) 2008 Novell, Inc.
16 // Permission is hereby granted, free of charge, to any person obtaining
17 // a copy of this software and associated documentation files (the
18 // "Software"), to deal in the Software without restriction, including
19 // without limitation the rights to use, copy, modify, merge, publish,
20 // distribute, sublicense, and/or sell copies of the Software, and to
21 // permit persons to whom the Software is furnished to do so, subject to
22 // the following conditions:
23 //
24 // The above copyright notice and this permission notice shall be
25 // included in all copies or substantial portions of the Software.
26 //
27 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
31 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
32 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 // About:
38 // mono-shlib-cop is designed to inspect an assembly and report about
39 // potentially erroneous practices. In particular, this includes:
40 // - DllImporting a .so which may be a symlink (which typically requires the
41 // -devel packages on Linux distros, thus bloating installation and
42 // angering users)
43 // - DllImporting a symbol which doesn't exist in the target library
44 // - etc.
46 // Implementation:
47 // - Each assembly needs to be loaded into an AppDomain so that we can
48 // adjust the ApplicationBase path (which will allow us to more reliably
49 // load assemblies which depend upon assemblies in the same directory).
50 // We can share AppDomains (1/directory), but we (alas) can't use a
51 // single AppDomain for the entire app.
52 // - Thus, algorithm:
53 // - Create AppDomain with ApplicationBase path set to directory assembly
54 // resides in
55 // - Create an AssemblyChecker instance within the AppDomain
56 // - Check an assembly with AssemblyChecker; store results in AssemblyCheckInfo.
57 // - Print results.
59 // TODO:
60 // - AppDomain use
61 // - Make -r work correctly (-r:Mono.Posix should read Mono.Posix from the
62 // GAC and inspect it.)
64 #define TRACE
66 using System;
67 using System.Collections;
68 using System.Collections.Generic;
69 using System.Diagnostics;
70 using System.IO;
71 using System.Reflection;
72 using System.Runtime.InteropServices;
73 using System.Xml;
75 using Mono.Options;
76 using Mono.Unix;
78 [assembly: AssemblyTitle ("mono-shlib-cop")]
79 [assembly: AssemblyCopyright ("(C) 2005 Jonathan Pryor")]
80 [assembly: AssemblyDescription ("Looks up shared library dependencies of managed code")]
82 namespace Mono.Unmanaged.Check {
83 [Serializable]
84 sealed class MessageInfo {
85 public string Type;
86 public string Member;
87 public string Message;
89 public MessageInfo (string type, string member, string message)
91 Type = type;
92 Member = member;
93 Message = message;
96 public override bool Equals (object value)
98 MessageInfo other = value as MessageInfo;
99 if (other == null)
100 return false;
102 return Type == other.Type && Member == other.Member &&
103 Message == other.Message;
106 public override int GetHashCode ()
108 return Type.GetHashCode () ^ Member.GetHashCode () ^
109 Message.GetHashCode ();
113 sealed class MessageCollection : MarshalByRefObject {
114 private ArrayList InnerList = new ArrayList ();
116 public MessageCollection ()
120 public int Add (MessageInfo value)
122 if (!InnerList.Contains (value))
123 return InnerList.Add (value);
124 return InnerList.IndexOf (value);
127 public void AddRange (MessageInfo[] value)
129 foreach (MessageInfo v in value)
130 Add (v);
133 public void AddRange (MessageCollection value)
135 foreach (MessageInfo v in value)
136 Add (v);
139 public bool Contains (MessageInfo value)
141 return InnerList.Contains (value);
144 public void CopyTo (MessageInfo[] array, int index)
146 InnerList.CopyTo (array, index);
149 public int IndexOf (MessageInfo value)
151 return InnerList.IndexOf (value);
154 public void Insert (int index, MessageInfo value)
156 InnerList.Insert (index, value);
159 public void Remove (MessageInfo value)
161 InnerList.Remove (value);
164 public IEnumerator GetEnumerator ()
166 return InnerList.GetEnumerator ();
170 sealed class AssemblyCheckInfo : MarshalByRefObject {
171 private MessageCollection errors = new MessageCollection ();
172 private MessageCollection warnings = new MessageCollection ();
174 public MessageCollection Errors {
175 get {return errors;}
178 public MessageCollection Warnings {
179 get {return warnings;}
182 private XmlDocument[] mono_configs = new XmlDocument [0];
183 private IDictionary assembly_configs = new Hashtable ();
185 public void SetInstallationPrefixes (IList<string> prefixes)
187 mono_configs = new XmlDocument [prefixes.Count];
188 for (int i = 0; i < mono_configs.Length; ++i) {
189 mono_configs [i] = new XmlDocument ();
190 mono_configs [i].Load (Path.Combine (prefixes [i], "etc/mono/config"));
194 public string GetDllmapEntry (string assemblyPath, string library)
196 string xpath = "/configuration/dllmap[@dll=\"" + library + "\"]";
198 XmlDocument d = GetAssemblyConfig (assemblyPath);
199 if (d != null) {
200 XmlNode map = d.SelectSingleNode (xpath);
201 if (map != null)
202 return map.Attributes ["target"].Value;
204 foreach (XmlDocument config in mono_configs) {
205 XmlNode map = config.SelectSingleNode (xpath);
206 if (map != null)
207 return map.Attributes ["target"].Value;
209 return null;
212 private XmlDocument GetAssemblyConfig (string assemblyPath)
214 XmlDocument d = null;
215 if (assembly_configs.Contains (assemblyPath)) {
216 d = (XmlDocument) assembly_configs [assemblyPath];
218 else {
219 string _config = assemblyPath + ".config";
220 if (File.Exists (_config)) {
221 d = new XmlDocument ();
222 d.Load (_config);
224 assembly_configs.Add (assemblyPath, d);
226 return d;
230 sealed class AssemblyChecker : MarshalByRefObject {
232 public void CheckFile (string file, AssemblyCheckInfo report)
234 try {
235 Check (Assembly.LoadFile (Path.GetFullPath (file)), report);
237 catch (FileNotFoundException e) {
238 report.Errors.Add (new MessageInfo (null, null,
239 "Could not load `" + file + "': " + e.Message));
243 public void CheckWithPartialName (string partial, AssemblyCheckInfo report)
245 string p = partial;
246 Assembly a;
247 bool retry;
249 do {
250 a = Assembly.LoadWithPartialName (p);
251 retry = p.EndsWith (".dll");
252 if (retry) {
253 p = p.Substring (0, p.Length-4);
255 } while (a == null && retry);
257 if (a == null) {
258 report.Errors.Add (new MessageInfo (null, null,
259 "Could not load assembly reference `" + partial + "'."));
260 return;
263 Check (a, report);
266 private void Check (Assembly a, AssemblyCheckInfo report)
268 foreach (Type t in a.GetTypes ()) {
269 Check (t, report);
273 private void Check (Type type, AssemblyCheckInfo report)
275 BindingFlags bf = BindingFlags.Instance | BindingFlags.Static |
276 BindingFlags.Public | BindingFlags.NonPublic;
278 foreach (MemberInfo mi in type.GetMembers (bf)) {
279 CheckMember (type, mi, report);
283 private void CheckMember (Type type, MemberInfo mi, AssemblyCheckInfo report)
285 DllImportAttribute[] attributes = null;
286 MethodBase[] methods = null;
287 switch (mi.MemberType) {
288 case MemberTypes.Constructor: case MemberTypes.Method: {
289 MethodBase mb = (MethodBase) mi;
290 attributes = new DllImportAttribute[]{GetDllImportInfo (mb)};
291 methods = new MethodBase[]{mb};
292 break;
294 case MemberTypes.Event: {
295 EventInfo ei = (EventInfo) mi;
296 MethodBase add = ei.GetAddMethod (true);
297 MethodBase remove = ei.GetRemoveMethod (true);
298 attributes = new DllImportAttribute[]{
299 GetDllImportInfo (add), GetDllImportInfo (remove)};
300 methods = new MethodBase[]{add, remove};
301 break;
303 case MemberTypes.Property: {
304 PropertyInfo pi = (PropertyInfo) mi;
305 MethodInfo[] accessors = pi.GetAccessors (true);
306 if (accessors == null)
307 break;
308 attributes = new DllImportAttribute[accessors.Length];
309 methods = new MethodBase [accessors.Length];
310 for (int i = 0; i < accessors.Length; ++i) {
311 attributes [i] = GetDllImportInfo (accessors [i]);
312 methods [i] = accessors [i];
314 break;
317 if (attributes == null || methods == null)
318 return;
320 for (int i = 0; i < attributes.Length; ++i) {
321 if (attributes [i] == null)
322 continue;
323 CheckLibrary (methods [i], attributes [i], report);
327 private static DllImportAttribute GetDllImportInfo (MethodBase method)
329 if (method == null)
330 return null;
332 if ((method.Attributes & MethodAttributes.PinvokeImpl) == 0)
333 return null;
335 // .NET 2.0 synthesizes pseudo-attributes such as DllImport
336 DllImportAttribute dia = (DllImportAttribute) Attribute.GetCustomAttribute (method,
337 typeof(DllImportAttribute), false);
338 if (dia != null)
339 return dia;
341 // We're not on .NET 2.0; assume we're on Mono and use some internal
342 // methods...
343 Type MonoMethod = Type.GetType ("System.Reflection.MonoMethod", false);
344 if (MonoMethod == null) {
345 return null;
347 MethodInfo GetDllImportAttribute =
348 MonoMethod.GetMethod ("GetDllImportAttribute",
349 BindingFlags.Static | BindingFlags.NonPublic);
350 if (GetDllImportAttribute == null) {
351 return null;
353 IntPtr mhandle = method.MethodHandle.Value;
354 return (DllImportAttribute) GetDllImportAttribute.Invoke (null,
355 new object[]{mhandle});
358 private void CheckLibrary (MethodBase method, DllImportAttribute attribute,
359 AssemblyCheckInfo report)
361 string library = attribute.Value;
362 string entrypoint = attribute.EntryPoint;
363 string type = method.DeclaringType.FullName;
364 string mname = method.Name;
366 string found = null;
367 string error = null;
369 Trace.WriteLine ("Trying to load base library: " + library);
371 foreach (string name in GetLibraryNames (method.DeclaringType, library, report)) {
372 if (LoadLibrary (type, mname, name, entrypoint, report, out error)) {
373 found = name;
374 break;
378 if (found == null) {
379 report.Errors.Add (new MessageInfo (
380 type, mname,
381 "Could not load library `" + library + "': " + error));
382 return;
385 // UnixFileInfo f = new UnixFileInfo (soname);
386 if (found.EndsWith (".so")) {
387 report.Warnings.Add (new MessageInfo (type, mname,
388 string.Format ("Library `{0}' might be a development library",
389 found)));
393 [DllImport ("libgmodule-2.0.so")]
394 private static extern IntPtr g_module_open (string filename, int flags);
395 private static int G_MODULE_BIND_LAZY = 1 << 0;
396 private static int G_MODULE_BIND_LOCAL = 1 << 1;
397 // private static int G_MODULE_BIND_MASK = 0x03;
399 [DllImport ("libgmodule-2.0.so")]
400 private static extern int g_module_close (IntPtr handle);
402 [DllImport ("libgmodule-2.0.so")]
403 private static extern IntPtr g_module_error ();
405 [DllImport ("libgmodule-2.0.so")]
406 private static extern IntPtr g_module_name (IntPtr h);
408 [DllImport ("libgmodule-2.0.so")]
409 private static extern IntPtr g_module_build_path (
410 string directory, string module_name);
412 [DllImport ("libgmodule-2.0.so")]
413 private static extern int g_module_symbol (IntPtr module,
414 string symbol_name, out IntPtr symbol);
416 [DllImport ("libglib-2.0.so")]
417 private static extern void g_free (IntPtr mem);
419 private static string[] GetLibraryNames (Type type, string library, AssemblyCheckInfo report)
421 // TODO: keep in sync with
422 // mono/metadata/loader.c:mono_lookup_pinvoke_call
423 ArrayList names = new ArrayList ();
425 string dll_map = report.GetDllmapEntry (type.Assembly.Location, library);
426 if (dll_map != null)
427 names.Add (dll_map);
429 names.Add (library);
430 int _dll_index = library.LastIndexOf (".dll");
431 if (_dll_index >= 0)
432 names.Add (library.Substring (0, _dll_index));
434 if (!library.StartsWith ("lib"))
435 names.Add ("lib" + library);
437 IntPtr s = g_module_build_path (null, library);
438 if (s != IntPtr.Zero) {
439 try {
440 names.Add (Marshal.PtrToStringAnsi (s));
442 finally {
443 g_free (s);
447 s = g_module_build_path (".", library);
448 if (s != IntPtr.Zero) {
449 try {
450 names.Add (Marshal.PtrToStringAnsi (s));
452 finally {
453 g_free (s);
457 return (string[]) names.ToArray (typeof(string));
460 private static bool LoadLibrary (string type, string member,
461 string library, string symbol, AssemblyCheckInfo report, out string error)
463 error = null;
464 IntPtr h = g_module_open (library,
465 G_MODULE_BIND_LAZY | G_MODULE_BIND_LOCAL);
466 try {
467 Trace.WriteLine (" Trying library name: " + library);
468 if (h != IntPtr.Zero) {
469 string soname = Marshal.PtrToStringAnsi (g_module_name (h));
470 Trace.WriteLine ("Able to load library " + library +
471 "; soname=" + soname);
472 IntPtr ignore;
473 if (g_module_symbol (h, symbol, out ignore) == 0)
474 report.Errors.Add (new MessageInfo (
475 type, member,
476 string.Format ("library `{0}' is missing symbol `{1}'",
477 library, symbol)));
478 return true;
480 error = Marshal.PtrToStringAnsi (g_module_error ());
481 Trace.WriteLine ("\tError loading library `" + library + "': " + error);
483 finally {
484 if (h != IntPtr.Zero)
485 g_module_close (h);
487 return false;
491 class Runner {
493 public static void Main (string[] args)
495 var references = new List<string> ();
496 var prefixes = new List<string> ();
498 List<string> files = new OptionSet {
499 { "p|prefix|prefixes=",
500 "Mono installation prefixes (for $prefix/etc/mono/config)",
501 v => prefixes.Add (v) },
502 { "r|reference|references=",
503 "Assemblies to load by partial names (e.g. from the GAC)",
504 v => references.Add (v) },
505 }.Parse (args);
507 AssemblyChecker checker = new AssemblyChecker ();
508 AssemblyCheckInfo report = new AssemblyCheckInfo ();
509 if (prefixes.Count == 0) {
510 // SystemConfigurationFile is $sysconfdir/mono/VERSION/machine.config
511 // We want $sysconfdir
512 DirectoryInfo configDir =
513 new FileInfo (RuntimeEnvironment.SystemConfigurationFile).Directory.Parent.Parent.Parent;
514 prefixes.Add (configDir.ToString ());
516 report.SetInstallationPrefixes (prefixes);
517 foreach (string assembly in files) {
518 checker.CheckFile (assembly, report);
521 foreach (string assembly in references) {
522 checker.CheckWithPartialName (assembly, report);
525 foreach (MessageInfo m in report.Errors) {
526 PrintMessage ("error", m);
529 foreach (MessageInfo m in report.Warnings) {
530 PrintMessage ("warning", m);
534 private static void PrintMessage (string type, MessageInfo m)
536 Console.Write ("{0}: ", type);
537 if (m.Type != null)
538 Console.Write ("in {0}", m.Type);
539 if (m.Member != null)
540 Console.Write (".{0}: ", m.Member);
541 Console.WriteLine (m.Message);