DebugService.cs 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. using ILRuntime.CLR.Method;
  8. using ILRuntime.Runtime.Intepreter;
  9. using ILRuntime.Runtime.Stack;
  10. using ILRuntime.CLR.Utils;
  11. namespace ILRuntime.Runtime.Debugger
  12. {
  13. public class DebugService
  14. {
  15. BreakPointContext curBreakpoint;
  16. DebuggerServer server;
  17. Runtime.Enviorment.AppDomain domain;
  18. Dictionary<int, LinkedList<BreakpointInfo>> activeBreakpoints = new Dictionary<int, LinkedList<BreakpointInfo>>();
  19. Dictionary<int, BreakpointInfo> breakpointMapping = new Dictionary<int, BreakpointInfo>();
  20. Queue<KeyValuePair<int, VariableReference>> pendingReferences = new Queue<KeyValuePair<int, VariableReference>>();
  21. Queue<KeyValuePair<int, VariableReference>> pendingEnuming = new Queue<KeyValuePair<int, VariableReference>>();
  22. Queue<KeyValuePair<int, KeyValuePair<VariableReference, VariableReference>>> pendingIndexing = new Queue<KeyValuePair<int, KeyValuePair<VariableReference, VariableReference>>>();
  23. AutoResetEvent evt = new AutoResetEvent(false);
  24. public Action<string> OnBreakPoint;
  25. public Enviorment.AppDomain AppDomain { get { return domain; } }
  26. public AutoResetEvent BlockEvent { get { return evt; } }
  27. public bool IsDebuggerAttached
  28. {
  29. get
  30. {
  31. #if DEBUG && !DISABLE_ILRUNTIME_DEBUG
  32. return (server != null && server.IsAttached);
  33. #else
  34. return false;
  35. #endif
  36. }
  37. }
  38. public DebugService(Runtime.Enviorment.AppDomain domain)
  39. {
  40. this.domain = domain;
  41. }
  42. /// <summary>
  43. /// Start Debugger Server
  44. /// </summary>
  45. /// <param name="port">Port to listen on</param>
  46. public void StartDebugService(int port)
  47. {
  48. #if DEBUG && !DISABLE_ILRUNTIME_DEBUG
  49. server = new Debugger.DebuggerServer(this);
  50. server.Port = port;
  51. server.Start();
  52. #endif
  53. }
  54. /// <summary>
  55. /// Stop Debugger Server
  56. /// </summary>
  57. public void StopDebugService()
  58. {
  59. #if DEBUG && !DISABLE_ILRUNTIME_DEBUG
  60. server.Stop();
  61. server = null;
  62. #endif
  63. }
  64. /// <summary>
  65. /// 中断运行
  66. /// </summary>
  67. /// <param name="intpreter"></param>
  68. /// <param name="ex"></param>
  69. /// <returns>如果挂的有调试器则返回true</returns>
  70. internal bool Break(ILIntepreter intpreter, Exception ex = null)
  71. {
  72. BreakPointContext ctx = new BreakPointContext();
  73. ctx.Interpreter = intpreter;
  74. ctx.Exception = ex;
  75. curBreakpoint = ctx;
  76. if (OnBreakPoint != null)
  77. {
  78. OnBreakPoint(ctx.DumpContext());
  79. return true;
  80. }
  81. return false;
  82. }
  83. public string GetStackTrace(ILIntepreter intepreper)
  84. {
  85. StringBuilder sb = new StringBuilder();
  86. ILRuntime.CLR.Method.ILMethod m;
  87. StackFrame[] frames = intepreper.Stack.Frames.ToArray();
  88. Mono.Cecil.Cil.Instruction ins = null;
  89. if (frames[0].Address != null)
  90. {
  91. ins = frames[0].Method.Definition.Body.Instructions[frames[0].Address.Value];
  92. sb.AppendLine(ins.ToString());
  93. }
  94. for (int i = 0; i < frames.Length; i++)
  95. {
  96. var f = frames[i];
  97. m = f.Method;
  98. string document = "";
  99. if (f.Address != null)
  100. {
  101. ins = m.Definition.Body.Instructions[f.Address.Value];
  102. var seq = FindSequencePoint(ins, m.Definition.DebugInformation.GetSequencePointMapping());
  103. if (seq != null)
  104. {
  105. string path = seq.Document.Url.Replace("\\", "/");
  106. document = string.Format("(at {0}:{1})", path, seq.StartLine);
  107. }
  108. }
  109. sb.AppendFormat("at {0} {1}\r\n", m, document);
  110. }
  111. return sb.ToString();
  112. }
  113. public unsafe string GetThisInfo(ILIntepreter intepreter)
  114. {
  115. var topFrame = intepreter.Stack.Frames.Peek();
  116. var arg = Minus(topFrame.LocalVarPointer, topFrame.Method.ParameterCount);
  117. if (topFrame.Method.HasThis)
  118. arg--;
  119. if (arg->ObjectType == ObjectTypes.StackObjectReference)
  120. {
  121. var addr = *(long*)&arg->Value;
  122. arg = (StackObject*)addr;
  123. }
  124. ILTypeInstance instance = arg->ObjectType != ObjectTypes.Null ? intepreter.Stack.ManagedStack[arg->Value] as ILTypeInstance : null;
  125. if (instance == null)
  126. return "null";
  127. var fields = instance.Type.TypeDefinition.Fields;
  128. int idx = 0;
  129. StringBuilder sb = new StringBuilder();
  130. for (int i = 0; i < fields.Count; i++)
  131. {
  132. try
  133. {
  134. var f = fields[i];
  135. if (f.IsStatic)
  136. continue;
  137. var field = instance.Fields[idx];
  138. var v = StackObject.ToObject(&field, intepreter.AppDomain, instance.ManagedObjects);
  139. if (v == null)
  140. v = "null";
  141. string name = f.Name;
  142. sb.AppendFormat("{0} {1} = {2}", f.FieldType.Name, name, v);
  143. if ((idx % 3 == 0 && idx != 0) || idx == instance.Fields.Length - 1)
  144. sb.AppendLine();
  145. else
  146. sb.Append(", ");
  147. idx++;
  148. }
  149. catch
  150. {
  151. }
  152. }
  153. return sb.ToString();
  154. }
  155. public unsafe string GetLocalVariableInfo(ILIntepreter intepreter)
  156. {
  157. StackFrame topFrame = intepreter.Stack.Frames.Peek();
  158. var m = topFrame.Method;
  159. StringBuilder sb = new StringBuilder();
  160. for (int i = 0; i < m.LocalVariableCount; i++)
  161. {
  162. try
  163. {
  164. var lv = m.Definition.Body.Variables[i];
  165. var val = Add(topFrame.LocalVarPointer, i);
  166. var v = StackObject.ToObject(val, intepreter.AppDomain, intepreter.Stack.ManagedStack);
  167. if (v == null)
  168. v = "null";
  169. string vName = null;
  170. m.Definition.DebugInformation.TryGetName(lv, out vName);
  171. string name = string.IsNullOrEmpty(vName) ? "v" + lv.Index : vName;
  172. sb.AppendFormat("{0} {1} = {2}", lv.VariableType.Name, name, v);
  173. if ((i % 3 == 0 && i != 0) || i == m.LocalVariableCount - 1)
  174. sb.AppendLine();
  175. else
  176. sb.Append(", ");
  177. }
  178. catch
  179. {
  180. }
  181. }
  182. return sb.ToString();
  183. }
  184. internal static Mono.Cecil.Cil.SequencePoint FindSequencePoint(Mono.Cecil.Cil.Instruction ins, IDictionary<Mono.Cecil.Cil.Instruction, Mono.Cecil.Cil.SequencePoint> seqMapping)
  185. {
  186. Mono.Cecil.Cil.Instruction cur = ins;
  187. Mono.Cecil.Cil.SequencePoint sp;
  188. while (!seqMapping.TryGetValue(cur, out sp) && cur.Previous != null)
  189. cur = cur.Previous;
  190. return sp;
  191. }
  192. unsafe StackObject* Add(StackObject* a, int b)
  193. {
  194. return (StackObject*)((long)a + sizeof(StackObject) * b);
  195. }
  196. unsafe StackObject* Minus(StackObject* a, int b)
  197. {
  198. return (StackObject*)((long)a - sizeof(StackObject) * b);
  199. }
  200. internal void NotifyModuleLoaded(string moduleName)
  201. {
  202. if (server != null && server.IsAttached)
  203. server.NotifyModuleLoaded(moduleName);
  204. }
  205. internal void SetBreakPoint(int methodHash, int bpHash, int startLine)
  206. {
  207. lock (activeBreakpoints)
  208. {
  209. LinkedList<BreakpointInfo> lst;
  210. if(!activeBreakpoints.TryGetValue(methodHash, out lst))
  211. {
  212. lst = new LinkedList<Debugger.BreakpointInfo>();
  213. activeBreakpoints[methodHash] = lst;
  214. }
  215. BreakpointInfo bpInfo = new BreakpointInfo();
  216. bpInfo.BreakpointHashCode = bpHash;
  217. bpInfo.MethodHashCode = methodHash;
  218. bpInfo.StartLine = startLine;
  219. lst.AddLast(bpInfo);
  220. breakpointMapping[bpHash] = bpInfo;
  221. }
  222. }
  223. internal void DeleteBreakpoint(int bpHash)
  224. {
  225. lock (activeBreakpoints)
  226. {
  227. BreakpointInfo bpInfo;
  228. if (breakpointMapping.TryGetValue(bpHash, out bpInfo))
  229. {
  230. LinkedList<BreakpointInfo> lst;
  231. if(activeBreakpoints.TryGetValue(bpInfo.MethodHashCode, out lst))
  232. {
  233. lst.Remove(bpInfo);
  234. }
  235. breakpointMapping.Remove(bpHash);
  236. }
  237. }
  238. }
  239. internal void ExecuteThread(int threadHash)
  240. {
  241. lock (AppDomain.FreeIntepreters)
  242. {
  243. foreach(var i in AppDomain.Intepreters)
  244. {
  245. //We should resume all threads on execute
  246. i.Value.ClearDebugState();
  247. i.Value.Resume();
  248. }
  249. }
  250. }
  251. internal unsafe void StepThread(int threadHash, StepTypes type)
  252. {
  253. lock (AppDomain.FreeIntepreters)
  254. {
  255. ILIntepreter intp;
  256. if(AppDomain.Intepreters.TryGetValue(threadHash, out intp))
  257. {
  258. intp.ClearDebugState();
  259. intp.CurrentStepType = type;
  260. intp.LastStepFrameBase = intp.Stack.Frames.Count > 0 ? intp.Stack.Frames.Peek().BasePointer : (StackObject*)0;
  261. intp.LastStepInstructionIndex = intp.Stack.Frames.Count > 0 ? intp.Stack.Frames.Peek().Address.Value : 0;
  262. intp.Resume();
  263. }
  264. }
  265. }
  266. unsafe internal void CheckShouldBreak(ILMethod method, ILIntepreter intp, int ip)
  267. {
  268. if (server != null && server.IsAttached)
  269. {
  270. int methodHash = method.GetHashCode();
  271. BreakpointInfo[] lst = null;
  272. lock (activeBreakpoints)
  273. {
  274. LinkedList<BreakpointInfo> bps;
  275. if (activeBreakpoints.TryGetValue(methodHash, out bps))
  276. lst = bps.ToArray();
  277. }
  278. bool bpHit = false;
  279. if (lst != null)
  280. {
  281. var sp = method.Definition.DebugInformation.GetSequencePoint(method.Definition.Body.Instructions[ip]);
  282. if (sp != null)
  283. {
  284. foreach (var i in lst)
  285. {
  286. if ((i.StartLine + 1) == sp.StartLine)
  287. {
  288. DoBreak(intp, i.BreakpointHashCode, false);
  289. bpHit = true;
  290. break;
  291. }
  292. }
  293. }
  294. }
  295. if (!bpHit)
  296. {
  297. var sp = method.Definition.DebugInformation.GetSequencePoint(method.Definition.Body.Instructions[ip]);//.SequencePoint;
  298. if (sp != null && IsSequenceValid(sp))
  299. {
  300. switch (intp.CurrentStepType)
  301. {
  302. case StepTypes.Into:
  303. DoBreak(intp, 0, true);
  304. break;
  305. case StepTypes.Over:
  306. if (intp.Stack.Frames.Peek().BasePointer <= intp.LastStepFrameBase && ip != intp.LastStepInstructionIndex)
  307. {
  308. DoBreak(intp, 0, true);
  309. }
  310. break;
  311. case StepTypes.Out:
  312. {
  313. if (intp.Stack.Frames.Count > 0 && intp.Stack.Frames.Peek().BasePointer < intp.LastStepFrameBase)
  314. {
  315. DoBreak(intp, 0, true);
  316. }
  317. }
  318. break;
  319. }
  320. }
  321. }
  322. }
  323. }
  324. bool IsSequenceValid(Mono.Cecil.Cil.SequencePoint sp)
  325. {
  326. return sp.StartLine != sp.EndLine || sp.StartColumn != sp.EndColumn;
  327. }
  328. void DoBreak(ILIntepreter intp, int bpHash, bool isStep)
  329. {
  330. KeyValuePair<int, StackFrameInfo[]>[] frames = new KeyValuePair<int, StackFrameInfo[]>[AppDomain.Intepreters.Count];
  331. frames[0] = new KeyValuePair<int, StackFrameInfo[]>(intp.GetHashCode(), GetStackFrameInfo(intp));
  332. int idx = 1;
  333. foreach (var j in AppDomain.Intepreters)
  334. {
  335. if (j.Value != intp)
  336. {
  337. j.Value.ShouldBreak = true;
  338. try
  339. {
  340. frames[idx++] = new KeyValuePair<int, Debugger.StackFrameInfo[]>(j.Value.GetHashCode(), GetStackFrameInfo(j.Value));
  341. }
  342. catch
  343. {
  344. frames[idx++] = new KeyValuePair<int, Debugger.StackFrameInfo[]>(j.Value.GetHashCode(), new StackFrameInfo[0]);
  345. }
  346. }
  347. }
  348. if (!isStep)
  349. server.SendSCBreakpointHit(intp.GetHashCode(), bpHash, frames);
  350. else
  351. server.SendSCStepComplete(intp.GetHashCode(), frames);
  352. //Breakpoint hit
  353. intp.Break();
  354. }
  355. unsafe StackFrameInfo[] GetStackFrameInfo(ILIntepreter intp)
  356. {
  357. StackFrame[] frames = intp.Stack.Frames.ToArray();
  358. Mono.Cecil.Cil.Instruction ins = null;
  359. ILMethod m;
  360. List<StackFrameInfo> frameInfos = new List<StackFrameInfo>();
  361. for (int j = 0; j < frames.Length; j++)
  362. {
  363. StackFrameInfo info = new Debugger.StackFrameInfo();
  364. var f = frames[j];
  365. m = f.Method;
  366. info.MethodName = m.ToString();
  367. if (f.Address != null)
  368. {
  369. ins = m.Definition.Body.Instructions[f.Address.Value];
  370. var seq = FindSequencePoint(ins, m.Definition.DebugInformation.GetSequencePointMapping());
  371. if (seq != null)
  372. {
  373. info.DocumentName = seq.Document.Url;
  374. info.StartLine = seq.StartLine - 1;
  375. info.StartColumn = seq.StartColumn - 1;
  376. info.EndLine = seq.EndLine - 1;
  377. info.EndColumn = seq.EndColumn - 1;
  378. }
  379. else
  380. continue;
  381. }
  382. StackFrame topFrame = f;
  383. m = topFrame.Method;
  384. int argumentCount = m.ParameterCount;
  385. if (m.HasThis)
  386. argumentCount++;
  387. info.LocalVariables = new VariableInfo[argumentCount + m.LocalVariableCount];
  388. for(int i = 0; i < argumentCount; i++)
  389. {
  390. int argIdx = m.HasThis ? i - 1 : i;
  391. var arg = Minus(topFrame.LocalVarPointer, argumentCount);
  392. string name = null;
  393. object v = null;
  394. string typeName = null;
  395. var val = Add(arg, i);
  396. v = StackObject.ToObject(val, intp.AppDomain, intp.Stack.ManagedStack);
  397. if (argIdx >= 0)
  398. {
  399. var lv = m.Definition.Parameters[argIdx];
  400. name = string.IsNullOrEmpty(lv.Name) ? "arg" + lv.Index : lv.Name;
  401. typeName = lv.ParameterType.FullName;
  402. }
  403. else
  404. {
  405. name = "this";
  406. typeName = m.DeclearingType.FullName;
  407. }
  408. VariableInfo vinfo = VariableInfo.FromObject(v);
  409. vinfo.Address = (long)val;
  410. vinfo.Name = name;
  411. vinfo.TypeName = typeName;
  412. vinfo.Expandable = GetValueExpandable(val, intp.Stack.ManagedStack);
  413. info.LocalVariables[i] = vinfo;
  414. }
  415. for (int i = argumentCount; i < info.LocalVariables.Length; i++)
  416. {
  417. var locIdx = i - argumentCount;
  418. var lv = m.Definition.Body.Variables[locIdx];
  419. var val = Add(topFrame.LocalVarPointer, locIdx);
  420. var v = StackObject.ToObject(val, intp.AppDomain, intp.Stack.ManagedStack);
  421. var type = intp.AppDomain.GetType(lv.VariableType, m.DeclearingType, m);
  422. string vName = null;
  423. m.Definition.DebugInformation.TryGetName(lv, out vName);
  424. string name = string.IsNullOrEmpty(vName) ? "v" + lv.Index : vName;
  425. VariableInfo vinfo = VariableInfo.FromObject(v);
  426. vinfo.Address = (long)val;
  427. vinfo.Name = name;
  428. vinfo.TypeName = lv.VariableType.FullName;
  429. vinfo.Expandable = GetValueExpandable(val, intp.Stack.ManagedStack);
  430. info.LocalVariables[i] = vinfo;
  431. }
  432. frameInfos.Add(info);
  433. }
  434. return frameInfos.ToArray();
  435. }
  436. internal unsafe VariableInfo[] EnumChildren(int threadHashCode, VariableReference parent)
  437. {
  438. ILIntepreter intepreter;
  439. if (AppDomain.Intepreters.TryGetValue(threadHashCode, out intepreter))
  440. {
  441. #if DEBUG && (UNITY_EDITOR || UNITY_ANDROID || UNITY_IPHONE)
  442. if (domain.IsNotUnityMainThread())
  443. {
  444. lock (pendingEnuming)
  445. {
  446. pendingEnuming.Enqueue(new KeyValuePair<int, VariableReference>(threadHashCode, parent));
  447. }
  448. return null;
  449. }
  450. #endif
  451. object obj;
  452. var info = ResolveVariable(threadHashCode, parent, out obj);
  453. if (obj != null)
  454. {
  455. if(obj is Array)
  456. {
  457. return EnumArray((Array)obj, intepreter);
  458. }
  459. else if(obj is IList)
  460. {
  461. return EnumList((IList)obj, intepreter);
  462. }
  463. else if(obj is IDictionary)
  464. {
  465. return EnumDictionary((IDictionary)obj, intepreter);
  466. }
  467. else if(obj is ILTypeInstance)
  468. {
  469. return EnumILTypeInstance((ILTypeInstance)obj, intepreter);
  470. }
  471. else if(obj is ILRuntime.Runtime.Enviorment.CrossBindingAdaptorType)
  472. {
  473. return EnumILTypeInstance(((Enviorment.CrossBindingAdaptorType)obj).ILInstance, intepreter);
  474. }
  475. else
  476. {
  477. return EnumCLRObject(obj, intepreter);
  478. }
  479. }
  480. else
  481. return new VariableInfo[] { VariableInfo.NullReferenceExeption };
  482. }
  483. else
  484. return new VariableInfo[] { VariableInfo.NullReferenceExeption };
  485. }
  486. VariableInfo[] EnumArray(Array arr, ILIntepreter intepreter)
  487. {
  488. VariableInfo[] res = new VariableInfo[arr.Length];
  489. for(int i = 0; i < arr.Length; i++)
  490. {
  491. try
  492. {
  493. var obj = arr.GetValue(i);
  494. VariableInfo info = VariableInfo.FromObject(obj, true);
  495. info.Name = string.Format("[{0}]", i);
  496. info.Offset = i;
  497. info.Type = VariableTypes.IndexAccess;
  498. res[i] = info;
  499. }
  500. catch(Exception ex)
  501. {
  502. var info = VariableInfo.GetException(ex);
  503. info.Name = string.Format("[{0}]", i);
  504. res[i] = info;
  505. }
  506. }
  507. return res;
  508. }
  509. VariableInfo[] EnumList(IList lst, ILIntepreter intepreter)
  510. {
  511. VariableInfo[] res = new VariableInfo[lst.Count];
  512. for (int i = 0; i < lst.Count; i++)
  513. {
  514. try
  515. {
  516. var obj = lst[i];
  517. VariableInfo info = VariableInfo.FromObject(obj, true);
  518. info.Name = string.Format("[{0}]", i);
  519. info.Offset = i;
  520. info.Type = VariableTypes.IndexAccess;
  521. res[i] = info;
  522. }
  523. catch (Exception ex)
  524. {
  525. var info = VariableInfo.GetException(ex);
  526. info.Name = string.Format("[{0}]", i);
  527. res[i] = info;
  528. }
  529. }
  530. return res;
  531. }
  532. VariableInfo[] EnumDictionary(IDictionary lst, ILIntepreter intepreter)
  533. {
  534. VariableInfo[] res = new VariableInfo[lst.Count];
  535. var keys = GetArray(lst.Keys);
  536. var values = GetArray(lst.Values);
  537. for (int i = 0; i < lst.Count; i++)
  538. {
  539. try
  540. {
  541. var obj = values[i];
  542. VariableInfo info = VariableInfo.FromObject(obj, true);
  543. info.Name = string.Format("[{0}]", i);
  544. info.Type = VariableTypes.IndexAccess;
  545. info.Offset = i;
  546. info.Value = string.Format("{0},{1}", SafeToString(keys[i]), SafeToString(values[i]));
  547. info.Expandable = true;
  548. res[i] = info;
  549. }
  550. catch (Exception ex)
  551. {
  552. var info = VariableInfo.GetException(ex);
  553. info.Name = string.Format("[{0}]", i);
  554. res[i] = info;
  555. }
  556. }
  557. return res;
  558. }
  559. string SafeToString(object obj)
  560. {
  561. if (obj != null)
  562. return obj.ToString();
  563. else
  564. return "null";
  565. }
  566. object[] GetArray(ICollection lst)
  567. {
  568. object[] res = new object[lst.Count];
  569. int idx = 0;
  570. foreach(var i in lst)
  571. {
  572. res[idx++] = i;
  573. }
  574. return res;
  575. }
  576. VariableInfo[] EnumILTypeInstance(ILTypeInstance obj, ILIntepreter intepreter)
  577. {
  578. return EnumObject(obj, obj.Type.ReflectionType);
  579. }
  580. VariableInfo[] EnumCLRObject(object obj, ILIntepreter intepreter)
  581. {
  582. return EnumObject(obj, obj.GetType());
  583. }
  584. VariableInfo[] EnumObject(object obj, Type t)
  585. {
  586. List<VariableInfo> lst = new List<VariableInfo>();
  587. foreach (var i in t.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance))
  588. {
  589. try
  590. {
  591. if (i.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), false).Length > 0)
  592. continue;
  593. var val = i.GetValue(obj);
  594. VariableInfo info = VariableInfo.FromObject(val);
  595. info.Type = VariableTypes.FieldReference;
  596. info.TypeName = i.FieldType.FullName;
  597. info.Name = i.Name;
  598. info.Expandable = !i.FieldType.IsPrimitive && val != null;
  599. info.IsPrivate = i.IsPrivate;
  600. info.IsProtected = i.IsFamily;
  601. lst.Add(info);
  602. }
  603. catch (Exception ex)
  604. {
  605. var info = VariableInfo.GetException(ex);
  606. info.Name = i.Name;
  607. lst.Add(info);
  608. }
  609. }
  610. foreach (var i in t.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance))
  611. {
  612. try
  613. {
  614. if (i.GetIndexParameters().Length > 0)
  615. continue;
  616. if (i.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length > 0)
  617. continue;
  618. var val = i.GetValue(obj, null);
  619. VariableInfo info = VariableInfo.FromObject(val);
  620. info.Type = VariableTypes.PropertyReference;
  621. info.TypeName = i.PropertyType.FullName;
  622. info.Name = i.Name;
  623. info.Expandable = !i.PropertyType.IsPrimitive && val != null;
  624. info.IsPrivate = i.GetGetMethod(true).IsPrivate;
  625. info.IsProtected = i.GetGetMethod(true).IsFamily;
  626. lst.Add(info);
  627. }
  628. catch (Exception ex)
  629. {
  630. var info = VariableInfo.GetException(ex);
  631. info.Name = i.Name;
  632. lst.Add(info);
  633. }
  634. }
  635. return lst.ToArray();
  636. }
  637. internal unsafe VariableInfo ResolveIndexAccess(int threadHashCode, VariableReference body, VariableReference idx, out object res)
  638. {
  639. ILIntepreter intepreter;
  640. res = null;
  641. if (AppDomain.Intepreters.TryGetValue(threadHashCode, out intepreter))
  642. {
  643. #if DEBUG && (UNITY_EDITOR || UNITY_ANDROID || UNITY_IPHONE)
  644. if (domain.IsNotUnityMainThread())
  645. {
  646. lock (pendingIndexing)
  647. {
  648. pendingIndexing.Enqueue(new KeyValuePair<int, KeyValuePair<VariableReference, VariableReference>>(threadHashCode, new KeyValuePair<VariableReference, VariableReference>(body, idx)));
  649. }
  650. res = null;
  651. return new VariableInfo() { Type = VariableTypes.Pending };
  652. }
  653. #endif
  654. object obj;
  655. var info = ResolveVariable(threadHashCode, body, out obj);
  656. if (obj != null)
  657. {
  658. object idxObj;
  659. info = ResolveVariable(threadHashCode, idx, out idxObj);
  660. if(obj is Array)
  661. {
  662. res = ((Array)obj).GetValue((int)idxObj);
  663. info = VariableInfo.FromObject(res);
  664. info.Type = VariableTypes.IndexAccess;
  665. info.TypeName = obj.GetType().GetElementType().FullName;
  666. info.Expandable = res != null && !obj.GetType().GetElementType().IsPrimitive;
  667. return info;
  668. }
  669. else
  670. {
  671. if(obj is ILTypeInstance)
  672. {
  673. var m = ((ILTypeInstance)obj).Type.GetMethod("get_Item");
  674. if (m != null)
  675. {
  676. res = intepreter.AppDomain.Invoke(m, obj, idxObj);
  677. info = VariableInfo.FromObject(res);
  678. info.Type = VariableTypes.IndexAccess;
  679. info.TypeName = m.ReturnType.FullName;
  680. info.Expandable = res != null && !m.ReturnType.IsPrimitive;
  681. return info;
  682. }
  683. else
  684. return VariableInfo.NullReferenceExeption;
  685. }
  686. else
  687. {
  688. if(obj is ILRuntime.Runtime.Enviorment.CrossBindingAdaptorType)
  689. {
  690. throw new NotImplementedException();
  691. }
  692. else
  693. {
  694. if(obj is IDictionary && idxObj is int)
  695. {
  696. IDictionary dic = (IDictionary)obj;
  697. var keys = GetArray(dic.Keys);
  698. if (keys[0].GetType() != typeof(int))
  699. {
  700. int index = (int)idxObj;
  701. var values = GetArray(dic.Values);
  702. var t = typeof(KeyValuePair<,>).MakeGenericType(keys[index].GetType(), values[index].GetType());
  703. var ctor = t.GetConstructor(new Type[] { keys[index].GetType(), values[index].GetType() });
  704. res = ctor.Invoke(new object[] { keys[index], values[index] });
  705. info = VariableInfo.FromObject(res);
  706. info.Type = VariableTypes.IndexAccess;
  707. info.Offset = index;
  708. info.TypeName = t.FullName;
  709. info.Expandable = true;
  710. return info;
  711. }
  712. }
  713. var pi = obj.GetType().GetProperty("Item");
  714. if (pi != null)
  715. {
  716. res = pi.GetValue(obj, new object[] { idxObj });
  717. info = VariableInfo.FromObject(res);
  718. info.Type = VariableTypes.IndexAccess;
  719. info.TypeName = pi.PropertyType.FullName;
  720. info.Expandable = res != null && !pi.PropertyType.IsPrimitive;
  721. return info;
  722. }
  723. else
  724. return VariableInfo.NullReferenceExeption;
  725. }
  726. }
  727. }
  728. }
  729. else
  730. return VariableInfo.NullReferenceExeption;
  731. }
  732. else
  733. return VariableInfo.NullReferenceExeption;
  734. }
  735. internal void ResolvePendingRequests()
  736. {
  737. lock (pendingReferences)
  738. {
  739. while (pendingReferences.Count > 0)
  740. {
  741. VariableInfo info;
  742. var r = pendingReferences.Dequeue();
  743. try
  744. {
  745. object res;
  746. info = ResolveVariable(r.Key, r.Value, out res);
  747. }
  748. catch (Exception ex)
  749. {
  750. info = VariableInfo.GetException(ex);
  751. }
  752. server.SendSCResolveVariableResult(info);
  753. }
  754. }
  755. lock (pendingEnuming)
  756. {
  757. while (pendingEnuming.Count > 0)
  758. {
  759. VariableInfo[] info;
  760. var r = pendingEnuming.Dequeue();
  761. try
  762. {
  763. info = EnumChildren(r.Key, r.Value);
  764. }
  765. catch (Exception ex)
  766. {
  767. info = new VariableInfo[] { VariableInfo.GetException(ex) };
  768. }
  769. server.SendSCEnumChildrenResult(info);
  770. }
  771. }
  772. lock (pendingIndexing)
  773. {
  774. while (pendingIndexing.Count > 0)
  775. {
  776. VariableInfo info;
  777. var r = pendingIndexing.Dequeue();
  778. try
  779. {
  780. object res;
  781. info = ResolveIndexAccess(r.Key, r.Value.Key, r.Value.Value, out res);
  782. }
  783. catch (Exception ex)
  784. {
  785. info = VariableInfo.GetException(ex);
  786. }
  787. server.SendSCResolveVariableResult(info);
  788. }
  789. }
  790. }
  791. internal unsafe VariableInfo ResolveVariable(int threadHashCode, VariableReference variable, out object res)
  792. {
  793. ILIntepreter intepreter;
  794. res = null;
  795. if (AppDomain.Intepreters.TryGetValue(threadHashCode, out intepreter))
  796. {
  797. if (variable != null)
  798. {
  799. #if DEBUG && (UNITY_EDITOR || UNITY_ANDROID || UNITY_IPHONE)
  800. if (domain.IsNotUnityMainThread())
  801. {
  802. lock (pendingReferences)
  803. {
  804. pendingReferences.Enqueue(new KeyValuePair<int, VariableReference>(threadHashCode, variable));
  805. }
  806. res = null;
  807. return new VariableInfo() { Type = VariableTypes.Pending };
  808. }
  809. #endif
  810. switch (variable.Type)
  811. {
  812. case VariableTypes.Normal:
  813. {
  814. StackObject* ptr = (StackObject*)variable.Address;
  815. object obj = StackObject.ToObject(ptr, AppDomain, intepreter.Stack.ManagedStack);
  816. if (obj != null)
  817. {
  818. //return ResolveMember(obj, name, out res);
  819. res = obj;
  820. return null;
  821. }
  822. else
  823. {
  824. return VariableInfo.Null;
  825. }
  826. }
  827. case VariableTypes.FieldReference:
  828. case VariableTypes.PropertyReference:
  829. {
  830. object obj;
  831. if (variable.Parent != null)
  832. {
  833. var info = ResolveVariable(threadHashCode, variable.Parent, out obj);
  834. if (obj != null)
  835. {
  836. return ResolveMember(obj, variable.Name, out res);
  837. }
  838. else
  839. {
  840. return VariableInfo.NullReferenceExeption;
  841. }
  842. }
  843. else
  844. {
  845. var frame = intepreter.Stack.Frames.Peek();
  846. var m = frame.Method;
  847. if (m.HasThis)
  848. {
  849. var addr = Minus(frame.LocalVarPointer, m.ParameterCount + 1);
  850. var v = StackObject.ToObject(addr, intepreter.AppDomain, intepreter.Stack.ManagedStack);
  851. var result = ResolveMember(v, variable.Name, out res);
  852. if (result.Type == VariableTypes.NotFound)
  853. {
  854. ILTypeInstance ins = v as ILTypeInstance;
  855. if (ins != null)
  856. {
  857. var ilType = ins.Type.ReflectionType;
  858. var fields = ilType.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
  859. foreach (var f in fields)
  860. {
  861. if (f.Name.Contains("_this"))
  862. {
  863. result = ResolveMember(f.GetValue(v), variable.Name, out res);
  864. if (result.Type != VariableTypes.NotFound)
  865. return result;
  866. }
  867. }
  868. }
  869. }
  870. return result;
  871. }
  872. else
  873. {
  874. return VariableInfo.GetCannotFind(variable.Name);
  875. }
  876. }
  877. }
  878. case VariableTypes.IndexAccess:
  879. {
  880. return ResolveIndexAccess(threadHashCode, variable.Parent, variable.Parameters[0], out res);
  881. }
  882. case VariableTypes.Integer:
  883. {
  884. res = variable.Offset;
  885. return VariableInfo.GetInteger(variable.Offset);
  886. }
  887. case VariableTypes.String:
  888. {
  889. res = variable.Name;
  890. return VariableInfo.GetString(variable.Name);
  891. }
  892. case VariableTypes.Boolean:
  893. {
  894. if(variable.Offset == 1)
  895. {
  896. res = true;
  897. return VariableInfo.True;
  898. }
  899. else
  900. {
  901. res = false;
  902. return VariableInfo.False;
  903. }
  904. }
  905. case VariableTypes.Null:
  906. {
  907. res = null;
  908. return VariableInfo.Null;
  909. }
  910. default:
  911. throw new NotImplementedException();
  912. }
  913. }
  914. else
  915. {
  916. return VariableInfo.NullReferenceExeption;
  917. }
  918. }
  919. else
  920. return VariableInfo.NullReferenceExeption;
  921. }
  922. VariableInfo ResolveMember(object obj, string name, out object res)
  923. {
  924. res = null;
  925. Type type = null;
  926. if (obj is ILTypeInstance)
  927. {
  928. type = ((ILTypeInstance)obj).Type.ReflectionType;
  929. }
  930. else if (obj is Enviorment.CrossBindingAdaptorType)
  931. type = ((Enviorment.CrossBindingAdaptorType)obj).ILInstance.Type.ReflectionType;
  932. else
  933. type = obj.GetType();
  934. var fi = type.GetField(name, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
  935. if (fi != null)
  936. {
  937. res = fi.GetValue(obj);
  938. VariableInfo info = VariableInfo.FromObject(res);
  939. info.Address = 0;
  940. info.Name = name;
  941. info.Type = VariableTypes.FieldReference;
  942. info.TypeName = fi.FieldType.FullName;
  943. info.IsPrivate = fi.IsPrivate;
  944. info.IsProtected = fi.IsFamily;
  945. info.Expandable = res != null && !fi.FieldType.IsPrimitive;
  946. return info;
  947. }
  948. else
  949. {
  950. var fields = type.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
  951. string match = string.Format("<{0}>", name);
  952. foreach (var f in fields)
  953. {
  954. if (f.Name.Contains(match))
  955. {
  956. res = f.GetValue(obj);
  957. VariableInfo info = VariableInfo.FromObject(res);
  958. info.Address = 0;
  959. info.Name = name;
  960. info.Type = VariableTypes.FieldReference;
  961. info.TypeName = f.FieldType.FullName;
  962. info.IsPrivate = f.IsPrivate;
  963. info.IsProtected = f.IsFamily;
  964. info.Expandable = res != null && !f.FieldType.IsPrimitive;
  965. return info;
  966. }
  967. }
  968. }
  969. var pi = type.GetProperty(name, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
  970. if (pi != null)
  971. {
  972. res = pi.GetValue(obj, null);
  973. VariableInfo info = VariableInfo.FromObject(res);
  974. info.Address = 0;
  975. info.Name = name;
  976. info.Type = VariableTypes.PropertyReference;
  977. info.TypeName = pi.PropertyType.FullName;
  978. info.IsPrivate = pi.GetGetMethod(true).IsPrivate;
  979. info.IsProtected = pi.GetGetMethod(true).IsFamily;
  980. info.Expandable = res != null && !pi.PropertyType.IsPrimitive;
  981. return info;
  982. }
  983. return VariableInfo.GetCannotFind(name);
  984. }
  985. unsafe bool GetValueExpandable(StackObject* esp, IList<object> mStack)
  986. {
  987. if (esp->ObjectType < ObjectTypes.Object)
  988. return false;
  989. else
  990. {
  991. var obj = mStack[esp->Value];
  992. if (obj == null)
  993. return false;
  994. if (obj is ILTypeInstance)
  995. return true;
  996. else if (obj.GetType().IsPrimitive)
  997. return false;
  998. else
  999. return true;
  1000. }
  1001. }
  1002. internal void ThreadStarted(ILIntepreter intp)
  1003. {
  1004. if (server != null && server.IsAttached)
  1005. {
  1006. server.SendSCThreadStarted(intp.GetHashCode());
  1007. }
  1008. }
  1009. internal void ThreadEnded(ILIntepreter intp)
  1010. {
  1011. if (server != null && server.IsAttached)
  1012. {
  1013. server.SendSCThreadEnded(intp.GetHashCode());
  1014. }
  1015. }
  1016. internal void Detach()
  1017. {
  1018. activeBreakpoints.Clear();
  1019. breakpointMapping.Clear();
  1020. pendingEnuming.Clear();
  1021. pendingReferences.Clear();
  1022. pendingIndexing.Clear();
  1023. foreach (var j in AppDomain.Intepreters)
  1024. {
  1025. j.Value.ClearDebugState();
  1026. j.Value.Resume();
  1027. }
  1028. }
  1029. internal unsafe void DumpStack(StackObject* esp, RuntimeStack stack)
  1030. {
  1031. var start = stack.StackBase;
  1032. var end = esp + 10;
  1033. var frames = stack.Frames;
  1034. var mStack = stack.ManagedStack;
  1035. var valuePointerEnd = stack.ValueTypeStackPointer;
  1036. StringBuilder final = new StringBuilder();
  1037. HashSet<long> leakVObj = new HashSet<long>();
  1038. for (var i = stack.ValueTypeStackBase; i > stack.ValueTypeStackPointer;)
  1039. {
  1040. leakVObj.Add((long)i);
  1041. i = Minus(i, i->ValueLow + 1);
  1042. }
  1043. for (var i = start; i <= end; i++)
  1044. {
  1045. StringBuilder sb = new StringBuilder();
  1046. ILMethod localMethod = null, baseMethod = null;
  1047. bool isLocal = false;
  1048. bool isBase = false;
  1049. int localIdx = 0;
  1050. if (i == esp)
  1051. sb.Append("->");
  1052. foreach (var j in frames)
  1053. {
  1054. if (i >= j.LocalVarPointer && i < j.BasePointer)
  1055. {
  1056. isLocal = true;
  1057. localIdx = (int)(i - j.LocalVarPointer);
  1058. localMethod = j.Method;
  1059. }
  1060. else if (i == j.BasePointer)
  1061. {
  1062. isBase = true;
  1063. baseMethod = j.Method;
  1064. }
  1065. }
  1066. sb.Append(string.Format("(0x{0:X8}) Type:{1} ", (long)i, i->ObjectType));
  1067. try
  1068. {
  1069. GetStackObjectText(sb, i, mStack, valuePointerEnd);
  1070. }
  1071. catch
  1072. {
  1073. sb.Append(" Cannot Fetch Object Info");
  1074. }
  1075. if (i < esp)
  1076. {
  1077. if (i->ObjectType == ObjectTypes.ValueTypeObjectReference)
  1078. VisitValueTypeReference(ILIntepreter.ResolveReference(i), leakVObj);
  1079. }
  1080. if (isLocal)
  1081. {
  1082. sb.Append(string.Format("|Loc:{0}", localIdx));
  1083. if (localIdx == 0)
  1084. {
  1085. sb.Append(" Method:");
  1086. sb.Append(localMethod.ToString());
  1087. }
  1088. }
  1089. if (isBase)
  1090. {
  1091. sb.Append("|Base");
  1092. sb.Append(" Method:");
  1093. sb.Append(baseMethod.ToString());
  1094. }
  1095. final.AppendLine(sb.ToString());
  1096. }
  1097. for (var i = stack.ValueTypeStackBase; i > stack.ValueTypeStackPointer;)
  1098. {
  1099. var vt = domain.GetType(i->Value);
  1100. var cnt = i->ValueLow;
  1101. bool leak = leakVObj.Contains((long)i);
  1102. final.AppendLine("----------------------------------------------");
  1103. final.AppendLine(string.Format("{2}(0x{0:X8}){1}", (long)i, vt, leak ? "*" : ""));
  1104. for (int j = 0; j < cnt; j++)
  1105. {
  1106. StringBuilder sb = new StringBuilder();
  1107. var ptr = Minus(i, j + 1);
  1108. sb.Append(string.Format("(0x{0:X8}) Type:{1} ", (long)ptr, ptr->ObjectType));
  1109. GetStackObjectText(sb, ptr, mStack, valuePointerEnd);
  1110. final.AppendLine(sb.ToString());
  1111. }
  1112. i = Minus(i, i->ValueLow + 1);
  1113. }
  1114. final.AppendLine("Managed Objects:");
  1115. for (int i = 0; i < mStack.Count; i++)
  1116. {
  1117. final.AppendLine(string.Format("({0}){1}", i, mStack[i]));
  1118. }
  1119. #if !UNITY_5 && !UNITY_2017_1_OR_NEWER && !UNITY_4
  1120. System.Diagnostics.Debug.Print(final.ToString());
  1121. #else
  1122. UnityEngine.Debug.LogWarning(final.ToString());
  1123. #endif
  1124. }
  1125. unsafe void GetStackObjectText(StringBuilder sb, StackObject* esp, IList<object> mStack, StackObject* valueTypeEnd)
  1126. {
  1127. string text = "null";
  1128. switch (esp->ObjectType)
  1129. {
  1130. case ObjectTypes.StackObjectReference:
  1131. {
  1132. sb.Append(string.Format("Value:0x{0:X8}", (long)ILIntepreter.ResolveReference(esp)));
  1133. }
  1134. break;
  1135. case ObjectTypes.ValueTypeObjectReference:
  1136. {
  1137. object obj = null;
  1138. var dst = ILIntepreter.ResolveReference(esp);
  1139. try
  1140. {
  1141. if (dst > valueTypeEnd)
  1142. obj = StackObject.ToObject(esp, domain, mStack);
  1143. if (obj != null)
  1144. text = obj.ToString();
  1145. }
  1146. catch
  1147. {
  1148. text = "Invalid Object";
  1149. }
  1150. text += string.Format("({0})", domain.GetType(dst->Value));
  1151. }
  1152. sb.Append(string.Format("Value:0x{0:X8} Text:{1} ", (long)ILIntepreter.ResolveReference(esp), text));
  1153. break;
  1154. default:
  1155. {
  1156. if (esp->ObjectType >= ObjectTypes.Null && esp->ObjectType <= ObjectTypes.ArrayReference)
  1157. {
  1158. if (esp->ObjectType < ObjectTypes.Object || esp->Value < mStack.Count)
  1159. {
  1160. var obj = StackObject.ToObject(esp, domain, mStack);
  1161. if (obj != null)
  1162. text = obj.ToString();
  1163. }
  1164. }
  1165. sb.Append(string.Format("Value:{0} ValueLow:{1} Text:{2} ", esp->Value, esp->ValueLow, text));
  1166. }
  1167. break;
  1168. }
  1169. }
  1170. unsafe void VisitValueTypeReference(StackObject* esp, HashSet<long> leak)
  1171. {
  1172. leak.Remove((long)esp);
  1173. for (int i = 0; i < esp->ValueLow; i++)
  1174. {
  1175. var ptr = Minus(esp, i + 1);
  1176. if (ptr->ObjectType == ObjectTypes.ValueTypeObjectReference)
  1177. {
  1178. VisitValueTypeReference(ILIntepreter.ResolveReference(ptr), leak);
  1179. }
  1180. }
  1181. }
  1182. }
  1183. }