LockTracerDecoder.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Globalization;
  6. using System.Runtime.InteropServices;
  7. public enum Record {
  8. MustNotHoldAny,
  9. MustNotHoldOne,
  10. MustHoldOne,
  11. LockAcquired,
  12. LockReleased
  13. }
  14. public struct LockRecord {
  15. public SimLock lk;
  16. public string frame;
  17. public LockRecord (SimLock lk, string frame) {
  18. this.lk = lk;
  19. this.frame = frame;
  20. }
  21. }
  22. public class SimThread
  23. {
  24. int thread;
  25. List <LockRecord> locks = new List <LockRecord> ();
  26. public SimThread (int t)
  27. {
  28. this.thread = t;
  29. }
  30. public bool HoldsLock (SimLock lk) {
  31. foreach (var l in locks) {
  32. if (l.lk == lk)
  33. return true;
  34. }
  35. return false;
  36. }
  37. public int HoldCount (SimLock lk) {
  38. int res = 0;
  39. foreach (var l in locks)
  40. if (l.lk == lk)
  41. ++res;
  42. return res;
  43. }
  44. public void Lock (SimLock lk, string frame) {
  45. foreach (LockRecord lr in locks) {
  46. if (lk.WarnAbout (this, lr.lk))
  47. Console.WriteLine ("WARNING: tried to acquire lock {0} at {1} while holding {2} at {3}: {4}", lk, frame, lr.lk, lr.frame, lk.GetWarningMessage (this, lr.lk));
  48. else if (!lk.IsValid (this, lr.lk))
  49. Console.WriteLine ("ERROR: tried to acquire lock {0} at {1} while holding {2} at {3}: {4}", lk, frame, lr.lk, lr.frame, lk.GetErrorMessage (this, lr.lk));
  50. }
  51. locks.Add (new LockRecord (lk, frame));
  52. }
  53. public void Release (SimLock lk, string frame) {
  54. if (locks.Count == 0) {
  55. Console.WriteLine ("ERROR: released lock {0} at {1} while holding no locks!", lk, frame);
  56. return;
  57. }
  58. LockRecord top = locks [locks.Count - 1];
  59. if (top.lk != lk && !(lk.IsGlobalLock && HoldCount (lk) > 1)) {
  60. Console.WriteLine ("WARNING: released lock {0} at {1} out of order with {2} at {3}!", lk, frame, top.lk, top.frame);
  61. }
  62. for (int i = locks.Count -1; i >= 0; --i) {
  63. if (locks [i].lk == lk) {
  64. locks.RemoveAt (i);
  65. break;
  66. }
  67. }
  68. }
  69. }
  70. /*
  71. LOCK RULES
  72. Simple locks:
  73. Can be acquired at any point regardless of which locks are taken or not.
  74. No other locks can be acquired or released while holding a simple lock.
  75. Reentrancy is not recomended. (warning)
  76. Simple locks are leaf locks on the lock lattice.
  77. Complex locks:
  78. Must respect locking order, which form a lattice.
  79. IOW, to take a given lock, only it's parents might have been taken.
  80. Reentrancy is ok.
  81. Locks around resources count as separate instances of the hierarchy.
  82. Global locks:
  83. Must respect locking order.
  84. Must be the at the botton of the locking lattice.
  85. Can be taken out-of-order by other locks given that it was previously acquired.
  86. Adding global locks is not to be taken lightly.
  87. The current lock hierarchy:
  88. loader lock
  89. domain lock
  90. domain jit lock
  91. simple locks
  92. Examples:
  93. You can take the loader lock without holding a domain lock.
  94. You cannot take a domain lock if the loader lock is held.
  95. You cannot take a domain lock while holding the lock to another domain.
  96. */
  97. public enum Lock {
  98. Invalid,
  99. LoaderLock,
  100. ImageDataLock,
  101. DomainLock,
  102. DomainAssembliesLock,
  103. DomainJitCodeHashLock,
  104. }
  105. public class SimLock
  106. {
  107. Lock kind;
  108. int id;
  109. public SimLock (Lock kind, int id) {
  110. this.kind = kind;
  111. this.id = id;
  112. }
  113. static int GetLockOrder (Lock kind) {
  114. switch (kind) {
  115. case Lock.LoaderLock:
  116. return 0;
  117. case Lock.DomainLock:
  118. return 1;
  119. case Lock.DomainJitCodeHashLock:
  120. return 2;
  121. default:
  122. return 3;
  123. }
  124. }
  125. bool IsParent (SimLock other) {
  126. return GetLockOrder (kind) > GetLockOrder (other.kind);
  127. }
  128. public bool IsSimpleLock {
  129. get { return GetLockOrder (kind) == 3; }
  130. }
  131. public bool IsGlobalLock {
  132. get { return kind == Lock.LoaderLock; }
  133. }
  134. /*locked is already owned by the thread, 'this' is the new one*/
  135. bool Compare (SimThread thread, SimLock locked, out bool isWarning, out string msg)
  136. {
  137. isWarning = false;
  138. msg = null;
  139. if (locked != this) {
  140. if (!IsParent (locked)) {
  141. if (IsGlobalLock) { /*acquiring a global lock*/
  142. if (!thread.HoldsLock (this)) { /*does the thread alread hold it?*/
  143. msg = "Acquired a global lock after a regular lock without having it before.";
  144. return false;
  145. }
  146. } else {
  147. msg = "Hierarchy violation.";
  148. return false;
  149. }
  150. }
  151. } else if (IsSimpleLock) {
  152. msg = "Avoid taking simple locks recursively";
  153. isWarning = true;
  154. return false;
  155. }
  156. return true;
  157. }
  158. public bool IsValid (SimThread thread, SimLock locked) {
  159. bool warn;
  160. string msg;
  161. return Compare (thread, locked, out warn, out msg);
  162. }
  163. public bool WarnAbout (SimThread thread, SimLock locked) {
  164. bool warn;
  165. string msg;
  166. Compare (thread, locked, out warn, out msg);
  167. return warn;
  168. }
  169. public string GetWarningMessage (SimThread thread, SimLock locked) {
  170. bool warn;
  171. string msg;
  172. Compare (thread, locked, out warn, out msg);
  173. return warn ? msg : null;
  174. }
  175. public string GetErrorMessage (SimThread thread, SimLock locked) {
  176. bool warn;
  177. string msg;
  178. bool res = Compare (thread, locked, out warn, out msg);
  179. return !res && !warn ? msg : null;
  180. }
  181. public override string ToString () {
  182. return String.Format ("{0}", kind);
  183. }
  184. }
  185. public class LockSimulator
  186. {
  187. static Dictionary <int, SimThread> threads = new Dictionary <int, SimThread> ();
  188. static Dictionary <int, SimLock> locks = new Dictionary <int, SimLock> ();
  189. SymbolTable syms;
  190. public LockSimulator (SymbolTable s) { this.syms = s; }
  191. SimLock GetLock (Trace t) {
  192. if (locks.ContainsKey (t.lockPtr))
  193. return locks [t.lockPtr];
  194. else {
  195. return locks [t.lockPtr] = new SimLock (t.lockKind, t.lockPtr);
  196. }
  197. }
  198. SimThread GetThread (Trace t) {
  199. if (threads.ContainsKey (t.thread))
  200. return threads [t.thread];
  201. else
  202. return threads [t.thread] = new SimThread (t.thread);
  203. }
  204. public void PlayBack (IEnumerable<Trace> traces) {
  205. foreach (var t in traces) {
  206. SimThread thread = GetThread (t);
  207. SimLock lk = GetLock (t);
  208. string frame = t.GetUsefullTopTrace (this.syms);
  209. switch (t.record) {
  210. case Record.MustNotHoldAny:
  211. case Record.MustNotHoldOne:
  212. case Record.MustHoldOne:
  213. throw new Exception ("not supported");
  214. case Record.LockAcquired:
  215. thread.Lock (lk, frame);
  216. break;
  217. case Record.LockReleased:
  218. thread.Release (lk, frame);
  219. break;
  220. default:
  221. throw new Exception ("Invalid trace record: "+t.record);
  222. }
  223. }
  224. }
  225. }
  226. public class Trace {
  227. public int thread;
  228. public Record record;
  229. public Lock lockKind;
  230. public int lockPtr;
  231. int[] frames;
  232. static readonly string[] BAD_FRAME_METHODS = new string[] {
  233. "mono_loader_lock",
  234. "mono_loader_unlock",
  235. "mono_image_lock",
  236. "mono_image_unlock",
  237. };
  238. public Trace (string[] fields) {
  239. thread = fields [0].ParseHex ();
  240. record = (Record)fields [1].ParseDec ();
  241. lockKind = (Lock)fields [2].ParseDec ();
  242. lockPtr = fields [3].ParseHex ();
  243. frames = new int [fields.Length - 4];
  244. for (int i = 0; i < frames.Length; ++i)
  245. frames [i] = fields [i + 4].ParseHex ();
  246. }
  247. public void Dump (SymbolTable table) {
  248. Console.WriteLine ("{0:x} {1} {2} {3:x}", thread, record, lockKind, lockPtr);
  249. for (int i = 0; i < frames.Length; ++i)
  250. Console.WriteLine ("\t{0}", table.Translate (frames [i]));
  251. }
  252. public string GetUsefullTopTrace (SymbolTable syms) {
  253. for (int i = 0; i < frames.Length; ++i) {
  254. string str = syms.Translate (frames [i]);
  255. bool ok = true;
  256. for (int j = 0; j < BAD_FRAME_METHODS.Length; ++j) {
  257. if (str.IndexOf (BAD_FRAME_METHODS [j]) >= 0) {
  258. ok = false;
  259. break;
  260. }
  261. }
  262. if (ok)
  263. return str;
  264. }
  265. return "[unknown]";
  266. }
  267. }
  268. public class Symbol : IComparable<Symbol>
  269. {
  270. public int offset;
  271. public int size;
  272. public string name;
  273. public Symbol (int o, int size, string n) {
  274. this.offset = o;
  275. this.size = size;
  276. this.name = n;
  277. }
  278. public int CompareTo(Symbol other) {
  279. return offset - other.offset;
  280. }
  281. }
  282. public interface SymbolTable {
  283. string Translate (int offset);
  284. }
  285. public class OsxSymbolTable : SymbolTable
  286. {
  287. Symbol[] table;
  288. const int MAX_FUNC_SIZE = 0x20000;
  289. public OsxSymbolTable (string binary) {
  290. Load (binary);
  291. }
  292. void Load (string binary) {
  293. ProcessStartInfo psi = new ProcessStartInfo ("gobjdump", "-t "+binary);
  294. psi.UseShellExecute = false;
  295. psi.RedirectStandardOutput = true;
  296. var proc = Process.Start (psi);
  297. var list = new List<Symbol> ();
  298. string line;
  299. while ((line = proc.StandardOutput.ReadLine ()) != null) {
  300. string[] fields = line.Split(new char[] {' ', '\t'}, StringSplitOptions.RemoveEmptyEntries);
  301. if (fields.Length < 4)
  302. continue;
  303. if (!(fields [1].Equals ("g") || fields [1].Equals ("d")))
  304. continue;
  305. if (!fields [2].Equals ("*UND*"))
  306. continue;
  307. int offset = fields [0].ParseHex ();
  308. string name = fields [3];
  309. if (offset != 0)
  310. list.Add (new Symbol (offset, 0, name));
  311. }
  312. table = new Symbol [list.Count];
  313. list.CopyTo (table, 0);
  314. Array.Sort (table);
  315. }
  316. public string Translate (int offset) {
  317. Symbol sym = null;
  318. int res = Array.BinarySearch (table, new Symbol (offset, 0, null));
  319. if (res >= 0)
  320. return table [res].name;
  321. res = ~res;
  322. if (res >= table.Length)
  323. sym = table [table.Length - 1];
  324. else if (res != 0)
  325. sym = table [res - 1];
  326. if (sym != null) {
  327. int size = Math.Max (sym.size, 10);
  328. if (offset - sym.offset < size)
  329. return sym.name;
  330. }
  331. return String.Format ("[{0:x}]", offset);
  332. }
  333. }
  334. public class LinuxSymbolTable : SymbolTable
  335. {
  336. Symbol[] table;
  337. const int MAX_FUNC_SIZE = 0x20000;
  338. public LinuxSymbolTable (string binary) {
  339. Load (binary);
  340. }
  341. void Load (string binary) {
  342. ProcessStartInfo psi = new ProcessStartInfo ("objdump", "-t "+binary);
  343. psi.UseShellExecute = false;
  344. psi.RedirectStandardOutput = true;
  345. var proc = Process.Start (psi);
  346. var list = new List<Symbol> ();
  347. string line;
  348. while ((line = proc.StandardOutput.ReadLine ()) != null) {
  349. string[] fields = line.Split(new char[] {' ', '\t'}, StringSplitOptions.RemoveEmptyEntries);
  350. if (fields.Length < 6)
  351. continue;
  352. if (fields [3] != ".text" || fields [2] != "F")
  353. continue;
  354. int offset = fields [0].ParseHex ();
  355. int size = fields [4].ParseHex ();
  356. string name = fields [fields.Length - 1];
  357. if (offset != 0)
  358. list.Add (new Symbol (offset, size, name));
  359. }
  360. table = new Symbol [list.Count];
  361. list.CopyTo (table, 0);
  362. Array.Sort (table);
  363. }
  364. public string Translate (int offset) {
  365. Symbol sym = null;
  366. int res = Array.BinarySearch (table, new Symbol (offset, 0, null));
  367. if (res >= 0)
  368. return table [res].name;
  369. res = ~res;
  370. if (res >= table.Length)
  371. sym = table [table.Length - 1];
  372. else if (res != 0)
  373. sym = table [res - 1];
  374. if (sym != null && offset - sym.offset < MAX_FUNC_SIZE)
  375. return sym.name;
  376. return String.Format ("[{0:x}]", offset);
  377. }
  378. }
  379. public class TraceDecoder
  380. {
  381. string file;
  382. public TraceDecoder (string file) {
  383. this.file = file;
  384. }
  385. public IEnumerable<Trace> GetTraces () {
  386. using (StreamReader reader = new StreamReader (file)) {
  387. string line;
  388. while ((line = reader.ReadLine ()) != null) {
  389. string[] fields = line.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
  390. if (fields.Length >= 7) {
  391. yield return new Trace (fields);
  392. }
  393. }
  394. }
  395. }
  396. }
  397. public class Driver
  398. {
  399. [DllImport ("libc")]
  400. static extern int uname (IntPtr buf);
  401. static bool IsOSX ()
  402. {
  403. bool isOsx = false;
  404. IntPtr buf = Marshal.AllocHGlobal (8192);
  405. if (uname (buf) == 0) {
  406. string os = Marshal.PtrToStringAnsi (buf);
  407. isOsx = os == "Darwin";
  408. }
  409. Marshal.FreeHGlobal (buf);
  410. return isOsx;
  411. }
  412. static void Main (string[] args) {
  413. SymbolTable syms;
  414. if (args.Length != 2) {
  415. Console.WriteLine ("usage: LockTracerDecoder.exe /path/to/mono /path/to/locks.pid");
  416. return;
  417. }
  418. if (IsOSX ())
  419. syms = new OsxSymbolTable (args [0]);
  420. else
  421. syms = new LinuxSymbolTable (args [0]);
  422. var decoder = new TraceDecoder (args [1]);
  423. var sim = new LockSimulator (syms);
  424. sim.PlayBack (decoder.GetTraces ());
  425. }
  426. }
  427. public static class Utils
  428. {
  429. public static int ParseHex (this string number) {
  430. while (number.Length > 1 && (number [0] == '0' || number [0] == 'x' || number [0] == 'X'))
  431. number = number.Substring (1);
  432. return int.Parse (number, NumberStyles.HexNumber);
  433. }
  434. public static int ParseDec (this string number) {
  435. while (number.Length > 1 && number [0] == '0')
  436. number = number.Substring (1);
  437. return int.Parse (number);
  438. }
  439. }