blob: 0b0ae4973963162635704f2faa5a9e7792263101 [file] [log] [blame]
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +00001
2/* Return the initial module search path. */
Jesus Ceaf1af7052012-10-05 02:48:46 +02003/* Used by DOS, Windows 3.1, Windows 95/98, Windows NT. */
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +00004
Guido van Rossum88716bb2000-03-30 19:45:39 +00005/* ----------------------------------------------------------------
6 PATH RULES FOR WINDOWS:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007 This describes how sys.path is formed on Windows. It describes the
8 functionality, not the implementation (ie, the order in which these
Steve Dowered51b262016-09-17 12:54:06 -07009 are actually fetched is different). The presence of a python._pth or
10 pythonXY._pth file alongside the program overrides these rules - see
11 below.
Guido van Rossum88716bb2000-03-30 19:45:39 +000012
13 * Python always adds an empty entry at the start, which corresponds
14 to the current directory.
15
Georg Brandl7eb4b7d2005-07-22 21:49:32 +000016 * If the PYTHONPATH env. var. exists, its entries are added next.
Guido van Rossum88716bb2000-03-30 19:45:39 +000017
18 * We look in the registry for "application paths" - that is, sub-keys
19 under the main PythonPath registry key. These are added next (the
20 order of sub-key processing is undefined).
21 HKEY_CURRENT_USER is searched and added first.
22 HKEY_LOCAL_MACHINE is searched and added next.
23 (Note that all known installers only use HKLM, so HKCU is typically
24 empty)
25
26 * We attempt to locate the "Python Home" - if the PYTHONHOME env var
27 is set, we believe it. Otherwise, we use the path of our host .EXE's
Martin Panterfd13c0f2016-09-10 10:45:28 +000028 to try and locate one of our "landmarks" and deduce our home.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000029 - If we DO have a Python Home: The relevant sub-directories (Lib,
Zachary Warec4b53af2016-09-09 17:59:49 -070030 DLLs, etc) are based on the Python Home
Guido van Rossum88716bb2000-03-30 19:45:39 +000031 - If we DO NOT have a Python Home, the core Python Path is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000032 loaded from the registry. This is the main PythonPath key,
Guido van Rossum88716bb2000-03-30 19:45:39 +000033 and both HKLM and HKCU are combined to form the path)
34
35 * Iff - we can not locate the Python Home, have not had a PYTHONPATH
36 specified, and can't locate any Registry entries (ie, we have _nothing_
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000037 we can assume is a good path), a default path with relative entries is
Zachary Warec4b53af2016-09-09 17:59:49 -070038 used (eg. .\Lib;.\DLLs, etc)
Guido van Rossum88716bb2000-03-30 19:45:39 +000039
40
Steve Dowered51b262016-09-17 12:54:06 -070041 If a '._pth' file exists adjacent to the executable with the same base name
42 (e.g. python._pth adjacent to python.exe) or adjacent to the shared library
43 (e.g. python36._pth adjacent to python36.dll), it is used in preference to
44 the above process. The shared library file takes precedence over the
45 executable. The path file must contain a list of paths to add to sys.path,
46 one per line. Each path is relative to the directory containing the file.
47 Blank lines and comments beginning with '#' are permitted.
48
49 In the presence of this ._pth file, no other paths are added to the search
50 path, the registry finder is not enabled, site.py is not imported and
51 isolated mode is enabled. The site package can be enabled by including a
52 line reading "import site"; no other imports are recognized. Any invalid
53 entry (other than directories that do not exist) will result in immediate
54 termination of the program.
55
Steve Dower4db86bc2016-09-09 09:17:35 -070056
Guido van Rossum88716bb2000-03-30 19:45:39 +000057 The end result of all this is:
58 * When running python.exe, or any other .exe in the main Python directory
59 (either an installed version, or directly from the PCbuild directory),
60 the core path is deduced, and the core paths in the registry are
61 ignored. Other "application paths" in the registry are always read.
62
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 * When Python is hosted in another exe (different directory, embedded via
Guido van Rossum88716bb2000-03-30 19:45:39 +000064 COM, etc), the Python Home will not be deduced, so the core path from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 the registry is used. Other "application paths" in the registry are
Guido van Rossum88716bb2000-03-30 19:45:39 +000066 always read.
67
68 * If Python can't find its home and there is no registry (eg, frozen
69 exe, some very strange installation setup) you get a path with
70 some default, but relative, paths.
71
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +000072 * An embedding application can use Py_SetPath() to override all of
Steve Dower4db86bc2016-09-09 09:17:35 -070073 these automatic path computations.
74
Steve Dowered51b262016-09-17 12:54:06 -070075 * An install of Python can fully specify the contents of sys.path using
76 either a 'EXENAME._pth' or 'DLLNAME._pth' file, optionally including
77 "import site" to enable the site module.
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +000078
Guido van Rossum88716bb2000-03-30 19:45:39 +000079 ---------------------------------------------------------------- */
80
81
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +000082#include "Python.h"
83#include "osdefs.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000084#include <wchar.h>
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +000085
Steve Dower4db86bc2016-09-09 09:17:35 -070086#ifndef MS_WINDOWS
87#error getpathp.c should only be built on Windows
Guido van Rossum8f1b6511997-08-13 19:55:43 +000088#endif
89
Steve Dower4db86bc2016-09-09 09:17:35 -070090#include <windows.h>
91#include <Shlwapi.h>
92
Thomas Wouters0e3f5912006-08-11 14:57:12 +000093#ifdef HAVE_SYS_TYPES_H
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +000094#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000095#endif /* HAVE_SYS_TYPES_H */
96
97#ifdef HAVE_SYS_STAT_H
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +000098#include <sys/stat.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000099#endif /* HAVE_SYS_STAT_H */
100
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000101#include <string.h>
102
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000103/* Search in some common locations for the associated Python libraries.
104 *
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000105 * Py_GetPath() tries to return a sensible Python module search path.
106 *
Guido van Rossum42a97441998-02-19 21:00:45 +0000107 * The approach is an adaptation for Windows of the strategy used in
108 * ../Modules/getpath.c; it uses the Windows Registry as one of its
109 * information sources.
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +0000110 *
111 * Py_SetPath() can be used to override this mechanism. Call Py_SetPath
112 * with a semicolon separated path prior to calling Py_Initialize.
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000113 */
114
115#ifndef LANDMARK
Martin v. Löwis790465f2008-04-05 20:41:37 +0000116#define LANDMARK L"lib\\os.py"
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000117#endif
118
Martin v. Löwis790465f2008-04-05 20:41:37 +0000119static wchar_t prefix[MAXPATHLEN+1];
120static wchar_t progpath[MAXPATHLEN+1];
121static wchar_t dllpath[MAXPATHLEN+1];
122static wchar_t *module_search_path = NULL;
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000123
Guido van Rossumeea14491997-08-13 21:30:44 +0000124
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000125static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126is_sep(wchar_t ch) /* determine if "ch" is a separator character */
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000127{
128#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 return ch == SEP || ch == ALTSEP;
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000130#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 return ch == SEP;
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000132#endif
133}
134
Mark Hammond8bf9e3b2000-10-07 11:10:50 +0000135/* assumes 'dir' null terminated in bounds. Never writes
136 beyond existing terminator.
137*/
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000138static void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000139reduce(wchar_t *dir)
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000140{
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700141 size_t i = wcsnlen_s(dir, MAXPATHLEN+1);
142 if (i >= MAXPATHLEN+1)
143 Py_FatalError("buffer overflow in getpathp.c's reduce()");
144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 while (i > 0 && !is_sep(dir[i]))
146 --i;
147 dir[i] = '\0';
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000148}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149
Steve Dowered51b262016-09-17 12:54:06 -0700150static int
151change_ext(wchar_t *dest, const wchar_t *src, const wchar_t *ext)
152{
153 size_t src_len = wcsnlen_s(src, MAXPATHLEN+1);
154 size_t i = src_len;
155 if (i >= MAXPATHLEN+1)
156 Py_FatalError("buffer overflow in getpathp.c's reduce()");
157
158 while (i > 0 && src[i] != '.' && !is_sep(src[i]))
159 --i;
160
161 if (i == 0) {
162 dest[0] = '\0';
163 return -1;
164 }
165
166 if (is_sep(src[i]))
167 i = src_len;
168
169 if (wcsncpy_s(dest, MAXPATHLEN+1, src, i) ||
170 wcscat_s(dest, MAXPATHLEN+1, ext)) {
171 dest[0] = '\0';
172 return -1;
173 }
174
175 return 0;
176}
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000177
178static int
Martin v. Löwis790465f2008-04-05 20:41:37 +0000179exists(wchar_t *filename)
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 return GetFileAttributesW(filename) != 0xFFFFFFFF;
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000182}
183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184/* Assumes 'filename' MAXPATHLEN+1 bytes long -
Mark Hammond8bf9e3b2000-10-07 11:10:50 +0000185 may extend 'filename' by one character.
186*/
Guido van Rossum43ff1141998-08-08 23:40:40 +0000187static int
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700188ismodule(wchar_t *filename, int update_filename) /* Is module -- check for .pyc/.pyo too */
Guido van Rossum43ff1141998-08-08 23:40:40 +0000189{
Victor Stinnerccb1f8c2016-03-23 11:31:58 +0100190 size_t n;
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 if (exists(filename))
193 return 1;
Guido van Rossum43ff1141998-08-08 23:40:40 +0000194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 /* Check for the compiled version of prefix. */
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700196 n = wcsnlen_s(filename, MAXPATHLEN+1);
197 if (n < MAXPATHLEN) {
198 int exist = 0;
199 filename[n] = Py_OptimizeFlag ? L'o' : L'c';
200 filename[n + 1] = L'\0';
201 exist = exists(filename);
202 if (!update_filename)
203 filename[n] = L'\0';
204 return exist;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 }
206 return 0;
Guido van Rossum43ff1141998-08-08 23:40:40 +0000207}
208
Tim Peters8484fbf2004-08-07 19:12:27 +0000209/* Add a path component, by appending stuff to buffer.
210 buffer must have at least MAXPATHLEN + 1 bytes allocated, and contain a
211 NUL-terminated string with no more than MAXPATHLEN characters (not counting
212 the trailing NUL). It's a fatal error if it contains a string longer than
213 that (callers must be careful!). If these requirements are met, it's
214 guaranteed that buffer will still be a NUL-terminated string with no more
215 than MAXPATHLEN characters at exit. If stuff is too long, only as much of
216 stuff as fits will be appended.
217*/
Steve Dower4db86bc2016-09-09 09:17:35 -0700218
219static int _PathCchCombineEx_Initialized = 0;
220typedef HRESULT(__stdcall *PPathCchCombineEx)(PWSTR pszPathOut, size_t cchPathOut, PCWSTR pszPathIn, PCWSTR pszMore, unsigned long dwFlags);
221static PPathCchCombineEx _PathCchCombineEx;
222
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000223static void
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700224join(wchar_t *buffer, const wchar_t *stuff)
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000225{
Steve Dower4db86bc2016-09-09 09:17:35 -0700226 if (_PathCchCombineEx_Initialized == 0) {
227 HMODULE pathapi = LoadLibraryW(L"api-ms-win-core-path-l1-1-0.dll");
228 if (pathapi)
229 _PathCchCombineEx = (PPathCchCombineEx)GetProcAddress(pathapi, "PathCchCombineEx");
230 else
231 _PathCchCombineEx = NULL;
232 _PathCchCombineEx_Initialized = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 }
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700234
Steve Dower4db86bc2016-09-09 09:17:35 -0700235 if (_PathCchCombineEx) {
236 if (FAILED(_PathCchCombineEx(buffer, MAXPATHLEN+1, buffer, stuff, 0)))
237 Py_FatalError("buffer overflow in getpathp.c's join()");
238 } else {
Steve Dower3ceb5732016-09-09 15:53:58 -0700239 if (!PathCombineW(buffer, buffer, stuff))
Steve Dower4db86bc2016-09-09 09:17:35 -0700240 Py_FatalError("buffer overflow in getpathp.c's join()");
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700241 }
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000242}
243
Mark Hammond8bf9e3b2000-10-07 11:10:50 +0000244/* gotlandmark only called by search_for_prefix, which ensures
245 'prefix' is null terminated in bounds. join() ensures
246 'landmark' can not overflow prefix if too long.
247*/
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000248static int
Steve Dower50289382016-09-09 14:22:43 -0700249gotlandmark(const wchar_t *landmark)
Guido van Rossume02e48b2000-03-29 01:49:47 +0000250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 int ok;
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700252 Py_ssize_t n = wcsnlen_s(prefix, MAXPATHLEN);
Guido van Rossume02e48b2000-03-29 01:49:47 +0000253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 join(prefix, landmark);
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700255 ok = ismodule(prefix, FALSE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 prefix[n] = '\0';
257 return ok;
Guido van Rossume02e48b2000-03-29 01:49:47 +0000258}
259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd.
Mark Hammond8bf9e3b2000-10-07 11:10:50 +0000261 assumption provided by only caller, calculate_path() */
Guido van Rossume02e48b2000-03-29 01:49:47 +0000262static int
Steve Dower50289382016-09-09 14:22:43 -0700263search_for_prefix(wchar_t *argv0_path, const wchar_t *landmark)
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 /* Search from argv0_path, until landmark is found */
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700266 wcscpy_s(prefix, MAXPATHLEN + 1, argv0_path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 do {
268 if (gotlandmark(landmark))
269 return 1;
270 reduce(prefix);
271 } while (prefix[0]);
272 return 0;
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000273}
274
Martin v. Löwisbc186a82009-02-02 15:32:22 +0000275#ifdef Py_ENABLE_SHARED
Guido van Rossum43ff1141998-08-08 23:40:40 +0000276
Guido van Rossum88716bb2000-03-30 19:45:39 +0000277/* a string loaded from the DLL at startup.*/
278extern const char *PyWin_DLLVersionString;
Guido van Rossum271f9771997-09-29 23:39:31 +0000279
Guido van Rossumeea14491997-08-13 21:30:44 +0000280
281/* Load a PYTHONPATH value from the registry.
282 Load from either HKEY_LOCAL_MACHINE or HKEY_CURRENT_USER.
283
Guido van Rossum88716bb2000-03-30 19:45:39 +0000284 Works in both Unicode and 8bit environments. Only uses the
285 Ex family of functions so it also works with Windows CE.
286
Guido van Rossumeea14491997-08-13 21:30:44 +0000287 Returns NULL, or a pointer that should be freed.
Mark Hammond5edc6272001-02-23 11:38:38 +0000288
289 XXX - this code is pretty strange, as it used to also
290 work on Win16, where the buffer sizes werent available
291 in advance. It could be simplied now Win16/Win32s is dead!
Guido van Rossumeea14491997-08-13 21:30:44 +0000292*/
293
Martin v. Löwis790465f2008-04-05 20:41:37 +0000294static wchar_t *
Guido van Rossum88716bb2000-03-30 19:45:39 +0000295getpythonregpath(HKEY keyBase, int skipcore)
Guido van Rossumeea14491997-08-13 21:30:44 +0000296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 HKEY newKey = 0;
298 DWORD dataSize = 0;
299 DWORD numKeys = 0;
300 LONG rc;
301 wchar_t *retval = NULL;
302 WCHAR *dataBuf = NULL;
303 static const WCHAR keyPrefix[] = L"Software\\Python\\PythonCore\\";
304 static const WCHAR keySuffix[] = L"\\PythonPath";
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700305 size_t versionLen, keyBufLen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 DWORD index;
307 WCHAR *keyBuf = NULL;
308 WCHAR *keyBufPtr;
309 WCHAR **ppPaths = NULL;
Guido van Rossum271f9771997-09-29 23:39:31 +0000310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 /* Tried to use sysget("winver") but here is too early :-( */
312 versionLen = strlen(PyWin_DLLVersionString);
313 /* Space for all the chars, plus one \0 */
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700314 keyBufLen = sizeof(keyPrefix) +
315 sizeof(WCHAR)*(versionLen-1) +
316 sizeof(keySuffix);
317 keyBuf = keyBufPtr = PyMem_RawMalloc(keyBufLen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 if (keyBuf==NULL) goto done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000319
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700320 memcpy_s(keyBufPtr, keyBufLen, keyPrefix, sizeof(keyPrefix)-sizeof(WCHAR));
Victor Stinner63941882011-09-29 00:42:28 +0200321 keyBufPtr += Py_ARRAY_LENGTH(keyPrefix) - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 mbstowcs(keyBufPtr, PyWin_DLLVersionString, versionLen);
323 keyBufPtr += versionLen;
324 /* NULL comes with this one! */
325 memcpy(keyBufPtr, keySuffix, sizeof(keySuffix));
326 /* Open the root Python key */
327 rc=RegOpenKeyExW(keyBase,
328 keyBuf, /* subkey */
329 0, /* reserved */
330 KEY_READ,
331 &newKey);
332 if (rc!=ERROR_SUCCESS) goto done;
333 /* Find out how big our core buffer is, and how many subkeys we have */
334 rc = RegQueryInfoKey(newKey, NULL, NULL, NULL, &numKeys, NULL, NULL,
335 NULL, NULL, &dataSize, NULL, NULL);
336 if (rc!=ERROR_SUCCESS) goto done;
337 if (skipcore) dataSize = 0; /* Only count core ones if we want them! */
338 /* Allocate a temp array of char buffers, so we only need to loop
339 reading the registry once
340 */
Victor Stinner1a7425f2013-07-07 16:25:15 +0200341 ppPaths = PyMem_RawMalloc( sizeof(WCHAR *) * numKeys );
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 if (ppPaths==NULL) goto done;
343 memset(ppPaths, 0, sizeof(WCHAR *) * numKeys);
344 /* Loop over all subkeys, allocating a temp sub-buffer. */
345 for(index=0;index<numKeys;index++) {
346 WCHAR keyBuf[MAX_PATH+1];
347 HKEY subKey = 0;
348 DWORD reqdSize = MAX_PATH+1;
349 /* Get the sub-key name */
350 DWORD rc = RegEnumKeyExW(newKey, index, keyBuf, &reqdSize,
351 NULL, NULL, NULL, NULL );
352 if (rc!=ERROR_SUCCESS) goto done;
353 /* Open the sub-key */
354 rc=RegOpenKeyExW(newKey,
355 keyBuf, /* subkey */
356 0, /* reserved */
357 KEY_READ,
358 &subKey);
359 if (rc!=ERROR_SUCCESS) goto done;
360 /* Find the value of the buffer size, malloc, then read it */
361 RegQueryValueExW(subKey, NULL, 0, NULL, NULL, &reqdSize);
362 if (reqdSize) {
Victor Stinner1a7425f2013-07-07 16:25:15 +0200363 ppPaths[index] = PyMem_RawMalloc(reqdSize);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 if (ppPaths[index]) {
365 RegQueryValueExW(subKey, NULL, 0, NULL,
366 (LPBYTE)ppPaths[index],
367 &reqdSize);
368 dataSize += reqdSize + 1; /* 1 for the ";" */
369 }
370 }
371 RegCloseKey(subKey);
372 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 /* return null if no path to return */
375 if (dataSize == 0) goto done;
376
377 /* original datasize from RegQueryInfo doesn't include the \0 */
Victor Stinner1a7425f2013-07-07 16:25:15 +0200378 dataBuf = PyMem_RawMalloc((dataSize+1) * sizeof(WCHAR));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 if (dataBuf) {
380 WCHAR *szCur = dataBuf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 /* Copy our collected strings */
382 for (index=0;index<numKeys;index++) {
383 if (index > 0) {
384 *(szCur++) = L';';
385 dataSize--;
386 }
387 if (ppPaths[index]) {
388 Py_ssize_t len = wcslen(ppPaths[index]);
389 wcsncpy(szCur, ppPaths[index], len);
390 szCur += len;
391 assert(dataSize > (DWORD)len);
392 dataSize -= (DWORD)len;
393 }
394 }
395 if (skipcore)
396 *szCur = '\0';
397 else {
398 /* If we have no values, we dont need a ';' */
399 if (numKeys) {
400 *(szCur++) = L';';
401 dataSize--;
402 }
403 /* Now append the core path entries -
404 this will include the NULL
405 */
406 rc = RegQueryValueExW(newKey, NULL, 0, NULL,
407 (LPBYTE)szCur, &dataSize);
Serhiy Storchakae0cb9da2015-12-18 09:54:19 +0200408 if (rc != ERROR_SUCCESS) {
409 PyMem_RawFree(dataBuf);
410 goto done;
411 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 }
413 /* And set the result - caller must free */
414 retval = dataBuf;
415 }
Guido van Rossum88716bb2000-03-30 19:45:39 +0000416done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 /* Loop freeing my temp buffers */
418 if (ppPaths) {
Victor Stinner1a7425f2013-07-07 16:25:15 +0200419 for(index=0; index<numKeys; index++)
420 PyMem_RawFree(ppPaths[index]);
421 PyMem_RawFree(ppPaths);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 }
423 if (newKey)
424 RegCloseKey(newKey);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200425 PyMem_RawFree(keyBuf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 return retval;
Guido van Rossumeea14491997-08-13 21:30:44 +0000427}
Martin v. Löwisbc186a82009-02-02 15:32:22 +0000428#endif /* Py_ENABLE_SHARED */
Guido van Rossumeea14491997-08-13 21:30:44 +0000429
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000430static void
Thomas Wouters78890102000-07-22 19:25:51 +0000431get_progpath(void)
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 extern wchar_t *Py_GetProgramName(void);
434 wchar_t *path = _wgetenv(L"PATH");
435 wchar_t *prog = Py_GetProgramName();
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000436
Martin v. Löwisbc186a82009-02-02 15:32:22 +0000437#ifdef Py_ENABLE_SHARED
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 extern HANDLE PyWin_DLLhModule;
439 /* static init of progpath ensures final char remains \0 */
440 if (PyWin_DLLhModule)
441 if (!GetModuleFileNameW(PyWin_DLLhModule, dllpath, MAXPATHLEN))
442 dllpath[0] = 0;
Martin v. Löwisbc186a82009-02-02 15:32:22 +0000443#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 dllpath[0] = 0;
Martin v. Löwisbc186a82009-02-02 15:32:22 +0000445#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 if (GetModuleFileNameW(NULL, progpath, MAXPATHLEN))
447 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 if (prog == NULL || *prog == '\0')
449 prog = L"python";
Guido van Rossumeea14491997-08-13 21:30:44 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 /* If there is no slash in the argv0 path, then we have to
452 * assume python is on the user's $PATH, since there's no
453 * other way to find a directory to start the search from. If
454 * $PATH isn't exported, you lose.
455 */
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000456#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 if (wcschr(prog, SEP) || wcschr(prog, ALTSEP))
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000458#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 if (wcschr(prog, SEP))
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000460#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 wcsncpy(progpath, prog, MAXPATHLEN);
462 else if (path) {
463 while (1) {
464 wchar_t *delim = wcschr(path, DELIM);
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 if (delim) {
467 size_t len = delim - path;
468 /* ensure we can't overwrite buffer */
469 len = min(MAXPATHLEN,len);
470 wcsncpy(progpath, path, len);
471 *(progpath + len) = '\0';
472 }
473 else
474 wcsncpy(progpath, path, MAXPATHLEN);
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 /* join() is safe for MAXPATHLEN+1 size buffer */
477 join(progpath, prog);
478 if (exists(progpath))
479 break;
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 if (!delim) {
482 progpath[0] = '\0';
483 break;
484 }
485 path = delim + 1;
486 }
487 }
488 else
489 progpath[0] = '\0';
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000490}
491
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100492static int
493find_env_config_value(FILE * env_file, const wchar_t * key, wchar_t * value)
494{
495 int result = 0; /* meaning not found */
496 char buffer[MAXPATHLEN*2+1]; /* allow extra for key, '=', etc. */
497
498 fseek(env_file, 0, SEEK_SET);
499 while (!feof(env_file)) {
500 char * p = fgets(buffer, MAXPATHLEN*2, env_file);
501 wchar_t tmpbuffer[MAXPATHLEN*2+1];
502 PyObject * decoded;
Victor Stinner8bda4652013-06-05 00:22:34 +0200503 size_t n;
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100504
505 if (p == NULL)
506 break;
507 n = strlen(p);
508 if (p[n - 1] != '\n') {
509 /* line has overflowed - bail */
510 break;
511 }
512 if (p[0] == '#') /* Comment - skip */
513 continue;
514 decoded = PyUnicode_DecodeUTF8(buffer, n, "surrogateescape");
515 if (decoded != NULL) {
516 Py_ssize_t k;
517 k = PyUnicode_AsWideChar(decoded,
518 tmpbuffer, MAXPATHLEN * 2);
519 Py_DECREF(decoded);
520 if (k >= 0) {
Steve Dowerf63dab52015-02-25 20:48:01 -0800521 wchar_t * context = NULL;
522 wchar_t * tok = wcstok_s(tmpbuffer, L" \t\r\n", &context);
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100523 if ((tok != NULL) && !wcscmp(tok, key)) {
Steve Dowerf63dab52015-02-25 20:48:01 -0800524 tok = wcstok_s(NULL, L" \t", &context);
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100525 if ((tok != NULL) && !wcscmp(tok, L"=")) {
Steve Dowerf63dab52015-02-25 20:48:01 -0800526 tok = wcstok_s(NULL, L"\r\n", &context);
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100527 if (tok != NULL) {
528 wcsncpy(value, tok, MAXPATHLEN);
529 result = 1;
530 break;
531 }
532 }
533 }
534 }
535 }
536 }
537 return result;
538}
539
Steve Dower4db86bc2016-09-09 09:17:35 -0700540static int
Steve Dowered51b262016-09-17 12:54:06 -0700541read_pth_file(const wchar_t *path, wchar_t *prefix, int *isolated, int *nosite)
Steve Dower4db86bc2016-09-09 09:17:35 -0700542{
543 FILE *sp_file = _Py_wfopen(path, L"r");
544 if (sp_file == NULL)
545 return -1;
546
Steve Dowered51b262016-09-17 12:54:06 -0700547 wcscpy_s(prefix, MAXPATHLEN+1, path);
548 reduce(prefix);
549 *isolated = 1;
550 *nosite = 1;
551
Steve Dower4db86bc2016-09-09 09:17:35 -0700552 size_t bufsiz = MAXPATHLEN;
553 size_t prefixlen = wcslen(prefix);
554
555 wchar_t *buf = (wchar_t*)PyMem_RawMalloc(bufsiz * sizeof(wchar_t));
556 buf[0] = '\0';
557
558 while (!feof(sp_file)) {
559 char line[MAXPATHLEN + 1];
560 char *p = fgets(line, MAXPATHLEN + 1, sp_file);
561 if (!p)
562 break;
Steve Dowered51b262016-09-17 12:54:06 -0700563 if (*p == '\0' || *p == '#')
564 continue;
565 while (*++p) {
566 if (*p == '\r' || *p == '\n') {
567 *p = '\0';
568 break;
569 }
570 }
Steve Dower4db86bc2016-09-09 09:17:35 -0700571
Steve Dowered51b262016-09-17 12:54:06 -0700572 if (strcmp(line, "import site") == 0) {
573 *nosite = 0;
574 continue;
575 } else if (strncmp(line, "import ", 7) == 0) {
576 Py_FatalError("only 'import site' is supported in ._pth file");
577 }
Steve Dower4db86bc2016-09-09 09:17:35 -0700578
Steve Dowered51b262016-09-17 12:54:06 -0700579 DWORD wn = MultiByteToWideChar(CP_UTF8, 0, line, -1, NULL, 0);
Steve Dower4db86bc2016-09-09 09:17:35 -0700580 wchar_t *wline = (wchar_t*)PyMem_RawMalloc((wn + 1) * sizeof(wchar_t));
Steve Dowered51b262016-09-17 12:54:06 -0700581 wn = MultiByteToWideChar(CP_UTF8, 0, line, -1, wline, wn + 1);
Steve Dower4db86bc2016-09-09 09:17:35 -0700582 wline[wn] = '\0';
583
Steve Dowerc6dd4152016-10-27 14:28:07 -0700584 size_t usedsiz = wcslen(buf);
585 while (usedsiz + wn + prefixlen + 4 > bufsiz) {
Steve Dower4db86bc2016-09-09 09:17:35 -0700586 bufsiz += MAXPATHLEN;
587 buf = (wchar_t*)PyMem_RawRealloc(buf, (bufsiz + 1) * sizeof(wchar_t));
588 if (!buf) {
589 PyMem_RawFree(wline);
590 goto error;
591 }
592 }
593
Steve Dowerc6dd4152016-10-27 14:28:07 -0700594 if (usedsiz) {
Steve Dower4db86bc2016-09-09 09:17:35 -0700595 wcscat_s(buf, bufsiz, L";");
Steve Dowerc6dd4152016-10-27 14:28:07 -0700596 usedsiz += 1;
597 }
Steve Dowered51b262016-09-17 12:54:06 -0700598
Steve Dowerc6dd4152016-10-27 14:28:07 -0700599 errno_t result;
600 _Py_BEGIN_SUPPRESS_IPH
601 result = wcscat_s(buf, bufsiz, prefix);
602 _Py_END_SUPPRESS_IPH
603 if (result == EINVAL) {
604 Py_FatalError("invalid argument during ._pth processing");
605 } else if (result == ERANGE) {
606 Py_FatalError("buffer overflow during ._pth processing");
607 }
608 wchar_t *b = &buf[usedsiz];
Steve Dower4db86bc2016-09-09 09:17:35 -0700609 join(b, wline);
610
611 PyMem_RawFree(wline);
612 }
613
614 module_search_path = buf;
615
616 fclose(sp_file);
617 return 0;
618
619error:
620 PyMem_RawFree(buf);
621 fclose(sp_file);
622 return -1;
623}
624
625
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000626static void
Thomas Wouters78890102000-07-22 19:25:51 +0000627calculate_path(void)
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 wchar_t argv0_path[MAXPATHLEN+1];
630 wchar_t *buf;
631 size_t bufsz;
632 wchar_t *pythonhome = Py_GetPythonHome();
633 wchar_t *envpath = NULL;
Guido van Rossumeea14491997-08-13 21:30:44 +0000634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 int skiphome, skipdefault;
636 wchar_t *machinepath = NULL;
637 wchar_t *userpath = NULL;
638 wchar_t zip_path[MAXPATHLEN+1];
Amaury Forgeot d'Arc66f8c432009-06-09 21:30:01 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 if (!Py_IgnoreEnvironmentFlag) {
641 envpath = _wgetenv(L"PYTHONPATH");
642 }
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 get_progpath();
645 /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700646 wcscpy_s(argv0_path, MAXPATHLEN+1, progpath);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 reduce(argv0_path);
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100648
Steve Dower4db86bc2016-09-09 09:17:35 -0700649 /* Search for a sys.path file */
650 {
651 wchar_t spbuffer[MAXPATHLEN+1];
652
Steve Dowered51b262016-09-17 12:54:06 -0700653 if ((dllpath[0] && !change_ext(spbuffer, dllpath, L"._pth") && exists(spbuffer)) ||
654 (progpath[0] && !change_ext(spbuffer, progpath, L"._pth") && exists(spbuffer))) {
655
656 if (!read_pth_file(spbuffer, prefix, &Py_IsolatedFlag, &Py_NoSiteFlag)) {
657 return;
658 }
Steve Dower4db86bc2016-09-09 09:17:35 -0700659 }
660 }
661
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100662 /* Search for an environment configuration file, first in the
663 executable's directory and then in the parent directory.
664 If found, open it for use when searching for prefixes.
665 */
666
667 {
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700668 wchar_t envbuffer[MAXPATHLEN+1];
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100669 wchar_t tmpbuffer[MAXPATHLEN+1];
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700670 const wchar_t *env_cfg = L"pyvenv.cfg";
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100671 FILE * env_file = NULL;
672
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700673 wcscpy_s(envbuffer, MAXPATHLEN+1, argv0_path);
674 join(envbuffer, env_cfg);
675 env_file = _Py_wfopen(envbuffer, L"r");
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100676 if (env_file == NULL) {
677 errno = 0;
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700678 reduce(envbuffer);
679 reduce(envbuffer);
680 join(envbuffer, env_cfg);
681 env_file = _Py_wfopen(envbuffer, L"r");
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100682 if (env_file == NULL) {
683 errno = 0;
684 }
685 }
686 if (env_file != NULL) {
687 /* Look for a 'home' variable and set argv0_path to it, if found */
688 if (find_env_config_value(env_file, L"home", tmpbuffer)) {
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700689 wcscpy_s(argv0_path, MAXPATHLEN+1, tmpbuffer);
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100690 }
691 fclose(env_file);
692 env_file = NULL;
693 }
694 }
695
Steve Dower50289382016-09-09 14:22:43 -0700696 /* Calculate zip archive path from DLL or exe path */
Steve Dowered51b262016-09-17 12:54:06 -0700697 change_ext(zip_path, dllpath[0] ? dllpath : progpath, L".zip");
Steve Dower50289382016-09-09 14:22:43 -0700698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 if (pythonhome == NULL || *pythonhome == '\0') {
Steve Dower50289382016-09-09 14:22:43 -0700700 if (zip_path[0] && exists(zip_path)) {
701 wcscpy_s(prefix, MAXPATHLEN+1, zip_path);
702 reduce(prefix);
703 pythonhome = prefix;
704 } else if (search_for_prefix(argv0_path, LANDMARK))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 pythonhome = prefix;
706 else
707 pythonhome = NULL;
708 }
709 else
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700710 wcscpy_s(prefix, MAXPATHLEN+1, pythonhome);
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 if (envpath && *envpath == '\0')
713 envpath = NULL;
Guido van Rossumeea14491997-08-13 21:30:44 +0000714
Guido van Rossume02e48b2000-03-29 01:49:47 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 skiphome = pythonhome==NULL ? 0 : 1;
Martin v. Löwisbc186a82009-02-02 15:32:22 +0000717#ifdef Py_ENABLE_SHARED
Steve Dower4db86bc2016-09-09 09:17:35 -0700718 machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, skiphome);
719 userpath = getpythonregpath(HKEY_CURRENT_USER, skiphome);
Martin v. Löwisbc186a82009-02-02 15:32:22 +0000720#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 /* We only use the default relative PYTHONPATH if we havent
722 anything better to use! */
723 skipdefault = envpath!=NULL || pythonhome!=NULL || \
724 machinepath!=NULL || userpath!=NULL;
Guido van Rossum43ff1141998-08-08 23:40:40 +0000725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 /* We need to construct a path from the following parts.
727 (1) the PYTHONPATH environment variable, if set;
728 (2) for Win32, the zip archive file path;
729 (3) for Win32, the machinepath and userpath, if set;
730 (4) the PYTHONPATH config macro, with the leading "."
731 of each component replaced with pythonhome, if set;
732 (5) the directory containing the executable (argv0_path).
733 The length calculation calculates #4 first.
734 Extra rules:
735 - If PYTHONHOME is set (in any way) item (3) is ignored.
736 - If registry values are used, (4) and (5) are ignored.
737 */
Guido van Rossumeea14491997-08-13 21:30:44 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 /* Calculate size of return buffer */
740 if (pythonhome != NULL) {
741 wchar_t *p;
742 bufsz = 1;
743 for (p = PYTHONPATH; *p; p++) {
744 if (*p == DELIM)
745 bufsz++; /* number of DELIM plus one */
746 }
Steve Dowerf64b9d52015-05-23 17:34:50 -0700747 bufsz *= wcslen(pythonhome);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 }
749 else
750 bufsz = 0;
Steve Dowerf64b9d52015-05-23 17:34:50 -0700751 bufsz += wcslen(PYTHONPATH) + 1;
752 bufsz += wcslen(argv0_path) + 1;
Steve Dower4db86bc2016-09-09 09:17:35 -0700753 if (userpath)
Steve Dowerf64b9d52015-05-23 17:34:50 -0700754 bufsz += wcslen(userpath) + 1;
Steve Dower4db86bc2016-09-09 09:17:35 -0700755 if (machinepath)
Steve Dowerf64b9d52015-05-23 17:34:50 -0700756 bufsz += wcslen(machinepath) + 1;
757 bufsz += wcslen(zip_path) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 if (envpath != NULL)
Steve Dowerf64b9d52015-05-23 17:34:50 -0700759 bufsz += wcslen(envpath) + 1;
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000760
Victor Stinner1a7425f2013-07-07 16:25:15 +0200761 module_search_path = buf = PyMem_RawMalloc(bufsz*sizeof(wchar_t));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 if (buf == NULL) {
763 /* We can't exit, so print a warning and limp along */
764 fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n");
765 if (envpath) {
766 fprintf(stderr, "Using environment $PYTHONPATH.\n");
767 module_search_path = envpath;
768 }
769 else {
770 fprintf(stderr, "Using default static path.\n");
771 module_search_path = PYTHONPATH;
772 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200773 PyMem_RawFree(machinepath);
774 PyMem_RawFree(userpath);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 return;
776 }
Guido van Rossumeea14491997-08-13 21:30:44 +0000777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 if (envpath) {
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700779 if (wcscpy_s(buf, bufsz - (buf - module_search_path), envpath))
780 Py_FatalError("buffer overflow in getpathp.c's calculate_path()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 buf = wcschr(buf, L'\0');
782 *buf++ = DELIM;
783 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 if (zip_path[0]) {
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700785 if (wcscpy_s(buf, bufsz - (buf - module_search_path), zip_path))
786 Py_FatalError("buffer overflow in getpathp.c's calculate_path()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 buf = wcschr(buf, L'\0');
788 *buf++ = DELIM;
789 }
790 if (userpath) {
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700791 if (wcscpy_s(buf, bufsz - (buf - module_search_path), userpath))
792 Py_FatalError("buffer overflow in getpathp.c's calculate_path()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 buf = wcschr(buf, L'\0');
794 *buf++ = DELIM;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200795 PyMem_RawFree(userpath);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 }
797 if (machinepath) {
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700798 if (wcscpy_s(buf, bufsz - (buf - module_search_path), machinepath))
799 Py_FatalError("buffer overflow in getpathp.c's calculate_path()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 buf = wcschr(buf, L'\0');
801 *buf++ = DELIM;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200802 PyMem_RawFree(machinepath);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 }
804 if (pythonhome == NULL) {
805 if (!skipdefault) {
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700806 if (wcscpy_s(buf, bufsz - (buf - module_search_path), PYTHONPATH))
807 Py_FatalError("buffer overflow in getpathp.c's calculate_path()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 buf = wcschr(buf, L'\0');
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700809 *buf++ = DELIM;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 }
Steve Dower4db86bc2016-09-09 09:17:35 -0700811 } else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 wchar_t *p = PYTHONPATH;
813 wchar_t *q;
814 size_t n;
815 for (;;) {
816 q = wcschr(p, DELIM);
817 if (q == NULL)
818 n = wcslen(p);
819 else
820 n = q-p;
821 if (p[0] == '.' && is_sep(p[1])) {
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700822 if (wcscpy_s(buf, bufsz - (buf - module_search_path), pythonhome))
823 Py_FatalError("buffer overflow in getpathp.c's calculate_path()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 buf = wcschr(buf, L'\0');
825 p++;
826 n--;
827 }
828 wcsncpy(buf, p, n);
829 buf += n;
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700830 *buf++ = DELIM;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 if (q == NULL)
832 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 p = q+1;
834 }
835 }
836 if (argv0_path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 wcscpy(buf, argv0_path);
838 buf = wcschr(buf, L'\0');
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700839 *buf++ = DELIM;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 }
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700841 *(buf - 1) = L'\0';
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 /* Now to pull one last hack/trick. If sys.prefix is
843 empty, then try and find it somewhere on the paths
844 we calculated. We scan backwards, as our general policy
845 is that Python core directories are at the *end* of
846 sys.path. We assume that our "lib" directory is
847 on the path, and that our 'prefix' directory is
848 the parent of that.
849 */
850 if (*prefix==L'\0') {
851 wchar_t lookBuf[MAXPATHLEN+1];
852 wchar_t *look = buf - 1; /* 'buf' is at the end of the buffer */
853 while (1) {
854 Py_ssize_t nchars;
855 wchar_t *lookEnd = look;
856 /* 'look' will end up one character before the
857 start of the path in question - even if this
858 is one character before the start of the buffer
859 */
860 while (look >= module_search_path && *look != DELIM)
861 look--;
862 nchars = lookEnd-look;
863 wcsncpy(lookBuf, look+1, nchars);
864 lookBuf[nchars] = L'\0';
865 /* Up one level to the parent */
866 reduce(lookBuf);
867 if (search_for_prefix(lookBuf, LANDMARK)) {
868 break;
869 }
870 /* If we are out of paths to search - give up */
871 if (look < module_search_path)
872 break;
873 look--;
874 }
875 }
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000876}
877
878
879/* External interface */
880
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +0000881void
882Py_SetPath(const wchar_t *path)
883{
884 if (module_search_path != NULL) {
Victor Stinner1a7425f2013-07-07 16:25:15 +0200885 PyMem_RawFree(module_search_path);
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +0000886 module_search_path = NULL;
887 }
888 if (path != NULL) {
889 extern wchar_t *Py_GetProgramName(void);
890 wchar_t *prog = Py_GetProgramName();
891 wcsncpy(progpath, prog, MAXPATHLEN);
892 prefix[0] = L'\0';
Victor Stinner1a7425f2013-07-07 16:25:15 +0200893 module_search_path = PyMem_RawMalloc((wcslen(path) + 1) * sizeof(wchar_t));
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +0000894 if (module_search_path != NULL)
895 wcscpy(module_search_path, path);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200896 }
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +0000897}
898
Martin v. Löwis790465f2008-04-05 20:41:37 +0000899wchar_t *
Thomas Wouters78890102000-07-22 19:25:51 +0000900Py_GetPath(void)
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 if (!module_search_path)
903 calculate_path();
904 return module_search_path;
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000905}
906
Martin v. Löwis790465f2008-04-05 20:41:37 +0000907wchar_t *
Thomas Wouters78890102000-07-22 19:25:51 +0000908Py_GetPrefix(void)
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 if (!module_search_path)
911 calculate_path();
912 return prefix;
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000913}
914
Martin v. Löwis790465f2008-04-05 20:41:37 +0000915wchar_t *
Thomas Wouters78890102000-07-22 19:25:51 +0000916Py_GetExecPrefix(void)
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 return Py_GetPrefix();
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000919}
920
Martin v. Löwis790465f2008-04-05 20:41:37 +0000921wchar_t *
Thomas Wouters78890102000-07-22 19:25:51 +0000922Py_GetProgramFullPath(void)
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 if (!module_search_path)
925 calculate_path();
926 return progpath;
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000927}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000928
Victor Stinner63941882011-09-29 00:42:28 +0200929/* Load python3.dll before loading any extension module that might refer
930 to it. That way, we can be sure that always the python3.dll corresponding
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000931 to this python DLL is loaded, not a python3.dll that might be on the path
932 by chance.
933 Return whether the DLL was found.
934*/
935static int python3_checked = 0;
936static HANDLE hPython3;
937int
938_Py_CheckPython3()
939{
940 wchar_t py3path[MAXPATHLEN+1];
941 wchar_t *s;
942 if (python3_checked)
943 return hPython3 != NULL;
944 python3_checked = 1;
945
946 /* If there is a python3.dll next to the python3y.dll,
947 assume this is a build tree; use that DLL */
948 wcscpy(py3path, dllpath);
949 s = wcsrchr(py3path, L'\\');
950 if (!s)
951 s = py3path;
952 wcscpy(s, L"\\python3.dll");
953 hPython3 = LoadLibraryExW(py3path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
954 if (hPython3 != NULL)
955 return 1;
956
957 /* Check sys.prefix\DLLs\python3.dll */
958 wcscpy(py3path, Py_GetPrefix());
959 wcscat(py3path, L"\\DLLs\\python3.dll");
960 hPython3 = LoadLibraryExW(py3path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
961 return hPython3 != NULL;
962}