summaryrefslogtreecommitdiff
path: root/vendor/github.com/shirou/gopsutil/v4/internal/common/common_darwin.go
blob: c9d610540e9dcf294c247e02d6d0e10f7adf5ba8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
// SPDX-License-Identifier: BSD-3-Clause
//go:build darwin

package common

import (
	"context"
	"errors"
	"fmt"
	"os"
	"os/exec"
	"strings"
	"unsafe"

	"github.com/ebitengine/purego"
	"golang.org/x/sys/unix"
)

func DoSysctrlWithContext(ctx context.Context, mib string) ([]string, error) {
	cmd := exec.CommandContext(ctx, "sysctl", "-n", mib)
	cmd.Env = getSysctrlEnv(os.Environ())
	out, err := cmd.Output()
	if err != nil {
		return []string{}, err
	}
	v := strings.Replace(string(out), "{ ", "", 1)
	v = strings.Replace(string(v), " }", "", 1)
	values := strings.Fields(string(v))

	return values, nil
}

func CallSyscall(mib []int32) ([]byte, uint64, error) {
	miblen := uint64(len(mib))

	// get required buffer size
	length := uint64(0)
	_, _, err := unix.Syscall6(
		202, // unix.SYS___SYSCTL https://github.com/golang/sys/blob/76b94024e4b621e672466e8db3d7f084e7ddcad2/unix/zsysnum_darwin_amd64.go#L146
		uintptr(unsafe.Pointer(&mib[0])),
		uintptr(miblen),
		0,
		uintptr(unsafe.Pointer(&length)),
		0,
		0)
	if err != 0 {
		var b []byte
		return b, length, err
	}
	if length == 0 {
		var b []byte
		return b, length, err
	}
	// get proc info itself
	buf := make([]byte, length)
	_, _, err = unix.Syscall6(
		202, // unix.SYS___SYSCTL https://github.com/golang/sys/blob/76b94024e4b621e672466e8db3d7f084e7ddcad2/unix/zsysnum_darwin_amd64.go#L146
		uintptr(unsafe.Pointer(&mib[0])),
		uintptr(miblen),
		uintptr(unsafe.Pointer(&buf[0])),
		uintptr(unsafe.Pointer(&length)),
		0,
		0)
	if err != 0 {
		return buf, length, err
	}

	return buf, length, nil
}

// Library represents a dynamic library loaded by purego.
type Library struct {
	addr  uintptr
	path  string
	close func()
}

// library paths
const (
	IOKit          = "/System/Library/Frameworks/IOKit.framework/IOKit"
	CoreFoundation = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation"
	System         = "/usr/lib/libSystem.B.dylib"
)

func NewLibrary(path string) (*Library, error) {
	lib, err := purego.Dlopen(path, purego.RTLD_LAZY|purego.RTLD_GLOBAL)
	if err != nil {
		return nil, err
	}

	closeFunc := func() {
		purego.Dlclose(lib)
	}

	return &Library{
		addr:  lib,
		path:  path,
		close: closeFunc,
	}, nil
}

func (lib *Library) Dlsym(symbol string) (uintptr, error) {
	return purego.Dlsym(lib.addr, symbol)
}

func GetFunc[T any](lib *Library, symbol string) T {
	var fptr T
	purego.RegisterLibFunc(&fptr, lib.addr, symbol)
	return fptr
}

func (lib *Library) Close() {
	lib.close()
}

// status codes
const (
	KERN_SUCCESS = 0
)

// IOKit functions and symbols.
type (
	IOServiceGetMatchingServiceFunc       func(mainPort uint32, matching uintptr) uint32
	IOServiceGetMatchingServicesFunc      func(mainPort uint32, matching uintptr, existing *uint32) int
	IOServiceMatchingFunc                 func(name string) unsafe.Pointer
	IOServiceOpenFunc                     func(service, owningTask, connType uint32, connect *uint32) int
	IOServiceCloseFunc                    func(connect uint32) int
	IOIteratorNextFunc                    func(iterator uint32) uint32
	IORegistryEntryGetNameFunc            func(entry uint32, name CStr) int
	IORegistryEntryGetParentEntryFunc     func(entry uint32, plane string, parent *uint32) int
	IORegistryEntryCreateCFPropertyFunc   func(entry uint32, key, allocator uintptr, options uint32) unsafe.Pointer
	IORegistryEntryCreateCFPropertiesFunc func(entry uint32, properties unsafe.Pointer, allocator uintptr, options uint32) int
	IOObjectConformsToFunc                func(object uint32, className string) bool
	IOObjectReleaseFunc                   func(object uint32) int
	IOConnectCallStructMethodFunc         func(connection, selector uint32, inputStruct, inputStructCnt, outputStruct uintptr, outputStructCnt *uintptr) int

	IOHIDEventSystemClientCreateFunc      func(allocator uintptr) unsafe.Pointer
	IOHIDEventSystemClientSetMatchingFunc func(client, match uintptr) int
	IOHIDServiceClientCopyEventFunc       func(service uintptr, eventType int64,
		options int32, timeout int64) unsafe.Pointer
	IOHIDServiceClientCopyPropertyFunc     func(service, property uintptr) unsafe.Pointer
	IOHIDEventGetFloatValueFunc            func(event uintptr, field int32) float64
	IOHIDEventSystemClientCopyServicesFunc func(client uintptr) unsafe.Pointer
)

const (
	IOServiceGetMatchingServiceSym       = "IOServiceGetMatchingService"
	IOServiceGetMatchingServicesSym      = "IOServiceGetMatchingServices"
	IOServiceMatchingSym                 = "IOServiceMatching"
	IOServiceOpenSym                     = "IOServiceOpen"
	IOServiceCloseSym                    = "IOServiceClose"
	IOIteratorNextSym                    = "IOIteratorNext"
	IORegistryEntryGetNameSym            = "IORegistryEntryGetName"
	IORegistryEntryGetParentEntrySym     = "IORegistryEntryGetParentEntry"
	IORegistryEntryCreateCFPropertySym   = "IORegistryEntryCreateCFProperty"
	IORegistryEntryCreateCFPropertiesSym = "IORegistryEntryCreateCFProperties"
	IOObjectConformsToSym                = "IOObjectConformsTo"
	IOObjectReleaseSym                   = "IOObjectRelease"
	IOConnectCallStructMethodSym         = "IOConnectCallStructMethod"

	IOHIDEventSystemClientCreateSym       = "IOHIDEventSystemClientCreate"
	IOHIDEventSystemClientSetMatchingSym  = "IOHIDEventSystemClientSetMatching"
	IOHIDServiceClientCopyEventSym        = "IOHIDServiceClientCopyEvent"
	IOHIDServiceClientCopyPropertySym     = "IOHIDServiceClientCopyProperty"
	IOHIDEventGetFloatValueSym            = "IOHIDEventGetFloatValue"
	IOHIDEventSystemClientCopyServicesSym = "IOHIDEventSystemClientCopyServices"
)

const (
	KIOMainPortDefault = 0

	KIOHIDEventTypeTemperature = 15

	KNilOptions = 0
)

const (
	KIOMediaWholeKey = "Media"
	KIOServicePlane  = "IOService"
)

// CoreFoundation functions and symbols.
type (
	CFGetTypeIDFunc        func(cf uintptr) int32
	CFNumberCreateFunc     func(allocator uintptr, theType int32, valuePtr uintptr) unsafe.Pointer
	CFNumberGetValueFunc   func(num uintptr, theType int32, valuePtr uintptr) bool
	CFDictionaryCreateFunc func(allocator uintptr, keys, values *unsafe.Pointer, numValues int32,
		keyCallBacks, valueCallBacks uintptr) unsafe.Pointer
	CFDictionaryAddValueFunc      func(theDict, key, value uintptr)
	CFDictionaryGetValueFunc      func(theDict, key uintptr) unsafe.Pointer
	CFArrayGetCountFunc           func(theArray uintptr) int32
	CFArrayGetValueAtIndexFunc    func(theArray uintptr, index int32) unsafe.Pointer
	CFStringCreateMutableFunc     func(alloc uintptr, maxLength int32) unsafe.Pointer
	CFStringGetLengthFunc         func(theString uintptr) int32
	CFStringGetCStringFunc        func(theString uintptr, buffer CStr, bufferSize int32, encoding uint32)
	CFStringCreateWithCStringFunc func(alloc uintptr, cStr string, encoding uint32) unsafe.Pointer
	CFDataGetLengthFunc           func(theData uintptr) int32
	CFDataGetBytePtrFunc          func(theData uintptr) unsafe.Pointer
	CFReleaseFunc                 func(cf uintptr)
)

const (
	CFGetTypeIDSym               = "CFGetTypeID"
	CFNumberCreateSym            = "CFNumberCreate"
	CFNumberGetValueSym          = "CFNumberGetValue"
	CFDictionaryCreateSym        = "CFDictionaryCreate"
	CFDictionaryAddValueSym      = "CFDictionaryAddValue"
	CFDictionaryGetValueSym      = "CFDictionaryGetValue"
	CFArrayGetCountSym           = "CFArrayGetCount"
	CFArrayGetValueAtIndexSym    = "CFArrayGetValueAtIndex"
	CFStringCreateMutableSym     = "CFStringCreateMutable"
	CFStringGetLengthSym         = "CFStringGetLength"
	CFStringGetCStringSym        = "CFStringGetCString"
	CFStringCreateWithCStringSym = "CFStringCreateWithCString"
	CFDataGetLengthSym           = "CFDataGetLength"
	CFDataGetBytePtrSym          = "CFDataGetBytePtr"
	CFReleaseSym                 = "CFRelease"
)

const (
	KCFStringEncodingUTF8 = 0x08000100
	KCFNumberSInt64Type   = 4
	KCFNumberIntType      = 9
	KCFAllocatorDefault   = 0
)

// Kernel functions and symbols.
type MachTimeBaseInfo struct {
	Numer uint32
	Denom uint32
}

type (
	HostProcessorInfoFunc func(host uint32, flavor int32, outProcessorCount *uint32, outProcessorInfo uintptr,
		outProcessorInfoCnt *uint32) int
	HostStatisticsFunc   func(host uint32, flavor int32, hostInfoOut uintptr, hostInfoOutCnt *uint32) int
	MachHostSelfFunc     func() uint32
	MachTaskSelfFunc     func() uint32
	MachTimeBaseInfoFunc func(info uintptr) int
	VMDeallocateFunc     func(targetTask uint32, vmAddress, vmSize uintptr) int
)

const (
	HostProcessorInfoSym = "host_processor_info"
	HostStatisticsSym    = "host_statistics"
	MachHostSelfSym      = "mach_host_self"
	MachTaskSelfSym      = "mach_task_self"
	MachTimeBaseInfoSym  = "mach_timebase_info"
	VMDeallocateSym      = "vm_deallocate"
)

const (
	CTL_KERN       = 1
	KERN_ARGMAX    = 8
	KERN_PROCARGS2 = 49

	HOST_VM_INFO       = 2
	HOST_CPU_LOAD_INFO = 3

	HOST_VM_INFO_COUNT = 0xf
)

// System functions and symbols.
type (
	ProcPidPathFunc func(pid int32, buffer uintptr, bufferSize uint32) int32
	ProcPidInfoFunc func(pid, flavor int32, arg uint64, buffer uintptr, bufferSize int32) int32
)

const (
	SysctlSym      = "sysctl"
	ProcPidPathSym = "proc_pidpath"
	ProcPidInfoSym = "proc_pidinfo"
)

const (
	MAXPATHLEN               = 1024
	PROC_PIDPATHINFO_MAXSIZE = 4 * MAXPATHLEN
	PROC_PIDTASKINFO         = 4
	PROC_PIDVNODEPATHINFO    = 9
)

// SMC represents a SMC instance.
type SMC struct {
	lib        *Library
	conn       uint32
	callStruct IOConnectCallStructMethodFunc
}

const ioServiceSMC = "AppleSMC"

const (
	KSMCUserClientOpen  = 0
	KSMCUserClientClose = 1
	KSMCHandleYPCEvent  = 2
	KSMCReadKey         = 5
	KSMCWriteKey        = 6
	KSMCGetKeyCount     = 7
	KSMCGetKeyFromIndex = 8
	KSMCGetKeyInfo      = 9
)

const (
	KSMCSuccess     = 0
	KSMCError       = 1
	KSMCKeyNotFound = 132
)

func NewSMC(ioKit *Library) (*SMC, error) {
	if ioKit.path != IOKit {
		return nil, errors.New("library is not IOKit")
	}

	ioServiceGetMatchingService := GetFunc[IOServiceGetMatchingServiceFunc](ioKit, IOServiceGetMatchingServiceSym)
	ioServiceMatching := GetFunc[IOServiceMatchingFunc](ioKit, IOServiceMatchingSym)
	ioServiceOpen := GetFunc[IOServiceOpenFunc](ioKit, IOServiceOpenSym)
	ioObjectRelease := GetFunc[IOObjectReleaseFunc](ioKit, IOObjectReleaseSym)
	machTaskSelf := GetFunc[MachTaskSelfFunc](ioKit, MachTaskSelfSym)

	ioConnectCallStructMethod := GetFunc[IOConnectCallStructMethodFunc](ioKit, IOConnectCallStructMethodSym)

	service := ioServiceGetMatchingService(0, uintptr(ioServiceMatching(ioServiceSMC)))
	if service == 0 {
		return nil, fmt.Errorf("ERROR: %s NOT FOUND", ioServiceSMC)
	}

	var conn uint32
	if result := ioServiceOpen(service, machTaskSelf(), 0, &conn); result != 0 {
		return nil, errors.New("ERROR: IOServiceOpen failed")
	}

	ioObjectRelease(service)
	return &SMC{
		lib:        ioKit,
		conn:       conn,
		callStruct: ioConnectCallStructMethod,
	}, nil
}

func (s *SMC) CallStruct(selector uint32, inputStruct, inputStructCnt, outputStruct uintptr, outputStructCnt *uintptr) int {
	return s.callStruct(s.conn, selector, inputStruct, inputStructCnt, outputStruct, outputStructCnt)
}

func (s *SMC) Close() error {
	ioServiceClose := GetFunc[IOServiceCloseFunc](s.lib, IOServiceCloseSym)

	if result := ioServiceClose(s.conn); result != 0 {
		return errors.New("ERROR: IOServiceClose failed")
	}
	return nil
}

type CStr []byte

func NewCStr(length int32) CStr {
	return make(CStr, length)
}

func (s CStr) Length() int32 {
	// Include null terminator to make CFStringGetCString properly functions
	return int32(len(s)) + 1
}

func (s CStr) Ptr() *byte {
	if len(s) < 1 {
		return nil
	}

	return &s[0]
}

func (s CStr) Addr() uintptr {
	return uintptr(unsafe.Pointer(s.Ptr()))
}

func (s CStr) GoString() string {
	if s == nil {
		return ""
	}

	var length int
	for _, char := range s {
		if char == '\x00' {
			break
		}
		length++
	}
	return string(s[:length])
}

// https://github.com/ebitengine/purego/blob/main/internal/strings/strings.go#L26
func GoString(cStr *byte) string {
	if cStr == nil {
		return ""
	}
	var length int
	for *(*byte)(unsafe.Add(unsafe.Pointer(cStr), uintptr(length))) != '\x00' {
		length++
	}
	return string(unsafe.Slice(cStr, length))
}