Example #1
0
    public static bool SaveSnapshotFiles(string targetSession, string targetName, PackedMemorySnapshot packed /*, CrawledMemorySnapshot unpacked*/)
    {
        string targetDir = Path.Combine(MemUtil.SnapshotsDir, targetSession);

        if (!Directory.Exists(targetDir))
        {
            Directory.CreateDirectory(targetDir);
        }

        if (!TrackerModeUtil.SaveSnapshotBin(targetDir, targetName + TrackerModeConsts.SnapshotBinPostfix, packed))
        {
            return(false);
        }

        Debug.LogFormat("Snapshot saved successfully. (dir: {0}, name: {1})", targetDir, targetName);
        return(true);
    }
Example #2
0
        private void CrawlRawObjectData(PackedMemorySnapshot packedMemorySnapshot, StartIndices startIndices, BytesAndOffset bytesAndOffset, TypeDescription typeDescription, bool useStaticFields, int indexOfFrom, List <Connection> out_connections, List <PackedManagedObject> out_managedObjects)
        {
            foreach (var field in TypeTools.AllFieldsOf(typeDescription, _typeDescriptions, useStaticFields ? TypeTools.FieldFindOptions.OnlyStatic : TypeTools.FieldFindOptions.OnlyInstance))
            {
                if (field.typeIndex == typeDescription.typeIndex && typeDescription.isValueType)
                {
                    //this happens in System.Single, which is a weird type that has a field of its own type.
                    continue;
                }

                if (field.offset == -1)
                {
                    //this is how we encode TLS fields. todo: actually treat TLS fields as roots
                    continue;
                }

                var fieldType = packedMemorySnapshot.typeDescriptions[field.typeIndex];

                var fieldLocation = bytesAndOffset.Add(field.offset - (useStaticFields ? 0 : _virtualMachineInformation.objectHeaderSize));

                if (fieldType.isValueType)
                {
                    CrawlRawObjectData(packedMemorySnapshot, startIndices, fieldLocation, fieldType, false, indexOfFrom, out_connections, out_managedObjects);
                    continue;
                }

                //temporary workaround for a bug in 5.3b4 and earlier where we would get literals returned as fields with offset 0. soon we'll be able to remove this code.
                bool gotException = false;
                try
                {
                    fieldLocation.ReadPointer();
                }
                catch (ArgumentException)
                {
                    UnityEngine.Debug.LogWarningFormat("Skipping field {0} on type {1}", field.name, typeDescription.name);
                    UnityEngine.Debug.LogWarningFormat("FieldType.name: {0}", fieldType.name);
                    gotException = true;
                }

                if (!gotException)
                {
                    CrawlPointer(packedMemorySnapshot, startIndices, fieldLocation.ReadPointer(), indexOfFrom, out_connections, out_managedObjects);
                }
            }
        }
Example #3
0
        private void CrawlRawObjectDataNonRecursive(PackedMemorySnapshot packedMemorySnapshot, StartIndices startIndices, BytesAndOffset bytesAndOffset, TypeDescription typeDescription, bool useStaticFields, int indexOfFrom,
                                                    List <Connection> out_connections, List <PackedManagedObject> out_managedObjects, Stack <ThingToProfile> out_thingsToProfile)
        {
            // Do not crawl MemoryProfilerWindow objects
            if (typeDescription.name.StartsWith("MemoryProfilerWindow."))
            {
                return;
            }

            var fields = useStaticFields ? _staticFields[typeDescription.typeIndex] : _instanceFields[typeDescription.typeIndex];

            for (int i = 0; i < fields.Length; ++i)
            {
                var field         = fields[i];
                var fieldType     = packedMemorySnapshot.typeDescriptions[field.typeIndex];
                var fieldLocation = bytesAndOffset.Add(field.offset - (useStaticFields ? 0 : _virtualMachineInformation.objectHeaderSize));

                if (fieldType.isValueType)
                {
                    out_thingsToProfile.Push(new ThingToProfile(fieldType, fieldLocation, false, indexOfFrom));

                    continue;
                }
                else
                {
                    //temporary workaround for a bug in 5.3b4 and earlier where we would get literals returned as fields with offset 0. soon we'll be able to remove this code.
                    bool gotException = false;
                    try
                    {
                        fieldLocation.ReadPointer();
                    }
                    catch (ArgumentException)
                    {
                        UnityEngine.Debug.LogWarningFormat("Skipping field {0} on type {1}", field.name, typeDescription.name);
                        UnityEngine.Debug.LogWarningFormat("FieldType.name: {0}", fieldType.name);
                        gotException = true;
                    }

                    if (!gotException)
                    {
                        out_thingsToProfile.Push(new ThingToProfile(fieldLocation.ReadPointer(), indexOfFrom));
                    }
                }
            }
        }
        static NativeUnityEngineObject UnpackNativeUnityEngineObject(PackedMemorySnapshot packedSnapshot, PackedNativeUnityEngineObject packedNativeUnityEngineObject)
        {
            var className = packedSnapshot.nativeTypes[packedNativeUnityEngineObject.classId].name;

            return(new NativeUnityEngineObject()
            {
                instanceID = packedNativeUnityEngineObject.instanceId,
                classID = packedNativeUnityEngineObject.classId,
                className = className,
                name = packedNativeUnityEngineObject.name,
                caption = packedNativeUnityEngineObject.name + "(" + className + ")",
                size = packedNativeUnityEngineObject.size,
                isPersistent = packedNativeUnityEngineObject.isPersistent,
                isDontDestroyOnLoad = packedNativeUnityEngineObject.isDontDestroyOnLoad,
                isManager = packedNativeUnityEngineObject.isManager,
                hideFlags = packedNativeUnityEngineObject.hideFlags
            });
        }
Example #5
0
        void _IncomingSnapshot(PackedMemorySnapshot snapshot)
        {
            _snapshot = snapshot;

            MemUtil.LoadSnapshotProgress(0.01f, "creating Crawler");

            _packedCrawled = new Crawler().Crawl(_snapshot);
            MemUtil.LoadSnapshotProgress(0.7f, "unpacking");

            _unpackedCrawl = CrawlDataUnpacker.Unpack(_packedCrawled);
            MemUtil.LoadSnapshotProgress(0.8f, "creating Inspector");

            _inspector = new Inspector(this, _unpackedCrawl, _snapshot);
            MemUtil.LoadSnapshotProgress(0.9f, "refreshing view");

            RefreshCurrentView();
            MemUtil.LoadSnapshotProgress(1.0f, "done");
        }
        private void IncomingSnapshot(PackedMemorySnapshot snapshot)
        {
            _snapshot = snapshot;

            UnityEditor.EditorUtility.DisplayProgressBar("Take Snapshot", "Crawling Snapshot...", 0.33f);
            try
            {
                _packedCrawled = new Crawler().Crawl(_snapshot);

                UnityEditor.EditorUtility.DisplayProgressBar("Take Snapshot", "Unpacking Snapshot...", 0.67f);

                Unpack();
            }
            finally
            {
                UnityEditor.EditorUtility.ClearProgressBar();
            }
        }
        private static void SaveToFile(string filePath, PackedMemorySnapshot snapshot)
        {
            // Saving snapshots using JsonUtility, instead of BinaryFormatter, is significantly faster.
            // I cancelled saving a memory snapshot that is saving using BinaryFormatter after 24 hours.
            // Saving the same memory snapshot using JsonUtility.ToJson took 20 seconds only.

            Debug.LogFormat("Saving...");
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            Profiler.BeginSample("PackedMemorySnapshotUtility.SaveToFile");
            stopwatch.Start();

            string json = JsonUtility.ToJson(snapshot);

            File.WriteAllText(filePath, json);

            stopwatch.Stop();
            Profiler.EndSample();
            Debug.LogFormat("Saving took {0}ms", stopwatch.ElapsedMilliseconds);
        }
Example #8
0
        public PackedCrawlerData Crawl(PackedMemorySnapshot input)
        {
            _typeInfoToTypeDescription = input.typeDescriptions.ToDictionary(td => td.typeInfoAddress, td => td);
            _virtualMachineInformation = input.virtualMachineInformation;
            _typeDescriptions          = input.typeDescriptions;
            _instanceFields            = new FieldDescription[_typeDescriptions.Length][];
            _staticFields = new FieldDescription[_typeDescriptions.Length][];

            foreach (var type in _typeDescriptions)
            {
                _instanceFields[type.typeIndex] = TypeTools.AllFieldsOf(type, _typeDescriptions, TypeTools.FieldFindOptions.OnlyInstance).ToArray();
                _staticFields[type.typeIndex]   = TypeTools.AllFieldsOf(type, _typeDescriptions, TypeTools.FieldFindOptions.OnlyStatic).ToArray();
            }

            var result = new PackedCrawlerData(input);

            var managedObjects = new List <PackedManagedObject>(result.startIndices.OfFirstManagedObject * 3);

            var connections = new List <Connection>(managedObjects.Count * 3);

            //we will be adding a lot of connections, but the input format also already had connections. (nativeobject->nativeobject and nativeobject->gchandle). we'll add ours to the ones already there.
            connections.AddRange(input.connections);

            for (int i = 0; i != input.gcHandles.Length; i++)
            {
                CrawlPointer(input, result.startIndices, input.gcHandles[i].target, result.startIndices.OfFirstGCHandle + i, connections, managedObjects);
            }

            for (int i = 0; i < result.typesWithStaticFields.Length; i++)
            {
                var typeDescription = result.typesWithStaticFields[i];
                CrawlRawObjectData(input, result.startIndices, new BytesAndOffset {
                    bytes = typeDescription.staticFieldBytes, offset = 0, pointerSize = _virtualMachineInformation.pointerSize
                }, typeDescription, true, result.startIndices.OfFirstStaticFields + i, connections, managedObjects);
            }

            result.managedObjects = managedObjects.ToArray();
            connections.AddRange(AddManagedToNativeConnectionsAndRestoreObjectHeaders(input, result.startIndices, result));
            result.connections = connections.ToArray();

            return(result);
        }
Example #9
0
        public CachedSnapshot(PackedMemorySnapshot s)
        {
            var vmInfo = s.virtualMachineInformation;

            if (!VMTools.ValidateVirtualMachineInfo(vmInfo))
            {
                throw new UnityException("Invalid VM info. Snapshot file is corrupted.");
            }

            virtualMachineInformation = vmInfo;
            packedMemorySnapshot      = s;
            m_SnapshotVersion         = s.version;
            nativeAllocationSites     = new NativeAllocationSiteEntriesCache(s.nativeAllocationSites);
            typeDescriptions          = new TypeDescriptionEntriesCache(s.typeDescriptions);
            nativeTypes            = new NativeTypeEntriesCache(s.nativeTypes);
            nativeRootReferences   = new NativeRootReferenceEntriesCache(s.nativeRootReferences);
            nativeObjects          = new NativeObjectEntriesCache(s.nativeObjects);
            nativeMemoryRegions    = new NativeMemoryRegionEntriesCache(s.nativeMemoryRegions);
            nativeMemoryLabels     = new NativeMemoryLabelEntriesCache(s.nativeMemoryLabels);
            nativeCallstackSymbols = new NativeCallstackSymbolEntriesCache(s.nativeCallstackSymbols);
            nativeAllocations      = new NativeAllocationEntriesCache(s.nativeAllocations);
            managedStacks          = new ManagedMemorySectionEntriesCache(s.managedStacks);
            managedHeapSections    = new ManagedMemorySectionEntriesCache(s.managedHeapSections);
            gcHandles         = new GCHandleEntriesCache(s.gcHandles);
            fieldDescriptions = new FieldDescriptionEntriesCache(s.fieldDescriptions);
            connections       = new ConnectionEntriesCache(s, HasConnectionOverhaul);

            SortedNativeRegionsEntries = new SortedNativeMemoryRegionEntriesCache(this);
            SortedManagedStacksEntries = new SortedManagedMemorySectionEntriesCache(managedStacks);
            SortedManagedHeapEntries   = new SortedManagedMemorySectionEntriesCache(managedHeapSections);

            SortedManagedObjects    = new SortedManagedObjectsCache(this);
            SortedNativeAllocations = new SortedNativeAllocationsCache(this);
            SortedNativeObjects     = new SortedNativeObjectsCache(this);

            CrawledData = new ManagedData();

            typeDescriptions.InitSecondaryItems(this);
            nativeObjects.InitSecondaryItems();
            nativeObjects.InitSecondaryItems(this);
        }
Example #10
0
        public PackedCrawlerData Crawl(PackedMemorySnapshot input)
        {
            _typeInfoToTypeDescription = input.typeDescriptions.ToDictionary(td => td.typeInfoAddress, td => td);
            _virtualMachineInformation = input.virtualMachineInformation;
            _typeDescriptions          = input.typeDescriptions;

            MemUtil.LoadSnapshotProgress(0.1f, "adding connections");
            var result         = new PackedCrawlerData(input);
            var managedObjects = new List <PackedManagedObject>(result.startIndices.OfFirstManagedObject * 3);

            var connections = new List <Connection>(managedObjects.Count * 3);

            //we will be adding a lot of connections, but the input format also already had connections. (nativeobject->nativeobject and nativeobject->gchandle). we'll add ours to the ones already there.
            connections.AddRange(input.connections);

            MemUtil.LoadSnapshotProgress(0.2f, "CrawlPointer");
            for (int i = 0; i != input.gcHandles.Length; i++)
            {
                CrawlPointer(input, result.startIndices, input.gcHandles[i].target, result.startIndices.OfFirstGCHandle + i, connections, managedObjects);
                MemUtil.LoadSnapshotProgress(0.2f + 0.2f * ((float)i / (float)input.gcHandles.Length),
                                             string.Format("CrawlPointer({0}/{1})", i, input.gcHandles.Length));
            }

            MemUtil.LoadSnapshotProgress(0.4f, "CrawlRawObjectData");
            for (int i = 0; i < result.typesWithStaticFields.Length; i++)
            {
                var typeDescription = result.typesWithStaticFields[i];
                CrawlRawObjectData(input, result.startIndices, new BytesAndOffset {
                    bytes = typeDescription.staticFieldBytes, offset = 0, pointerSize = _virtualMachineInformation.pointerSize
                }, typeDescription, true, result.startIndices.OfFirstStaticFields + i, connections, managedObjects);
                MemUtil.LoadSnapshotProgress(0.4f + 0.2f * ((float)i / (float)result.typesWithStaticFields.Length),
                                             string.Format("CrawlRawObjectData({0}/{1})", i, result.typesWithStaticFields.Length));
            }

            MemUtil.LoadSnapshotProgress(0.6f, "composing result");
            result.managedObjects = managedObjects.ToArray();
            connections.AddRange(AddManagedToNativeConnectionsAndRestoreObjectHeaders(input, result.startIndices, result));
            result.connections = connections.ToArray();

            return(result);
        }
Example #11
0
    public static string Save(PackedMemorySnapshot snapshot)
    {
        try
        {
            string filename = GetFullpath(string.Format("{0}-{1}.memsnap",
                                                        SysUtil.FormatDateAsFileNameString(DateTime.Now),
                                                        SysUtil.FormatTimeAsFileNameString(DateTime.Now)));

            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            using (Stream stream = File.Open(filename, FileMode.Create))
            {
                bf.Serialize(stream, snapshot);
            }
            return(filename);
        }
        catch (Exception ex)
        {
            Debug.LogException(ex);
            return("");
        }
    }
    static void SaveToFile(string filePath, PackedMemorySnapshot snapshot)
    {
        // Saving snapshots using JsonUtility, instead of BinaryFormatter, is significantly faster.
        // I cancelled saving a memory snapshot that is saving using BinaryFormatter after 24 hours.
        // Saving the same memory snapshot using JsonUtility.ToJson took 20 seconds only.
#if UNITY_5_OR_NEWER
        UnityEngine.Profiling.Profiler.BeginSample("PackedMemorySnapshotUtility.SaveToFile");

        var json = JsonUtility.ToJson(snapshot);
        File.WriteAllText(filePath, json);

        UnityEngine.Profiling.Profiler.EndSample();
#else
        Profiler.BeginSample("PackedMemorySnapshotUtility.SaveToFile");

        var json = JsonUtility.ToJson(snapshot);
        File.WriteAllText(filePath, json);

        Profiler.EndSample();
#endif
    }
Example #13
0
        private static void ExportMemorySnapshot(PackedMemorySnapshot snapshot, bool nativeEnabled)
        {
            var spacedir = string.Format("{0}/../MemoryCapture", Application.dataPath);

            if (!Directory.Exists(spacedir))
            {
                Directory.CreateDirectory(spacedir);
            }

            var        filepath = string.Format("{0}/{1:yyyyMMddHHmmss}_snapshot.pms", spacedir, DateTime.Now);
            FileStream stream   = new FileStream(filepath, FileMode.CreateNew);

            // Write snapshot header
            long offset = 0;

            stream.Write('P');
            stream.Write('M');
            stream.Write('S');
            stream.Write("GENERATED THROUGH MEMORYPROFILER DEVELOPED BY LARRYHOU");
            stream.Write(Application.unityVersion);
            stream.Write(SystemInfo.operatingSystem);
            stream.Write(Guid.NewGuid().ToByteArray());
            offset = stream.Position;
            stream.Write((uint)0);
            stream.Write(DateTime.Now);

            // Write basic snapshot memory
            PackSnapshotMemory(stream, snapshot);

            if (nativeEnabled)
            {
                // Write native object memory
                PackNativeObjectMemory(stream, snapshot);
            }

            RepackUInt32(stream, offset, (uint)stream.Length);

            stream.Close();
            Debug.LogFormat("+ {0}", filepath);
        }
    static void SaveToFile(string filePath, PackedMemorySnapshot snapshot)
    {
        // Saving snapshots using JsonUtility, instead of BinaryFormatter, is significantly faster.
        // I cancelled saving a memory snapshot that is saving using BinaryFormatter after 24 hours.
        // Saving the same memory snapshot using JsonUtility.ToJson took 20 seconds only.

        Debug.LogFormat("Saving...");
        System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
        Profiler.BeginSample("PackedMemorySnapshotUtility.SaveToFile");
        stopwatch.Start();

        string fileExtension = Path.GetExtension(filePath);

        if (string.Equals(fileExtension, ".memsnap", System.StringComparison.OrdinalIgnoreCase))
        {
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            using (Stream stream = File.Open(filePath, FileMode.Create)) {
                bf.Serialize(stream, snapshot);
            }
        }
        else if (string.Equals(fileExtension, ".memsnap2", System.StringComparison.OrdinalIgnoreCase))
        {
            var json = JsonUtility.ToJson(snapshot);
            File.WriteAllText(filePath, json);
        }
        else     // memsnap3 + default
        // Stream writing -- will not to exhaust memory (for large snapshots)
        {
            using (TextWriter writer = File.CreateText(filePath)) {
                var errors     = new List <string>();
                var serializer = getSerializer(errors);
                serializer.Serialize(writer, snapshot);
                logErrors(errors);
            }
        }

        stopwatch.Stop();
        Profiler.EndSample();
        Debug.LogFormat("Saving took {0}ms", stopwatch.ElapsedMilliseconds);
    }
Example #15
0
 public static bool SaveSnapshotBin(string binFilePath, string binFileName, PackedMemorySnapshot packed)
 {
     try
     {
         string fullName = Path.Combine(binFilePath, binFileName);
         if (!File.Exists(fullName))
         {
             System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
             using (Stream stream = File.Open(fullName, FileMode.Create))
             {
                 bf.Serialize(stream, packed);
             }
         }
         return(true);
     }
     catch (Exception ex)
     {
         Debug.LogError(string.Format("save snapshot error ! msg ={0}", ex.Message));
         Debug.LogException(ex);
         return(false);
     }
 }
        static NativeUnityEngineObject UnpackNativeUnityEngineObject(PackedMemorySnapshot packedSnapshot, PackedNativeUnityEngineObject packedNativeUnityEngineObject)
        {
#if UNITY_4_5_OR_NEWER
            var className = packedSnapshot.nativeTypes[packedNativeUnityEngineObject.nativeTypeArrayIndex].name;

            return(new NativeUnityEngineObject()
            {
                instanceID = packedNativeUnityEngineObject.instanceId,
                classID = packedNativeUnityEngineObject.nativeTypeArrayIndex,
                className = className,
                name = packedNativeUnityEngineObject.name,
                caption = packedNativeUnityEngineObject.name + "(" + className + ")",
                size = packedNativeUnityEngineObject.size,
                isPersistent = packedNativeUnityEngineObject.isPersistent,
                isDontDestroyOnLoad = packedNativeUnityEngineObject.isDontDestroyOnLoad,
                isManager = packedNativeUnityEngineObject.isManager,
                hideFlags = packedNativeUnityEngineObject.hideFlags,
                type = "NativeUnityEngineObject"
            });
#else
            var className = packedSnapshot.nativeTypes[packedNativeUnityEngineObject.classId].name;

            return(new NativeUnityEngineObject()
            {
                instanceID = packedNativeUnityEngineObject.instanceId,
                classID = packedNativeUnityEngineObject.classId,
                className = className,
                name = packedNativeUnityEngineObject.name,
                caption = packedNativeUnityEngineObject.name + "(" + className + ")",
                size = packedNativeUnityEngineObject.size,
                isPersistent = packedNativeUnityEngineObject.isPersistent,
                isDontDestroyOnLoad = packedNativeUnityEngineObject.isDontDestroyOnLoad,
                isManager = packedNativeUnityEngineObject.isManager,
                hideFlags = packedNativeUnityEngineObject.hideFlags,
                type = "NativeUnityEngineObject"
            });
#endif
        }
    public void AddSnapshot(PackedMemorySnapshot packed)
    {
        try
        {
            TrackerMode_Base curMode = GetCurrentMode();
            if (curMode == null)
            {
                Debug.LogErrorFormat("AddSnapshot() failed. (invalid mode: {0})", curMode);
                return;
            }

            Debug.Log("accepting snapshot...");
            var snapshotInfo = new MemSnapshotInfo();
            if (!snapshotInfo.AcceptSnapshot(packed))
            {
                Debug.LogError("AcceptSnapshot() failed.");
                return;
            }

            Debug.Log("appending snapshot...");
            curMode.AddSnapshot(snapshotInfo);

            //Debug.Log("saving snapshot...");
            if (AutoSaveOnSnapshot)
            {
                if (!curMode.SaveSessionInfo(packed, snapshotInfo.Unpacked))
                {
                    Debug.LogErrorFormat("Save Session Info Failed!");
                }
            }

            Debug.Log("appending snapshot. (done)");
        }
        catch (Exception ex)
        {
            Debug.LogException(ex);
        }
    }
Example #18
0
        void OnGUI()
        {
            Initialize();

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Take Snapshot"))
            {
                UnityEditor.EditorUtility.DisplayProgressBar("Take Snapshot", "Downloading Snapshot...", 0.0f);
                UnityEditor.MemoryProfiler.MemorySnapshot.RequestNewSnapshot();
            }

            EditorGUI.BeginDisabledGroup(_snapshot == null);
            if (GUILayout.Button("Save Snapshot..."))
            {
                PackedMemorySnapshotUtility.SaveToFile(_snapshot);
            }
            EditorGUI.EndDisabledGroup();

            if (GUILayout.Button("Load Snapshot..."))
            {
                PackedMemorySnapshot packedSnapshot = PackedMemorySnapshotUtility.LoadFromFile();
                if (packedSnapshot != null)
                {
                    IncomingSnapshot(packedSnapshot);
                }
            }
            GUILayout.EndHorizontal();
            if (_treeMapView != null)
            {
                _treeMapView.Draw();
            }
            if (_inspector != null)
            {
                _inspector.Draw();
            }

            //RenderDebugList();
        }
        private static NativeUnityEngineObject UnpackNativeUnityEngineObject(PackedMemorySnapshot packedSnapshot, PackedNativeUnityEngineObject packedNativeUnityEngineObject)
        {
#if UNITY_5_6_OR_NEWER
            int classId = packedNativeUnityEngineObject.nativeTypeArrayIndex;
#else
            int classId = packedNativeUnityEngineObject.classId;
#endif
            string className = packedSnapshot.nativeTypes[classId].name;

            return(new NativeUnityEngineObject()
            {
                instanceID = packedNativeUnityEngineObject.instanceId,
                classID = classId,
                className = className,
                name = packedNativeUnityEngineObject.name,
                caption = packedNativeUnityEngineObject.name + "(" + className + ")",
                size = packedNativeUnityEngineObject.size,
                isPersistent = packedNativeUnityEngineObject.isPersistent,
                isDontDestroyOnLoad = packedNativeUnityEngineObject.isDontDestroyOnLoad,
                isManager = packedNativeUnityEngineObject.isManager,
                hideFlags = packedNativeUnityEngineObject.hideFlags
            });
        }
Example #20
0
        private static void PackNativeObjectMemory(Stream input, PackedMemorySnapshot snapshot)
        {
            var offset = input.Position;

            input.Write((uint)0);
            input.Write('1');

            // Write the number of native objects
            input.Write(snapshot.nativeObjects.Length);

            // Write native objects memory
            var buffer = new byte[1 << 25];

            foreach (var no in snapshot.nativeObjects)
            {
                input.Write(no.nativeObjectAddress);
                input.Write(no.size);
                if (no.size > buffer.Length || no.size < 0)
                {
                    Debug.LogFormat("[SIZE] address=0x{0:X} name='{1}' type='{2}' size={3}", no.nativeObjectAddress, no.name,
                                    snapshot.nativeTypes[no.nativeTypeArrayIndex].name, no.size);
                    input.Write((uint)0);
                }
                else
                {
                    Marshal.Copy(new IntPtr(no.nativeObjectAddress), buffer, 0, no.size);
                    input.Write(buffer, 0, no.size);
                }
            }

            {
                RepackUInt32(input, offset, (uint)(input.Position - offset));
                input.Write(DateTime.Now);
            }

            input.Flush();
        }
        void TopToolBar(Rect rect)
        {
            GUILayout.BeginArea(rect);
            using (new EditorGUILayout.HorizontalScope())
            {
                var style = "miniButton";
                if (GUILayout.Button("Take Snapshot", style))
                {
                    bCheckHeapOnly = false;
                    m_Status       = "Taking snapshot.....";
                    UnityEditor.MemoryProfiler.MemorySnapshot.RequestNewSnapshot();
                }

                if (GUILayout.Button("Load Snapshot", style))
                {
                    bCheckHeapOnly = false;
                    m_Status       = "Loading snapshot.....";
                    PackedMemorySnapshot packedSnapshot = PackedMemorySnapshotUtility.LoadFromFile();
                    //Debug.Log("Unlock!!!!!!!!!!!! " + packedSnapshot);
                    if (packedSnapshot != null)
                    {
                        IncomingSnapshot(packedSnapshot);
                    }
                }

                if (_snapshot != null)
                {
                    if (GUILayout.Button("Save Snapshot", style))
                    {
                        m_Status = "Saving snapshot.....";
                        PackedMemorySnapshotUtility.SaveToFile(_snapshot);
                    }
                }

                if (_unpackedCrawl != null)
                {
#if UNITY_5_6_OR_NEWER
                    //if (bCheckHeapOnly)
                    //{

                    if (GUILayout.Button("Show Tree/Node View", style))
                    {
                        bCheckHeapOnly          = false;
                        m_nodeView.bShowMemHeap = false;
                        m_nodeView.ClearNodeView();
                        m_TreeView.Reload();
                    }

                    //}
                    //else
                    {
#endif
                    if (GUILayout.Button("Show Heap Usage", style))
                    {
                        bCheckHeapOnly = true;
                        bshowPlainData = false;
                        m_nodeView.ClearNodeView();
                        m_nodeView.CreateTreelessView(_unpackedCrawl);
                    }

                    if (GUILayout.Button("Show Plain Data", style))
                    {
                        bCheckHeapOnly = true;
                        bshowPlainData = true;
                    }
#if UNITY_5_6_OR_NEWER
                }
#endif
                }
            }

            GUILayout.EndArea();
        }
Example #22
0
            public DiffMode(DataRenderer dataRenderer, PackedMemorySnapshot snapshotFirst, PackedMemorySnapshot snapshotSecond)
            {
                m_DataRenderer = dataRenderer;
                m_DataRenderer.PrettyNamesOptionChanged += UpdateTableSelectionNames;
                modeFirst      = new SnapshotMode(dataRenderer, snapshotFirst);
                modeSecond     = new SnapshotMode(dataRenderer, snapshotSecond);
                m_SchemaFirst  = modeFirst.GetSchema();
                m_SchemaSecond = modeSecond.GetSchema();

                m_SchemaDiff = new Database.Operation.DiffSchema(m_SchemaFirst, m_SchemaSecond);
                UpdateTableSelectionNames();
            }
Example #23
0
 public SnapshotMode(DataRenderer dataRenderer, PackedMemorySnapshot snapshot)
 {
     dataRenderer.PrettyNamesOptionChanged += UpdateTableSelectionNames;
     SetSnapshot(dataRenderer, snapshot);
 }
Example #24
0
 public SnapshotMode(ObjectDataFormatter objectDataFormatter, PackedMemorySnapshot snapshot)
 {
     objectDataFormatter.PrettyNamesOptionChanged += UpdateTableSelectionNames;
     SetSnapshot(objectDataFormatter, snapshot);
 }
Example #25
0
        public Inspector(MemoryProfilerWindow hostWindow, CrawledMemorySnapshot unpackedCrawl, PackedMemorySnapshot snapshot)
        {
            _unpackedCrawl            = unpackedCrawl;
            _hostWindow               = hostWindow;
            _shortestPathToRootFinder = new ShortestPathToRootFinder(unpackedCrawl);
            _primitiveValueReader     = new PrimitiveValueReader(_unpackedCrawl.virtualMachineInformation, _unpackedCrawl.managedHeap);

            _textureBack    = Resources.Load("back") as Texture2D;
            _textureForward = Resources.Load("forward") as Texture2D;
        }
Example #26
0
        private IEnumerable <Connection> AddManagedToNativeConnectionsAndRestoreObjectHeaders(PackedMemorySnapshot packedMemorySnapshot, StartIndices startIndices, PackedCrawlerData packedCrawlerData)
        {
            if (packedMemorySnapshot.typeDescriptions.Length == 0)
            {
                yield break;
            }

            var unityEngineObjectTypeDescription = packedMemorySnapshot.typeDescriptions.First(td => td.name == "UnityEngine.Object");

            bool unityEngineObjectHasInstanceIDField = unityEngineObjectTypeDescription.fields.Any(f => f.name == "m_InstanceID");
            int  instanceIDOffset = -1;

            if (unityEngineObjectHasInstanceIDField)
            {
                instanceIDOffset = unityEngineObjectTypeDescription.fields.Single(f => f.name == "m_InstanceID").offset;
            }

#if UNITY_5_4_OR_NEWER
            var cachedPtrOffset = unityEngineObjectTypeDescription.fields.Single(f => f.name == "m_CachedPtr").offset;
#endif

            for (int i = 0; i != packedCrawlerData.managedObjects.Length; i++)
            {
                var managedObjectIndex = i + startIndices.OfFirstManagedObject;
                var address            = packedCrawlerData.managedObjects[i].address;

                var typeInfoAddress = RestoreObjectHeader(packedMemorySnapshot.managedHeapSections, address, managedObjectIndex);

                if (!DerivesFrom(packedMemorySnapshot.typeDescriptions, _typeInfoToTypeDescription[typeInfoAddress].typeIndex, unityEngineObjectTypeDescription.typeIndex))
                {
                    continue;
                }

                int indexOfNativeObject = -1;
                if (unityEngineObjectHasInstanceIDField)
                {
                    var instanceID = packedMemorySnapshot.managedHeapSections.Find(address + (UInt64)instanceIDOffset, packedMemorySnapshot.virtualMachineInformation).ReadInt32();
                    indexOfNativeObject = Array.FindIndex(packedMemorySnapshot.nativeObjects, no => no.instanceId == instanceID);
                }
#if UNITY_5_4_OR_NEWER // Since Unity 5.4, UnityEngine.Object no longer stores instance id inside when running in the player. Use cached ptr instead to find the index of native object
                else
                {
                    // If you get a compilation error on the following 2 lines, update to Unity 5.4b14.
                    var cachedPtr = packedMemorySnapshot.managedHeapSections.Find(address + (UInt64)cachedPtrOffset, packedMemorySnapshot.virtualMachineInformation).ReadPointer();
                    indexOfNativeObject = Array.FindIndex(packedMemorySnapshot.nativeObjects, no => (ulong)no.nativeObjectAddress == cachedPtr);
                }
#endif

                if (indexOfNativeObject != -1)
                {
                    yield return new Connection {
                               @from = managedObjectIndex, to = indexOfNativeObject + startIndices.OfFirstNativeObject
                    }
                }
                ;
            }
        }
Example #27
0
        void IncomingSnapshot(PackedMemorySnapshot snapshot)
        {
            if (null == snapshot)
            {
                return;
            }
            lastRefreshTime = DateTime.Now;
            Debug.Log("GoProfilerWindow.IncomingSnapshot");
            data.mSnapshot = snapshot;
            memoryRootNode = new PackedItemNode("Root");
            PackedItemNode assetsRoot           = new PackedItemNode("Assets");
            PackedItemNode sceneMemoryRoot      = new PackedItemNode("SceneMemory");
            PackedItemNode notSavedRoot         = new PackedItemNode("NotSaved");
            PackedItemNode builtinResourcesRoot = new PackedItemNode("BuiltinResources");
            PackedItemNode unknownRoot          = new PackedItemNode("Unknown");

            //PackedItemNode managerNode = PackedItemNode.BuildNode<PackedItemNode>("Managers");
            memoryRootNode.AddNode(assetsRoot);
            memoryRootNode.AddNode(sceneMemoryRoot);
            memoryRootNode.AddNode(notSavedRoot);
            memoryRootNode.AddNode(builtinResourcesRoot);
            //assetsRoot.AddNode(managerNode);
            Dictionary <int, Group> assetGroup                         = new Dictionary <int, Group>();
            Dictionary <int, Group> sceneMemoryGroup                   = new Dictionary <int, Group>();
            Dictionary <int, Group> notSavedGroup                      = new Dictionary <int, Group>();
            Dictionary <int, Group> builtinResourcesGroup              = new Dictionary <int, Group>();
            Dictionary <int, Group> unknownGroup                       = new Dictionary <int, Group>();//I can't find any unknown object yet.
            List <PackedNativeUnityEngineObject> assetsObjectList      = new List <PackedNativeUnityEngineObject>();
            List <PackedNativeUnityEngineObject> sceneMemoryObjectList = new List <PackedNativeUnityEngineObject>();
            List <PackedNativeUnityEngineObject> notSavedObjectList    = new List <PackedNativeUnityEngineObject>();
            List <PackedNativeUnityEngineObject> builtinResourcesList  = new List <PackedNativeUnityEngineObject>();
            List <PackedNativeUnityEngineObject> unknownObjectList     = new List <PackedNativeUnityEngineObject>();

            //List<PackedNativeUnityEngineObject> managerList = new List<PackedNativeUnityEngineObject>();
            for (int i = 0; i < snapshot.nativeObjects.Length; i++)
            {
                PackedNativeUnityEngineObject obj = snapshot.nativeObjects[i];
                if (obj.isPersistent && ((obj.hideFlags & HideFlags.DontUnloadUnusedAsset) == 0))
                {
                    assetsObjectList.Add(obj);
                }
                else if (!obj.isPersistent && obj.hideFlags == HideFlags.None)
                {
                    sceneMemoryObjectList.Add(obj);
                }
                else if (!obj.isPersistent && (obj.hideFlags & HideFlags.HideAndDontSave) != 0)
                {
                    notSavedObjectList.Add(obj);
                }
                else if (obj.isPersistent && (obj.hideFlags & HideFlags.HideAndDontSave) != 0)
                {
                    builtinResourcesList.Add(obj);
                }
                else
                {
                    unknownObjectList.Add(obj);
                }
            }
            if (unknownObjectList.Count > 0)//I can't find any unknown object yet.
            {
                memoryRootNode.AddNode(unknownRoot);
            }
            for (int i = 0; i < assetsObjectList.Count; i++)
            {
                PackedNativeUnityEngineObject assetsObject = assetsObjectList[i];
                if (!assetGroup.ContainsKey(assetsObject.nativeTypeArrayIndex))
                {
                    assetGroup.Add(assetsObject.nativeTypeArrayIndex, new Group(assetsObject.nativeTypeArrayIndex, data.mSnapshot.nativeTypes[assetsObject.nativeTypeArrayIndex].name));
                }
                assetGroup[assetsObject.nativeTypeArrayIndex].packedNativeObjectList.Add(assetsObject);
            }
            for (int i = 0; i < sceneMemoryObjectList.Count; i++)
            {
                PackedNativeUnityEngineObject sceneObject = sceneMemoryObjectList[i];
                if (!sceneMemoryGroup.ContainsKey(sceneObject.nativeTypeArrayIndex))
                {
                    sceneMemoryGroup.Add(sceneObject.nativeTypeArrayIndex, new Group(sceneObject.nativeTypeArrayIndex, data.mSnapshot.nativeTypes[sceneObject.nativeTypeArrayIndex].name));
                }
                sceneMemoryGroup[sceneObject.nativeTypeArrayIndex].packedNativeObjectList.Add(sceneObject);
            }
            for (int i = 0; i < notSavedObjectList.Count; i++)
            {
                PackedNativeUnityEngineObject notSavedObject = notSavedObjectList[i];
                if (!notSavedGroup.ContainsKey(notSavedObject.nativeTypeArrayIndex))
                {
                    notSavedGroup.Add(notSavedObject.nativeTypeArrayIndex, new Group(notSavedObject.nativeTypeArrayIndex, data.mSnapshot.nativeTypes[notSavedObject.nativeTypeArrayIndex].name));
                }
                notSavedGroup[notSavedObject.nativeTypeArrayIndex].packedNativeObjectList.Add(notSavedObject);
            }
            for (int i = 0; i < builtinResourcesList.Count; i++)
            {
                PackedNativeUnityEngineObject builtinResourcesObject = builtinResourcesList[i];
                if (!builtinResourcesGroup.ContainsKey(builtinResourcesObject.nativeTypeArrayIndex))
                {
                    builtinResourcesGroup.Add(builtinResourcesObject.nativeTypeArrayIndex, new Group(builtinResourcesObject.nativeTypeArrayIndex, data.mSnapshot.nativeTypes[builtinResourcesObject.nativeTypeArrayIndex].name));
                }
                builtinResourcesGroup[builtinResourcesObject.nativeTypeArrayIndex].packedNativeObjectList.Add(builtinResourcesObject);
            }
            for (int i = 0; i < unknownObjectList.Count; i++)
            {
                PackedNativeUnityEngineObject unknownObject = unknownObjectList[i];
                if (!unknownGroup.ContainsKey(unknownObject.nativeTypeArrayIndex))
                {
                    unknownGroup.Add(unknownObject.nativeTypeArrayIndex, new Group(unknownObject.nativeTypeArrayIndex, data.mSnapshot.nativeTypes[unknownObject.nativeTypeArrayIndex].name));
                }
                unknownGroup[unknownObject.nativeTypeArrayIndex].packedNativeObjectList.Add(unknownObject);
            }
            using (var i = assetGroup.GetEnumerator())//replace foreach
            {
                while (i.MoveNext())
                {
                    Group group = i.Current.Value;
                    SetNodeByClassID(group.classId, group.itemNode, group.packedNativeObjectList);
                    if (group.itemNode != null)
                    {
                        assetsRoot.AddNode(group.itemNode);
                    }
                }
            }
            using (var i = sceneMemoryGroup.GetEnumerator())//replace foreach
            {
                while (i.MoveNext())
                {
                    Group group = i.Current.Value;
                    SetNodeByClassID(group.classId, group.itemNode, group.packedNativeObjectList);
                    if (group.itemNode != null)
                    {
                        sceneMemoryRoot.AddNode(group.itemNode);
                    }
                }
            }
            using (var i = notSavedGroup.GetEnumerator())//replace foreach
            {
                while (i.MoveNext())
                {
                    Group group = i.Current.Value;
                    SetNodeByClassID(group.classId, group.itemNode, group.packedNativeObjectList);
                    if (group.itemNode != null)
                    {
                        notSavedRoot.AddNode(group.itemNode);
                    }
                }
            }
            using (var i = builtinResourcesGroup.GetEnumerator())//replace foreach
            {
                while (i.MoveNext())
                {
                    Group group = i.Current.Value;
                    SetNodeByClassID(group.classId, group.itemNode, group.packedNativeObjectList);
                    if (group.itemNode != null)
                    {
                        builtinResourcesRoot.AddNode(group.itemNode);
                    }
                }
            }
            using (var i = unknownGroup.GetEnumerator())//replace foreach
            {
                while (i.MoveNext())
                {
                    Group group = i.Current.Value;
                    SetNodeByClassID(group.classId, group.itemNode, group.packedNativeObjectList);
                    if (group.itemNode != null)
                    {
                        unknownRoot.AddNode(group.itemNode);
                    }
                }
            }
            memoryRootNode.SetCount();
            memoryRootNode.Convert();
            memoryRootNode.Sort();
            //ClearEditorReferences();//To release gc and memory.
            RemoveNotification();
        }
Example #28
0
    public override bool SaveSessionInfo(PackedMemorySnapshot packed)
    {
        string sessionName = _sessionTimeStr + TrackerModeConsts.EditorTag;

        return(TrackerModeUtil.SaveSnapshotFiles(sessionName, _selected.ToString(), packed));
    }
Example #29
0
 public static void AcceptMemorySnapshot(PackedMemorySnapshot snapshot)
 {
     ExportMemorySnapshot(snapshot, false);
 }
Example #30
0
 private static void OnSnapshotCompleteForCrawling(PackedMemorySnapshot snapshot)
 {
     MemorySnapshot.OnSnapshotReceived -= OnSnapshotCompleteForCrawling;
     ExportMemorySnapshot(snapshot, true);
 }