LockTracerDecoder.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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 (global)
  89. domain lock (complex)
  90. domain jit lock (complex)
  91. marshal lock
  92. simple locks
  93. Examples:
  94. You can take the loader lock without holding a domain lock.
  95. You can take the domain load while holding the loader lock
  96. You cannot take the loader lock if only the domain lock is held.
  97. You cannot take a domain lock while holding the lock to another domain.
  98. TODO:
  99. We have a few known ok violation. We need a way to whitelist them.
  100. Known ok issues:
  101. ERROR: tried to acquire lock DomainLock at mono_domain_code_reserve_align while holding DomainLock at mono_class_create_runtime_vtable: Hierarchy violation.
  102. This is triggered when building the vtable of a non-root domain and fetching a vtable trampoline for an offset that has not been built. We'll take the root
  103. domain lock while holding the other one.
  104. This is ok since we never allow locking to have in the other direction, IOW, the root-domain lock is one level down from the other domain-locks.
  105. WARNING: tried to acquire lock ImageDataLock at mono_image_init_name_cache while holding ImageDataLock at mono_class_from_name
  106. WARNING: tried to acquire lock ImageDataLock at mono_image_init_name_cache while holding ImageDataLock at mono_image_add_to_name_cache
  107. Both of those happen when filling up the name_cache, as it needs to alloc image memory.
  108. This one is fixable by spliting mono_image_init_name_cache into a locked and an unlocked variants and calling them appropriatedly.
  109. */
  110. public enum Lock {
  111. Invalid,
  112. LoaderLock,
  113. ImageDataLock,
  114. DomainLock,
  115. DomainAssembliesLock,
  116. DomainJitCodeHashLock,
  117. IcallLock,
  118. AssemblyBindingLock,
  119. MarshalLock,
  120. ClassesLock,
  121. LoaderGlobalDataLock,
  122. ThreadsLock,
  123. }
  124. public class SimLock
  125. {
  126. Lock kind;
  127. int id;
  128. public SimLock (Lock kind, int id) {
  129. this.kind = kind;
  130. this.id = id;
  131. }
  132. static int GetLockOrder (Lock kind) {
  133. switch (kind) {
  134. case Lock.LoaderLock:
  135. return 0;
  136. case Lock.DomainLock:
  137. return 1;
  138. case Lock.DomainJitCodeHashLock:
  139. case Lock.MarshalLock:
  140. return 2;
  141. default:
  142. return 3;
  143. }
  144. }
  145. bool IsParent (SimLock other) {
  146. return GetLockOrder (kind) > GetLockOrder (other.kind);
  147. }
  148. public bool IsSimpleLock {
  149. get { return GetLockOrder (kind) == 3; }
  150. }
  151. public bool IsGlobalLock {
  152. get { return kind == Lock.LoaderLock; }
  153. }
  154. public bool IsResursiveLock {
  155. get { return kind == Lock.LoaderLock || kind == Lock.DomainLock; }
  156. }
  157. /*locked is already owned by the thread, 'this' is the new one*/
  158. bool Compare (SimThread thread, SimLock locked, out bool isWarning, out string msg)
  159. {
  160. isWarning = false;
  161. msg = null;
  162. if (locked != this) {
  163. if (!IsParent (locked)) {
  164. if (IsGlobalLock) { /*acquiring a global lock*/
  165. if (!thread.HoldsLock (this)) { /*does the thread alread hold it?*/
  166. msg = "Acquired a global lock after a regular lock without having it before.";
  167. return false;
  168. }
  169. } else {
  170. msg = "Hierarchy violation.";
  171. return false;
  172. }
  173. }
  174. } else if (IsSimpleLock) {
  175. msg = "Avoid taking simple locks recursively";
  176. isWarning = true;
  177. return false;
  178. }
  179. return true;
  180. }
  181. public bool IsValid (SimThread thread, SimLock locked) {
  182. bool warn;
  183. string msg;
  184. return Compare (thread, locked, out warn, out msg);
  185. }
  186. public bool WarnAbout (SimThread thread, SimLock locked) {
  187. bool warn;
  188. string msg;
  189. Compare (thread, locked, out warn, out msg);
  190. return warn;
  191. }
  192. public string GetWarningMessage (SimThread thread, SimLock locked) {
  193. bool warn;
  194. string msg;
  195. Compare (thread, locked, out warn, out msg);
  196. return warn ? msg : null;
  197. }
  198. public string GetErrorMessage (SimThread thread, SimLock locked) {
  199. bool warn;
  200. string msg;
  201. bool res = Compare (thread, locked, out warn, out msg);
  202. return !res && !warn ? msg : null;
  203. }
  204. public override string ToString () {
  205. switch (kind) {
  206. case Lock.LoaderLock:
  207. case Lock.IcallLock:
  208. case Lock.AssemblyBindingLock:
  209. case Lock.MarshalLock:
  210. case Lock.ClassesLock:
  211. case Lock.LoaderGlobalDataLock:
  212. case Lock.ThreadsLock:
  213. return String.Format ("{0}", kind);
  214. case Lock.ImageDataLock:
  215. case Lock.DomainLock:
  216. case Lock.DomainAssembliesLock:
  217. case Lock.DomainJitCodeHashLock:
  218. return String.Format ("{0}[{1}]", kind, id);
  219. default:
  220. return String.Format ("Unknown({0})[{1}]", kind, id);
  221. }
  222. }
  223. }
  224. public class LockSimulator
  225. {
  226. static Dictionary <int, SimThread> threads = new Dictionary <int, SimThread> ();
  227. static Dictionary <int, SimLock> locks = new Dictionary <int, SimLock> ();
  228. SymbolTable syms;
  229. public LockSimulator (SymbolTable s) { this.syms = s; }
  230. SimLock GetLock (Trace t) {
  231. if (locks.ContainsKey (t.lockPtr))
  232. return locks [t.lockPtr];
  233. else {
  234. return locks [t.lockPtr] = new SimLock (t.lockKind, t.lockPtr);
  235. }
  236. }
  237. SimThread GetThread (Trace t) {
  238. if (threads.ContainsKey (t.thread))
  239. return threads [t.thread];
  240. else
  241. return threads [t.thread] = new SimThread (t.thread);
  242. }
  243. public void PlayBack (IEnumerable<Trace> traces) {
  244. foreach (var t in traces) {
  245. SimThread thread = GetThread (t);
  246. SimLock lk = GetLock (t);
  247. string frame = t.GetUsefullTopTrace (this.syms);
  248. switch (t.record) {
  249. case Record.MustNotHoldAny:
  250. case Record.MustNotHoldOne:
  251. case Record.MustHoldOne:
  252. throw new Exception ("not supported");
  253. case Record.LockAcquired:
  254. thread.Lock (lk, frame);
  255. break;
  256. case Record.LockReleased:
  257. thread.Release (lk, frame);
  258. break;
  259. default:
  260. throw new Exception ("Invalid trace record: "+t.record);
  261. }
  262. }
  263. }
  264. }
  265. public class Trace {
  266. public int thread;
  267. public Record record;
  268. public Lock lockKind;
  269. public int lockPtr;
  270. int[] frames;
  271. static readonly string[] BAD_FRAME_METHODS = new string[] {
  272. "mono_loader_lock",
  273. "mono_loader_unlock",
  274. "mono_image_lock",
  275. "mono_image_unlock",
  276. "mono_icall_lock",
  277. "mono_icall_unlock",
  278. "add_record",
  279. "mono_locks_lock_acquired",
  280. "mono_locks_lock_released",
  281. "mono_threads_lock",
  282. "mono_threads_unlock",
  283. "mono_domain_lock",
  284. "mono_domain_unlock",
  285. };
  286. public Trace (string[] fields) {
  287. thread = fields [0].ParseHex ();
  288. record = (Record)fields [1].ParseDec ();
  289. lockKind = (Lock)fields [2].ParseDec ();
  290. lockPtr = fields [3].ParseHex ();
  291. frames = new int [fields.Length - 4];
  292. for (int i = 0; i < frames.Length; ++i)
  293. frames [i] = fields [i + 4].ParseHex ();
  294. }
  295. public void Dump (SymbolTable table) {
  296. Console.WriteLine ("{0:x} {1} {2} {3:x}", thread, record, lockKind, lockPtr);
  297. for (int i = 0; i < frames.Length; ++i)
  298. Console.WriteLine ("\t{0}", table.Translate (frames [i]));
  299. }
  300. public string GetUsefullTopTrace (SymbolTable syms) {
  301. for (int i = 0; i < frames.Length; ++i) {
  302. string str = syms.Translate (frames [i]);
  303. bool ok = true;
  304. for (int j = 0; j < BAD_FRAME_METHODS.Length; ++j) {
  305. if (str.IndexOf (BAD_FRAME_METHODS [j]) >= 0) {
  306. ok = false;
  307. break;
  308. }
  309. }
  310. if (ok)
  311. return str;
  312. }
  313. return "[unknown]";
  314. }
  315. }
  316. public class Symbol : IComparable<Symbol>
  317. {
  318. public int offset;
  319. public int size;
  320. public string name;
  321. public Symbol (int o, int size, string n) {
  322. this.offset = o;
  323. this.size = size;
  324. this.name = n;
  325. }
  326. public int CompareTo(Symbol other) {
  327. return offset - other.offset;
  328. }
  329. public void AdjustSize (Symbol next) {
  330. size = next.offset - this.offset;
  331. }
  332. }
  333. public interface SymbolTable {
  334. string Translate (int offset);
  335. }
  336. public class OsxSymbolTable : SymbolTable
  337. {
  338. Symbol[] table;
  339. const int MAX_FUNC_SIZE = 0x20000;
  340. public OsxSymbolTable (string binary) {
  341. Load (binary);
  342. }
  343. void Load (string binary) {
  344. ProcessStartInfo psi = new ProcessStartInfo ("gobjdump", "-t "+binary);
  345. psi.UseShellExecute = false;
  346. psi.RedirectStandardOutput = true;
  347. var proc = Process.Start (psi);
  348. var list = new List<Symbol> ();
  349. string line;
  350. while ((line = proc.StandardOutput.ReadLine ()) != null) {
  351. string[] fields = line.Split(new char[] {' ', '\t'}, StringSplitOptions.RemoveEmptyEntries);
  352. if (fields.Length < 7)
  353. continue;
  354. if (!fields [3].Equals ("FUN"))
  355. continue;
  356. int offset = fields [0].ParseHex ();
  357. string name = fields [6];
  358. if (name.StartsWith ("_"))
  359. name = name.Substring (1);
  360. if (offset != 0)
  361. list.Add (new Symbol (offset, 0, name));
  362. }
  363. table = new Symbol [list.Count];
  364. list.CopyTo (table, 0);
  365. Array.Sort (table);
  366. for (int i = 1; i < table.Length; ++i) {
  367. table [i - 1].AdjustSize (table [i]);
  368. }
  369. }
  370. public string Translate (int offset) {
  371. Symbol sym = null;
  372. int res = Array.BinarySearch (table, new Symbol (offset, 0, null));
  373. if (res >= 0)
  374. return table [res].name;
  375. res = ~res;
  376. if (res >= table.Length)
  377. sym = table [table.Length - 1];
  378. else if (res != 0)
  379. sym = table [res - 1];
  380. if (sym != null) {
  381. int size = Math.Max (sym.size, 10);
  382. if (offset - sym.offset < size)
  383. return sym.name;
  384. }
  385. return String.Format ("[{0:x}]", offset);
  386. }
  387. }
  388. public class LinuxSymbolTable : SymbolTable
  389. {
  390. Symbol[] table;
  391. const int MAX_FUNC_SIZE = 0x20000;
  392. public LinuxSymbolTable (string binary) {
  393. Load (binary);
  394. }
  395. void Load (string binary) {
  396. ProcessStartInfo psi = new ProcessStartInfo ("objdump", "-t "+binary);
  397. psi.UseShellExecute = false;
  398. psi.RedirectStandardOutput = true;
  399. var proc = Process.Start (psi);
  400. var list = new List<Symbol> ();
  401. string line;
  402. while ((line = proc.StandardOutput.ReadLine ()) != null) {
  403. string[] fields = line.Split(new char[] {' ', '\t'}, StringSplitOptions.RemoveEmptyEntries);
  404. if (fields.Length < 6)
  405. continue;
  406. if (fields [3] != ".text" || fields [2] != "F")
  407. continue;
  408. int offset = fields [0].ParseHex ();
  409. int size = fields [4].ParseHex ();
  410. string name = fields [fields.Length - 1];
  411. if (offset != 0)
  412. list.Add (new Symbol (offset, size, name));
  413. }
  414. table = new Symbol [list.Count];
  415. list.CopyTo (table, 0);
  416. Array.Sort (table);
  417. }
  418. public string Translate (int offset) {
  419. Symbol sym = null;
  420. int res = Array.BinarySearch (table, new Symbol (offset, 0, null));
  421. if (res >= 0)
  422. return table [res].name;
  423. res = ~res;
  424. if (res >= table.Length)
  425. sym = table [table.Length - 1];
  426. else if (res != 0)
  427. sym = table [res - 1];
  428. if (sym != null && offset - sym.offset < MAX_FUNC_SIZE)
  429. return sym.name;
  430. return String.Format ("[{0:x}]", offset);
  431. }
  432. }
  433. public class TraceDecoder
  434. {
  435. string file;
  436. public TraceDecoder (string file) {
  437. this.file = file;
  438. }
  439. public IEnumerable<Trace> GetTraces () {
  440. using (StreamReader reader = new StreamReader (file)) {
  441. string line;
  442. while ((line = reader.ReadLine ()) != null) {
  443. string[] fields = line.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
  444. if (fields.Length >= 7) {
  445. yield return new Trace (fields);
  446. }
  447. }
  448. }
  449. }
  450. }
  451. public class Driver
  452. {
  453. [DllImport ("libc")]
  454. static extern int uname (IntPtr buf);
  455. static bool IsOSX ()
  456. {
  457. bool isOsx = false;
  458. IntPtr buf = Marshal.AllocHGlobal (8192);
  459. if (uname (buf) == 0) {
  460. string os = Marshal.PtrToStringAnsi (buf);
  461. isOsx = os == "Darwin";
  462. }
  463. Marshal.FreeHGlobal (buf);
  464. return isOsx;
  465. }
  466. static void Main (string[] args) {
  467. SymbolTable syms;
  468. if (args.Length != 2) {
  469. Console.WriteLine ("usage: LockTracerDecoder.exe /path/to/mono /path/to/locks.pid");
  470. return;
  471. }
  472. if (IsOSX ())
  473. syms = new OsxSymbolTable (args [0]);
  474. else
  475. syms = new LinuxSymbolTable (args [0]);
  476. var decoder = new TraceDecoder (args [1]);
  477. var sim = new LockSimulator (syms);
  478. sim.PlayBack (decoder.GetTraces ());
  479. }
  480. }
  481. public static class Utils
  482. {
  483. public static int ParseHex (this string number) {
  484. while (number.Length > 1 && (number [0] == '0' || number [0] == 'x' || number [0] == 'X'))
  485. number = number.Substring (1);
  486. return int.Parse (number, NumberStyles.HexNumber);
  487. }
  488. public static int ParseDec (this string number) {
  489. while (number.Length > 1 && number [0] == '0')
  490. number = number.Substring (1);
  491. return int.Parse (number);
  492. }
  493. }