LuaHookSetup.cs 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  1. /*
  2. #########
  3. ############
  4. #############
  5. ## ###########
  6. ### ###### #####
  7. ### ####### ####
  8. ### ########## ####
  9. #### ########### ####
  10. #### ########### #####
  11. ##### ### ######## #####
  12. ##### ### ######## ######
  13. ###### ### ########### ######
  14. ###### #### ############## ######
  15. ####### ##################### ######
  16. ####### ###################### ######
  17. ####### ###### ################# ######
  18. ####### ###### ###### ######### ######
  19. ####### ## ###### ###### ######
  20. ####### ###### ##### #####
  21. ###### ##### ##### ####
  22. ##### #### ##### ###
  23. ##### ### ### #
  24. ### ### ###
  25. ## ### ###
  26. __________#_______####_______####______________
  27. 我们的未来没有BUG
  28. * ==============================================================================
  29. * Filename: LuaHookSetup
  30. * Created: 2018/7/2 11:36:16
  31. * Author: エル・プサイ・コングリィ
  32. * Purpose:
  33. * ==============================================================================
  34. */
  35. #if UNITY_EDITOR || USE_LUA_PROFILER
  36. using System;
  37. using System.Collections.Generic;
  38. using System.Text;
  39. using UnityEngine;
  40. namespace MikuLuaProfiler
  41. {
  42. #region monobehaviour
  43. public class HookLuaSetup : MonoBehaviour
  44. {
  45. #region field
  46. public static float fps { private set; get; }
  47. public static int frameCount { private set; get; }
  48. public static int pss { private set; get; }
  49. public static float power { private set; get; }
  50. public static LuaDeepProfilerSetting setting { private set; get; }
  51. private bool needShowMenu = false;
  52. public float showTime = 1f;
  53. private int count = 0;
  54. private float deltaTime = 0f;
  55. public const float DELTA_TIME = 0.1f;
  56. public float currentTime = 0;
  57. private static bool isInite = false;
  58. private static Queue<Action> actionQueue = new Queue<Action>();
  59. public static void RegisterAction(Action a)
  60. {
  61. lock (actionQueue)
  62. {
  63. actionQueue.Enqueue(a);
  64. }
  65. }
  66. #endregion
  67. #if UNITY_5 || UNITY_2017_1_OR_NEWER
  68. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
  69. #endif
  70. public static void OnStartGame()
  71. {
  72. #if UNITY_EDITOR
  73. if (!Application.isPlaying) return;
  74. #endif
  75. if (isInite) return;
  76. LuaDeepProfilerSetting.MakeInstance();
  77. isInite = true;
  78. setting = LuaDeepProfilerSetting.Instance;
  79. LuaProfiler.mainThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;
  80. if (setting.isNeedCapture)
  81. {
  82. Screen.SetResolution(480, 270, true);
  83. }
  84. if (setting.isDeepLuaProfiler)
  85. {
  86. LuaDLL.Install();
  87. }
  88. if (setting.isDeepLuaProfiler || setting.isDeepMonoProfiler || setting.isCleanMode)
  89. {
  90. GameObject go = new GameObject();
  91. go.name = "MikuLuaProfiler";
  92. go.hideFlags = HideFlags.HideAndDontSave;
  93. DontDestroyOnLoad(go);
  94. go.AddComponent<HookLuaSetup>();
  95. NetWorkClient.ConnectServer(setting.ip, setting.port);
  96. }
  97. }
  98. private void Awake()
  99. {
  100. setting = LuaDeepProfilerSetting.Instance;
  101. }
  102. private void LateUpdate()
  103. {
  104. if (actionQueue.Count > 0)
  105. {
  106. lock (actionQueue)
  107. {
  108. while (actionQueue.Count > 0)
  109. {
  110. actionQueue.Dequeue()();
  111. }
  112. }
  113. }
  114. frameCount = Time.frameCount;
  115. count++;
  116. deltaTime += Time.unscaledDeltaTime;
  117. if (deltaTime >= showTime)
  118. {
  119. fps = count / deltaTime;
  120. count = 0;
  121. deltaTime = 0f;
  122. }
  123. if (Time.unscaledTime - currentTime > DELTA_TIME)
  124. {
  125. pss = NativeHelper.GetPass();
  126. power = NativeHelper.GetBatteryLevel();
  127. currentTime = Time.unscaledTime;
  128. }
  129. if (Input.touchCount == 4 || Input.GetKeyDown(KeyCode.Delete))
  130. {
  131. needShowMenu = !needShowMenu;
  132. if (needShowMenu)
  133. {
  134. Menu.EnableMenu(gameObject);
  135. }
  136. else
  137. {
  138. Menu.DisableMenu();
  139. }
  140. }
  141. }
  142. private void OnApplicationQuit()
  143. {
  144. #if UNITY_EDITOR
  145. desotryCount = 0;
  146. Destroy(gameObject);
  147. UnityEditor.EditorApplication.update += WaitDestory;
  148. #else
  149. NetWorkClient.Close();
  150. #endif
  151. }
  152. #if UNITY_EDITOR
  153. int desotryCount = 0;
  154. private void WaitDestory()
  155. {
  156. desotryCount++;
  157. if (desotryCount > 10)
  158. {
  159. UnityEditor.EditorApplication.update -= WaitDestory;
  160. if (LuaProfiler.mainL != IntPtr.Zero)
  161. {
  162. LuaDLL.lua_close(LuaProfiler.mainL);
  163. }
  164. LuaProfiler.mainL = IntPtr.Zero;
  165. NetWorkClient.Close();
  166. desotryCount = 0;
  167. }
  168. }
  169. #endif
  170. }
  171. public class Menu : MonoBehaviour
  172. {
  173. private static Menu m_menu;
  174. public static void EnableMenu(GameObject go)
  175. {
  176. if (m_menu == null)
  177. {
  178. m_menu = go.AddComponent<Menu>();
  179. }
  180. m_menu.enabled = true;
  181. }
  182. public static void DisableMenu()
  183. {
  184. if (m_menu == null)
  185. {
  186. return;
  187. }
  188. m_menu.enabled = false;
  189. }
  190. private void OnGUI()
  191. {
  192. var setting = HookLuaSetup.setting;
  193. if (GUI.Button(new Rect(0, 0, 200, 100), "Connect"))
  194. {
  195. NetWorkClient.ConnectServer(setting.ip, setting.port);
  196. }
  197. setting.ip = GUI.TextField(new Rect(210, 20, 200, 60), setting.ip);
  198. if (GUI.Button(new Rect(0, 110, 200, 100), "Disconnect"))
  199. {
  200. NetWorkClient.Close();
  201. }
  202. if (setting.discardInvalid)
  203. {
  204. if (GUI.Button(new Rect(0, 220, 200, 100), "ShowAll"))
  205. {
  206. setting.discardInvalid = false;
  207. }
  208. }
  209. else
  210. {
  211. if (GUI.Button(new Rect(0, 220, 200, 100), "HideUseless"))
  212. {
  213. setting.discardInvalid = true;
  214. }
  215. }
  216. }
  217. }
  218. #endregion
  219. public class LuaHook
  220. {
  221. public static bool isHook = true;
  222. public static byte[] Hookloadbuffer(IntPtr L, byte[] buff, string name)
  223. {
  224. if (LuaDeepProfilerSetting.Instance.isCleanMode)
  225. {
  226. return buff;
  227. }
  228. if (!isHook)
  229. {
  230. return buff;
  231. }
  232. if (buff.Length < 2)
  233. {
  234. return buff;
  235. }
  236. if (buff[0] == 0x1b && buff[1] == 0x4c)
  237. {
  238. return buff;
  239. }
  240. string value = "";
  241. string hookedValue = "";
  242. string fileName = name.Replace(".lua", "");
  243. fileName = fileName.Replace("@", "").Replace('.', '/');
  244. if (fileName.Contains("protobuf"))
  245. {
  246. return buff;
  247. }
  248. // utf-8
  249. if (buff[0] == 239 && buff[1] == 187 && buff[2] == 191)
  250. {
  251. value = Encoding.UTF8.GetString(buff, 3, buff.Length - 3);
  252. }
  253. else
  254. {
  255. value = Encoding.UTF8.GetString(buff);
  256. }
  257. hookedValue = Parse.InsertSample(value, fileName);
  258. buff = Encoding.UTF8.GetBytes(hookedValue);
  259. return buff;
  260. }
  261. public static void HookRef(IntPtr L, int reference, LuaDLL.tolua_getref_fun refFun = null)
  262. {
  263. if (isHook)
  264. {
  265. LuaLib.DoRefLuaFun(L, "lua_miku_add_ref_fun_info", reference, refFun);
  266. }
  267. }
  268. public static void HookUnRef(IntPtr L, int reference, LuaDLL.tolua_getref_fun refFun = null)
  269. {
  270. if (isHook)
  271. {
  272. LuaLib.DoRefLuaFun(L, "lua_miku_remove_ref_fun_info", reference, refFun);
  273. }
  274. }
  275. #region check
  276. public static int staticHistoryRef = -100;
  277. public static LuaDiffInfo RecordStatic()
  278. {
  279. IntPtr L = LuaProfiler.mainL;
  280. if (L == IntPtr.Zero)
  281. {
  282. return null;
  283. }
  284. isHook = false;
  285. ClearStaticRecord();
  286. Resources.UnloadUnusedAssets();
  287. // 调用C# LuaTable LuaFunction WeakTable的析构 来清理掉lua的 ref
  288. GC.Collect();
  289. // 清理掉C#强ref后,顺便清理掉很多弱引用
  290. LuaDLL.lua_gc(L, LuaGCOptions.LUA_GCCOLLECT, 0);
  291. int oldTop = LuaDLL.lua_gettop(L);
  292. LuaDLL.lua_getglobal(L, "miku_handle_error");
  293. LuaDLL.lua_getglobal(L, "miku_do_record");
  294. LuaDLL.lua_getglobal(L, "_G");
  295. LuaDLL.lua_pushstring(L, "");
  296. LuaDLL.lua_pushstring(L, "_G");
  297. //recrod
  298. LuaDLL.lua_newtable(L);
  299. staticHistoryRef = LuaDLL.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX);
  300. LuaDLL.lua_getref(L, staticHistoryRef);
  301. //history
  302. LuaDLL.lua_pushnil(L);
  303. //null_list
  304. LuaDLL.lua_newtable(L);
  305. LuaDLL.lua_pushvalue(L, -1);
  306. int nullObjectRef = LuaDLL.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX);
  307. if (LuaDLL.lua_pcall(L, 6, 0, oldTop + 1) == 0)
  308. {
  309. LuaDLL.lua_remove(L, oldTop + 1);
  310. }
  311. LuaDLL.lua_settop(L, oldTop);
  312. oldTop = LuaDLL.lua_gettop(L);
  313. LuaDLL.lua_getglobal(L, "miku_handle_error");
  314. LuaDLL.lua_getglobal(L, "miku_do_record");
  315. LuaDLL.lua_pushvalue(L, LuaIndexes.LUA_REGISTRYINDEX);
  316. LuaDLL.lua_pushstring(L, "");
  317. LuaDLL.lua_pushstring(L, "_R");
  318. LuaDLL.lua_getref(L, staticHistoryRef);
  319. //history
  320. LuaDLL.lua_pushnil(L);
  321. //null_list
  322. LuaDLL.lua_getref(L, nullObjectRef);
  323. if (LuaDLL.lua_pcall(L, 6, 0, oldTop + 1) == 0)
  324. {
  325. LuaDLL.lua_remove(L, oldTop + 1);
  326. }
  327. LuaDLL.lua_settop(L, oldTop);
  328. LuaDiffInfo ld = LuaDiffInfo.Create();
  329. SetTable(nullObjectRef, ld.nullRef, ld.nullDetail);
  330. isHook = true;
  331. return ld;
  332. }
  333. public static int historyRef = -100;
  334. public static LuaDiffInfo Record()
  335. {
  336. IntPtr L = LuaProfiler.mainL;
  337. if (L == IntPtr.Zero)
  338. {
  339. return null;
  340. }
  341. isHook = false;
  342. ClearRecord();
  343. Resources.UnloadUnusedAssets();
  344. // 调用C# LuaTable LuaFunction WeakTable的析构 来清理掉lua的 ref
  345. GC.Collect();
  346. // 清理掉C#强ref后,顺便清理掉很多弱引用
  347. LuaDLL.lua_gc(L, LuaGCOptions.LUA_GCCOLLECT, 0);
  348. int oldTop = LuaDLL.lua_gettop(L);
  349. LuaDLL.lua_getglobal(L, "miku_handle_error");
  350. LuaDLL.lua_getglobal(L, "miku_do_record");
  351. LuaDLL.lua_getglobal(L, "_G");
  352. LuaDLL.lua_pushstring(L, "");
  353. LuaDLL.lua_pushstring(L, "_G");
  354. //recrod
  355. LuaDLL.lua_newtable(L);
  356. historyRef = LuaDLL.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX);
  357. LuaDLL.lua_getref(L, historyRef);
  358. //history
  359. LuaDLL.lua_pushnil(L);
  360. //null_list
  361. LuaDLL.lua_newtable(L);
  362. LuaDLL.lua_pushvalue(L, -1);
  363. int nullObjectRef = LuaDLL.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX);
  364. LuaDLL.lua_getref(L, staticHistoryRef);
  365. if (LuaDLL.lua_pcall(L, 7, 0, oldTop + 1) == 0)
  366. {
  367. LuaDLL.lua_remove(L, oldTop + 1);
  368. }
  369. LuaDLL.lua_settop(L, oldTop);
  370. oldTop = LuaDLL.lua_gettop(L);
  371. LuaDLL.lua_getglobal(L, "miku_handle_error");
  372. LuaDLL.lua_getglobal(L, "miku_do_record");
  373. LuaDLL.lua_pushvalue(L, LuaIndexes.LUA_REGISTRYINDEX);
  374. LuaDLL.lua_pushstring(L, "");
  375. LuaDLL.lua_pushstring(L, "_R");
  376. LuaDLL.lua_getref(L, historyRef);
  377. //history
  378. LuaDLL.lua_pushnil(L);
  379. //null_list
  380. LuaDLL.lua_getref(L, nullObjectRef);
  381. LuaDLL.lua_getref(L, staticHistoryRef);
  382. if (LuaDLL.lua_pcall(L, 7, 0, oldTop + 1) == 0)
  383. {
  384. LuaDLL.lua_remove(L, oldTop + 1);
  385. }
  386. LuaDLL.lua_settop(L, oldTop);
  387. LuaDiffInfo ld = LuaDiffInfo.Create();
  388. SetTable(nullObjectRef, ld.nullRef, ld.nullDetail);
  389. LuaDLL.lua_unref(L, nullObjectRef);
  390. isHook = true;
  391. return ld;
  392. }
  393. public static void ClearStaticRecord()
  394. {
  395. IntPtr L = LuaProfiler.mainL;
  396. if (L == IntPtr.Zero)
  397. {
  398. return;
  399. }
  400. if (staticHistoryRef != -100)
  401. {
  402. LuaDLL.lua_unref(L, staticHistoryRef);
  403. staticHistoryRef = -100;
  404. }
  405. }
  406. public static void ClearRecord()
  407. {
  408. IntPtr L = LuaProfiler.mainL;
  409. if (L == IntPtr.Zero)
  410. {
  411. return;
  412. }
  413. if (historyRef != -100)
  414. {
  415. LuaDLL.lua_unref(L, historyRef);
  416. historyRef = -100;
  417. }
  418. }
  419. private static void SetTable(int refIndex, Dictionary<LuaTypes, HashSet<string>> dict, Dictionary<string, List<string>> detailDict)
  420. {
  421. IntPtr L = LuaProfiler.mainL;
  422. if (L == IntPtr.Zero)
  423. {
  424. return;
  425. }
  426. dict.Clear();
  427. int oldTop = LuaDLL.lua_gettop(L);
  428. LuaDLL.lua_getref(L, refIndex);
  429. if (LuaDLL.lua_type(L, -1) != LuaTypes.LUA_TTABLE)
  430. {
  431. LuaDLL.lua_pop(L, 1);
  432. return;
  433. }
  434. int t = oldTop + 1;
  435. LuaDLL.lua_pushnil(L); /* 第一个 key */
  436. while (LuaDLL.lua_next(L, t) != 0)
  437. {
  438. /* 用一下 'key' (在索引 -2 处) 和 'value' (在索引 -1 处) */
  439. int key_t = LuaDLL.lua_gettop(L);
  440. LuaDLL.lua_pushnil(L); /* 第一个 key */
  441. string firstKey = null;
  442. List<string> detailList = new List<string>();
  443. while (LuaDLL.lua_next(L, key_t) != 0)
  444. {
  445. string key = LuaHook.GetRefString(L, -1);
  446. if (string.IsNullOrEmpty(firstKey))
  447. {
  448. firstKey = key;
  449. }
  450. detailList.Add(key);
  451. LuaDLL.lua_pop(L, 1);
  452. }
  453. LuaDLL.lua_settop(L, key_t);
  454. if (!string.IsNullOrEmpty(firstKey))
  455. {
  456. HashSet<string> list;
  457. LuaTypes luaType = (LuaTypes)LuaDLL.lua_type(L, -2);
  458. if (!dict.TryGetValue(luaType, out list))
  459. {
  460. list = new HashSet<string>();
  461. dict.Add(luaType, list);
  462. }
  463. if (!list.Contains(firstKey))
  464. {
  465. list.Add(firstKey);
  466. }
  467. detailDict[firstKey] = detailList;
  468. }
  469. /* 移除 'value' ;保留 'key' 做下一次迭代 */
  470. LuaDLL.lua_pop(L, 1);
  471. }
  472. LuaDLL.lua_settop(L, oldTop);
  473. }
  474. public static void DiffServer()
  475. {
  476. NetWorkClient.SendMessage(Diff());
  477. }
  478. public static void MarkRecordServer()
  479. {
  480. NetWorkClient.SendMessage(Record());
  481. }
  482. public static void MarkStaticServer()
  483. {
  484. NetWorkClient.SendMessage(Record());
  485. }
  486. public static LuaDiffInfo Diff()
  487. {
  488. IntPtr L = LuaProfiler.mainL;
  489. if (L == IntPtr.Zero)
  490. {
  491. return null;
  492. }
  493. isHook = false;
  494. Resources.UnloadUnusedAssets();
  495. // 调用C# LuaTable LuaFunction WeakTable的析构 来清理掉lua的 ref
  496. GC.Collect();
  497. // 清理掉C#强ref后,顺便清理掉很多弱引用
  498. LuaDLL.lua_gc(L, LuaGCOptions.LUA_GCCOLLECT, 0);
  499. if (staticHistoryRef == -100)
  500. {
  501. Debug.LogError("has no history");
  502. return null;
  503. }
  504. if (historyRef == -100)
  505. {
  506. Debug.LogError("has no history");
  507. return null;
  508. }
  509. int oldTop = LuaDLL.lua_gettop(L);
  510. LuaDLL.lua_getglobal(L, "miku_handle_error");
  511. LuaDLL.lua_getglobal(L, "miku_diff");
  512. LuaDLL.lua_getref(L, historyRef);
  513. LuaDLL.lua_getref(L, staticHistoryRef);
  514. if (LuaDLL.lua_type(L, -1) != LuaTypes.LUA_TTABLE &&
  515. LuaDLL.lua_type(L, -2) != LuaTypes.LUA_TTABLE)
  516. {
  517. Debug.LogError(LuaDLL.lua_type(L, -1));
  518. LuaDLL.lua_settop(L, oldTop);
  519. historyRef = -100;
  520. staticHistoryRef = -100;
  521. return null;
  522. }
  523. if (LuaDLL.lua_pcall(L, 2, 3, oldTop + 1) == 0)
  524. {
  525. LuaDLL.lua_remove(L, oldTop + 1);
  526. }
  527. int nullObjectRef = LuaDLL.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX);
  528. int rmRef = LuaDLL.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX);
  529. int addRef = LuaDLL.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX);
  530. LuaDiffInfo ld = LuaDiffInfo.Create();
  531. SetTable(nullObjectRef, ld.nullRef, ld.nullDetail);
  532. SetTable(rmRef, ld.rmRef, ld.rmDetail);
  533. SetTable(addRef, ld.addRef, ld.addDetail);
  534. LuaDLL.lua_unref(L, nullObjectRef);
  535. LuaDLL.lua_unref(L, rmRef);
  536. LuaDLL.lua_unref(L, addRef);
  537. LuaDLL.lua_settop(L, oldTop);
  538. isHook = true;
  539. return ld;
  540. }
  541. #endregion
  542. #region luastring
  543. public static readonly Dictionary<long, object> stringDict = new Dictionary<long, object>();
  544. public static bool TryGetLuaString(IntPtr p, out object result)
  545. {
  546. return stringDict.TryGetValue(p.ToInt64(), out result);
  547. }
  548. public static void RefString(IntPtr strPoint, int index, object s, IntPtr L)
  549. {
  550. int oldTop = LuaDLL.lua_gettop(L);
  551. //把字符串ref了之后就不GC了
  552. LuaDLL.lua_getglobal(L, "MikuLuaProfilerStrTb");
  553. int len = LuaDLL.lua_getobjlen(L, -1);
  554. LuaDLL.lua_pushnumber(L, len + 1);
  555. LuaDLL.lua_pushvalue(L, index);
  556. LuaDLL.lua_rawset(L, -3);
  557. LuaDLL.lua_settop(L, oldTop);
  558. stringDict[(long)strPoint] = s;
  559. }
  560. public static string GetRefString(IntPtr L, int index)
  561. {
  562. IntPtr len;
  563. IntPtr intPtr = LuaDLL.lua_tolstring(L, index, out len);
  564. object text;
  565. if (!TryGetLuaString(intPtr, out text))
  566. {
  567. string tmpText = LuaDLL.lua_tostring(L, index);
  568. if (!string.IsNullOrEmpty(tmpText))
  569. {
  570. text = string.Intern(tmpText);
  571. }
  572. else
  573. {
  574. text = "nil";
  575. }
  576. RefString(intPtr, index, text, L);
  577. }
  578. return (string)text;
  579. }
  580. #endregion
  581. }
  582. public class LuaLib
  583. {
  584. public static long GetLuaMemory(IntPtr luaState)
  585. {
  586. long result = 0;
  587. if (LuaProfiler.m_hasL)
  588. {
  589. result = LuaDLL.lua_gc(luaState, LuaGCOptions.LUA_GCCOUNT, 0);
  590. result = result * 1024 + LuaDLL.lua_gc(luaState, LuaGCOptions.LUA_GCCOUNTB, 0);
  591. }
  592. return result;
  593. }
  594. public static void DoString(IntPtr L, string script)
  595. {
  596. LuaHook.isHook = false;
  597. byte[] chunk = Encoding.UTF8.GetBytes(script);
  598. int oldTop = LuaDLL.lua_gettop(L);
  599. LuaDLL.lua_getglobal(L, "miku_handle_error");
  600. if (LuaDLL.luaL_loadbuffer(L, chunk, (IntPtr)chunk.Length, "chunk") == 0)
  601. {
  602. if (LuaDLL.lua_pcall(L, 0, -1, oldTop + 1) == 0)
  603. {
  604. LuaDLL.lua_remove(L, oldTop + 1);
  605. }
  606. }
  607. else
  608. {
  609. Debug.Log(script);
  610. }
  611. LuaHook.isHook = true;
  612. LuaDLL.lua_settop(L, oldTop);
  613. }
  614. public static void DoRefLuaFun(IntPtr L, string funName, int reference, LuaDLL.tolua_getref_fun refFun)
  615. {
  616. int moreOldTop = LuaDLL.lua_gettop(L);
  617. if (refFun == null)
  618. {
  619. LuaDLL.lua_getref(L, reference);
  620. }
  621. else
  622. {
  623. refFun(L, reference);
  624. }
  625. if (LuaDLL.lua_isfunction(L, -1) || LuaDLL.lua_istable(L, -1))
  626. {
  627. int oldTop = LuaDLL.lua_gettop(L);
  628. LuaDLL.lua_getglobal(L, "miku_handle_error");
  629. do
  630. {
  631. LuaDLL.lua_getglobal(L, funName);
  632. if (!LuaDLL.lua_isfunction(L, -1)) break;
  633. LuaDLL.lua_pushvalue(L, oldTop);
  634. if (LuaDLL.lua_pcall(L, 1, 0, oldTop + 1) == 0)
  635. {
  636. LuaDLL.lua_remove(L, oldTop + 1);
  637. }
  638. } while (false);
  639. LuaDLL.lua_settop(L, oldTop);
  640. }
  641. LuaDLL.lua_settop(L, moreOldTop);
  642. }
  643. }
  644. #region bind
  645. public class MikuLuaProfilerLuaProfilerWrap
  646. {
  647. public static LuaDeepProfilerSetting setting = LuaDeepProfilerSetting.Instance;
  648. public static LuaCSFunction beginSample = new LuaCSFunction(BeginSample);
  649. public static LuaCSFunction beginSampleCustom = new LuaCSFunction(BeginSampleCustom);
  650. public static LuaCSFunction endSample = new LuaCSFunction(EndSample);
  651. public static LuaCSFunction unpackReturnValue = new LuaCSFunction(UnpackReturnValue);
  652. public static LuaCSFunction addRefFunInfo = new LuaCSFunction(AddRefFunInfo);
  653. public static LuaCSFunction removeRefFunInfo = new LuaCSFunction(RemoveRefFunInfo);
  654. public static LuaCSFunction checkType = new LuaCSFunction(CheckType);
  655. public static LuaCSFunction handleError = new LuaCSFunction(HandleError);
  656. public static void __Register(IntPtr L)
  657. {
  658. LuaDLL.lua_newtable(L);
  659. LuaDLL.lua_pushstring(L, "LuaProfiler");
  660. LuaDLL.lua_newtable(L);
  661. LuaDLL.lua_pushstring(L, "BeginSample");
  662. LuaDLL.lua_pushstdcallcfunction(L, beginSample);
  663. LuaDLL.lua_rawset(L, -3);
  664. LuaDLL.lua_pushstring(L, "EndSample");
  665. LuaDLL.lua_pushstdcallcfunction(L, endSample);
  666. LuaDLL.lua_rawset(L, -3);
  667. LuaDLL.lua_pushstring(L, "BeginSampleCustom");
  668. LuaDLL.lua_pushstdcallcfunction(L, beginSampleCustom);
  669. LuaDLL.lua_rawset(L, -3);
  670. LuaDLL.lua_pushstring(L, "EndSampleCustom");
  671. LuaDLL.lua_pushstdcallcfunction(L, endSample);
  672. LuaDLL.lua_rawset(L, -3);
  673. LuaDLL.lua_rawset(L, -3);
  674. LuaDLL.lua_setglobal(L, "MikuLuaProfiler");
  675. LuaDLL.lua_pushstdcallcfunction(L, unpackReturnValue);
  676. LuaDLL.lua_setglobal(L, "miku_unpack_return_value");
  677. LuaDLL.lua_pushstdcallcfunction(L, addRefFunInfo);
  678. LuaDLL.lua_setglobal(L, "miku_add_ref_fun_info");
  679. LuaDLL.lua_pushstdcallcfunction(L, removeRefFunInfo);
  680. LuaDLL.lua_setglobal(L, "miku_remove_ref_fun_info");
  681. LuaDLL.lua_pushstdcallcfunction(L, checkType);
  682. LuaDLL.lua_setglobal(L, "miku_check_type");
  683. LuaDLL.lua_pushstdcallcfunction(L, handleError);
  684. LuaDLL.lua_setglobal(L, "miku_handle_error");
  685. LuaDLL.lua_newtable(L);
  686. LuaDLL.lua_setglobal(L, "MikuLuaProfilerStrTb");
  687. LuaLib.DoString(L, get_ref_string);
  688. LuaLib.DoString(L, null_script);
  689. LuaLib.DoString(L, diff_script);
  690. }
  691. #region script
  692. const string get_ref_string = @"
  693. local weak_meta_table = {__mode = 'k'}
  694. local infoTb = {}
  695. local funAddrTb = {}
  696. setmetatable(infoTb, weak_meta_table)
  697. setmetatable(funAddrTb, weak_meta_table)
  698. function miku_get_fun_info(fun)
  699. local result = infoTb[fun]
  700. local addr = funAddrTb[fun]
  701. if not result then
  702. local info = debug.getinfo(fun, 'Sl')
  703. result = string.format('function:%s&line:%d', info.source, info.linedefined)
  704. addr = string.sub(tostring(fun), 11)
  705. infoTb[fun] = result
  706. funAddrTb[fun] = addr
  707. end
  708. return result,addr
  709. end
  710. local function serialize(obj)
  711. if obj == _G then
  712. return '_G'
  713. end
  714. local lua = ''
  715. lua = lua .. '{\n'
  716. local count = 0
  717. for k, v in pairs(obj) do
  718. lua = lua .. '[' .. tostring(tostring(k)) .. ']=' .. tostring(tostring(v)) .. ',\n'
  719. count = count + 1
  720. if count > 5 then
  721. break
  722. end
  723. end
  724. lua = lua .. '}'
  725. if lua == '{\n}' then
  726. lua = tostring(obj)
  727. end
  728. return lua
  729. end
  730. local function get_table_info(tb)
  731. local result = infoTb[tb]
  732. local addr = funAddrTb[tb]
  733. if not result then
  734. local tostringFun
  735. local metaTb = getmetatable(tb)
  736. if metaTb and miku_check_type(metaTb) == 2 and rawget(metaTb, '__tostring') then
  737. tostringFun = rawget(metaTb, '__tostring')
  738. rawset(metaTb, '__tostring', nil)
  739. end
  740. local addStr = tostring(tb)
  741. if tostringFun then
  742. rawset(getmetatable(tb), '__tostring', tostringFun)
  743. end
  744. result = rawget(tb, '__name') or rawget(tb, 'name') or rawget(tb, '__cname') or rawget(tb, '.name')
  745. if not result then
  746. result = serialize(tb)
  747. end
  748. addr = string.sub(addStr, 7)
  749. infoTb[tb] = result
  750. funAddrTb[tb] = addr
  751. end
  752. return result,addr
  753. end
  754. function lua_miku_add_ref_fun_info(data)
  755. local result = ''
  756. local addr = ''
  757. local t = 1
  758. local typeStr = miku_check_type(data)
  759. if typeStr == 1 then
  760. result,addr = miku_get_fun_info(data)
  761. t = 1
  762. elseif typeStr == 2 then
  763. result,addr = get_table_info(data)
  764. t = 2
  765. end
  766. miku_add_ref_fun_info(result, addr, t)
  767. end
  768. function lua_miku_remove_ref_fun_info(data)
  769. local result = infoTb[data]
  770. local addr = funAddrTb[data]
  771. local typeStr = miku_check_type(data)
  772. local t = 1
  773. if typeStr == 1 then
  774. t = 1
  775. elseif typeStr == 2 then
  776. t = 2
  777. end
  778. miku_remove_ref_fun_info(result, addr, t)
  779. end
  780. ";
  781. const string null_script = @"
  782. function miku_is_null(val)
  783. local metaTable = getmetatable(val)
  784. if type(metaTable) == 'table' and metaTable.__index and val.Equals then
  785. local status,retval = pcall(val.Equals, val, nil)
  786. if status then
  787. return retval
  788. else
  789. return true
  790. end
  791. end
  792. return false
  793. end
  794. ";
  795. const string diff_script = @"
  796. local weak_meta_key_table = {__mode = 'k'}
  797. local weak_meta_value_table = {__mode = 'v'}
  798. local infoTb = {}
  799. local cache_key = 'miku_record_prefix_cache'
  800. function miku_do_record(val, prefix, key, record, history, null_list, staticRecord)
  801. if val == staticRecord then
  802. return
  803. end
  804. if val == infoTb then
  805. return
  806. end
  807. if val == miku_do_record then
  808. return
  809. end
  810. if val == miku_diff then
  811. return
  812. end
  813. if val == lua_miku_remove_ref_fun_info then
  814. return
  815. end
  816. if val == lua_miku_add_ref_fun_info then
  817. return
  818. end
  819. if val == history then
  820. return
  821. end
  822. if val == record then
  823. return
  824. end
  825. if val == miku_get_fun_info then
  826. return
  827. end
  828. if val == MikuLuaProfilerStrTb then
  829. return
  830. end
  831. if getmetatable(record) ~= weak_meta_key_table then
  832. setmetatable(record, weak_meta_key_table)
  833. end
  834. local typeStr = type(val)
  835. if typeStr ~= 'table' and typeStr ~= 'userdata' and typeStr ~= 'function' then
  836. return
  837. end
  838. local tmp_prefix
  839. local strKey = tostring(key)
  840. if not strKey then
  841. strKey = 'empty'
  842. end
  843. local prefixTb = infoTb[prefix]
  844. if not prefixTb then
  845. prefixTb = {}
  846. infoTb[prefix] = prefixTb
  847. end
  848. tmp_prefix = prefixTb[strKey]
  849. if not tmp_prefix then
  850. tmp_prefix = prefix.. (prefix == '' and '' or '.') .. strKey
  851. prefixTb[strKey] = tmp_prefix
  852. end
  853. if null_list then
  854. if type(val) == 'userdata' then
  855. local st,ret = pcall(miku_is_null, val)
  856. if st and ret then
  857. if null_list[val] == nil then
  858. null_list[val] = { }
  859. end
  860. table.insert(null_list[val], tmp_prefix)
  861. end
  862. end
  863. end
  864. if record[val] then
  865. table.insert(record[val], tmp_prefix)
  866. return
  867. end
  868. local prefix_cache
  869. if history == nil then
  870. if record[cache_key] == nil then
  871. record[cache_key] = {}
  872. end
  873. prefix_cache = record[cache_key]
  874. prefix_cache[tmp_prefix] = tmp_prefix
  875. local record_val = record[val]
  876. if record_val == nil then
  877. record_val = {}
  878. if typeStr == 'function' then
  879. local funInfo = miku_get_fun_info(val)
  880. table.insert(record_val, funInfo)
  881. end
  882. record[val] = record_val
  883. end
  884. table.insert(record_val, tmp_prefix)
  885. else
  886. prefix_cache = history[cache_key]
  887. if prefix_cache[tmp_prefix] == nil or history[val] then
  888. local record_val = record[val]
  889. if record_val == nil then
  890. record_val = {}
  891. if typeStr == 'function' then
  892. local funInfo = miku_get_fun_info(val)
  893. table.insert(record_val, funInfo)
  894. end
  895. record[val] = record_val
  896. end
  897. table.insert(record_val, tmp_prefix)
  898. end
  899. end
  900. if typeStr == 'table' then
  901. for k,v in pairs(val) do
  902. local typeKStr = type(k)
  903. local typeVStr = type(v)
  904. local key = k
  905. if typeKStr == 'table' or typeKStr == 'userdata' or typeKStr == 'function' then
  906. key = 'table:'
  907. miku_do_record(k, tmp_prefix, 'table:', record, history, null_list, staticRecord)
  908. end
  909. miku_do_record(v, tmp_prefix, key, record, history, null_list, staticRecord)
  910. end
  911. elseif typeStr == 'function' then
  912. if val ~= lua_miku_add_ref_fun_info and val ~= lua_miku_remove_ref_fun_info then
  913. local i = 1
  914. while true do
  915. local k, v = debug.getupvalue(val, i)
  916. if not k then
  917. break
  918. end
  919. if v then
  920. local funPrefix = miku_get_fun_info(val)
  921. miku_do_record(v, funPrefix, k, record, history, null_list, staticRecord)
  922. end
  923. i = i + 1
  924. end
  925. end
  926. end
  927. local metaTable = getmetatable(val)
  928. if metaTable then
  929. miku_do_record(metaTable, tmp_prefix, 'metaTable', record, history, null_list, staticRecord)
  930. end
  931. end
  932. -- staticRecord为打开UI前的快照, record为打开UI后的快照,add为关闭并释放UI后的快照
  933. function miku_diff(record, staticRecord)
  934. local add = { }
  935. setmetatable(add, weak_meta_key_table)
  936. local null_list = { }
  937. setmetatable(null_list, weak_meta_key_table)
  938. miku_do_record(_G, '', '_G', add, record, null_list, staticRecord)
  939. miku_do_record(debug.getregistry(), '', '_R', add, record, null_list, staticRecord)
  940. local remain = { }
  941. for key, val in pairs(record) do
  942. if not add[key] and key ~= cache_key then
  943. else
  944. -- 如果打开UI前的快照没有这个数据
  945. -- 但是打开UI后及关闭并释放UI后的快照都拥有这个数据,视为泄漏
  946. if not staticRecord[key] and key ~= staticRecord and key ~= cache_key then
  947. remain[key] = val
  948. end
  949. add[key] = nil
  950. end
  951. end
  952. return add,remain,null_list
  953. end";
  954. #endregion
  955. [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
  956. static int BeginSample(IntPtr L)
  957. {
  958. LuaProfiler.BeginSample(L, LuaHook.GetRefString(L, 1));
  959. return 0;
  960. }
  961. [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
  962. static int BeginSampleCustom(IntPtr L)
  963. {
  964. LuaProfiler.BeginSample(L, LuaHook.GetRefString(L, 1), true);
  965. return 0;
  966. }
  967. [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
  968. static int UnpackReturnValue(IntPtr L)
  969. {
  970. LuaProfiler.EndSample(L);
  971. return LuaDLL.lua_gettop(L);
  972. }
  973. [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
  974. static int CheckType(IntPtr L)
  975. {
  976. if (LuaDLL.lua_isfunction(L, 1))
  977. {
  978. LuaDLL.lua_pushnumber(L, 1);
  979. }
  980. else if (LuaDLL.lua_istable(L, 1))
  981. {
  982. LuaDLL.lua_pushnumber(L, 2);
  983. }
  984. else
  985. {
  986. LuaDLL.lua_pushnumber(L, 0);
  987. }
  988. return 1;
  989. }
  990. [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
  991. static int AddRefFunInfo(IntPtr L)
  992. {
  993. string funName = LuaHook.GetRefString(L, 1);
  994. string funAddr = LuaHook.GetRefString(L, 2);
  995. byte type = (byte)LuaDLL.lua_tonumber(L, 3);
  996. LuaProfiler.AddRef(funName, funAddr, type);
  997. return 0;
  998. }
  999. [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
  1000. static int RemoveRefFunInfo(IntPtr L)
  1001. {
  1002. string funName = LuaHook.GetRefString(L, 1);
  1003. string funAddr = LuaHook.GetRefString(L, 2);
  1004. byte type = (byte)LuaDLL.lua_tonumber(L, 3);
  1005. LuaProfiler.RemoveRef(funName, funAddr, type);
  1006. return 0;
  1007. }
  1008. [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
  1009. static int HandleError(IntPtr L)
  1010. {
  1011. string error = LuaHook.GetRefString(L, 1);
  1012. Debug.LogError(error);
  1013. return 0;
  1014. }
  1015. [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
  1016. static int EndSample(IntPtr L)
  1017. {
  1018. LuaProfiler.EndSample(L);
  1019. return 0;
  1020. }
  1021. }
  1022. #endregion
  1023. }
  1024. #endif