reexec_to_match_kernel.c [plain text]
#include <sys/cdefs.h>
#include <spawn.h>
#include <errno.h>
#include <crt_externs.h>
#include <mach/mach.h>
#include <mach-o/loader.h>
#include <mach-o/dyld.h>
#include <sys/sysctl.h>
#include <stdlib.h>
#include <stdio.h>
#include "libutil.h"
static cpu_type_t current_program_arch(void);
static cpu_type_t current_kernel_arch(void);
static int reexec(cpu_type_t cputype);
#define kReExec "REEXEC_TO_MATCH_KERNEL"
int reexec_to_match_kernel(void)
{
cpu_type_t kernarch, progarch;
char *alreadyenv;
alreadyenv = getenv(kReExec);
if (alreadyenv) {
return 0;
}
kernarch = current_kernel_arch();
progarch = current_program_arch();
if (kernarch == 0) {
errno = EINVAL;
return -1;
}
if (kernarch == progarch) {
return 0;
}
return reexec(kernarch);
}
static cpu_type_t current_program_arch(void)
{
cpu_type_t current_arch = (_NSGetMachExecuteHeader())->cputype;
return current_arch;
}
static cpu_type_t current_kernel_arch(void)
{
struct host_basic_info hi;
unsigned int size;
kern_return_t kret;
cpu_type_t current_arch;
int ret, mib[4];
size_t len;
struct kinfo_proc kp;
size = sizeof(hi)/sizeof(int);
kret = host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hi, &size);
if (kret != KERN_SUCCESS) {
return 0;
}
current_arch = hi.cpu_type;
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PID;
mib[3] = 0;
len = sizeof(kp);
ret = sysctl(mib, sizeof(mib)/sizeof(mib[0]), &kp, &len, NULL, 0);
if (ret == -1) {
return 0;
}
if (kp.kp_proc.p_flag & P_LP64) {
current_arch |= CPU_ARCH_ABI64;
}
return current_arch;
}
static int reexec(cpu_type_t cputype)
{
posix_spawnattr_t attr;
int ret, envcount;
size_t copied = 0;
char **argv, **oldenvp, **newenvp;
char execpath[MAXPATHLEN+1];
uint32_t execsize;
argv = *_NSGetArgv();
oldenvp = *_NSGetEnviron();
for (envcount = 0; oldenvp[envcount]; envcount++);
newenvp = calloc(envcount+2, sizeof(newenvp[0]));
for (envcount = 0; oldenvp[envcount]; envcount++) {
newenvp[envcount] = oldenvp[envcount];
}
newenvp[envcount++] = kReExec"=1";
newenvp[envcount] = NULL;
execsize = (uint32_t)sizeof(execpath);
ret = _NSGetExecutablePath(execpath, &execsize);
if (ret != 0) {
return -1;
}
ret = posix_spawnattr_init(&attr);
if (ret != 0) {
return -1;
}
ret = posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETEXEC);
if (ret != 0) {
return -1;
}
ret = posix_spawnattr_setbinpref_np(&attr, 1, &cputype, &copied);
if (ret != 0 || copied != 1) {
return -1;
}
ret = posix_spawn(NULL, execpath, NULL, &attr, argv, newenvp);
if (ret != 0) {
errno = ret;
return -1;
}
return 0;
}