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>
32 #include <sys/types.h>
34 #include <sys/param.h>
37 #include <mach/mach.h>
38 #include <mach-o/arch.h>
39 #include <Foundation/Foundation.h>
40 #include <TargetConditionals.h>
43 #define ARCH_PROG "arch"
47 #define MACHINE_PROG "machine"
50 #define CPUCOUNT(c) ((c)->ptr - (c)->buf)
52 static NSMutableDictionary *ArchDict;
53 static NSString *KeyExecPath = @"ExecutablePath";
54 static NSString *KeyPlistVersion = @"PropertyListVersion";
55 static NSString *KeyPrefOrder = @"PreferredOrder";
56 static NSString *PlistExtension = @"plist";
57 static NSString *SettingsDir = @"archSettings";
59 static const char envname[] = "ARCHPREFERENCE";
73 static const CPUTypes initArches[] = {
74 #if defined(__i386__) || defined(__x86_64__)
75 {"i386", CPU_TYPE_I386},
76 {"x86_64", CPU_TYPE_X86_64},
77 #elif defined(__arm__)
78 {"arm", CPU_TYPE_ARM},
80 #error "Unsupported architecture"
86 * ignore contains architectures supported by previous releases, but
87 * now unsupported. The seen field will be set to true if the corresponding
88 * architecture was specified.
96 static Ignore ignore[] = {
97 #if defined(__i386__) || defined(__x86_64__)
101 {NULL, false} // sentinel
104 /* The total number of architectures specified */
105 static int archCount = 0;
107 /* environment SPI */
108 char **_copyenv(char **env);
109 int _setenvp(const char *name, const char *value, int rewrite, char ***envp, void *state);
110 int _unsetenvp(const char *name, char ***envp, void *state);
112 /* copy of environment */
113 char **envCopy = NULL;
114 extern char **environ;
117 * The native 32 and 64-bit architectures (this is relative to the architecture
118 * the arch command is running. NULL means unsupported.
120 #if defined(__i386__) || defined(__x86_64__)
121 #define NATIVE_32 "i386"
122 #define NATIVE_64 "x86_64"
123 #elif defined(__arm__)
124 #define NATIVE_32 "arm"
125 #define NATIVE_64 NULL
127 #error "Unsupported architecture"
129 bool native32seen = false;
130 bool native64seen = false;
133 * arch - perform the original behavior of the arch and machine commands.
134 * The archcmd flag is non-zero for the arch command, zero for the machine
135 * command. This routine never returns.
140 const NXArchInfo *arch = NXGetLocalArchInfo();
143 errx(-1, "Unknown architecture.");
145 arch = NXGetArchInfoFromCpuType(arch->cputype, CPU_SUBTYPE_MULTIPLE);
147 errx(-1, "Unknown architecture.");
149 printf("%s%s", arch->name, (isatty(STDIN_FILENO) ? "\n" : ""));
154 * spawnIt - run the posix_spawn command. cpu is the auto-sizing CPU structure.
155 * pflag is non-zero to call posix_spawnp; zero means to call posix_spawn.
156 * str is the name/path to pass to posix_spawn{,p}, and argv are
157 * the argument arrays to pass. This routine never returns.
160 spawnIt(CPU *cpu, int pflag, const char *str, char **argv)
162 posix_spawnattr_t attr;
167 int count = CPUCOUNT(cpu);
168 cpu_type_t *prefs = cpu->buf;
171 if(archCount == 0) // shouldn't happen
172 errx(1, "spawnIt called with no architectures specified");
173 for(ip = ignore; ip->arch; ip++) {
175 warnx("Unsupported architecture: %s", ip->arch);
178 warnx("Unsupported native 32-bit architecture");
180 warnx("Unsupported native 64-bit architecture");
183 for(ip = ignore; ip->arch; ip++) {
185 fprintf(stderr, "warning: unsupported architecture: %s\n", ip->arch);
188 fprintf(stderr, "warning: unsupported native 32-bit architecture\n");
190 fprintf(stderr, "warning: unsupported native 64-bit architecture\n");
192 if((ret = posix_spawnattr_init(&attr)) != 0)
193 errc(1, ret, "posix_spawnattr_init");
194 /* do the equivalent of exec, rather than creating a separate process */
195 if((ret = posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETEXEC)) != 0)
196 errc(1, ret, "posix_spawnattr_setflags");
197 if((ret = posix_spawnattr_setbinpref_np(&attr, count, prefs, &copied)) != 0)
198 errc(1, ret, "posix_spawnattr_setbinpref_np");
200 errx(1, "posix_spawnattr_setbinpref_np only copied %d of %d", (int)copied, count);
202 ret = posix_spawnp(&pid, str, NULL, &attr, argv, envCopy ? envCopy : environ);
204 ret = posix_spawn(&pid, str, NULL, &attr, argv, envCopy ? envCopy : environ);
205 errc(1, ret, "posix_spawn%s: %s", (pflag ? "p" : ""), str);
209 * initCPU - initialize a CPU structure, a dynamically expanding CPU types
215 cpu->buf = (cpu_type_t *)malloc(CPUDELTA * sizeof(cpu_type_t));
217 err(1, "Failed to malloc CPU buffer");
219 cpu->end = cpu->buf + CPUDELTA;
224 * addCPU - add a new CPU type value to the CPU structure, expanding
225 * the array as necessary.
228 addCPU(CPU *cpu, int n)
231 if(n <= 0) { // ignore values
232 ignore[-n].seen = true; // negate to get real index
235 if(cpu->ptr >= cpu->end) {
236 cpu_type_t *new = realloc(cpu->buf, (cpu->end - cpu->buf + CPUDELTA) * sizeof(cpu_type_t));
238 err(1, "Out of memory realloc-ing CPU structure");
239 ptrdiff_t diff = (void *)new - (void *)cpu->buf;
241 cpu->ptr = (cpu_type_t *)((void *)cpu->ptr + diff);
242 cpu->end = (cpu_type_t *)((void *)cpu->end + diff) + CPUDELTA;
248 * addCPUbyname - add a new CPU type, given by name, to the CPU structure,
249 * expanding the array as necessary. The name is converted to a type value
250 * by the ArchDict dictionary.
253 addCPUbyname(CPU *cpu, const char *name)
255 NSNumber *n = (NSNumber *)[ArchDict objectForKey: [[NSString stringWithUTF8String: name] lowercaseString]];
257 warnx("Unknown architecture: %s", name);
261 addCPU(cpu, [n intValue]);
265 * useEnv - parse the environment variable for CPU preferences. Use name
266 * to look for program-specific preferences, and append any CPU types to cpu.
267 * Returns the number of CPU types. Returns any specified execute path in
270 * The environment variable ARCHPREFERENCE has the format:
272 * a semicolon separated list of specifiers. Each specifier has the format:
273 * [prog:[execpath:]]type[,type]...
274 * a comma separate list of CPU type names, optionally proceeded by a program
275 * name and an execpath. If program name exist, that types only apply to that
276 * program. If execpath is specified, it is returned. If no program name
277 * exists, then it applies to all programs. So ordering of the specifiers is
278 * important, as the default (no program name) specifier must be last.
281 useEnv(CPU *cpu, const char *name, char **execpath)
283 char *val = getenv(envname);
287 /* cp will point to the basename of name */
288 const char *cp = strrchr(name, '/');
292 errx(1, "%s: no name after last slash", name);
295 /* make a copy of the environment variable value, so we can modify it */
298 err(1, "Can't copy environment %s", envname);
301 /* for each specifier */
302 while((blk = strsep(&str, ";")) != NULL) {
304 continue; /* two adjacent semicolons */
305 /* now split on colons */
306 char *n = strsep(&blk, ":");
308 char *p = strsep(&blk, ":");
309 if(!blk) { /* there is only one colon, so no execpath */
312 } else if(!*p) /* two consecutive colons, so no execpath */
315 continue; /* no cpu list, so skip */
316 /* if the name matches, or there is no name, process the cpus */
317 if(!*n || strcmp(n, cp) == 0) {
318 if(archCount <= 0) { /* only if we haven't processed architectures */
320 while((t = strsep(&blk, ",")) != NULL)
321 addCPUbyname(cpu, t);
323 *execpath = (*n ? p : NULL); /* only use the exec path is name is set */
326 } else { /* no colons at all, so process as default */
327 if(archCount <= 0) { /* only if we haven't processed architectures */
329 while((n = strsep(&blk, ",")) != NULL)
330 addCPUbyname(cpu, n);
336 if(cpu->errs) /* errors during addCPUbyname are fatal */
338 return archCount; /* return count of architectures */
342 * spawnFromPreference - called when argv[0] is not "arch" or "machine", or
343 * argv[0] was arch, but no commandline architectures were specified.
344 * If the environment variable ARCHPREFERENCE is specified, and there is a
345 * match to argv[0], use the specified cpu preferences. If no exec path
346 * is specified in ARCHPREFERENCE, or no match is found in ARCHPREFERENCE,
347 * get any additional information from a .plist file with the name of argv[0].
348 * This routine never returns.
351 spawnFromPreferences(CPU *cpu, int needexecpath, char **argv)
355 const char *prog = strrchr(*argv, '/');
361 errx(1, "Not program name specified");
363 /* check the environment variable first */
364 if((count = useEnv(cpu, prog, &epath)) > 0) {
365 /* if we were called as arch, use posix_spawnp */
367 spawnIt(cpu, 1, (epath ? epath : *argv), argv);
368 /* otherwise, if we have the executable path, call posix_spawn */
370 spawnIt(cpu, 0, epath, argv);
373 /* pathArray is use to build the .plist file path for each domain */
374 NSMutableArray *pathArray = [NSMutableArray arrayWithCapacity: 3];
376 errx(1, "Can't create NSMutableArray");
377 [pathArray addObject: @""]; // placeholder for domain directory
378 [pathArray addObject: SettingsDir];
379 [pathArray addObject: [[NSString stringWithUTF8String: prog] stringByAppendingPathExtension: PlistExtension]];
381 /* get the list of top level directories for all domains */
382 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSAllDomainsMask, true);
383 int cnt = [paths count];
385 errx(1, "No domains");
387 /* create the .plist path, and try to read it */
389 NSString *path = NULL;
391 for(i = 0; i < cnt; i++) {
392 [pathArray replaceObjectAtIndex: 0 withObject: [paths objectAtIndex: i]];
393 path = [NSString pathWithComponents: pathArray];
394 data = [NSData dataWithContentsOfFile: path];
395 if(data) /* found it */
399 errx(1, "Can't find any plists for %s", prog);
401 /* try to convert the file into a NSDictionary */
403 id plist = [NSPropertyListSerialization propertyListFromData: data mutabilityOption: NSPropertyListImmutable format: nil errorDescription: &error];
405 errx(1, "%s: NSPropertyListSerialization error: %s", [path UTF8String], [error UTF8String]);
406 if(![plist isKindOfClass: [NSDictionary class]])
407 errx(1, "%s: plist not a dictionary", [path UTF8String]);
410 int errs = 0; /* scan for all errors and fail later */
411 do { /* begin block */
412 /* check the plist version */
413 NSString *vers = [(NSDictionary *)plist objectForKey: KeyPlistVersion];
415 warnx("%s: No key %s", [path UTF8String], [KeyPlistVersion UTF8String]);
417 } else if(![vers isKindOfClass: [NSString class]]) {
418 warnx("%s: %s is not a string", [path UTF8String], [KeyPlistVersion UTF8String]);
420 } else if(![vers isEqualToString: @"1.0"]) {
421 warnx("%s: %s not 1.0", [path UTF8String], [KeyPlistVersion UTF8String]);
424 /* get the execpath */
425 execpath = [(NSDictionary *)plist objectForKey: KeyExecPath];
427 warnx("%s: No key %s", [path UTF8String], [KeyExecPath UTF8String]);
429 } else if(![execpath isKindOfClass: [NSString class]]) {
430 warnx("%s: %s is not a string", [path UTF8String], [KeyExecPath UTF8String]);
433 /* if we already got cpu preferences from ARCHPREFERENCE, we are done */
436 /* otherwise, parse the cpu preferences from the plist */
437 id p = [(NSDictionary *)plist objectForKey: KeyPrefOrder];
439 warnx("%s: No key %s", [path UTF8String], [KeyPrefOrder UTF8String]);
441 } else if(![p isKindOfClass: [NSArray class]]) {
442 warnx("%s: %s is not an array", [path UTF8String], [KeyPrefOrder UTF8String]);
444 } else if((count = [p count]) == 0) {
445 warnx("%s: no entries in %s", [path UTF8String], [KeyPrefOrder UTF8String]);
448 /* finally build the cpu type array */
449 for(i = 0; i < count; i++) {
450 id a = [(NSArray *)p objectAtIndex: i];
452 if(![a isKindOfClass: [NSString class]]) {
453 warnx("%s: entries %d of %s is not a string", [path UTF8String], i, [KeyPrefOrder UTF8String]);
455 } else if((n = (NSNumber *)[ArchDict objectForKey: [(NSString *)a lowercaseString]]) == nil) {
456 warnx("%s: %s: unknown architecture %s", [path UTF8String], [KeyPrefOrder UTF8String], [(NSString *)a UTF8String]);
459 addCPU(cpu, [n intValue]);
463 } while(0); /* end block */
464 if(errs) /* exit if there were any reported errors */
467 /* call posix_spawn */
468 spawnIt(cpu, 0, [execpath fileSystemRepresentation], argv);
476 " Display the machine's architecture type\n"
477 "Usage: %s {-arch_name | -arch arch_name} ... [-c] [-d envname] ... [-e envname=value] ... [-h] prog [arg ...]\n"
478 " Run prog with any arguments, using the given architecture\n"
479 " order. If no architectures are specified, use the\n"
480 " ARCHPREFERENCE environment variable, or a property list file.\n"
481 " -c will clear out all environment variables before running prog.\n"
482 " -d will delete the given environment variable before running prog.\n"
483 " -e will add the given environment variable/value before running prog.\n"
484 " -h will print usage message and exit.\n",
485 ARCH_PROG, ARCH_PROG);
490 * wrapped - check the path to see if it is a link to /usr/bin/arch.
493 wrapped(const char *name)
499 char buf[MAXPATHLEN], rpbuf[MAXPATHLEN];
504 do { /* begin block */
505 /* If it's an absolute or relative path name, it's easy. */
506 if(index(name, '/')) {
507 if(stat(name, &sb) == 0 && S_ISREG(sb.st_mode) && access(name, X_OK) == 0) {
511 errx(1, "%s isn't executable", name);
514 /* search the PATH, looking for name */
515 if((path = getenv("PATH")) == NULL)
516 path = _PATH_DEFPATH;
518 cur = alloca(strlen(path) + 1);
522 while((p = strsep(&cur, ":")) != NULL) {
524 * It's a SHELL path -- double, leading and trailing colons
525 * mean the current directory.
534 * If the path is too long complain. This is a possible
535 * security issue; given a way to make the path too long
536 * the user may execute the wrong program.
538 if(lp + ln + 2 > sizeof(buf)) {
539 warn("%s: path too long", p);
544 bcopy(name, buf + lp + 1, ln);
545 buf[lp + ln + 1] = '\0';
546 if(stat(buf, &sb) == 0 && S_ISREG(sb.st_mode) && access(buf, X_OK) == 0) {
552 errx(1, "Can't find %s in PATH", name);
553 } while(0); /* end block */
554 if(realpath(bp, rpbuf) == NULL)
555 errx(1, "realpath failed on %s", bp);
556 return (strcmp(rpbuf, "/usr/bin/" ARCH_PROG) == 0);
560 * spawnFromArgs - called when arch has arguments specified. The arch command
561 * line arguments are:
562 * % arch [[{-xxx | -arch xxx}]...] prog [arg]...
563 * where xxx is a cpu name, and the command to execute and its arguments follow.
564 * If no commandline cpu names are given, the environment variable
565 * ARCHPREFERENCE is used. This routine never returns.
568 #define MATCHARG(a,m) ({ \
569 const char *arg = *(a); \
570 if(arg[1] == '-') arg++; \
571 strcmp(arg, (m)) == 0; \
574 #define MATCHARGWITHVALUE(a,m,n,e) ({ \
575 const char *ret = NULL; \
576 const char *arg = *(a); \
577 if(arg[1] == '-') arg++; \
578 if(strcmp(arg, (m)) == 0) { \
579 if(*++(a) == NULL) { \
584 } else if(strncmp(arg, (m), (n)) == 0 && arg[n] == '=') { \
585 ret = arg + (n) + 1; \
590 #define MAKEENVCOPY(e) \
592 envCopy = _copyenv(environ); \
593 if(envCopy == NULL) \
598 spawnFromArgs(CPU *cpu, char **argv)
600 const char *ap, *ret;
602 /* process arguments */
603 for(argv++; *argv && **argv == '-'; argv++) {
604 if((ret = MATCHARGWITHVALUE(argv, "-arch", 5, "-arch without architecture"))) {
606 } else if(MATCHARG(argv, "-32")) {
613 } else if(MATCHARG(argv, "-64")) {
620 } else if(MATCHARG(argv, "-c")) {
622 envCopy = _copyenv(NULL); // create empty environment
624 errx(1, "Out of memory processing -c");
626 } else if((ret = MATCHARGWITHVALUE(argv, "-d", 2, "-d without envname"))) {
627 MAKEENVCOPY("Out of memory processing -d");
628 _unsetenvp(ret, &envCopy, NULL);
630 } else if((ret = MATCHARGWITHVALUE(argv, "-e", 2, "-e without envname=value"))) {
631 MAKEENVCOPY("Out of memory processing -e");
632 const char *cp = strchr(ret, '=');
634 warnx("-e %s: no equal sign", ret);
637 cp++; // skip to value
639 * _setenvp() only uses the name before any equal sign found in
640 * the first argument.
642 _setenvp(ret, cp, 1, &envCopy, NULL);
644 } else if(MATCHARG(argv, "-h")) {
650 addCPUbyname(cpu, ap);
654 if(!*argv || !**argv) {
655 warnx("No command to execute");
658 /* if the program is already a link to arch, then force execpath */
659 int needexecpath = wrapped(*argv);
662 * If we don't have any architecutures, try ARCHPREFERENCE and plist
665 if(archCount <= 0 || needexecpath)
666 spawnFromPreferences(cpu, needexecpath, argv); /* doesn't return */
669 * Call posix_spawnp on the program name.
671 spawnIt(cpu, 1, *argv, argv);
675 * init - initializes the ArchDict dictionary from the values in initArches,
676 * and the CPU structure.
681 ArchDict = [NSMutableDictionary dictionaryWithCapacity: 4];
683 errx(1, "Can't create NSMutableDictionary");
685 for(cp = initArches; cp->arch; cp++) {
686 NSString *s = [NSString stringWithUTF8String: cp->arch];
688 errx(1, "Can't create NSString for %s", cp->arch);
689 NSNumber *n = [NSNumber numberWithInt: cp->cpu];
691 errx(1, "Can't create NSNumber for %s", cp->arch);
692 [ArchDict setObject: n forKey: s];
695 * The valid architecture numbers above are one or greater. The ignore
696 * values are the negative of the index in the ignore array.
700 for(ip = ignore, i = 0; ip->arch; ip++, i--) { // i is negative of index
701 NSString *s = [NSString stringWithUTF8String: ip->arch];
703 errx(1, "Can't create NSString for %s", ip->arch);
704 NSNumber *n = [NSNumber numberWithInt: i];
706 errx(1, "Can't create NSNumber for %s", ip->arch);
707 [ArchDict setObject: n forKey: s];
712 /* the main() routine */
714 main(int argc, char **argv)
716 const char *prog = getprogname();
720 if(strcmp(prog, MACHINE_PROG) == 0) {
722 errx(-1, "no arguments accepted");
723 arch(0); /* the "machine" command was called */
724 } else if((my_name_is_arch = (strcmp(prog, ARCH_PROG) == 0))) {
726 arch(1); /* the "arch" command with no arguments was called */
729 /* set up Objective C autorelease pool */
730 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
731 init(&cpu); /* initialize */
734 spawnFromArgs(&cpu, argv);
736 spawnFromPreferences(&cpu, 1, argv);
737 /* should never get here */
739 errx(1, "returned from spawn");