diff --git a/LuaProfiler/Tools/InjectLua/InjectLua/Parse/LLex.cs b/LuaProfiler/Tools/InjectLua/InjectLua/Parse/LLex.cs index 728d63ce..69f89f02 100644 --- a/LuaProfiler/Tools/InjectLua/InjectLua/Parse/LLex.cs +++ b/LuaProfiler/Tools/InjectLua/InjectLua/Parse/LLex.cs @@ -512,7 +512,7 @@ public int Length public void Replace(int start, int end, string value) { - LoadInfo.Replace(start, end + 1 - start, value); + LoadInfo.Replace(start, end - start, value); } public string ReadString(int start, int end) diff --git a/LuaProfiler/Tools/InjectLua/InjectLua/Parse/Parse.cs b/LuaProfiler/Tools/InjectLua/InjectLua/Parse/Parse.cs index 8e0ed6e8..9aa6b958 100644 --- a/LuaProfiler/Tools/InjectLua/InjectLua/Parse/Parse.cs +++ b/LuaProfiler/Tools/InjectLua/InjectLua/Parse/Parse.cs @@ -223,9 +223,8 @@ static void InsertSample(LLex l, ref int lastPos, ref int nextPos, int tokenType { lastPos = lastPos - 1; - string returnStr = l.ReadString(insertPos, lastPos - 1); - returnStr = " return miku_unpack_return_value(" + returnStr.Substring(6, returnStr.Length - 6) + ") "; - l.Replace(insertPos, lastPos - 1, returnStr); + l.Replace(insertPos, insertPos + 6, " return miku_unpack_return_value("); + l.InsertString(lastPos , ") "); nextPos = l.pos; if (tokenType == (int)TK.END) diff --git a/LuaProfiler/example/Assets/Plugins/Android/java/ShadowHook.java b/LuaProfiler/Tools/shadowhook/ShadowHook.java similarity index 97% rename from LuaProfiler/example/Assets/Plugins/Android/java/ShadowHook.java rename to LuaProfiler/Tools/shadowhook/ShadowHook.java index 526d52ec..0cc9c4ca 100644 --- a/LuaProfiler/example/Assets/Plugins/Android/java/ShadowHook.java +++ b/LuaProfiler/Tools/shadowhook/ShadowHook.java @@ -38,14 +38,10 @@ public final class ShadowHook { private static final ILibLoader defaultLibLoader = null; private static final int defaultMode = Mode.UNIQUE.getValue(); - private static final boolean defaultDebuggable = true; + private static final boolean defaultDebuggable = false; public static int init() { - if (inited) { - return initErrno; - } - - return init(new ConfigBuilder().build()); + return init(null); } public static synchronized int init(Config config) { @@ -56,6 +52,11 @@ public static synchronized int init(Config config) { long start = System.currentTimeMillis(); + if (config == null) { + //use default parameters + config = new ConfigBuilder().build(); + } + if (!loadLibrary(config)) { initErrno = ERRNO_LOAD_LIBRARY_EXCEPTION; initCostMs = System.currentTimeMillis() - start; diff --git a/LuaProfiler/example/Assets/LuaProfiler/Common/Setting/LuaDeepProfilerSetting.cs b/LuaProfiler/example/Assets/LuaProfiler/Common/Setting/LuaDeepProfilerSetting.cs index bd862611..3c562ced 100644 --- a/LuaProfiler/example/Assets/LuaProfiler/Common/Setting/LuaDeepProfilerSetting.cs +++ b/LuaProfiler/example/Assets/LuaProfiler/Common/Setting/LuaDeepProfilerSetting.cs @@ -53,7 +53,7 @@ public static LuaDeepProfilerSetting Instance { if (instance == null) { - instance = new LuaDeepProfilerSetting(); + instance = Load(); } return instance; } @@ -315,7 +315,7 @@ public static LuaDeepProfilerSetting Load() try { - JsonUtility.FromJson(json); + result = JsonUtility.FromJson(json); } catch { diff --git a/LuaProfiler/example/Assets/LuaProfiler/Common/Struct/Sample.cs b/LuaProfiler/example/Assets/LuaProfiler/Common/Struct/Sample.cs index 88048246..c34bddef 100644 --- a/LuaProfiler/example/Assets/LuaProfiler/Common/Struct/Sample.cs +++ b/LuaProfiler/example/Assets/LuaProfiler/Common/Struct/Sample.cs @@ -61,54 +61,6 @@ public abstract class NetBase public abstract void Restore(); } - public class LuaRefInfo : NetBase - { - #region field - public byte cmd; //1添加、0移除 - public int frameCount; - public string name; - public string addr; - public byte type; //1 function 2 table - #endregion - - #region pool - private static ObjectPool m_pool = new ObjectPool(32); - public static LuaRefInfo Create() - { - LuaRefInfo r = m_pool.GetObject(); - return r; - } - - public static LuaRefInfo Create(byte cmd, string name, string addr, byte type) - { - LuaRefInfo r = m_pool.GetObject(); - r.cmd = cmd; - r.name = name; - r.addr = addr; - r.type = type; - return r; - } - - public override void Restore() - { - m_pool.Store(this); - } - - public LuaRefInfo Clone() - { - LuaRefInfo result = new LuaRefInfo(); - - result.cmd = this.cmd; - result.frameCount = this.frameCount; - result.name = this.name; - result.addr = this.addr; - result.type = this.type; - - return result; - } - #endregion - } - public class LuaDiffInfo : NetBase { #region field @@ -227,505 +179,6 @@ public class SampleData public static float power; } - public class Sample : NetBase - { - public int currentLuaMemory; - public int currentMonoMemory; - public long currentTime; - - public int calls; - public int frameCount; - public float fps; - public uint pss; - public float power; - - public int costLuaGC; - public int costMonoGC; - public string name; - public int costTime; - public Sample _father; - public MList childs = new MList(16); - public string captureUrl = null; - private string _fullName; - public bool needShow = false; - - public bool isCopy = false; - public long copySelfLuaGC = -1; - public long selfLuaGC - { - get - { - if (isCopy) return copySelfLuaGC; - long result = costLuaGC; - for (int i = 0, imax = childs.Count; i < imax; i++) - { - var item = childs[i]; - result -= item.costLuaGC; - } - return Math.Max(result, 0); - } - } - - public long copySelfMonoGC = -1; - - public long selfMonoGC - { - get - { - if (isCopy) return copySelfMonoGC; - long result = costMonoGC; - for (int i = 0, imax = childs.Count; i < imax; i++) - { - var item = childs[i]; - result -= item.costMonoGC; - } - - return Math.Max(result, 0); - } - } - - public int copySelfCostTime = -1; - public int selfCostTime - { - get - { - if (isCopy) return copySelfCostTime; - int result = costTime; - for (int i = 0, imax = childs.Count; i < imax; i++) - { - var item = childs[i]; - result -= item.costTime; - } - - return Math.Max(result, 0); - } - } - - public bool CheckSampleValid() - { - bool result = false; - do - { - if (needShow) - { - result = true; - break; - } - var setting = LuaDeepProfilerSetting.Instance; - if (setting != null && !setting.discardInvalid) - { - result = true; - break; - } - - if (costLuaGC != 0) - { - result = true; - break; - } - - if (costMonoGC != 0) - { - result = true; - break; - } - - if (costTime > 10000) - { - result = true; - break; - } - - } while (false); - - - return result; - } - - #region property - public string fullName - { - get - { - if (_father == null) return name; - - if (_fullName == null) - { - Dictionary childDict; - if (!m_fullNamePool.TryGetValue(_father.fullName, out childDict)) - { - childDict = new Dictionary(); - m_fullNamePool.Add(_father.fullName, childDict); - } - - if (!childDict.TryGetValue(name, out _fullName)) - { - string value = name; - var f = _father; - while (f != null) - { - value = f.name + value; - f = f.fahter; - } - _fullName = value; - childDict[name] = string.Intern(_fullName); - } - - return _fullName; - } - else - { - return _fullName; - } - } - } - - public Sample fahter - { - set - { - if (value != null) - { - bool needAdd = true; - var childList = value.childs; - for (int i = 0,imax = childList.Count;i> m_fullNamePool = new Dictionary>(); - public static ObjectPool samplePool = new ObjectPool(8192); - public static Sample Create() - { - Sample s = samplePool.GetObject(); - return s; - } - - public static Sample Create(long time, int memory, string name) - { - Sample s = samplePool.GetObject(); - - s.calls = 1; - s.currentTime = time; - s.currentLuaMemory = memory; - s.currentMonoMemory = (int)GC.GetTotalMemory(false); - s.frameCount = SampleData.frameCount; - s.fps = SampleData.fps; - s.pss = SampleData.pss; - s.power = SampleData.power; - s.costLuaGC = 0; - s.costMonoGC = 0; - s.name = name; - s.costTime = 0; - s._father = null; - s.childs.Clear(); - s.captureUrl = null; - s._fullName = null; - s.needShow = false; - - return s; - } - - public override void Restore() - { - lock (this) - { - for (int i = 0, imax = childs.Count; i < imax; i++) - { - childs[i].Restore(); - } - _fullName = null; - childs.Clear(); - samplePool.Store(this); - } - } - #endregion - - #region method - public void AddSample(Sample s) - { - calls += s.calls; - costLuaGC += Math.Max(s.costLuaGC, 0); - costMonoGC += Math.Max(s.costMonoGC, 0); - costTime += s.costTime; - for (int i = s.childs.Count - 1; i >= 0; i--) - { - var item = s.childs[i]; - item.fahter = this; - if (item.fahter != s) - { - s.childs.RemoveAt(i); - } - } - } - public static string Capture() - { - if (string.IsNullOrEmpty(capturePath)) capturePath = "capture" + DateTime.Now.Ticks.ToString(); - - Directory.CreateDirectory(capturePath); - - string result = capturePath + "/" + Time.frameCount.ToString() + ".png"; -#if UNITY_2017_1_OR_NEWER - ScreenCapture.CaptureScreenshot(result, 0); -#else - Application.CaptureScreenshot(result, 0); -#endif - return result; - } - - public Sample Clone() - { - Sample s = new Sample(); - - s.calls = calls; - s.frameCount = frameCount; - s.fps = fps; - s.pss = pss; - s.power = power; - s.costMonoGC = costMonoGC; - s.costLuaGC = costLuaGC; - s.name = name; - s.costTime = costTime; - - int childCount = childs.Count; - for (int i = 0; i < childCount; i++) - { - Sample child = childs[i].Clone(); - child.fahter = s; - } - - s.currentLuaMemory = currentLuaMemory; - s.currentMonoMemory = currentMonoMemory; - s.currentTime = currentTime; - s.captureUrl = captureUrl; - return s; - } - #endregion - - #region 序列化 - public static void SerializeList(List samples, string path) - { - FileStream fs = new FileStream(path, FileMode.CreateNew, FileAccess.Write); - BinaryWriter b = new BinaryWriter(fs); -#if UNITY_EDITOR - UnityEditor.EditorUtility.ClearProgressBar(); -#endif - b.Write(samples.Count); - for (int i = 0, imax = samples.Count; i < imax; i++) - { - Sample s = samples[i]; -#if UNITY_EDITOR - UnityEditor.EditorUtility.DisplayProgressBar("serialize profiler data", "serialize " + s.name, (float)i / (float)imax); -#endif - byte[] datas = s.Serialize(); - b.Write(datas.Length); - b.Write(datas); - } - b.Close(); -#if UNITY_EDITOR - UnityEditor.EditorUtility.ClearProgressBar(); -#endif - } - - public static List DeserializeList(string path) - { - FileStream ms = new FileStream(path, FileMode.Open, FileAccess.Read); - BinaryReader b = new BinaryReader(ms); - - int count = b.ReadInt32(); - List result = new List(count); - - for (int i = 0, imax = count; i < imax; i++) - { - int len = b.ReadInt32(); - Sample s = Deserialize(b.ReadBytes(len)); - result.Add(s); - } - b.Close(); - - return result; - } - - public byte[] Serialize() - { - byte[] result = null; - MemoryStream ms = new MemoryStream(); - BinaryWriter b = new BinaryWriter(ms); - - b.Write(calls); - b.Write(frameCount); - b.Write(fps); - b.Write(pss); - b.Write(power); - b.Write(costLuaGC); - b.Write(costMonoGC); - - byte[] datas = Encoding.UTF8.GetBytes(name); - b.Write(datas.Length); - b.Write(datas); - - b.Write(costTime); - - b.Write(childs.Count); - for (int i = 0, imax = childs.Count; i < imax; i++) - { - datas = childs[i].Serialize(); - b.Write(datas.Length); - b.Write(datas); - } - - if (string.IsNullOrEmpty(captureUrl) || !File.Exists(captureUrl)) - { - b.Write(false); - } - else - { - b.Write(true); - datas = Encoding.UTF8.GetBytes(captureUrl); - b.Write(datas.Length); - b.Write(datas); - - //写入图片数据 - datas = File.ReadAllBytes(captureUrl); - b.Write(datas.Length); - b.Write(datas); - } - b.Write(currentLuaMemory); - b.Write(currentMonoMemory); - - result = ms.ToArray(); - b.Close(); - - return result; - } - - public static Sample Deserialize(byte[] data) - { - MemoryStream ms = new MemoryStream(data); - BinaryReader b = new BinaryReader(ms); - - return Deserialize(b); - } - - public static Sample Deserialize(BinaryReader b) - { - Sample s = new Sample(); - s.calls = b.ReadInt32(); - s.frameCount = b.ReadInt32(); - s.fps = b.ReadSingle(); - s.pss = b.ReadUInt32(); - s.power = b.ReadSingle(); - s.costLuaGC = b.ReadInt32(); - s.costMonoGC = b.ReadInt32(); - - int len = b.ReadInt32(); - byte[] datas = b.ReadBytes(len); - s.name = Encoding.UTF8.GetString(datas); - s.costTime = b.ReadInt32(); - - int childCount = b.ReadInt32(); - for (int i = 0; i < childCount; i++) - { - len = b.ReadInt32(); - datas = b.ReadBytes(len); - Sample child = Deserialize(datas); - child.fahter = s; - } - - bool hasCapture = b.ReadBoolean(); - if (hasCapture) - { - len = b.ReadInt32(); - datas = b.ReadBytes(len); - s.captureUrl = Encoding.UTF8.GetString(datas); - - if (!File.Exists(s.captureUrl)) - { - string dir = Path.GetDirectoryName(s.captureUrl); - if (!Directory.Exists(dir)) - { - Directory.CreateDirectory(dir); - } - - len = b.ReadInt32(); - datas = b.ReadBytes(len); - //写入图片数据 - File.WriteAllBytes(s.captureUrl, datas); - } - - } - s.currentLuaMemory = b.ReadInt32(); - s.currentMonoMemory = b.ReadInt32(); - - int lua_gc = 0; - int mono_gc = 0; - for (int i = 0, imax = s.childs.Count; i < imax; i++) - { - var item = s.childs[i]; - lua_gc += item.costLuaGC; - mono_gc += item.costMonoGC; - } - s.costLuaGC = Math.Max(lua_gc, s.costLuaGC); - s.costMonoGC = Math.Max(mono_gc, s.costMonoGC); - - b.Close(); - - return s; - - } - - public static void DeleteFiles(string str) - { - DirectoryInfo fatherFolder = new DirectoryInfo(str); - //删除当前文件夹内文件 - FileInfo[] files = fatherFolder.GetFiles(); - foreach (FileInfo file in files) - { - string fileName = file.Name; - try - { - File.Delete(file.FullName); - } - catch (Exception ex) - { - Debug.LogError(ex); - } - } - //递归删除子文件夹内文件 - foreach (DirectoryInfo childFolder in fatherFolder.GetDirectories()) - { - DeleteFiles(childFolder.FullName); - } - Directory.Delete(str, true); - } - #endregion - } - } #endif diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/Driver/Hook/AndroidHook/AndroidNativeHooker.cs b/LuaProfiler/example/Assets/LuaProfiler/Core/Driver/Hook/AndroidHook/AndroidNativeHooker.cs index 630f7487..42a3e2af 100644 --- a/LuaProfiler/example/Assets/LuaProfiler/Core/Driver/Hook/AndroidHook/AndroidNativeHooker.cs +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/Driver/Hook/AndroidHook/AndroidNativeHooker.cs @@ -28,7 +28,7 @@ public IntPtr GetProcAddress(string InPath, string InProcName) public IntPtr GetProcAddressByHandle(IntPtr InModule, string InProcName) { - return dlsym(RTLD_DEFAULT, InProcName); + return dlsym(InModule, InProcName); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] @@ -52,17 +52,19 @@ public void HookLoadLibrary(Action callBack) _callBack = callBack; } } + + private static bool isLoadLuaSo = false; [MonoPInvokeCallbackAttribute(typeof(dlopenfun))] static IntPtr dlopen_replace(string libfile, int flag) { var ret = dlopenF(libfile, flag); - if (dlsym(RTLD_DEFAULT, "luaL_newstate") != IntPtr.Zero) + if (!isLoadLuaSo && dlsym(ret, "luaL_newstate") != IntPtr.Zero) { - _callBack?.Invoke(ret); + isLoadLuaSo = true; + UnityEngine.Debug.LogError("_callBack HookLoadLibrary"); + _callBack.Invoke(ret); } - hooker.Uninstall(); - return ret; } @@ -76,12 +78,13 @@ public unsafe class AndroidNativeHooker : INativeHooker { public Delegate GetProxyFun(Type t) { + UnityEngine.Debug.LogError($"_proxyFun:{(IntPtr)_proxyFun}"); if (_proxyFun == null) return null; - return Marshal.GetDelegateForFunctionPointer((IntPtr)(*_proxyFun), t); + return Marshal.GetDelegateForFunctionPointer((IntPtr)_proxyFun, t); } public bool isHooked { get; set; } - private void** _proxyFun = null; + private void* _proxyFun = null; private IntPtr _targetPtr = IntPtr.Zero; private IntPtr _replacementPtr = IntPtr.Zero; private IntPtr stub = IntPtr.Zero; @@ -105,7 +108,10 @@ public void Init(IntPtr targetPtr, IntPtr replacementPtr) public void Install() { - stub = shadowhook_hook_func_addr( _targetPtr, _replacementPtr, _proxyFun); + fixed (void** addr = &_proxyFun) + { + stub = shadowhook_hook_func_addr( _targetPtr, _replacementPtr, addr); + } } public void Uninstall() @@ -114,6 +120,7 @@ public void Uninstall() { shadowhook_unhook(stub); _proxyFun = null; + stub = IntPtr.Zero; } } } diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/Driver/Hook/WindowsHook/WindowsNativeHooker.cs b/LuaProfiler/example/Assets/LuaProfiler/Core/Driver/Hook/WindowsHook/WindowsNativeHooker.cs index 5cf7616f..453c9289 100644 --- a/LuaProfiler/example/Assets/LuaProfiler/Core/Driver/Hook/WindowsHook/WindowsNativeHooker.cs +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/Driver/Hook/WindowsHook/WindowsNativeHooker.cs @@ -52,8 +52,8 @@ public void HookLoadLibrary(Action callBack) if (GetProcAddressByHandle(ret, "luaL_newstate") != IntPtr.Zero) { callBack(ret); + hooker.Uninstall(); } - hooker.Uninstall(); return ret; }); hooker = new WindowsNativeHooker(); diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/Driver/LuaDLL.cs b/LuaProfiler/example/Assets/LuaProfiler/Core/Driver/LuaDLL.cs index b95c362d..de3d3c94 100644 --- a/LuaProfiler/example/Assets/LuaProfiler/Core/Driver/LuaDLL.cs +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/Driver/LuaDLL.cs @@ -315,6 +315,16 @@ public static void luaL_initlibs(IntPtr luaState) } } + public static unsafe IntPtr ConvertByteArrayToPtr(byte[] buff) + { + IntPtr intPtr; + fixed (byte* b = buff) + { + intPtr = (IntPtr)b; + } + return intPtr; + } + #region script const string env_script = @" local function getfunction(level) @@ -360,7 +370,7 @@ elseif not name then public static int luaL_loadbufferUnHook(IntPtr luaState, byte[] buff, IntPtr size, string name) { - IntPtr intPtr = NativeUtility.ConvertByteArrayToPtr(buff); + IntPtr intPtr = ConvertByteArrayToPtr(buff); int result; if (LUA_VERSION > 510) { @@ -448,44 +458,46 @@ public static void Uninstall() } private static bool isBinding = false; - public static void BindEasyHook() + public static void BindEasyHook(IntPtr module) { lock (m_Lock) { if (m_hooked) return; if(isBinding) return; isBinding = true; - string moduleName = CheckHasLuaDLL(); + if (module == IntPtr.Zero) + { + module = CheckHasLuaDLL(); + } + isBinding = false; - if (m_hooked) return; - if (string.IsNullOrEmpty(moduleName)) + if (module == IntPtr.Zero) { - HookLoadLibrary(); return; } - if (GetProcAddress(moduleName, "luaopen_jit") != IntPtr.Zero) + if (GetProcAddress(module, "luaopen_jit") != IntPtr.Zero) { IS_LUA_JIT = true; } - if (GetProcAddress(moduleName, "lua_rotate") != IntPtr.Zero) + if (GetProcAddress(module, "lua_rotate") != IntPtr.Zero) { LUA_VERSION = 530; // LUA_REGISTRYINDEX == LUAI_FIRSTPSEUDOIDX with LUAI_FIRSTPSEUDOIDX == (-LUAI_MAXSTACK - 1000) with LUAI_MAXSTACK == 15000 (for 32 bits build...) LuaIndexes.LUA_REGISTRYINDEX = -1001000; // starting with Lua 5.2, there is no longer a LUA_GLOBALSINDEX pseudo-index. Instead the global table is stored in the registry at LUA_RIDX_GLOBALS LuaIndexes.LUA_GLOBALSINDEX = 2; - IntPtr handle = GetProcAddress(moduleName, "lua_rotate"); + IntPtr handle = GetProcAddress(module, "lua_rotate"); lua_rotate = (lua_rotate_fun)Marshal.GetDelegateForFunctionPointer(handle, typeof(lua_rotate_fun)); } - else if (GetProcAddress(moduleName, "lua_open") != IntPtr.Zero) + else if (GetProcAddress(module, "lua_open") != IntPtr.Zero) { LUA_VERSION = 500; LuaIndexes.LUA_REGISTRYINDEX = -10000; LuaIndexes.LUA_GLOBALSINDEX = -10001; } - else if (GetProcAddress(moduleName, "lua_callk") != IntPtr.Zero) + else if (GetProcAddress(module, "lua_callk") != IntPtr.Zero) { LUA_VERSION = 520; // LUA_REGISTRYINDEX == LUAI_FIRSTPSEUDOIDX with LUAI_FIRSTPSEUDOIDX == (-LUAI_MAXSTACK - 1000) with LUAI_MAXSTACK == 15000 (for 32 bits build...) @@ -493,7 +505,7 @@ public static void BindEasyHook() // starting with Lua 5.2, there is no longer a LUA_GLOBALSINDEX pseudo-index. Instead the global table is stored in the registry at LUA_RIDX_GLOBALS LuaIndexes.LUA_GLOBALSINDEX = 2; } - else if (GetProcAddress(moduleName, "lua_gettop") != IntPtr.Zero) // should be ok for any version + else if (GetProcAddress(module, "lua_gettop") != IntPtr.Zero) // should be ok for any version { LUA_VERSION = 510; LuaIndexes.LUA_REGISTRYINDEX = -10000; @@ -509,7 +521,7 @@ public static void BindEasyHook() if (luaL_newstate_hook == null) { - IntPtr handle = GetProcAddress(moduleName, "luaL_newstate"); + IntPtr handle = GetProcAddress(module, "luaL_newstate"); luaL_newstate_fun luaFun = new luaL_newstate_fun(luaL_newstate_replace); INativeHooker hooker = nativeUtil.CreateHook(); hooker.Init(handle, Marshal.GetFunctionPointerForDelegate(luaFun)); @@ -520,7 +532,7 @@ public static void BindEasyHook() if (lua_close_hook == null) { - IntPtr handle = GetProcAddress(moduleName, "lua_close"); + IntPtr handle = GetProcAddress(module, "lua_close"); lua_close_fun luaFun = new lua_close_fun(lua_close_replace); INativeHooker hooker = nativeUtil.CreateHook(); hooker.Init(handle, Marshal.GetFunctionPointerForDelegate(luaFun)); @@ -531,7 +543,7 @@ public static void BindEasyHook() if (lua_gc_hook == null) { - IntPtr handle = GetProcAddress(moduleName, "lua_gc"); + IntPtr handle = GetProcAddress(module, "lua_gc"); lua_gc_fun luaFun = new lua_gc_fun(lua_gc_replace); INativeHooker hooker = nativeUtil.CreateHook(); hooker.Init(handle, Marshal.GetFunctionPointerForDelegate(luaFun)); @@ -552,7 +564,7 @@ public static void BindEasyHook() if (luaL_ref_hook == null) { - IntPtr handle = GetProcAddress(moduleName, "luaL_ref"); + IntPtr handle = GetProcAddress(module, "luaL_ref"); luaL_ref_fun luaFun = new luaL_ref_fun(luaL_ref_replace); INativeHooker hooker = nativeUtil.CreateHook(); hooker.Init(handle, Marshal.GetFunctionPointerForDelegate(luaFun)); @@ -563,7 +575,7 @@ public static void BindEasyHook() if (luaL_unref_hook == null) { - IntPtr handle = GetProcAddress(moduleName, "luaL_unref"); + IntPtr handle = GetProcAddress(module, "luaL_unref"); luaL_unref_fun luaFun = new luaL_unref_fun(luaL_unref_replace); INativeHooker hooker = nativeUtil.CreateHook(); hooker.Init(handle, Marshal.GetFunctionPointerForDelegate(luaFun)); @@ -588,7 +600,7 @@ public static void BindEasyHook() { if (LUA_VERSION > 510) { - IntPtr handle = GetProcAddress(moduleName, "luaL_loadbufferx"); + IntPtr handle = GetProcAddress(module, "luaL_loadbufferx"); luaL_loadbufferx_fun luaFun = new luaL_loadbufferx_fun(luaL_loadbufferx_replace); INativeHooker hooker = nativeUtil.CreateHook(); hooker.Init(handle, Marshal.GetFunctionPointerForDelegate(luaFun)); @@ -598,7 +610,7 @@ public static void BindEasyHook() } else { - IntPtr handle = GetProcAddress(moduleName, "luaL_loadbuffer"); + IntPtr handle = GetProcAddress(module, "luaL_loadbuffer"); luaL_loadbuffer_fun luaFun = new luaL_loadbuffer_fun(luaL_loadbuffer_replace); INativeHooker hooker = nativeUtil.CreateHook(); hooker.Init(handle, Marshal.GetFunctionPointerForDelegate(luaFun)); @@ -610,7 +622,7 @@ public static void BindEasyHook() if (luaL_openlibs_hook == null) { - IntPtr handle = GetProcAddress(moduleName, "luaL_openlibs"); + IntPtr handle = GetProcAddress(module, "luaL_openlibs"); luaL_openlibs_fun luaFun = new luaL_openlibs_fun(luaL_openlibs_replace); INativeHooker hooker = nativeUtil.CreateHook(); hooker.Init(handle, Marshal.GetFunctionPointerForDelegate(luaFun)); @@ -624,7 +636,7 @@ public static void BindEasyHook() if (LUA_VERSION > 510) { { - IntPtr handle = GetProcAddress(moduleName, "lua_getglobal"); + IntPtr handle = GetProcAddress(module, "lua_getglobal"); if (handle != IntPtr.Zero) { lua_getglobal = @@ -633,7 +645,7 @@ public static void BindEasyHook() } } { - IntPtr handle = GetProcAddress(moduleName, "lua_setglobal"); + IntPtr handle = GetProcAddress(module, "lua_setglobal"); if (handle != IntPtr.Zero) { lua_setglobal = @@ -642,7 +654,7 @@ public static void BindEasyHook() } } { - IntPtr handle = GetProcAddress(moduleName, "lua_rawlen"); + IntPtr handle = GetProcAddress(module, "lua_rawlen"); if (handle != IntPtr.Zero) { lua_objlen = @@ -655,7 +667,7 @@ public static void BindEasyHook() lua_getglobal = new lua_getglobal_fun(lua_getglobal51); lua_setglobal = new lua_setglobal_fun(lua_setglobal51); { - IntPtr handle = GetProcAddress(moduleName, "lua_objlen"); + IntPtr handle = GetProcAddress(module, "lua_objlen"); if (handle != IntPtr.Zero) { lua_objlen = @@ -665,7 +677,7 @@ public static void BindEasyHook() } { - IntPtr handle = GetProcAddress(moduleName, "lua_gettop"); + IntPtr handle = GetProcAddress(module, "lua_gettop"); if (handle != IntPtr.Zero) { lua_gettop = @@ -674,7 +686,7 @@ public static void BindEasyHook() } { - IntPtr handle = GetProcAddress(moduleName, "lua_settop"); + IntPtr handle = GetProcAddress(module, "lua_settop"); if (handle != IntPtr.Zero) { lua_settop = @@ -683,7 +695,7 @@ public static void BindEasyHook() } { - IntPtr handle = GetProcAddress(moduleName, "lua_pushvalue"); + IntPtr handle = GetProcAddress(module, "lua_pushvalue"); if (handle != IntPtr.Zero) { lua_pushvalue = @@ -692,7 +704,7 @@ public static void BindEasyHook() } { - IntPtr handle = GetProcAddress(moduleName, "lua_remove"); + IntPtr handle = GetProcAddress(module, "lua_remove"); if (handle != IntPtr.Zero) { lua_remove = @@ -705,7 +717,7 @@ public static void BindEasyHook() } { - IntPtr handle = GetProcAddress(moduleName, "lua_insert"); + IntPtr handle = GetProcAddress(module, "lua_insert"); if (handle != IntPtr.Zero) { lua_insert = @@ -718,7 +730,7 @@ public static void BindEasyHook() } { - IntPtr handle = GetProcAddress(moduleName, "lua_type"); + IntPtr handle = GetProcAddress(module, "lua_type"); if (handle != IntPtr.Zero) { lua_type = (lua_type_fun)Marshal.GetDelegateForFunctionPointer(handle, typeof(lua_type_fun)); @@ -728,7 +740,7 @@ public static void BindEasyHook() { if (LUA_VERSION >= 520) { - IntPtr handle = GetProcAddress(moduleName, "lua_tonumberx"); + IntPtr handle = GetProcAddress(module, "lua_tonumberx"); if (handle != IntPtr.Zero) { var tonumx = @@ -739,7 +751,7 @@ public static void BindEasyHook() } else { - IntPtr handle = GetProcAddress(moduleName, "lua_tonumber"); + IntPtr handle = GetProcAddress(module, "lua_tonumber"); if (handle != IntPtr.Zero) { lua_tonumber = @@ -750,7 +762,7 @@ public static void BindEasyHook() } { - IntPtr handle = GetProcAddress(moduleName, "lua_pushnil"); + IntPtr handle = GetProcAddress(module, "lua_pushnil"); if (handle != IntPtr.Zero) { lua_pushnil = @@ -759,7 +771,7 @@ public static void BindEasyHook() } { - IntPtr handle = GetProcAddress(moduleName, "lua_pushnumber"); + IntPtr handle = GetProcAddress(module, "lua_pushnumber"); if (handle != IntPtr.Zero) { lua_pushnumber = @@ -769,7 +781,7 @@ public static void BindEasyHook() } { - IntPtr handle = GetProcAddress(moduleName, "lua_pushstring"); + IntPtr handle = GetProcAddress(module, "lua_pushstring"); if (handle != IntPtr.Zero) { lua_pushstring = @@ -779,7 +791,7 @@ public static void BindEasyHook() } { - IntPtr handle = GetProcAddress(moduleName, "lua_pushboolean"); + IntPtr handle = GetProcAddress(module, "lua_pushboolean"); if (handle != IntPtr.Zero) { lua_pushboolean = @@ -789,7 +801,7 @@ public static void BindEasyHook() } { - IntPtr handle = GetProcAddress(moduleName, "lua_getfield"); + IntPtr handle = GetProcAddress(module, "lua_getfield"); if (handle != IntPtr.Zero) { lua_getfield = @@ -798,7 +810,7 @@ public static void BindEasyHook() } { - IntPtr handle = GetProcAddress(moduleName, "lua_rawget"); + IntPtr handle = GetProcAddress(module, "lua_rawget"); if (handle != IntPtr.Zero) { lua_rawget = @@ -807,7 +819,7 @@ public static void BindEasyHook() } { - IntPtr handle = GetProcAddress(moduleName, "lua_rawgeti"); + IntPtr handle = GetProcAddress(module, "lua_rawgeti"); if (handle != IntPtr.Zero) { lua_rawgeti = @@ -816,7 +828,7 @@ public static void BindEasyHook() } { - IntPtr handle = GetProcAddress(moduleName, "lua_createtable"); + IntPtr handle = GetProcAddress(module, "lua_createtable"); if (handle != IntPtr.Zero) { lua_createtable = @@ -826,7 +838,7 @@ public static void BindEasyHook() } { - IntPtr handle = GetProcAddress(moduleName, "lua_setfield"); + IntPtr handle = GetProcAddress(module, "lua_setfield"); if (handle != IntPtr.Zero) { lua_setfield = @@ -835,7 +847,7 @@ public static void BindEasyHook() } { - IntPtr handle = GetProcAddress(moduleName, "lua_rawset"); + IntPtr handle = GetProcAddress(module, "lua_rawset"); if (handle != IntPtr.Zero) { lua_rawset = @@ -846,7 +858,7 @@ public static void BindEasyHook() { if (LUA_VERSION >= 520) { - IntPtr handle = GetProcAddress(moduleName, "lua_pcallk"); + IntPtr handle = GetProcAddress(module, "lua_pcallk"); if (handle != IntPtr.Zero) { lua_pcallk = @@ -859,7 +871,7 @@ public static void BindEasyHook() } else { - IntPtr handle = GetProcAddress(moduleName, "lua_pcall"); + IntPtr handle = GetProcAddress(module, "lua_pcall"); if (handle != IntPtr.Zero) { lua_pcall = (lua_pcall_fun)Marshal.GetDelegateForFunctionPointer(handle, @@ -871,7 +883,7 @@ public static void BindEasyHook() { if (LUA_VERSION >= 520) { - IntPtr handle = GetProcAddress(moduleName, "lua_callk"); + IntPtr handle = GetProcAddress(module, "lua_callk"); if (handle != IntPtr.Zero) { lua_callk = @@ -884,7 +896,7 @@ public static void BindEasyHook() } else { - IntPtr handle = GetProcAddress(moduleName, "lua_call"); + IntPtr handle = GetProcAddress(module, "lua_call"); if (handle != IntPtr.Zero) { lua_call = @@ -894,7 +906,7 @@ public static void BindEasyHook() } { - IntPtr handle = GetProcAddress(moduleName, "lua_next"); + IntPtr handle = GetProcAddress(module, "lua_next"); if (handle != IntPtr.Zero) { lua_next = (lua_next_fun)Marshal.GetDelegateForFunctionPointer(handle, typeof(lua_next_fun)); @@ -902,7 +914,7 @@ public static void BindEasyHook() } { - IntPtr handle = GetProcAddress(moduleName, "lua_tolstring"); + IntPtr handle = GetProcAddress(module, "lua_tolstring"); if (handle != IntPtr.Zero) { lua_tolstring = @@ -911,7 +923,7 @@ public static void BindEasyHook() } { - IntPtr handle = GetProcAddress(moduleName, "lua_pushcclosure"); + IntPtr handle = GetProcAddress(module, "lua_pushcclosure"); if (handle != IntPtr.Zero) { lua_pushcclosure = @@ -927,43 +939,50 @@ public static void BindEasyHook() public static void HookLoadLibrary() { + IntPtr module = CheckHasLuaDLL(); + if (module != IntPtr.Zero) + { + return; + } + nativeUtil.HookLoadLibrary((ret) => { if (!m_hooked) { - if (nativeUtil.GetProcAddressByHandle(ret, "luaL_newstate") != IntPtr.Zero) - { - BindEasyHook(); - } + UnityEngine.Debug.LogError("HookLoadLibrary"); + BindEasyHook(ret); } }); } - private static IntPtr GetProcAddress(string moduleName, string funName) + private static IntPtr GetProcAddress(IntPtr module, string funName) { IntPtr result = IntPtr.Zero; try { - result = nativeUtil.GetProcAddress(moduleName, funName); + result = nativeUtil.GetProcAddressByHandle(module, funName); } catch{} return result; } - private static string CheckHasLuaDLL() + private static IntPtr CheckHasLuaDLL() { - string result = null; + IntPtr result = IntPtr.Zero; +#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN var process = Process.GetCurrentProcess(); var modules = process.Modules; foreach (ProcessModule item in modules) { - string moduleName = item.ModuleName; - if (GetProcAddress(moduleName, "luaL_newstate") != IntPtr.Zero) + result = GetProcAddress(item.BaseAddress, "luaL_newstate"); + if (result != IntPtr.Zero) { - result = moduleName; - break; + return item.BaseAddress; } } +#else + result = GetProcAddress(IntPtr.Zero, "luaL_newstate"); +#endif return result; } @@ -1086,7 +1105,7 @@ public static int luaL_loadbufferx_replace(IntPtr luaState, IntPtr buff, IntPtr name = "chunk"; } buffer = LuaHook.Hookloadbuffer(luaState, buffer, name); - buff = NativeUtility.ConvertByteArrayToPtr(buffer); + buff = ConvertByteArrayToPtr(buffer); size = (IntPtr)buffer.Length; } return luaL_loadbufferx(luaState, buff, size, name, mode); @@ -1153,7 +1172,7 @@ public static int luaL_loadbuffer_replace(IntPtr luaState, IntPtr buff, IntPtr s name = "chunk"; } buffer = LuaHook.Hookloadbuffer(luaState, buffer, name); - buff = NativeUtility.ConvertByteArrayToPtr(buffer); + buff = ConvertByteArrayToPtr(buffer); size = (IntPtr)buffer.Length; } return luaL_loadbuffer(luaState, buff, size, name); diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/Driver/LuaProfiler.cs b/LuaProfiler/example/Assets/LuaProfiler/Core/Driver/LuaProfiler.cs index dc5d4257..375a5aff 100644 --- a/LuaProfiler/example/Assets/LuaProfiler/Core/Driver/LuaProfiler.cs +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/Driver/LuaProfiler.cs @@ -168,8 +168,7 @@ public static void BeginSample(IntPtr luaState, string name, bool needShow = fal m_currentFrame = frameCount; PopAllSampleWhenLateUpdate(luaState); } - Sample sample = Sample.Create(getcurrentTime, (int)memoryCount, name); - sample.needShow = needShow; + Sample sample = Sample.Create(getcurrentTime, (int)memoryCount, name); beginSampleMemoryStack.Push(sample); } catch(Exception e) @@ -227,7 +226,7 @@ public static void EndSample(IntPtr luaState) if (setting == null) return; if (!setting.isLocal) { - NetWorkClient.SendMessage(sample); + NetWorkMgr.SendCmd(sample); } else if(m_onReceiveSample != null) { @@ -248,7 +247,7 @@ public static void SendFrameSample() Sample sample = Sample.Create(getcurrentTime, (int)memoryCount, ""); if (!setting.isLocal) { - NetWorkClient.SendMessage(sample); + NetWorkMgr.SendCmd(sample); } else if (m_onReceiveSample != null) { @@ -288,7 +287,7 @@ public static void SendAddRef(string funName, string funAddr, byte type) var setting = LuaDeepProfilerSetting.Instance; if (!setting.isLocal) { - NetWorkClient.SendMessage(refInfo); + NetWorkMgr.SendCmd(refInfo); } else if (m_onReceiveRef != null) { @@ -327,7 +326,7 @@ public static void SendRemoveRef(string funName, string funAddr, byte type) var setting = LuaDeepProfilerSetting.Instance; if (!setting.isLocal) { - NetWorkClient.SendMessage(refInfo); + NetWorkMgr.SendCmd(refInfo); } else if (m_onReceiveRef != null) { diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/LuaHookSetup.cs b/LuaProfiler/example/Assets/LuaProfiler/Core/LuaHookSetup.cs index 2a86d7ac..715aa63f 100644 --- a/LuaProfiler/example/Assets/LuaProfiler/Core/LuaHookSetup.cs +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/LuaHookSetup.cs @@ -79,23 +79,16 @@ public static void OnStartGame() isInite = true; setting = LuaDeepProfilerSetting.Instance; LuaProfiler.mainThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId; - -#if UNITY_EDITOR - if (setting.isDeepLuaProfiler) + + if (setting.isDeepLuaProfiler || !setting.isLocal) { LuaDLL.Uninstall(); LuaDLL.HookLoadLibrary(); - LuaDLL.BindEasyHook(); + LuaDLL.BindEasyHook(IntPtr.Zero); //LuaDLL.Install(); - - if (setting.isCleanMode) - { - LuaProfilerPrecompileSetting.CompileLuaScript(false); - } } -#endif - if (setting.isDeepLuaProfiler || setting.isCleanMode) + if (setting.isDeepLuaProfiler || setting.isCleanMode || !setting.isLocal) { GameObject go = new GameObject(); go.name = "MikuLuaProfiler"; @@ -104,7 +97,7 @@ public static void OnStartGame() go.AddComponent(); if (!setting.isLocal) { - NetWorkClient.ConnectServer(setting.ip, setting.port); + NetWorkMgr.BeginListen("0.0.0.0", setting.port); } } } @@ -156,9 +149,8 @@ private void OnApplicationQuit() desotryCount = 0; Destroy(gameObject); UnityEditor.EditorApplication.update += WaitDestory; -#else - NetWorkClient.Close(); #endif + NetWorkMgr.Close(); } #if UNITY_EDITOR @@ -175,7 +167,7 @@ private void WaitDestory() } LuaDLL.Uninstall(); LuaProfiler.mainL = IntPtr.Zero; - NetWorkClient.Close(); + NetWorkMgr.Close(); desotryCount = 0; } } @@ -207,17 +199,6 @@ private void OnGUI() { var setting = HookLuaSetup.setting; - if (GUI.Button(new Rect(0, 0, 200, 100), "Connect")) - { - NetWorkClient.ConnectServer(setting.ip, setting.port); - } - - setting.ip = GUI.TextField(new Rect(210, 20, 200, 60), setting.ip); - - if (GUI.Button(new Rect(0, 110, 200, 100), "Disconnect")) - { - NetWorkClient.Close(); - } if (setting.discardInvalid) { if (GUI.Button(new Rect(0, 220, 200, 100), "ShowAll")) @@ -557,20 +538,20 @@ private static void SetTable(int refIndex, Dictionary> LuaDLL.lua_settop(L, oldTop); } - public static void DiffServer() - { - NetWorkClient.SendMessage(Diff()); - } - - public static void MarkRecordServer() - { - NetWorkClient.SendMessage(Record()); - } - - public static void MarkStaticServer() - { - NetWorkClient.SendMessage(Record()); - } + // public static void DiffServer() + // { + // NetWorkClient.SendMessage(Diff()); + // } + // + // public static void MarkRecordServer() + // { + // NetWorkClient.SendMessage(Record()); + // } + // + // public static void MarkStaticServer() + // { + // NetWorkClient.SendMessage(Record()); + // } public static LuaDiffInfo Diff() { diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/MBinaryReader.cs b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/MBinaryReader.cs new file mode 100644 index 00000000..6fb4b111 --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/MBinaryReader.cs @@ -0,0 +1,42 @@ +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace MikuLuaProfiler +{ + public class MBinaryReader : BinaryReader + { + public MBinaryReader(Stream input) : base(input) + { + } + + public MBinaryReader(Stream input, Encoding encoding) : base(input, encoding) + { + } + + public MBinaryReader(Stream input, Encoding encoding, bool leaveOpen) : base(input, encoding, leaveOpen) + { + } + + private Dictionary m_strCacheDict = new Dictionary(4096); + public override string ReadString() + { + string result = null; + + bool isRef = ReadBoolean(); + int index = ReadInt32(); + if (!isRef) + { + int len = ReadInt32(); + byte[] datas = ReadBytes(len); + result = string.Intern(Encoding.UTF8.GetString(datas)); + m_strCacheDict[index] = result; + } + else + { + result = m_strCacheDict[index]; + } + return result; + } + } +} \ No newline at end of file diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/MBinaryReader.cs.meta b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/MBinaryReader.cs.meta new file mode 100644 index 00000000..3912b7c6 --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/MBinaryReader.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 16db94328e2c472d8215f80ad7c9ef0c +timeCreated: 1669952711 \ No newline at end of file diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/MBinaryWriter.cs b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/MBinaryWriter.cs new file mode 100644 index 00000000..ba998719 --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/MBinaryWriter.cs @@ -0,0 +1,114 @@ +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace MikuLuaProfiler +{ + // Token: 0x02000002 RID: 2 + public sealed class MBinaryWriter : BinaryWriter + { + // Token: 0x06000001 RID: 1 RVA: 0x00002050 File Offset: 0x00000250 + public MBinaryWriter(Stream output) : base(output) + { + this._buffer = new byte[8]; + } + + // Token: 0x06000002 RID: 2 RVA: 0x00002068 File Offset: 0x00000268 + public unsafe override void Write(float value) + { + fixed (byte* ptr = _buffer) + { + *(float*)ptr = value; + } + this.OutStream.Write(this._buffer, 0, 4); + } + + // Token: 0x06000003 RID: 3 RVA: 0x000020AC File Offset: 0x000002AC + public unsafe override void Write(short value) + { + fixed (byte* ptr = _buffer) + { + *(short*)ptr = value; + } + this.OutStream.Write(this._buffer, 0, 2); + } + + // Token: 0x06000004 RID: 4 RVA: 0x000020F0 File Offset: 0x000002F0 + public unsafe override void Write(ushort value) + { + fixed (byte* ptr = _buffer) + { + *(ushort*)ptr = value; + } + this.OutStream.Write(this._buffer, 0, 2); + } + + // Token: 0x06000005 RID: 5 RVA: 0x00002134 File Offset: 0x00000334 + public unsafe override void Write(int value) + { + fixed (byte* ptr = _buffer) + { + *(int*)ptr = value; + } + this.OutStream.Write(this._buffer, 0, 4); + } + + // Token: 0x06000006 RID: 6 RVA: 0x00002178 File Offset: 0x00000378 + public unsafe override void Write(uint value) + { + fixed (byte* ptr = _buffer) + { + *(uint*)ptr = value; + } + this.OutStream.Write(this._buffer, 0, 4); + } + + // Token: 0x04000001 RID: 1 + private byte[] _buffer; + + #region string + private int m_key = 0; + private int GetUniqueKey() + { + return m_key++; + } + private Dictionary> m_strDict = new Dictionary>(8192); + private bool GetBytes(string s, out byte[] result, out int index) + { + bool ret = false; + KeyValuePair keyValuePair; + if (!m_strDict.TryGetValue(s, out keyValuePair)) + { + result = Encoding.UTF8.GetBytes(s); + index = GetUniqueKey(); + keyValuePair = new KeyValuePair(index, result); + m_strDict.Add(s, keyValuePair); + ret = false; + } + else + { + ret = true; + index = keyValuePair.Key; + result = keyValuePair.Value; + } + + return ret; + } + + public override void Write(string v) + { + byte[] datas; + int index = 0; + bool isRef = GetBytes(v, out datas, out index); + Write(isRef); + Write(index); + if (!isRef) + { + Write(datas.Length); + Write(datas); + } + } + + #endregion + } +} diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/NetWorkClient.cs.meta b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/MBinaryWriter.cs.meta similarity index 83% rename from LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/NetWorkClient.cs.meta rename to LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/MBinaryWriter.cs.meta index e0618535..9a944fcc 100644 --- a/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/NetWorkClient.cs.meta +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/MBinaryWriter.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 317e8d7f7830bf841b45bdf4d57f90b3 +guid: 6ac1bcbe8e1dcbe46bcf0a98a45e7bcb MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/NetWorkMgr.Server.cs b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/NetWorkMgr.Server.cs new file mode 100644 index 00000000..aa587173 --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/NetWorkMgr.Server.cs @@ -0,0 +1,113 @@ +#if !CSHARP_7_3_OR_NEWER +#define NET35 +#endif + +using System; +using System.Net; +using System.Net.Sockets; +using System.Threading; +using Debug = UnityEngine.Debug; + +namespace MikuLuaProfiler +{ + public static partial class NetWorkMgr + { + private static TcpListener tcpLister; + private static TcpClient tcpClient = null; + private static Thread acceptThread; + + public static event Action OnConnected; + public static event Action OnDisconnect; + + #region public + public static void BeginListen(string ip, int port) + { + if (tcpLister != null) return; + + AddListener(OnRecvDisconnect); + + IPAddress myIP = IPAddress.Parse(ip); + tcpLister = new TcpListener(myIP, port); + tcpLister.Start(); + acceptThread = new Thread(AcceptThread); + acceptThread.Name = "ProfilerAcceptThread"; + acceptThread.Start(); + } + + public static void Close() + { + RemoveAllListeners(); + isClose = true; + if (tcpLister != null) + { + tcpLister.Stop(); + tcpLister = null; + } + + if (acceptThread != null) + { + acceptThread.Abort(); + acceptThread = null; + } + } + + #endregion + + #region private + private static void AcceptThread() + { + Debug.Log("begin listerner"); + tcpClient = null; + + while (true) + { + try + { + if (tcpLister == null) break; + AcceptAClient(); + Thread.Sleep(100); + } + catch + { + break; + } + } + } + + private static void AcceptAClient() + { + var newTcpClient = tcpLister.AcceptTcpClient(); + Debug.Log("link start"); + + // 有新的连接,强制踢掉旧连接(不然偶尔会出现莫名挂掉无法连接) TODO: 支持多客户端并发连接 + _Close(); + tcpClient?.Close(); + receiveThread?.Join(); + sendThread?.Join(); + + tcpClient = newTcpClient; + lastBeatTime = curTime; + isClose = false; + + NetworkStream ns = tcpClient.GetStream(); + // 启动一个线程来接受请求 + receiveThread = new Thread(()=>DoReceiveMessage(ns)); + receiveThread.Name = "ProfilerReceiveMessage"; + receiveThread.Start(); + + // 启动一个线程来发送请求 + sendThread = new Thread(()=>DoSendMessage(ns)); + sendThread.Name = "ProfilerSendMessage"; + sendThread.Start(); + + if (OnConnected != null) + { + var clientCtx = tcpClient; + Action actionOnConnected = ()=> OnConnected(clientCtx); + lock(m_eventQueue) + m_eventQueue.Enqueue(actionOnConnected); + } + } + #endregion + } +} diff --git a/LuaProfiler/example/Assets/LuaProfiler/Editor/Window/ProfilerWin/NetWork/NetWorkServer.cs.meta b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/NetWorkMgr.Server.cs.meta similarity index 83% rename from LuaProfiler/example/Assets/LuaProfiler/Editor/Window/ProfilerWin/NetWork/NetWorkServer.cs.meta rename to LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/NetWorkMgr.Server.cs.meta index e8abbb43..fef186e4 100644 --- a/LuaProfiler/example/Assets/LuaProfiler/Editor/Window/ProfilerWin/NetWork/NetWorkServer.cs.meta +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/NetWorkMgr.Server.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 759d5f5c3ac2df342b07c1f445a1c71a +guid: d788f1be9de5f904aa266535f55a3448 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/NetWorkMgr.cs b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/NetWorkMgr.cs new file mode 100644 index 00000000..76148ab8 --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/NetWorkMgr.cs @@ -0,0 +1,302 @@ +#if !CSHARP_7_3_OR_NEWER +#define NET35 +#endif + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Threading; +using Debug = UnityEngine.Debug; + +namespace MikuLuaProfiler +{ + public static partial class NetWorkMgr + { + private static Thread receiveThread; + private static Thread sendThread; + private const int PACK_HEAD = 0x114514; + private const float HEART_BEAT_DELTA = float.MaxValue; // 永不超时 (原来是10分钟) + public static float lastBeatTime = 0; + public static float curTime = 0; + public static bool isClose = false; + private static Queue m_cmdQueue = new Queue(32); + private static Queue m_msgQueue = new Queue(32); + private static Queue m_eventQueue = new Queue(); + private static object m_CloseLock = 1; + + private static Dictionary receiveMsgDict = new Dictionary(); + + static NetWorkMgr() + { + var types = typeof(NetWorkMgr).Assembly.GetTypes(); + foreach (var t in types) + { + if (t.IsSubclassOf(typeof(PacketBase)) && !t.IsAbstract) + { + var attr = (PacketMsgAttribute)Attribute.GetCustomAttribute(t, typeof(PacketMsgAttribute)); + if (attr != null) + { + receiveMsgDict[(int)attr.msgHead] = t; + // PaperU3dProfiler.Log(t + "=" + attr.msgHead); + } + } + } + } + + public static void Update() + { + if (m_eventQueue.Count > 0) + { + lock (m_eventQueue) + { + while (m_eventQueue.Count > 0) + { + var msg = m_eventQueue.Dequeue(); + msg(); + } + } + } + + if (m_msgQueue.Count > 0) + { + lock (m_msgQueue) + { + while (m_msgQueue.Count > 0) + { + var msg = m_msgQueue.Dequeue(); + msg.OnRun(); + } + } + } + } + + #region public + + static void OnRecvDisconnect(PKGDisconnect pkg) + { + NetWorkMgr.Disconnect(); + } + + private static void _Close() + { + isClose = true; + if (tcpClient != null) + { + if (OnDisconnect != null) + { + var clientCtx = tcpClient; + tcpClient = null; + Action actionDisconnect = () => OnDisconnect(clientCtx); + lock(m_eventQueue) + m_eventQueue.Enqueue(actionDisconnect); + } + } + } + + public static void Disconnect() + { + isClose = true; + } + + public static void SendCmd(PacketBase cmd) + { + lock (m_cmdQueue) + { + m_cmdQueue.Enqueue(cmd); + } + } + #endregion + + #region private + + // 接受请求 + private static void DoReceiveMessage(NetworkStream ns) + { + UnityEngine.Debug.Log("begin to receive"); + + BinaryReader br = new BinaryReader(ns); + ; + //sign为true 循环接受数据 + while (true) + { + try + { + if (isClose || tcpClient == null) + { + _Close(); + break; + } + + while (ns.CanRead && ns.DataAvailable) + { + int head = br.ReadInt32(); + //处理粘包 + if (head == PACK_HEAD) + { + int messageId = br.ReadInt32(); + + Type t; + if (receiveMsgDict.TryGetValue(messageId, out t)) + { + var msg = (PacketBase) Activator.CreateInstance(t); + msg.Context = tcpClient; + msg.Read(br); + + if (messageId != (int) MsgHead.HeartBeat) + { + lock (m_msgQueue) + { + m_msgQueue.Enqueue(msg); + } + } + } + } + lastBeatTime = curTime; + } + + // 处理超时的时候 要断开链接 + if (curTime - lastBeatTime > HEART_BEAT_DELTA) + { + _Close(); + break; + } + } + catch (Exception e) + { + UnityEngine.Debug.Log(e); + _Close(); + break; + } + Thread.Sleep(10); + } + } + private static void DoSendMessage(NetworkStream ns) + { + MBinaryWriter bw = new MBinaryWriter(ns); + + while (true) + { + try + { + if (isClose) + { + break; + } + + if (ns.CanWrite) + { + lock (m_cmdQueue) + { + while (m_cmdQueue.Count > 0) + { + var msg = m_cmdQueue.Dequeue(); + bw.Write(PACK_HEAD); + bw.Write((int)msg.MsgHead); + msg.Write(bw); + msg.WriteOver(); + } + } + } + } + catch (Exception e) + { + if (tcpClient.Connected) + { + UnityEngine.Debug.Log(e); + } + _Close(); + break; + } + Thread.Sleep(10); + } + } + #endregion + + #region dispatch + + private static Dictionary _msgHandlers = new Dictionary(); + + public delegate void MsgHandlerDelegate(TPacket pkg) where TPacket : PacketBase; + + public static void AddListener(MsgHandlerDelegate handler) + where TPacket : PacketBase + { + // Debug.Log("AddListener: " + typeof(TPacket)); + Delegate oldHandler; + var msgType = typeof(TPacket); + if (_msgHandlers.TryGetValue(msgType, out oldHandler)) + { + _msgHandlers[msgType] = Delegate.Combine(oldHandler, handler); + } + else + { + _msgHandlers[msgType] = handler; + } + } + + public static void RemoveListener(MsgHandlerDelegate handler) + where TPacket : PacketBase + { + // Debug.Log("RemoveListener: " + typeof(TPacket)); + Delegate @delegate; + var msgType = typeof(TPacket); + if (_msgHandlers.TryGetValue(msgType, out @delegate)) + { + Delegate currentDel = Delegate.Remove(@delegate, handler); + + if (currentDel == null) + { + _msgHandlers.Remove(msgType); + } + else + { + _msgHandlers[msgType] = currentDel; + } + } + } + + public static void Dispatch(PacketBase pkg) + { + if (pkg == null) throw new ArgumentNullException("pkg"); + if (_msgHandlers == null) throw new ObjectDisposedException("Cannot dispatch and event when disposed! "); + + Delegate handler; + var msgType = pkg.GetType(); + if (_msgHandlers.TryGetValue(msgType, out handler)) + { + handler.DynamicInvoke(pkg); + } + else + { + Debug.LogError("Invalid handler for msg: " + pkg.ToString()); + } + } + + internal static void RemoveAllListeners() + { + // Debug.Log("RemoveAllListeners: "); + var handlerTypes = new Type[_msgHandlers.Keys.Count]; + _msgHandlers.Keys.CopyTo(handlerTypes, 0); + + foreach (var handlerType in handlerTypes) + { + Delegate[] delegates = _msgHandlers[handlerType].GetInvocationList(); + foreach (Delegate @delegate1 in delegates) + { + var handlerToRemove = Delegate.Remove(_msgHandlers[handlerType], @delegate1); + if (handlerToRemove == null) + { + _msgHandlers.Remove(handlerType); + } + else + { + _msgHandlers[handlerType] = handlerToRemove; + } + } + } + } + #endregion + } +} diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/NetWorkMgr.cs.meta b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/NetWorkMgr.cs.meta new file mode 100644 index 00000000..909816dd --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/NetWorkMgr.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ee9aca590e2330949924f38dc1ee8e29 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet.meta b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet.meta new file mode 100644 index 00000000..ca49b037 --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 06840242a762d6746b3b29a646908f02 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/LuaRefInfo.cs b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/LuaRefInfo.cs new file mode 100644 index 00000000..d50dd2bd --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/LuaRefInfo.cs @@ -0,0 +1,94 @@ +using System; +using System.IO; + +namespace MikuLuaProfiler +{ + [PacketMsg(MsgHead.LuaRefInfo)] + public class LuaRefInfo: PacketBase + { + public override MsgHead MsgHead => MsgHead.LuaRefInfo; + + #region field + public byte cmd; //1添加、0移除 + public int frameCount; + public string name; + public string addr; + public byte type; //1 function 2 table + #endregion + + #region pool + public static LuaRefInfo Create() + { + LuaRefInfo r = PacketFactory.GetPacket(); + return r; + } + + public static LuaRefInfo Create(byte cmd, string name, string addr, byte type) + { + LuaRefInfo r = PacketFactory.GetPacket(); + r.cmd = cmd; + r.name = name; + r.addr = addr; + r.type = type; + return r; + } + + public void Restore() + { + PacketFactory.Release(this); + } + + public LuaRefInfo Clone() + { + LuaRefInfo result = new LuaRefInfo(); + + result.cmd = this.cmd; + result.frameCount = this.frameCount; + result.name = this.name; + result.addr = this.addr; + result.type = this.type; + + return result; + } + #endregion + + #region static + + private static Action OnReciveSample; + + public static void RegAction(Action action) + { + OnReciveSample = action; + } + + public static void UnRegAction() + { + OnReciveSample = null; + } + #endregion + + public override void Read(BinaryReader br) + { + cmd = br.ReadByte(); + frameCount = br.ReadInt32(); + name = br.ReadString(); + addr = br.ReadString(); + type = br.ReadByte(); + } + + public override void Write(BinaryWriter bw) + { + bw.Write(cmd); + bw.Write(SampleData.frameCount); + bw.Write(name); + bw.Write(addr); + bw.Write(type); + } + + public override void OnRun() + { + OnReciveSample?.Invoke(this); + } + + } +} \ No newline at end of file diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/LuaRefInfo.cs.meta b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/LuaRefInfo.cs.meta new file mode 100644 index 00000000..15682e5e --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/LuaRefInfo.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 8bfc363caf6e4299b600f93b13db543c +timeCreated: 1669951305 \ No newline at end of file diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/PKGDisconnect.cs b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/PKGDisconnect.cs new file mode 100644 index 00000000..fc37ec7a --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/PKGDisconnect.cs @@ -0,0 +1,9 @@ + +namespace MikuLuaProfiler +{ + [PacketMsg(MsgHead.DisConnect)] + public class PKGDisconnect : PacketBase + { + public override MsgHead MsgHead => MsgHead.DisConnect; + } +} diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/PKGDisconnect.cs.meta b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/PKGDisconnect.cs.meta new file mode 100644 index 00000000..55853799 --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/PKGDisconnect.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2e6b3e30ba0f360479bc2ea08d15702b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/PKGHeartBeat.cs b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/PKGHeartBeat.cs new file mode 100644 index 00000000..0363a2d5 --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/PKGHeartBeat.cs @@ -0,0 +1,9 @@ + +namespace MikuLuaProfiler +{ + [PacketMsg(MsgHead.HeartBeat)] + public class HeartBeatMsg : PacketBase + { + public override MsgHead MsgHead => MsgHead.HeartBeat; + } +} diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/PKGHeartBeat.cs.meta b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/PKGHeartBeat.cs.meta new file mode 100644 index 00000000..a3b730f0 --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/PKGHeartBeat.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 801071247d6b58b4f9aae592a2007e8e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/PacketBase.cs b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/PacketBase.cs new file mode 100644 index 00000000..b5dd9eaa --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/PacketBase.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace MikuLuaProfiler +{ + + public enum MsgHead + { + HeartBeat = 0, + DisConnect, + ProfileSampleData, + LuaRefInfo, + } + + public class PacketMsgAttribute : Attribute + { + public MsgHead msgHead; + + public PacketMsgAttribute(MsgHead msgHead) + { + this.msgHead = msgHead; + } + } + + public static class PacketFactory where T: new() + { + private static Stack pool = new Stack(1024); + public static T GetPacket() + { + if (pool.Count > 0) + { + lock (pool) + { + return pool.Pop(); + } + } + return new T(); + } + + public static void Release(T p) + { + lock (pool) + { + pool.Push(p); + } + } + } + + public abstract class PacketBase + { + public abstract MsgHead MsgHead { get; } + public object Context { get; set; } + + public PacketBase() + { + } + + public virtual void Read(BinaryReader br) + { + } + + public virtual void Write(BinaryWriter bw) + { + } + + public virtual void OnRun() + { + } + + public virtual void OnRelease() + { + } + + public abstract void WriteOver(); + } + + public abstract class PacketBase : PacketBase where T : PacketBase, new() + { + public override void WriteOver() + { + T obj = (T)this; + obj.OnRelease(); + PacketFactory.Release(obj); + } + } +} diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/PacketBase.cs.meta b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/PacketBase.cs.meta new file mode 100644 index 00000000..281022e4 --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/PacketBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8288505d7e8e6d14089f6a22ad8503f4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/NetWorkClient.cs b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/Sample.cs similarity index 77% rename from LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/NetWorkClient.cs rename to LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/Sample.cs index 21984fdf..186b49d5 100644 --- a/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/NetWorkClient.cs +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/Sample.cs @@ -1,295 +1,333 @@ -/* - ######### - ############ - ############# - ## ########### - ### ###### ##### - ### ####### #### - ### ########## #### - #### ########### #### - #### ########### ##### - ##### ### ######## ##### - ##### ### ######## ###### - ###### ### ########### ###### - ###### #### ############## ###### - ####### ##################### ###### - ####### ###################### ###### - ####### ###### ################# ###### - ####### ###### ###### ######### ###### - ####### ## ###### ###### ###### - ####### ###### ##### ##### - ###### ##### ##### #### - ##### #### ##### ### - ##### ### ### # - ### ### ### - ## ### ### -__________#_______####_______####______________ - 我们的未来没有BUG -* ============================================================================== -* Filename: NetWorkClient -* Created: 2018/7/13 14:29:22 -* Author: エル・プサイ・コングリィ -* Purpose: -* ============================================================================== -*/ -#if UNITY_EDITOR_WIN || USE_LUA_PROFILER +using System; +using System.Collections.Generic; +using System.IO; namespace MikuLuaProfiler { - using System; - using System.Collections.Generic; - using System.IO; - using System.Net.Sockets; - using System.Text; - using System.Threading; - - public static class NetWorkClient + [PacketMsg(MsgHead.ProfileSampleData)] + public class Sample: PacketBase { - private static TcpClient m_client = null; - private static Thread m_sendThread; - private static Thread m_receiveThread; - private static Queue m_sampleQueue = new Queue(256); - private const int PACK_HEAD = 0x23333333; - private static NetworkStream ns; - public static MBinaryWriter bw; - private static BinaryReader br; - private static int m_frameCount = 0; - - #region public - public static void ConnectServer(string host, int port) + #region head + public override MsgHead MsgHead => MsgHead.ProfileSampleData; + + public int currentLuaMemory; + public int currentMonoMemory; + public long currentTime; + + public int calls; + public int frameCount; + public float fps; + public uint pss; + public float power; + + public int costLuaGC; + public int costMonoGC; + public string name; + public int costTime; + public MList childs = new MList(16); + + #region property + public Sample _father; + private string _fullName; + public bool needShow = false; + + public bool isCopy = false; + public long copySelfLuaGC = -1; + public long selfLuaGC { - if (m_client != null) return; - m_client = new TcpClient(); - - m_client.NoDelay = true; - try - { - m_client.Connect(host, port); - - UnityEngine.Debug.Log("connect success"); - m_client.Client.SendTimeout = 30000; - //m_sampleDict.Clear(); - m_strDict.Clear(); - m_key = 0; - ns = m_client.GetStream(); - bw = new MBinaryWriter(ns); - br = new BinaryReader(ns); - - m_sendThread = new Thread(new ThreadStart(DoSendMessage)); - m_sendThread.Start(); - m_receiveThread = new Thread(new ThreadStart(DoRecieveMessage)); - m_receiveThread.Priority = ThreadPriority.Lowest; - m_receiveThread.Start(); - } - catch (Exception e) + get { - UnityEngine.Debug.Log(e); - Close(); + if (isCopy) return copySelfLuaGC; + long result = costLuaGC; + for (int i = 0, imax = childs.Count; i < imax; i++) + { + var item = childs[i]; + result -= item.costLuaGC; + } + return Math.Max(result, 0); } } - public static void Close() + public long copySelfMonoGC = -1; + + public long selfMonoGC { - try + get { - if (m_client != null) + if (isCopy) return copySelfMonoGC; + long result = costMonoGC; + for (int i = 0, imax = childs.Count; i < imax; i++) { - if (m_client.Connected) - { - m_client.Close(); - } - m_client = null; + var item = childs[i]; + result -= item.costMonoGC; } - m_sampleQueue.Clear(); - } - catch (Exception e) - { - UnityEngine.Debug.Log(e); - } - finally - { - m_strDict.Clear(); - } - if (m_receiveThread != null) - { - var tmp = m_receiveThread; - m_receiveThread = null; - tmp.Abort(); + return Math.Max(result, 0); } + } - if (m_sendThread != null) + public int copySelfCostTime = -1; + public int selfCostTime + { + get { - var tmp = m_sendThread; - m_sendThread = null; - tmp.Abort(); + if (isCopy) return copySelfCostTime; + int result = costTime; + for (int i = 0, imax = childs.Count; i < imax; i++) + { + var item = childs[i]; + result -= item.costTime; + } + + return Math.Max(result, 0); } } - //private static Dictionary m_sampleDict = new Dictionary(256); - - public static void SendMessage(NetBase sample) + public bool CheckSampleValid() { - if (m_client == null) + bool result = false; + do { - sample.Restore(); - return; - } - lock (m_sampleQueue) - { - m_sampleQueue.Enqueue(sample); - } + if (needShow) + { + result = true; + break; + } + var setting = LuaDeepProfilerSetting.Instance; + if (setting != null && !setting.discardInvalid) + { + result = true; + break; + } + + if (costLuaGC != 0) + { + result = true; + break; + } + + if (costMonoGC != 0) + { + result = true; + break; + } + + if (costTime > 10000) + { + result = true; + break; + } + + } while (false); + + + return result; } - #endregion - #region private - private static void DoSendMessage() + private static Dictionary> m_fullNamePool = new Dictionary>(); + public string fullName { - while (true) + get { - try + if (_father == null) return name; + + if (_fullName == null) { - if (m_sendThread == null) + Dictionary childDict; + if (!m_fullNamePool.TryGetValue(_father.fullName, out childDict)) { - UnityEngine.Debug.LogError("m_sendThread null"); - return; + childDict = new Dictionary(); + m_fullNamePool.Add(_father.fullName, childDict); } - if (m_sampleQueue.Count > 0) + + if (!childDict.TryGetValue(name, out _fullName)) { - while (m_sampleQueue.Count > 0) + string value = name; + var f = _father; + while (f != null) { - NetBase s = null; - lock (m_sampleQueue) - { - s = m_sampleQueue.Dequeue(); - } - bw.Write(PACK_HEAD); - if (s is Sample) - { - bw.Write((int)0); - } - else if (s is LuaRefInfo) - { - bw.Write((int)1); - } - else if (s is LuaDiffInfo) - { - bw.Write((int)2); - } - Serialize(s, bw); - s.Restore(); + value = f.name + value; + f = f.fahter; } + _fullName = value; + childDict[name] = string.Intern(_fullName); } - else if (m_frameCount != SampleData.frameCount) - { - bw.Write(PACK_HEAD); - //写入message 头编号 - bw.Write((int)0); - Sample s = Sample.Create(0, (int)LuaLib.GetLuaMemory(LuaProfiler.mainL), ""); - Serialize(s, bw); - s.Restore(); - m_frameCount = SampleData.frameCount; - } - Thread.Sleep(10); + + return _fullName; } -#pragma warning disable 0168 - catch (ThreadAbortException e) { } - catch (Exception e) + else { - UnityEngine.Debug.Log(e); - Close(); + return _fullName; } -#pragma warning restore 0168 } - } - private static void DoRecieveMessage() + public Sample fahter { - while (true) + set { - try + if (value != null) { - if (m_receiveThread == null) + bool needAdd = true; + var childList = value.childs; + for (int i = 0,imax = childList.Count;im_receiveThread null"); - return; - } - if (ns.CanRead && ns.DataAvailable) - { - int head = br.ReadInt32(); - //处理粘包 - while (head == PACK_HEAD) + var item = childList[i]; + if (item.name == name) { - int messageId = br.ReadInt32(); - switch (messageId) - { - case 0: - { - LuaProfiler.SendAllRef(); - } - break; - case 1: - { - lock (m_client) - { - LuaHook.MarkRecordServer(); - } - } - break; - case 2: - { - lock (m_client) - { - LuaHook.DiffServer(); - } - } - break; - } - head = br.ReadInt32(); + needAdd = false; + item.AddSample(this); + break; } } + if (needAdd) + { + childList.Add(this); + _father = value; + } } - catch (Exception e) + else { - UnityEngine.Debug.Log(e); + _father = null; } - Thread.Sleep(10); + } + get + { + return _father; } } + #endregion - private static int m_key = 0; - public static int GetUniqueKey() + public void AddSample(Sample s) { - return m_key++; + calls += s.calls; + costLuaGC += Math.Max(s.costLuaGC, 0); + costMonoGC += Math.Max(s.costMonoGC, 0); + costTime += s.costTime; + for (int i = s.childs.Count - 1; i >= 0; i--) + { + var item = s.childs[i]; + item.fahter = this; + if (item.fahter != s) + { + s.childs.RemoveAt(i); + } + } } - private static Dictionary> m_strDict = new Dictionary>(8192); - private static bool GetBytes(string s, out byte[] result, out int index) + + public static Sample Create(long time, int memory, string name) { - bool ret = true; - KeyValuePair keyValuePair; - if (!m_strDict.TryGetValue(s, out keyValuePair)) + Sample s = PacketFactory.GetPacket(); + + s.calls = 1; + s.currentTime = time; + s.currentLuaMemory = memory; + s.currentMonoMemory = (int)GC.GetTotalMemory(false); + s.frameCount = SampleData.frameCount; + s.fps = SampleData.fps; + s.pss = SampleData.pss; + s.power = SampleData.power; + s.costLuaGC = 0; + s.costMonoGC = 0; + s.name = name; + s.costTime = 0; + s._father = null; + s.childs.Clear(); + s._fullName = null; + s.needShow = false; + + return s; + } + + public override void OnRelease() + { + lock (this) { - result = Encoding.UTF8.GetBytes(s); - index = GetUniqueKey(); - keyValuePair = new KeyValuePair(index, result); - m_strDict.Add(s, keyValuePair); - ret = false; + for (int i = 0, imax = childs.Count; i < imax; i++) + { + PacketFactory.Release(childs[i]); + } + _fullName = null; + childs.Clear(); } - else + } + + public void Restore() + { + PacketFactory.Release(this); + } + + public Sample Clone() + { + Sample s = new Sample(); + + s.calls = calls; + s.frameCount = frameCount; + s.fps = fps; + s.pss = pss; + s.power = power; + s.costMonoGC = costMonoGC; + s.costLuaGC = costLuaGC; + s.name = name; + s.costTime = costTime; + + int childCount = childs.Count; + for (int i = 0; i < childCount; i++) { - index = keyValuePair.Key; - result = keyValuePair.Value; + Sample child = childs[i].Clone(); + child.fahter = s; } - return ret; + s.currentLuaMemory = currentLuaMemory; + s.currentMonoMemory = currentMonoMemory; + s.currentTime = currentTime; + return s; + } + + #endregion + + #region static + + private static Action OnReciveSample; + + public static void RegAction(Action action) + { + OnReciveSample = action; } - private static void Serialize(NetBase o, BinaryWriter bw) + + public static void UnRegAction() { - if (o is Sample) + OnReciveSample = null; + } + #endregion + + #region virtual + public override void Read(BinaryReader br) + { + calls = br.ReadInt32(); + frameCount = br.ReadInt32(); + fps = br.ReadSingle(); + pss = br.ReadUInt32(); + power = br.ReadSingle(); + costLuaGC = br.ReadInt32(); + costMonoGC = br.ReadInt32(); + name = br.ReadString(); + + costTime = br.ReadInt32(); + currentLuaMemory = br.ReadInt32(); + currentMonoMemory = br.ReadInt32(); + ushort childCount = br.ReadUInt16(); + for (int i = 0; i < childCount; i++) { - Sample s = (Sample)o; - + var s = PacketFactory.GetPacket(); + s.Read(br); + childs.Add(s); + } + } + + public override void Write(BinaryWriter bw) + { + Sample s = this; bw.Write(s.calls); bw.Write(s.frameCount); bw.Write(s.fps); @@ -297,7 +335,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s.power); bw.Write(s.costLuaGC); bw.Write(s.costMonoGC); - WriteString(bw, s.name); + bw.Write(s.name); bw.Write(s.costTime); bw.Write(s.currentLuaMemory); @@ -316,7 +354,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s0.power); bw.Write(s0.costLuaGC); bw.Write(s0.costMonoGC); - WriteString(bw, s0.name); + bw.Write(s0.name); bw.Write(s0.costTime); bw.Write(s0.currentLuaMemory); @@ -333,7 +371,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s1.power); bw.Write(s1.costLuaGC); bw.Write(s1.costMonoGC); - WriteString(bw, s1.name); + bw.Write(s1.name); bw.Write(s1.costTime); bw.Write(s1.currentLuaMemory); @@ -350,7 +388,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s2.power); bw.Write(s2.costLuaGC); bw.Write(s2.costMonoGC); - WriteString(bw, s2.name); + bw.Write(s2.name); bw.Write(s2.costTime); bw.Write(s2.currentLuaMemory); @@ -367,7 +405,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s3.power); bw.Write(s3.costLuaGC); bw.Write(s3.costMonoGC); - WriteString(bw, s3.name); + bw.Write(s3.name); bw.Write(s3.costTime); bw.Write(s3.currentLuaMemory); @@ -384,7 +422,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s4.power); bw.Write(s4.costLuaGC); bw.Write(s4.costMonoGC); - WriteString(bw, s4.name); + bw.Write(s4.name); bw.Write(s4.costTime); bw.Write(s4.currentLuaMemory); @@ -401,7 +439,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s5.power); bw.Write(s5.costLuaGC); bw.Write(s5.costMonoGC); - WriteString(bw, s5.name); + bw.Write(s5.name); bw.Write(s5.costTime); bw.Write(s5.currentLuaMemory); @@ -418,7 +456,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s6.power); bw.Write(s6.costLuaGC); bw.Write(s6.costMonoGC); - WriteString(bw, s6.name); + bw.Write(s6.name); bw.Write(s6.costTime); bw.Write(s6.currentLuaMemory); @@ -435,7 +473,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s7.power); bw.Write(s7.costLuaGC); bw.Write(s7.costMonoGC); - WriteString(bw, s7.name); + bw.Write(s7.name); bw.Write(s7.costTime); bw.Write(s7.currentLuaMemory); @@ -452,7 +490,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s8.power); bw.Write(s8.costLuaGC); bw.Write(s8.costMonoGC); - WriteString(bw, s8.name); + bw.Write(s8.name); bw.Write(s8.costTime); bw.Write(s8.currentLuaMemory); @@ -469,7 +507,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s9.power); bw.Write(s9.costLuaGC); bw.Write(s9.costMonoGC); - WriteString(bw, s9.name); + bw.Write(s9.name); bw.Write(s9.costTime); bw.Write(s9.currentLuaMemory); @@ -486,7 +524,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s10.power); bw.Write(s10.costLuaGC); bw.Write(s10.costMonoGC); - WriteString(bw, s10.name); + bw.Write(s10.name); bw.Write(s10.costTime); bw.Write(s10.currentLuaMemory); @@ -503,7 +541,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s11.power); bw.Write(s11.costLuaGC); bw.Write(s11.costMonoGC); - WriteString(bw, s11.name); + bw.Write(s11.name); bw.Write(s11.costTime); bw.Write(s11.currentLuaMemory); @@ -520,7 +558,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s12.power); bw.Write(s12.costLuaGC); bw.Write(s12.costMonoGC); - WriteString(bw, s12.name); + bw.Write(s12.name); bw.Write(s12.costTime); bw.Write(s12.currentLuaMemory); @@ -537,7 +575,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s13.power); bw.Write(s13.costLuaGC); bw.Write(s13.costMonoGC); - WriteString(bw, s13.name); + bw.Write(s13.name); bw.Write(s13.costTime); bw.Write(s13.currentLuaMemory); @@ -554,7 +592,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s14.power); bw.Write(s14.costLuaGC); bw.Write(s14.costMonoGC); - WriteString(bw, s14.name); + bw.Write(s14.name); bw.Write(s14.costTime); bw.Write(s14.currentLuaMemory); @@ -571,7 +609,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s15.power); bw.Write(s15.costLuaGC); bw.Write(s15.costMonoGC); - WriteString(bw, s15.name); + bw.Write(s15.name); bw.Write(s15.costTime); bw.Write(s15.currentLuaMemory); @@ -588,7 +626,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s16.power); bw.Write(s16.costLuaGC); bw.Write(s16.costMonoGC); - WriteString(bw, s16.name); + bw.Write(s16.name); bw.Write(s16.costTime); bw.Write(s16.currentLuaMemory); @@ -605,7 +643,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s17.power); bw.Write(s17.costLuaGC); bw.Write(s17.costMonoGC); - WriteString(bw, s17.name); + bw.Write(s17.name); bw.Write(s17.costTime); bw.Write(s17.currentLuaMemory); @@ -622,7 +660,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s18.power); bw.Write(s18.costLuaGC); bw.Write(s18.costMonoGC); - WriteString(bw, s18.name); + bw.Write(s18.name); bw.Write(s18.costTime); bw.Write(s18.currentLuaMemory); @@ -639,7 +677,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s19.power); bw.Write(s19.costLuaGC); bw.Write(s19.costMonoGC); - WriteString(bw, s19.name); + bw.Write(s19.name); bw.Write(s19.costTime); bw.Write(s19.currentLuaMemory); @@ -656,7 +694,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s20.power); bw.Write(s20.costLuaGC); bw.Write(s20.costMonoGC); - WriteString(bw, s20.name); + bw.Write(s20.name); bw.Write(s20.costTime); bw.Write(s20.currentLuaMemory); @@ -673,7 +711,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s21.power); bw.Write(s21.costLuaGC); bw.Write(s21.costMonoGC); - WriteString(bw, s21.name); + bw.Write(s21.name); bw.Write(s21.costTime); bw.Write(s21.currentLuaMemory); @@ -690,7 +728,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s22.power); bw.Write(s22.costLuaGC); bw.Write(s22.costMonoGC); - WriteString(bw, s22.name); + bw.Write(s22.name); bw.Write(s22.costTime); bw.Write(s22.currentLuaMemory); @@ -707,7 +745,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s23.power); bw.Write(s23.costLuaGC); bw.Write(s23.costMonoGC); - WriteString(bw, s23.name); + bw.Write(s23.name); bw.Write(s23.costTime); bw.Write(s23.currentLuaMemory); @@ -724,7 +762,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s24.power); bw.Write(s24.costLuaGC); bw.Write(s24.costMonoGC); - WriteString(bw, s24.name); + bw.Write(s24.name); bw.Write(s24.costTime); bw.Write(s24.currentLuaMemory); @@ -741,7 +779,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s25.power); bw.Write(s25.costLuaGC); bw.Write(s25.costMonoGC); - WriteString(bw, s25.name); + bw.Write(s25.name); bw.Write(s25.costTime); bw.Write(s25.currentLuaMemory); @@ -758,7 +796,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s26.power); bw.Write(s26.costLuaGC); bw.Write(s26.costMonoGC); - WriteString(bw, s26.name); + bw.Write(s26.name); bw.Write(s26.costTime); bw.Write(s26.currentLuaMemory); @@ -775,7 +813,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) bw.Write(s27.power); bw.Write(s27.costLuaGC); bw.Write(s27.costMonoGC); - WriteString(bw, s27.name); + bw.Write(s27.name); bw.Write(s27.costTime); bw.Write(s27.currentLuaMemory); @@ -785,7 +823,7 @@ private static void Serialize(NetBase o, BinaryWriter bw) for (int i28 = 0, i28max = childs28.Count; i28 < i28max; i28++) { Sample s28 = childs28[i28]; - Serialize(s28, bw); + s28.Write(bw); } } } @@ -813,116 +851,59 @@ private static void Serialize(NetBase o, BinaryWriter bw) } } } - } } } - else if (o is LuaRefInfo) - { - LuaRefInfo r = (LuaRefInfo)o; - - bw.Write(r.cmd); - bw.Write(SampleData.frameCount); - WriteString(bw, r.name); - WriteString(bw, r.addr); - bw.Write(r.type); - } - else if (o is LuaDiffInfo) + } + + public override void OnRun() + { + OnReciveSample?.Invoke(this); + } + + #endregion + + #region serialize + public static void SerializeList(List samples, string path) + { + FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); + MBinaryWriter b = new MBinaryWriter(fs); +#if UNITY_EDITOR + UnityEditor.EditorUtility.ClearProgressBar(); +#endif + b.Write(samples.Count); + for (int i = 0, imax = samples.Count; i < imax; i++) { - LuaDiffInfo ld = (LuaDiffInfo)o; - // add - var addDict = ld.addRef; - bw.Write(addDict.Count); - foreach (var item in addDict) - { - bw.Write((int)item.Key); - bw.Write(item.Value.Count); - foreach (var v in item.Value) - { - WriteString(bw, v); - } - } - var addDetail = ld.addDetail; - bw.Write(addDetail.Count); - foreach (var item in addDetail) - { - WriteString(bw, item.Key); - var list = item.Value; - bw.Write(list.Count); - foreach (var listItem in list) - { - WriteString(bw, listItem); - } - } - // rm - var rmDict = ld.rmRef; - bw.Write(rmDict.Count); - foreach (var item in rmDict) - { - bw.Write((int)item.Key); - bw.Write(item.Value.Count); - foreach (var v in item.Value) - { - WriteString(bw, v); - } - } - var rmDetail = ld.rmDetail; - bw.Write(rmDetail.Count); - foreach (var item in rmDetail) - { - WriteString(bw, item.Key); - var list = item.Value; - bw.Write(list.Count); - foreach (var listItem in list) - { - WriteString(bw, listItem); - } - } - - // null - var nullDict = ld.nullRef; - bw.Write(nullDict.Count); - foreach (var item in nullDict) - { - bw.Write((int)item.Key); - bw.Write(item.Value.Count); - foreach (var v in item.Value) - { - WriteString(bw, v); - } - } - var nullDetail = ld.nullDetail; - bw.Write(nullDetail.Count); - foreach (var item in nullDetail) - { - WriteString(bw, item.Key); - var list = item.Value; - bw.Write(list.Count); - foreach (var listItem in list) - { - WriteString(bw, listItem); - } - } + Sample s = samples[i]; +#if UNITY_EDITOR + UnityEditor.EditorUtility.DisplayProgressBar("serialize profiler data", "serialize " + s.name, (float)i / (float)imax); +#endif + s.Write(b); } + b.Close(); +#if UNITY_EDITOR + UnityEditor.EditorUtility.ClearProgressBar(); +#endif } - public static void WriteString(BinaryWriter bw, string name) + public static List DeserializeList(string path) { - byte[] datas; - int index = 0; - bool isRef = GetBytes(name, out datas, out index); - bw.Write(isRef); - bw.Write(index); - if (!isRef) + FileStream ms = new FileStream(path, FileMode.Open, FileAccess.Read); + MBinaryReader b = new MBinaryReader(ms); + + int count = b.ReadInt32(); + List result = new List(count); + + for (int i = 0, imax = count; i < imax; i++) { - bw.Write(datas.Length); - bw.Write(datas); + Sample s = new Sample(); + s.Read(b); + result.Add(s); } - } + b.Close(); + return result; + } #endregion - } - -} - -#endif \ No newline at end of file + +} \ No newline at end of file diff --git a/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/Sample.cs.meta b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/Sample.cs.meta new file mode 100644 index 00000000..8729768e --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Core/NetWork/Packet/Sample.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 07fd026c8ec04d7cbb964599d3db835e +timeCreated: 1658392633 \ No newline at end of file diff --git a/LuaProfiler/example/Assets/LuaProfiler/Editor/Window/ProfilerWin/NetWork/NetWorkMgr.Client.cs b/LuaProfiler/example/Assets/LuaProfiler/Editor/Window/ProfilerWin/NetWork/NetWorkMgr.Client.cs new file mode 100644 index 00000000..a7b826ab --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Editor/Window/ProfilerWin/NetWork/NetWorkMgr.Client.cs @@ -0,0 +1,148 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Reflection; +using System.Threading; +using UnityEngine; + +namespace MikuLuaProfiler +{ + public static class NetWorkMgrClient + { + private static NetworkStream ns; + private static MBinaryReader br; + private static MBinaryWriter bw; + private const int PACK_HEAD = 0x114514; + + private static Dictionary receiveMsgDict = new Dictionary(); + private static Dictionary receiveMsgTypeDict = new Dictionary(); + private static Thread receiveThread; + private static TcpClient tcpClient; + private static bool _isConnected = false; + + static NetWorkMgrClient() + { + var types = typeof(NetWorkMgr).Assembly.GetTypes(); + foreach (var t in types) + { + if (t.Namespace == "MikuLuaProfiler" + && t.IsSubclassOf(typeof(PacketBase))) + { + var attr = t.GetCustomAttribute(); + if (attr != null) + { + receiveMsgDict[(int)attr.msgHead] = t; + receiveMsgTypeDict[t] = (int)attr.msgHead; + } + } + } + } + + public static void Disconnect() + { + if (tcpClient != null) + { + SendMessage(new PKGDisconnect()); + tcpClient.Close(); + tcpClient.Dispose(); + tcpClient = null; + if (bw != null) + { + bw.Dispose(); + bw = null; + } + + if (br != null) + { + br.Dispose(); + br = null; + } + + _isConnected = false; + } + } + + public static void Connect(string ip, int port) + { + tcpClient = new TcpClient(); + tcpClient.Connect(ip, port); + + ns = tcpClient.GetStream(); + br = new MBinaryReader(ns); + bw = new MBinaryWriter(ns); + if (receiveThread != null) + { + receiveThread.Abort(); + receiveThread = null; + } + receiveThread = new Thread(DoReceiveMessage); + receiveThread.Name = "Client ReceiveThread"; + receiveThread.Start(); + _isConnected = true; + } + + public static bool GetIsConnect() + { + return _isConnected; + } + + private static void DoReceiveMessage() + { + while (true) + { + try + { + if (tcpClient == null) + { + break; + } + + if (ns.CanRead && ns.DataAvailable) + { + int head = br.ReadInt32(); + //处理粘包 + while (head == PACK_HEAD) + { + int messageId = br.ReadInt32(); + Type t; + if (receiveMsgDict.TryGetValue(messageId, out t)) + { + var msg = Activator.CreateInstance(t) as PacketBase; + msg.Read(br); + msg.OnRun(); + } + } + } + } + catch (Exception e) + { + Debug.Log(e.ToString()); + break; + } + Thread.Sleep(10); + } + + + if (receiveThread != null) + { + receiveThread.Abort(); + receiveThread = null; + } + } + + public static void SendMessage(PacketBase msg) + { + if(bw == null) return; + + bw.Write(PACK_HEAD); + int msgId = 0; + receiveMsgTypeDict.TryGetValue(msg.GetType(), out msgId); + bw.Write(msgId); + msg.Write(bw); + msg.WriteOver(); + } + + } +} diff --git a/LuaProfiler/example/Assets/LuaProfiler/Editor/Window/ProfilerWin/NetWork/NetWorkMgr.Client.cs.meta b/LuaProfiler/example/Assets/LuaProfiler/Editor/Window/ProfilerWin/NetWork/NetWorkMgr.Client.cs.meta new file mode 100644 index 00000000..add20164 --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Editor/Window/ProfilerWin/NetWork/NetWorkMgr.Client.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8da5bc0f18e767f47a104886d64dc3a6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/LuaProfiler/example/Assets/LuaProfiler/Editor/Window/ProfilerWin/NetWork/NetWorkServer.cs b/LuaProfiler/example/Assets/LuaProfiler/Editor/Window/ProfilerWin/NetWork/NetWorkServer.cs deleted file mode 100644 index 88770d47..00000000 --- a/LuaProfiler/example/Assets/LuaProfiler/Editor/Window/ProfilerWin/NetWork/NetWorkServer.cs +++ /dev/null @@ -1,467 +0,0 @@ -/* - ######### - ############ - ############# - ## ########### - ### ###### ##### - ### ####### #### - ### ########## #### - #### ########### #### - #### ########### ##### - ##### ### ######## ##### - ##### ### ######## ###### - ###### ### ########### ###### - ###### #### ############## ###### - ####### ##################### ###### - ####### ###################### ###### - ####### ###### ################# ###### - ####### ###### ###### ######### ###### - ####### ## ###### ###### ###### - ####### ###### ##### ##### - ###### ##### ##### #### - ##### #### ##### ### - ##### ### ### # - ### ### ### - ## ### ### -__________#_______####_______####______________ - 我们的未来没有BUG -* ============================================================================== -* Filename: NetWorkServer -* Created: 2018/7/13 14:29:22 -* Author: エル・プサイ・コングリィ -* Purpose: -* ============================================================================== -*/ - -#if UNITY_5_6_OR_NEWER && UNITY_EDITOR_WIN -namespace MikuLuaProfiler -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using System.Net.Sockets; - using System.Text; - using System.Threading; - using UnityEditor; - - public static class NetWorkServer - { - private static TcpListener tcpLister; - private static TcpClient tcpClient = null; - private static Thread receiveThread; - private static Thread sendThread; - public static Thread acceptThread; - private static NetworkStream ns; - private static BinaryReader br; - private static BinaryWriter bw; - - private const int PACK_HEAD = 0x23333333; - private static Action m_onReceiveSample; - private static Action m_onReceiveRef; - private static Action m_onReceiveDiff; - private static Queue m_cmdQueue = new Queue(32); - - public static bool CheckIsReceiving() - { - return tcpClient != null; - } - - public static void RegisterOnReceiveSample(Action onReceive) - { - m_onReceiveSample = onReceive; - } - - public static void RegisterOnReceiveRefInfo(Action onReceive) - { - m_onReceiveRef = onReceive; - } - - public static void RegisterOnReceiveDiffInfo(Action onReceive) - { - m_onReceiveDiff = onReceive; - } - - public static void UnRegisterReceive() - { - m_onReceiveSample = null; - m_onReceiveRef = null; - m_onReceiveDiff = null; - } - - public static void BeginListen(string ip, int port) - { - if (tcpLister != null) return; - - m_strCacheDict.Clear(); - - IPAddress myIP = IPAddress.Parse(ip); - tcpLister = new TcpListener(myIP, port); - tcpLister.Start(); - acceptThread = new Thread(AcceptThread); - acceptThread.Start(); - - } - - private static void AcceptThread() - { - UnityEngine.Debug.Log("begin listerner"); - tcpClient = null; - - while (true) - { - AcceptAClient(); - Thread.Sleep(100); - } - } - - private static void AcceptAClient() - { - if (tcpClient != null) return; - - try - { - if (tcpClient == null) - { - tcpClient = tcpLister.AcceptTcpClient(); - } - } - catch(Exception e) - { - UnityEngine.Debug.Log(e); - UnityEngine.Debug.Log("start fail"); - Close(); - return; - } - LuaProfilerWindow.ClearTreeView(); - - UnityEngine.Debug.Log("link start"); - tcpClient.ReceiveTimeout = 1000000; - ns = tcpClient.GetStream(); - br = new BinaryReader(ns); - bw = new BinaryWriter(ns); - ns.ReadTimeout = 600000; - - // 启动一个线程来接受请求 - receiveThread = new Thread(DoReceiveMessage); - receiveThread.Start(); - - SendCmd(0); - // 启动一个线程来发送请求 - sendThread = new Thread(DoSendMessage); - sendThread.Start(); - } - - // 0获取ref表,1 记录下当前全局表状态,2 diff 当前状态与历史记录 - public static void SendCmd(int cmd) - { - lock (m_cmdQueue) - { - m_cmdQueue.Enqueue(cmd); - } - } - - // 接受请求 - private static void DoReceiveMessage() - { - UnityEngine.Debug.Log("begin to listener"); - - //sign为true 循环接受数据 - while (true) - { - try - { - if (tcpClient == null) - { - Close(); - return; - } - - if (ns.CanRead && ns.DataAvailable) - { - try - { - int head = br.ReadInt32(); - //处理粘包 - while (head == PACK_HEAD) - { - int messageId = br.ReadInt32(); - switch (messageId) - { - case 0: - { - Sample s = Deserialize(br); - if (m_onReceiveSample != null) - { - m_onReceiveSample(s); - } - } - break; - case 1: - { - var r = DeserializeRef(br); - if (m_onReceiveRef != null) - { - m_onReceiveRef(r); - } - } - break; - case 2: - { - var r = DeserializeDiff(br); - if (m_onReceiveDiff != null) - { - m_onReceiveDiff(r); - } - } - break; - } - - } - } -#pragma warning disable 0168 - catch (EndOfStreamException ex) - { - Close(); - return; - } -#pragma warning restore 0168 - } - - } -#pragma warning disable 0168 - catch (ThreadAbortException e) { - } - catch (Exception e) - { - Close(); - } -#pragma warning restore 0168 - Thread.Sleep(10); - } - } - - private static void DoSendMessage() - { - while (true) - { - try - { - if (ns.CanWrite) - { - lock (m_cmdQueue) - { - while (m_cmdQueue.Count > 0) - { - int msgId = -1; - msgId = m_cmdQueue.Dequeue(); - bw.Write(PACK_HEAD); - bw.Write(msgId); - } - } - } - } -#pragma warning disable 0168 - catch (ThreadAbortException e) { } - catch (Exception e) - { - UnityEngine.Debug.Log(e); - Close(); - } -#pragma warning restore 0168 - Thread.Sleep(10); - } - } - - public static void RealClose() - { - try - { - if (tcpLister != null) - { - tcpLister.Stop(); - tcpLister = null; - } - } - catch (Exception e) - { - UnityEngine.Debug.Log(e); - } - if (acceptThread != null) - { - try - { - acceptThread.Abort(); - } - catch { } - acceptThread = null; - } - Close(); - } - - public static void Close() - { - tcpClient = null; - if (receiveThread != null) - { - try - { - receiveThread.Abort(); - } - catch { } - receiveThread = null; - } - if (sendThread != null) - { - try - { - sendThread.Abort(); - } - catch { } - sendThread = null; - } - } - - private static Dictionary m_strCacheDict = new Dictionary(4096); - public static Sample Deserialize(BinaryReader br) - { - Sample s = null; - - if (LuaDeepProfilerSetting.Instance.isLocal) - { - s = Sample.Deserialize(br); - } - else - { - s = new Sample(); - s.calls = br.ReadInt32(); - s.frameCount = br.ReadInt32(); - s.fps = br.ReadSingle(); - s.pss = br.ReadUInt32(); - s.power = br.ReadSingle(); - s.costLuaGC = br.ReadInt32(); - s.costMonoGC = br.ReadInt32(); - s.name = ReadString(br); - - s.costTime = br.ReadInt32(); - s.currentLuaMemory = br.ReadInt32(); - s.currentMonoMemory = br.ReadInt32(); - int count = br.ReadUInt16(); - for (int i = 0, imax = count; i < imax; i++) - { - Deserialize(br).fahter = s; - } - - int lua_gc = 0; - int mono_gc = 0; - for (int i = 0, imax = s.childs.Count; i < imax; i++) - { - var item = s.childs[i]; - lua_gc += item.costLuaGC; - mono_gc += item.costMonoGC; - } - s.costLuaGC = Math.Max(lua_gc, s.costLuaGC); - s.costMonoGC = Math.Max(mono_gc, s.costMonoGC); - } - - return s; - } - - public static LuaRefInfo DeserializeRef(BinaryReader br) - { - LuaRefInfo refInfo = LuaRefInfo.Create(); - refInfo.cmd = br.ReadByte(); - refInfo.frameCount = br.ReadInt32(); - refInfo.name = ReadString(br); - refInfo.addr = ReadString(br); - refInfo.type = br.ReadByte(); - - return refInfo; - } - public static LuaDiffInfo DeserializeDiff(BinaryReader br) - { - LuaDiffInfo diffInfo = LuaDiffInfo.Create(); - int addTypeCount = br.ReadInt32(); - for (int i = 0; i < addTypeCount; i++) - { - int type = br.ReadInt32(); - int valueCount = br.ReadInt32(); - for (int j = 0; j < valueCount; j++) - { - diffInfo.PushAddRef(ReadString(br), type); - } - } - int addDetailCount = br.ReadInt32(); - for (int i = 0; i < addDetailCount; i++) - { - string key = ReadString(br); - int count = br.ReadInt32(); - for (int ii = 0; ii < count; ii++) - { - diffInfo.PushAddDetail(key, ReadString(br)); - } - } - - int rmTypeCount = br.ReadInt32(); - for (int i = 0; i < rmTypeCount; i++) - { - int type = br.ReadInt32(); - int valueCount = br.ReadInt32(); - for (int j = 0; j < valueCount; j++) - { - diffInfo.PushRmRef(ReadString(br), type); - } - } - int rmDetailCount = br.ReadInt32(); - for (int i = 0; i < rmDetailCount; i++) - { - string key = ReadString(br); - int count = br.ReadInt32(); - for (int ii = 0; ii < count; ii++) - { - diffInfo.PushRmDetail(key, ReadString(br)); - } - } - - int nullCount = br.ReadInt32(); - for (int i = 0; i < nullCount; i++) - { - diffInfo.PushNullRef(ReadString(br), br.ReadInt32()); - } - int nullDetailCount = br.ReadInt32(); - for (int i = 0; i < nullDetailCount; i++) - { - string key = ReadString(br); - int count = br.ReadInt32(); - for (int ii = 0; ii < count; ii++) - { - diffInfo.PushNullDetail(key, ReadString(br)); - } - } - - return diffInfo; - } - public static string ReadString(BinaryReader br) - { - string result = null; - - bool isRef = br.ReadBoolean(); - int index = br.ReadInt32(); - if (!isRef) - { - int len = br.ReadInt32(); - byte[] datas = br.ReadBytes(len); - result = string.Intern(Encoding.UTF8.GetString(datas)); - m_strCacheDict[index] = result; - } - else - { - result = m_strCacheDict[index]; - } - - return result; - } - } - -} -#endif \ No newline at end of file diff --git a/LuaProfiler/example/Assets/LuaProfiler/Editor/Window/ProfilerWin/TreeView/LuaProfilerTreeView.cs b/LuaProfiler/example/Assets/LuaProfiler/Editor/Window/ProfilerWin/TreeView/LuaProfilerTreeView.cs index 390d963f..d4ecb28f 100644 --- a/LuaProfiler/example/Assets/LuaProfiler/Editor/Window/ProfilerWin/TreeView/LuaProfilerTreeView.cs +++ b/LuaProfiler/example/Assets/LuaProfiler/Editor/Window/ProfilerWin/TreeView/LuaProfilerTreeView.cs @@ -336,7 +336,6 @@ public Sample CopySelfToSample() s.name = m_originName; s.costTime = (int)totalTime; - s.captureUrl = ""; s.currentLuaMemory = 0; s.currentMonoMemory = 0; return s; @@ -359,7 +358,6 @@ public Sample CopyToSample() Sample child = childs[i].CopyToSample(); child.fahter = s; } - s.captureUrl = ""; s.currentLuaMemory = 0; s.currentMonoMemory = 0; return s; @@ -773,15 +771,6 @@ public void ReLoadSamples(int start, int end) end = Mathf.Max(Mathf.Min(end, history.Count - 1), 0); start = Mathf.Max(Mathf.Min(start, history.Count - 1), 0); - //if (end == start) - //{ - // LoadRootSample(history[start], false, true); - // return; - //} - - startUrl = history[start].captureUrl; - endUrl = history[end].captureUrl; - end = Mathf.Min(history.Count - 1, end); m_catchLuaMemory = 0; for (int i = start; i <= end; i++) diff --git a/LuaProfiler/example/Assets/LuaProfiler/Editor/Window/ProfilerWin/TreeView/LuaProfilerWindow.cs b/LuaProfiler/example/Assets/LuaProfiler/Editor/Window/ProfilerWin/TreeView/LuaProfilerWindow.cs index 42259135..df100622 100644 --- a/LuaProfiler/example/Assets/LuaProfiler/Editor/Window/ProfilerWin/TreeView/LuaProfilerWindow.cs +++ b/LuaProfiler/example/Assets/LuaProfiler/Editor/Window/ProfilerWin/TreeView/LuaProfilerWindow.cs @@ -368,28 +368,41 @@ void DoToolbar() if (!LuaDeepProfilerSetting.Instance.isLocal) { - if (GUILayout.Button("OpenService", EditorStyles.toolbarButton, GUILayout.Height(30))) - { - ClearConsole(); - NetWorkServer.RealClose(); - currentFrameIndex = 0; - m_TreeView.Clear(true); - LuaProfiler.UnRegistReceive(); - NetWorkServer.UnRegisterReceive(); - NetWorkServer.RegisterOnReceiveSample(m_TreeView.LoadRootSample); - NetWorkServer.RegisterOnReceiveRefInfo(m_luaRefScrollView.DelRefInfo); - NetWorkServer.RegisterOnReceiveDiffInfo(m_luaDiffScrollView.DelDiffInfo); - NetWorkServer.BeginListen("0.0.0.0", port); - } + GUILayout.Label("ip:", GUILayout.Height(30), GUILayout.Width(35)); + LuaDeepProfilerSetting.Instance.ip = EditorGUILayout.TextField(LuaDeepProfilerSetting.Instance.ip, GUILayout.Height(16), GUILayout.Width(150)); + GUILayout.Label("port:", GUILayout.Height(30), GUILayout.Width(35)); port = EditorGUILayout.IntField(port, GUILayout.Height(16), GUILayout.Width(50)); - if (GUILayout.Button("CloseService", EditorStyles.toolbarButton, GUILayout.Height(30))) + if (!NetWorkMgrClient.GetIsConnect()) { - ClearConsole(); - NetWorkServer.RealClose(); - UnityEngine.Debug.Log("disconnect"); + if (GUILayout.Button("Connect", GUILayout.Height(20))) + { + ClearConsole(); + NetWorkMgrClient.Disconnect(); + currentFrameIndex = 0; + m_TreeView.Clear(true); + LuaProfiler.UnRegistReceive(); + Sample.UnRegAction(); + LuaRefInfo.UnRegAction(); + + NetWorkMgrClient.Connect(LuaDeepProfilerSetting.Instance.ip, port); + Sample.RegAction(m_TreeView.LoadRootSample); + LuaRefInfo.RegAction(m_luaRefScrollView.DelRefInfo); + //NetWorkServer.RegisterOnReceiveDiffInfo(m_luaDiffScrollView.DelDiffInfo); + + } } + else + { + if (GUILayout.Button("Disconnect",GUILayout.Height(20))) + { + ClearConsole(); + NetWorkMgrClient.Disconnect(); + UnityEngine.Debug.Log("disconnect"); + } + } + } else { @@ -434,12 +447,13 @@ void DoToolbar() } } + /* GUILayout.Space(25); if (GUILayout.Button("MarkStaticRecord", EditorStyles.toolbarButton, GUILayout.Height(30))) { if (!LuaDeepProfilerSetting.Instance.isLocal) { - NetWorkServer.SendCmd(3); + NetWorkMgrClient.SendCmd(3); } else { @@ -474,7 +488,7 @@ void DoToolbar() if (GUILayout.Button("ClearDiff", EditorStyles.toolbarButton, GUILayout.Height(30))) { m_luaDiffScrollView.Clear(); - } + }*/ GUILayout.Space(20); if (GUILayout.Button("AddLuaDir", EditorStyles.toolbarButton, GUILayout.Height(30))) @@ -489,15 +503,21 @@ void DoToolbar() { LocalToLuaIDE.ClearPath(); } - - GUILayout.Space(10); - if (NetWorkServer.acceptThread != null) + if (!LuaDeepProfilerSetting.Instance.isRecord) { - Color c = GUI.color; - GUI.color = Color.green; - GUILayout.Label("listerning.."); - GUI.color = c; + bool isSave = GUILayout.Button("Save", EditorStyles.toolbarButton, GUILayout.Height(30), GUILayout.Width(50)); + if (isSave) + { + m_TreeView.SaveResult(); + } + + bool isLoad = GUILayout.Button("Load", EditorStyles.toolbarButton, GUILayout.Height(30), GUILayout.Width(50)); + if (isLoad) + { + m_TreeView.LoadHistory(); + } } + #endregion #region gc value @@ -517,7 +537,10 @@ void DoToolbar() void DoRecord() { var instance = LuaDeepProfilerSetting.Instance; - if (!instance.isRecord) return; + if (!instance.isRecord) + { + return; + } EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); @@ -533,7 +556,7 @@ void DoRecord() { m_TreeView.Clear(true); m_luaRefScrollView.ClearRefInfo(true); - NetWorkServer.SendCmd(0); + //NetWorkServer.SendCmd(0); } if (state && !instance.isStartRecord) @@ -1216,11 +1239,12 @@ void HandleInputForChart(Rect expandRect) private void OpenLocalMode() { ClearConsole(); - NetWorkServer.RealClose(); + NetWorkMgrClient.Disconnect(); currentFrameIndex = 0; m_TreeView.Clear(true); LuaProfiler.UnRegistReceive(); - NetWorkServer.UnRegisterReceive(); + Sample.UnRegAction(); + LuaRefInfo.UnRegAction(); LuaProfiler.RegisterOnReceiveSample(m_TreeView.LoadRootSample); LuaProfiler.RegisterOnReceiveRefInfo(m_luaRefScrollView.DelRefInfo); LuaProfiler.RegisterOnReceiveDiffInfo(m_luaDiffScrollView.DelDiffInfo); diff --git a/LuaProfiler/example/Assets/LuaProfiler/Plugins.meta b/LuaProfiler/example/Assets/LuaProfiler/Plugins.meta index 41952b67..99628ebb 100644 --- a/LuaProfiler/example/Assets/LuaProfiler/Plugins.meta +++ b/LuaProfiler/example/Assets/LuaProfiler/Plugins.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 9088dc344e398b9439bb19a6db49a937 +guid: ba70fc0a43afa084e8d42d5d7105bbf4 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android.meta b/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android.meta new file mode 100644 index 00000000..5f43e0b1 --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6076d8e2a9ee20e4fb7523c062353962 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/java.meta b/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/java.meta new file mode 100644 index 00000000..7dfdcacd --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/java.meta @@ -0,0 +1,33 @@ +fileFormatVersion: 2 +guid: e1219e1c64b4aad43abf2dc6ae5c1c4a +folderAsset: yes +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Android: Android + second: + enabled: 1 + settings: {} + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/java/ShadowHook.aar b/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/java/ShadowHook.aar new file mode 100644 index 00000000..cc382a5f Binary files /dev/null and b/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/java/ShadowHook.aar differ diff --git a/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/java/ShadowHook.aar.meta b/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/java/ShadowHook.aar.meta new file mode 100644 index 00000000..753fec45 --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/java/ShadowHook.aar.meta @@ -0,0 +1,32 @@ +fileFormatVersion: 2 +guid: 7d0ea1291d53155408d82b486598a12e +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Android: Android + second: + enabled: 1 + settings: {} + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/libs.meta b/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/libs.meta new file mode 100644 index 00000000..64c0cdb3 --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/libs.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 08fcce44ca98528498e1969173b58db6 +folderAsset: yes +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/libs/arm64-v8a.meta b/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/libs/arm64-v8a.meta new file mode 100644 index 00000000..47173f34 --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/libs/arm64-v8a.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: be36276396afc5d47ae8210112ad5ef6 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/libs/arm64-v8a/libshadowhook.so b/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/libs/arm64-v8a/libshadowhook.so new file mode 100644 index 00000000..0ab27139 Binary files /dev/null and b/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/libs/arm64-v8a/libshadowhook.so differ diff --git a/LuaProfiler/example/Assets/Plugins/Android/libs/arm64-v8a/libshadowhook.so.meta b/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/libs/arm64-v8a/libshadowhook.so.meta similarity index 100% rename from LuaProfiler/example/Assets/Plugins/Android/libs/arm64-v8a/libshadowhook.so.meta rename to LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/libs/arm64-v8a/libshadowhook.so.meta diff --git a/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/libs/armeabi-v7a.meta b/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/libs/armeabi-v7a.meta new file mode 100644 index 00000000..7749f060 --- /dev/null +++ b/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/libs/armeabi-v7a.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 7119f0c3b3e8dd7468b1165ca504f193 +folderAsset: yes +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/libs/armeabi-v7a/libshadowhook.so b/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/libs/armeabi-v7a/libshadowhook.so new file mode 100644 index 00000000..77ab2e3e Binary files /dev/null and b/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/libs/armeabi-v7a/libshadowhook.so differ diff --git a/LuaProfiler/example/Assets/LuaProfiler/Plugins/MikuBinary.dll.meta b/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/libs/armeabi-v7a/libshadowhook.so.meta similarity index 74% rename from LuaProfiler/example/Assets/LuaProfiler/Plugins/MikuBinary.dll.meta rename to LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/libs/armeabi-v7a/libshadowhook.so.meta index b10c0f5c..f0fbea6d 100644 --- a/LuaProfiler/example/Assets/LuaProfiler/Plugins/MikuBinary.dll.meta +++ b/LuaProfiler/example/Assets/LuaProfiler/Plugins/Android/libs/armeabi-v7a/libshadowhook.so.meta @@ -1,30 +1,33 @@ fileFormatVersion: 2 -guid: 38b52d2a4d811c348b5f69147af47732 +guid: 977c2e7c6b17c7942acc2d4fbb58c1ca PluginImporter: externalObjects: {} serializedVersion: 2 iconMap: {} executionOrder: {} + defineConstraints: [] isPreloaded: 0 isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 platformData: - first: - Any: + Android: Android second: enabled: 1 - settings: {} + settings: + CPU: ARMv7 - first: - Editor: Editor + Any: second: enabled: 0 - settings: - DefaultValueInitialized: true + settings: {} - first: - Windows Store Apps: WindowsStoreApps + Editor: Editor second: enabled: 0 settings: - CPU: AnyCPU + DefaultValueInitialized: true userData: assetBundleName: assetBundleVariant: diff --git a/LuaProfiler/example/Assets/LuaProfiler/Plugins/MikuBinary.dll b/LuaProfiler/example/Assets/LuaProfiler/Plugins/MikuBinary.dll deleted file mode 100644 index 0e431732..00000000 Binary files a/LuaProfiler/example/Assets/LuaProfiler/Plugins/MikuBinary.dll and /dev/null differ diff --git a/LuaProfiler/example/Assets/Plugins/Android/java/ShadowHook.java.meta b/LuaProfiler/example/Assets/Plugins/Android/java/ShadowHook.java.meta deleted file mode 100644 index 052f6a38..00000000 --- a/LuaProfiler/example/Assets/Plugins/Android/java/ShadowHook.java.meta +++ /dev/null @@ -1,70 +0,0 @@ -fileFormatVersion: 2 -guid: ff63db311c1b8514090553be5cc7fdc9 -PluginImporter: - externalObjects: {} - serializedVersion: 2 - iconMap: {} - executionOrder: {} - defineConstraints: [] - isPreloaded: 1 - isOverridable: 0 - isExplicitlyReferenced: 0 - validateReferences: 1 - platformData: - - first: - : Any - second: - enabled: 0 - settings: - Exclude Android: 0 - Exclude Editor: 1 - Exclude Linux64: 1 - Exclude OSXUniversal: 1 - Exclude Win: 1 - Exclude Win64: 1 - - first: - Android: Android - second: - enabled: 1 - settings: - CPU: ARMv7 - - first: - Any: - second: - enabled: 0 - settings: {} - - first: - Editor: Editor - second: - enabled: 0 - settings: - CPU: AnyCPU - DefaultValueInitialized: true - OS: AnyOS - - first: - Standalone: Linux64 - second: - enabled: 0 - settings: - CPU: AnyCPU - - first: - Standalone: OSXUniversal - second: - enabled: 0 - settings: - CPU: None - - first: - Standalone: Win - second: - enabled: 0 - settings: - CPU: x86 - - first: - Standalone: Win64 - second: - enabled: 0 - settings: - CPU: x86_64 - userData: - assetBundleName: - assetBundleVariant: diff --git a/LuaProfiler/example/Assets/Plugins/Android/libs/arm64-v8a/libshadowhook.so b/LuaProfiler/example/Assets/Plugins/Android/libs/arm64-v8a/libshadowhook.so deleted file mode 100644 index 00c9b9bc..00000000 Binary files a/LuaProfiler/example/Assets/Plugins/Android/libs/arm64-v8a/libshadowhook.so and /dev/null differ diff --git a/LuaProfiler/example/Assets/XLua/Src/LuaDLL.cs b/LuaProfiler/example/Assets/XLua/Src/LuaDLL.cs index d74ae255..cc3cb8af 100644 --- a/LuaProfiler/example/Assets/XLua/Src/LuaDLL.cs +++ b/LuaProfiler/example/Assets/XLua/Src/LuaDLL.cs @@ -292,7 +292,7 @@ public static string lua_tostring(IntPtr L, int index) [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushstring(IntPtr L, string str); #else - public static void lua_pushstring(IntPtr L, string str) //ҵʹ + public static void lua_pushstring(IntPtr L, string str) //ҵ��ʹ�� { if (str == null) { @@ -542,7 +542,7 @@ public static int lua_error(IntPtr L) //[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] //public static extern void xlua_pushbuffer(IntPtr L, byte[] buff); - //Unityɵstruct϶࣬⼸apiŻstruct + //����Unity����������ɵ�struct�϶࣬�⼸��api�����Ż�����struct [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern bool xlua_pack_float2(IntPtr buff, int offset, float f1, float f2); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] diff --git a/LuaProfiler/example/Assets/XLua/Src/LuaEnv.cs b/LuaProfiler/example/Assets/XLua/Src/LuaEnv.cs index 61ec1eba..1fb69bd2 100644 --- a/LuaProfiler/example/Assets/XLua/Src/LuaEnv.cs +++ b/LuaProfiler/example/Assets/XLua/Src/LuaEnv.cs @@ -359,7 +359,7 @@ public void Tick() #endif } - //API + //����API public void GC() { Tick(); @@ -600,8 +600,8 @@ elseif not name then internal List customLoaders = new List(); - //loader : CustomLoader filepathrefͣrequireIJҪֵ֧ԣҪʵ· - // ֵnullظԴ޺ʵļ򷵻UTF8byte[] + //loader : CustomLoader�� filepath��������ref���ͣ�������require�IJ����������Ҫ֧�ֵ��ԣ���Ҫ�����ʵ·���� + // ����ֵ���������null��������ظ�Դ���޺��ʵ��ļ������򷵻�UTF8�����byte[] public void AddLoader(CustomLoader loader) { customLoaders.Add(loader);