Skip to content

Commit 43fb05c

Browse files
authored
Fix macos filesystem collector cgo memory leak (#3315)
Signed-off-by: Charlie Chiang <[email protected]>
1 parent 38d32a3 commit 43fb05c

File tree

1 file changed

+21
-14
lines changed

1 file changed

+21
-14
lines changed

collector/filesystem_macos.go

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -21,21 +21,25 @@ package collector
2121
#cgo LDFLAGS: -framework Foundation
2222
#import <Foundation/Foundation.h>
2323
Float64 purgeable(char *path) {
24-
CFNumberRef tmp;
25-
NSError *error = nil;
26-
NSString *str = [NSString stringWithUTF8String:path];
27-
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:str];
28-
NSDictionary *results = [fileURL resourceValuesForKeys:@[NSURLVolumeAvailableCapacityForImportantUsageKey] error:&error];
29-
if (results) {
30-
if ((tmp = CFDictionaryGetValue((CFDictionaryRef)results, NSURLVolumeAvailableCapacityForImportantUsageKey)) == NULL) {
31-
return -1.0f;
32-
}
33-
Float64 value;
34-
if (CFNumberGetValue(tmp, kCFNumberFloat64Type, &value)) {
35-
return value;
24+
Float64 value = -1.0f;
25+
26+
@autoreleasepool {
27+
NSError *error = nil;
28+
NSString *str = [NSString stringWithUTF8String:path];
29+
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:str];
30+
31+
NSDictionary *results = [fileURL resourceValuesForKeys:@[NSURLVolumeAvailableCapacityForImportantUsageKey] error:&error];
32+
if (results) {
33+
CFNumberRef tmp = CFDictionaryGetValue((CFDictionaryRef)results, NSURLVolumeAvailableCapacityForImportantUsageKey);
34+
if (tmp != NULL) {
35+
CFNumberGetValue(tmp, kCFNumberFloat64Type, &value);
36+
}
3637
}
38+
39+
[fileURL release];
3740
}
38-
return -1.0f;
41+
42+
return value;
3943
}
4044
*/
4145
import "C"
@@ -88,6 +92,9 @@ func (c *filesystemCollector) GetStats() (stats []filesystemStats, err error) {
8892
ro = 1
8993
}
9094

95+
mountpointCString := C.CString(mountpoint)
96+
defer C.free(unsafe.Pointer(mountpointCString))
97+
9198
stats = append(stats, filesystemStats{
9299
labels: filesystemLabels{
93100
device: device,
@@ -99,7 +106,7 @@ func (c *filesystemCollector) GetStats() (stats []filesystemStats, err error) {
99106
avail: float64(mnt[i].f_bavail) * float64(mnt[i].f_bsize),
100107
files: float64(mnt[i].f_files),
101108
filesFree: float64(mnt[i].f_ffree),
102-
purgeable: float64(C.purgeable(C.CString(mountpoint))),
109+
purgeable: float64(C.purgeable(mountpointCString)),
103110
ro: ro,
104111
})
105112
}

0 commit comments

Comments
 (0)