Ok so here is what I came up with. This works fine, the only thing I have yet to see is if it has any memory leaks. I hope this helps someone in the future :) If you have any suggestions to the func please let me know.
Also, you should first convert the audit_token to pid using the function mentioned above.
func getArgs(from pid: Int32) -> [NSString]? {
var arguments: [NSString] = []
var mib: [Int32] = [0, 0, 0]
var argsMax: Int = 0
mib[0] = CTL_KERN
mib[1] = KERN_ARGMAX
var size = MemoryLayout<Int>.stride(ofValue: argsMax)
if sysctl(&mib, 2, &argsMax, &size, nil, 0) == -1 {
return nil
}
let processArgs = UnsafeMutablePointer<CChar>.allocate(capacity: argsMax)
mib[0] = CTL_KERN
mib[1] = KERN_PROCARGS2
mib[2] = pid
size = argsMax as size_t
// Get process arguments
if sysctl(&mib, 3, processArgs, &size, nil, 0) == -1 {
return nil
}
if size <= MemoryLayout<Int>.size {
return nil
}
var numberOfArgs: Int32 = 0
//Get number of args
memcpy(&numberOfArgs, processArgs, MemoryLayout.size(ofValue: numberOfArgs))
// Initialize the pointer to the start of args
var parser: UnsafeMutablePointer<CChar> = processArgs + MemoryLayout.size(ofValue: numberOfArgs)
// Iterate until NULL terminated path
while parser < &processArgs[size] {
if 0x0 == parser.pointee {
// arrived ar argv[0]
break
}
parser += 1
}
// sanity check
if parser == &processArgs[size] {
return nil
}
while parser < &processArgs[size] {
if 0x0 != parser.pointee {
break
}
parser += 1
}
// sanity check
if parser == &processArgs[size] {
return nil
}
var argStart: UnsafeMutablePointer<CChar>? = parser
// Get all args
while parser < &processArgs[size] {
if parser.pointee == CChar(0) {
if nil != argStart {
let argument = NSString(utf8String: argStart!)
if argument != nil {
arguments.append(argument!)
}
}
argStart = parser + 1
if arguments.count == numberOfArgs {
break
}
}
parser += 1
}
// Is this free necessary?
free(processArgs)
return arguments
}