diff --git a/FirebasePerformance/Sources/Gauges/Memory/FPRMemoryGaugeCollector.m b/FirebasePerformance/Sources/Gauges/Memory/FPRMemoryGaugeCollector.m index 7c4104d79f1..2ba9344b0eb 100644 --- a/FirebasePerformance/Sources/Gauges/Memory/FPRMemoryGaugeCollector.m +++ b/FirebasePerformance/Sources/Gauges/Memory/FPRMemoryGaugeCollector.m @@ -37,10 +37,18 @@ @interface FPRMemoryGaugeCollector () FPRMemoryGaugeData *fprCollectMemoryMetric(void) { NSDate *collectionTime = [NSDate date]; - struct mstats ms = mstats(); - FPRMemoryGaugeData *gaugeData = [[FPRMemoryGaugeData alloc] initWithCollectionTime:collectionTime - heapUsed:ms.bytes_used - heapAvailable:ms.bytes_free]; + // Use malloc_zone_statistics to get heap memory usage. + // Passing nil aggregates statistics from all malloc zones. + malloc_statistics_t stats; + malloc_zone_statistics(nil, &stats); + uint64_t usedBytes = stats.size_in_use; + uint64_t totalHeapBytes = stats.size_allocated; + uint64_t freeInsideHeap = totalHeapBytes - usedBytes; + + FPRMemoryGaugeData *gaugeData = + [[FPRMemoryGaugeData alloc] initWithCollectionTime:collectionTime + heapUsed:usedBytes + heapAvailable:freeInsideHeap]; return gaugeData; } diff --git a/FirebasePerformance/Sources/Gauges/Memory/FPRMemoryGaugeData.h b/FirebasePerformance/Sources/Gauges/Memory/FPRMemoryGaugeData.h index 747a4aac254..a1327d41ad8 100644 --- a/FirebasePerformance/Sources/Gauges/Memory/FPRMemoryGaugeData.h +++ b/FirebasePerformance/Sources/Gauges/Memory/FPRMemoryGaugeData.h @@ -24,10 +24,13 @@ NS_ASSUME_NONNULL_BEGIN /** @brief Time at which memory data was measured. */ @property(nonatomic, readonly) NSDate *collectionTime; -/** @brief Heap memory that is used. */ +/** @brief Physical memory footprint of the application, measured via task_info phys_footprint. + * Note: This represents the total memory used by the process (as reported by Jetsam accounting), + * not just heap allocations. It includes heap, stack, memory-mapped files, and other resources. */ @property(nonatomic, readonly) u_long heapUsed; -/** @brief Heap memory that is available. */ +/** @brief Heap memory that is available within allocated heap space (size_allocated - size_in_use). + */ @property(nonatomic, readonly) u_long heapAvailable; - (instancetype)init NS_UNAVAILABLE; @@ -36,8 +39,9 @@ NS_ASSUME_NONNULL_BEGIN * Creates an instance of memory gauge data with the provided information. * * @param collectionTime Time at which the gauge data was collected. - * @param heapUsed Heap memory that is used. - * @param heapAvailable Heap memory that is available. + * @param heapUsed Physical memory footprint of the application (measured via task_info + * phys_footprint). + * @param heapAvailable Free memory within allocated heap space (size_allocated - size_in_use). * @return Instance of memory gauge data. */ - (instancetype)initWithCollectionTime:(NSDate *)collectionTime