blob: 1d18faed4500ed77f6022ab134a0fb45988b7f57 [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
Xiang Zhang0710d752017-03-11 13:02:52 +0800188ismodule(wchar_t *filename, int update_filename) /* Is module -- check for .pyc 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;
Xiang Zhang0710d752017-03-11 13:02:52 +0800199 filename[n] = L'c';
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700200 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 {
luzpaza5293b42017-11-05 07:37:50 -0600398 /* If we have no values, we don't need a ';' */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 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 Dower5f9193a2017-02-04 15:19:29 -0800563 if (*p == '\0' || *p == '\r' || *p == '\n' || *p == '#')
Steve Dowered51b262016-09-17 12:54:06 -0700564 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
Victor Stinnere32e79f2017-11-23 01:49:45 +0100627calculate_path(_PyMainInterpreterConfig *config)
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
Victor Stinnere32e79f2017-11-23 01:49:45 +0100640 if (config) {
641 envpath = config->module_search_path_env;
Victor Stinnerd4341102017-11-23 00:12:09 +0100642 }
643 else if (!Py_IgnoreEnvironmentFlag) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 envpath = _wgetenv(L"PYTHONPATH");
Victor Stinnerd4341102017-11-23 00:12:09 +0100645 if (envpath && *envpath == '\0')
646 envpath = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 }
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 get_progpath();
650 /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700651 wcscpy_s(argv0_path, MAXPATHLEN+1, progpath);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 reduce(argv0_path);
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100653
Steve Dower4db86bc2016-09-09 09:17:35 -0700654 /* Search for a sys.path file */
655 {
656 wchar_t spbuffer[MAXPATHLEN+1];
657
Steve Dowered51b262016-09-17 12:54:06 -0700658 if ((dllpath[0] && !change_ext(spbuffer, dllpath, L"._pth") && exists(spbuffer)) ||
659 (progpath[0] && !change_ext(spbuffer, progpath, L"._pth") && exists(spbuffer))) {
660
661 if (!read_pth_file(spbuffer, prefix, &Py_IsolatedFlag, &Py_NoSiteFlag)) {
662 return;
663 }
Steve Dower4db86bc2016-09-09 09:17:35 -0700664 }
665 }
666
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100667 /* Search for an environment configuration file, first in the
668 executable's directory and then in the parent directory.
669 If found, open it for use when searching for prefixes.
670 */
671
672 {
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700673 wchar_t envbuffer[MAXPATHLEN+1];
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100674 wchar_t tmpbuffer[MAXPATHLEN+1];
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700675 const wchar_t *env_cfg = L"pyvenv.cfg";
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100676 FILE * env_file = NULL;
677
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700678 wcscpy_s(envbuffer, MAXPATHLEN+1, argv0_path);
679 join(envbuffer, env_cfg);
680 env_file = _Py_wfopen(envbuffer, L"r");
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100681 if (env_file == NULL) {
682 errno = 0;
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700683 reduce(envbuffer);
684 reduce(envbuffer);
685 join(envbuffer, env_cfg);
686 env_file = _Py_wfopen(envbuffer, L"r");
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100687 if (env_file == NULL) {
688 errno = 0;
689 }
690 }
691 if (env_file != NULL) {
692 /* Look for a 'home' variable and set argv0_path to it, if found */
693 if (find_env_config_value(env_file, L"home", tmpbuffer)) {
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700694 wcscpy_s(argv0_path, MAXPATHLEN+1, tmpbuffer);
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100695 }
696 fclose(env_file);
697 env_file = NULL;
698 }
699 }
700
Steve Dower50289382016-09-09 14:22:43 -0700701 /* Calculate zip archive path from DLL or exe path */
Steve Dowered51b262016-09-17 12:54:06 -0700702 change_ext(zip_path, dllpath[0] ? dllpath : progpath, L".zip");
Steve Dower50289382016-09-09 14:22:43 -0700703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 if (pythonhome == NULL || *pythonhome == '\0') {
Steve Dower50289382016-09-09 14:22:43 -0700705 if (zip_path[0] && exists(zip_path)) {
706 wcscpy_s(prefix, MAXPATHLEN+1, zip_path);
707 reduce(prefix);
708 pythonhome = prefix;
709 } else if (search_for_prefix(argv0_path, LANDMARK))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 pythonhome = prefix;
711 else
712 pythonhome = NULL;
713 }
714 else
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700715 wcscpy_s(prefix, MAXPATHLEN+1, pythonhome);
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000716
Guido van Rossume02e48b2000-03-29 01:49:47 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 skiphome = pythonhome==NULL ? 0 : 1;
Martin v. Löwisbc186a82009-02-02 15:32:22 +0000719#ifdef Py_ENABLE_SHARED
Steve Dower4db86bc2016-09-09 09:17:35 -0700720 machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, skiphome);
721 userpath = getpythonregpath(HKEY_CURRENT_USER, skiphome);
Martin v. Löwisbc186a82009-02-02 15:32:22 +0000722#endif
luzpaza5293b42017-11-05 07:37:50 -0600723 /* We only use the default relative PYTHONPATH if we haven't
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 anything better to use! */
725 skipdefault = envpath!=NULL || pythonhome!=NULL || \
726 machinepath!=NULL || userpath!=NULL;
Guido van Rossum43ff1141998-08-08 23:40:40 +0000727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 /* We need to construct a path from the following parts.
729 (1) the PYTHONPATH environment variable, if set;
730 (2) for Win32, the zip archive file path;
731 (3) for Win32, the machinepath and userpath, if set;
732 (4) the PYTHONPATH config macro, with the leading "."
733 of each component replaced with pythonhome, if set;
734 (5) the directory containing the executable (argv0_path).
735 The length calculation calculates #4 first.
736 Extra rules:
737 - If PYTHONHOME is set (in any way) item (3) is ignored.
738 - If registry values are used, (4) and (5) are ignored.
739 */
Guido van Rossumeea14491997-08-13 21:30:44 +0000740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 /* Calculate size of return buffer */
742 if (pythonhome != NULL) {
743 wchar_t *p;
744 bufsz = 1;
745 for (p = PYTHONPATH; *p; p++) {
746 if (*p == DELIM)
747 bufsz++; /* number of DELIM plus one */
748 }
Steve Dowerf64b9d52015-05-23 17:34:50 -0700749 bufsz *= wcslen(pythonhome);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 }
751 else
752 bufsz = 0;
Steve Dowerf64b9d52015-05-23 17:34:50 -0700753 bufsz += wcslen(PYTHONPATH) + 1;
754 bufsz += wcslen(argv0_path) + 1;
Steve Dower4db86bc2016-09-09 09:17:35 -0700755 if (userpath)
Steve Dowerf64b9d52015-05-23 17:34:50 -0700756 bufsz += wcslen(userpath) + 1;
Steve Dower4db86bc2016-09-09 09:17:35 -0700757 if (machinepath)
Steve Dowerf64b9d52015-05-23 17:34:50 -0700758 bufsz += wcslen(machinepath) + 1;
759 bufsz += wcslen(zip_path) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 if (envpath != NULL)
Steve Dowerf64b9d52015-05-23 17:34:50 -0700761 bufsz += wcslen(envpath) + 1;
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000762
Victor Stinner1a7425f2013-07-07 16:25:15 +0200763 module_search_path = buf = PyMem_RawMalloc(bufsz*sizeof(wchar_t));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 if (buf == NULL) {
765 /* We can't exit, so print a warning and limp along */
766 fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n");
767 if (envpath) {
768 fprintf(stderr, "Using environment $PYTHONPATH.\n");
769 module_search_path = envpath;
770 }
771 else {
772 fprintf(stderr, "Using default static path.\n");
773 module_search_path = PYTHONPATH;
774 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200775 PyMem_RawFree(machinepath);
776 PyMem_RawFree(userpath);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 return;
778 }
Guido van Rossumeea14491997-08-13 21:30:44 +0000779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 if (envpath) {
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700781 if (wcscpy_s(buf, bufsz - (buf - module_search_path), envpath))
782 Py_FatalError("buffer overflow in getpathp.c's calculate_path()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 buf = wcschr(buf, L'\0');
784 *buf++ = DELIM;
785 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 if (zip_path[0]) {
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700787 if (wcscpy_s(buf, bufsz - (buf - module_search_path), zip_path))
788 Py_FatalError("buffer overflow in getpathp.c's calculate_path()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 buf = wcschr(buf, L'\0');
790 *buf++ = DELIM;
791 }
792 if (userpath) {
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700793 if (wcscpy_s(buf, bufsz - (buf - module_search_path), userpath))
794 Py_FatalError("buffer overflow in getpathp.c's calculate_path()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 buf = wcschr(buf, L'\0');
796 *buf++ = DELIM;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200797 PyMem_RawFree(userpath);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 }
799 if (machinepath) {
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700800 if (wcscpy_s(buf, bufsz - (buf - module_search_path), machinepath))
801 Py_FatalError("buffer overflow in getpathp.c's calculate_path()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 buf = wcschr(buf, L'\0');
803 *buf++ = DELIM;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200804 PyMem_RawFree(machinepath);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 }
806 if (pythonhome == NULL) {
807 if (!skipdefault) {
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700808 if (wcscpy_s(buf, bufsz - (buf - module_search_path), PYTHONPATH))
809 Py_FatalError("buffer overflow in getpathp.c's calculate_path()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 buf = wcschr(buf, L'\0');
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700811 *buf++ = DELIM;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 }
Steve Dower4db86bc2016-09-09 09:17:35 -0700813 } else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 wchar_t *p = PYTHONPATH;
815 wchar_t *q;
816 size_t n;
817 for (;;) {
818 q = wcschr(p, DELIM);
819 if (q == NULL)
820 n = wcslen(p);
821 else
822 n = q-p;
823 if (p[0] == '.' && is_sep(p[1])) {
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700824 if (wcscpy_s(buf, bufsz - (buf - module_search_path), pythonhome))
825 Py_FatalError("buffer overflow in getpathp.c's calculate_path()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 buf = wcschr(buf, L'\0');
827 p++;
828 n--;
829 }
830 wcsncpy(buf, p, n);
831 buf += n;
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700832 *buf++ = DELIM;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 if (q == NULL)
834 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 p = q+1;
836 }
837 }
838 if (argv0_path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 wcscpy(buf, argv0_path);
840 buf = wcschr(buf, L'\0');
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700841 *buf++ = DELIM;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 }
Steve Dower4a7fe7e2015-05-22 15:10:10 -0700843 *(buf - 1) = L'\0';
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 /* Now to pull one last hack/trick. If sys.prefix is
845 empty, then try and find it somewhere on the paths
846 we calculated. We scan backwards, as our general policy
847 is that Python core directories are at the *end* of
848 sys.path. We assume that our "lib" directory is
849 on the path, and that our 'prefix' directory is
850 the parent of that.
851 */
852 if (*prefix==L'\0') {
853 wchar_t lookBuf[MAXPATHLEN+1];
854 wchar_t *look = buf - 1; /* 'buf' is at the end of the buffer */
855 while (1) {
856 Py_ssize_t nchars;
857 wchar_t *lookEnd = look;
858 /* 'look' will end up one character before the
859 start of the path in question - even if this
860 is one character before the start of the buffer
861 */
862 while (look >= module_search_path && *look != DELIM)
863 look--;
864 nchars = lookEnd-look;
865 wcsncpy(lookBuf, look+1, nchars);
866 lookBuf[nchars] = L'\0';
867 /* Up one level to the parent */
868 reduce(lookBuf);
869 if (search_for_prefix(lookBuf, LANDMARK)) {
870 break;
871 }
872 /* If we are out of paths to search - give up */
873 if (look < module_search_path)
874 break;
875 look--;
876 }
877 }
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000878}
879
880
881/* External interface */
882
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +0000883void
884Py_SetPath(const wchar_t *path)
885{
886 if (module_search_path != NULL) {
Victor Stinner1a7425f2013-07-07 16:25:15 +0200887 PyMem_RawFree(module_search_path);
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +0000888 module_search_path = NULL;
889 }
890 if (path != NULL) {
891 extern wchar_t *Py_GetProgramName(void);
892 wchar_t *prog = Py_GetProgramName();
893 wcsncpy(progpath, prog, MAXPATHLEN);
894 prefix[0] = L'\0';
Victor Stinner1a7425f2013-07-07 16:25:15 +0200895 module_search_path = PyMem_RawMalloc((wcslen(path) + 1) * sizeof(wchar_t));
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +0000896 if (module_search_path != NULL)
897 wcscpy(module_search_path, path);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200898 }
Kristján Valur Jónsson3b69db22010-09-27 05:32:54 +0000899}
900
Martin v. Löwis790465f2008-04-05 20:41:37 +0000901wchar_t *
Victor Stinnere32e79f2017-11-23 01:49:45 +0100902_Py_GetPathWithConfig(_PyMainInterpreterConfig *config)
Victor Stinnerd4341102017-11-23 00:12:09 +0100903{
904 if (!module_search_path) {
Victor Stinnere32e79f2017-11-23 01:49:45 +0100905 calculate_path(config);
Victor Stinnerd4341102017-11-23 00:12:09 +0100906 }
907 return module_search_path;
908}
909
910wchar_t *
Thomas Wouters78890102000-07-22 19:25:51 +0000911Py_GetPath(void)
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 if (!module_search_path)
Victor Stinnerd4341102017-11-23 00:12:09 +0100914 calculate_path(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 return module_search_path;
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000916}
917
Martin v. Löwis790465f2008-04-05 20:41:37 +0000918wchar_t *
Thomas Wouters78890102000-07-22 19:25:51 +0000919Py_GetPrefix(void)
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 if (!module_search_path)
Victor Stinnerd4341102017-11-23 00:12:09 +0100922 calculate_path(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 return prefix;
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000924}
925
Martin v. Löwis790465f2008-04-05 20:41:37 +0000926wchar_t *
Thomas Wouters78890102000-07-22 19:25:51 +0000927Py_GetExecPrefix(void)
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 return Py_GetPrefix();
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000930}
931
Martin v. Löwis790465f2008-04-05 20:41:37 +0000932wchar_t *
Thomas Wouters78890102000-07-22 19:25:51 +0000933Py_GetProgramFullPath(void)
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 if (!module_search_path)
Victor Stinnerd4341102017-11-23 00:12:09 +0100936 calculate_path(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 return progpath;
Guido van Rossum1aa7e3a1997-05-19 14:16:21 +0000938}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000939
Victor Stinner63941882011-09-29 00:42:28 +0200940/* Load python3.dll before loading any extension module that might refer
941 to it. That way, we can be sure that always the python3.dll corresponding
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000942 to this python DLL is loaded, not a python3.dll that might be on the path
943 by chance.
944 Return whether the DLL was found.
945*/
946static int python3_checked = 0;
947static HANDLE hPython3;
948int
949_Py_CheckPython3()
950{
951 wchar_t py3path[MAXPATHLEN+1];
952 wchar_t *s;
953 if (python3_checked)
954 return hPython3 != NULL;
955 python3_checked = 1;
956
957 /* If there is a python3.dll next to the python3y.dll,
958 assume this is a build tree; use that DLL */
959 wcscpy(py3path, dllpath);
960 s = wcsrchr(py3path, L'\\');
961 if (!s)
962 s = py3path;
963 wcscpy(s, L"\\python3.dll");
964 hPython3 = LoadLibraryExW(py3path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
965 if (hPython3 != NULL)
966 return 1;
967
968 /* Check sys.prefix\DLLs\python3.dll */
969 wcscpy(py3path, Py_GetPrefix());
970 wcscat(py3path, L"\\DLLs\\python3.dll");
971 hPython3 = LoadLibraryExW(py3path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
972 return hPython3 != NULL;
973}