ยปCore Development>Code coverage>PC/getpathp.c

Python code coverage for PC/getpathp.c

#countcontent
1n/a
2n/a/* Return the initial module search path. */
3n/a/* Used by DOS, Windows 3.1, Windows 95/98, Windows NT. */
4n/a
5n/a/* ----------------------------------------------------------------
6n/a PATH RULES FOR WINDOWS:
7n/a This describes how sys.path is formed on Windows. It describes the
8n/a functionality, not the implementation (ie, the order in which these
9n/a are actually fetched is different). The presence of a python._pth or
10n/a pythonXY._pth file alongside the program overrides these rules - see
11n/a below.
12n/a
13n/a * Python always adds an empty entry at the start, which corresponds
14n/a to the current directory.
15n/a
16n/a * If the PYTHONPATH env. var. exists, its entries are added next.
17n/a
18n/a * We look in the registry for "application paths" - that is, sub-keys
19n/a under the main PythonPath registry key. These are added next (the
20n/a order of sub-key processing is undefined).
21n/a HKEY_CURRENT_USER is searched and added first.
22n/a HKEY_LOCAL_MACHINE is searched and added next.
23n/a (Note that all known installers only use HKLM, so HKCU is typically
24n/a empty)
25n/a
26n/a * We attempt to locate the "Python Home" - if the PYTHONHOME env var
27n/a is set, we believe it. Otherwise, we use the path of our host .EXE's
28n/a to try and locate one of our "landmarks" and deduce our home.
29n/a - If we DO have a Python Home: The relevant sub-directories (Lib,
30n/a DLLs, etc) are based on the Python Home
31n/a - If we DO NOT have a Python Home, the core Python Path is
32n/a loaded from the registry. This is the main PythonPath key,
33n/a and both HKLM and HKCU are combined to form the path)
34n/a
35n/a * Iff - we can not locate the Python Home, have not had a PYTHONPATH
36n/a specified, and can't locate any Registry entries (ie, we have _nothing_
37n/a we can assume is a good path), a default path with relative entries is
38n/a used (eg. .\Lib;.\DLLs, etc)
39n/a
40n/a
41n/a If a '._pth' file exists adjacent to the executable with the same base name
42n/a (e.g. python._pth adjacent to python.exe) or adjacent to the shared library
43n/a (e.g. python36._pth adjacent to python36.dll), it is used in preference to
44n/a the above process. The shared library file takes precedence over the
45n/a executable. The path file must contain a list of paths to add to sys.path,
46n/a one per line. Each path is relative to the directory containing the file.
47n/a Blank lines and comments beginning with '#' are permitted.
48n/a
49n/a In the presence of this ._pth file, no other paths are added to the search
50n/a path, the registry finder is not enabled, site.py is not imported and
51n/a isolated mode is enabled. The site package can be enabled by including a
52n/a line reading "import site"; no other imports are recognized. Any invalid
53n/a entry (other than directories that do not exist) will result in immediate
54n/a termination of the program.
55n/a
56n/a
57n/a The end result of all this is:
58n/a * When running python.exe, or any other .exe in the main Python directory
59n/a (either an installed version, or directly from the PCbuild directory),
60n/a the core path is deduced, and the core paths in the registry are
61n/a ignored. Other "application paths" in the registry are always read.
62n/a
63n/a * When Python is hosted in another exe (different directory, embedded via
64n/a COM, etc), the Python Home will not be deduced, so the core path from
65n/a the registry is used. Other "application paths" in the registry are
66n/a always read.
67n/a
68n/a * If Python can't find its home and there is no registry (eg, frozen
69n/a exe, some very strange installation setup) you get a path with
70n/a some default, but relative, paths.
71n/a
72n/a * An embedding application can use Py_SetPath() to override all of
73n/a these automatic path computations.
74n/a
75n/a * An install of Python can fully specify the contents of sys.path using
76n/a either a 'EXENAME._pth' or 'DLLNAME._pth' file, optionally including
77n/a "import site" to enable the site module.
78n/a
79n/a ---------------------------------------------------------------- */
80n/a
81n/a
82n/a#include "Python.h"
83n/a#include "osdefs.h"
84n/a#include <wchar.h>
85n/a
86n/a#ifndef MS_WINDOWS
87n/a#error getpathp.c should only be built on Windows
88n/a#endif
89n/a
90n/a#include <windows.h>
91n/a#include <Shlwapi.h>
92n/a
93n/a#ifdef HAVE_SYS_TYPES_H
94n/a#include <sys/types.h>
95n/a#endif /* HAVE_SYS_TYPES_H */
96n/a
97n/a#ifdef HAVE_SYS_STAT_H
98n/a#include <sys/stat.h>
99n/a#endif /* HAVE_SYS_STAT_H */
100n/a
101n/a#include <string.h>
102n/a
103n/a/* Search in some common locations for the associated Python libraries.
104n/a *
105n/a * Py_GetPath() tries to return a sensible Python module search path.
106n/a *
107n/a * The approach is an adaptation for Windows of the strategy used in
108n/a * ../Modules/getpath.c; it uses the Windows Registry as one of its
109n/a * information sources.
110n/a *
111n/a * Py_SetPath() can be used to override this mechanism. Call Py_SetPath
112n/a * with a semicolon separated path prior to calling Py_Initialize.
113n/a */
114n/a
115n/a#ifndef LANDMARK
116n/a#define LANDMARK L"lib\\os.py"
117n/a#endif
118n/a
119n/astatic wchar_t prefix[MAXPATHLEN+1];
120n/astatic wchar_t progpath[MAXPATHLEN+1];
121n/astatic wchar_t dllpath[MAXPATHLEN+1];
122n/astatic wchar_t *module_search_path = NULL;
123n/a
124n/a
125n/astatic int
126n/ais_sep(wchar_t ch) /* determine if "ch" is a separator character */
127n/a{
128n/a#ifdef ALTSEP
129n/a return ch == SEP || ch == ALTSEP;
130n/a#else
131n/a return ch == SEP;
132n/a#endif
133n/a}
134n/a
135n/a/* assumes 'dir' null terminated in bounds. Never writes
136n/a beyond existing terminator.
137n/a*/
138n/astatic void
139n/areduce(wchar_t *dir)
140n/a{
141n/a size_t i = wcsnlen_s(dir, MAXPATHLEN+1);
142n/a if (i >= MAXPATHLEN+1)
143n/a Py_FatalError("buffer overflow in getpathp.c's reduce()");
144n/a
145n/a while (i > 0 && !is_sep(dir[i]))
146n/a --i;
147n/a dir[i] = '\0';
148n/a}
149n/a
150n/astatic int
151n/achange_ext(wchar_t *dest, const wchar_t *src, const wchar_t *ext)
152n/a{
153n/a size_t src_len = wcsnlen_s(src, MAXPATHLEN+1);
154n/a size_t i = src_len;
155n/a if (i >= MAXPATHLEN+1)
156n/a Py_FatalError("buffer overflow in getpathp.c's reduce()");
157n/a
158n/a while (i > 0 && src[i] != '.' && !is_sep(src[i]))
159n/a --i;
160n/a
161n/a if (i == 0) {
162n/a dest[0] = '\0';
163n/a return -1;
164n/a }
165n/a
166n/a if (is_sep(src[i]))
167n/a i = src_len;
168n/a
169n/a if (wcsncpy_s(dest, MAXPATHLEN+1, src, i) ||
170n/a wcscat_s(dest, MAXPATHLEN+1, ext)) {
171n/a dest[0] = '\0';
172n/a return -1;
173n/a }
174n/a
175n/a return 0;
176n/a}
177n/a
178n/astatic int
179n/aexists(wchar_t *filename)
180n/a{
181n/a return GetFileAttributesW(filename) != 0xFFFFFFFF;
182n/a}
183n/a
184n/a/* Assumes 'filename' MAXPATHLEN+1 bytes long -
185n/a may extend 'filename' by one character.
186n/a*/
187n/astatic int
188n/aismodule(wchar_t *filename, int update_filename) /* Is module -- check for .pyc/.pyo too */
189n/a{
190n/a size_t n;
191n/a
192n/a if (exists(filename))
193n/a return 1;
194n/a
195n/a /* Check for the compiled version of prefix. */
196n/a n = wcsnlen_s(filename, MAXPATHLEN+1);
197n/a if (n < MAXPATHLEN) {
198n/a int exist = 0;
199n/a filename[n] = Py_OptimizeFlag ? L'o' : L'c';
200n/a filename[n + 1] = L'\0';
201n/a exist = exists(filename);
202n/a if (!update_filename)
203n/a filename[n] = L'\0';
204n/a return exist;
205n/a }
206n/a return 0;
207n/a}
208n/a
209n/a/* Add a path component, by appending stuff to buffer.
210n/a buffer must have at least MAXPATHLEN + 1 bytes allocated, and contain a
211n/a NUL-terminated string with no more than MAXPATHLEN characters (not counting
212n/a the trailing NUL). It's a fatal error if it contains a string longer than
213n/a that (callers must be careful!). If these requirements are met, it's
214n/a guaranteed that buffer will still be a NUL-terminated string with no more
215n/a than MAXPATHLEN characters at exit. If stuff is too long, only as much of
216n/a stuff as fits will be appended.
217n/a*/
218n/a
219n/astatic int _PathCchCombineEx_Initialized = 0;
220n/atypedef HRESULT(__stdcall *PPathCchCombineEx)(PWSTR pszPathOut, size_t cchPathOut, PCWSTR pszPathIn, PCWSTR pszMore, unsigned long dwFlags);
221n/astatic PPathCchCombineEx _PathCchCombineEx;
222n/a
223n/astatic void
224n/ajoin(wchar_t *buffer, const wchar_t *stuff)
225n/a{
226n/a if (_PathCchCombineEx_Initialized == 0) {
227n/a HMODULE pathapi = LoadLibraryW(L"api-ms-win-core-path-l1-1-0.dll");
228n/a if (pathapi)
229n/a _PathCchCombineEx = (PPathCchCombineEx)GetProcAddress(pathapi, "PathCchCombineEx");
230n/a else
231n/a _PathCchCombineEx = NULL;
232n/a _PathCchCombineEx_Initialized = 1;
233n/a }
234n/a
235n/a if (_PathCchCombineEx) {
236n/a if (FAILED(_PathCchCombineEx(buffer, MAXPATHLEN+1, buffer, stuff, 0)))
237n/a Py_FatalError("buffer overflow in getpathp.c's join()");
238n/a } else {
239n/a if (!PathCombineW(buffer, buffer, stuff))
240n/a Py_FatalError("buffer overflow in getpathp.c's join()");
241n/a }
242n/a}
243n/a
244n/a/* gotlandmark only called by search_for_prefix, which ensures
245n/a 'prefix' is null terminated in bounds. join() ensures
246n/a 'landmark' can not overflow prefix if too long.
247n/a*/
248n/astatic int
249n/agotlandmark(const wchar_t *landmark)
250n/a{
251n/a int ok;
252n/a Py_ssize_t n = wcsnlen_s(prefix, MAXPATHLEN);
253n/a
254n/a join(prefix, landmark);
255n/a ok = ismodule(prefix, FALSE);
256n/a prefix[n] = '\0';
257n/a return ok;
258n/a}
259n/a
260n/a/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd.
261n/a assumption provided by only caller, calculate_path() */
262n/astatic int
263n/asearch_for_prefix(wchar_t *argv0_path, const wchar_t *landmark)
264n/a{
265n/a /* Search from argv0_path, until landmark is found */
266n/a wcscpy_s(prefix, MAXPATHLEN + 1, argv0_path);
267n/a do {
268n/a if (gotlandmark(landmark))
269n/a return 1;
270n/a reduce(prefix);
271n/a } while (prefix[0]);
272n/a return 0;
273n/a}
274n/a
275n/a#ifdef Py_ENABLE_SHARED
276n/a
277n/a/* a string loaded from the DLL at startup.*/
278n/aextern const char *PyWin_DLLVersionString;
279n/a
280n/a
281n/a/* Load a PYTHONPATH value from the registry.
282n/a Load from either HKEY_LOCAL_MACHINE or HKEY_CURRENT_USER.
283n/a
284n/a Works in both Unicode and 8bit environments. Only uses the
285n/a Ex family of functions so it also works with Windows CE.
286n/a
287n/a Returns NULL, or a pointer that should be freed.
288n/a
289n/a XXX - this code is pretty strange, as it used to also
290n/a work on Win16, where the buffer sizes werent available
291n/a in advance. It could be simplied now Win16/Win32s is dead!
292n/a*/
293n/a
294n/astatic wchar_t *
295n/agetpythonregpath(HKEY keyBase, int skipcore)
296n/a{
297n/a HKEY newKey = 0;
298n/a DWORD dataSize = 0;
299n/a DWORD numKeys = 0;
300n/a LONG rc;
301n/a wchar_t *retval = NULL;
302n/a WCHAR *dataBuf = NULL;
303n/a static const WCHAR keyPrefix[] = L"Software\\Python\\PythonCore\\";
304n/a static const WCHAR keySuffix[] = L"\\PythonPath";
305n/a size_t versionLen, keyBufLen;
306n/a DWORD index;
307n/a WCHAR *keyBuf = NULL;
308n/a WCHAR *keyBufPtr;
309n/a WCHAR **ppPaths = NULL;
310n/a
311n/a /* Tried to use sysget("winver") but here is too early :-( */
312n/a versionLen = strlen(PyWin_DLLVersionString);
313n/a /* Space for all the chars, plus one \0 */
314n/a keyBufLen = sizeof(keyPrefix) +
315n/a sizeof(WCHAR)*(versionLen-1) +
316n/a sizeof(keySuffix);
317n/a keyBuf = keyBufPtr = PyMem_RawMalloc(keyBufLen);
318n/a if (keyBuf==NULL) goto done;
319n/a
320n/a memcpy_s(keyBufPtr, keyBufLen, keyPrefix, sizeof(keyPrefix)-sizeof(WCHAR));
321n/a keyBufPtr += Py_ARRAY_LENGTH(keyPrefix) - 1;
322n/a mbstowcs(keyBufPtr, PyWin_DLLVersionString, versionLen);
323n/a keyBufPtr += versionLen;
324n/a /* NULL comes with this one! */
325n/a memcpy(keyBufPtr, keySuffix, sizeof(keySuffix));
326n/a /* Open the root Python key */
327n/a rc=RegOpenKeyExW(keyBase,
328n/a keyBuf, /* subkey */
329n/a 0, /* reserved */
330n/a KEY_READ,
331n/a &newKey);
332n/a if (rc!=ERROR_SUCCESS) goto done;
333n/a /* Find out how big our core buffer is, and how many subkeys we have */
334n/a rc = RegQueryInfoKey(newKey, NULL, NULL, NULL, &numKeys, NULL, NULL,
335n/a NULL, NULL, &dataSize, NULL, NULL);
336n/a if (rc!=ERROR_SUCCESS) goto done;
337n/a if (skipcore) dataSize = 0; /* Only count core ones if we want them! */
338n/a /* Allocate a temp array of char buffers, so we only need to loop
339n/a reading the registry once
340n/a */
341n/a ppPaths = PyMem_RawMalloc( sizeof(WCHAR *) * numKeys );
342n/a if (ppPaths==NULL) goto done;
343n/a memset(ppPaths, 0, sizeof(WCHAR *) * numKeys);
344n/a /* Loop over all subkeys, allocating a temp sub-buffer. */
345n/a for(index=0;index<numKeys;index++) {
346n/a WCHAR keyBuf[MAX_PATH+1];
347n/a HKEY subKey = 0;
348n/a DWORD reqdSize = MAX_PATH+1;
349n/a /* Get the sub-key name */
350n/a DWORD rc = RegEnumKeyExW(newKey, index, keyBuf, &reqdSize,
351n/a NULL, NULL, NULL, NULL );
352n/a if (rc!=ERROR_SUCCESS) goto done;
353n/a /* Open the sub-key */
354n/a rc=RegOpenKeyExW(newKey,
355n/a keyBuf, /* subkey */
356n/a 0, /* reserved */
357n/a KEY_READ,
358n/a &subKey);
359n/a if (rc!=ERROR_SUCCESS) goto done;
360n/a /* Find the value of the buffer size, malloc, then read it */
361n/a RegQueryValueExW(subKey, NULL, 0, NULL, NULL, &reqdSize);
362n/a if (reqdSize) {
363n/a ppPaths[index] = PyMem_RawMalloc(reqdSize);
364n/a if (ppPaths[index]) {
365n/a RegQueryValueExW(subKey, NULL, 0, NULL,
366n/a (LPBYTE)ppPaths[index],
367n/a &reqdSize);
368n/a dataSize += reqdSize + 1; /* 1 for the ";" */
369n/a }
370n/a }
371n/a RegCloseKey(subKey);
372n/a }
373n/a
374n/a /* return null if no path to return */
375n/a if (dataSize == 0) goto done;
376n/a
377n/a /* original datasize from RegQueryInfo doesn't include the \0 */
378n/a dataBuf = PyMem_RawMalloc((dataSize+1) * sizeof(WCHAR));
379n/a if (dataBuf) {
380n/a WCHAR *szCur = dataBuf;
381n/a /* Copy our collected strings */
382n/a for (index=0;index<numKeys;index++) {
383n/a if (index > 0) {
384n/a *(szCur++) = L';';
385n/a dataSize--;
386n/a }
387n/a if (ppPaths[index]) {
388n/a Py_ssize_t len = wcslen(ppPaths[index]);
389n/a wcsncpy(szCur, ppPaths[index], len);
390n/a szCur += len;
391n/a assert(dataSize > (DWORD)len);
392n/a dataSize -= (DWORD)len;
393n/a }
394n/a }
395n/a if (skipcore)
396n/a *szCur = '\0';
397n/a else {
398n/a /* If we have no values, we dont need a ';' */
399n/a if (numKeys) {
400n/a *(szCur++) = L';';
401n/a dataSize--;
402n/a }
403n/a /* Now append the core path entries -
404n/a this will include the NULL
405n/a */
406n/a rc = RegQueryValueExW(newKey, NULL, 0, NULL,
407n/a (LPBYTE)szCur, &dataSize);
408n/a if (rc != ERROR_SUCCESS) {
409n/a PyMem_RawFree(dataBuf);
410n/a goto done;
411n/a }
412n/a }
413n/a /* And set the result - caller must free */
414n/a retval = dataBuf;
415n/a }
416n/adone:
417n/a /* Loop freeing my temp buffers */
418n/a if (ppPaths) {
419n/a for(index=0; index<numKeys; index++)
420n/a PyMem_RawFree(ppPaths[index]);
421n/a PyMem_RawFree(ppPaths);
422n/a }
423n/a if (newKey)
424n/a RegCloseKey(newKey);
425n/a PyMem_RawFree(keyBuf);
426n/a return retval;
427n/a}
428n/a#endif /* Py_ENABLE_SHARED */
429n/a
430n/astatic void
431n/aget_progpath(void)
432n/a{
433n/a extern wchar_t *Py_GetProgramName(void);
434n/a wchar_t *path = _wgetenv(L"PATH");
435n/a wchar_t *prog = Py_GetProgramName();
436n/a
437n/a#ifdef Py_ENABLE_SHARED
438n/a extern HANDLE PyWin_DLLhModule;
439n/a /* static init of progpath ensures final char remains \0 */
440n/a if (PyWin_DLLhModule)
441n/a if (!GetModuleFileNameW(PyWin_DLLhModule, dllpath, MAXPATHLEN))
442n/a dllpath[0] = 0;
443n/a#else
444n/a dllpath[0] = 0;
445n/a#endif
446n/a if (GetModuleFileNameW(NULL, progpath, MAXPATHLEN))
447n/a return;
448n/a if (prog == NULL || *prog == '\0')
449n/a prog = L"python";
450n/a
451n/a /* If there is no slash in the argv0 path, then we have to
452n/a * assume python is on the user's $PATH, since there's no
453n/a * other way to find a directory to start the search from. If
454n/a * $PATH isn't exported, you lose.
455n/a */
456n/a#ifdef ALTSEP
457n/a if (wcschr(prog, SEP) || wcschr(prog, ALTSEP))
458n/a#else
459n/a if (wcschr(prog, SEP))
460n/a#endif
461n/a wcsncpy(progpath, prog, MAXPATHLEN);
462n/a else if (path) {
463n/a while (1) {
464n/a wchar_t *delim = wcschr(path, DELIM);
465n/a
466n/a if (delim) {
467n/a size_t len = delim - path;
468n/a /* ensure we can't overwrite buffer */
469n/a len = min(MAXPATHLEN,len);
470n/a wcsncpy(progpath, path, len);
471n/a *(progpath + len) = '\0';
472n/a }
473n/a else
474n/a wcsncpy(progpath, path, MAXPATHLEN);
475n/a
476n/a /* join() is safe for MAXPATHLEN+1 size buffer */
477n/a join(progpath, prog);
478n/a if (exists(progpath))
479n/a break;
480n/a
481n/a if (!delim) {
482n/a progpath[0] = '\0';
483n/a break;
484n/a }
485n/a path = delim + 1;
486n/a }
487n/a }
488n/a else
489n/a progpath[0] = '\0';
490n/a}
491n/a
492n/astatic int
493n/afind_env_config_value(FILE * env_file, const wchar_t * key, wchar_t * value)
494n/a{
495n/a int result = 0; /* meaning not found */
496n/a char buffer[MAXPATHLEN*2+1]; /* allow extra for key, '=', etc. */
497n/a
498n/a fseek(env_file, 0, SEEK_SET);
499n/a while (!feof(env_file)) {
500n/a char * p = fgets(buffer, MAXPATHLEN*2, env_file);
501n/a wchar_t tmpbuffer[MAXPATHLEN*2+1];
502n/a PyObject * decoded;
503n/a size_t n;
504n/a
505n/a if (p == NULL)
506n/a break;
507n/a n = strlen(p);
508n/a if (p[n - 1] != '\n') {
509n/a /* line has overflowed - bail */
510n/a break;
511n/a }
512n/a if (p[0] == '#') /* Comment - skip */
513n/a continue;
514n/a decoded = PyUnicode_DecodeUTF8(buffer, n, "surrogateescape");
515n/a if (decoded != NULL) {
516n/a Py_ssize_t k;
517n/a k = PyUnicode_AsWideChar(decoded,
518n/a tmpbuffer, MAXPATHLEN * 2);
519n/a Py_DECREF(decoded);
520n/a if (k >= 0) {
521n/a wchar_t * context = NULL;
522n/a wchar_t * tok = wcstok_s(tmpbuffer, L" \t\r\n", &context);
523n/a if ((tok != NULL) && !wcscmp(tok, key)) {
524n/a tok = wcstok_s(NULL, L" \t", &context);
525n/a if ((tok != NULL) && !wcscmp(tok, L"=")) {
526n/a tok = wcstok_s(NULL, L"\r\n", &context);
527n/a if (tok != NULL) {
528n/a wcsncpy(value, tok, MAXPATHLEN);
529n/a result = 1;
530n/a break;
531n/a }
532n/a }
533n/a }
534n/a }
535n/a }
536n/a }
537n/a return result;
538n/a}
539n/a
540n/astatic int
541n/aread_pth_file(const wchar_t *path, wchar_t *prefix, int *isolated, int *nosite)
542n/a{
543n/a FILE *sp_file = _Py_wfopen(path, L"r");
544n/a if (sp_file == NULL)
545n/a return -1;
546n/a
547n/a wcscpy_s(prefix, MAXPATHLEN+1, path);
548n/a reduce(prefix);
549n/a *isolated = 1;
550n/a *nosite = 1;
551n/a
552n/a size_t bufsiz = MAXPATHLEN;
553n/a size_t prefixlen = wcslen(prefix);
554n/a
555n/a wchar_t *buf = (wchar_t*)PyMem_RawMalloc(bufsiz * sizeof(wchar_t));
556n/a buf[0] = '\0';
557n/a
558n/a while (!feof(sp_file)) {
559n/a char line[MAXPATHLEN + 1];
560n/a char *p = fgets(line, MAXPATHLEN + 1, sp_file);
561n/a if (!p)
562n/a break;
563n/a if (*p == '\0' || *p == '\r' || *p == '\n' || *p == '#')
564n/a continue;
565n/a while (*++p) {
566n/a if (*p == '\r' || *p == '\n') {
567n/a *p = '\0';
568n/a break;
569n/a }
570n/a }
571n/a
572n/a if (strcmp(line, "import site") == 0) {
573n/a *nosite = 0;
574n/a continue;
575n/a } else if (strncmp(line, "import ", 7) == 0) {
576n/a Py_FatalError("only 'import site' is supported in ._pth file");
577n/a }
578n/a
579n/a DWORD wn = MultiByteToWideChar(CP_UTF8, 0, line, -1, NULL, 0);
580n/a wchar_t *wline = (wchar_t*)PyMem_RawMalloc((wn + 1) * sizeof(wchar_t));
581n/a wn = MultiByteToWideChar(CP_UTF8, 0, line, -1, wline, wn + 1);
582n/a wline[wn] = '\0';
583n/a
584n/a size_t usedsiz = wcslen(buf);
585n/a while (usedsiz + wn + prefixlen + 4 > bufsiz) {
586n/a bufsiz += MAXPATHLEN;
587n/a buf = (wchar_t*)PyMem_RawRealloc(buf, (bufsiz + 1) * sizeof(wchar_t));
588n/a if (!buf) {
589n/a PyMem_RawFree(wline);
590n/a goto error;
591n/a }
592n/a }
593n/a
594n/a if (usedsiz) {
595n/a wcscat_s(buf, bufsiz, L";");
596n/a usedsiz += 1;
597n/a }
598n/a
599n/a errno_t result;
600n/a _Py_BEGIN_SUPPRESS_IPH
601n/a result = wcscat_s(buf, bufsiz, prefix);
602n/a _Py_END_SUPPRESS_IPH
603n/a if (result == EINVAL) {
604n/a Py_FatalError("invalid argument during ._pth processing");
605n/a } else if (result == ERANGE) {
606n/a Py_FatalError("buffer overflow during ._pth processing");
607n/a }
608n/a wchar_t *b = &buf[usedsiz];
609n/a join(b, wline);
610n/a
611n/a PyMem_RawFree(wline);
612n/a }
613n/a
614n/a module_search_path = buf;
615n/a
616n/a fclose(sp_file);
617n/a return 0;
618n/a
619n/aerror:
620n/a PyMem_RawFree(buf);
621n/a fclose(sp_file);
622n/a return -1;
623n/a}
624n/a
625n/a
626n/astatic void
627n/acalculate_path(void)
628n/a{
629n/a wchar_t argv0_path[MAXPATHLEN+1];
630n/a wchar_t *buf;
631n/a size_t bufsz;
632n/a wchar_t *pythonhome = Py_GetPythonHome();
633n/a wchar_t *envpath = NULL;
634n/a
635n/a int skiphome, skipdefault;
636n/a wchar_t *machinepath = NULL;
637n/a wchar_t *userpath = NULL;
638n/a wchar_t zip_path[MAXPATHLEN+1];
639n/a
640n/a if (!Py_IgnoreEnvironmentFlag) {
641n/a envpath = _wgetenv(L"PYTHONPATH");
642n/a }
643n/a
644n/a get_progpath();
645n/a /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */
646n/a wcscpy_s(argv0_path, MAXPATHLEN+1, progpath);
647n/a reduce(argv0_path);
648n/a
649n/a /* Search for a sys.path file */
650n/a {
651n/a wchar_t spbuffer[MAXPATHLEN+1];
652n/a
653n/a if ((dllpath[0] && !change_ext(spbuffer, dllpath, L"._pth") && exists(spbuffer)) ||
654n/a (progpath[0] && !change_ext(spbuffer, progpath, L"._pth") && exists(spbuffer))) {
655n/a
656n/a if (!read_pth_file(spbuffer, prefix, &Py_IsolatedFlag, &Py_NoSiteFlag)) {
657n/a return;
658n/a }
659n/a }
660n/a }
661n/a
662n/a /* Search for an environment configuration file, first in the
663n/a executable's directory and then in the parent directory.
664n/a If found, open it for use when searching for prefixes.
665n/a */
666n/a
667n/a {
668n/a wchar_t envbuffer[MAXPATHLEN+1];
669n/a wchar_t tmpbuffer[MAXPATHLEN+1];
670n/a const wchar_t *env_cfg = L"pyvenv.cfg";
671n/a FILE * env_file = NULL;
672n/a
673n/a wcscpy_s(envbuffer, MAXPATHLEN+1, argv0_path);
674n/a join(envbuffer, env_cfg);
675n/a env_file = _Py_wfopen(envbuffer, L"r");
676n/a if (env_file == NULL) {
677n/a errno = 0;
678n/a reduce(envbuffer);
679n/a reduce(envbuffer);
680n/a join(envbuffer, env_cfg);
681n/a env_file = _Py_wfopen(envbuffer, L"r");
682n/a if (env_file == NULL) {
683n/a errno = 0;
684n/a }
685n/a }
686n/a if (env_file != NULL) {
687n/a /* Look for a 'home' variable and set argv0_path to it, if found */
688n/a if (find_env_config_value(env_file, L"home", tmpbuffer)) {
689n/a wcscpy_s(argv0_path, MAXPATHLEN+1, tmpbuffer);
690n/a }
691n/a fclose(env_file);
692n/a env_file = NULL;
693n/a }
694n/a }
695n/a
696n/a /* Calculate zip archive path from DLL or exe path */
697n/a change_ext(zip_path, dllpath[0] ? dllpath : progpath, L".zip");
698n/a
699n/a if (pythonhome == NULL || *pythonhome == '\0') {
700n/a if (zip_path[0] && exists(zip_path)) {
701n/a wcscpy_s(prefix, MAXPATHLEN+1, zip_path);
702n/a reduce(prefix);
703n/a pythonhome = prefix;
704n/a } else if (search_for_prefix(argv0_path, LANDMARK))
705n/a pythonhome = prefix;
706n/a else
707n/a pythonhome = NULL;
708n/a }
709n/a else
710n/a wcscpy_s(prefix, MAXPATHLEN+1, pythonhome);
711n/a
712n/a if (envpath && *envpath == '\0')
713n/a envpath = NULL;
714n/a
715n/a
716n/a skiphome = pythonhome==NULL ? 0 : 1;
717n/a#ifdef Py_ENABLE_SHARED
718n/a machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, skiphome);
719n/a userpath = getpythonregpath(HKEY_CURRENT_USER, skiphome);
720n/a#endif
721n/a /* We only use the default relative PYTHONPATH if we havent
722n/a anything better to use! */
723n/a skipdefault = envpath!=NULL || pythonhome!=NULL || \
724n/a machinepath!=NULL || userpath!=NULL;
725n/a
726n/a /* We need to construct a path from the following parts.
727n/a (1) the PYTHONPATH environment variable, if set;
728n/a (2) for Win32, the zip archive file path;
729n/a (3) for Win32, the machinepath and userpath, if set;
730n/a (4) the PYTHONPATH config macro, with the leading "."
731n/a of each component replaced with pythonhome, if set;
732n/a (5) the directory containing the executable (argv0_path).
733n/a The length calculation calculates #4 first.
734n/a Extra rules:
735n/a - If PYTHONHOME is set (in any way) item (3) is ignored.
736n/a - If registry values are used, (4) and (5) are ignored.
737n/a */
738n/a
739n/a /* Calculate size of return buffer */
740n/a if (pythonhome != NULL) {
741n/a wchar_t *p;
742n/a bufsz = 1;
743n/a for (p = PYTHONPATH; *p; p++) {
744n/a if (*p == DELIM)
745n/a bufsz++; /* number of DELIM plus one */
746n/a }
747n/a bufsz *= wcslen(pythonhome);
748n/a }
749n/a else
750n/a bufsz = 0;
751n/a bufsz += wcslen(PYTHONPATH) + 1;
752n/a bufsz += wcslen(argv0_path) + 1;
753n/a if (userpath)
754n/a bufsz += wcslen(userpath) + 1;
755n/a if (machinepath)
756n/a bufsz += wcslen(machinepath) + 1;
757n/a bufsz += wcslen(zip_path) + 1;
758n/a if (envpath != NULL)
759n/a bufsz += wcslen(envpath) + 1;
760n/a
761n/a module_search_path = buf = PyMem_RawMalloc(bufsz*sizeof(wchar_t));
762n/a if (buf == NULL) {
763n/a /* We can't exit, so print a warning and limp along */
764n/a fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n");
765n/a if (envpath) {
766n/a fprintf(stderr, "Using environment $PYTHONPATH.\n");
767n/a module_search_path = envpath;
768n/a }
769n/a else {
770n/a fprintf(stderr, "Using default static path.\n");
771n/a module_search_path = PYTHONPATH;
772n/a }
773n/a PyMem_RawFree(machinepath);
774n/a PyMem_RawFree(userpath);
775n/a return;
776n/a }
777n/a
778n/a if (envpath) {
779n/a if (wcscpy_s(buf, bufsz - (buf - module_search_path), envpath))
780n/a Py_FatalError("buffer overflow in getpathp.c's calculate_path()");
781n/a buf = wcschr(buf, L'\0');
782n/a *buf++ = DELIM;
783n/a }
784n/a if (zip_path[0]) {
785n/a if (wcscpy_s(buf, bufsz - (buf - module_search_path), zip_path))
786n/a Py_FatalError("buffer overflow in getpathp.c's calculate_path()");
787n/a buf = wcschr(buf, L'\0');
788n/a *buf++ = DELIM;
789n/a }
790n/a if (userpath) {
791n/a if (wcscpy_s(buf, bufsz - (buf - module_search_path), userpath))
792n/a Py_FatalError("buffer overflow in getpathp.c's calculate_path()");
793n/a buf = wcschr(buf, L'\0');
794n/a *buf++ = DELIM;
795n/a PyMem_RawFree(userpath);
796n/a }
797n/a if (machinepath) {
798n/a if (wcscpy_s(buf, bufsz - (buf - module_search_path), machinepath))
799n/a Py_FatalError("buffer overflow in getpathp.c's calculate_path()");
800n/a buf = wcschr(buf, L'\0');
801n/a *buf++ = DELIM;
802n/a PyMem_RawFree(machinepath);
803n/a }
804n/a if (pythonhome == NULL) {
805n/a if (!skipdefault) {
806n/a if (wcscpy_s(buf, bufsz - (buf - module_search_path), PYTHONPATH))
807n/a Py_FatalError("buffer overflow in getpathp.c's calculate_path()");
808n/a buf = wcschr(buf, L'\0');
809n/a *buf++ = DELIM;
810n/a }
811n/a } else {
812n/a wchar_t *p = PYTHONPATH;
813n/a wchar_t *q;
814n/a size_t n;
815n/a for (;;) {
816n/a q = wcschr(p, DELIM);
817n/a if (q == NULL)
818n/a n = wcslen(p);
819n/a else
820n/a n = q-p;
821n/a if (p[0] == '.' && is_sep(p[1])) {
822n/a if (wcscpy_s(buf, bufsz - (buf - module_search_path), pythonhome))
823n/a Py_FatalError("buffer overflow in getpathp.c's calculate_path()");
824n/a buf = wcschr(buf, L'\0');
825n/a p++;
826n/a n--;
827n/a }
828n/a wcsncpy(buf, p, n);
829n/a buf += n;
830n/a *buf++ = DELIM;
831n/a if (q == NULL)
832n/a break;
833n/a p = q+1;
834n/a }
835n/a }
836n/a if (argv0_path) {
837n/a wcscpy(buf, argv0_path);
838n/a buf = wcschr(buf, L'\0');
839n/a *buf++ = DELIM;
840n/a }
841n/a *(buf - 1) = L'\0';
842n/a /* Now to pull one last hack/trick. If sys.prefix is
843n/a empty, then try and find it somewhere on the paths
844n/a we calculated. We scan backwards, as our general policy
845n/a is that Python core directories are at the *end* of
846n/a sys.path. We assume that our "lib" directory is
847n/a on the path, and that our 'prefix' directory is
848n/a the parent of that.
849n/a */
850n/a if (*prefix==L'\0') {
851n/a wchar_t lookBuf[MAXPATHLEN+1];
852n/a wchar_t *look = buf - 1; /* 'buf' is at the end of the buffer */
853n/a while (1) {
854n/a Py_ssize_t nchars;
855n/a wchar_t *lookEnd = look;
856n/a /* 'look' will end up one character before the
857n/a start of the path in question - even if this
858n/a is one character before the start of the buffer
859n/a */
860n/a while (look >= module_search_path && *look != DELIM)
861n/a look--;
862n/a nchars = lookEnd-look;
863n/a wcsncpy(lookBuf, look+1, nchars);
864n/a lookBuf[nchars] = L'\0';
865n/a /* Up one level to the parent */
866n/a reduce(lookBuf);
867n/a if (search_for_prefix(lookBuf, LANDMARK)) {
868n/a break;
869n/a }
870n/a /* If we are out of paths to search - give up */
871n/a if (look < module_search_path)
872n/a break;
873n/a look--;
874n/a }
875n/a }
876n/a}
877n/a
878n/a
879n/a/* External interface */
880n/a
881n/avoid
882n/aPy_SetPath(const wchar_t *path)
883n/a{
884n/a if (module_search_path != NULL) {
885n/a PyMem_RawFree(module_search_path);
886n/a module_search_path = NULL;
887n/a }
888n/a if (path != NULL) {
889n/a extern wchar_t *Py_GetProgramName(void);
890n/a wchar_t *prog = Py_GetProgramName();
891n/a wcsncpy(progpath, prog, MAXPATHLEN);
892n/a prefix[0] = L'\0';
893n/a module_search_path = PyMem_RawMalloc((wcslen(path) + 1) * sizeof(wchar_t));
894n/a if (module_search_path != NULL)
895n/a wcscpy(module_search_path, path);
896n/a }
897n/a}
898n/a
899n/awchar_t *
900n/aPy_GetPath(void)
901n/a{
902n/a if (!module_search_path)
903n/a calculate_path();
904n/a return module_search_path;
905n/a}
906n/a
907n/awchar_t *
908n/aPy_GetPrefix(void)
909n/a{
910n/a if (!module_search_path)
911n/a calculate_path();
912n/a return prefix;
913n/a}
914n/a
915n/awchar_t *
916n/aPy_GetExecPrefix(void)
917n/a{
918n/a return Py_GetPrefix();
919n/a}
920n/a
921n/awchar_t *
922n/aPy_GetProgramFullPath(void)
923n/a{
924n/a if (!module_search_path)
925n/a calculate_path();
926n/a return progpath;
927n/a}
928n/a
929n/a/* Load python3.dll before loading any extension module that might refer
930n/a to it. That way, we can be sure that always the python3.dll corresponding
931n/a to this python DLL is loaded, not a python3.dll that might be on the path
932n/a by chance.
933n/a Return whether the DLL was found.
934n/a*/
935n/astatic int python3_checked = 0;
936n/astatic HANDLE hPython3;
937n/aint
938n/a_Py_CheckPython3()
939n/a{
940n/a wchar_t py3path[MAXPATHLEN+1];
941n/a wchar_t *s;
942n/a if (python3_checked)
943n/a return hPython3 != NULL;
944n/a python3_checked = 1;
945n/a
946n/a /* If there is a python3.dll next to the python3y.dll,
947n/a assume this is a build tree; use that DLL */
948n/a wcscpy(py3path, dllpath);
949n/a s = wcsrchr(py3path, L'\\');
950n/a if (!s)
951n/a s = py3path;
952n/a wcscpy(s, L"\\python3.dll");
953n/a hPython3 = LoadLibraryExW(py3path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
954n/a if (hPython3 != NULL)
955n/a return 1;
956n/a
957n/a /* Check sys.prefix\DLLs\python3.dll */
958n/a wcscpy(py3path, Py_GetPrefix());
959n/a wcscat(py3path, L"\\DLLs\\python3.dll");
960n/a hPython3 = LoadLibraryExW(py3path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
961n/a return hPython3 != NULL;
962n/a}