getpathp.c 16.4 KB
Newer Older
1 2

/* Return the initial module search path. */
3
/* Used by DOS, OS/2, Windows 3.1, Windows 95/98, Windows NT. */
4

5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/* ----------------------------------------------------------------
   PATH RULES FOR WINDOWS:
   This describes how sys.path is formed on Windows.  It describes the 
   functionality, not the implementation (ie, the order in which these 
   are actually fetched is different)

   * Python always adds an empty entry at the start, which corresponds
     to the current directory.

   * If the PYTHONPATH env. var. exists, it's entries are added next.

   * We look in the registry for "application paths" - that is, sub-keys
     under the main PythonPath registry key.  These are added next (the
     order of sub-key processing is undefined).
     HKEY_CURRENT_USER is searched and added first.
     HKEY_LOCAL_MACHINE is searched and added next.
     (Note that all known installers only use HKLM, so HKCU is typically
     empty)

   * We attempt to locate the "Python Home" - if the PYTHONHOME env var
     is set, we believe it.  Otherwise, we use the path of our host .EXE's
26
     to try and locate our "landmark" (lib\\os.py) and deduce our home.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
     - If we DO have a Python Home: The relevant sub-directories (Lib, 
       plat-win, lib-tk, etc) are based on the Python Home
     - If we DO NOT have a Python Home, the core Python Path is
       loaded from the registry.  This is the main PythonPath key, 
       and both HKLM and HKCU are combined to form the path)

   * Iff - we can not locate the Python Home, have not had a PYTHONPATH
     specified, and can't locate any Registry entries (ie, we have _nothing_
     we can assume is a good path), a default path with relative entries is 
     used (eg. .\Lib;.\plat-win, etc)


  The end result of all this is:
  * When running python.exe, or any other .exe in the main Python directory
    (either an installed version, or directly from the PCbuild directory),
    the core path is deduced, and the core paths in the registry are
    ignored.  Other "application paths" in the registry are always read.

  * When Python is hosted in another exe (different directory, embedded via 
    COM, etc), the Python Home will not be deduced, so the core path from
47
    the registry is used.  Other "application paths" in the registry are 
48 49 50 51 52 53 54 55 56
    always read.

  * If Python can't find its home and there is no registry (eg, frozen
    exe, some very strange installation setup) you get a path with
    some default, but relative, paths.

   ---------------------------------------------------------------- */


57 58 59
#include "Python.h"
#include "osdefs.h"

60 61
#ifdef MS_WIN32
#include <windows.h>
62
#include <tchar.h>
63 64
#endif

65 66 67 68 69 70 71 72
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>

/* Search in some common locations for the associated Python libraries.
 *
 * Py_GetPath() tries to return a sensible Python module search path.
 *
73 74 75
 * The approach is an adaptation for Windows of the strategy used in
 * ../Modules/getpath.c; it uses the Windows Registry as one of its
 * information sources.
76 77 78
 */

#ifndef LANDMARK
79
#define LANDMARK "lib\\os.py"
80 81 82 83 84 85
#endif

static char prefix[MAXPATHLEN+1];
static char progpath[MAXPATHLEN+1];
static char *module_search_path = NULL;

86

87
static int
88
is_sep(char ch)	/* determine if "ch" is a separator character */
89 90 91 92 93 94 95 96
{
#ifdef ALTSEP
	return ch == SEP || ch == ALTSEP;
#else
	return ch == SEP;
#endif
}

97 98 99
/* assumes 'dir' null terminated in bounds.  Never writes
   beyond existing terminator.
*/
100
static void
101
reduce(char *dir)
102
{
103
	size_t i = strlen(dir);
104 105 106 107 108 109 110
	while (i > 0 && !is_sep(dir[i]))
		--i;
	dir[i] = '\0';
}
	

static int
111
exists(char *filename)
112 113 114 115 116
{
	struct stat buf;
	return stat(filename, &buf) == 0;
}

117 118 119
/* Assumes 'filename' MAXPATHLEN+1 bytes long - 
   may extend 'filename' by one character.
*/
120
static int
121
ismodule(char *filename)	/* Is module -- check for .pyc/.pyo too */
122 123 124 125 126 127 128 129 130 131 132 133 134
{
	if (exists(filename))
		return 1;

	/* Check for the compiled version of prefix. */
	if (strlen(filename) < MAXPATHLEN) {
		strcat(filename, Py_OptimizeFlag ? "o" : "c");
		if (exists(filename))
			return 1;
	}
	return 0;
}

135
/* guarantees buffer will never overflow MAXPATHLEN+1 bytes */
136
static void
137
join(char *buffer, char *stuff)
138
{
139
	size_t n, k;
140 141 142 143 144 145 146 147 148 149 150 151 152 153
	if (is_sep(stuff[0]))
		n = 0;
	else {
		n = strlen(buffer);
		if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN)
			buffer[n++] = SEP;
	}
	k = strlen(stuff);
	if (n + k > MAXPATHLEN)
		k = MAXPATHLEN - n;
	strncpy(buffer+n, stuff, k);
	buffer[n+k] = '\0';
}

154 155 156 157
/* gotlandmark only called by search_for_prefix, which ensures
   'prefix' is null terminated in bounds.  join() ensures
   'landmark' can not overflow prefix if too long.
*/
158
static int
159
gotlandmark(char *landmark)
160 161 162 163 164 165 166 167 168 169
{
	int n, ok;

	n = strlen(prefix);
	join(prefix, landmark);
	ok = ismodule(prefix);
	prefix[n] = '\0';
	return ok;
}

170 171
/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd. 
   assumption provided by only caller, calculate_path() */
172
static int
173
search_for_prefix(char *argv0_path, char *landmark)
174
{
175
	/* Search from argv0_path, until landmark is found */
176 177
	strcpy(prefix, argv0_path);
	do {
178
		if (gotlandmark(landmark))
179 180 181 182 183 184
			return 1;
		reduce(prefix);
	} while (prefix[0]);
	return 0;
}

185
#ifdef MS_WIN32
186

187 188
/* a string loaded from the DLL at startup.*/
extern const char *PyWin_DLLVersionString;
189

190 191 192 193

/* Load a PYTHONPATH value from the registry.
   Load from either HKEY_LOCAL_MACHINE or HKEY_CURRENT_USER.

194 195 196
   Works in both Unicode and 8bit environments.  Only uses the
   Ex family of functions so it also works with Windows CE.

197
   Returns NULL, or a pointer that should be freed.
198 199 200 201

   XXX - this code is pretty strange, as it used to also
   work on Win16, where the buffer sizes werent available
   in advance.  It could be simplied now Win16/Win32s is dead!
202 203 204
*/

static char *
205
getpythonregpath(HKEY keyBase, int skipcore)
206 207 208
{
	HKEY newKey = 0;
	DWORD dataSize = 0;
209
	DWORD numKeys = 0;
210 211
	LONG rc;
	char *retval = NULL;
212 213 214
	TCHAR *dataBuf = NULL;
	static const TCHAR keyPrefix[] = _T("Software\\Python\\PythonCore\\");
	static const TCHAR keySuffix[] = _T("\\PythonPath");
215
	size_t versionLen;
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
	DWORD index;
	TCHAR *keyBuf = NULL;
	TCHAR *keyBufPtr;
	TCHAR **ppPaths = NULL;

	/* Tried to use sysget("winver") but here is too early :-( */
	versionLen = _tcslen(PyWin_DLLVersionString);
	/* Space for all the chars, plus one \0 */
	keyBuf = keyBufPtr = malloc(sizeof(keyPrefix) + 
		                    sizeof(TCHAR)*(versionLen-1) + 
				    sizeof(keySuffix));
	if (keyBuf==NULL) goto done;

	memcpy(keyBufPtr, keyPrefix, sizeof(keyPrefix)-sizeof(TCHAR));
	keyBufPtr += sizeof(keyPrefix)/sizeof(TCHAR) - 1;
	memcpy(keyBufPtr, PyWin_DLLVersionString, versionLen * sizeof(TCHAR));
	keyBufPtr += versionLen;
	/* NULL comes with this one! */
	memcpy(keyBufPtr, keySuffix, sizeof(keySuffix));
	/* Open the root Python key */
	rc=RegOpenKeyEx(keyBase,
	                keyBuf, /* subkey */
	                0, /* reserved */
	                KEY_READ,
	                &newKey);
	if (rc!=ERROR_SUCCESS) goto done;
	/* Find out how big our core buffer is, and how many subkeys we have */
	rc = RegQueryInfoKey(newKey, NULL, NULL, NULL, &numKeys, NULL, NULL, 
	                NULL, NULL, &dataSize, NULL, NULL);
	if (rc!=ERROR_SUCCESS) goto done;
	if (skipcore) dataSize = 0; /* Only count core ones if we want them! */
	/* Allocate a temp array of char buffers, so we only need to loop 
	   reading the registry once
	*/
	ppPaths = malloc( sizeof(TCHAR *) * numKeys );
	if (ppPaths==NULL) goto done;
	memset(ppPaths, 0, sizeof(TCHAR *) * numKeys);
	/* Loop over all subkeys, allocating a temp sub-buffer. */
	for(index=0;index<numKeys;index++) {
		TCHAR keyBuf[MAX_PATH+1];
		HKEY subKey = 0;
		DWORD reqdSize = MAX_PATH+1;
		/* Get the sub-key name */
		DWORD rc = RegEnumKeyEx(newKey, index, keyBuf, &reqdSize,
		                        NULL, NULL, NULL, NULL );
		if (rc!=ERROR_SUCCESS) goto done;
		/* Open the sub-key */
		rc=RegOpenKeyEx(newKey,
						keyBuf, /* subkey */
						0, /* reserved */
						KEY_READ,
						&subKey);
		if (rc!=ERROR_SUCCESS) goto done;
		/* Find the value of the buffer size, malloc, then read it */
		RegQueryValueEx(subKey, NULL, 0, NULL, NULL, &reqdSize);
		if (reqdSize) {
			ppPaths[index] = malloc(reqdSize);
			if (ppPaths[index]) {
274 275 276
				RegQueryValueEx(subKey, NULL, 0, NULL, 
				                (LPBYTE)ppPaths[index], 
				                &reqdSize);
277 278
				dataSize += reqdSize + 1; /* 1 for the ";" */
			}
279
		}
280 281
		RegCloseKey(subKey);
	}
282
	/* original datasize from RegQueryInfo doesn't include the \0 */
283 284 285 286 287 288 289 290
	dataBuf = malloc((dataSize+1) * sizeof(TCHAR));
	if (dataBuf) {
		TCHAR *szCur = dataBuf;
		DWORD reqdSize = dataSize;
		/* Copy our collected strings */
		for (index=0;index<numKeys;index++) {
			if (index > 0) {
				*(szCur++) = _T(';');
291 292
				dataSize--;
			}
293 294 295 296 297 298
			if (ppPaths[index]) {
				int len = _tcslen(ppPaths[index]);
				_tcsncpy(szCur, ppPaths[index], len);
				szCur += len;
				dataSize -= len;
			}
299
		}
300 301 302
		if (skipcore)
			*szCur = '\0';
		else {
303 304 305 306 307
			/* If we have no values, we dont need a ';' */
			if (numKeys) {
				*(szCur++) = _T(';');
				dataSize--;
			}
308 309 310 311 312
			/* Now append the core path entries - 
			   this will include the NULL 
			*/
			rc = RegQueryValueEx(newKey, NULL, 0, NULL, 
			                     (LPBYTE)szCur, &dataSize);
313
		}
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
		/* And set the result - caller must free 
		   If MBCS, it is fine as is.  If Unicode, allocate new
		   buffer and convert.
		*/
#ifdef UNICODE
		retval = (char *)malloc(reqdSize+1);
		if (retval)
			WideCharToMultiByte(CP_ACP, 0, 
					dataBuf, -1, /* source */ 
					retval, dataSize+1, /* dest */
					NULL, NULL);
		free(dataBuf);
#else
		retval = dataBuf;
#endif
	}
done:
	/* Loop freeing my temp buffers */
	if (ppPaths) {
		for(index=0;index<numKeys;index++)
			if (ppPaths[index]) free(ppPaths[index]);
		free(ppPaths);
336 337 338
	}
	if (newKey)
		RegCloseKey(newKey);
339 340
	if (keyBuf)
		free(keyBuf);
341 342 343 344
	return retval;
}
#endif /* MS_WIN32 */

345
static void
346
get_progpath(void)
347
{
348
	extern char *Py_GetProgramName(void);
349 350 351
	char *path = getenv("PATH");
	char *prog = Py_GetProgramName();

352
#ifdef MS_WIN32
353 354
#ifdef UNICODE
	WCHAR wprogpath[MAXPATHLEN+1];
355 356 357 358 359
	/* Windows documents that GetModuleFileName() will "truncate",
	   but makes no mention of the null terminator.  Play it safe.
	   PLUS Windows itself defines MAX_PATH as the same, but anyway...
	*/
	wprogpath[MAXPATHLEN]=_T('\0')';
360
	if (GetModuleFileName(NULL, wprogpath, MAXPATHLEN)) {
361 362 363 364
		WideCharToMultiByte(CP_ACP, 0, 
		                    wprogpath, -1, 
		                    progpath, MAXPATHLEN+1, 
		                    NULL, NULL);
365 366 367
		return;
	}
#else
368
	/* static init of progpath ensures final char remains \0 */
369 370
	if (GetModuleFileName(NULL, progpath, MAXPATHLEN))
		return;
371
#endif
372 373 374 375
#endif
	if (prog == NULL || *prog == '\0')
		prog = "python";

376 377 378 379 380 381 382 383 384 385
	/* If there is no slash in the argv0 path, then we have to
	 * assume python is on the user's $PATH, since there's no
	 * other way to find a directory to start the search from.  If
	 * $PATH isn't exported, you lose.
	 */
#ifdef ALTSEP
	if (strchr(prog, SEP) || strchr(prog, ALTSEP))
#else
	if (strchr(prog, SEP))
#endif
386
		strncpy(progpath, prog, MAXPATHLEN);
387 388 389 390 391
	else if (path) {
		while (1) {
			char *delim = strchr(path, DELIM);

			if (delim) {
392
				size_t len = delim - path;
393 394
				/* ensure we can't overwrite buffer */
				len = min(MAXPATHLEN,len);
395 396 397 398
				strncpy(progpath, path, len);
				*(progpath + len) = '\0';
			}
			else
399
				strncpy(progpath, path, MAXPATHLEN);
400

401
			/* join() is safe for MAXPATHLEN+1 size buffer */
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
			join(progpath, prog);
			if (exists(progpath))
				break;

			if (!delim) {
				progpath[0] = '\0';
				break;
			}
			path = delim + 1;
		}
	}
	else
		progpath[0] = '\0';
}

static void
418
calculate_path(void)
419 420 421
{
	char argv0_path[MAXPATHLEN+1];
	char *buf;
422
	size_t bufsz;
Guido van Rossum's avatar
Guido van Rossum committed
423
	char *pythonhome = Py_GetPythonHome();
424
	char *envpath = Py_GETENV("PYTHONPATH");
425

426
#ifdef MS_WIN32
427
	int skiphome, skipdefault;
428 429
	char *machinepath = NULL;
	char *userpath = NULL;
430
#endif
431 432

	get_progpath();
433
	/* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */
434 435
	strcpy(argv0_path, progpath);
	reduce(argv0_path);
436 437 438
	if (pythonhome == NULL || *pythonhome == '\0') {
		if (search_for_prefix(argv0_path, LANDMARK))
			pythonhome = prefix;
439 440
		else
			pythonhome = NULL;
441
	}
442
	else
443
		strncpy(prefix, pythonhome, MAXPATHLEN);
444 445 446 447

	if (envpath && *envpath == '\0')
		envpath = NULL;

448

449
#ifdef MS_WIN32
450 451 452 453 454 455 456
	skiphome = pythonhome==NULL ? 0 : 1;
	machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, skiphome);
	userpath = getpythonregpath(HKEY_CURRENT_USER, skiphome);
	/* We only use the default relative PYTHONPATH if we havent
	   anything better to use! */
	skipdefault = envpath!=NULL || pythonhome!=NULL || \
		      machinepath!=NULL || userpath!=NULL;
457 458 459
#endif

	/* We need to construct a path from the following parts.
460 461 462 463 464 465
	   (1) the PYTHONPATH environment variable, if set;
	   (2) for Win32, the machinepath and userpath, if set;
	   (3) the PYTHONPATH config macro, with the leading "."
	       of each component replaced with pythonhome, if set;
	   (4) the directory containing the executable (argv0_path).
	   The length calculation calculates #3 first.
466 467 468
	   Extra rules:
	   - If PYTHONHOME is set (in any way) item (2) is ignored.
	   - If registry values are used, (3) and (4) are ignored.
469 470 471 472 473 474 475 476 477
	*/

	/* Calculate size of return buffer */
	if (pythonhome != NULL) {
		char *p;
		bufsz = 1;	
		for (p = PYTHONPATH; *p; p++) {
			if (*p == DELIM)
				bufsz++; /* number of DELIM plus one */
478
		}
479
		bufsz *= strlen(pythonhome);
480
	}
481 482
	else
		bufsz = 0;
483
	bufsz += strlen(PYTHONPATH) + 1;
484
	bufsz += strlen(argv0_path) + 1;
485 486 487
#ifdef MS_WIN32
	if (userpath)
		bufsz += strlen(userpath) + 1;
488 489
	if (machinepath)
		bufsz += strlen(machinepath) + 1;
490
#endif
491 492
	if (envpath != NULL)
		bufsz += strlen(envpath) + 1;
493 494 495 496

	module_search_path = buf = malloc(bufsz);
	if (buf == NULL) {
		/* We can't exit, so print a warning and limp along */
497 498
		fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n");
		if (envpath) {
499
			fprintf(stderr, "Using environment $PYTHONPATH.\n");
500 501 502
			module_search_path = envpath;
		}
		else {
503
			fprintf(stderr, "Using default static path.\n");
504 505
			module_search_path = PYTHONPATH;
		}
506 507 508 509 510 511
#ifdef MS_WIN32
		if (machinepath)
			free(machinepath);
		if (userpath)
			free(userpath);
#endif /* MS_WIN32 */
512 513
		return;
	}
514 515 516 517 518 519 520

	if (envpath) {
		strcpy(buf, envpath);
		buf = strchr(buf, '\0');
		*buf++ = DELIM;
	}
#ifdef MS_WIN32
521 522 523 524 525 526
	if (userpath) {
		strcpy(buf, userpath);
		buf = strchr(buf, '\0');
		*buf++ = DELIM;
		free(userpath);
	}
527 528 529 530
	if (machinepath) {
		strcpy(buf, machinepath);
		buf = strchr(buf, '\0');
		*buf++ = DELIM;
531
		free(machinepath);
532
	}
533 534 535 536 537
	if (pythonhome == NULL) {
		if (!skipdefault) {
			strcpy(buf, PYTHONPATH);
			buf = strchr(buf, '\0');
		}
538
	}
539
#else
540 541 542 543
	if (pythonhome == NULL) {
		strcpy(buf, PYTHONPATH);
		buf = strchr(buf, '\0');
	}
544
#endif /* MS_WIN32 */
545 546 547
	else {
		char *p = PYTHONPATH;
		char *q;
548
		size_t n;
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
		for (;;) {
			q = strchr(p, DELIM);
			if (q == NULL)
				n = strlen(p);
			else
				n = q-p;
			if (p[0] == '.' && is_sep(p[1])) {
				strcpy(buf, pythonhome);
				buf = strchr(buf, '\0');
				p++;
				n--;
			}
			strncpy(buf, p, n);
			buf += n;
			if (q == NULL)
				break;
			*buf++ = DELIM;
			p = q+1;
567 568
		}
	}
569 570 571 572 573
	if (argv0_path) {
		*buf++ = DELIM;
		strcpy(buf, argv0_path);
		buf = strchr(buf, '\0');
	}
574
	*buf = '\0';
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
	/* Now to pull one last hack/trick.  If sys.prefix is
	   empty, then try and find it somewhere on the paths
	   we calculated.  We scan backwards, as our general policy
	   is that Python core directories are at the *end* of
	   sys.path.  We assume that our "lib" directory is
	   on the path, and that our 'prefix' directory is
	   the parent of that.
	*/
	if (*prefix=='\0') {
		char lookBuf[MAXPATHLEN+1];
		char *look = buf - 1; /* 'buf' is at the end of the buffer */
		while (1) {
			int nchars;
			char *lookEnd = look;
			/* 'look' will end up one character before the
			   start of the path in question - even if this
			   is one character before the start of the buffer
			*/
			while (*look != DELIM && look >= module_search_path)
				look--;
			nchars = lookEnd-look;
			strncpy(lookBuf, look+1, nchars);
			lookBuf[nchars] = '\0';
			/* Up one level to the parent */
			reduce(lookBuf);
			if (search_for_prefix(lookBuf, LANDMARK)) {
				break;
			}
			/* If we are out of paths to search - give up */
			if (look < module_search_path)
				break;
			look--;
		}
	}
609 610 611 612 613 614
}


/* External interface */

char *
615
Py_GetPath(void)
616 617 618 619 620 621 622
{
	if (!module_search_path)
		calculate_path();
	return module_search_path;
}

char *
623
Py_GetPrefix(void)
624
{
625 626 627
	if (!module_search_path)
		calculate_path();
	return prefix;
628 629 630
}

char *
631
Py_GetExecPrefix(void)
632
{
633
	return Py_GetPrefix();
634 635 636
}

char *
637
Py_GetProgramFullPath(void)
638 639 640 641 642
{
	if (!module_search_path)
		calculate_path();
	return progpath;
}