*BSD News Article 39145


Return to BSD News archive

Path: sserve!newshost.anu.edu.au!harbinger.cc.monash.edu.au!bunyip.cc.uq.oz.au!munnari.oz.au!spool.mu.edu!howland.reston.ans.net!swrinde!cs.utexas.edu!news.cs.utah.edu!news.cc.utah.edu!cs.weber.edu!terry
From: terry@cs.weber.edu (Terry Lambert)
Newsgroups: comp.os.386bsd.development
Subject: Re: How to find the filename of the binary executable...
Date: 9 Dec 1994 01:39:16 GMT
Organization: Weber State University, Ogden, UT
Lines: 58
Message-ID: <3c8cg4$qdi@news.cc.utah.edu>
References: <3c35e2$6sv@shore.shore.net>
NNTP-Posting-Host: cs.weber.edu

In article <3c35e2$6sv@shore.shore.net> witr@rwwa.com writes:
] Can someone tell me how to find the filename of the *binary*
] file being executed (on, say, FreeBSD 1.1.5.1, or sunos.recent)?

In what context?  A shell script or the program itself?

If the program itself:

	char	image[ 256];

	sprintf( image, "/proc/%d", getpid());

If you want the program that ran, assuming the runner did not pass a
totally new envp or a false argv[ 0] to the exec:

	<pesudo code>:

		<get relative path name from argv[ 0]>
		<if name begins with "/", stop>
		<if name begins with ".", getcwd(), then relative from there>
		<else>
		<getenv( "PATH")>
		<foreach PATH element, stat <pathelement>/argv[ 0]>
		<first one to stat true is your binary>

If you must have the pre-load image instead of the post-load image (and
therefore can't use the one in /proc), or if you don't have /proc, or
your envp or argv[ 0] is untrustworthy because of the exec arguments
modifying them from the expected values, then you must brute-force it:

	<pseudo-code>:

		<using kvm_* routines (see ps sources in source tree)
		 get the inode number and dev_t of the running program;
		 an execution instance is considered an open reference>
		<traverse the mount table to find the correct dev_t>
		<using the equivalent of 'find' not crossing mount points
		 and starting at the root of the partition, look for the
		 path that results in the inode>
		<because of hard links, this won't be "the" file name, it
		 will be "a" file name, unless the file has a single link,
		 but the inode it refers to will be the freexecution image>

This last method will go away in case of a copy-to-swap or other discard
of the use of the file as a swap store (in which case the open instance
will last through program load, but not after).  Systems that do a copy
to swap instead of paging from the file on startup (most older systems)
can not use this method.

I suspect if you are trying for symbol locations, the /proc reference will
be perfectly acceptable.


					Terry Lambert
					terry@cs.weber.edu
---
Any opinions in this posting are my own and not those of my present
or previous employers.