magic numbers? (teach me, please)

Guy Harris guy at sun.uucp
Fri Nov 29 07:03:16 AEST 1985


> >	1)  How does the shell (exec?) know whether the command I just typed
> >		is a shell script or one of several possible types of
> >		executable?
> 
> The shell doesn't know.  The shell merely tells the kernel to exec the
> file, after doing a fork.  The kernel determines if a file is a binary
> executable by the magic number, which is obtained by reading an a.out.h
> structure (4.1,4.2)

And V7 and System III, and maybe Version 8.

> or filehdr.h (sys 5) and comparing it against hardcoded numbers in the
> kernel.  The kernel also recognizes 
> #! /your/shellname
> at the beginning of a file and execs off the appropriate shell instead.

The *4.1 or 4.2 or Version 8* kernel recognizes "#! shellname"; this isn't
in V7 or S3/S5 (although it could be added).

In the case of other systems, or shell scripts which *don't* have a "#!"
line at the beginning, the kernel sees that the file isn't an executable,
and returns to the (forked) shell with an error indicating this.  The shell
then sees that the file had execute permission but wasn't an executable, and
runs it as a script.  In the C shell, and the 4.1/4.1 Bourne shells, there
is a convention that if the first character of the script is a "#" that it's
a C shell script and that if it's a ":" it's a Bourne shell script (this is
because ":" used to be the only form of comment in the V6 and Bourne shells,
and "#" was a comment character in the C shell; however, the 4.1/4.2 and
S3/S5 Bourne shells accept "#" as a comment, so this convention is now a
crock).  They would "exec" the other shell if the first character of the
script so indicated; otherwise, they'd interpret it themselves.

> >	2)  Presuming the answer to #1 above has something to do with
> >		magic numbers, who issues them?  is there a common
> >		(definitive) base of them or does each
> >		manufacturer/environment make up their own set?
> 
> The magic number is issued by the linker/loader.

I think that by "issued" he meant "who decides what the magic number is"; as
you point out, this is done by the manufacturer.  Some of them are specified
for System V as part of the Common Object File Format (does anybody know why
there seem to be four(!) different magic numbers for 68000-family
executables?).  I don't think AT&T acts as a clearinghouse for them, though,
so if you've just ported UNIX to your new 27-bit machine I guess you get to
choose your own.

	Guy Harris



More information about the Comp.unix.wizards mailing list