Reading the symbol table of the currently running executable

Mark Rosenthal mbr at aoa.UUCP
Sat Sep 9 07:11:55 AEST 1989


In article <LIMES.89Sep7153103 at ouroborous.wseng.sun.com> limes at sun.com (Greg Limes) writes:
>In article <6131 at lynx.UUCP> mitch at lynx.uucp (Mitch Bunnell) writes:
>
>> In article <9104 at june.cs.washington.edu> bcn at cs.washington.edu (Clifford Neuman) writes:
>> >  2) Obtaining the full path name of the presently running executable.
>
>> 2 - Not possible.
>
>Back before I knew this was impossible, I wrote the following piece of
>support code. It has been doing the impossible for me for quite some
>time (geez, has it been that long?) with limitations as stated.

Your approach works if the program was exec'd by a reasonably well-behaved
program.  'sh' and 'csh' fall into this category.  Unfortunately, your code
(or anybody else's) fails to solve the general case.  Your code depends on the
value in argv.  Let's say you call your findx() inside a program called
yourprog in /usr/bin.  If you invoke it from either 'sh' or 'csh' with either a
full or partial pathname, it should come up with the right directory.  But try
invoking your code by running the following:

    main()
    {
	execl("/usr/bin/yourprog", "garbagename", "arg1", "arg2");
    }

The point is that the value in argv[0] is not necessarily guaranteed to have
anything to do with the name of the file the program resided in.

This is not merely hypothetical.  There is code in vi to execute a command from
within vi.  Have you checked it to see if it calls system() or parses the
command itself, and does its own fork() and exec().  What about emacs?  In order
to be sure you can count on argv[0], you would have to have checked every single
Unix utility that calls any version of exec() to make sure it passes the right
thing for argv[0].

More bad news.  You can't depend on the value of environment variables like
PATH.  Your program could have been invoked with execve() or execle(), in
which case the PATH variable your program sees has no necessary relationship
to the PATH variable used to find your program in order to exec() it.

Sorry, but it really is not possible using information legally available to
the program.  It might be possible by examining tables in kernel memory (if
your program has privileges to do this), but I'm not certain of that.
-- 
	Mark of the Valley of Roses
	...!bbn.com!aoa!mbr



More information about the Comp.unix.wizards mailing list