2 * Copyright (c) 1999, 2006 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
24 #include <sys/cdefs.h>
31 #include <sys/types.h>
33 #include <sys/param.h>
36 #include <mach/mach.h>
37 #include <mach-o/arch.h>
38 #include <Foundation/Foundation.h>
41 #define ARCH_PROG "arch"
45 #define MACHINE_PROG "machine"
48 #define CPUCOUNT(c) ((c)->ptr - (c)->buf)
50 static NSMutableDictionary *ArchDict;
51 static NSString *KeyExecPath = @"ExecutablePath";
52 static NSString *KeyPlistVersion = @"PropertyListVersion";
53 static NSString *KeyPrefOrder = @"PreferredOrder";
54 static NSString *PlistExtension = @"plist";
55 static NSString *SettingsDir = @"archSettings";
57 static const char envname[] = "ARCHPREFERENCE";
71 static StrInt initArches[] = {
72 {"i386", CPU_TYPE_I386},
73 {"ppc", CPU_TYPE_POWERPC},
74 {"ppc64", CPU_TYPE_POWERPC64},
75 {"x86_64", CPU_TYPE_X86_64},
80 * arch - perform the original behavior of the arch and machine commands.
81 * The archcmd flag is non-zero for the arch command, zero for the machine
82 * command. This routine never returns.
87 const NXArchInfo *arch = NXGetLocalArchInfo();
90 errx(-1, "Unknown architecture.");
92 arch = NXGetArchInfoFromCpuType(arch->cputype, CPU_SUBTYPE_MULTIPLE);
94 errx(-1, "Unknown architecture.");
96 printf("%s%s", arch->name, (isatty(STDIN_FILENO) ? "\n" : ""));
101 * spawnIt - run the posix_spawn command. count is the number of CPU types
102 * in the prefs array. pflag is non-zero to call posix_spawnp; zero means to
103 * call posix_spawn. str is the name/path to pass to posix_spawn{,p}, and
104 * argv and environ are the argument and environment arrays to pass. This
105 * routine never returns.
108 spawnIt(int count, cpu_type_t *prefs, int pflag, const char *str, char **argv, char **environ)
111 posix_spawnattr_t attr;
116 if((ret = posix_spawnattr_init(&attr)) != 0)
117 errc(1, ret, "posix_spawnattr_init");
118 /* do the equivalent of exec, rather than creating a separate process */
119 if((ret = posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETEXEC)) != 0)
120 errc(1, ret, "posix_spawnattr_setflags");
121 if((ret = posix_spawnattr_setbinpref_np(&attr, count, prefs, &copied)) != 0)
122 errc(1, ret, "posix_spawnattr_setbinpref_np");
124 errx(1, "posix_spawnattr_setbinpref_np only copied %d of %d", (int)copied, count);
126 ret = posix_spawnp(&pid, str, NULL, &attr, argv, environ);
128 ret = posix_spawn(&pid, str, NULL, &attr, argv, environ);
129 errc(1, ret, "posix_spawn%s: %s", (pflag ? "p" : ""), str);
133 * initCPU - initialize a CPU structure, a dynamically expanding CPU types
139 cpu->buf = (cpu_type_t *)malloc(CPUDELTA * sizeof(cpu_type_t));
141 err(1, "Failed to malloc CPU buffer");
143 cpu->end = cpu->buf + CPUDELTA;
148 * addCPU - add a new CPU type value to the CPU structure, expanding
149 * the array as necessary.
152 addCPU(CPU *cpu, int n)
154 if(cpu->ptr >= cpu->end) {
155 cpu_type_t *new = realloc(cpu->buf, (cpu->end - cpu->buf + CPUDELTA) * sizeof(cpu_type_t));
157 err(1, "Out of memory realloc-ing CPU structure");
158 ptrdiff_t diff = (void *)new - (void *)cpu->buf;
160 cpu->ptr = (cpu_type_t *)((void *)cpu->ptr + diff);
161 cpu->end = (cpu_type_t *)((void *)cpu->end + diff) + CPUDELTA;
167 * addCPUbyname - add a new CPU type, given by name, to the CPU structure,
168 * expanding the array as necessary. The name is converted to a type value
169 * by the ArchDict dictionary.
172 addCPUbyname(CPU *cpu, const char *name)
174 NSNumber *n = (NSNumber *)[ArchDict objectForKey: [[NSString stringWithUTF8String: name] lowercaseString]];
176 warnx("Unknown architecture: %s", name);
180 addCPU(cpu, [n intValue]);
184 * useEnv - parse the environment variable for CPU preferences. Use name
185 * to look for program-specific preferences, and append any CPU types to cpu.
186 * Returns the number of CPU types. Returns any specified execute path in
189 * The environment variable ARCHPREFERENCE has the format:
191 * a semicolon separated list of specifiers. Each specifier has the format:
192 * [prog:[execpath:]]type[,type]...
193 * a comma separate list of CPU type names, optionally proceeded by a program
194 * name and an execpath. If program name exist, that types only apply to that
195 * program. If execpath is specified, it is returned. If no program name
196 * exists, then it applies to all programs. So ordering of the specifiers is
197 * important, as the default (no program name) specifier must be last.
200 useEnv(CPU *cpu, const char *name, char **execpath)
202 char *val = getenv(envname);
206 /* cp will point to the basename of name */
207 const char *cp = strrchr(name, '/');
211 errx(1, "%s: no name after last slash", name);
214 /* make a copy of the environment variable value, so we can modify it */
217 err(1, "Can't copy environment %s", envname);
220 /* for each specifier */
221 while((blk = strsep(&str, ";")) != NULL) {
223 continue; /* two adjacent semicolons */
224 /* now split on colons */
225 char *n = strsep(&blk, ":");
227 char *p = strsep(&blk, ":");
228 if(!blk) { /* there is only one colon, so no execpath */
231 } else if(!*p) /* two consecutive colons, so no execpath */
234 continue; /* no cpu list, so skip */
235 /* if the name matches, or there is no name, process the cpus */
236 if(!*n || strcmp(n, cp) == 0) {
237 if(CPUCOUNT(cpu) <= 0) { /* only if we don't already have cpu types */
239 while((t = strsep(&blk, ",")) != NULL)
240 addCPUbyname(cpu, t);
242 *execpath = (*n ? p : NULL); /* only use the exec path is name is set */
245 } else { /* no colons at all, so process as default */
246 if(CPUCOUNT(cpu) <= 0) { /* only if we don't already have cpu types */
248 while((n = strsep(&blk, ",")) != NULL)
249 addCPUbyname(cpu, n);
255 if(cpu->errs) /* errors during addCPUbyname are fatal */
257 return CPUCOUNT(cpu); /* return count of cpus */
261 * spawnFromPreference - called when argv[0] is not "arch" or "machine", or
262 * argv[0] was arch, but no commandline architectures were specified.
263 * If the environment variable ARCHPREFERENCE is specified, and there is a
264 * match to argv[0], use the specified cpu preferences. If no exec path
265 * is specified in ARCHPREFERENCE, or no match is found in ARCHPREFERENCE,
266 * get any additional information from a .plist file with the name of argv[0].
267 * This routine never returns.
270 spawnFromPreferences(CPU *cpu, int needexecpath, char **argv, char **environ)
274 const char *prog = strrchr(*argv, '/');
280 errx(1, "Not program name specified");
282 /* check the environment variable first */
283 if((count = useEnv(cpu, prog, &epath)) > 0) {
284 /* if we were called as arch, use posix_spawnp */
286 spawnIt(count, cpu->buf, 1, (epath ? epath : *argv), argv, environ);
287 /* otherwise, if we have the executable path, call posix_spawn */
289 spawnIt(count, cpu->buf, 0, epath, argv, environ);
292 /* pathArray is use to build the .plist file path for each domain */
293 NSMutableArray *pathArray = [NSMutableArray arrayWithCapacity: 3];
295 errx(1, "Can't create NSMutableArray");
296 [pathArray addObject: @""]; // placeholder for domain directory
297 [pathArray addObject: SettingsDir];
298 [pathArray addObject: [[NSString stringWithUTF8String: prog] stringByAppendingPathExtension: PlistExtension]];
300 /* get the list of top level directories for all domains */
301 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSAllDomainsMask, true);
302 int cnt = [paths count];
304 errx(1, "No domains");
306 /* create the .plist path, and try to read it */
308 NSString *path = NULL;
310 for(i = 0; i < cnt; i++) {
311 [pathArray replaceObjectAtIndex: 0 withObject: [paths objectAtIndex: i]];
312 path = [NSString pathWithComponents: pathArray];
313 data = [NSData dataWithContentsOfFile: path];
314 if(data) /* found it */
318 errx(1, "Can't find any plists for %s", prog);
320 /* try to convert the file into a NSDictionary */
322 id plist = [NSPropertyListSerialization propertyListFromData: data mutabilityOption: NSPropertyListImmutable format: nil errorDescription: &error];
324 errx(1, "%s: NSPropertyListSerialization error: %s", [path UTF8String], [error UTF8String]);
325 if(![plist isKindOfClass: [NSDictionary class]])
326 errx(1, "%s: plist not a dictionary", [path UTF8String]);
329 int errs = 0; /* scan for all errors and fail later */
330 do { /* begin block */
331 /* check the plist version */
332 NSString *vers = [(NSDictionary *)plist objectForKey: KeyPlistVersion];
334 warnx("%s: No key %s", [path UTF8String], [KeyPlistVersion UTF8String]);
336 } else if(![vers isKindOfClass: [NSString class]]) {
337 warnx("%s: %s is not a string", [path UTF8String], [KeyPlistVersion UTF8String]);
339 } else if(![vers isEqualToString: @"1.0"]) {
340 warnx("%s: %s not 1.0", [path UTF8String], [KeyPlistVersion UTF8String]);
343 /* get the execpath */
344 execpath = [(NSDictionary *)plist objectForKey: KeyExecPath];
346 warnx("%s: No key %s", [path UTF8String], [KeyExecPath UTF8String]);
348 } else if(![execpath isKindOfClass: [NSString class]]) {
349 warnx("%s: %s is not a string", [path UTF8String], [KeyExecPath UTF8String]);
352 /* if we already got cpu preferences from ARCHPREFERENCE, we are done */
355 /* otherwise, parse the cpu preferences from the plist */
356 id p = [(NSDictionary *)plist objectForKey: KeyPrefOrder];
358 warnx("%s: No key %s", [path UTF8String], [KeyPrefOrder UTF8String]);
360 } else if(![p isKindOfClass: [NSArray class]]) {
361 warnx("%s: %s is not an array", [path UTF8String], [KeyPrefOrder UTF8String]);
363 } else if((count = [p count]) == 0) {
364 warnx("%s: no entries in %s", [path UTF8String], [KeyPrefOrder UTF8String]);
367 /* finally but the cpu type array */
368 for(i = 0; i < count; i++) {
369 id a = [(NSArray *)p objectAtIndex: i];
371 if(![a isKindOfClass: [NSString class]]) {
372 warnx("%s: entries %d of %s is not a string", [path UTF8String], i, [KeyPrefOrder UTF8String]);
374 } else if((n = (NSNumber *)[ArchDict objectForKey: [(NSString *)a lowercaseString]]) == nil) {
375 warnx("%s: %s: unknown architecture %s", [path UTF8String], [KeyPrefOrder UTF8String], [(NSString *)a UTF8String]);
378 addCPU(cpu, [n intValue]);
382 } while(0); /* end block */
383 if(errs) /* exit if there were any reported errors */
386 /* call posix_spawn */
387 spawnIt(count, cpu->buf, 0, [execpath fileSystemRepresentation], argv, environ);
395 " Display the machine's architecture type\n"
396 "Usage: %s [-h] [[-arch_name | -arch arch_name] ...] prog [arg ...]\n"
397 " Run prog with any arguments, using the given architecture\n"
398 " order. If no architectures are specified, use the\n"
399 " ARCHPREFERENCE environment variable, or a property list file.\n"
400 " -h will print usage message and exit.\n",
401 ARCH_PROG, ARCH_PROG);
406 * wrapped - check the path to see if it is a link to /usr/bin/arch.
409 wrapped(const char *name)
415 char buf[MAXPATHLEN], rpbuf[MAXPATHLEN];
420 do { /* begin block */
421 /* If it's an absolute or relative path name, it's easy. */
422 if(index(name, '/')) {
423 if(stat(name, &sb) == 0 && S_ISREG(sb.st_mode) && access(name, X_OK) == 0) {
427 errx(1, "%s isn't executable", name);
430 /* search the PATH, looking for name */
431 if((path = getenv("PATH")) == NULL)
432 path = _PATH_DEFPATH;
434 cur = alloca(strlen(path) + 1);
438 while((p = strsep(&cur, ":")) != NULL) {
440 * It's a SHELL path -- double, leading and trailing colons
441 * mean the current directory.
450 * If the path is too long complain. This is a possible
451 * security issue; given a way to make the path too long
452 * the user may execute the wrong program.
454 if(lp + ln + 2 > sizeof(buf)) {
455 warn("%s: path too long", p);
460 bcopy(name, buf + lp + 1, ln);
461 buf[lp + ln + 1] = '\0';
462 if(stat(buf, &sb) == 0 && S_ISREG(sb.st_mode) && access(buf, X_OK) == 0) {
468 errx(1, "Can't find %s in PATH", name);
469 } while(0); /* end block */
470 if(realpath(bp, rpbuf) == NULL)
471 errx(1, "realpath failed on %s", bp);
472 return (strcmp(rpbuf, "/usr/bin/" ARCH_PROG) == 0);
476 * spawnFromArgs - called when arch has arguments specified. The arch command
477 * line arguments are:
478 * % arch [[{-xxx | -arch xxx}]...] prog [arg]...
479 * where xxx is a cpu name, and the command to execute and its arguments follow.
480 * If no commandline cpu names are given, the environment variable
481 * ARCHPREFERENCE is used. This routine never returns.
484 spawnFromArgs(CPU *cpu, char **argv, char **environ)
488 /* process cpu options */
489 for(argv++; *argv && **argv == '-'; argv++) {
490 if(strcmp(*argv, "-arch") == 0) {
491 if(*++argv == NULL) {
492 warnx("-arch without architecture");
496 } else if(strcmp(*argv, "-h") == 0) {
500 addCPUbyname(cpu, ap);
504 if(!*argv || !**argv) {
505 warnx("No command to execute");
508 /* if the program is already a link to arch, then force execpath */
509 int needexecpath = wrapped(*argv);
512 * If we don't have any architecutures, try ARCHPREFERENCE and plist
515 int count = CPUCOUNT(cpu);
516 if(count <= 0 || needexecpath)
517 spawnFromPreferences(cpu, needexecpath, argv, environ); /* doesn't return */
520 * Call posix_spawnp on the program name.
522 spawnIt(count, cpu->buf, 1, *argv, argv, environ);
526 * init - initializes the ArchDict dictionary from the values in initArches,
527 * and the CPU structure.
532 ArchDict = [NSMutableDictionary dictionaryWithCapacity: 4];
534 errx(1, "Can't create NSMutableDictionary");
536 for(sp = initArches; sp->str; sp++) {
537 NSString *s = [NSString stringWithUTF8String: sp->str];
539 errx(1, "Can't create NSString for %s", sp->str);
540 NSNumber *n = [NSNumber numberWithInt: sp->i];
542 errx(1, "Can't create NSNumber for %s", sp->str);
543 [ArchDict setObject: n forKey: s];
548 /* the main() routine */
550 main(int argc, char **argv, char **environ)
552 const char *prog = getprogname();
556 if(strcmp(prog, MACHINE_PROG) == 0) {
558 errx(-1, "no arguments accepted");
559 arch(0); /* the "machine" command was called */
560 } else if((my_name_is_arch = (strcmp(prog, ARCH_PROG) == 0))) {
562 arch(1); /* the "arch" command with no arguments was called */
565 /* set up Objective C autorelease pool */
566 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
567 init(&cpu); /* initialize */
570 spawnFromArgs(&cpu, argv, environ);
572 spawnFromPreferences(&cpu, 1, argv, environ);
573 /* should never get here */
575 errx(1, "returned from spawn");