48 lines
2.7 KiB
Swift
48 lines
2.7 KiB
Swift
import Foundation
|
|
import Darwin
|
|
|
|
@main struct ProcessEnergyReaderChecks {
|
|
static func main() throws {
|
|
var bsd = proc_bsdinfo()
|
|
precondition(proc_pidinfo(getpid(), PROC_PIDTBSDINFO, 0, &bsd, Int32(MemoryLayout.size(ofValue: bsd))) > 0)
|
|
let id = ProcessIdentity(pid: getpid(), seconds: bsd.pbi_start_tvsec, microseconds: bsd.pbi_start_tvusec)
|
|
func read(_ ids: [ProcessIdentity]) throws -> ProcessEnergyReply {
|
|
let request = ProcessEnergyRequest(token: UUID(), identities: ids)
|
|
let data = try JSONEncoder().encode(request)
|
|
let reply = try JSONDecoder().decode(ProcessEnergyReply.self, from: ProcessEnergyReader.read(data)!)
|
|
precondition(reply.token == request.token && reply.readings.count == ids.count)
|
|
return reply
|
|
}
|
|
usleep(10_000)
|
|
let first = try read([id]).readings[0]
|
|
#if arch(arm64)
|
|
let start = ProcessInfo.processInfo.systemUptime
|
|
var work: UInt64 = 1
|
|
while ProcessInfo.processInfo.systemUptime - start < 0.15 { work = work &* 6364136223846793005 &+ 1 }
|
|
usleep(10_000) // Let scheduler accounting include the completed CPU slice.
|
|
let second = try read([id])
|
|
precondition(second.capability == .verifiedCPU && second.readings[0].nanojoules! > first.nanojoules!)
|
|
precondition(second.readings[0].birth == first.birth && second.readings[0].uptime > first.uptime)
|
|
print("PASS: live same-UID CPU energy counter advances under controlled CPU work", work)
|
|
#else
|
|
precondition(first.status == .unsupported)
|
|
#endif
|
|
let wrong = ProcessIdentity(pid: getpid(), seconds: id.seconds + 1, microseconds: id.microseconds)
|
|
let mismatched = try read([wrong])
|
|
#if arch(arm64)
|
|
precondition(mismatched.readings[0].status == .identityChanged)
|
|
let denied = try read([ProcessIdentity(pid: 1, seconds: 1, microseconds: 0)])
|
|
precondition(denied.readings[0].status == .denied || denied.readings[0].status == .gone)
|
|
#endif
|
|
precondition(ProcessEnergyReader.read(Data(repeating: 0, count: ProcessEnergyRequest.byteLimit + 1)) == nil)
|
|
let duplicates = try JSONEncoder().encode(ProcessEnergyRequest(token: UUID(), identities: [id, id]))
|
|
precondition(ProcessEnergyReader.read(duplicates) == nil)
|
|
precondition(ProcessEnergyReader.read(Data("not json".utf8)) == nil)
|
|
let tooMany = try JSONEncoder().encode(ProcessEnergyRequest(token: UUID(), identities: (1...257).map {
|
|
ProcessIdentity(pid: Int32($0), seconds: 1, microseconds: 0)
|
|
}))
|
|
precondition(ProcessEnergyReader.read(tooMany) == nil)
|
|
print("PASS: nonce/identity, permission, duplicate and byte/decode boundaries")
|
|
}
|
|
}
|