[comp.sys.tandy] ARRGGH! Beware of "cc -n"

michael@stb.UUCP (Michael) (06/04/88)

This one took me days to track down. It is not mentioned anywhere in the
manuals that I could find.

Programs Compiled With -n *ARE* shared and **ARE NOT**  pure.

If one copy of the program writes to the code segment, all copies see
the modified code segment. No segmentation violation occurs.

Here's some test code. It prints 78 78 when compiled normally,
78 0 when compiled with -n

Note: if you chmod +t on the object, you get 0 0 segmentation violation
the second time if p and x are declared register. If p and x are non-register,
you get a segmentation violation before any output. In both cases, the PC
points to the sleep() routine at the end of main().  My suspision: when main()
exits, the kernel checksums the code segment, and finds it different.
Still unknown: why register variables result in it printing, while
non-registers do not. 

Note that with register variables, and trapping segmentation violation,
you really do get permanent shared memory.

System: 16A, xenix 3.1.1

main()
{	/* register */ char *p;
	/* register */ int x;
	p = main;
	printf ("%d ", *p);
	x = fork();
	if (x == 0)
		*p = 0;		/* Should be a segmentation violation */
	else
	{	sleep (3);
		printf ("%d", *p);
	}
}

Final note: Another test, incrementing a variable placed in the text segment,
shows that the first time the code is run the new code segment is saved,
but not after that. So you can detect if your program has ever run before,
such as the first time the program runs a deamon is started, and no other
invocation starts the deamon.
(oddly enough, this did NOT trigger a segmentation violation no matter what
I tried.)

Or, you can find out how many copies of your program are running at any time.
(Or at least an upper bound, how many were started while at least one was
running).
: --- 
: Michael Gersten			 uunet.uu.net!denwa!stb!michael
:				 ihnp4!hermix!ucla-an!denwa!stb!michael
:				sdcsvax!crash!gryphon!denwa!stb!michael
: "Machine Takeover? Just say no."
: "Sockets? Just say no."     <-- gasoline